diff --git a/GlowScriptOffline/GlowScript.html b/GlowScriptOffline/GlowScript.html index 04074569..ef89ffe4 100644 --- a/GlowScriptOffline/GlowScript.html +++ b/GlowScriptOffline/GlowScript.html @@ -42,8 +42,8 @@ - - + + @@ -60,7 +60,7 @@ - diff --git a/docs/GlowScriptDocs/Templates/template.dwt b/docs/GlowScriptDocs/Templates/template.dwt deleted file mode 100644 index 4a68ac1a..00000000 --- a/docs/GlowScriptDocs/Templates/template.dwt +++ /dev/null @@ -1,36 +0,0 @@ - - - -Template - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/VPtoGS.py b/docs/GlowScriptDocs/VPtoGS.py deleted file mode 100644 index f2d1820b..00000000 --- a/docs/GlowScriptDocs/VPtoGS.py +++ /dev/null @@ -1,265 +0,0 @@ -from __future__ import division , print_function - -## Convert all .py files in this folder to run in GlowScript VPython -## Bruce Sherwood, begun June 2011; major rewrite November 2014 - -import os -import re - -allfiles = os.listdir(os.curdir) -#allfiles = ['aaa.py'] # for testing purposes, convert just this one file - -# VPython objects: -prims = ['arrow', 'box', 'cone', 'curve', 'cylinder', 'display', - 'ellipsoid', 'extrusion', 'faces', 'helix', - 'label', 'pyramid', 'ring', 'sphere', 'frame', - 'text', 'local_light', 'distant_light'] - -# Objects for which obj.x should be obj.pos.x: -posobjects = ['arrow', 'box', 'cone', 'curve', 'cylinder', 'ellipsoid', 'label', - 'helix', 'pyramid', 'ring', 'sphere', 'local_light', 'frame'] - -# Basic categories with respect to radius, length, etc. are arrow, box, cylinder, ring, sphere, curve: -primtypes = {'arrow':'rect', 'box':'rect', 'cone':'radial', 'curve':'curve', 'cylinder':'radial', - 'ellipsoid':'rect', 'extrusion':'rect', 'faces':'not_implemented', 'helix':'radial', - 'label':'label', 'pyramid':'rect', 'ring':'radial', 'sphere':'radial', 'frame':'not_implemented', - 'text':'not_implemented', 'local_light':'light', 'distant_light':'light', 'display':'display'} - -symbols = {} # variables which refer to VPython objects, in form var:prim - -# A left paren was found at location i in the string line; -# convert (x,y,z) -> vector(x,y,z) and (x,y) -> vector(x,y,0) and return new line and advanced i -# But don't convert xxx.plot(pos=(x,y)). -def insert_vector(line, i): - start = i - commas = 0 - parens = 1 - while i < len(line): - c = line[i] - i += 1 - if c == ' ': continue - elif c == ',': commas += 1 - elif c == '(': parens += 1 - elif c == ')': - parens -= 1 - if parens == 0: - if commas == 1: # (x,y) -> vector(x,y,0) - line = line[:start-1]+'vector'+line[start-1:i-1] + ',0' + line[i-1:] - i += 8 - elif commas == 2: # (x,y,z) -> vector(x,y,z) - line = line[:start-1]+'vector'+line[start-1:] - i += 6 - break - return [line, i] - -def firstpass(pname): - global symbols - print('--------------------') - print('Processing '+pname) - output = [] - symbols = {'scene':'display'} # predefined name of a primitive - lines = open(pname+'.py', 'r').readlines() - - def add(s): - output.append(s) - - rerange = re.compile('\.range\s*=\s*\((\s*\w*\s*,\s*\w*\s*,\s*\w*\s*)\)') - - def replacements(line): - line = line.replace('vector()', 'vector(0,0,0)') - line = line.replace('mouse.getclick()',"waitfor('click')") - line = line.replace('arcsin', 'asin') - line = line.replace('arccos', 'acos') - line = line.replace('arctan', 'atan') - line = line.replace('gdisplay', 'graph') - line = line.replace('display', 'canvas') - m = rerange.search(line) - if m: - line = line.replace('('+m.group(1),m.group(1)+' # range was ('+m.group(1)) - #line = line.replace('vector', 'vec') # don't do this until/unless class VPython accepts vec - return line - - nlines = len(lines) - linenumber = 0 - reblank = re.compile(r'^[\s]*$') - recomment = re.compile(r'^[\s]*#') - - while linenumber < nlines: - line = lines[linenumber][:-1] # remove final carriage return - linenumber += 1 - m = reblank.match(line) - if m is None: - m = recomment.match(line) - if m is not None: - add(lines[linenumber-1][:-1]) - continue - else: - add(lines[linenumber-1][:-1]) - continue - - # Simple replacements such as arcsin -> asin - line = replacements(line) - - # Build dictionary of names that reference VPython primitives - foundprim = False - for prim in prims: - p = re.compile('\s*(\w+)\s*=\s*'+prim+'\s*(\()') - m = p.search(line) - if m: - symbols[m.group(1)] = prim - begin = m.start(2)+1 # location of '(' after primitive name - foundprim = True - break - - # Concatenate any continuation lines and move end-of-line comment to previous line - reindent = re.compile('^\s*') - parens = 0 - comments = '' - i = 0 - while i < len(line): - c = line[i] - if c == "'": - i += 1 - while i < len(line): - c = line[i] - i += 1 - if c == "'": break - continue - if c == '"': - i += 1 - while i < len(line): - c = line[i] - i += 1 - if c == '"': break - continue - if c == '(': parens += 1 - elif c == ')': parens -= 1 - elif c == '\\': - line = line[:i]+line[i+1:] - i -= 1 - elif c == '#': - comments += line[i:]+'\n' - line = line[:i] - if parens > 0: - i -= 1 - if i == len(line)-1: - if parens > 0: - nextline = lines[linenumber] - if len(nextline) > 0: nextline = nextline[:-1] - linenumber += 1 - indent = reindent.match(nextline) - if indent != None: - nextline = nextline[indent.span()[1]:] - if line[i] != ' ': nextline = ' '+nextline - line += nextline - else: - break - i += 1 - - if foundprim and (primtypes[prim] == 'not_implemented'): - print('The '+prim+' object is not yet implemented in GlowScript') - add(line) - continue - - if len(comments) > 0: add(comments[:-1]) # delete final carriage return, which add will attach - - # Replace ' = (x,y,z)' in a constructor with ' = vector(x,y,z)' - # If it is ' = (x,y)', replace with ' = vector(x,y,0)' - p = re.compile('\.plot\s*\(') - m = p.search(line) # look for xxx.plot(pos=(x,y)) and don't insert 'vector' - if not m: - # Could use regex to find '= (' instead of marching through the line one character at a time. - lastc = '' - i = 0 - while i < len(line): - c = line[i] - i += 1 - if c == ' ': continue - if c == "'": - while i < len(line): - c = line[i] - i += 1 - if c == "'": break - continue - if c == '"': - while i < len(line): - c = line[i] - i += 1 - if c == '"': break - continue - elif c == '(' and lastc == '=': # need to test for =(x,y,z) or =(x,y) - line, i = insert_vector(line, i) - lastc = c - - add(line) - - return output - -# Replace obj.x with obj.pos.x, and convert obj.attr += vector to ob.jattr = obj.attr + vector -out = '' -def secondpass(lines): - global out - out = '' - attrs = {'x':'pos.x', 'y':'pos.y', 'z':'pos.z'} - objattrs = ['pos', 'axis', 'up', 'size', 'color'] - patt = re.compile('(\w+)\.(\w+)') - pluseq = re.compile('(\w+)\.(\w+)\s*([\+\-\*\/]=\s*)') - - def add(s): - global out - out += s+'\n' - - for line in lines: - start = 0 - while True: - m = patt.search(line[start:]) - if m: - name = m.group(1) - attr = m.group(2) - if name in symbols: - prim = symbols[name] - # Replace obj.x with obj.pos.x - if (attr in attrs) and (prim != 'curve') and (prim != 'display'): # curve.x and scene.x are legal - newattr = attrs[attr] - line = line[:m.start(1)+start]+name+'.'+newattr+line[m.end(2)+start:] - start += m.end(2) + len(newattr) - len(attr) - else: - start += m.end(2) - else: - start += m.end(2) - else: break - for objattr in objattrs: - m = pluseq.search(line) - if m: - # Replace obj.attr += vector with ob.jattr = obj.attr + vector - if m.group(1) in symbols and m.group(2) == objattr: - if (m.group(3)[0] == '+'): - line = line[:m.start(3)-1]+' = '+m.group(1)+'.'+m.group(2)+'+'+line[m.end(3):] - else: - line = line[:m.start(3)-1]+' = '+m.group(1)+'.'+m.group(2)+m.group(3)[0]+'('+line[m.end(3):]+')' - add(line) - - return out - -outputdir = 'Converted' -if not os.path.exists(outputdir): - os.makedirs(outputdir) - -for filename in allfiles: - pname = filename.split('.') - if pname[-1] != 'py': continue - pname = filename[:-3] - # How does one get the name of this converter file? __file__ gives an error - if pname[:6] == 'VPtoGS': continue - - lines = firstpass(pname) - final = secondpass(lines) - - fd = open(outputdir+'/'+pname+'.py', 'w') - fd.write(final) - fd.close() - -if len(allfiles) == 1: - print('---------------------') - print(final) -else: print('Done') diff --git a/docs/GlowScriptDocs/VPython-vs-GlowScript.html b/docs/GlowScriptDocs/VPython-vs-GlowScript.html deleted file mode 100644 index ad419592..00000000 --- a/docs/GlowScriptDocs/VPython-vs-GlowScript.html +++ /dev/null @@ -1,84 +0,0 @@ - - -VPython vs GlowScript - - - - - -

GlowScript RapydScript for those who have used VPython 6 ("Classic VPython")

-

This document is intended for those who may wish to write their GlowScript programs directly in RapydScript rather than using the VPython definitions.

-

The capabilities and syntax of GlowScript are based on those of VPython. For those familiar with VPython, this is a summary of the differences between the two environments. For those familiar with Python, it offers a summary of the main differences between the programming languages Python and RapydScript.

-

VPython uses the OpenGL 3D graphics library; it does not run in a browser. GlowScript uses the closely related WebGL 3D graphics library that is included in major web browsers. See the first page of the GlowScript Help for browser details.

-

Using the editor in GlowScript

-

GlowScript uses the ACE text editor. Here is a list of keyboard shortcuts for find, replace, etc.

-

for loops

-

In Python, when a for-loop increment is a fraction, you must use the arange() function, like this: "for x in arange(0, 10, 0.1)". In RapydScript you simply say "for x in range(0, 10, 0.1)".

-

vec instead of vector; vec is required

-

In VPython you can say b.pos = (1,2,0), and the (1,2,0) is converted to vector(1,2,0). This is not possible in GlowScript, where you must be specific about vector quantitities. Here are the possibilities:

-
-

b.pos = vec(1,2,0)    # okay
- b.pos = (1,2,0)       # error

-
-

A related issue is that in VPython b.x is a shorthand for b.pos.x. The shorthand b.x is not available in GlowScript; you must refer to b.pos.x. Because GlowScript requires that all vectors be explicitly stated to be vectors, the name "vector" has been shortened to "vec".

-

In VPython, pos, axis, and up are vectors, but size and color are not. In GlowScript size and color are also vector quantities. Here is how to create a non-cubic box with a special color:

-
-

box( pos=vec(2,1,0), size=vec(4,2,0.5), color=vec(1,0.6,0)} )

-
-

An interesting capability that results from treating color as a vector is that you can blend two colors c1 and c2 as (a*c1 + b*c2)/(a+b).

-

axis, size, radius, and length

-

In VPython axis and length (size.x) are tied to each other. When you change axis of a VPython object, length is set to the magnitude of axis. Similarly, when you set length, you also set the magnitude of axis.

-

In GlowScript axis and size are not tied to each other. You can set axis without affecting size, and you can set size without affecting axis. Only in the case of the arrow object is there a special attribute, axis_and_length, for changing both direction and length at the same time.

-

All basic GlowScript objects (box, cylinder, etc., but not arrow) have size attributes, which is not the case in VPython, and these objects fit into a bounding box given by size. By default, size = vec(1,1,1) except for the ring object where size is vec(0.1,1,1) to give a thickness of 0.1. This means that you can change a box to a sphere or vice versa and they'll fit into the same cube of 1 unit on a side (so the default diameter of a sphere is 1 rather than the default radius being 1). Similarly, you can interchange cones and pyramids and cylinders and helices.

-

There is no radius or length or height or width attribute for these objects. Rather, you specify the bounding box with size. A convenient way to specify the diameter D of a sphere is by setting size to D*vec(1,1,1). Note that you can make an ellipsoid from a sphere, or make a cylinder with an elliptical cross section, by making size.y different from size.z.

-

curve

-

A GlowScript curve is an array of point objects, each of which has attributes of pos, color, and radius.

-

See the curve documentation for ways to manipulate the list of points in a curve.

-

Unlike VPython, you can vary the radius of the cross section along the curve by setting the radius attribute of the point objects. Also, the curve object itself has its own pos, size, axis, and up attributes, so that you can move or rotate or resize the entire curve object quickly and easily.

-

Animations and rate

-

VPython animation loops must contain a rate statement to make the animation run at an appropriate rate. In a web browser environment, one must occasionally pause to permit the screen to be redrawn, and programs must be written to run for short amounts of time and then exit, having specified a time in the future when they want to run again. This structure is enabled in GlowScript by you marking in your program where such pauses can occur in your program. This special mark is the word "wait":

- - - - - - -
 

ate(100)
-

 

-

There is also a statement sleep(0.01), wait for 1/100th of a second. The statement update() gives the browser the opportunity to update the page display.

-

VPython objects available in GlowScript

-

Currently, all VPython objects have been implemented except for faces (replaced by vertex, triangle, and quad) and frame. Instead of frame there is a "compound" object, which among other things makes possible very fast displays of objects consisting of several combined objects. There is also a "clone" capability to make copies of existing objects.

-

Display regions

-

A display region was called a "display" in VPython and is a "canvas" in GlowScript, corresponding to the name by which drawing regions are known on web pages.

-

Wait for a mouse event

-

You can wait for a mouse event with these statements:

-

scene.waitfor('click')      # wait for mouse click
- scene.waitfor('mousedown')  # wait for mouse button to be depressed
- scene.waitfor('mouseup')    # wait for mouse to be moved (with button depressed)
- scene.waitfor('mousemove')  # wait for mouse button to be released

-

As in VPython, scene.mouse.pos gives the current position of the mouse.

-

The statement scene.waitfor('redraw') will wait for the beginning of the next screen update time, which lets you synchronize your updates with the screen. There is a similar statement scene.waitfor('draw_complete') which waits until the next screen update has been completed.
-

-

Graphs

-

Making graphs in GlowScript is quite similar to making graphs in VPython. See the description in the Help for details. One difference is that each line-graph, scatter-graph, or bar-graph object has its own label, which appears in a legend on the graph. Also, if you don't specify a color, a color will be assigned automatically by the flot graphing library, http://code.google.com/p/flot.

-

Math functions

-

The math functions sqrt, sin, cos, tan, asin, acos, atan, atan2, exp, log, pow, abs, and the constant pi are all available in GlowScript. The function Math.random() provides a random number in the range 0 to 1. For a full discussion, including radian/degree conversion and getting time information, see the description in the Help.

-

Vector functions

-

See the description of GlowScript vector functions for some differences from VPython.

-

Miscellaneous

-

Here is a name that is different in VPython and GlowScript:

- - - - - - -
 

# VPython

-

scene.mouse.camera

# GlowScript

-

scene.camera.pos

-

In a Python function you can specify that a variable "x" is global rather than local to the function. In RapydScript, as in Python 3, you say "nonlocal x" instead of "global x".

-

Full RapydScript documentation

-

Full documentation of RapydScript is available at https://github.com/kovidgoyal/rapydscript-ng.

-

 

- - diff --git a/docs/GlowScriptDocs/VisualRef.css b/docs/GlowScriptDocs/VisualRef.css deleted file mode 100644 index fde7e1fb..00000000 --- a/docs/GlowScriptDocs/VisualRef.css +++ /dev/null @@ -1,226 +0,0 @@ -a:link, a:visited, a:hover { - color: #006699; - text-decoration: none; -} -a:hover { - text-decoration: underline; -} -P.attributes { - display: block; - text-align: justify; - text-indent: -54.000000pt; - margin-top: 6.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 72.000000pt; - font-size: 10pt; - font-weight: medium; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: sans-serif; -} -P.Body { - display: block; - text-align: left; - text-indent: 0.000000pt; - margin-top: 0.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 0.000000pt; - font-size: 10pt; - font-weight: medium; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: sans-serif; -; top: 6pt; clip: rect( ) -} -P.Body-Text { - display: block; - text-align: justify; - text-indent: 0.000000pt; - margin-top: 0.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 0.000000pt; - font-size: 10pt; - font-weight: medium; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: sans-serif; -} -P.Footer { - display: block; - text-align: left; - text-indent: 0.000000pt; - margin-top: 0.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 0.000000pt; - font-size: 12.000000pt; - font-weight: medium; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: "Times"; -} -P.Footnote { - display: block; - text-align: left; - text-indent: 0.000000pt; - margin-top: 0.000000pt; - margin-bottom: 0.000000pt; - margin-right: 18.000000pt; - margin-left: 18.000000pt; - font-size: 12.000000pt; - font-weight: medium; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: "Times"; -} -P.Header { - display: block; - text-align: left; - text-indent: 0.000000pt; - margin-top: 0.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 0.000000pt; - font-size: 12.000000pt; - font-weight: medium; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: "Times"; -} -H1.Heading-1, H2.Heading-1, H3.Heading-1, H4.Heading-1, H5.Heading-1, H6.Heading-1 { - display: block; - text-align: justify; - text-indent: 0.000000pt; - margin-top: 14.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 0.000000pt; - font-size: 14.000000pt; - font-weight: Bold; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: "Century Schoolbook"; -} -P.Normal { - display: block; - text-align: justify; - text-indent: 0.000000pt; - margin-top: 6.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 0.000000pt; - font-size: 10pt; - font-weight: medium; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: sans-serif; -} -P.program { - display: block; - text-align: left; - text-indent: 0.000000pt; - margin-top: 6.000000pt; - margin-bottom: 6.000000pt; - margin-right: 0.000000pt; - margin-left: 10.000000pt; - font-size: 12pt; - font-weight: bold; - font-style: normal; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: Courier; -} -H1.program0, H2.program0, H3.program0, H4.program0, H5.program0, H6.program0 { - display: block; - text-align: left; - text-indent: -36.000000pt; - margin-top: 6.000000pt; - margin-bottom: 0.000000pt; - margin-right: 0.000000pt; - margin-left: 54.000000pt; - font-size: 12.000000pt; - font-weight: Bold; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: "Courier"; -} -EM.code { - font-size: 12.000000pt; - font-weight: Bold; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: "Courier New"; -} -EM.Default-XREF-style { - color: #00ff00; -} -EM.program { - font-size: 12.000000pt; - font-weight: Bold; - font-style: Regular; - color: #000000; - text-decoration: none; - vertical-align: baseline; - text-transform: none; - font-family: "Courier"; -} -EM.Symbol { - font-size: 12.000000pt; - font-family: "Symbol"; -} -.attribute { color: #FF0000} - -.navigation td { background-color: #669933; - color: #ffffcc; - font-weight: bold; - font-family: avantgarde, sans-serif; - font-size: 110%; - margin: 0pt; - padding: 0pt; } -.style3.style4.style5 font { - color: #F00; -} -.centered { - font-family: Verdana, Geneva, sans-serif; - font-size: 16px; - text-align: center; -} -.sans strong { - color: #000; - font-size: 16px; -} diff --git a/docs/GlowScriptDocs/arrow.html b/docs/GlowScriptDocs/arrow.html deleted file mode 100644 index e29ada1c..00000000 --- a/docs/GlowScriptDocs/arrow.html +++ /dev/null @@ -1,105 +0,0 @@ - - - -arrow - - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - -
arrow
arrow
-
-
-

arrow The arrow object has a straight box-shaped shaft with an arrowhead at one end. The following statement will display an arrow pointing parallel to the x axis, 5 units long:

-
-


- pointer = arrow(   pos=vec(0,2,1),
-   shaftwidth=1,
-  axis_and_length=vec(5,0,0) )

-

The arrow object has the following attributes and - default values, similar to those for cylinder: pos vec(0,0,0), axis_and_length vec(1,0,0), color vec(1,1,1) - which is color.white, opacity (1), shininess (0.6), emissive (False), up vec(0,1,0), and visible (True). - As with box, the up attribute - is significant for arrow because the shaft and head have square - cross sections, and setting the up attribute - rotates the arrow about its axis.

-

axis_and_length: Due to its typical uses for quantitative displays of vector quantities, the arrow object differs from the other 3D objects. There is no size attribute; the lateral dimensions are determined by shaftwidth. The attribute axis_and_length is used to specify simultaneously the direction and the length of the arrow object. For example, pointer.axis_and_length = vec(3,4,0) yields an arrow pointing in the direction of vec(3,4,0) with a length that is 5, the magnitude of this vector.

-

Additional arrow attributes:

-

shaftwidth By default, shaftwidth - - = 0.1*(length of arrow)

-

headwidth By default, headwidth - - = 2*shaftwidth

-

headlength By default, headlength - - = 3*shaftwidth

-

Assigning shaftwidth = 0 makes it be the default (0.1 times the length of the arrow). If you don't explicitly set headwidth or headlength, its length is based as shown above on shaftwidth (either the default or whatever value you specify for shaftwidth). If headlength becomes larger than half the length of the arrow, or the shaft becomes thinner - than 1/50 the length, the entire arrow is scaled accordingly.

-

If you specifically specify shaftwidth yourself, the only adjustment that is made is that headlength is - adjusted so that it never gets longer than half the total length, - so that the total length of the arrow is correct. This means that - very short, thick arrows look similar to a thumbtack, with a nearly - flat head.

-

No texture: Currently it is not possible to apply a texture to an arrow.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

To attach an arrow to a moving object, see Attach a trail or arrow.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/axes.gif b/docs/GlowScriptDocs/axes.gif deleted file mode 100644 index 1307d863..00000000 Binary files a/docs/GlowScriptDocs/axes.gif and /dev/null differ diff --git a/docs/GlowScriptDocs/box.html b/docs/GlowScriptDocs/box.html deleted file mode 100644 index df1f9817..00000000 --- a/docs/GlowScriptDocs/box.html +++ /dev/null @@ -1,110 +0,0 @@ - - - -box - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
box
box
-
-
-

IHere is how to create a box object:

-
-

mybox = box(   pos=vec(x0,y0,z0),
-  size=vec(L,H,W) )

-

The given position is in the center of the box, at (x0, - y0, z0). This is different from cylinder, whose pos attribute is at one - end of the cylinder. Just as with a cylinder, we can refer to the individual - vector components of the box as mybox.pos.x, mybox.pos.y, and mybox.pos.z. - For this box, we have mybox.axis - = vec(1, 0, 0). - Note that the axis of a box is just like the axis of - a cylinder.

-

For a box that isn't aligned with the coordinate axes, additional issues come into play. The orientation of the length of the box is given by the axis:box

-
-
-

mybox = box(  pos=vec(x0,y0,z0),  axis=vec(a,b,c),  size=vec(L,H,W) )

-

The axis attribute gives a direction for the length of the box, and the length, height, and width of the box are given as before.

-

You can rotate the box around its own axis by changing which way is "up" for the box, by specifying an up attribute for the box that is different from the up vector of the coordinate system:

-
-
-

mybox = box( pos=vec(x0,y0,z0),              axis=vec(a,b,c),              size=vec(L,H,W),              up=vec(q,r,s) )

-

With this statement, the width of the box will lie in a plane perpendicular to the (q,r,s) vector, and the height of the box will be perpendicular to the width and to the (a,b,c) vector.

-

Here is a full list of attributes for a box. All 3D objects have all of these attributes, other than arrow and curve:

-

pos Position: the center of the box; default = vec(0,0,0).

-

size The length, width, and height of the box; default = vec(1,1,1).

-

axis The axis points in the direction of the length of the box, default = vec(1,0,0). Only the direction of the axis is meaningful, not its magnitude. The length of the box is size.x, not the magnitude of the axis. An object's axis and up attributes are always perpendicular to each other. Changing the direction of axis also changes the direction of up so that the two directions always remain at right angles to each other.

-

-

up Which side - of the box is "up". An object's axis and up attributes are always perpendicular to each other. Changing the direction of up also changes the direction of axis so that the two directions always remain at right angles to each other.

-

color Color of object, - as a red-green-blue (RGB) triple: vec(1,0,0) is the same as color.red, default = vec(1,1,1), - which is color.white.

-

opacity Opacity of object, default = 1 (fully opaque); 0 is completely transparent.

-

shininess 0 to 1, default 0.6; governs the amount of specular reflections.

-

emissive If True, local and distant lights are ignored, and the brightness is governed by the object's own color. An example of its use is to put an emissive sphere at the location of a local_light, which looks like a glowing lamp. The default for emissive is False.

-

visible If False, - - object is not displayed; e.g. mybox.visible = False
-
Use mybox.visible = True to make the object - - visible again.

-

texture You can specify a texture to apply to the object's surface. See the Textures documentation.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

To display a trail or an arrow along the path of a moving object, see Attach a trail or arrow.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/canvas.html b/docs/GlowScriptDocs/canvas.html deleted file mode 100644 index 1cb62432..00000000 --- a/docs/GlowScriptDocs/canvas.html +++ /dev/null @@ -1,227 +0,0 @@ - - - -canvas - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- -

Controlling canvases on the browser page

-

When you create a box or other 3D object, a region of the web page called a "canvas" is allocated to displaying objects, and the objects are displayed in that rectangle, with a reasonable default width (640 pixels) and height (400 pixels). If you don't explicitly create a canvas, a canvas named "scene" is created for you, with default width and hight. If you want to specify the width and height of this default canvas, execute the following before creating any 3D objects:

-

scene.width = 200   # default is 640
- scene.height = 400  # default is 400

-

You can also create your own canvas, like this:

-

cv = canvas( width=300, height=200 )

-

In JavaScript: var cv = canvas( {width:300, height:200} )

-

After creating your own canvas, you can set the width and height like this instead of setting them in the canvas statement:

-

cv.width = 200
- cv.height = 400

-

You can have more than one canvas active on the web page. After creating a canvas, by default any objects you create later will appear in the most recently mentioned canvas, but you can specify which canvas you want the object to be in:

-

box() # appears in default "scene" canvas
- var c2 = canvas()  # additional canvas
- pyramid() # place in 2nd canvas, "c2"
- # This sphere goes in "scene": -
- sphere(canvas=scene, pos=vec(2,0,0))
- # This ring goes in "c2": -
- ring(canvas=c2, pos=vec(-1,0,0))

-

General-purpose options

-

You can specify any of these properties of the default scene or other canvas:

-

-

width, height Width - and height of the canvas area in pixels. Defaults are 640 and 400. Can be specified when creating the canvas, as in the example above, or set or changed later.

-

align Set to "left" (canvas forced to left side of window), "right" (canvas forced to right side of window), or "none" (the default alignment). For example, if you want to place a graph to the right of a canvas, set the canvas align attribute to the string "left" and the graph align attribute to the string "right". If the window is too narrow, the object that is on the right will be displayed below the other object.

-

resizable If True (the default) the user can resize the canvas.If C is a canvas that is resizable, then C.bind('resize', R) will execute the function R when the user resizes that canvas. If R has the form def R(ev):, then ev.event will be 'resize' and ev.canvas will be the canvas C.

-

background Set color - to be used to fill the canvas region; default is color.black.

-

ambient Color - of nondirectional ("ambient") lighting. Default is color.gray(0.2).

-

lights List of light - objects created for this canvas. By default, scene.lights is a list of distant_lights with these properties:
- direction:vec(0.22, 0.44, 0.88), color:color.gray(0.8)
- direction:vec(-0.88, -0.22, -0.44), - colo:color.gray(0.3)
- For how to create your own distant and local lights, see Lighting. You can eliminate the lights by setting scene.lights = [], an empty list, then create your own lights. To change the color of the first of the two default lights, do this, where 0 refers to the first of the two lights:

-

          scene.lights[0].color = color.red

-

objects A list - of all the visible objects in the canvas; invisible objects and - lights are not listed (scene.lights is a list of existing lights). - For example, the following makes all visible boxes in the scene red:

-

    for obj in scene2.objects:
-         if isinstance(obj, box):
-             obj.color = color.red

-

visible Setting scene.visible = false means that no objects are displayed, until scene.visible is set true again.

-

delete() Deletes all the objects in this canvas and then deletes the canvas itself

-

capture(filename) Sends to your Download folder a png screen shot of the canvas. If filename is the string "boxes" or "boxes.png" the file will be named "boxes.png".

-

To obtain the current location of the camera, see below for details of scene.camera.pos.

-

camera.follow If you say scene.camera.follow(ball), the center of the scene will continually be reset to the current position of the ball object. To stop following the object, execute scene.camera.follow(null).

-

                  Instead of specifying an object to follow, you can provide a function of your own:

-

          def f():
-              return 2*ball.pos
-           scene.camera.follow(f)

-

-

                  Alternatively, you can specify an "anonymous" (unnamed) function:

-

          scene.camera.follow(def ():
-               return 2*ball.pos
-          )

-

-

pixel_to_world Gives the width of a pixel in "world" coordinates (that is, the coordinates you use to position objects). This is read-only; you cannot set it. It is determined from the current value of scene.range. An example of its use is that if you want the radius of a curve object to be 5 pixels, set the radius to 5*scene.pixel_to_world.

-

Here are canvas options to wait for canvas updates:

-

scene.waitfor("redraw") Wait for the start of the next update of the canvas by the web browser

-

scene.waitfor("draw_complete") Wait for the end of the next update of the canvas by the web browser

-

Selecting a canvas

-

Suppose you have two canvases named scene1 and scene2. If you execute the statement canvas.selected = scene1, later creations of objects such as boxes or cylinders will be placed in scene1. Similarly, you can obtain the currently selected canvas with a statement such as current = canvas.selected.

-

Displaying text

-

You can use the label object to display text on the canvas. You can also place a title just above the canvas and/or a caption just below when you create a canvas:

-

canvas(title='Some title', caption='A caption')

-

After a canvas has been created you can change the title with scene.title = "Hello" or the caption with scene.caption = "Hello":

-

scene.caption = "Hello"
- sleep(3) # wait for 3 seconds
- scene.caption = "Goodbye"

-

You can put end-of-line markers ("\n") in the text to make multiline displays.

-

HTML: You can include html directives such as this: <b>This is bold.</b>

-

You can append more text to the title or caption (you can also use this form initially, as the caption and title start out as zero-length strings):

-

scene.append_to_title(
-           "Now <b>click the box</b>.")
- scene.append_to_caption(
-           "See the <i>effect?</i>")

-

In these append operations you can also use forms like this, where V is some variable (see text output for details):

-

("There are {:.1f} {}.".format(V, 'liters))
- ("There are", V, "liters")

-

scene.wrapper is the web page component which contains the canvas and its overlay (the overlay is a 2D canvas on which label objects and the prompt generated by scene.pause() are displayed). For example, scene.align = 'left' is equivalent to scene.wrapper.css('float', 'left') to force the canvas+overlay to the left side of the web page. Similarly, if you have a graph named g, scene.align = 'right' is equivalent to g.wrapper.css('float', 'right').

-

Similarly, scene.canvas refers to the 3D canvas and scene.elements refers to the 3D canvas and the 2D overlay.

-

(The following additional connections to the web page are not yet documented here: scene.events, canvas.container.)

-

List of objects

-

-

objects A list - of all the visible objects in the canvas; invisible objects and - lights are not listed (scene.lights is a list of existing lights). - For example, the following makes all visible boxes in the scene turn red:

-

for obj in scene.objects:
-     if obj.constructor == box:
-         obj.color = color.red

-

You could also write if (obj.constructor.name == 'box').

-

JavaScript version:

-

for (var obj in scene.objects) {
-    var o = scene.objects[obj]
-     if o.constructor == box {
-         obj.color = color.red
-     }
- }

-

-

Using jQuery

-

If you use jQuery to display widgets (buttons, sliders, menus), see this documentation on how to reference the title, caption, and print regions of the page.

-

Controlling the view

-

Here is a diagram that shows the relationship among the quantities discussed below that affect how the scene appears to the viewer:

-

     canvas

-

center Location at which - - the camera continually looks, even as the user rotates the position of the - - camera. If you change center, the camera - - moves to continue to look in the same "compass" direction toward - - the new center, unless you also change forward. Default vec(0,0,0).

-

autoscale = false no automatic - - scaling (set range or scale explicitly); autoscale - - = true automatic scaling (default). It is often useful to let GlowScript - - make an initial canvas with autoscaling, then turn autoscaling off to prevent - - further automated changes. With autoscaling in effect, scene.range is updated to correspond to the current size of the scene.

-

forward Vector pointing - - in the same direction as the camera looks (that is, from the current camera - - location, given by scene.camera.pos, toward scene.center). The user rotation - - controls, when active, will change this vector continuously. When forward is changed, the camera position changes to continue looking at center. - - Default vec(0,0,-1). Its magnitude is not significant.

-

fov Field of view of - - the camera in radians. This is defined as the maximum of the horizontal - - and vertical fields of view. You can think of it as the angular size of - - an object of size range, or as the angular size of the longer axis of the - - window as seen by the user. Default pi/3 radians (60 degrees).

-

rangeThe extent - of - the region of interest to the left or right of center. Setting range to 10 means that scene.center.x+scene.range - will be at the right edge of a square window. A sphere of radius - 10 will fill the window. A cubical box whose half-width is 10 will - overfill the window, because the front of the box in 3D appears larger - than the xy plane passing through scene.center, unless the field - of view is very small.

-

 up A vector representing - - world-space up. This vector will always project to a vertical line on the - - screen (think of the camera as having a "plumb bob" that keeps - - the top of the screen oriented toward up). The camera also rotates around - - this axis when the user rotates "horizontally". By default the - - y axis is the up vector.

-

userzoom = false user cannot zoom in and out of the scene

-

userzoom = true user can zoom (default)

-

userspin = false user cannot rotate the scene

-

userspin = true user can rotate (default)

-

-

Controlling the view using scene.camera

-

The mechanisms described above for controlling the view are designed to try to make sure that the objects are visible no matter how the user rotates or zooms the view, because the camera direction is always automatically adjusted to point toward scene.center, which by default is at the origin, and scene.range is automatically adjusted to correspond to the user zoom.

-

However, if you want to "fly" through the scene, with scene.center necessarily varying but zoom held constant, it is more convenient to move and point the camera directly. WARNING: When you take direct control of the camera, there is increased risk of seeing nothing, due to unintentionally pointing the camera away from the objects, or moving the camera far away from the objects.

-

An example of controlling the camera directly is the fly-through in the program Stonehenge, in which changing scene.camera.pos (the location of the camera) and  scene.camera.axis (the direction the camera is pointing) is a convenient way to move through the scene.

-

     canvas

-

 

-

 scene.camera.pos The current - location of the camera, whether due to your own settings, autoscaling, or as positioned by the user, is scene.camera.pos. - For example, mag(scene.center - scene.camera.pos) is the distance from the current position of the - camera to the center of the scene. The vectors scene.camera.pos and scene.mouse.ray together define all of the - 3D points under the mouse cursor.
-
- You can place the camera where you want it by executing scene.camera.pos = vec(x,y,z). When you set the camera position in this way, scene.center is reset to the location scene.camera.pos + scene.camera.axis. The effect is that the camera continues to point in the same direction as before, but from a new location.

-

 scene.camera.axis The current - direction that the camera is pointing, whether due to your own settings, autoscaling, or as positioned by the user, is scene.camera.axis, which is equal to scene.center - scene.camera.pos; it points from the camera to scene.center.
-
- When you change
scene.camera.axis, scene.camera.pos is unaffected, but scene.center is reset to the location scene.camera.pos + scene.camera.axis, and scene.forward is reset to norm(scene.camera.axis).

-

  scene.up Changing scene.up rotates the display around the z axis and would be appropriate for example if you imagine the camera is attached to an airplane that rotates around its own axis in a turn or barrel roll.

-

 scene.camera.rotate(angle=..., axis=..., origin=...) As with other VPython objects, you can rotate the camera by an angle in radians, about a specified axis (which by default is scene.camera.axis), relative to a specified origin (which by default is scene.camera.pos).

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/clone.html b/docs/GlowScriptDocs/clone.html deleted file mode 100644 index b7f21bcc..00000000 --- a/docs/GlowScriptDocs/clone.html +++ /dev/null @@ -1,71 +0,0 @@ - - - -clone - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
clone
-

clone

-
-
-
-

You can clone objects:

-

b = box(pos=vec(1,1,0), axis=vec(1,1,0),
-             color=color.red)
-bcopy = b.clone(pos=vec(1,-1,0))

-

This will give you two copies of a box, differing only in their positions. After making the clone, changes to the clone do not affect the original box.

-

If you simply say b.clone(), all of the properties of the new object are exactly the same as those of the original object.

-

Current restrictions

-

Currently you cannot clone triangles/quads, because it is the underlying vertex objects that control their appearance. You can clone compound objects.

-

Currently there is no way to clone an object from one canvas to another.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/color.html b/docs/GlowScriptDocs/color.html deleted file mode 100644 index dc192a2a..00000000 --- a/docs/GlowScriptDocs/color.html +++ /dev/null @@ -1,97 +0,0 @@ - - - -color - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
-

Color

-
-
-

In the RGB color system, you specify a color in terms of fractions of red, green, and blue, corresponding to how strongly glowing are the tiny red, green, and blue dots of the computer screen. In the RGB scheme, white is the color with a maximum of red, blue, and green (1, 1, 1). Black has minimum amounts (0, 0, 0). The brightest red is represented by (1, 0, 0); that is, it has the full amount of red, no green, and no blue.

-

Here are examples of RGB colors, with names you can - use in GlowScript:

- - - - - - - - - - - - - - - - - - - - - -
   vec(1,0,0) color.red
 vec(1,1,0) color.yellow
   vec(0,1,0) color.green
 vec(1,0.5,0) color.orange
   vec (0,0,1) color.blue
 vec(0,1,1) color.cyan
   vec(1,0,1) color.magenta
 vec(0.4,0.2,0.6) color.purple
   vec(0,0,0) color.black
 vec(1,1,1) color.white
-

You can also create your own colors, such as these:

-

vec(0.5, 0.5, 0.5) a rather dark gray;
- or say color=color.gray(0.5) to mean (0.5,0.5,0.5)

-

vec(1,0.7,0.2) a coppery color

-

Colors may appear differently on different computers, and under different 3D lighting conditions. The named colors above are most likely to display appropriately, because RGB values of 0 or 1 are unaffected by differing color corrections ("gamma" corrections).

-

There is a VPython demo program that lets you adjust RGB sliders to visualize colors and print color triples that - you copy into your program. It also provides HSV sliders to adjust hue, saturation - (how much white is added to dilute the hue), and value (brightness), which - is an alternative way to describe colors.

-

GlowScript only accepts RGB color descriptions, but - there are functions for converting color triples between RGB and HSV (hue, saturation, and value or intensity):

-
-

c = vec(1,1,0)
- # Convert RGB to HSV:
- c2 = color.rgb_to_hsv(c)
-# c2 is now vec(0.16667, 1, 1)
- # Convert back to RGB:
- c3 = color.hsv_to_rgb(c2)
- # c3 is now vec(1, 1, 0)

-

Another example: sphere( color:hsv_to_rgb( - vec(0.5,1,0.8)  )

-

You can explore the RGB and HSV color systems in the GlowScript example program Color-RGB-HSV.

-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/compound.html b/docs/GlowScriptDocs/compound.html deleted file mode 100644 index d4189a1b..00000000 --- a/docs/GlowScriptDocs/compound.html +++ /dev/null @@ -1,79 +0,0 @@ - - - -compound - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
compound
hammer
-
-
-

The compound object lets you group objects together and manage them as though they were one object, by specifying in the usual way pos, color, size (and length, width, height), axis, up, opacity, shininess, emissive, and texture. Moreover, the display of a complicated compound object is faster than displaying the individual objects one at a time. (In GlowScript version 2.1 the details were somewhat different.)

-

The object shown above is a compound of a cylinder and a box:

-

handle = cylinder( size=vec(1,.2,.2),                   color=vec(0.72,0.42,0) )
-
- head = box( size=vec(.2,.6,.2),
-             pos=vec(1.1,0,0),              color=color.gray(.6) )
-
- hammer = compound([handle, head])
- hammer.axis = vec(1,1,0)

-

The size of the object: After creating the compound named "hammer", hammer.size represents the size of the bounding box of the object.

-

The position of the compound is hammer.pos: After creating the compound, hammer.pos is located at the center of the bounding box. Later changes to hammer.pos move the center of the extrusion to a new location.

-

The individual objects in a compound are "frozen". You can't change their attributes such as positions or orientations except as a group.

-

Color blending

-

Setting hammer.color to something other than white makes a multiplicative blend of the overall color with the colors of the individual objects. For example, if the color of the handle is cyan, vec(0,1,1), and the hammer color is yellow, vec(1,1,0), the blend results in vec(0*1, 1*1, 0*0) or vec(0,1,0), which is green. If you plan to vary the color after creating the compound object, start with the color being white, vec(1,1,1), which is the default.

-

Setting parameters when creating a compound

-

You can optionally specify parameters to be applied to a compound after its creation. The following statement is equivalent to creating the hammer, then changing the position and axis, where the resulting center of the compound will be at vec(3,2,0)::

-

hammer = compound( [handle, head],
-          pos=vec(3,2,0), axis=vec(1,1,0) )

-

Compound and world coordinates

-

There are two functions for translating between compound and world coordinates, which may differ if the compound object has been moved or rotated. Suppose the name of the compound is c, c_pos is a position within that compound, and world_pos is the corresponding position in world coordinates:

-

world_pos = c.compound_to_world(c_pos)

-

c_pos = c.world_to_compound(world_pos)

-

Current restrictions

-

Currently objects in a compound can have their own values of color, opacity, shininess, and emissive, but they cannot have individual textures or bumpmaps, which can only be specified for the combined object, and which affect all of the compounded objects.

-

Currently label objects, lights, and objects based on curve objects (curve, helix) cannot be compounded. However, triangles, quads, and even other compounds can be compounded. Also, a compound object can be cloned to make additional copies.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/compound2.1.html b/docs/GlowScriptDocs/compound2.1.html deleted file mode 100644 index f8c851c6..00000000 --- a/docs/GlowScriptDocs/compound2.1.html +++ /dev/null @@ -1,86 +0,0 @@ - - - -compound - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
compound
hammer
-
-
-

The compound object lets you group objects together and manage them as though they were one object, by specifying in the usual way pos, color, size, axis, up, and texture. Moreover, the display of a complicated compound object is faster than displaying the individual objects one at a time. The object shown above is a compound of a cylinder and a box:

-

handle = cylinder( size=vec(1,.2,.2),                   color=vec(0.72,0.42,0) )
-
- head = box( size=vec(.2,.6,.2),    pos=vec(1.1,0,0), color=color.gray(.6) )
-
- hammer = compound([handle, head])
- hammer.axis = vec(1,1,0)

-

Note that after creating the hammer as a compound object, changing the axis rotates the combined object. The positions of the cylinder and box are relative to the origin, vec(0,0,0). If you set hammer.pos.x = 1, you move the hammer 1 unit to the right. The individual objects in a compound are "frozen". You can't change their attributes such as positions or orientations except as a group. It is often conceptually advantageous to create the objects near the origin, vector(0,0,0), and then after creating the compound move them by changing pos.

-

The size of a compound object

-

When you create a compound object, its size is vector(1,1,1), even if the actual length, width, and height are 10, 4, and 2. If you then set size to vector(2,1,1), the actual size of the object will be 20, 4, and 2. In other words, for a compound object size is a multiplier of the original size.

-

Changing axis doesn't change size, nor vice versa

-

When you change the size of an ordinary VPython object, the magnitude of the axis is changed to be the x component of the size, and when you change the axis, the x component of the size is changed to be the magnitude of the axis. These interactions between size and axis do not apply to compound objects.

-

Color blending

-

Setting hammer.color to something other than white makes a multiplicative blend of the overall color with the colors of the individual objects. For example, if the color of the handle is cyan, vec(0,1,1), and the hammer color is yellow, vec(1,1,0), the blend results in vec(0*1, 1*1, 0*0) or vec(0,1,0), which is green.

-

Setting parameters when creating a compound

-

You can optionally specify parameters for a compound. The following statement is equivalent to creating the hammer, then changing the positoin and axis:

-

hammer = compound( [handle, head],
-                   pos=vector(3,2,0),
-                    axis=vec(1,1,0) )

-

Compound and world coordinates

-

There are two functions for translating between compound and world coordinates, which may differ if the compound object has been moved or rotated. Suppose the name of the compound is c, c_pos is a position within that compound, and world_pos is the corresponding position in world coordinates:

-

world_pos = c.compound_to_world(c_pos)

-

c_pos = c.world_to_compound(world_pos)

-

Current restrictions

-

Currently objects in a compound can have their own colors and opacities but they cannot have individual textures or bumpmaps, which can only be specified for the combined object, and which affect all of the compounded objects.

-

Currently label objects, lights, and objects based on curve objects (curve, helix) cannot be compounded. However, triangles, quads, and even other compounds can be compounded.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/cone.html b/docs/GlowScriptDocs/cone.html deleted file mode 100644 index 67b4616e..00000000 --- a/docs/GlowScriptDocs/cone.html +++ /dev/null @@ -1,96 +0,0 @@ - - - -cone - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - -
cone
cone
-
-
-

cone The cone object - has a circular or elliptical cross section and tapers to a point. The following statement - will display a cone with circular cross section with the center of its circular base at (5,2,0), pointing - parallel to the x axis with length 12; the wide end of the cone has diameter = 2:

-
-

cone( pos=vec(5,2,0),
-      axis=vec(1,0,0),
-      size=vec(12,2,2) )

-

If you specify the size to be vec(12,1,2), the cone will have an elliptical cross section.

-

Here is a full list of attributes for a cone. All 3D objects have all of these attributes, other than arrow and curve:

-

pos Position: the center of one end of the cone; default = vec(0,0,0).

-

size The length, width, and height of the cone; default = vec(1,1,1).

-

axis The axis points in the direction of the length of the cone, default = vec(1,0,0). Only the direction of the axis is meaningful, not its magnitude. The length of the cone is size.x, not the magnitude of the axis.

-

color Color of object, - as a red-green-blue (RGB) triple: vec(1,0,0) is the same as color.red, default = vec(1,1,1), - which is color.white.

-

opacity Opacity of object, default = 1 (fully opaque); 0 is completely transparent.

-

shininess 0 to 1, default 0.6; governs the amount of specular reflections.

-

emissive If True, local and distant lights are ignored, and the brightness is governed by the object's own color. An example of its use is to put an emissive sphere at the location of a local_light, which looks like a glowing lamp. The default for emissive is False.

-

up Which side - of the cone is "up"; this has only a subtle effect - on the 3D appearance of a cone unless the cross section is not circular or a texture is applied; default = vec(0,1,0).

-

visible If False, - - object is not displayed; e.g. obj.visible = False
-
Use obj.visible = True to make the object - - visible again.

-

texture You can specify a texture to apply to the object's surface. See the Textures documentation.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

To display a trail or an arrow along the path of a moving object, see Attach a trail or arrow.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/controls.html b/docs/GlowScriptDocs/controls.html deleted file mode 100644 index 87f6d43b..00000000 --- a/docs/GlowScriptDocs/controls.html +++ /dev/null @@ -1,77 +0,0 @@ - - - -controls - - - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - -
Widgets: button, radio, checkbox,
- slider, menu,
- wtext
controls
-

Run the ButtonsSlidersMenus example program (snapshot shown above) and inspect the program code to see how to create buttons, sliders, and drop-down menus to control the execution of a 3D animation.

-
-

You'll see dollar signs ("$") all through the example. It is a standard abbreviation for jQuery, a widely used library for making connections between a JavaScript program and the HTML of a web page. You may wish to study a jQuery tutorial. GlowScript imports the jQuery and jQuery-ui libraries.

-
-

Full understanding of the jQuery mechanisms requires a good knowledge of HTML coding as well as knowledge of jQuery itself. However, the examples shown in the program above should provide you with enough information to be able to use controls in your own GlowScript programs.

-

You can also use the simpler scheme described here.

-

GlowScript provides three anchor points that can be used to place jQuery widgets on the page:

-

scene.title_anchor
- scene.caption_anchor
- print_anchor

-

In a jQuery operation, appendTo(cvs.title_anchor) can be used to add a widget to the title above the canvas named cvs and appendTo(cvs.caption_anchor) to add a widget to the caption below the canvas. Specifying print_anchor adds a widget to the bottom of the web page, where the print area is.

-

Important: Do not use character strings to specify a function as an argument in a jquery statement, as the character string is evaluated in a global context outside the GlowScript context, and your function will not be found. For example, say something like $("<button/>").click(handle_click) rather than something like $("<button onclick='handle_click'></button")

-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/css/help.css b/docs/GlowScriptDocs/css/help.css deleted file mode 100644 index c4cba3c7..00000000 --- a/docs/GlowScriptDocs/css/help.css +++ /dev/null @@ -1,30 +0,0 @@ -body { margin-bottom: 0px; font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px } - - -a:link, a:visited, a:hover { - color: #0000ff; - font-weight: bold; - text-decoration: none; -} - -a:hover { - text-decoration: underline; -} -/* overrides decoration from previous rule for hovered links */ - -td, textarea, input, select { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 13px} -.sectionHead { font-size: 16px; line-height: 30px; font-weight: bold; color: #000000;} -.tableDetail { background-color: #CCCCCC;} -.tableHeading { color:#FFFFFF; text-decoration: bold ; background-color: #424973} -.Courier { - font-family: "Courier New", Courier, monospace; -} -.program { - font-family: "Courier New", Courier, monospace; - color: #03F; -} -.program { - color: #00C; - font-family: "Courier New", Courier, monospace; - font-weight: bold; -} diff --git a/docs/GlowScriptDocs/curve.html b/docs/GlowScriptDocs/curve.html deleted file mode 100644 index f3b6715f..00000000 --- a/docs/GlowScriptDocs/curve.html +++ /dev/null @@ -1,275 +0,0 @@ - - - -curve - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - - -
curve
curve
-

The curve object displays straight lines between - points, and if the points are sufficiently close together you get the - appearance of a smooth curve.

-

Details of the GlowScript curve object

-

The simplest example of a curve is the following statement, which draws a white straight line of length 2, between the position < -1,-1,0 > and the position < 1,--1,0 >:

-
-

c = curve(vector(-1,-1,0), vector(1,-1,0))

-
-

You can add additional points to this curve like this, completing a square of width 2 whose center is at location < 0,0,0 >:

-
-

c.append(vector(1,1,0), vector(-1,1,0),          vector(-1,-1,0))

-
-

Suppose you have two vectors named v1 and v2. Any of the following schemes will draw a white straight line from position v1 to position v2:

-
-

1) c = curve(v1,v2)

-

2) c = curve([v1,v2])

-

3) c = curve(pos=[v1,v2])

-

4) c = curve(v1)
-    c.append(v2)

-

5) c = curve()
-    c.append(v1,v2)

-

Shorthand

-

When specifying a list of points as pos = [....] you can use lists or tuples without the keyword "vector":

-
-

curve( pos=[(1,1,0, (-1,1,0)], color=...)

-
-

Specifying overall color and radius

-

By default a curve is white, with a radius of the cross-section of only a few pixels. You can change the default color and radius for all points, using either of the following schemes:

-
-

1) c = curve(pos=[v1,v2], color=color.cyan,              radius=0.3)

-
-
-

2) c = curve(color=color.cyan, radius=0.3)
-    c.append(v1,v2)

-
-

Specifying the color and radius of individual points

-

You can specify the color and radius of individual points that override the color and radius specified for the curve as a whole. The following sequence will create two "dictionaries" to use as individual points, then will use them to draw a line whose color shades from red to blue and whose radius increases from 0.1 to 0.3:

-
-

p1 = dict(pos=v1, color=color.red,           radius=0.1)
- p2 = dict(pos=v2, color=color.blue,           radius=0.3)
- curve(p1,p2)

-
-
-
-
-

In addition to the attributes pos, color, radius, each point has a visible attribute, which makes that particular point visible or invisible.

-
-
-

Retaining a limited number of points

-
-

When creating a curve, or when appending a point to a curve, you can specify how many points should be retained. The following statement specifies that only the most recent 150 points should be retained as you add points to the curve:

-

c = curve(retain=150)

-

The following statement specifies that if there are already 30 points in the curve, the oldest one should be deleted and the new point added.

-

c.append( pos=vector(2,-1,0), retain=30)

-

The curve attributes

-

Here is a summary of the attributes for individual points or for the curve as a whole:

-

pos A vector position or list of positions.

-

color Color - of a point; if specified for the curve as a whole, it specifies the color of any points for which no specific color was given.

-

radius Radius of - the cross-section of this segment of the curve; if specified for the curve as a whole, it specifies the radius of any points for which no specific radius was given. The default radius is 0, which makes a thin curve.

-

visible If False, - - point is not displayed; if False for the curve as a whole, no points are displayed.

-

retain Specify how many points to retain.

-

-

A curve also has the standard attributes size, axis, up, shininess, and emissive.

-

No texture, opacity, or compounding: Currently curves cannot be transparent, it is not possible to apply a texture, and a curve cannot be part of a compound object.

-

Moving, reorienting, and resizing a curve

-

Point positions are relative; the use of origin: A point whose pos is vector(2, 1, 0) is of course normally displayed at location vector(2, 1, 0). However, the position of a point is relative to a curve's own origin value, which by default is vector(0, 0, 0). If you change the curve's origin value to vector(10, 6, 5), the point is displayed at the location vector(12, 7, 5); that is, the point is displayed 2 to the right, 6 above, and 0 in front of the curve's position vector(10, 6, 5). Another way of saying this is that the display location is the vector sum vector(10, 6, 5) + vector(2, 1, 0). This means that you can quickly and efficiently move the entire curve just by changing the curve's origin value. The pos value of an individual point does not change; it's just that the point is displayed in a shifted position. As a result, moving an entire curve is very fast.

-
-
-

Similarly, changes to size, axis, up, shininess, and emissive immediately and quickly change the size of the curve, its orientation in space, and the appearance of its surface. When you specify the position of a point, it is relative to an origin at vector(0,0,0) and with the standard axis vector(1,0,0). Changing the size does not change the radius; it just moves the points closer or farther apart.
-

-

Rotating a curve

-

As with other objects, tne way to change the orientation of the entire curve is to change the curve's axis. You can also rotate the entire curve about a specified axis. If you don't specify an origin, rotation will occur around the origin of the curve:

-

c.rotate( angle=ang, axis=a, origin=o )

-

c.rotate( angle=ang, axis=a )
-
-

-

Curve methods

-

The basic aspects of the GlowScript curve object are the same as the Classic VPython curve object. You create a curve and append points to it. However, modifying existing points is not done directly but instead by using a powerful set of functions, and this change makes it possible to display curves much more rapidly. In Classic VPython, the possibility of direct modification of the positions meant that the entire curve had to be reprocessed every time it was rendered, on the chance that some undetected change had occurred.

-
-

The following are useful for modifying a curve named "c" (full documentation below):

-

c.npoints The total number of points currently in the curve.

-

c.append(...) Add a point or several points to the end.

-

c.unshift(...) Insert a point or several points at the start.

-

c.splice(...) Insert a point or several points anywhere.

-

c.modify(...) Modify the Nth point.

-

c.clear() Remove all points.

-

data =c.pop(n) Get the data for point number n and remove it.

-

data = c.shift() Get the data for the first point and remove it.

-

data = c.point(N) Get the data for the Nth point.

-

data = c.slice(start, end) Get the data for a list of points.

-
-

Appending points

-
-

Suppose you have created a curve named c. You can add points to the curve one at a time, like this:

-

c.append(pos=vector(-1,0,0), color=color.red,
-             radius=0.05)
- c.append(pos=vector(0,1,0), color=color.cyan,
-             radius=0.15)
- c.append(pos=vector(1,0,0), color=color.red,
-             radius=0.05)

-
-

This creates the following image:

-
-
-
-
-

                       curve

-
-
-
-
-
-

If you don't need to specify color or radius you can just give a list of positions, either as individual positions or in a list of positions:

-

c.append( vector(-1,0,0), vector(0,1,0),           vector(1,0,0) )
- c.append([vector(-1,0,0), vector(0,1,0),           vector(1,0,0)])

-
-

Suppose you have created a curve named c, and p represents either just a position vector (as just shown above) or a full description of a point in either of the following forms:
-
-     p = {pos:vector, color:a vector, radius:a number, visible:true or false}
-
-     p = dict(pos=a vector, color=a vector,
-                 radius=a number, visible=true or false)

-
-

-
-

c.append( p1, p2, p3 ) # add several points

-
-

c.append([p1, p2, p3]) # add several points

-

pts = [p1, p2, p3]
- c.append(pts)          # add several points

-
-

You can also add several points that all have the same color, radius, etc.:

-
-
-

c.append(pos=[p1, p2, p3], color=color.green)

-

-

Manipulating points

-
-
-
-

Here are details on getting data about points in a curve named "c", or modifying them.

-

npoints

-
-

c.npoints   # number of points in the curve

-

-

append

-

c.append(...) # add points at end
-              # (see above)

-

-

unshift

-

c.unshift(p1, p2, p3)  # insert points at                        # start

-

pts = [p1, p2, p3]
- c.unshift(pts)        # insert points at                       # start

-

The splice method inserts new points starting at location "start" (where 0 is the first point of the curve), deleting "howmany" points before doing the insertion:

-

c.splice(start,howmany,p1,p2,p3) # insert

-

pts = [p1, p2, p3]
- c.splice(start,howmany,pts) # insert

-

-

The modify method lets you change specified attributes of a point:

-

c.modify(N, # modify point number N
-     pos=p, color=c, radius=r, visible=v)
- c.modify(N, x=3, y=5) # changing x and y
-                      # but not z
- c.modify(N, vector(x,y,z)) # change only pos

-

-

clear

-

c.clear() # remove all points from curve

-

-

pop

-

data=c.pop()  # get & remove last point
-data=c.pop(3) # get & remove point number 3

-

-

shift This is the same as c.pop(0):

-

data = c.shift() # get & remove first point

-

-

point

-

P = c.point(N) # get a point in the form
-       # {pos:p, color:c, radius:r,           visible:v}
-       # P.pos is p, P.color is c, etc.

-

-

slice

-

data = c.slice(2,4) # get a list of
-     # points from point 2 through point 3,
-     # each in the form
-     # {pos:p, color:c, radius:r, visible:v}
-     # The first point is 0,
-    # the last point is -1

-
-
-

Interpolation of colors

-
-

The curve machinery interpolates colors from one point to the next. If you want an abrupt change in color, add another - point at the same location. In the following example, adding a cyan - point at the same location as the orange point makes the first - segment be purely cyan.

-
-

c = curve(color=color.cyan, radius=0.1)
- c.append( vector(-1,0,0) )
- # add an extra cyan point:
- c.append( vector(0,0,0) )
- # repeat the same point:
- c.append( pos=vector(0,0,0),
-          color=color.orange )
- # add another orange point:
- c.append( pos=vector(1,0,0),
-          color=color.orange )

-

In the image shown here, the upper thick curve, made without the second cyan point, has three pos and color points, cyan, orange, orange, left to right, so the blue fades into the orange. The lower curve includes the extra cyan point and has four pos and color points, cyan, cyan, orange, orange, so there is a sharp break between blue and orange. (Again, in JavaScript use "push" instead of "append".)

- - - - -
colors abutting
- -
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/cylinder.html b/docs/GlowScriptDocs/cylinder.html deleted file mode 100644 index d2cb7bd2..00000000 --- a/docs/GlowScriptDocs/cylinder.html +++ /dev/null @@ -1,129 +0,0 @@ - - - -cylinder - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - -
cylinder
cylinder
-

Studying this description of the cylinder object - provides an overview of important aspects common to all of the - GlowScript 3D objects, box, sphere, pyramid, etc. Additional details about how to orient an object using "axis" and "up" are found in the description of the box object.

- - - - - -

Here is an example - of how to make a cylinder, naming it "rod" for future reference:

-

rod  = cylinder()
- rod.pos  = vec(0,1,2)
- rod.axis = vec(1,0,0)
- rod.size = vec(5,1,1) -

-

Attributes: The properties pos (position), axis, and size are called "attributes" of the object. The function "vec" creates a vector with (x,y,z) components.

cylinder
-

Alternatively, you can specify the initial values of the attributes when creating the cylinder::

-

rod = cylinder( pos=vec(0,2,1),                 axis=vec(1,0,0),
-                size=vec(5,1,1) )

-

The center of one end of this cylinder (pos) is at x=0, y=2, - and z=1. Its axis lies along the x axis, vec(1,0,0), which points to the right (y points up, z points out of the screen toward you). The size or bounding box is 5 in the direction of the axis, so that the other - end of the cylinder is at (5,2,1). The lateral size of the cylinder, the diameter, is 1. If you specify the size to be vec(3,1,2), the cylinder will have an elliptical cross section.

-

JavaScript

-

Here is the form to use in JavaScript (if you specify "JavaScript" in the header line of your program):

-

var rod = cylinder( {pos:vec(0,2,1),
-    axis:vec(1,0,0), size:vec(5,1,1)} )

-

Note the required "var" and required braces. Also, True and False are spelled true and false.

-

Modifying attributes

-

You can modify the position attribute of the cylinder after it has - been created, which has the effect of moving it immediately to the new position:

-

rod.pos=vec(15,11,9) # change (x,y,z)
- rod.pos.x=15 # change the x component

-

If you create an object such as a cylinder without - giving it a name such as rod, you can't refer - to it later. This doesn't matter if you never intend to modify the object.

-

The bounding box: All of the 3D objects (except for arrow) can be thought of as being contained in a box whose size is specified by the size attribute. Changing the size corresponds to stretching or squeezing the box that contains the object. Setting size to vec(3,1,2) means that if the axis is in the x direction, vec(1,0,0), the bounding box will be 3 have a length of 3 in the x direction, a height of 1 in they y direction, and a depth of 2 in the z direction.

-

If you change the axis (rod.axis) to point in some direction other than in the x direction, you still specify the size attribute as though the axis were pointing to the right. In other words, when specifying the size, imagine that the object is aligned along the x axis even if you specify a different direction by setting the axis attribute. This is true for all the 3D objects (other than arrow).

-

Specifying the color: Since we didn't specify a color for rod, the cylinder will be the - default color, which is - white (shown on a black background). After creating the cylinder, you can change its color. The following will change the color to blue:

- -

rod.color = vec(0,0,1) # same as color.blue

-

This uses the - so-called RGB system for specifying colors in terms of fractions of red, - green, and blue. (For details on choosing colors, see Specifying - Colors.) You can set individual amounts of red, green, and blue, as colors are treated as though they were vectors, with x, y, and z components:

- -

rod.color.x = 0.4
- rod.color.y = 0.7
- rod.color.z = 0.8

-

Here is a full list of attributes for a cylinder. All 3D objects have all of these attributes, other than arrow and curve:

-

pos Position: the center of one end of the cylinder; default = vec(0,0,0).

-

size The length, width, and height of the cylinder; default = vec(1,1,1).

-

axis The axis points in the direction of the length of the cylinder, default = vec(1,0,0). Only the direction of the axis is meaningful, not its magnitude. The length of the cylinder is size.x, not the magnitude of the axis. Changing axis may change up, to ensure that axis and up are always perpendicular to each other.

-

up Which side - of the cylinder is "up"; this has only a subtle effect - on the 3D appearance of a cylinder unless the cross section is not circular or a texture is applied; default = vec(0,1,0). Changing up may change axis, to ensure that axis and up are always perpendicular to each other.

-

color Color of object, - as a red-green-blue (RGB) triple: vec(1,0,0) is the same as color.red, default = vec(1,1,1), - which is color.white.

-

opacity Opacity of object, default = 1 (fully opaque); 0 is completely transparent.

-

shininess 0 to 1, default 0.6; governs the amount of specular reflections.

-

emissive If True, local and distant lights are ignored, and the brightness is governed by the object's own color. An example of its use is to put an emissive sphere at the location of a local_light, which looks like a glowing lamp. The default for emissive is False. (For JavaScript, specify true or false instead of True or False.)

-

visible If false, - - object is not displayed; e.g. rod.visible = False
-
Use rod.visible = True to make the object - - visible again. (For JavaScript, specify true or false instead of True or False.)

-

texture You can specify a texture to apply to the object's surface. See the Textures documentation.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

To display a trail or an arrow along the path of a moving object, see Attach a trail or arrow.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/delete.html b/docs/GlowScriptDocs/delete.html deleted file mode 100644 index 35ce7a8a..00000000 --- a/docs/GlowScriptDocs/delete.html +++ /dev/null @@ -1,51 +0,0 @@ - - - -delete - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
-

Deleting an Object

-
-
-

To hide a GlowScript object just make it invisible: ball.visible - = False. This does not delete the object from computer memory, and you can make it visible again later. (In JavaScript say ball.visible = false.)

-

If however you later re-use the name ball, - for example by creating a new object and naming it ball, - the computer will be free to release the memory used by the object formerly named ball (assuming no other names currently refer - to that object). If the object is visible when you re-use the name ball, the original object will not be deleted from computer memory, and it will remain visible in the window.

-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/extrusion.2.1.html b/docs/GlowScriptDocs/extrusion.2.1.html deleted file mode 100644 index 59d1d272..00000000 --- a/docs/GlowScriptDocs/extrusion.2.1.html +++ /dev/null @@ -1,60 +0,0 @@ - - - -compound - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
extrusion
extrusion
-
-
-

The extrusion object extrudes a 2D shape along a path. Here is an example.

-

Here is the detailed documentation of the extrusion object.

-
-
-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/extrusion.html b/docs/GlowScriptDocs/extrusion.html deleted file mode 100644 index 8b5d6889..00000000 --- a/docs/GlowScriptDocs/extrusion.html +++ /dev/null @@ -1,60 +0,0 @@ - - - -compound - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
extrusion
extrusion
-
-
-

The extrusion object extrudes a 2D shape along a path. Here is an example.

-

Here is the detailed documentation of the extrusion object. Note however that when using RapydScript or JavaScript rather than VPython there is no linkage between size and axis.

-
-
-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/factorial.html b/docs/GlowScriptDocs/factorial.html deleted file mode 100644 index b6c41a6c..00000000 --- a/docs/GlowScriptDocs/factorial.html +++ /dev/null @@ -1,75 +0,0 @@ - - - -factorial - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
-

The factorial and combin Functions

-
-
-
-

print(factorial(4)) # gives 24
- print(combin(10,2)) # gives 45

-

The factorial function factorial(N) - is N!; 4! is (4)(3)(2)(1) = 24, and 0! is defined to be 1.
-The combin function is combin(a,b) = a!/(b!*(a-b)!)
.

-

A major use of these functions is in calculating the number - of ways of arranging a group of objects. For example, if there are 5 numbered - balls in a sack, there are factorial(5) = - 5! = 5*4*3*2*1 = 120 ways of taking them sequentially out of the sack (5 - possibilities for the first ball, 4 for the next, and so on).

-

If on the other hand the 5 balls are not numbered, but 2 - - are green and 3 are red, of the 120 ways of picking the balls there are - - 2! indistinguishable ways of arranging the green balls and 3! ways of arranging - - the red balls, so the number of different arrangements of the balls is combin(5,2) = 5!/(3!*2!) = 10.

-

Logically, the combin function is just a combination of - - factorial functions. However, cancellations in the numerator and denominator - - make it possible to evaluate the combin function for values of its arguments - - that would overflow the factorial function, due to the limited size of floating-point - - numbers. For example, combin(5,2) = 5!/(3!*2!) - - = (5*4)/(2*1) = (2.5*4) = 10, and we didn't have to evaluate any of the factorials fully..

-
-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/files.html b/docs/GlowScriptDocs/files.html deleted file mode 100644 index c4cbd460..00000000 --- a/docs/GlowScriptDocs/files.html +++ /dev/null @@ -1,73 +0,0 @@ - - - -files - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- -

File operations

-

You can import an external JavaScript library or read a file on the user's local computer.

-

get_library: import a library

-

To import a JavaScript library, do this:

-

get_library("https://xyz.org/lib.js")

-

If the file cannot be found within a reasonable amount of time, an error message is displayed. For use with your own callback function, see Using GlowScript as a JavaScript library.

-

Currently the library must be written in JavaScript, not RapydScript, or VPython. Moreover, there are restrictions imposed because the library doesn't go through the special preprocessing that occurs when you run your program at glowscript.org. The library cannot include options such as "rate" or "waitfor", and the following vector operations must be rewritten as shown, where A and B are vectors and k is an ordinary number:

-

A+B -> A.add(B)
- A-B -> A.sub(B)
- k*A -> A.multiply(k)
- A/k -> A.divide(k) -
-

-

However, when editing a file at glowscript.org in any language, clicking "Share this program" outputs code that has been converted to executable JavaScript, so you may find it useful to start from, say, RapydScript or VPython. You may have to make adjustments to the generated JavaScript.

-

It is not currently possible to import from your own glowscript.org files, so the library must be placed on your own web site.

-
-
-

read_local_file: user chooses a file

-

The reading and writing of files is very different in a web browser, due to security issues (you don't want an arbitrary web page to read and write your computer files). You can ask the user of your program to choose a text file on the user's computer and then use the contents of the file. The function read_local_file appends a button that says "Choose File" on the screen at the location specified, such as scene.title_anchor or scene.caption_anchor. When the user clicks that button, a file dialog appears which lets the user choose a file. Then the button is removed, and information about the file is returned.

-

f = read_local_file(
-          scene.title_anchor)
- print(f.name) # The file name
- print(f.size) # File size in bytes
- print(f.type) # What kind of file
- print(f.date) # Creation date if available
- print('*************')
- print(f.text) # The file contents

-

For use with your own callback function, see Using GlowScript as a JavaScript library.

-

If you say read_local_file(), the button is appended to the bottom of the window, corresponding to the jQuery location $('body').

-
-
-

Writing a file

-

Due to security issues, it is not possible to write directly to the user's computer storage from a browser. Currently the only way to write data to a local file is to print the data, select the print area (ctrl-A), copy (ctrl-C), paste into a local text editor, and save the file.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/frame.html b/docs/GlowScriptDocs/frame.html deleted file mode 100644 index 4768468c..00000000 --- a/docs/GlowScriptDocs/frame.html +++ /dev/null @@ -1,53 +0,0 @@ - - - -frame - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
-
-
-

Composite Objects with frame

-
-

There is currently no frame object in GlowScript. However, the GlowScript compound object provides an alternative for many purposes.

-
-

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/graph.html b/docs/GlowScriptDocs/graph.html deleted file mode 100644 index 35a4eafa..00000000 --- a/docs/GlowScriptDocs/graph.html +++ /dev/null @@ -1,192 +0,0 @@ - - - -graph - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
Graphs
graph
-
-

In this section we describe features for plotting graphs - - with tick marks and labels. If you move the mouse over the graph, crosshairs and the x,y position are displayed. See the example program MakeGraphs.

-

You can now choose between two graphing packages, one which is faster, which is the one used in previous versions (currently based on Flot), or one which offers rich interactive capabilities such as zooming and panning but is slower (currently based on Plotly). The default is the fast version, corresponding to specifying fast=True in a graph, gcurve, gdots, gvbars, or ghbars statement. To use the slower but more interactive version, say fast=False. In many programs the "slow" version may run nearly as fast as the "fast" version, but if you plot a large number of data points the speed difference can be significant.
-
-Both versions offer capabilities new to GlowScript: If you specify markers=True when creating a gcurve object, dots will be displayed at each gcurve point, and you can specify marker_radius (the default is slightly larger than the gcurve width) and marker_color (the default is the gcurve color). For a graphing object you can specify label="cos(x)" and this text, in the color of the object, will appear at the upper right. If you say legend=False the label is not actually shown.
-
-Do try fast=True to see the many options provided. As you drag the mouse across the graph with the mouse button up, you are shown the numerical values of the plotted points. You can drag with the mouse button down to select a region of the graph, and the selected region then fills the graph. As you drag just below the graph you can pan left and right, and if you drag along the left edge of the graph you can pan up and down. As you move the mouse you'll notice that there are many options at the upper right. Hover over each of the options for a brief description. The "home" icon restores the display you saw before zooming or panning. Try this demo.

-

Here is a simple example of how to plot a line graph, with connected points:

-

f1 = series(color=color.cyan)
- # x goes from 0 to 8 in steps of 0.01:
- for x in range(0,8,0.01):
-    f1.plot(x,5*cos(2*x)*exp(-0.2*x))

-

A set of data to be plotted is a series, and there can be more than one series on a graph. A series can be represented by connected points (line), which is the default, by - disconnected points (scatter), - or by vertical bars (bar). To display a series as a scatter or bar graph, set the series type:

-

series( type='scatter' ... )
- series( type='bar' ... )

-

After creating a series you can plot one or more points like this:

-

f1.plot(2,4)
- f1.plot([ [1,5],[3,-2],[6,4] ])

-

When creating a series you can optionally give a list of data points:

-

vb=series(data=[ [1,5],[3,-2],[6,4] ])

-

After displaying the series as a line type, you can change the display of the data simply by changing the series type:

-

vb.type = 'bar'

-

After creating one of these graphing objects, you can reset the data to a list of points (an empty list will remove this data from the graph):

-

vb.data = [ [1,-2], [3,2], [8,3], [12,4] ]
-

-

You can plot more than one thing on the same graph, and specify labels. The following statements produce the graph displayed above:

-

p = series( color=color.red,
-                 label='sin(x)' )
- q = series()
- # Can set color after making a series:
- q.color = color.green
- q.label = 'cos(x)'
-
- for i in range(0,11,0.2): -
-    rate(100)
-    p.plot(i+5, 3+2*sin(i))
-    q.plot(i+5, 3+2*cos(i))

-

It is often the case that skipping points may hardly affect the display but will make graph plotting much faster, in which case it's useful to specify an interval between plotting of points:

-

interval If interval=10, a point is added to the plot only every 10th time you ask to add a point. If interval is 0, no plot is shown. If interval is -1, no points are skipped.

-

-

Deleting an entire graph

-

If you say g = graph(), you can delete the entire graph by saying g.delete().

-

 

-
-
-
-
JavaScript version
-
-

var p = series( {color:color.red,
-                  label='sin(x)'} )
- var q = series()
- # Can set color after making a series:
- q.color = color.green
- q.label = 'cos(x)'
-
- for (var i=0; i<=11; i+=0.2) {
-     rate(100)
-     p.plot(i+5, 3+2*sin(i))
-     q.plot(i+5, 3+2*cos(i))
- } -

-

Summary of options that affect a series

-

color Color of the series

-

label Text of the label for the series

-

width Width in pixels of a line, or the edge of a scatter circle or bar

-

radius Radius in pixels of a scatter circle (default is 3 pixels)

-

size Diameter in pixels of a scatter circle (default is 6 pixels)

-

delta Width of a bar (default = 1)

-

horizontal true for horizontal bars (default is false, giving vertical bars)

-

interval Skip points (see discussion above)

-

-

Special option for a line series

-

For a line series, if you - specify dot=true the current plotting - point is highlighted with a dot, which is particularly useful if - a graph retraces its path. You can specify a dot_radius attribute, - which specifies the width of the dot in pixels (default is 1 pixel more than half the width of the line). - By default the dot has the same color as the line, but you can - specify a different color, as in dot_color=color.green.

-

Overall graph options

-

You can establish a graph to set the size, position, and title for the title bar of the graph window, - - specify titles for the x and y axes, specify maximum values for each - - axis, and set foreground and background colors, before creating gcurve or other kind - - of graph plotting object:

-

gd = graph(width=600, height=150,
-       title=''    <b>Test</b>',
-      xtitle='t', ytitle='N',
-       foreground=color.black, - -       background=color.white,
-       xmax=50, - - xmin=-20,
-      ymax=5E3, ymin=-2E3)

-

In this example, the graph window will have a size of 600 by 150 pixels, and above the graph - - there will be an indented bold title "Test". The x and y axes of the graph will have the labels. 't' and 'N' (xtitle and ytitle do not currently handle html commands such as <b>). The foreground color is black (the default), and the background color is white (the default). Once the graph has been activated by executing gcurve or gdots or gvbars or ghbars, it is not possible to change the title, xtitle, or ytitle and further.

-

Instead of autoscaling the graph to display all the data, the graph in this example - - will have fixed limits. The horizontal axis will extend from -20 to +50, - - and the vertical axis will extend from -200 to +5000. If you specify xmax but not xmin, it is as though you had also specified xmin to be 0; similarly, if you specify xmin but not xmax, xmax will be 0. The same rule holds for ymax and ymin.

-

Offsets: If you specify xmin or ymin to be greater than zero, or xmax or ymax to be less than zero, the crossing point (origin) of the x and y axes will no longer be at (0,0), and the graphing will be offset. If you offset the origin of the graph, you must specify xmax to be greater than xmin, and/or ymax to be greater than ymin.

-

If you simply say graph(), the defaults - - are width=640, height=200, fully autoscaled. Black foreground and white background are the defaults.

-

You can optionally specify minimum and maximum x or y values with xmin, xmax, ymin, ymax. The following will set minimum values for x and y, with the maximum values determined by the actual data:

-

gd = graph( width=600, height=150,
-             xmin=-5, ymin=10 } )

-

After creating a graph, you can change any of these graph attributes:

-

gd.xmin = 4
- gd.width = 300

-

You can align a graph to the left or right of another graph or a canvas:

-

align Set to "left" (graph forced to left side of window), "right" (graph forced to right side of window), or "none" (the default alignment). For example, if you want to place a graph to the right of a canvas, set the canvas align attribute to the string "left" and the graph align attribute to "right". If the window is too narrow, the object that is on the right will be displayed below the other object.

-

You can have more than one graph window: just create another graph. By default, any graphing objects - - created following a graph belong to that - - graph, or you can specify which graph a new object belongs to:

- -

E = series(graph=graph2,
-                type='scatter',
-                color=color.blue)

-

-

Log-log and semilog plots

-

When creating a graph, you can specify logarithmic plots by specifying logx=True and/or logy=True; in JavaScript, true.  All values must be positive, representing logarithms of numbers between infinitely small (logarithm approaches 0) and infinitely large; that is, numbers such as 0.01, 0.1, 1, 10, 100, etc. Do not specify a logx axis for horizontal bars, or logy for vertical bars, because the starting point of a bar is 0, and the log of 0 is negative infinity.

-

graph vs. canvas

-

A graph region is similar to a canvas region. The main difference - is that a graph is essentially two-dimensional and has nonuniform x and - y scale factors.

-

For more information

-

GlowScript incorporates the Flot 2D graphing package, and more information is available on the many features that Flot offers. The data atttribute is essentially the same as the data attribute of Flot graphs, except that GlowScript RGB colors (with components in the range 0 to 1) are converted to Flot RGB colors (with components in the range 0-255).

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/helix.html b/docs/GlowScriptDocs/helix.html deleted file mode 100644 index 64f6bd6f..00000000 --- a/docs/GlowScriptDocs/helix.html +++ /dev/null @@ -1,91 +0,0 @@ - - - -helix - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
helix
helix
-
-
-

The following statement will display a helix that is - parallel to the x axis (the default axis direction), with length 5 and diameter 1:

-
-

var spring = helix( pos=vec(0,2,1),
-                    size=vec(5,1,1) )

-

The attribute thickness is the diameter of the cross section of the curve used to draw the helix; default is diameter/10.

-

There is also a coils attribute, which is the number of coils; the default is 5.

-

Here is the rest of the attributes for a helix. All 3D objects have all of these attributes, other than arrow (which has axis_and_length instead of axis):

-

pos Position: the center of one end of the helix; default = vec(0,0,0).

-

size The length, width, and height of the helix; default = vec(1,1,1). Changing the size does not change the thickness.

-

axis The axis points in the direction of the length of the helix, default = vec(1,0,0). Only the direction of the axis is meaningful, not its magnitude. The length of the helix is size.x, not the magnitude of the axis.

-

color Color of object, - as a red-green-blue (RGB) triple: vec(1,0,0) is the same as color.red, default = vec(1,1,1), - which is color.white.

-

up Which side - of the helix is "up"; default = vec(0,1,0).

-

visible If False, - - object is not displayed; e.g. spring.visible = False
-
Use spring.visible = True to make the object - - visible again.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

No texture or opacity: Currently helixes, like curves, cannot be transparent, it is not possible to apply a texture, and it cannot be part of a compound object.

-

To display a trail or an arrow along the path of a moving object, see Attach a trail or arrow.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/history.html b/docs/GlowScriptDocs/history.html index 03fa58fa..1e3cdc5f 100644 --- a/docs/GlowScriptDocs/history.html +++ b/docs/GlowScriptDocs/history.html @@ -1,122 +1,20 @@ - - history - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- +
-
+
- - - - - -
Log of developments
ball in box
-
-
-

2019 Aug. 26: GlowScript 2.9
- The Streamline library is eliminated thanks to the new "async" and "await" options in JavaScript; compilation is now about 6 times faster. Can now put waiting functions such as pause, waitfor, sleep, and rate in functions that are bound to events. A new input() function mimics that of Python, and the winput function is enhanced to permit use without binding to a function, and to provide a prompt for the user. It is now possible for a program to trigger an event to be processed by a bound function. There is no longer any need to avoid naming an object "wait", which was associated with the use of Streamline.

-

2018 June 20: GlowScript 2.8
-An update to the Streamline library fixes bugs in complex programs.

-

2018 Jan. 28: GlowScript 2.7
-Now two graphing packages - are available, a somewhat improved version based on Flot (fast=True), and a new version based on Plotly (fast=False). The Plotly version offers powerful interactivity for the viewer but is significantly slower than the Flot version.

-

2017 Oct. 11 Provide clear error messages for scalar/vector errors.

-

2017 Sept. 7 Make it again possible to put pause() etc. inside functions.

-

2017 July 31: GlowScript 2.6
- Significant fixes to cloning and to the 3D text object. Adam Thompson implemented being able to resize a canvas, either by resetting width and/or height, or by user dragging. Andrew Morrison improved graph xtitle and ytitle to appear below and to the left of the graph rather than above the graph. GlowScript 2.6 incorporates an update by Kovid Goyal to RapydScript-NG to support class variables (that is, variables that are shared by all instances of the class).

-

2017 June 11: GlowScript 2.5
- Fix a bug in extrusion object that removed the last element in a user-supplied shape. The version number had to be incremented to 2.5 because some existing 2.4 programs might fail.

-

2017 Feb. 2: GlowScript 2.4
- Fix a long-standing error in changing axis without updating up to remain perpendicular to axis (and vice versa). The result was that rotating an object by continually changing its axis could cause abrupt changes in the appearance of the object which were only noticeable if there was a texture or a compound object that lacked symmetry.

-

2017 Jan. 4: GlowScript 2.3
- Replaced the original RapydScript Python-to-JavaScript compiler with RapydScript-NG by Kovid Goyal, which comes closer to supporting true Python syntax and also provides Python string methods such as lower() and upper() and split().

-

2016 Nov. 12: GlowScript 2.2
- Improved extrusion and compound objects. They now have pos at their centers and size that represents the bounding box. The extrusion path is now specified by "path", making it possible to specify "pos" as the location of the center of the extrusion's bounding box.

-

 

-

2016 Aug. 22: Much more powerful version of the extrusion object, with full shapes and paths libraries. Also added text to radio buttons and check boxes.

-

2016 Aug. 4: Widgets implemented -- button, radio button, check box, slider, and drop-down menu.

-

2016 July 2: 3D text object implemented, with major contributions by Kadir Haldenbilen.

-

 

-

2016 Feb. 28: GlowScript 2.1
- Improves and simplifies scene.title and scene.caption. Now you can say scene.title = "Watch the <b>ball</b>" ("ball" will be bold) and scene.caption = "This is what <i>always</i> happens" ("always" will be italic). You can also obtain the current contents for the title (T = scene.title) and caption (C = scene.caption). You can add to existing title or caption with scene.append_to_title(...) or scene.append_to_caption(...).

-

The old forms scene.title.text() and scene.title.html() could be used to specify the title but there wasn't a way to retrieve the current title. You had to decide between text and html, but now it doesn't matter; you always get full HTML capabilities.

-

These changes are not fully compatible with previous versions of GlowScript, which is why the version number has been changed to 2.1, but older versions will continue to work as before. Another reason for the changes has to do with making the Jupyter version of VPython work well.

-

Changes to the use of jQuery: If you use jQuery to display widgets (buttons, sliders, menus), see this documentation on changes to how to reference the title, caption, and print regions of the page.

-

2016 Jan. 24: GlowScript 2.0
- * Fixes a serious problem in make_trail, that long trails were very slow. New trail-related features: trail_color, trail_radius, pps (points per second), clear() which deletes existing points. Setting make_trail False stops leaving a trail; setting make_trail True turns the trail on again, without drawing an undesirable line between the stop and start points.
-
- * -If v is a vector, v.mag() must now be written as v.mag and v.mag2() must now be written as v.mag2. The older form was a mistake and is incompatible with the new Jupyter version of VPython.
-
-* display should be written as canvas; gdisplay as graph. The older names still work at present but are incompatible with the new Jupyter version of VPython.
-
-* The list of positions in a curve named c cannot be referenced directly as c.pos. If the curve is named c and N is the nth point in the curve, c.point(N) returns {pos:p, color:col, radius:r, visible:v}. To change the nth point, use c.modify(N, pos=p, color=col, radius=r, visible=v). See the documentation for the curve object for the full list of methods available for accessing or changing an existing curve.
-
-* - The points object has a radius, not a size (size was a scalar and confusing given that size is a vector elsewhere; size_units can still be used to specify whether the radius is in pixels or real-world measure).
-
- * Because it is hardly being used, CoffeeScript is not supported in GlowScript 2.0. It can still be used with "GlowScript 1.1 CoffeeScript". -
-
- * Here is a description of the plan for future development of VPython.

+

Log of major developments

+
+
+

This information has been moved to a new article.

 

-

2015 Dec. 21: Update of files that permit operator overloading (being able to add two vectors a and b simply as a+b) and the ability to use synchronous code (such as infinite loops) thanks to files supplied by Salvatore di Dio. Changes to Firefox made this update necessary. An added bonus was that GlowScript now runs on Internet Explorer and Edge.

-

2015 Oct. 18: Implement display.delete(), gdisplay.delete(), and the ability to delete a set of data from a graph. Add to the make_trail machinery the ability to set trail_color and trail_radius without having to reference trail_object.

-

2015 Oct. 15: scene.mouse.pos now always contains the up-to-date mouse information, which makes it possible to drag objects with the mouse buttons up.

-

2015 Sept. 19: Implement the standard Python string.format mechanism.

-

2015 August 27: Improve sphere and curve rendering; provide textures.earth.

-

2015 August 2: Implement simple editor as alternative to the ACE editor, so that it is now possible to edit programs on mobile devices.

-

2015 June 23: Implement Python-style string formatting.

-

2015 June 3: Ring is now a regular primitive and supports transparency.

-

2015 April 21: Add factorial and combin functions.

-

2015 Feb. 22: Enable transparency on mobile devices.

-

2015 Jan. 20: Support touch inputs on touch-sensitive devices.

-

2014 November 17: Updated GlowScript 1.1 to fix a problem with JavaScript programs. This also introduces the ability to handle programs written in classic VPython, with some restrictions; see the VPython Help. There are new vector capabilities such as dot(A,B), equivalent to A.dot(B). The curve object now has an attribute "origin" for moving the entire curve, relative to this origin.

-

2014 October 25: Released GlowScript 1.1. Support added for RapydScript, a Python look-alike, with much help from Alexander Tsepkov, Charles Law, and Salvatore di Dio. CoffeScript compiler updated, which among other things means that 3**4 now equals 81. Also, jquery and jquery-ui updated thanks to the work of Adam Thompson, who also added the ability to place print output to the right of the canvas and improved resizing of a canvas.

-

2012 October 10: Textures can now use images from other ("CORS-enabled") web sites. GlowScript programs run well on the latest version of Firefox for Android (smartphones and tablets), though you can't yet rotate the camera, and transparency is buggy.

-

2012 September 12: Add functions compound_to_world, world_to_compound, pixel_to_world, print, print_options, get_library, and read_local_file. Improve rate behavior for high rate values.

-

2012 August 21: Updated Version 1.0 to improve error reporting for both JavaScript and CoffeeScript programs, and to improve editing of CoffeeScript programs. Added to the Help sections on text output for debugging, and how to run GlowScript in the absence of an internet connection.

-

2012 May 30: Version 1.0 implements triangles and quads, based on vertex objects, which make it possible to design your own objects and even change their shape dynamically. Also new are compound (groups of objects that can be manipulated as though they were one object) and clone (make a copy of an existing object). David Scherer made major contributions to the design of these new features. Also, the curve object now permits rapid change of position, size, and orientation, and the array scene.objects now includes label objects.

-

2012 April 21: Now in version 0.7 you can write your program in CoffeeScript as well as in JavaScript. See the home page for details.

-

2012 March 27: Transparency added to version 0.7. You can set the opacity of an object, with default = 1 (fully opaque); 0 is completely transparent.

-

2012 Jan. 29: Release GlowScript version 0.7. The major new capability is textures, including bump maps (normal maps), for objects other than curves (and the curve-like objects helix and ring). Other new features include shininess, emissive, and scene.visible. Changes were made to require named arguments for object.rotate, vector.rotate, local and distant lights, and scene.mouse.project. Improved glowscript.org front page thanks to Tim Sherwood.

-

May/June 2011: David Scherer and Bruce Sherwood begin collaborating on implementing GlowScript, patterned on VPython but running in a web browser, exploiting the the new JavaScript/WebGL environment.

+
+
-

Top of page

- - - + \ No newline at end of file diff --git a/docs/GlowScriptDocs/images/MathJax.jpg b/docs/GlowScriptDocs/images/MathJax.jpg deleted file mode 100644 index a5879c59..00000000 Binary files a/docs/GlowScriptDocs/images/MathJax.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/VisualRef-4.gif b/docs/GlowScriptDocs/images/VisualRef-4.gif deleted file mode 100644 index 5a9abe1a..00000000 Binary files a/docs/GlowScriptDocs/images/VisualRef-4.gif and /dev/null differ diff --git a/docs/GlowScriptDocs/images/VisualRef-7.gif b/docs/GlowScriptDocs/images/VisualRef-7.gif deleted file mode 100644 index 4ae24efc..00000000 Binary files a/docs/GlowScriptDocs/images/VisualRef-7.gif and /dev/null differ diff --git a/docs/GlowScriptDocs/images/arc.jpg b/docs/GlowScriptDocs/images/arc.jpg deleted file mode 100644 index 55e4863f..00000000 Binary files a/docs/GlowScriptDocs/images/arc.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/arc_and_triangle_with_hole.jpg b/docs/GlowScriptDocs/images/arc_and_triangle_with_hole.jpg deleted file mode 100644 index 10287471..00000000 Binary files a/docs/GlowScriptDocs/images/arc_and_triangle_with_hole.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/arc_shape.jpg b/docs/GlowScriptDocs/images/arc_shape.jpg deleted file mode 100644 index 6e833d5e..00000000 Binary files a/docs/GlowScriptDocs/images/arc_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/arrow.jpg b/docs/GlowScriptDocs/images/arrow.jpg deleted file mode 100644 index 533387dc..00000000 Binary files a/docs/GlowScriptDocs/images/arrow.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/arrow_info.jpg b/docs/GlowScriptDocs/images/arrow_info.jpg deleted file mode 100644 index d07adb5f..00000000 Binary files a/docs/GlowScriptDocs/images/arrow_info.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/box.jpg b/docs/GlowScriptDocs/images/box.jpg deleted file mode 100644 index 8c70dd86..00000000 Binary files a/docs/GlowScriptDocs/images/box.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/box_axis_up.png b/docs/GlowScriptDocs/images/box_axis_up.png deleted file mode 100644 index db4c987f..00000000 Binary files a/docs/GlowScriptDocs/images/box_axis_up.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/box_info1.jpg b/docs/GlowScriptDocs/images/box_info1.jpg deleted file mode 100644 index e2bc9a20..00000000 Binary files a/docs/GlowScriptDocs/images/box_info1.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/box_info2.jpg b/docs/GlowScriptDocs/images/box_info2.jpg deleted file mode 100644 index a41eee57..00000000 Binary files a/docs/GlowScriptDocs/images/box_info2.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/camera.png b/docs/GlowScriptDocs/images/camera.png deleted file mode 100644 index 5e7d39f5..00000000 Binary files a/docs/GlowScriptDocs/images/camera.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/camera2.png b/docs/GlowScriptDocs/images/camera2.png deleted file mode 100644 index e60c60c2..00000000 Binary files a/docs/GlowScriptDocs/images/camera2.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/circle.jpg b/docs/GlowScriptDocs/images/circle.jpg deleted file mode 100644 index 90627012..00000000 Binary files a/docs/GlowScriptDocs/images/circle.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/circle_frame.jpg b/docs/GlowScriptDocs/images/circle_frame.jpg deleted file mode 100644 index 35c35e75..00000000 Binary files a/docs/GlowScriptDocs/images/circle_frame.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/circle_shape.jpg b/docs/GlowScriptDocs/images/circle_shape.jpg deleted file mode 100644 index d18cf2c1..00000000 Binary files a/docs/GlowScriptDocs/images/circle_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/clone.jpg b/docs/GlowScriptDocs/images/clone.jpg deleted file mode 100644 index 08477bb7..00000000 Binary files a/docs/GlowScriptDocs/images/clone.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/colors_abutting.png b/docs/GlowScriptDocs/images/colors_abutting.png deleted file mode 100644 index a5c17992..00000000 Binary files a/docs/GlowScriptDocs/images/colors_abutting.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/compound.jpg b/docs/GlowScriptDocs/images/compound.jpg deleted file mode 100644 index d5c0cddb..00000000 Binary files a/docs/GlowScriptDocs/images/compound.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/cone.jpg b/docs/GlowScriptDocs/images/cone.jpg deleted file mode 100644 index f7ce132d..00000000 Binary files a/docs/GlowScriptDocs/images/cone.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/cone_info.jpg b/docs/GlowScriptDocs/images/cone_info.jpg deleted file mode 100644 index 91ffcd44..00000000 Binary files a/docs/GlowScriptDocs/images/cone_info.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/controls.jpg b/docs/GlowScriptDocs/images/controls.jpg deleted file mode 100644 index 1141a20d..00000000 Binary files a/docs/GlowScriptDocs/images/controls.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/cross.jpg b/docs/GlowScriptDocs/images/cross.jpg deleted file mode 100644 index d326d459..00000000 Binary files a/docs/GlowScriptDocs/images/cross.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/cross_ellipse.jpg b/docs/GlowScriptDocs/images/cross_ellipse.jpg deleted file mode 100644 index ad03e908..00000000 Binary files a/docs/GlowScriptDocs/images/cross_ellipse.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/cross_shape.jpg b/docs/GlowScriptDocs/images/cross_shape.jpg deleted file mode 100644 index 91749571..00000000 Binary files a/docs/GlowScriptDocs/images/cross_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/curve.jpg b/docs/GlowScriptDocs/images/curve.jpg deleted file mode 100644 index 2156c90b..00000000 Binary files a/docs/GlowScriptDocs/images/curve.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/curve_append.png b/docs/GlowScriptDocs/images/curve_append.png deleted file mode 100644 index b4ced81b..00000000 Binary files a/docs/GlowScriptDocs/images/curve_append.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/cylinder.jpg b/docs/GlowScriptDocs/images/cylinder.jpg deleted file mode 100644 index 89750c21..00000000 Binary files a/docs/GlowScriptDocs/images/cylinder.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/cylinder_info.jpg b/docs/GlowScriptDocs/images/cylinder_info.jpg deleted file mode 100644 index e830c95e..00000000 Binary files a/docs/GlowScriptDocs/images/cylinder_info.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/ellipse.jpg b/docs/GlowScriptDocs/images/ellipse.jpg deleted file mode 100644 index ae98c33d..00000000 Binary files a/docs/GlowScriptDocs/images/ellipse.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/ellipse_shape.jpg b/docs/GlowScriptDocs/images/ellipse_shape.jpg deleted file mode 100644 index 39213c64..00000000 Binary files a/docs/GlowScriptDocs/images/ellipse_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/extrusion.PNG b/docs/GlowScriptDocs/images/extrusion.PNG deleted file mode 100644 index 96cab8b6..00000000 Binary files a/docs/GlowScriptDocs/images/extrusion.PNG and /dev/null differ diff --git a/docs/GlowScriptDocs/images/filedialog.jpg b/docs/GlowScriptDocs/images/filedialog.jpg deleted file mode 100644 index a1c41025..00000000 Binary files a/docs/GlowScriptDocs/images/filedialog.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/gear.jpg b/docs/GlowScriptDocs/images/gear.jpg deleted file mode 100644 index 6de5bb0a..00000000 Binary files a/docs/GlowScriptDocs/images/gear.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/graph.jpg b/docs/GlowScriptDocs/images/graph.jpg deleted file mode 100644 index 03cd0428..00000000 Binary files a/docs/GlowScriptDocs/images/graph.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/gyro2.jpg b/docs/GlowScriptDocs/images/gyro2.jpg deleted file mode 100644 index ea63584a..00000000 Binary files a/docs/GlowScriptDocs/images/gyro2.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/helix.jpg b/docs/GlowScriptDocs/images/helix.jpg deleted file mode 100644 index 048f0fd0..00000000 Binary files a/docs/GlowScriptDocs/images/helix.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/heptagon.jpg b/docs/GlowScriptDocs/images/heptagon.jpg deleted file mode 100644 index 87a0a67c..00000000 Binary files a/docs/GlowScriptDocs/images/heptagon.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/hexagon.jpg b/docs/GlowScriptDocs/images/hexagon.jpg deleted file mode 100644 index 76a9f636..00000000 Binary files a/docs/GlowScriptDocs/images/hexagon.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/hexagon_shape.jpg b/docs/GlowScriptDocs/images/hexagon_shape.jpg deleted file mode 100644 index 0228243c..00000000 Binary files a/docs/GlowScriptDocs/images/hexagon_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/label.jpg b/docs/GlowScriptDocs/images/label.jpg deleted file mode 100644 index 45fcde23..00000000 Binary files a/docs/GlowScriptDocs/images/label.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/label2.png b/docs/GlowScriptDocs/images/label2.png deleted file mode 100644 index a49ad1dc..00000000 Binary files a/docs/GlowScriptDocs/images/label2.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/material_etc.jpg b/docs/GlowScriptDocs/images/material_etc.jpg deleted file mode 100644 index eda69524..00000000 Binary files a/docs/GlowScriptDocs/images/material_etc.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/mesh.jpg b/docs/GlowScriptDocs/images/mesh.jpg deleted file mode 100644 index 60009dbc..00000000 Binary files a/docs/GlowScriptDocs/images/mesh.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/newtext3d.png b/docs/GlowScriptDocs/images/newtext3d.png deleted file mode 100644 index b6dd9e54..00000000 Binary files a/docs/GlowScriptDocs/images/newtext3d.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/ngon_shape.jpg b/docs/GlowScriptDocs/images/ngon_shape.jpg deleted file mode 100644 index 36825b23..00000000 Binary files a/docs/GlowScriptDocs/images/ngon_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/partial_circle_shape.jpg b/docs/GlowScriptDocs/images/partial_circle_shape.jpg deleted file mode 100644 index c25affb7..00000000 Binary files a/docs/GlowScriptDocs/images/partial_circle_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/pentagon.jpg b/docs/GlowScriptDocs/images/pentagon.jpg deleted file mode 100644 index d316d457..00000000 Binary files a/docs/GlowScriptDocs/images/pentagon.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/pentagon_shape.jpg b/docs/GlowScriptDocs/images/pentagon_shape.jpg deleted file mode 100644 index afbe1b69..00000000 Binary files a/docs/GlowScriptDocs/images/pentagon_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/points.jpg b/docs/GlowScriptDocs/images/points.jpg deleted file mode 100644 index 979674fb..00000000 Binary files a/docs/GlowScriptDocs/images/points.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/pyramid.jpg b/docs/GlowScriptDocs/images/pyramid.jpg deleted file mode 100644 index 1d46928e..00000000 Binary files a/docs/GlowScriptDocs/images/pyramid.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rackgear.jpg b/docs/GlowScriptDocs/images/rackgear.jpg deleted file mode 100644 index ff7c7bb2..00000000 Binary files a/docs/GlowScriptDocs/images/rackgear.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle.jpg b/docs/GlowScriptDocs/images/rectangle.jpg deleted file mode 100644 index 6fd0a21f..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_chamfered.jpg b/docs/GlowScriptDocs/images/rectangle_chamfered.jpg deleted file mode 100644 index 9aa2d02d..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_chamfered.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_rotated.jpg b/docs/GlowScriptDocs/images/rectangle_rotated.jpg deleted file mode 100644 index 3d323c5c..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_rotated.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_rounded.jpg b/docs/GlowScriptDocs/images/rectangle_rounded.jpg deleted file mode 100644 index ebbf6938..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_rounded.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_shape.jpg b/docs/GlowScriptDocs/images/rectangle_shape.jpg deleted file mode 100644 index 669c1f06..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_shape_chamfered.jpg b/docs/GlowScriptDocs/images/rectangle_shape_chamfered.jpg deleted file mode 100644 index 4737c8f5..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_shape_chamfered.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_shape_frame.jpg b/docs/GlowScriptDocs/images/rectangle_shape_frame.jpg deleted file mode 100644 index 1f13d643..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_shape_frame.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_shape_rotated.jpg b/docs/GlowScriptDocs/images/rectangle_shape_rotated.jpg deleted file mode 100644 index 2ca4e5ff..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_shape_rotated.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/rectangle_shape_rounded.jpg b/docs/GlowScriptDocs/images/rectangle_shape_rounded.jpg deleted file mode 100644 index 0d22755f..00000000 Binary files a/docs/GlowScriptDocs/images/rectangle_shape_rounded.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/ring.jpg b/docs/GlowScriptDocs/images/ring.jpg deleted file mode 100644 index 4b48061a..00000000 Binary files a/docs/GlowScriptDocs/images/ring.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/sphere.jpg b/docs/GlowScriptDocs/images/sphere.jpg deleted file mode 100644 index 89120d1e..00000000 Binary files a/docs/GlowScriptDocs/images/sphere.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/star.jpg b/docs/GlowScriptDocs/images/star.jpg deleted file mode 100644 index 091736c6..00000000 Binary files a/docs/GlowScriptDocs/images/star.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/star_shape.jpg b/docs/GlowScriptDocs/images/star_shape.jpg deleted file mode 100644 index bcae8aba..00000000 Binary files a/docs/GlowScriptDocs/images/star_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/star_with_hole.jpg b/docs/GlowScriptDocs/images/star_with_hole.jpg deleted file mode 100644 index ba94453e..00000000 Binary files a/docs/GlowScriptDocs/images/star_with_hole.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/stonehenge.jpg b/docs/GlowScriptDocs/images/stonehenge.jpg deleted file mode 100644 index 7ddaf556..00000000 Binary files a/docs/GlowScriptDocs/images/stonehenge.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/text3d.jpg b/docs/GlowScriptDocs/images/text3d.jpg deleted file mode 100644 index 8e908943..00000000 Binary files a/docs/GlowScriptDocs/images/text3d.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/text3d.png b/docs/GlowScriptDocs/images/text3d.png deleted file mode 100644 index 61254509..00000000 Binary files a/docs/GlowScriptDocs/images/text3d.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/texture.jpg b/docs/GlowScriptDocs/images/texture.jpg deleted file mode 100644 index 45ef8704..00000000 Binary files a/docs/GlowScriptDocs/images/texture.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/trail.png b/docs/GlowScriptDocs/images/trail.png deleted file mode 100644 index 13c1eafc..00000000 Binary files a/docs/GlowScriptDocs/images/trail.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/trapezoid.jpg b/docs/GlowScriptDocs/images/trapezoid.jpg deleted file mode 100644 index 6c0e28d4..00000000 Binary files a/docs/GlowScriptDocs/images/trapezoid.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/trapezoid_shape.jpg b/docs/GlowScriptDocs/images/trapezoid_shape.jpg deleted file mode 100644 index 6f148ae4..00000000 Binary files a/docs/GlowScriptDocs/images/trapezoid_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle.jpg b/docs/GlowScriptDocs/images/triangle.jpg deleted file mode 100644 index 08fe2a15..00000000 Binary files a/docs/GlowScriptDocs/images/triangle.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle.png b/docs/GlowScriptDocs/images/triangle.png deleted file mode 100644 index c0bd6589..00000000 Binary files a/docs/GlowScriptDocs/images/triangle.png and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle_circular_hole.jpg b/docs/GlowScriptDocs/images/triangle_circular_hole.jpg deleted file mode 100644 index 26e14362..00000000 Binary files a/docs/GlowScriptDocs/images/triangle_circular_hole.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle_frame.jpg b/docs/GlowScriptDocs/images/triangle_frame.jpg deleted file mode 100644 index 79d3186c..00000000 Binary files a/docs/GlowScriptDocs/images/triangle_frame.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle_path.jpg b/docs/GlowScriptDocs/images/triangle_path.jpg deleted file mode 100644 index 73d9ff36..00000000 Binary files a/docs/GlowScriptDocs/images/triangle_path.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle_shape.jpg b/docs/GlowScriptDocs/images/triangle_shape.jpg deleted file mode 100644 index 5248afe5..00000000 Binary files a/docs/GlowScriptDocs/images/triangle_shape.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle_with_hole.jpg b/docs/GlowScriptDocs/images/triangle_with_hole.jpg deleted file mode 100644 index 3c969a5e..00000000 Binary files a/docs/GlowScriptDocs/images/triangle_with_hole.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangle_with_hole2.jpg b/docs/GlowScriptDocs/images/triangle_with_hole2.jpg deleted file mode 100644 index 0669bd7e..00000000 Binary files a/docs/GlowScriptDocs/images/triangle_with_hole2.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/images/triangular_ring.jpg b/docs/GlowScriptDocs/images/triangular_ring.jpg deleted file mode 100644 index 21d4f5d0..00000000 Binary files a/docs/GlowScriptDocs/images/triangular_ring.jpg and /dev/null differ diff --git a/docs/GlowScriptDocs/index.html b/docs/GlowScriptDocs/index.html deleted file mode 100644 index aa5d5c06..00000000 --- a/docs/GlowScriptDocs/index.html +++ /dev/null @@ -1,273 +0,0 @@ - - - -overview - - - - - - - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - -

GlowScript

-

3D animations in a browser

-

RapydScript and JavaScript

box
-

This is older documentation from before it was possible to write GlowScript programs in Python. You probably want VPython Help.

-

 

-

Choose from the menus above for documentation of GlowScript.
- Read the material below to understand the GlowScript context.

-
-

-

GlowScript ("Graphics Library on Web") makes it easy to write real-time navigable 3D animations that run in a browser. It is based on the JavaScript language plus the WebGL 3D graphics library, both of which are included in most modern browsers. Programs can be written in JavaScript or RapydScript, or they can use VPython syntax.

-

The design of GlowScript is based on that of VPython. Development of GlowScript was initiated by David Scherer and Bruce Sherwood - - in the summer of 2011. Here is an overview of the project, and here is a log of developments. Here is the open source for this project. Some technical overviews are available.

-

Descriptions of the options available at the top of the page:

-
-

Pictures of 3D objects: What - the objects look like

-

Choose a 3D object (use the pull-down menu above): Details of cylinder, box, etc. Start with cylinder for an overview.

-

Work with 3D objects (use the pull-down menu above): Issues that apply to all 3D objects: color, rotations, etc.

-

Canvases/Events (use the pull-down menu above): Creating - one or more canvases within which to show 3D animations; how to handle mouse events; etc.

-
-

Be sure to explore the many example programs that are available.

-
-
-

-
-
-

Using the GlowScript editor

-
-
-
-

GlowScript uses the ACE text editor. Here is a list of keyboard shortcuts for find, replace, etc. While editing, press Ctrl-1 to run your program in the same window. Press Ctrl-2 to run your program in a separate window, which can be convenient for comparing the program with its behavior. If you change your program, press Ctrl-2 again in the editor display to re-run the program with the new changes. Because ACE doesn't work on mobile devices, a simpler editor is used there.

-

A simple program: In the editor, after the GlowScript header, enter the statement "sphere()" and choose "Run this program". You should see a 3D sphere. Read the Help discussions on cylinder and box objects to learn how to customize 3D objects (position, color, size, etc.).

-

Rotate and zoom: You can rotate and zoom the camera using the mouse; for instructions, see the Example program AtomicSolid.

-

Errors and debugging: If you are using JavaScript, watch for little yellow triangles or red squares to the left of a program statement and move the mouse over the icon. You'll see a message describing an error with that line. (This capability is not yet active for VPython or RapydScript.) When you run the program you may see other error messages. Only with the Chrome or Edge browser is it usually possible for GlowScript to display the line number of the error, so when developing programs it is strongly advised to use Chrome or Edge. Some program errors are reported only to the "console". To enable the console, in Chrome or Edge, press shift-ctrl-j on Windows or Ubuntu, or option-cmd-j on Mac. In Firefox, on Windows choose Firefox > Web Developer > Web Console, and on Ubuntu choose Tools > Web Developer > Web Console. The output will be found at the end of the console output

-

When developing a program it can be very useful to comment out a block of code temporarily. Here is how to do this in the three languages:

-

# VPython or RapydScript (can also use '''):
- """
- a = 5
- b = 3
- """
-
- // JavaScript:
- /*
- var a = 5
- var b = 3
- */

-

 

-
-
-

Browsers that support GlowScript

-
-
-
-
-
-

GlowScript uses the WebGL 3D graphics library that is included in current versions of major web browsers. You must have a modern graphics card with Graphics Processing Units (GPUs). Here are browser details:

-

Chrome, Edge, Firefox, Safari,and Edge all support WebGL and GlowScript.

-

Tablets and smart phones: Most tablets and smart phones support WebGL and GlowScript, both Android and iOS.

-

Testing: If things don't work, it may be useful to visit get.webgl.org which checks whether WebGL is working properly on your computer. Also, here is a repository of WebGL demo programs, where it may be useful to see whether these programs will run on your computer.

-

RapydScript, a Python look-alike

-

Because the design of GlowScript is based on that of VPython, and to facilitate moving programs between GlowScript and VPython, GlowScript makes it possible to write GlowScript programs in RapydScript, a programming language that is very simiilar to Python but programs written in RapydScript can run in a browser.

-

For many kinds of programs RapydScript is identical to Python, but there are some differences due to the desire of the RapydScript designers to maintain high performance in the browser environment, where RapydScript programs are compiled to JavaScript, the underlying browser language. Thanks to its careful design, RapydScript programs run as fast as JavaScript programs but with simpler, cleaner syntax. RapydScript gives you easy access to the growing capabilities of JavaScript and its many libraries.

-

This GlowScript documentation emphasizes RapydScript syntax but also describes how to use JavaScript to create 3D animations. Excellent documentation on the differences between RapydScript and Python is available at RapydScript.

-

VPython

-

You can write programs using the syntax of VPython, or to run many existing VPython programs. The VPython Help documents this syntax for the GlowScript context. The VPython Help also includes a Python program that can convert an existing VPython program to a form that will run in the GlowScript browser environment.

-

When you create a new program, a header line is inserted that looks like this:

-

GlowScript 2.7 VPython

-

You can change "VPython" to "RapydScript" if you want to use one of these other language options. After making such a change, replot the browser page. You don't need to capitalize these language names: you can also use "vpython", "rapydscript", "javascript".

-

If you are new to programming or to RapydScript/Python, you'll find the Python tutorials at www.codecademy.com very helpful

-

JavaScript
-

-

You may choose to write GlowScript programs in JavaScript, the programming language that is built into browsers. Despite its name, JavaScript is not related to the Java programming language. If you are new to programming, or just new to JavaScript, you'll find the JavaScript tutorials at www.codecademy.com very helpful.

-

There are also helpful interactive tutorials on JavaScript available at www.w3schools.com/js. However, these tutorials assume quite a lot of prior knowledge about html and related web design issues.

-

An excellent, up to date textbook on JavaScript is available at javascript.info.

-

Reference materials are found at developer.mozilla.org/en/JavaScript.

-
-

Use var: When using JavaScript in the GlowScript environment, it is obligatory to specify that you are introducing new JavaScript variables of your own before you start using them:

-
-

var x, y
- x - = 5
- y = 3

-
-
-
-

You can initialize new variables at the same time that you introduce them:

-
-

var x = 5, y = 3

-

To invoke JavaScript, change the GlowScript header line:

-

GlowScript 2.7 JavaScript

-

You need not use upper-case letters; "javascript" will also work. After making such a change, replot the browser page. If no language is specified following "GlowScript 1.1" the language is JavaScript.

-

Post to the GlowScript Forum or write to - - if you - don't find what you need, or to tell us how you are using GlowScript. To prevent spam, your first post will be reviewed before becoming public.

-

Using the GlowScript libraries

-

It is possible for knowledgeable programmers to use the GlowScript libraries in their own JavaScript programs. Here are details.

-

Running locally

-

It is possible to use GlowScript locally, without an internet connection, though you will need to copy and paste your programs to glowscript.org if you want them stored in the cloud. Here are the instructions.

-

Versions

-

The text editor automatically inserts a header of the form "GlowScript X.Y VPython" at the start of every new program, where X.Y is the current version number. If future development of GlowScript should cause incompatibilities with earlier versions, old programs will be run with old versions of GlowScript, thereby ensuring to the extent possible that all programs will continue to work as they did originally. The "version" variable provides information about the version number:

-

version is ['X.Y', 'glowscript']

-

Technical issue with execution speed

-

In order to make it possible to add and subtract 3D vectors, and to be able to multiple or divide a vector by a scalar, all add, subtract, multiply, and divide operations are converted into function calls. If you have a critical function that needs to run as fast as possible, use the following vector operations, where A and B are vectors and k is an ordinary number:

-

A+B -> A.add(B)
- A-B -> A.sub(B)
- k*A -> A.multiply(k)
- A/k -> A.divide(k)

-

The Example program SurfaceCharge uses this technique in the Efield function. Here is one of the expressions in that function (divided across two lines to fit into this web page):

-

E.add(norm(r).divide(mag2(r)).
-                        multiply(qs[i]))

-

This corresponds to the following expression:

-

E+qs[i]*norm(r)/mag2(r)

-

For users of VPython

-

See this comparison of VPython and GlowScript.

-

 

-

CoffeeScript
-

-

You may choose to write GlowScript programs in CoffeeScript, which is an alternative to JavaScript. It has a simpler, cleaner syntax, yet it is in a sense just JavaScript, because it gets converted to standard JavaScript, while in the process avoiding various flaws in JavaScript. CoffeeScript has some similarities to RapydScript (and therefore to Python), but it is mainly suitable for those who already have significant JavaScript experience.

-

To invoke CoffeeScript with GlowScript 1.0 or 1.1, just add CoffeeScript to the GlowScript header:

-

GlowScript 1.1 CoffeeScript

-

You need not use upper-case letters; "coffeescript" will also work. After making such a change, replot the browser page. CoffeeScript is not available in GlowScript 2.0 or later, due to there being very little use of it now that VPython is available.

-

Conversion from JavaScript: There exists a JavaScript-to-CoffeeScript converter at js2coffee.org (don't include the initial "GlowScript" statement when using this converter). In the GlowScript example programs are some programs that have been converted using the js2coffee.org tool. See the folder "Examples-RapydScript".

-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/label.html b/docs/GlowScriptDocs/label.html deleted file mode 100644 index 047b5171..00000000 --- a/docs/GlowScriptDocs/label.html +++ /dev/null @@ -1,132 +0,0 @@ - - - -label - - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - - -
label
label
-

With the label object you can display text in - a box, and the label always faces forward, even if you rotate the - scene (for 3D text, see the text object). Here is a simple example:

- -

label( pos=vec(0,0.25,0), text='Hello!' ) - - - - - -

There are many additional - label options. In the diagram to the right, an object located at "obj.pos" has an associated - label with the text "Early" in a box, connected to the object.

-

L = label(pos=obj.pos,
-    text='Early',     xoffset=20,
-    yoffset=50, space=30,
-    height=16, border=4,
-    font='sans')

-

A unique feature of the label object is that several attributes - are given in terms of screen pixels instead of the usual "world-space" - coordinates. For example, the height of the text is given in pixels, with - the result that the text remains readable even when the sphere object is - moved far away. Other pixel-oriented attributes include xoffset, yoffset, and border. - Here are the label attributes:

label
-

pos The - point in world space being labeled.

-

pixel_pos If True, pos is the position in terms of pixels, with vec(0,0,0) in the lower left corner.

-

align Specify 'left', 'right', or 'center'. When you specify 'center', which is the default, the center of the topmost line of text is at the location given by pos. When you specify 'left', the start of the topmost line of text is at the location given by pos. When you specify 'right', the right end of the topmost line of text is at the location given by pos.

-

xoffset, yoffset The - x and y components of the line, in pixels (see diagram). Unless you specify a value for align, text above or below pos is centered, text to the left of pos is right-adjusted, and text to the right of pos is left-adjusted.

-

text The text to be - displayed, such as 'Earth'. - You can give a number or numerical expression; it will be converted to a string.You can includes the HTML styles for italic (<i> or <em>), bold (<b> or <strong>), superscript (<sup>), or subscript (<sub>). For example, the string
-     'The <b>mass <i>M</i></b><sub>sys</sub> = 10<sup>3</sup> kg.
-displays as
-    'The mass Msys = 103 kg.
-
-Multiple lines can be displayed by inserting line breaks (\n), as in "Three\nlines\nof - text" and you can insert <br> or <br/> instead of \n.

-

font Name of the desired - font; 'sans' or 'serif'' or 'monospace' (fixed-width), or a specific font name

-

height Height - of the font in pixels; default is 15 pixels

-

color Color of the text; default is white unless scene.background is white, in which case the default is black

-

background Color of the background of the box; default is scene.background

-

opacity Opacity of the background of the box, default 0.66
- (0 transparent, 1 opaque, for objects behind the box)

-

border Distance - in pixels from the text to the surrounding box; default is 5 pixels

-

box True if the box should - be drawn (default), else False

-

line true if the line from - the box to pos should be drawn (default), else false

-

linecolor Color of the line - and box; default is white unless scene.background is white, in which case the default is black; if the label's color is specified, the default linecolor is the same

-

linewidth The width in pixels of the line and box

-

space Radius - in real-world coordinates of a sphere surrounding pos, into which the connecting line does not go.

-

visible Label is not displayed if False

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. -canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/libraryuse.html b/docs/GlowScriptDocs/libraryuse.html deleted file mode 100644 index bca04c6c..00000000 --- a/docs/GlowScriptDocs/libraryuse.html +++ /dev/null @@ -1,134 +0,0 @@ - - - -library use - - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - -
Using GlowScript
- as a JavaScript library -
-

By far the *easiest* way to embed a glowscript program in your web page is to edit it at glowscript.org and then use the "Share" feature to get HTML source, which can be inserted into your own web page. This is easiest because the glowscript.org environment applies a number of transformations of GlowScript programs to add operator overloading for vectors and the ability to write infinite loops and yet update the window.

-

A knowledgable JavaScript programmer should be able to make use of the 'glow' JavaScript library directly, and this could make sense for some purposes.  One would have to write a tiny bit of initialization boilerplate to create a canvas, and one would have to write in pure JavaScript, without operator overloading and with function callbacks. The program must not include options such as rate or waitfor, and the following vector operations must be rewritten as shown, where A and B are vectors and k is an ordinary number:

-

A+B -> A.add(B)
- A-B -> A.sub(B)
- k*A -> A.multiply(k)
- A/k -> A.divide(k)

-

Here is a minimal working example HTML file. If you copy the program from here, be sure to delete the new line and extra spaces in the http strings.

-

<div id="glowscript" class="glowscript">
- <script type="text/javascript"        src="https://s3.amazonaws.com/glowscript/lib/
-            jquery/2.1/jquery.min.js"></script>
-
-<script type="text/javascript"        src="https://s3.amazonaws.com/glowscript/lib/
-            jquery/2.1/jquery-ui.custom.min.js"></script>
- <script type="text/javascript"        src="https://s3.amazonaws.com/glowscript/package/
-             glow.2.7.min.js"></script>
-
- <script type="text/javascript">
-        window.__context = { glowscript_container:        $("#glowscript").removeAttr("id") }
-
- var scene = canvas()
- var b = box()
-
- function spin() {
-   b.rotate({angle:0.01, axis:vec(0,1,0)})
-   rate(100, spin) // make spin a callback
-}
-
-spin()
-
-</script>
-</div>

-

Additional considerations

-

As in the use of the rate function in the example above, you need to use your own callback function to be called when the condition is met. For example, scene.waitfor('click) blocks, waiting for the user to click before executing the following statement. You can instead establish a callback function to be executed when the user clicks, as is illustrated by the use of scene.bind for handling keyboard and mouse events.

-

The function read_local_file() can be used in two ways, as shown below. The first form blocks, waiting for the user to choose a file before the following statement is executed. This blocking form is not available without using the preprocessing available at glowscript.org.

-

The second form establishes a callback function which will be executed when the user has chosen a file. If there are no errors, the callback function will receive two arguments, with the first argument ("err") equal to null. If there is an error, the callback function will receive one argument, the error code. In the case of the read_local_file() function, an error would presumably occur only in case of a disk error.

-

// Blocking; not available:
- var g = read_local_file()
- print(g.text)

-

// Nonblocking:
- function get(err, f) {
-     // First argument ("err") -is always
-    // null for read_local_file().
-     print(f.text)
- }
- read_local_file(get) // establish callback

-

The function get_library() times out if the library cannot be loaded and posts an alert to the user, asking whether the user wants to attempt the operation again. Here is one way to use this function:

-

var loaded = false
- var load = function() { loaded = true }
-
- get_library(file, load)
-
- var wait_for_load = function() {
-   if (loaded) {
-     print('Got library')
-    // use the library
-   } else {
-    rate(30,wait_for_load)
-   }
- }
-
- wait_for_load()
- while (!loaded) {
-  rate(30)
-}
-print('Library is loaded') -
-

-

The same structure can be used with scene.waitfor('textures',load), with the difference that there is no timeout; if any of the textures requested for objects cannot be found, the load() function will never be called. This structure can also be used with scene.pause('Click to see something',load).

-

 

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/lights.html b/docs/GlowScriptDocs/lights.html deleted file mode 100644 index 49d349b1..00000000 --- a/docs/GlowScriptDocs/lights.html +++ /dev/null @@ -1,94 +0,0 @@ - - - -lights - - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - -
Lighting
-

You can light a scene with distant lights (which act like point-like lamps far from the scene) and/or local lights (point-like lamps near the scene). For a distant light you specify its direction from the origin. For a local light you specify its location in the scene.

-

There is a list of all distant and local light - objects, scene.lights. By default, scene.lights is this list:
-

-

[distant_light(
-      direction:vec( 0.22, 0.44, 0.88),
-      color:color.gray(0.8) ),
-  distant_light(
-      direction:vec(-0.88,-0.22,-0.44),       color:color.gray(0.3) ) ]

-

You can get rid of these default lights by setting the list to empty with scene.lights - = []. To change the color of the first light to cyan, do this:

-

scene.lights[0].color = color.cyan

-

You can turn a light on or off by setting visible to True or False.

-

In addition to these default distant lights, there is default ambient lighting in the form of scene.ambient=color.gray(0.2). The - color of light objects and the amount of scene.ambient must - be specified with some care, because if the total lighting intensity - exceeds 1 anywhere in the scene the results are unpredictable.

-

The following statement creates a local yellow light whose position is at - (x,y,z), and if you continually update lamp.pos, the light will move. - You may wish to place a sphere or box at the same location, with emissive set to True, n so that the lamp acts like a glowing lamp.

-

lamp=local_light( pos:vec(x,y,z),
-                  color:color.yellow )

-

A distant red light located in the direction (x,y,z) from the origin is created like this:

-

DL = distant_light( direction:vec(x,y,z),
-                    color:color.red )

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/local.html b/docs/GlowScriptDocs/local.html index aa2a510d..3be65ef4 100644 --- a/docs/GlowScriptDocs/local.html +++ b/docs/GlowScriptDocs/local.html @@ -1,115 +1,20 @@ - - running locally - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- +
-
+
-

Running locally

+

Running locally, plus information for developers

-

When internet access is missing or poor, you may find it useful to run locally, independent of the internet. At vpython.org, in the section on using VPython without installing software, see the instructions for how to use GlowScript without an internet connection. Before going offline, use the download options at glowscript.org to get local copies of your programs.

-

Another option is to install Python and the VPython 7 module. At vpython.org see the section on using VPython with installed Python. As long as you don't import Python modules other than vpython, you will also be able to run the program at glowscript.org without having to make changes.

+

This information has been moved to a new article.

 

-

 

-

For developers
- If you want to be able to contribute to developing GlowScript, here are the (rather complex) steps required to be able to run locally with changes that you make to the GlowScript code, almost all of which is written in JavaScript (there is also some Python server code and some html code). An excellent, up to date textbook on JavaScript is available at javascript.info.

-

(1) Watch a YouTube overview of the VPython architecture:
-     tinyurl.com/GSarchitecture
- At a later time you should also study this document: -
-    GlowScriptOverview.md

-

(2) Download the GlowScript source files
- At the glowscript repository on GitHub, https://github.com/vpython/glowscript, click "Clone or download" and then clone the repository, or click on "Download ZIP" and unpack the contents of the glowscript-master folder into a new local folder named glowscript.

-

(3) Install the Google Cloud SDK for Python
- At developers.google.com/appengine/downloads choose Standard environment Python for your platform. Next, if you have not already installed the Google Cloud SDK ("Software Development Kit"), do this:
- 1) - Click the Download button for "Install and initialize Google Cloud SDK" and then click "Cloud SDK installer". Run this installer, which will install a Python 2.7 (which is required by the Google software) unless you uncheck "Bundled Python". Let it execute "gcloud init" for you.
-3) -In a command-line terminal, execute the following statement (on Mac or Linux, you may need to preface this command with "sudo"):
-    gcloud components install app-engine-python

-

(4) Using gcloud with Google App Engine
- To run GlowScript, execute
-     dev_appserver.py /..../glowscript/app.yaml
- where the location of the GlowScript code is at
-    /..../glowscript (on Windows, use backslashes instead of slashes).
-
-Then start a browser and enter -"localhost:8080" to run GlowScript.
-
-Alternatively, change directory ("cd") to the glowscript folder you downloaded, and execute
-     dev_appserver.py app.yaml
-
- More precisely, 8080 is the default port number. At the start of ide/api.py, if the variable "localport" is XXXX instead of 8080, to start up the application you must execute
-     dev_appserver.py --port=XXXX /..../glowscript/app.yaml
-and the browser must point to "localhost:XXXX".

-

(5) Testing your changes
- Suppose the current version of GlowScript is 2.9. Change the version number in a program to 3.0dev; that is, 0.1 greater than the current 2.9, plus dev. When you run the program, it will use your latest JavaScript changes. If you make further changes to the JavaScript code, just re-execute a test program to get the latest changes. You don't have to restart the application.
-
- If you want to remake/update the existing version 2.9, or create a new version 3.0, see MakingNewVersion.txt in the docs folder of the GlowScript GitHub repository. Note that use of the build program requires that there be an appropriate version of node in the build-tools folder.
-
- It is very useful to insert console.log(....) at critical points in the JavaScript code, which will generate output to the web page that is viewable if you turn on the browser developer console. On Chrome or Edge just press Ctrl-Shift-j.

-

(6) Save your test programs
- Updates to the Google software can have the effect that you lose the VPython programs you used for testing purposes. On Windows these programs are stored in C:\Users\YourName\AppData\Local\Temp\appengine.glowscript. On Mac, look for datastore.db in /private/var/folders/..... It is highly recommended that you keep a copy of the programs folder before updating the Google software.

-


-

-

-

-

Important: The "original App Engine SDK" described below, with its graphical user interface, will no longer be available after July 30, 2020, at which time it will be necessary to use the "gcloud" mechanism documented above.

-

* Install the Google App Engine SDK for Python
- At developers.google.com/appengine/downloads, download the package for your platform. Choose Standard environment Python, then scroll down and click "Download and install the original App Engine SDK for Python". If using Linux, unpack to a folder whose name will probably be google_appengine.
-

-

* On Windows and Mac, the Google App Engine installer includes an app "Google APP Engine Launcher" which simplifies launching GlowScript.
-
- On Windows, there will be a Google App Engine Launcher icon on your desktop, or in your Start menu. Run the app.
-
- On Mac, drag the GoogleAppEngineLauncher out of the installer package (for example, drag it into the Applications folder), then double-click it. When asked, accept the offer to create some symlinks.
-
- In the Launcher, choose File > Add Existing Application and specify the glowscript folder. Make a note of the Port number. Click Add. In ide/api.py and untrusted/run.js, search for "localhost:" and adjust the port number to the number assigned by the launcher.
-
- With the glowscript entry selected in the launcher, click the green Run button. When the Browse button lights up, click it, which will run your standard browser (which should be Chrome or Edge for best error reporting).
-
- Click Sign in, then click Login and use the name "test". Write or import a program and check that it runs properly.

-

* On Ubuntu, in a terminal cd to the google_appengine folder and execute
- python dev_appserver.py ../glowscript
-
- Next open a browser, preferably an up-to-date version of Chrome (which gives the best error reporting).
-
- Enter as a URL "localhost:8080"
-
- Click Sign in, then click Login and use the name "test".

-
+
-

Top of page

- - diff --git a/docs/GlowScriptDocs/math.html b/docs/GlowScriptDocs/math.html deleted file mode 100644 index 1f2e8b3d..00000000 --- a/docs/GlowScriptDocs/math.html +++ /dev/null @@ -1,89 +0,0 @@ - - - -math functions - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- -

Math Functions

- -

The following math functions are provided:

-

abs(x)
- sqrt(x)
- sin(x)
- cos(x)
- tan(x)
- asin(x)    # arc sine
- acos(x)    # arc cosine
- atan(x)    # arc tangent
- atan2(y,x) # angle whose tangent is y/x
- exp(x)     # e to the x
- log(x)     # natural log, base e
- # log(x)/log(10) gives log base 10
- pow(x,y)   # x to the power y
- pi         # 3.14159....
- ceil(x)    # round up to nearest integer
- floor(x)   # round down to nearest integer
- round(x)   # round to nearest integer
- max(x,y,z) # the largest of x,y,z
- min(x,y,z) # the smallest of x,y,z
- random()   # pseudorandom number 0 to 1
- factorial(x)  # x! = x*(x-1)*(x-2)....(1)
- combin(x,y)   # x!/(y!*(x-y)!)
- max(a,b,c,..) # maximum of these
- min(a,b,c,..) # minimum of these

-

Many of the quantities above are simplified forms of the JavaScript functions Math.abs(x), Math.sqrt(x), etc. Here are details of the factorial and combin functions.

-

 

-

In general, Python modules cannot be imported into VPython programs, because GlowScript VPython functions in a JavaScript environment. However, one can import the Python "random" module into a VPython program, provided by the RapydScript-NG tool that converts Python to JavaScript. One cannot use the form "from random import *" but must use "import random" or "import random as rr" (or other name) or "from random import randint, uniform" (or other list of functions). Here is documentation of the Python random module, however only seed_state, get_random_byte, seed, random, randrange, randint, uniform, choice, shuffle, and sample have been implemented in GlowScript. You do not need to import the random module in order to be able to use the random() function described above.

-

 

-

There are functions for converting between degrees and - radians, where there are 2*pi radians in 360 degrees:

-

radians(360)  # equal to 2*pi
- degrees(2*pi) # equal to 360

-

See JavaScript documentation on the Date object which provides methods for determining the current day etc.

-

Here is a way to determine elapsed time in seconds, with microsecond accuracy, using the clock() function that is also available in the standard Python "time" module. The displayed text is approximately 1.5:

-

t1 = clock()
- sleep(1.5)
- t2 = clock()
- print(t2-t1)

-

JavaScript:

-

var t1 = clock()
- sleep(1.5)
- var t2 = clock()
- print(t2-t1)

-

-

There is also a function msclock() which gives the time in milliseconds instead of seconds.

-

You can use LaTeX to display mathematical expressions on the page.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/mouse.html b/docs/GlowScriptDocs/mouse.html deleted file mode 100644 index 0c15fd26..00000000 --- a/docs/GlowScriptDocs/mouse.html +++ /dev/null @@ -1,134 +0,0 @@ - - - -mouse and keyboard - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- -

Mouse and Keyboard Events
-

-

Introduction to events

-

Here is the simplest mouse interaction, which simply waits for a mouse click:

-

scene.pause() An icon is displayed in the canvas to indicate a pause, waiting for a mouse click.

-

You can also wait for a mouse click, or for a key to be pressed or released, with these statements:

-

scene.waitfor('click') Wait for a mouse click.

-

scene.waitfor('keydown') Wait for a key to be pressed.

-

scene.waitfor('keyup') Wait for a key to be released.

-

scene.waitfor('keydown keyup') Wait for a key press or release.

-

You can set up a function to be called when a mouse or keyboard event occurs. The following will display the type of event (mouse click or keydown) and, in the case of a keydown event, which key is involved:

-

def process(event):
-    print(event.event, event.which)
-
- scene.bind('click keydown', process)

-

The quantity event.event will be 'keydown' if a key was pressed or 'mousedown' if the left mouse button was pressed. The quantity event.which is the numerical key code or mouse button indicator (mouse button is always 1 for now). For example, event.which is 65 for the 'a' key. The quantity event.key is the corresponding character string, such as 'a' or 'delete'.

-

The quantity event.canvas is the canvas associated with the event. You can bind events on different canvases to the same function and be able to tell in which canvas the event occurred.

-

Note that scene.mouse.shift is true if the shift key is down at the time of the keyboard event; similarly for scene.mouse.ctrl and scene.mouse.alt.

-

In RapydScript it is possible to use "anonymous" (unnamed) functions in this situation. For examples, see the mouse drag discussion.

-

-

JavaScript version::

-

var process = function(event) {
-     print(event.type, event.which)
- } -
-
- scene.bind('click keydown', process)

-

More on mouse events

-

Mouse objects are obtained from the mouse attribute of a - canvas object such as scene. For example, - to obtain mouse input from the default window created by GlowScript, refer to the object scene.mouse. For specific examples of mouse handling, - see Click example and Drag - example. A mouse object has a group of attributes corresponding to - the current state of the mouse.

-

The scene.pause() option can be modified to include a message:

-

scene.pause() An icon is displayed in the canvas to indicate a pause, waiting for a mouse click.

-

scene.pause("Click to proceed") The specified text is displayed in the canvas to indicate a pause, waiting for a mouse click.

-

You can also wait for mouse interactions without displaying a prompt:

-

scene.waitfor("click") Wait for the mouse button to be depressed and then released

-

scene.waitfor("mousedown") Wait for the mouse button to be depressed

-

scene.waitfor("mousemove") Wait for the mouse to move, whether or not the mouse button is depressed

-

scene.waitfor("mouseup") Wait for the mouse button to be released

-

scene.waitfor("mouseenter") Wait for the mouse to move, whether or not the mouse button is depressed

-

scene.waitfor("mouseleave") Wait for the mouse button to be released

-

Here are waitfor options to wait for canvas updates:

-

scene.waitfor("redraw") Wait for the start of the next update of the canvas by the web browser

-

scene.waitfor("draw_complete") Wait for the end of the next update of the canvas by the web browser

-

It is a useful debugging technique to insert scene.pause() into your program at a point where you would like to stop temporarily to examine - the scene. Then just click to proceed.

-

Multiple event types: You can wait for more than one type of event. The following statement will wait for either the mouse entering the canvas or leaving the canvas:

-

scene.waitfor("mouseenter mouseleave")

-

In the Drag - example you will see how to use event-handling functions to process mouse events continuously.

-

Current state of mouse and control keys

-

pos The current 3D position - of the mouse cursor; scene.mouse.pos. GlowScript - always chooses a point in the plane parallel to the screen and passing through canvas.center. (See Projecting - mouse information onto a given plane for other options.)

-

ray A unit vector pointing - from camera in the direction of the mouse cursor. The points under the mouse - cursor are exactly { scene.camera.pos + t*scene.mouse.ray for t>0}.

-

project() Projects position - onto a plane. See Projecting mouse position onto a given - plane.

-

pick() Execute var obj = scene.mouse.pick() to obtain the object pointed to by the mouse. If you have a box named B, you can determine whether the picked object is that box by asking if (B == obj). If there is no object pointed to by the mouse, obj is null. Also, obj will be null if the object has the pickable attribute set to false. For example, the curves, spheres, and arrows created by attach_trail and attach_arrow are not pickable, and you may wish to specify that some of your own objects are not pickable. Label objects are never pickable. For curve objects, obj.segment is the number of the picked segment along the curve, starting with 1 (representing the segment from point number 0 to point number 1). You can test for a curve object with if (obj.constructor == curve). See the GlowScript example MousePicking.

-

alt The quantity scene.mouse.alt is true if the ALT key - is currently down (Mac Options key), otherwise false

-

ctrl The quantity scene.mouse.ctrl is true if the CTRL key - is currently down, otherwise false

-

shift The quantity scene.mouse.shift is true if the SHIFT - key is currently down, otherwise false

-

Note that if scene.userzoom = true you won't see mouse events with the ALT key down, and if scene.userspin = true you won't see mouse events with the CTRL key down.

-

Projecting - mouse position onto a given plane

-

Here is a way to get the mouse position relative to a particular - plane in space:

-

temp = scene.mouse.project(
-             normal=vec(0,1,0),
-             point=vec(0,3,0) )
- # null if no intersection with plane:
- if temp != null) ball.pos = temp

-

This projects the mouse cursor onto a plane that is perpendicular - to the specified normal. If the second parameter is not - specified, the plane passes through the origin. It returns a 3D position, - or null if the projection of the mouse misses the plane (scene.mouse.ray is parallel to the plane).

-

In the example shown above, the user of your program will - be able to use the mouse to place balls in a plane parallel to the xy plane, - a height of 3 above the xy plane, no matter how the user has rotated the point - of view.

-

You can instead specify a perpendicular distance from the origin to the plane that is perpendicular to the specified normal. - The example above is equivalent to

-

temp=scene.mouse.project(
-              normal=vec(0,1,0), -d=3 )

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/mouse_click.html b/docs/GlowScriptDocs/mouse_click.html deleted file mode 100644 index 50f4fd34..00000000 --- a/docs/GlowScriptDocs/mouse_click.html +++ /dev/null @@ -1,92 +0,0 @@ - - - -click - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-

Click Example

-
-

This program displays a box (which automatically creates - a window referred to as scene), then repeatedly - waits for a mouse click, displays the mouse position in a label, and displays a - sphere. A mouse click is defined as pressing and releasing the left - mouse button, so the sphere appears when you release the mouse button.

-
-
-

scene.range = 2
- box() # display a box for context
- show = label( pos=vec(0,1,0) )
- while True:
-     scene.waitfor("click")
-    loc = scene.mouse.pos
-     show.text = loc
-     sphere( pos=loc, - size=0.1*vec(1,1,1) )
-

-

Copy this program and run the program. Click outside the box and a sphere appears where you click. If you click - inside the box, nothing seems to happen. This is because the mouse - click is in the xy plane, and the sphere is buried inside the box. If you rotate the scene and then click, you'll see that the - spheres go into the new plane parallel to the screen and passing - through scene.center. If you want all of the - spheres to go into the xy plane, perpendicular to the z axis, change the latter part of the program like this:

-
-
-

loc = - scene.mouse.project(vec(0,0,1))
- # loc is null if no intersection with plane
- if loc:
-     show.text = loc
-     sphere( pos=loc, size=0.2*vec(1,1,1) )

-
-
-
-

JavaScript version of original click program:

-
-
-

scene.range = 2
- box() // display a box for context
- var show = label({pos:vec(0,1,0)})
- while (true) {
-     scene.waitfor("click")
-     var loc = scene.mouse.pos
-     show.text = loc
-     sphere({pos:loc, size:0.1*vec(1,1,1)})
- }

-
-
-
-
-

Here is general mouse documentation.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/mouse_drag.html b/docs/GlowScriptDocs/mouse_drag.html deleted file mode 100644 index 7a902c2d..00000000 --- a/docs/GlowScriptDocs/mouse_drag.html +++ /dev/null @@ -1,148 +0,0 @@ - - - -drag - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-

Drag example

-

Here is the sequence of mouse events involved in dragging something:

-

1) Determine that the mouse button has been depressed (a mousedown event).

-

2) Continually watch for the mouse to move, and use scene.mouse.pos to update positions. These are mousemove events.

-

3) Conclude the drag when the mouse button has been released (a mouseup event).

-

The way you detect these mouse events is by writing functions that are bound to the mouse events using scene.bind, and GlowScript will execute these functions when these mouse events occur.

-

Here is a complete routine for repeatedly creating and dragging a sphere, so that you can arrange many spheres on the screen. While being dragged the sphere is red, but its color changes to cyan when the mouse button is released.

-

scene.range = 5
- box()
-
- drag = False
- s = None # declare s to be used below
-
- def down():
-     nonlocal drag, s
-     s = sphere(pos=scene.mouse.pos,
-         color=color.red,
-         size=0.2*vec(1,1,1))
-     drag = True
-
- def move():
-     nonlocal drag, s
-     if drag: # mouse button is down
-         s.pos = scene.mouse.pos
-
- def up():
-     nonlocal drag, s
-     s.color = color.cyan
-     drag = False
-
- scene.bind("mousedown", down)
-
- scene.bind("mousemove", move)
-
- scene.bind("mouseup", up)

-

It is also possible to use "anonymous" (unnamed) functions, an extended feature of RapydScript, as shown here:

-

scene.range = 5
- box()
-
- drag = False
- s = None # declare s to be used below
-
- scene.bind("mousedown", def ():
-    nonlocal drag, s
-     s = sphere(pos=scene.mouse.pos,
-                color=color.red,
-               size=0.2*vec(1,1,1))
-     drag = True
)
-
- scene.bind("mousemove", def ():
-    nonlocal drag, s
-     if drag: # mouse button is down
-         s.pos = scene.mouse.pos
- )
-
- scene.bind("mouseup", def ():
-    nonlocal drag, s
-     s.color = color.cyan
-     drag = False
)

-

JavaScript, with anonymous functions:

-

scene.range = 5
- box()
-
- var drag = false
- var s = null // declare s to be used below
-
- scene.bind("mousedown", function () {
-     s = sphere( {pos:scene.mouse.pos,
-                  color:color.red,
-                  size:0.2*vec(1,1,1)} )
-     drag = true
-     }
- )
-
- scene.bind("mousemove", function () {
-     if (drag) // mouse button is down
-         s.pos = scene.mouse.pos
-     }
- )
-
- scene.bind("mouseup", function () {
-     s.color = color.cyan
-     drag = false
-     }
- )

-

 

-

Other mouse events: You can also watch for mouseenter (the mouse is moved from the outside of the canvas to the inside), mouseleave (the mouse leaves the canvas), and click.

-

Multiple event types: You can bind a function to more than one type of event. Here is a function bound to both mousedown and mouseup events, either of which will cause a sphere to be created:

-

scene.bind("mousedown mouseup", def ():
-    sphere(pos=scene.mouse.pos)
)

-

Unbinding: After binding a function to a mouse event, you can unbind the function, in which case GlowScript will no longer send events to your function. In the program shown above, if you place scene.unbind("mousedown") in the mouseup event, you will be able to drag just one sphere.

-

Just one: If you use scene.one instead of scene.bind, the binding occurs for just one event and then is automatically unbound. In the program shown above, if you specify scene.one for the mousedown event, you will be able to drag just one sphere.

-

Custom events: You can set up your own custom events using scene.trigger. In the following sample program, first you see a box, then the while loop halts waiting for the custom "ball" event to occur. When you click, the "click" function is executed, and in the click function a sphere is created and a new type of event, "ball", is triggered by scene.trigger, with optional argument newball = s. With this triggering of a "ball" event, the "ball" function receives the triggered arguments in ev and sets the sphere's color to blue. The triggering of the "ball" function also breaks through the scene.waitfor in the while loop that was waiting for a "ball" event. The scene.waitfor statement returns the entity that was sent to the "ball" function, and uses the sphere's position to reposition the box. The process in the loop then repeats.

-

scene.bind("click", def ():
-     s = sphere(pos=scene.mouse.pos)
-     scene.trigger("ball", newball=s)
)
-
- scene.bind("ball", def (ev):
-     ev.newball.color = color.blue
)
-
- b = box()
-
- while True:
-     ss = scene.waitfor("ball")
-     b.pos = ss.newball.pos + vec(0,-1, 0)
-

-

Here is general mouse - documentation.

- -
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/navigation.js b/docs/GlowScriptDocs/navigation.js deleted file mode 100644 index 659899d7..00000000 --- a/docs/GlowScriptDocs/navigation.js +++ /dev/null @@ -1,52 +0,0 @@ -function jumpMenu(obj){ - eval("window.location='"+obj.options[obj.selectedIndex].value+"'"); -} - -var s = '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -document.getElementById("menu1").innerHTML = s - -s = '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -document.getElementById("menu2").innerHTML = s - -s = '' -s += '' -s += '' -s += '' -s += '' -s += '' -s += '' -document.getElementById("menu3").innerHTML = s - diff --git a/docs/GlowScriptDocs/points.html b/docs/GlowScriptDocs/points.html deleted file mode 100644 index fcf4ccc6..00000000 --- a/docs/GlowScriptDocs/points.html +++ /dev/null @@ -1,71 +0,0 @@ - - - -curve - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - - -
points
curve
-

The points object is essentially the same as the curve object except that it displays individual points at the specified positions instead of connecting them with lines, and it does not have origin, axis, or up attributes. The points are rendered as spheres.

-

The points object takes a list of points for pos, like the curve object. The following statement - will display two points, each of radius 50 pixels:

-

points(pos=[vec(-1,0,0), vec(1,0,0)],
-         radius=50, color=color.red)

-

The points object is similar to a curve, but with - disconnected points. As with curve, the pos attribute is an array - of points. The size of the points is specified by radius and the default radius is 2.5, meaning a sphere whose radius is 2.5 pixels (a diameter of 5 pixels). The radius attribute is in screen - pixels if size_units="pixels" (the - default), but if size_units="world", the radius is in the same terms as other objects. Setting the radius to 0 is the same as not specifying a radius, in which case the radius will be 2.5 pixels, just as a curve is thin if its radius is specified as 0.

-

The options for manipulating a curve can also be used with the points object, but currently the points object doesn't handle changes in axis or size, does not have an origin nor a rotate method, nor can be made into a compound.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-

 

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/primitives.html b/docs/GlowScriptDocs/primitives.html deleted file mode 100644 index fdd8f98d..00000000 --- a/docs/GlowScriptDocs/primitives.html +++ /dev/null @@ -1,131 +0,0 @@ - - - -3D objects - - - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-

The GlowScript 3D Objects - (click for details)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
arrow
- arrow
box
- box
clone
- sphere
compound
- cone
cone
- cone

-
curve
- curve
cylinder
- cylinder

-
extrusion
- extrusion
helix
- helix
label
- label
-
points
- points
pyramid
- pyramid
-
ring
- ring
sphere
- sphere
vertex/triangle/quad
- sphere
text
-
text

canvas

-

A display region

frame

-

Group objects together

- -
- - - - - -
- - - - - - - - -
-

controls
- controls

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/pyramid.html b/docs/GlowScriptDocs/pyramid.html deleted file mode 100644 index a0378463..00000000 --- a/docs/GlowScriptDocs/pyramid.html +++ /dev/null @@ -1,94 +0,0 @@ - - - -pyramid - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
pyramid
pyramid
-
-
-

The pyramid object has a rectangular cross section and tapers - to a point. The following statement will display a pyramid with the center - of the rectangular base at (5,2,0), pointing parallel to the x axis with a - base that is 6 high (in y), 4 wide (in z), and with a length 12 from base - to tip:

-
-

pyramid(pos=vec(5,2,0), size=vec(12,6,4))

-

Here is a full list of attributes for a pyramid. All 3D objects have all of these attributes, other than arrow and curve:

-

pos Position: the center of one end of the pyramid; default = vec(0,0,0).

-

size The length, width, and height of the pyramid; default = vec(1,1,1).

-

axis The axis points in the direction of the length of the pyramid, default = vec(1,0,0). Only the direction of the axis is meaningful, not its magnitude. The length of the pyramid, from base to tip, is size.x, not the magnitude of the axis.

-

color Color of object, - as a red-green-blue (RGB) triple: vec(1,0,0) is the same as color.red, default = vec(1,1,1), - which is color.white.

-

opacity Opacity of object, default = 1 (fully opaque); 0 is completely transparent.

-

shininess 0 to 1, default 0.6; governs the amount of specular reflections.

-

emissive If True, local and distant lights are ignored, and the brightness is governed by the object's own color. An example of its use is to put an emissive sphere at the location of a local_light, which looks like a glowing lamp. The default for emissive is False.

-

up Which side - of the pyramid is "up"; default = vec(0,1,0).

-

visible If False, - - object is not displayed; e.g. obj.visible = False
-
Use obj.visible = True to make the object - - visible again.

-

texture You can specify a texture to apply to the object's surface. See the Textures documentation.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

To display a trail or an arrow along the path of a moving object, see Attach a trail or arrow.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/rate.html b/docs/GlowScriptDocs/rate.html deleted file mode 100644 index 016dc91a..00000000 --- a/docs/GlowScriptDocs/rate.html +++ /dev/null @@ -1,74 +0,0 @@ - - - -rate - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
-

Limiting the Animation Rate

-
-
-
-

rate( frequency )

-

Halts computations until 1/frequency seconds after the previous - - call to rate().

-

For example, rate(50) will - halt computations long enough to make sure that at least 1.0/50.0 second - has elapsed since the last execution. If this much time has already elapsed, no halt is performed. - If you place rate(50) inside a computational - loop, the loop will execute at a maximum of 50 times per second, even if - the computer can run faster than this. This makes animations look about - the same on computers of different speeds, as long as the computers are - capable of carrying out 50 computations per second.

-

Related options

-
-

sleep(2) # wait 2 seconds 
-
- update()  # let web page update
-
- # Wait for a click, with an icon prompt:
- scene.pause()
-
- # Wait for a click, with a text prompt:
- scene.pause("Click to proceed")
-
- # Wait till next web page update:
- scene.waitfor("redraw")
-
- # Wait till end of next web page update:
- scene.waitfor("draw_complete")

-

The difference between update() and scene.waitfor("redraw") is that if the browser has nothing to do, update takes only a few milliseconds, whereas scene.waitfor("redraw") waits until the start of the next canvas update to be performed, which may wait for as much as 1/60th of a second (about 16 milliseconds). scene.waitfor("draw_complete") waits until the end of the next canvas update

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/ring.html b/docs/GlowScriptDocs/ring.html deleted file mode 100644 index 06067b57..00000000 --- a/docs/GlowScriptDocs/ring.html +++ /dev/null @@ -1,87 +0,0 @@ - - - -ring - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
ring
ring
-
-
-

The following statement creates a ring centered at location vec(3,0,1), with its axis pointing in the vec(0,1,0) direction, and with a thickness in that direction of 0.2 and a diameter of 1:

-
-

ring( pos=vec(3,0,1), axis=vec(0,1,0),
-      size=vec(0.2,1,1) )

-

Here is a full list of attributes for a ring. All 3D objects have all of these attributes, other than arrow (which has axis_and_length instead of axis):

-

pos Position: the center of one end of the ring; default = vec(0,0,0).

-

size The length, width, and height of the ring; default = vec(0.1,1,1), where size.x is the thickness of the ring.

-

axis The axis points in the direction of the length of the ring, default = vec(1,0,0). Only the direction of the axis is meaningful, not its magnitude. The length of the ring is size.x, not the magnitude of the axis.

-

color Color of object, - as a red-green-blue (RGB) triple: vec(1,0,0) is the same as color.red, default = vec(1,1,1), - which is color.white.

-

up Which side - of the ring is "up".

-

visible If False, - - object is not displayed; e.g. myring.visible = False
-
Use myring.visible = True to make the object - - visible again.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

To display a trail or an arrow along the path of a moving object, see Attach a trail or arrow.

-

No texture or opacity: Currently rings, like curve, cannot be transparent, it is not possible to apply a texture, and it cannot be part of a compound object.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-

Top of page

- - - diff --git a/docs/GlowScriptDocs/rotation.html b/docs/GlowScriptDocs/rotation.html deleted file mode 100644 index 5bd5a561..00000000 --- a/docs/GlowScriptDocs/rotation.html +++ /dev/null @@ -1,59 +0,0 @@ - - - -rotating an object - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- -

Rotating an Object

- -

The following statement will rotate the object named "obj" through an angle (measured in radians) about an axis relative to an origin:

-

obj.rotate(angle=a,
-           axis=vec(x,y,z),
-           origin=vec(xo,yo,zo))

-

If the origin is not given, rotation is relative to obj.pos:

-

# relative to obj.pos:
- obj.rotate(angle=a, axis=vec(x,y,z))

-

If neither the axis nor the origin is specified, rotation is about obj.axis, relative to obj.pos:

-

# about obj.axis, relative to obj.pos:
- obj.rotate(angle=a)

-

The rotate function applies a transformation to the specified object (sphere, box, etc.). The transformation is a rotation of angle radians, counterclockwise around the line defined by origin and origin+axis. By default, rotations are - around the object's own pos and axis.

-

There are functions for converting between degrees and - radians, where there are 2*pi radians in 360 degrees:

-

radians(360)  # equal to 2*pi

-

degrees(2*pi) # equal to 360

-

Also see the rotation function available for vectors.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/sphere.html b/docs/GlowScriptDocs/sphere.html deleted file mode 100644 index d08fb957..00000000 --- a/docs/GlowScriptDocs/sphere.html +++ /dev/null @@ -1,93 +0,0 @@ - - - -sphere - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- - - - - - -
sphere
sphere
-

sphere Here is an example of how to make a sphere:

- -

ball=sphere( pos=vec(1,2,1),
-             size=3*vec(1,1,1) )

-

This produces a sphere centered at location (1,2,1) with diameter = 3. If you specify unequal values for the components of size, you get an ellipsoid.

-

Here is a full list of attributes for a sphere. All 3D objects have all of these attributes, other than arrow and curve:

-

pos Position: the center of the sphere; default = vec(0,0,0).

-

size The length, width, and height of the sphere; default = vec(1,1,1).

-

axis The axis points in the direction of the length of the sphere, default = vec(1,0,0). Only the direction of the axis is meaningful, not its magnitude. The length of the sphere is size.x, not the magnitude of the axis.

-

color Color of object, - as a red-green-blue (RGB) triple: vec(1,0,0) is the same as color.red, default = vec(1,1,1), - which is color.white.

-

opacity Opacity of object, default = 1 (fully opaque); 0 is completely transparent.

-

shininess 0 to 1, default 0.6; governs the amount of specular reflections.

-

emissive If True, local and distant lights are ignored, and the brightness is governed by the object's own color. An example of its use is to put an emissive sphere at the location of a local_light, which looks like a glowing lamp. The default for emissive is False.

-

up Which side - of the sphere is "up"; this has only a subtle effect - on the 3D appearance of a sphere unless the cross section is not circular or a texture is applied; default = vec(0,1,0).

-

visible If False, - - object is not displayed; e.g. ball.visible = False
-
Use ball.visible = True to make the object - - visible again.

-

texture You can specify a texture to apply to the object's surface. See the Textures documentation.

-

End vs center: The pos attribute - for arrow, cone, cylinder, helix, and pyramid corresponds to one end of the object, - whereas for a box, ring, or sphere it corresponds to the center of the object.

-

To display a trail or an arrow along the path of a moving object, see Attach a trail or arrow.

-

See Rotating an Object for an easy way to change the orientation of an object.

-

When you run a program, for convenience GlowScript - creates a canvas on the web page and names it scene. - Objects that you create are drawn on this canvas. If you have more than one canvas, you can specify in which canvas to place a new object, as in box(canvas=myscene); in JavaScript this would be box( {canvas:myscene} ). If you don't specify a canvas, the new object goes into the most recently created canvas, or the most recently selected canvas as specified by setting canvas.selected.

-

A fast sphere object: simple_sphere

-

In order to look smooth, a sphere is made of a very large number of triangles. Sometimes speed is more important than ultimate beauty. The simple_sphere object can be used just like a sphere, but a large number of simple_sphere objects is displayed very much faster than the same number of regular spheres. The simple_sphere object is also used in the points object, for speed.

-
-
-
-
-

JavaScript

-

See the cylinder documentation for how to create an object in JavaScript.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/spherebox.gif b/docs/GlowScriptDocs/spherebox.gif deleted file mode 100644 index 46d0400d..00000000 Binary files a/docs/GlowScriptDocs/spherebox.gif and /dev/null differ diff --git a/docs/GlowScriptDocs/technical.html b/docs/GlowScriptDocs/technical.html index 7012cb6c..fa29f055 100644 --- a/docs/GlowScriptDocs/technical.html +++ b/docs/GlowScriptDocs/technical.html @@ -1,146 +1,20 @@ - - -technical - - - - - - +technical issues - - - - - -
HomePictures of 3D objects
- - - - - - -
- +
-
+
-

Technical issues

-

Here are collected some discussions of technical aspects of GlowScript, which may be of interest to other software developers.

-

Pixel-level transparency based on depth peeling

-

Handling transparency correctly in WebGL is challenging. A standard technique is to order the centers of objects according to their z depth from the camera and render back to front. This approach can make serious errors in the case of intersecting or enclosing transparent objects, where some parts of one object are in front of a second object, and other parts are behind the second object.

-

A better approach is called "depth peeling", in which transparency is dealt with at the pixel level rather than at the object level. Consider for example a transparent sphere enclosing an opaque box, and carry out the following operations:

-

1) Render the pixels of the opaque box to a texture, which we'll call a color texture. This of course takes into consideration the lights in the scene. Call this color texture C0. Note that all opacity values (the "a" in rgba) are 1.0 for this opaque object.

-

2) Render the z depths (distance from the camera) to a texture, which we'll call a depth texture. That is, given the depth of a pixel, the fragment shader stores a false color into the texture, a false color whose 4 bytes represents in some form the depth. Call this depth texture D0.

-

3) Render the transparent object (the sphere) to a texture C1, but using information in the depth texture D0. In the fragment shader, read the (false color) depth from D0, and if the z depth of the transparent sphere pixel is not in front of the opaque box pixel, discard the pixel (using the "discard" statement in the fragment shader). Upon completion of this render step, C1 contains color and opacity information (rgba) for the front-most transparent surface, a hemisphere. This is called a "depth peel".

-

4) We now have two color textures, C0 and C1, which we can merge to form a scene with an opaque box and a transparent hemisphere in front of the box. Render a simple quad object (two triangles) that fill the canvas. In the fragment shader, read the color information from C0 and C1. Store a pixel color that is determined like this, where (1.0-C1.a) is the transparency of the transparent layer:

-

vec3 color = C1.rgb*C1.a +
-            (1.0-C1.a)*C0.rgb;
- gl_FragColor = vec4 (color, 1.0);

-

These four steps illustrate the basic idea. In GlowScript, four transparent depth peels are performed rather than one, and 10 separate renders are carried out:

-

C0 -- opaque color texture
- D0 -- opaque depth texture
- C1 -- frontmost transparent color texture
- D1 -- frontmost transparent depth texture, corresponding to C1
- C2 -- transparent color texture for the next deeper "peel" after C1; if the pixel does not have a depth between that of D0 and D1, the pixel is discarded
- D2 -- transparent depth texture corresponding to C2
- C3 -- next deeper transparent color texture; discard a pixel if z not between D0 and D2
- D3 -- transparent depth texture corresponding to C3
- C4 -- deepest transparent color texture; discard a pixel if z not between D0 and D3

-

MERGE -- The final render is a merge of C0, C1, C2, C3, and C4:

-

vec3 color = C1.rgb*C1.a +
-    (1.0-C1.a)*(C2.rgb*C2.a +
-    (1.0-C2.a)*(C3.rgb*C3.a +
-    (1.0-C3.a)*(C4.rgb*C4.a +
-    (1.0-C4.a)*C0.rgb)));
- gl_FragColor = vec4 (color, 1.0);

-

It may be that C2, C3, and C4 are all empty, but there is no obvious inexpensive way to get the information needed to tell the CPU to avoid scheduling those extra renders, because readPixels is very expensive. If there are more than four transparent layers, this algorithm will not treat them properly. However, note that the fifth and later peels will contribute little to the final pixel color, being partially occluded by four transparent layers in front.

-

Before starting the many renders the objects are sorted into opaque and transparent lists, and if there are no transparent objects a simple C0 render is all that is needed. Moreover, this simple render can exploit antialiasing, whereas the storage into textures for depth peeling unfortunately turns off antialiasing.

-

It is remarkable that doing 10 separate renders runs adequately fast for real-time rendering of moderately complicated scenes. For example, displaying a 10x10x10 grid of rotating transparent boxes can run at around 20 frames per second on ordinary computers, depending on the graphics card.

-

In OpenGL it is possible to create several textures in one render, but WegGL permits attaching just one texture to a framebuffer object, hence a large number of separate renders are needed.

-

To see this algorithm in action, run this Transparency example program.

-

Note that the code for this transparency demo is remarkably short. GlowScript is aimed at making it feasible for nonexpert programmers to exploit WebGL to generate navigable real-time 3D animations.

-

At https://www.glowscript.org/docs/GlowScriptDocs/technical.html, the key files dealing with depth peeling are lib/glow/WebGLRender.js and the shader programs in the shaders folder.

-

It is possible to implement "Fast Approximate Anti-Aliasing" (FXAA) to get around the problem that the use of framebuffer objects turns off anti-aliasing:
- http://www.codinghorror.com/blog/2011/12/fast-approximate-anti-aliasing-fxaa.html

-

This has not been tried in GlowScript.

-

Mouse picking
-

-

Here is how mouse picking has been implemented in GlowScript. For an object with id number N, create a false color like this:

-

function id_to_falsecolor(N) {
- // convert integer object id
- //    to floating RGBA
- var R=0, G=0, B=0
- if (N >= 16777216) {
-    R = Math.floor(N/16777216)
-    N -= R*16777216
- }
- if (N >= 65536) {
-    G = Math.floor(N/65536)
-    N -= G*65536
- }
- if (N >= 256) {
-    B = Math.floor(N/256)
-    N -= B*256
- }
- return [R/255, G/255, B/255, N/255]
- }

-

We want to render the false colors of the objects to a texture the size of the canvas (need not be powers of 2):

-

var pick_texture = gl.createTexture()
- gl.bindTexture(gl.TEXTURE_2D, pick_texture )

-

gl.texParameteri(gl.TEXTURE_2D,
-      gl.TEXTURE_MIN_FILTER, gl.LINEAR)
- 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)

-

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA,
-   width, height, 0, gl.RGBA,
-   gl.UNSIGNED_BYTE, null)
- gl.bindTexture(gl.TEXTURE_2D, null)

-

Set up a framebuffer to render to:

-

var pickFramebuffer = gl.createFramebuffer()
- gl.bindFramebuffer(gl.FRAMEBUFFER,
-                    pickFramebuffer)

-

// create depth buffer:
- var pickRenderbuffer =
-    gl.createRenderbuffer()
- gl.bindRenderbuffer(gl.RENDERBUFFER,
-     pickRenderbuffer)
- gl.renderbufferStorage(gl.RENDERBUFFER,     gl.DEPTH_COMPONENT16, width, height)
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER,     gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER,     pickRenderbuffer)

-

gl.bindRenderbuffer(gl.RENDERBUFFER, null)
- gl.bindFramebuffer(gl.FRAMEBUFFER, null)

-

At the start of a render cycle execute this:

-

gl.bindFramebuffer(gl.FRAMEBUFFER,
-                    pickFramebuffer)
- gl.framebufferTexture2D(gl.FRAMEBUFFER,
-      gl.COLOR_ATTACHMENT0,
-      gl.TEXTURE_2D, - pick_texture, 0)

-

After rendering all the objects, with no lighting calculations (so that all pixels of an object have the same false color), get the id number of the object under the mouse like this:

-

var pixels = new Uint8Array(4)
- gl.readPixels(canvas.mouse.__pickx,     canvas.mouse.__picky, 1, 1, gl.RGBA,     gl.UNSIGNED_BYTE, pixels)
- var id = 16777216*pixels[0] +
-    65536*pixels[1] +
-     256*pixels[2] + pixels[3]

-

A non-power-of-two texture has restrictions; see
- http://www.khronos.org/webgl/wiki/WebGL_and_OpenGL_Differences.
- Important note: This destroys antialiasing, so render to texture is fully useful only for doing some computations, unless we do our own antialiasing.

-

Note that antialiasing being turned off is actually what one wants for mouse picking because you don't want an object with id of 10 that is next to an object of id 30 to get picked with an id of 20, which could happen with antialiasing turned on, due to the averaging of neighboring colors.

-
+

Technical issues

+
+
+

This information has been moved to a new article.

+

 

-

Top of page

- - - + \ No newline at end of file diff --git a/docs/GlowScriptDocs/text.html b/docs/GlowScriptDocs/text.html deleted file mode 100644 index d5f5ff71..00000000 --- a/docs/GlowScriptDocs/text.html +++ /dev/null @@ -1,108 +0,0 @@ - - - -text - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - -
text
-
-
-

3D text

-

See the Text Output discussion for additional ways to output text in the GlowScript environment.

-

With the text object you can display 3D text. The - green 3D text shown above was created with the following statement:

-

text(text='My text is\ngreen',
-     align='center', depth=-0.3,
-     color=color.green)

-

Labels were added to the display above to illustrate - some of the main attributes of the text object. Whether you extrude into or out of the screen, the text is created so that it is readable left to right from the normal viewing position, in the +z direction.

-

3D text is made out of quads and triangles which are then made into a compound object for speed of display. You can make additional copies of a text object by cloning it. You can move the text by specifying a new pos, and you can change its size, axis, up, color, opacity, shininess, and emissive, as with other objects, but note that color and size are "multiplicative"; see compound.

-

Here - is a list of text attributes, in addition to the usual attributes of canvas, color, shininess, and opacity (but not texture or bumpmap, currently):

-

pos The - location of the baseline of the text, to the left, to the right, - or at the center of the text, as per align.

-

align Specify 'left' - (default), 'right', or 'center'.

-

text The text to - be displayed, such as "My text is\ngreen" in the example above ('\n' is a new line character). - Unicode strings are supported. After creating the object, the text is read-only -- it cannot be changed. The reason for this is that it takes a significant portion of a second to create a 3D text object. If you need to change the text, make the current object invisible (visible=False) and create a new object.

-

font Name of - the desired font, either "sans" (sans serif, the default) or "serif". This is read-only.

-

billboard In computer graphics "billboard" behavior means that the object always faces you, no matter how you reorient the camera. Specifying billboard = True when creating the text turns this on, and then is read-only. Because lighting changes as you rotate the camera, you may wish to specify emissive = True, so that the text is always bright.

-

height Height - of an uppercase letter (see above); default is 1. Specifying the - height and depth sets the scale for the entire text display. Changing - the height also changes descent and vertical_spacing, but not depth.After creating the 3D text, you can change the height. For example, if you say T.height = 0.5*T.height, the letters become shorter but the length stays the same.

-

length length - of the displayed text. After creating the 3D text, you can change this. For example, if you say T.length = 0.5*T.length, the letters become narrower but the height stays the same.

-

depth Depth - of the text; the default is 0.2 times the height. A positive number means extrude toward you, out of the screen; negative - means extruded away from you, into the screen. After creating the 3D text, you can change this. For example, if you say T.depth = 2*T.length, the letters become twice as thick. If the depth is zero, the thickness is made to be 0.01 times the height, and the text looks like a thin sheet.

-

descender Height - of the descender on lower-case letters such as y (whether or not - there is such a letter in the text). This is typically about 0.3 - times the height. This is read-only but is affected by changes in height.

-

upper_left, upper_right, - lower_right, lower_left The bounding box of the displayed - text; all of these are read-only. For example, if you create title = text(text="My Text"), - you can place a sphere at the upper left corner with the statement sphere(pos=title.upper_left).

-

start, end The left-most and right-most - locations on the baseline. These are read-only. If align is 'left', pos is the same as start. If align is 'right', pos is the same as end.

-

vertical_spacing Vertical - distance from one baseline to the next in a multiline text. This is read-only.

-

size You change the size, which does not affect the axis. The size is multiplicative, as the text object is actually a compound object; see the documentation on compound objects.

-

axis The axis - points along the baseline; changing the axis changes the orientation - of text. The default is (1,0,0), with text going toward the right. Changing the axis only affects the direction of the line of text, not the length or size. up Controls - the up attribute of the frame; changing up makes the text tip away - from the vertical

-

up Controls - the up attribute of the text; changing up makes the text tip away - from the vertical.

-
-

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/text_output.html b/docs/GlowScriptDocs/text_output.html deleted file mode 100644 index 571f6c5b..00000000 --- a/docs/GlowScriptDocs/text_output.html +++ /dev/null @@ -1,156 +0,0 @@ - - - -text output - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- -

The print function

-

The print function places text in a scrolling text region at the bottom of the window. Consider the following statements:

-

v = vec(1,2,3)
- print("This is a test.")
- print("The vector v =", v, ".")

-

These statements produce this output:

-

This is a test.
- The vector v = < 1, 2, 3>.

-

The first print statement creates the scrolling text region. Later print statements add to the existing text, with end-of-line breaks after each print, and with spaces between items listed in a print statement.

-

In VPython and RapydScript you can print multiline text like the following:

-

print('''This is a test
- of multiline text which
- displays as shown.''')

-

You can change the end of line ('\n" by default) and the item separator (" " by default). Consider the following print statements:

-

v = vec(1,2,3)
- print("Look:", end="---")
- print("v =", v, ".", sep="_", end="!!")

-

These statements produce this output:

-

Look:---v =_< 1, 2, 3 >_.!!

-

The elements "sep=..., end=..." must be the last arguments in the print statement.

-

JavaScript:

-

var v = vec(1,2,3)
- print("Look:", {end:"---"})
- print("v =", v, ".", {sep="_", end="!!"})

-

-

String formatting

-
-

Python has a powerful mechanism for formatting a string. This has now been implemented in GlowScript (for VPython, RapydScript, and JavaScript). Here is an example (in RapydScript):

-
-
-
-

V = 13.47
- s = "There are {:.1f} {}."
- p = s.format(V, 'liters')
- print(p) # "There are 13.5 liters."

-
-
-

Or more compactly,

-

print( "There are {:.1f} {}.".format(V, 'liters') )

-
-
-

The element "{:.1f}" indicates "fixed format" with ".1" indicating that one digit should be shown after the decimal point. The value 13.47 is rounded to 13.5. If you specify "{:12.3f}", what will be displayed is "      13.470", with 6 spaces before the number, plus the 6 digits of "13.470" (3 after the decimal point), for a total of 12 characters.

-
-
-
-

The element "{}" indicates that the default method for representing an argument should be used. In this case "bucket" is displayed.

-
-
-
-

There are many formats available: b for binary (base 2), o for octal (base 8), x for hexidecimal (base 16; 28 displays as 1c), d for decimal integer, e for exponential (e.g. 5.32e-7), c for character code (e.g. converts "b" to 97), % for percent (displays 0.34 as 34%). The E exponential format gives 5.32E-7 and the X hexidecimal format gives 1C. 

-
-
-
-

The g format (g for general) is particularly useful because it flips between fixed and exponential formats depending on the size of the number.

-

The following statement

-
-
-

print("The {} {} {}.".format("quick","brown","fox"))

-
-
-

produces "The quick brown fox". You can specify a different order of the arguments. The following statement

-
-
-
-

print("The {2} {0} {1}.".format("quick","brown","fox"))
-

-
-
-

produces "The fox quick brown." In other words, {N} refers to the Nth argument, counting from zero.

-

Moreover, you can combine specifying which argument to display with the format to use:

-
-

s = "Here are fixed format ({0:.3f}) and exponential format ({0:.3e}) versions.".format(127.73)

-
-
-
-

Print options

-

With print_options you can change the default size of the print region, allow the user to edit the text, clear the text from the region, destroy the region, or obtain the current contents of the print region.

-

The following statement changes both the width (default 400) and height (default 100) of the print region. If you execute this before your first print statement, the initial size will be 500 by 300. If you execute this after executing print statements, the size of the region will change (but will retain its contents).

-

print_options(width=500, height=300)

-

By default, the text in the print region is read-only; the user cannot edit the text. If you want the user to be able to edit the text, do this:

-

print_options(readonly=False)

-

In any case, the user can select text and copy the text with ctrl-c.

-

You can clear out all the text from the region like this:

-

print_options(clear=True)

-

You can delete the region from the screen with this statement:

-

print_options(delete=True)

-

After deleting the region, another print statement will recreate it, with the previously specified width and height.

-

By default the print area appears underneath the canvas (pos = 'bottom') but you can make it appear to the right of the canvas with the following statement (you may have to include something like width=100, because if the window is too narrow to fit the display and the text area side by side, the text area goes below the display):

-

print_options(pos='right')

-

You can obtain the current contents of the print region as a character string:

-

text = print_options(contents=True)

-

The text is extracted before processing clear or destroy requests. If you don't request the contents, print_options returns the empty character string ""'.

-

You can of course combine any options in one statement:

-

print_options(width=150, readonly=False)

-

Additional text output methods

-

The canvas documentation explains how to add text above a canvas (scene.title.text or html) or below a canvas (scene.caption.text or html).

-

 

-

The Example program ScrollingText shows how to create a scrolling text object that you can send output to and type into, using the HTML element "textarea". This is the mechanism used by print.

-


-

-

alert('The mass is '+m+' kg.')
- This pauses execution and displays the string in a dialog box. Numeric values are converted to strings.

-

 

-

$('body').append('This is a test.<br>')
- ...
- $('body').append('This is only a test.<br>')

- These statements add text to the bottom of the web page. The <br> element makes a line break,

-

 

-

console.log('A scalar', a+10, 'and a vector', v.toString())
-

-

The output in the console is the following:
- A scalar 15 and a vector < 10, 20, 30 >
- Successive console.log outputs - appear as new lines.

-

Using console.log requires opening the browser's "console". To enable the console, in Chrome press shift-ctrl-j on Windows or Ubuntu, or option-cmd-j on Mac. In Firefox on Windows choose Firefox > Web Developer > Web Console, and on Ubuntu choose Tools > Web Developer > Web Console. The output will be found at the end of the console output

-

In some of these output options, to display the value of a vector v you have to write v.toString(), but this is done automatically by the print statement.

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/textures.html b/docs/GlowScriptDocs/textures.html deleted file mode 100644 index 29ce42cc..00000000 --- a/docs/GlowScriptDocs/textures.html +++ /dev/null @@ -1,131 +0,0 @@ - - - -textures - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
Textures
texture
-
-
-
-

The stucco-textured box shown above was made with this statement:

-
-
-

box( texture=textures.stucco )

-
-

A collection of ready-to-use textures is provided; "textures.stucco" actually represents a character string giving the name of the image file. For the complete set of existing built-in textures, see the example program Textures.

-
-
-

You can optionally specify that only portions of the object should be textured. The following statement places the texture only on the right face of the box, leaving the rest of the box green): 

-
-
-

box( color=color.green,
-     texture={'file':textures.stucco,
-                  'place':'right'} )

-

Using images from other web sites: You can use an image from another web site as a texture by specifying its URL, if that web site is "CORS enabled" (CORS = Cross-Origin Resource Sharing). For example,
-
-texture="https://s3.amazonaws.com/glowscript/textures/flower_texture.jpg"
-
-will fetch an image consisting of the word "CORS". For technical reasons, if the image has a width or height that is not a power of 2 (that is, not 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, etc.), the image is stretched to the next larger width or height that is a power of 2.
-
-There is -a CORS-enabled site, https://i.imgur.com, that has extensive galleries of freely usable images. When you see an image you want, right-click the image (Mac Ctrl-click), choose "Copy image address", and paste the address into your texture specification, bracketed by quotation marks.

-

Jupyter VPython and textures: If you are using Jupyter VPython you can use a texture on your own computer. Look at the Python directory
-
-     ...../ Lib/site-packages/vpython/vpython_data
-
- There you will find the standard textures that are installed with VPython. Place a copy of your own texture in this folder. Suppose its file name is T.jpg. In your VPython program, the following statement will display a box with your texture on it: box(texture='/nbextensions/vpython_data/T.jpg')

-

If you use "Share this program" in the GlowScript editor and copy code to a page on your own web site, you can fetch an image to use as a texture from the same web site, even if your web site isn't CORS-enabled.

-
-
-

Placing a texture on portions of the object: Placement options are 'left', 'right', 'sides' (all but the left and right ends), 'ends' (both left and right), and 'all' (the default). The meaning of left and right is that by default GlowScript objects have their axis in the (1,0,0) direction (+x), and the right end is on the right initially, before possible later changes of axis. In the case of a cylinder, 'sides' specifies the curving surface.

-
-
-

You can combine these options: 'place' : ['left', 'sides'] will place the texture on the left end and the sides.

-

Flipping and rotating: You can change the orientation of a texture on an object by specifying 'flipx' : true (reflect left <-> right),'flipy' : true (reflect up <-> down), ''turn' : N (rotate counterclockwise N 90-degree angles; if N is negative, the turning is clockwise). These transformations are applied in the order flipx, flipy, turn.

-

All the parameters for a texture are seen in the following example.

-

b = box( pos=vec(-1,2,0),
-       texture={'file':textures.stucco,
-               'bumpmap':bumpmaps.stucco,
-               'place':['right', 'sides'],
-               'flipx':True,
-               'flipy':True,
-               'turn:-3}) -

-

Currently you have to give all the information in one package, as in the example above, rather than specifing an individual parameter such as texture.turn. You can retrieve this information as var T = b.texture, which gives you the information in the form { 'file': ...., 'bumpmap':...., etc. }, so that T.turn would be -3.

-

Color: Textures have their own colors, but if you specify a non-white color for a fully textured object, that color is mixed into the texture color, so that you can have for example green stucco. If only portions of the object are textured, the object color is not mixed with the texture color, and non-textured portions are shown with the specified object color.

-

Textures loaded: It takes time to load a texture from the specified file, so it may be important in your program to wait for all textures to be loaded before displaying the scene. The following sequence will achieve this effect:

-
-
-

scene.visible = False # show nothing yet
- ...create the objects
- scene.waitfor("textures")
- scene.visible = True -  # show everything

-
-

First, make the scene invisible, create the objects (which won't be visible), then wait for all textures to have been loaded. Then make the scene visible, and you'll see the objects with their textures.This is the technique used in the example program Textures.

-

You can also check the status of an individual object B: the quantity B.ready is true if the texture has been loaded (or if B has no texture).

-

Textured objects are not displayed until the texture has been loaded. If you don't wait with scene.waitfor("textures",wait), you may see objects become visible in a random sequence, depending on when the various textures have been loaded.

-

Removing a texture: If you set texture=None, no texture is displayed.

-

Bump maps

-

Another option is to specify a "bump map". Bump maps make small distortions in a surface to give the illusion of a non-smooth surface. There are several kinds of bump maps, but the type of bump map currently supported in GlowScript is a "normals map", in which the normals (perpendiculars) to the surface, which affect the lighting of the surface, are varied across a surface in such a way that the surface no longer seems smooth. When you move the surface or the lights you will see an enhanced 3D effect. Bump maps can be produced from images by using computer tools made for this purpose, and a few bumpmaps have been provided in GlowScript. For example, bumpmaps.stucco is a normals map that enhances the 3D appearance of textures.stucco. Here is the statement that adds the built-in bump map to the built-in texture:

-
-
-

box(texture={'file':textures.stucco,
-        'bumpmap':bumpmaps.stucco)

-

The example program Bumpmaps lets you move the lighting around as well as rotate the object so that you can see the effects of adding a bumpmap.

-

The bump maps currently available are bumpmaps.gravel (to accompany textures.gravel), bumpmaps.rock (to accompany textures.rock), bumpmaps.stones (to accompany textures.stones), bumpmaps.stucco (to accompany textures.stucco), and bumpmaps.wood_old (to accompany textures.wood_old).

-

JavaScript

-

Here is the JavaScript version of the previous example:

-
-
-

box( texture={'file':textures.stucco,
-         'bumpmap':bumpmaps.stucco} )

-
-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/trail.html b/docs/GlowScriptDocs/trail.html deleted file mode 100644 index a5b5df0b..00000000 --- a/docs/GlowScriptDocs/trail.html +++ /dev/null @@ -1,138 +0,0 @@ - - - -attaching trail or arrow - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
Attach a trail or arrow
trails
-
-
-

Attach a trail

-

If an object is named "ball", the following statement will cause a curve to be drawn along the path of the moving object:

-
-
-

attach_trail(ball)

-

By default, the radius of the cross-section of the curve is 0.1 times the size.y of the object, and the color of the curve is the color of the object. You can change this:

-
-
-

attach_trail(ball, radius=0.1,
-                   color=color.white )

-

You can also specify that only the most recent N points are displayed, which has the effect of giving the object something like a comet's tail:

-
-
-

attach_trail(ball, retain=30 )

-

By default, points are added to the trail every time the scene is rendered, which is typically about 30 times per second. No trail is started until you explicitly specify a position of the ball. You can limit the number of points per second ("pps") to be added to the trail. In the following case, 5 points are added to the trail per second (the maximum value of pps that makes sense is about 30):

-
-
-

attach_trail(ball, pps=5 )

-

By default, the trail is a curve (connected points), but you can make a trail of separated spheres:

-
-
-

attach_trail(ball, type='points' )

-

Instead of specifying an object whose position is used to add points to the curve or set of spheres, you can specify a function which yields a vector to be used as a position. If you have a function named "center" that returns a vector position, you can say this:

-
-
-

def center():
-    return (ball1.pos+ball2.pos)/2
-
- attach_trail(center)

-
-

In summary, you can specify a trail to be constructed as a curve or a set of spheres, using the position of an object or the vector result of a function. You can specify options to control color, radius, retain, pps, and type. The default for the "curve" option is 0, which makes a thin curve (this works best in the xy plane; if it doesn't give the result you want, set trail_radius to the desired value).

-

The default for the "points" option is 0.2 times the radius, 0.1 times the height or size.y, of the moving object at the time your create that object. If you don't assign your own size to an object until after you've created it, you may also need to set radius at that time. If you change radius during the motion, later portions of the trail will have this radius.You can change color or radius and the following points will be displayed with the new attributes.

-

start, stop, clear

-
-
-
-

You can start and stop adding points to a trail, and you can clear the trail (remove the existing points):

-
-
-

b = attach_trail(ball)
- ...
- b.stop()
- ...
- b.start()
- ...
- b.clear()

-

 

-

Attach an arrow

-

You can attach an arrow to a moving object. The following statement will automatically display a green arrow at the current location of the ball. The arrow will have shaftwidth=0.3, and its axis and length is determined by scale*ball.axis:

-
-
-

attach_arrow(ball, "axis", scale=1e3,
-         shaftwidth=0.3, color=color.green)

-

The default value of scale is 1, and the default color of the arrow is the color of the ball. You can specify any vector attribute of the moving object, not just "axis". For example, if you continually update a vector quantity ball.velocity and want to continually display an arrow representing this quantity at the location of the moving ball (with scale=1 and the color of the ball), just say this:

-
-
-

attach_arrow(ball, "velocity")

-
-
-
-
- You can start and stop displaying the arrow:
-
-
-

b = attach_arrow(ball)
- ...
- b.stop()
- ...
- b.start()

-

-

JavaScript

-

Here is an example of the form to use in JavaScript:

-

attach_trail(ball, {type:spheres, pps:5})

-
-
-
-
-
-
-
-
-
-
-
-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/triangle.html b/docs/GlowScriptDocs/triangle.html deleted file mode 100644 index 96a879a7..00000000 --- a/docs/GlowScriptDocs/triangle.html +++ /dev/null @@ -1,110 +0,0 @@ - - - -triangle - - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
-
- - - - - -
triangle/quad
pyramid
-
-
-

GlowScript provides a set of built-in 3D objects (box, sphere, etc.). You can also create your own 3D objects, and even change their shapes dynamically, as in the case of the example program shown above, in which a pulse moves up along a rug.

-

The surface of an object consists of a mesh of triangles, and a triangle consists of 3 vertices. We can create a triangle by first creating three vertex objects, then using them to form a triangle:

-
-

a = vertex( pos=vec(0,0,0) )
- b = vertex( pos=vec(1,0,0) )
- c = vertex( pos=vec(1,1,0) )
- T = triangle( v0=a, v1=b, v2=c )

-

Equivalently, one could write this:

-

T = triangle(
-          v0=vertex( pos=vec(0,0,0) ),
-          v1=vertex( pos=vec(1,0,0) ),
-          v2=vertex( pos=vec(1,1,0) ) )

-

Another option is to give a list of vertex objects:

-

T = triangle( vs=[a,b,c] )

-

Often it is convenient to divide a surface into rectangles instead of triangles, which is done with a quad object. The following statements are equivalent to creating two triangles with vertices (a, b, c) and (a, c, d):

-

a = vertex( pos=vec(0,0,0) )
- b = vertex( pos=vec(1,0,0) )
- c = vertex( pos=vec(1,1,0) )
- d = vertex( pos=vec(0,1,0) )
- Q = quad( v0=a, v1=b, v2=c, v3=d )

-

You could also write this:

-

Q = quad( vs=[a,b,c,d] )

-

The vertices of a triangle or quad can have their own colors, which are blended between vertices:

-

triangle

-

The role of the "normals", shown here as arrows perpendicular to the plane of the triangle, is discussed in detail below. If point the thumb of your right hand in the direction of the normal, and curl the fingers of your right hand, your fingers should go from v0 to v1 to v2. To put it another way, looking down the normals from above, going from v0 to v1 to v2 should go counterclockwise.

-

The power of triangles and quads

-

There are two powerful capabilities of triangles and/or quads: First, any surface can be approximated by a mesh of triangles, so you can make any shape you like. Second, by changing the attributes of vertex objects, you can change the shape of a surface dynamically. A vertex object can be shared by several adjacent triangles, and changing that vertex object simultaneously affects all of the triangles that include that vertex object.

-

In the rug example pictured above, the rug is divided into a rectangular mesh of vertex objects, and quad objects are created from these vertex objects. The same vertex may be shared by as many as four adjacent quad objects. Changing the z position of a shared vertex object affects all those quads that refer to that vertex, which makes it easy to create a moving pulse simply by modifying the vertex positions. In the rug program the quad objects are needed to display the rug, but once the quads have been created all further calculations refer just to the underlying vertex objects.

-

For a triangle or quad, in addition to specifying vertex objects you can specify texture or visible, but the usual attributes for other objects such as pos or color don't apply; this information is specified in the vertex objects. (It is not possible to specify place, flipx, flipy, or turn for a triangle or quad texture. These effects can be achieved by the way texpos is specified in the vertex objects.)

-

If you wish to specify a bumpmap to go with a texture, use the same scheme used with other objects:

-

quad(vs=[a,b,c,d],     texture=dict(file=textures.stucco,                  bumpmap=bumpmaps.stucco))

-

Display speedup: Typically you will use many triangles to create a complex object. For clarity you might wish to keep them all in a list: tris = [ triangle1, triangle2, ....]. If the object's internal shape need not change (unlike the case of the rug), you can say "s = compound(tris)" in which case you can move and resize and rotate the object "s" very rapidly, just as though it were a built-in object such as a sphere.

-

Vertex attributes

-

The attributes of a vertex object are pos, normal, color, opacity, texpos, bumpaxis, shininess, and emissive. The pos attribute represents the location of the vertex in 3D space.

-

The attributes color, opacity, shininess, and emissive are the same as those for other objects such as box or sphere, but within a triangle they are averaged among the three vertex objects. For example, at locations between a red vertex and a green vertex there is a fade from red to green. A striking effect occurs if two of the three vertex objects have opacity = 0, because as you approach the edge of the triangle bounded by those two vertices the triangle fades to nothing.

-

The vertex attributes normal, texpos, and bumpaxis require additional explanation..

-

normal: The lighting of a triangle, based on its own color and the lights provided, is calculated based on the "normals" to the triangle, vectors pointing away from the surface of the triangle. In the simplest case, the normal at each vertex is perpendicular to the surface of the triangle, as shown in the figure above.

-

Each triangle has three normals, at each of the three vertices. The normal at each interior point of the triangle is an average of the three specified normals.

-

Where two triangles meet, you will see a sharp break if the two triangles have different normals. If you want to smooth the transition, you should average the neighboring normals (n1+n2)/2 and apply them to both triangles; this will smooth out the joint.

-

If you don't explicitly specify a normal for a vertex, the normal is given the default value vec(0,0,1), pointing out of the screen. If the vertex is to be used in a triangle that does not lie in the xy plane, you need to specify a normal yourself. If the three vertices are a, b, and c (in counter-clockwise order), and you want normals that are perpendicular to the triangle, you can calculate the normal like this:

-

(b-a).cross(c-b).norm()

-

The "vector cross product" produces a vector that is perpendicular to the plane defined by the two vectors b-a and c-b, the first two edges as you go around the triangle. If the fingers of your relaxed right hand curl in the direction a to b to c, your outstretched thumb points in the direction of the vector cross product.

-

texpos: If you intend to apply a texture or bumpmap to a mesh object, you must specify in the mesh how you want the texture to be mapped onto your object. You might want the texture to occupy only a portion of the object, or be stretched or distorted in some way. This is done by specifying "texel" coordinates, given as texpos vectors in the vertex objects.

-

Texel coordinates for a surface texture are specified by an "x" and a "y", both ranging from 0 to 1 if the entire texture is to be displayed. (In many discussions texel coordinates are referred to as "u" and "v", or as "s" and "t".) In anticipation that WebGL will eventually enable 3D textures, which permit filling a textured volume, GlowScript requires that in texpos elements the third component must be zero.

-

For example, to fill a quad with a texture, the texpos vectors in the vertex objects v0, v1, v2, and v3 would be vec(0,0,0), vec(1,0,0), vec(1,1,0), vec(0,1,0), no matter what the 3D pos attributes are. If you want only the lower quarter of the texture to fill the quad, the texpos vectors would be vec(0,0,0), vec(0.5,0,0), vec(0.5,0.5,0), vec(0,0.5,0). Note that <0,0,0> is at the lower left, and <1,1,0> is at the upper right.

-

bumpaxis: If you will use a bumpmap, you need to specify a vector bumpaxis direction for each vertex, specifying the direction of the "x" axis of the texture at that location. The default bumpaxis is vec(1,0,0).

-

Important limitation: WebGL currently supports no more than 65536 vertex objects.

-

Mouse picking of triangles/quads

-

The operation scene.mouse.pick() gives the object lying under the mouse. It may be convenient to specify my_id='car' as your own attribute for each triangle or quad in the object, so that you can tell whether the triangle or quad is part of the 'car' group:

-

t1 = triangle(... my_id='car')
- t2 = triangle(... my_id='car')
- ...
- obj = scene.mouse.pick()
- if (obj != null and
-     obj.my_id != undefined and
-     obj.my_id == 'car') hitcar = True

-
-

Top of page

- - - diff --git a/docs/GlowScriptDocs/vector.html b/docs/GlowScriptDocs/vector.html deleted file mode 100644 index 70f35d90..00000000 --- a/docs/GlowScriptDocs/vector.html +++ /dev/null @@ -1,139 +0,0 @@ - - - -vector - - - - - - - - - - - - - -
HomePictures of 3D objects
- - - - - - -
- - - - - -
- -

The vector object

- -

The vector object is not a displayable object but is - a powerful aid to 3D computations. Its properties are similar to - vectors used in science and engineering.

- -

vec(x,y,z)

-

This creates a 3D vector object with the given components x, y, and z.

-

Vectors can be added or subtracted from each other, or multiplied by an - ordinary number. For example,

- -

var v1 = vec(1,2,3)
- var v2 = vec(10,20,30)
- v1+v2 # same as vec( 1, 22, 33)
- 20*v1 # same as vec(20, 40, 60)

-

You can refer to individual components of a vector:

-

v2.x is 10, v2.y is 20, v2.z is 30

-

It is okay to make a vector from a vector: vec(v2) is still vec(10,20,30). This is a convenient way to make a separate copy of a vector.

-

Vector functions

-

The following functions are available for working with vectors:

-

mag(A) = A.mag = |A|, the magnitude of a vector
-
- mag2(A) = A.mag2 = |A|*|A|, the vector's magnitude squared
-
- norm(A) = A.norm() = A/|A|, a unit vector in the direction of the vector
-
- hat(A) = A.hat = -A/|A|, a unit vector in the direction of the vector; an alternative to A.norm(), based on the fact that unit vectors are customarily written in the form ĉ, with a "hat" over the vector
-
- dot(A,B) = A.dot(B) = A dot B, the scalar dot product between two vectors
-
- cross(A,B) = A.cross(B), the vector cross product between two vectors
-
- diff_angle(A,B) = A.diff_angle(B), the angle between two vectors, in radians
-
- proj(A,B) = A.proj(B) = dot(A,norm(B))*norm(B), the vector projection of A along B
-
- comp(A,B) = A.comp(B) = dot(A,norm(B)), the scalar projection of A along B
-
- A.equals(B) is True if A and B have the same components (which means that they have the same magnitude and the same direction)
-
- vec.random() produces a vector each of whose components are random numbers in the range -1 to +1
-
- Some examples:

- -

mag(A) # calculates length of A
- mag(vec(1,1,1))  # = sqrt(3) = 1.732...
- mag2(vec(1,1,1)) # = 3; magnitude - squared

-

It is possible to reset the magnitude or the - magnitude squared of a vector:

-

v2.mag = 5 # sets magnitude to 5;
-           # no change in direction
- v2.mag2 = 2.7 # sets squared magnitude
-              # of v2 to - 2.7

-

You can reset the magnitude to 1 with norm():

- -

norm(A) # A/|A|, normalized; magnitude 1
- norm(vec(1,1,1)) # vec(1,1,1)/sqrt(3)

-

You can also write v1.norm() or v1.hat. For convenience, norm(vec(0,0,0)) is calculated to be vec(0,0,0).

-

You can change the direction of a vector without changing its magnitude:

-

v2.hat = v1 # changes the direction of v2
-            # but not its magnitude
-

- -

To calculate the angle between two vectors (the "difference" - of the angles of the two vectors):

- -

ang = v1.diff_angle(v2)

-

You can also write v1.diff_angle(v2). For convenience, if either of the vectors has zero - magnitude, the difference of the angles is calculated to be zero.

- -

cross(A,B) or A.cross(B) gives the cross product of two vectors, a vector perpendicular to the plane defined by A and B, - in a direction defined by the right-hand rule: if the fingers of the right - hand bend from A toward B, the thumb points in the direction - of the cross product. The magnitude of this vector is equal to mag(A)*mag(B)*sin(A.diff_angle(B)).

-

dot(A,B) or A.dot(B) gives the dot product of two vectors, - which is an ordinary number equal to mag(A)*mag(B)*cos(A.diff_angle(B)). If the - two vectors are normalized, the dot product gives the cosine of the angle - between the vectors, which is often useful.

-

Rotating a vector

-

There is a function for rotating a vector:

-

v2 = rotate(v1, angle=a, axis=vec(x,y,z))

-

The angle must be in radians. The default axis is - (0,0,1), for a rotation counterclockwise in the xy plane around the z axis. There - is no origin for rotating a vector. You can also write v2 - = v1.rotate(angle=theta, axis=vec(1,1,1)). There is also a rotate capability for - objects.

-

The JavaScript versions are v2 = rotate(v1, {angle:a, axis=vec(x,y,z}) and v2 = v1.rotate({angle:a, axis=vec(x,y,z}).

-

There are functions for converting between degrees - and radians, where there are 2*pi radians in 360 degrees:

-

radians(360)  is equivalent to 2*pi
- degrees(2*pi) is equivalent to 360

-

-
-

Top of page

- - - diff --git a/docs/MakingNewVersion.txt b/docs/MakingNewVersion.txt index 30ca9e81..8e4bf1f2 100644 --- a/docs/MakingNewVersion.txt +++ b/docs/MakingNewVersion.txt @@ -61,12 +61,10 @@ to update the package files produced in the previous step that involved build.py There is a Glowscript program in build-tools/Symbols.js which you need to copy into (presumably local) glowscript and run to compile the symbols. You have to copy and paste the results into the appropriate file (package/symbols.X.Y.min.js). -Update the symbols reference at the end of ide/index.html. - -You also have to change ide/index.html to point to the new Symbols file, +You also have to make a change at the end of ide/index.html to point to the new Symbols file, since the IDE doesn't yet dynamically load symbols based on the version header. -Also change "Welcome to GlowScript X.Y" appropriately in ide/index.html. +Also change "G l o w S c r i p t X.Y" appropriately in ide/index.html. There is a jquery version reference in untrusted/run.html. diff --git a/docs/VPythonDocs/MathJax.html b/docs/VPythonDocs/MathJax.html index ac10ec67..3ce97a2b 100644 --- a/docs/VPythonDocs/MathJax.html +++ b/docs/VPythonDocs/MathJax.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/Templates/template.dwt b/docs/VPythonDocs/Templates/template.dwt index 3fcbd93f..a2c8fca1 100644 --- a/docs/VPythonDocs/Templates/template.dwt +++ b/docs/VPythonDocs/Templates/template.dwt @@ -18,10 +18,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/VisualIntro.html b/docs/VPythonDocs/VisualIntro.html index 150ad724..db6f661d 100644 --- a/docs/VPythonDocs/VisualIntro.html +++ b/docs/VPythonDocs/VisualIntro.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
@@ -33,7 +34,7 @@

Simple 3D Programming Using VPython

I. Getting started

-

To write a VPython program in the browser, sign in at glowscript.org, click the link to your programs, then click Create New Program. A blank edit page will open with a header line that says something like "GlowScript 1.1 VPython". Start typing your program on the second line. Click "Run this program" to try out your program.

+

To write a VPython program in the browser, sign in at glowscript.org, click the link to your programs, then click Create New Program. A blank edit page will open with a header line that says something like "GlowScript 3.0 VPython". Start typing your program on the second line. Click "Run this program" to try out your program.

The canvas

@@ -54,7 +55,7 @@

The Output window

The Code window

If you type or copy the following simple program into the program editor and run it (click "Run this program" or press Ctrl-1 or Ctrl-2), you will see - a canvas like the one shown in the figure.

+ a canvas conatining a red box and a green sphere, as shown in the figure.

redbox=box(pos=vector(4,2,3),
           size=vector(8,4,6),color=color.red)
ball=sphere(pos=vector(4,7,3),radius=2,color=color.green)

@@ -66,7 +67,7 @@

Viewing the scene

or down. Click and drag up or down with the middle mouse button to move closer to the scene or farther away (on a 2-button mouse, hold down the left and right buttons; on a 1-button mouse, hold down - the Alt key).

+ the Alt key). To pan left/right and up/down, drag with the shift key held down.

II. VPython Entities

@@ -83,7 +84,7 @@

Objects, names, and attributesball.pos (the position - of the sphere), ball.color, and radius or other size parameter. If you change an attribute of an object, such as + of the sphere), ball.color, and ball.radius or other size parameter. If you change an attribute of an object, such as its position or color, VPython will automatically display the object in its @@ -108,23 +109,23 @@

Vectors

you may refer to its components as a.x, a.y, and a.z. To add two vectors, a and b, however, you do not need to add the components one by one; VPython will do the vector addition for you:

-

a = vector(1,2,3)
+

a = vector(1,2,3) # can also be written briefly as vec(1,2,3)
b = vector(4,5,6)
c = a+b

If you include print(c), you will see that - it is a vector with components (5, 7, 9.).

+ it is a vector with components <5, 7, 9>.

Scalar multiplication

-

d = 3*a # d is a vector with components (3, 6, 9)

+

d = 3*a # d is a vector with components <3, 6, 9>

Vector magnitude

-

s = mag(c) # s is a scalar
- z = mag(c)**2 # you can square the magnitude of a vector

+

s = mag(c)    # s is a scalar magnitude
+ z = mag(c)**2 # square the magnitude of the vector; ** means "to the power of"

Vector products

f = cross(a,b) # cross product
- g = dot(a,b) # dot product
- h = norm(a) # normalized (unit) vector; a/mag(a)

+ g = dot(a,b)   # dot product
+ h = norm(a)    # normalized (unit) vector; a/mag(a); same as hat(a) or a.hat

The attributes of VPython objects can be vectors, such as velocity or momentum.

@@ -133,24 +134,23 @@

III. Simple Python ProgrammingUsing the 3D Graphics Module

-

The necessary first line of your program is created for you, and looks like this, if the current version is 1.1:

-

GlowScript 1.1 VPython

+

The necessary first line of your program is created for you, and looks like this, if the current version is 3.0:

+

GlowScript 3.0 VPython

Comments

A comment in a Python program starts with "#"

-

# this line is a comment

+

# This line is a comment

Variables

Variables can be created anywhere in a Python program, simply by assigning a variable name to a value. The type of the variable is determined by the assignment statement.

-

a = 3 # an integer
- b = -2.5 # a floating-point number
+

a = 3                      # an integer
+ b = -2.4                   # a floating-point number
c = vector(0.4, 3e3, -1e1) # a vector
- Earth = sphere(pos=vector(0,0,0),
-             radius=6.4e6) # a 3D object
+ Earth = sphere(pos=vector(0,0,0), radius=6.4e6) # a 3D object
bodies = [ship, Earth, Moon] - # a list of objects

+                    # a list of objects

Basic VPython objects such as sphere() and box() have a set of "attributes" such as color, and you can define additional attributes @@ -224,8 +224,9 @@

Lists

angles = arange (0, 2*pi, pi/100)
# from 0 to 2*pi-(pi/100) in steps of (pi/100)

- numbers = arange(10) # integer argument -> integers
- print(numbers) # [0,1,2,3,4,5,6,7,8,9]

+ numbers = arange(5)
+ for i in numbers:
+    print(i) # prints 0, 1, 2, 3, 4

Loops

The simplest loop in Python is a "while" loop. The loop continues as long as the specified logical expression is true (note the obligatory indentation):

@@ -257,13 +258,14 @@

Printing results

print(Europa.momentum)

To print a text message, enclose it in quotes:

print("We crashed with speed", v, "m/s.")

-

This could also be done like this:

-

print("We crashed with speed {} m/s.".format(v))

+

This could also be done like this (note the initial "f" that makes this work):

+

print(f"We crashed with speed {v} m/s.")

More Information about Python

We have summarized a small but important subset of the Python programming language. Extensive Python information is available on the internet.

+

 

- +
diff --git a/docs/VPythonDocs/VisualRef.css b/docs/VPythonDocs/VisualRef.css index 1995c406..0e39fc17 100644 --- a/docs/VPythonDocs/VisualRef.css +++ b/docs/VPythonDocs/VisualRef.css @@ -1,5 +1,5 @@ a:link, a:visited, a:hover { - color: #006699; + color: #0066dd; text-decoration: none; } a:hover { diff --git a/docs/VPythonDocs/arrow.html b/docs/VPythonDocs/arrow.html index f655e188..0ff691d7 100644 --- a/docs/VPythonDocs/arrow.html +++ b/docs/VPythonDocs/arrow.html @@ -30,10 +30,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/box.html b/docs/VPythonDocs/box.html index 1a952245..79b15178 100644 --- a/docs/VPythonDocs/box.html +++ b/docs/VPythonDocs/box.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/canvas.html b/docs/VPythonDocs/canvas.html index 8daeecf5..56f7f5ad 100644 --- a/docs/VPythonDocs/canvas.html +++ b/docs/VPythonDocs/canvas.html @@ -19,10 +19,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/clone.html b/docs/VPythonDocs/clone.html index 20c30ae6..4d564cf3 100644 --- a/docs/VPythonDocs/clone.html +++ b/docs/VPythonDocs/clone.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/color.html b/docs/VPythonDocs/color.html index 352e6cdf..45ce5055 100644 --- a/docs/VPythonDocs/color.html +++ b/docs/VPythonDocs/color.html @@ -25,10 +25,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/compound.html b/docs/VPythonDocs/compound.html index 6d410da5..dc5e6456 100644 --- a/docs/VPythonDocs/compound.html +++ b/docs/VPythonDocs/compound.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/compound2.1.html b/docs/VPythonDocs/compound2.1.html index fcf0646d..4a9a4c39 100644 --- a/docs/VPythonDocs/compound2.1.html +++ b/docs/VPythonDocs/compound2.1.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/cone.html b/docs/VPythonDocs/cone.html index cc20e50a..72890434 100644 --- a/docs/VPythonDocs/cone.html +++ b/docs/VPythonDocs/cone.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/controls.html b/docs/VPythonDocs/controls.html index 5a0b0bda..fc8be9f8 100644 --- a/docs/VPythonDocs/controls.html +++ b/docs/VPythonDocs/controls.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/curve.html b/docs/VPythonDocs/curve.html index 81a85220..4f4155c5 100644 --- a/docs/VPythonDocs/curve.html +++ b/docs/VPythonDocs/curve.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/cylinder.html b/docs/VPythonDocs/cylinder.html index 21f3f23c..1467fc49 100644 --- a/docs/VPythonDocs/cylinder.html +++ b/docs/VPythonDocs/cylinder.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
@@ -43,8 +44,9 @@

Studying this description of the cylinder object provides an overview of important aspects common to all of the VPython 3D objects, box, sphere, pyramid, etc. Additional details about how to orient an object using "axis" and "up" are found in the description of the box object.

+

This documentation explains how to use GlowScript VPython. If you prefer to write programs in JavaScript, see this document.

cylinder Here is an example - of how to make a cylinder, naming it "rod" for future reference:

+ of how to make a cylinder, naming it "rod" for future reference:

rod = cylinder(pos=vector(0,2,1),         axis=vector(5,0,0), radius=1)

The center of one end of this cylinder is at x=0, y=2, diff --git a/docs/VPythonDocs/defaults.html b/docs/VPythonDocs/defaults.html index 4624aa35..a6ad3aa1 100644 --- a/docs/VPythonDocs/defaults.html +++ b/docs/VPythonDocs/defaults.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/delete.html b/docs/VPythonDocs/delete.html index 48e68075..948ba9b9 100644 --- a/docs/VPythonDocs/delete.html +++ b/docs/VPythonDocs/delete.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/ellipsoid.html b/docs/VPythonDocs/ellipsoid.html index 410903f4..cdb78cda 100644 --- a/docs/VPythonDocs/ellipsoid.html +++ b/docs/VPythonDocs/ellipsoid.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/experienced.html b/docs/VPythonDocs/experienced.html new file mode 100644 index 00000000..596ae511 --- /dev/null +++ b/docs/VPythonDocs/experienced.html @@ -0,0 +1,74 @@ + + + +VPython Help + + + + + + + + +
+
+

  Home

+

  If you're new to Python
+   and VPython: Introduction

+

  A VPython tutorial

+

  Introductory Videos

+

  Pictures of 3D objects

+

  

+

  

+

  

+

  VPython 7 web site
+   VPython license
+
+

+ +
+ +
+ +
+

For those with Python and/or previous VPython experience

+
+
+

As a convenience to novice programmers to provide everything that is needed to get started, VPython by default imports all of the VPython features and includes standard math functions such as sqrt. The documentation is written as though "from vpython import *" were present. Also provided are clock(), random(), and arange(), and range() is like arange(); it accepts floating-point arguments.

+

You can however import selectively, as shown in the following examples, which are compatible with VPython 7. (To help with converting from Classic VPython, VPython 6, you can refer to "vis" or "visual" instead of "vpython".)

+

import vpython
+ import vpython as vp # "vp" is any name of your choice
+ from vpython import box, color

+

When using the form "from vpython import .....", if canvas is not specified, it is added, as GlowScript VPython cannot run without canvas.

+

 

+

For those who have used Classic VPython

+

A few Classic VPython objects are not currently available in VPython: convex, faces, and frame. The objects vertex, triangle, and quad represent a more powerful alternative to faces. Many applications of frame can be handled with the compound object.

+

One way to deal with differences is to check the elements of the "version" variable that is available in all versions of VPython:

+

Classic VPython:    version is ['X.Y', 'release']
+ GlowScript VPython: version is ['X.Y', 'glowscript']
+ VPython 7:          version is ['X.Y.Z', 'jupyter']
+    and in VPython 7, the version of the GlowScript graphics library
+   is given by GSversion as ['X.Y', 'glowscript']

+

The curve and points objects are somewhat different from Classic VPython. Note that now the list of points in a curve object is not a numpy array, so that a loop is required to change all of the points.

+

To handle mouse events one cannot use scene.getevent() but must use scene.bind(), which is available in all versions of VPython, starting with Classic VPython 6. Also available are scene.pause() and scene.waitfor('click') and related options.

+

In GlowScript VPython it is not possible to import arbitrary Python modules such as numpy, and any program that uses numpy will have to be modifed. However, loops are fast in the JavaScript language to which GlowScript programs compile, so if you are using numpy solely for the speed of array manipulation, you may be able to replace a numpy calculation easily and efficiently with a loop.

+

GlowScript by default processes VPython programs as though they had the following statements at the start of the program (which you don't need to include; they will be ignored):

+

from __future__ import division, print_function
+ from vpython import *

+
+

GlowScript treats 3/2 as 1.5 as in Python 3.x, not 1 as in the Python 2.x language, and the print statement must take the Python 3.x form of print('hello') rather than the Python 2.x form of print 'hello'.

+
+

Many programs written in Classic VPython 6 will run in GlowScript VPython or VPython 7 without change after being run through a conversion program written in Python. This program converts (x,y,z) => vector(x,y,z) and obj.x => obj.pos.x. These changes are necessary because GlowScript does not recognize (x,y,z) as a vector nor obj.x as a shorthand for obj.pos.x. The program also converts display => canvas and gdisplay => graph. The program also converts scene.mouse.getclick() => scene.waitfor('click'), which works in both environments.

+

In GlowScript VPython and VPython 7 you can use the shorthand "vec" for "vector". If you wish to use a GlowScript program containing "vec" in the Classic VPython environment, just add the statement "vec = vector" at the start of the program.

+
+
+ +
+
+ + + diff --git a/docs/VPythonDocs/extrusion.html b/docs/VPythonDocs/extrusion.html index dd0283b8..65380c63 100644 --- a/docs/VPythonDocs/extrusion.html +++ b/docs/VPythonDocs/extrusion.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/extrusion2.1.html b/docs/VPythonDocs/extrusion2.1.html index e8f10de8..c08c2c54 100644 --- a/docs/VPythonDocs/extrusion2.1.html +++ b/docs/VPythonDocs/extrusion2.1.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/factorial.html b/docs/VPythonDocs/factorial.html index d00a689c..0f3ed76e 100644 --- a/docs/VPythonDocs/factorial.html +++ b/docs/VPythonDocs/factorial.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/files.html b/docs/VPythonDocs/files.html index 604dfcfc..bee134af 100644 --- a/docs/VPythonDocs/files.html +++ b/docs/VPythonDocs/files.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/frame.html b/docs/VPythonDocs/frame.html index fa12b73b..94c69938 100644 --- a/docs/VPythonDocs/frame.html +++ b/docs/VPythonDocs/frame.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/graph.html b/docs/VPythonDocs/graph.html index 164b46f8..7262aa31 100644 --- a/docs/VPythonDocs/graph.html +++ b/docs/VPythonDocs/graph.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/helix.html b/docs/VPythonDocs/helix.html index 306e3ed1..4b41e332 100644 --- a/docs/VPythonDocs/helix.html +++ b/docs/VPythonDocs/helix.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/history.html b/docs/VPythonDocs/history.html new file mode 100644 index 00000000..91b58071 --- /dev/null +++ b/docs/VPythonDocs/history.html @@ -0,0 +1,124 @@ + + + +VPython Help + + + + + + + + +
+
+

  Home

+

  If you're new to Python
+   and VPython: Introduction

+

  A VPython tutorial

+

  Introductory Videos

+

  Pictures of 3D objects

+

  

+

  

+

  

+

  VPython 7 web site
+   VPython license
+
+

+ +
+ +
+ +
+
+ + + + + +
Log of major developments
ball in box
+
+
+

Also see "A time line for VPython development". There is also a log of work on the earlier Classic VPython.

+

2020 May 9: GlowScript 3.0
+ Significant improvements in translating VPython to JavaScript with respect to inserting async and await. RapydScript, which was a stepping stone to GlowScript VPython, is not supported in GlowScript 3.0. JavaScript programs now link axis and size, as with VPython, and JavaScript programs need to handle async and await themselves (this is done automatically for VPython programs).

+

2019 Aug. 26: GlowScript 2.9
+The Streamline library is eliminated thanks to the new "async" and "await" options in JavaScript; compilation is now about 6 times faster. Can now put waiting functions such as pause, waitfor, sleep, and rate in functions that are bound to events. A new input() function mimics that of Python, and the winput function is enhanced to permit use without binding to a function, and to provide a prompt for the user. It is now possible for a program to trigger an event to be processed by a bound function. There is no longer any need to avoid naming an object "wait", which was associated with the use of Streamline.

+

2018 June 20: GlowScript 2.8
+ An update to the Streamline library fixes bugs in complex programs.

+

2018 Jan. 28: GlowScript 2.7
+ Now two graphing packages + are available, a somewhat improved version based on Flot (fast=True), and a new version based on Plotly (fast=False). The Plotly version offers powerful interactivity for the viewer but is significantly slower than the Flot version.

+

2017 Oct. 11 Provide clear error messages for scalar/vector errors.

+

2017 Sept. 7 Make it again possible to put pause() etc. inside functions.

+

2017 July 31: GlowScript 2.6
+ Significant fixes to cloning and to the 3D text object. Adam Thompson implemented being able to resize a canvas, either by resetting width and/or height, or by user dragging. Andrew Morrison improved graph xtitle and ytitle to appear below and to the left of the graph rather than above the graph. GlowScript 2.6 incorporates an update by Kovid Goyal to RapydScript-NG to support class variables (that is, variables that are shared by all instances of the class).

+

2017 June 11: GlowScript 2.5
+ Fix a bug in extrusion object that removed the last element in a user-supplied shape. The version number had to be incremented to 2.5 because some existing 2.4 programs might fail.

+

2017 Feb. 2: GlowScript 2.4
+ Fix a long-standing error in changing axis without updating up to remain perpendicular to axis (and vice versa). The result was that rotating an object by continually changing its axis could cause abrupt changes in the appearance of the object which were only noticeable if there was a texture or a compound object that lacked symmetry.

+

2017 Jan. 4: GlowScript 2.3
+ Replaced the original RapydScript Python-to-JavaScript compiler with RapydScript-NG by Kovid Goyal, which comes closer to supporting true Python syntax and also provides Python string methods such as lower() and upper() and split().

+

2016 Nov. 12: GlowScript 2.2
+ Improved extrusion and compound objects. They now have pos at their centers and size that represents the bounding box. The extrusion path is now specified by "path", making it possible to specify "pos" as the location of the center of the extrusion's bounding box.

+

 

+

2016 Aug. 22: Much more powerful version of the extrusion object, with full shapes and paths libraries. Also added text to radio buttons and check boxes.

+

2016 Aug. 4: Widgets implemented -- button, radio button, check box, slider, and drop-down menu.

+

2016 July 2: 3D text object implemented, with major contributions by Kadir Haldenbilen.

+

 

+

2016 Feb. 28: GlowScript 2.1
+ Improves and simplifies scene.title and scene.caption. Now you can say scene.title = "Watch the <b>ball</b>" ("ball" will be bold) and scene.caption = "This is what <i>always</i> happens" ("always" will be italic). You can also obtain the current contents for the title (T = scene.title) and caption (C = scene.caption). You can add to existing title or caption with scene.append_to_title(...) or scene.append_to_caption(...).

+

The old forms scene.title.text() and scene.title.html() could be used to specify the title but there wasn't a way to retrieve the current title. You had to decide between text and html, but now it doesn't matter; you always get full HTML capabilities.

+

These changes are not fully compatible with previous versions of GlowScript, which is why the version number has been changed to 2.1, but older versions will continue to work as before. Another reason for the changes has to do with making the Jupyter version of VPython work well.

+

Changes to the use of jQuery: If you use jQuery to display widgets (buttons, sliders, menus), see this documentation on changes to how to reference the title, caption, and print regions of the page.

+

2016 Jan. 24: GlowScript 2.0
+ * Fixes a serious problem in make_trail, that long trails were very slow. New trail-related features: trail_color, trail_radius, pps (points per second), clear() which deletes existing points. Setting make_trail False stops leaving a trail; setting make_trail True turns the trail on again, without drawing an undesirable line between the stop and start points.
+
+ * + If v is a vector, v.mag() must now be written as v.mag and v.mag2() must now be written as v.mag2. The older form was a mistake and is incompatible with the new Jupyter version of VPython.
+
+ * display should be written as canvas; gdisplay as graph. The older names still work at present but are incompatible with the new Jupyter version of VPython.
+
+ * The list of positions in a curve named c cannot be referenced directly as c.pos. If the curve is named c and N is the nth point in the curve, c.point(N) returns {pos:p, color:col, radius:r, visible:v}. To change the nth point, use c.modify(N, pos=p, color=col, radius=r, visible=v). See the documentation for the curve object for the full list of methods available for accessing or changing an existing curve.
+
+ * + The points object has a radius, not a size (size was a scalar and confusing given that size is a vector elsewhere; size_units can still be used to specify whether the radius is in pixels or real-world measure).
+
+ * Because it is hardly being used, CoffeeScript is not supported in GlowScript 2.0. It can still be used with "GlowScript 1.1 CoffeeScript".
+
+ * Here is a description of the plan for future development of VPython.

+

 

+

2015 Dec. 21: Update of files that permit operator overloading (being able to add two vectors a and b simply as a+b) and the ability to use synchronous code (such as infinite loops) thanks to files supplied by Salvatore di Dio. Changes to Firefox made this update necessary. An added bonus was that GlowScript now runs on Internet Explorer and Edge.

+

2015 Oct. 18: Implement display.delete(), gdisplay.delete(), and the ability to delete a set of data from a graph. Add to the make_trail machinery the ability to set trail_color and trail_radius without having to reference trail_object.

+

2015 Oct. 15: scene.mouse.pos now always contains the up-to-date mouse information, which makes it possible to drag objects with the mouse buttons up.

+

2015 Sept. 19: Implement the standard Python string.format mechanism.

+

2015 August 27: Improve sphere and curve rendering; provide textures.earth.

+

2015 August 2: Implement simple editor as alternative to the ACE editor, so that it is now possible to edit programs on mobile devices.

+

2015 June 23: Implement Python-style string formatting.

+

2015 June 3: Ring is now a regular primitive and supports transparency.

+

2015 April 21: Add factorial and combin functions.

+

2015 Feb. 22: Enable transparency on mobile devices.

+

2015 Jan. 20: Support touch inputs on touch-sensitive devices.

+

2014 November 17: Updated GlowScript 1.1 to fix a problem with JavaScript programs. This also introduces the ability to handle programs written in classic VPython, with some restrictions; see the VPython Help. There are new vector capabilities such as dot(A,B), equivalent to A.dot(B). The curve object now has an attribute "origin" for moving the entire curve, relative to this origin.

+

2014 October 25: Released GlowScript 1.1. Support added for RapydScript, a Python look-alike, with much help from Alexander Tsepkov, Charles Law, and Salvatore di Dio. CoffeScript compiler updated, which among other things means that 3**4 now equals 81. Also, jquery and jquery-ui updated thanks to the work of Adam Thompson, who also added the ability to place print output to the right of the canvas and improved resizing of a canvas.

+

2012 October 10: Textures can now use images from other ("CORS-enabled") web sites. GlowScript programs run well on the latest version of Firefox for Android (smartphones and tablets), though you can't yet rotate the camera, and transparency is buggy.

+

2012 September 12: Add functions compound_to_world, world_to_compound, pixel_to_world, print, print_options, get_library, and read_local_file. Improve rate behavior for high rate values.

+

2012 August 21: Updated Version 1.0 to improve error reporting for both JavaScript and CoffeeScript programs, and to improve editing of CoffeeScript programs. Added to the Help sections on text output for debugging, and how to run GlowScript in the absence of an internet connection.

+

2012 May 30: Version 1.0 implements triangles and quads, based on vertex objects, which make it possible to design your own objects and even change their shape dynamically. Also new are compound (groups of objects that can be manipulated as though they were one object) and clone (make a copy of an existing object). David Scherer made major contributions to the design of these new features. Also, the curve object now permits rapid change of position, size, and orientation, and the array scene.objects now includes label objects.

+

2012 April 21: Now in version 0.7 you can write your program in CoffeeScript as well as in JavaScript. See the home page for details.

+

2012 March 27: Transparency added to version 0.7. You can set the opacity of an object, with default = 1 (fully opaque); 0 is completely transparent.

+

2012 Jan. 29: Release GlowScript version 0.7. The major new capability is textures, including bump maps (normal maps), for objects other than curves (and the curve-like objects helix and ring). Other new features include shininess, emissive, and scene.visible. Changes were made to require named arguments for object.rotate, vector.rotate, local and distant lights, and scene.mouse.project. Improved glowscript.org front page thanks to Tim Sherwood.

+

May/June 2011: David Scherer and Bruce Sherwood begin collaborating on implementing GlowScript, patterned on VPython but running in a web browser, exploiting the the new JavaScript/WebGL environment.

+

 

+
+
+ +
+
+ + + diff --git a/docs/GlowScriptDocs/images/bounce2.jpg b/docs/VPythonDocs/images/bounce2.jpg similarity index 100% rename from docs/GlowScriptDocs/images/bounce2.jpg rename to docs/VPythonDocs/images/bounce2.jpg diff --git a/docs/GlowScriptDocs/images/cover.jpg b/docs/VPythonDocs/images/cover.jpg similarity index 100% rename from docs/GlowScriptDocs/images/cover.jpg rename to docs/VPythonDocs/images/cover.jpg diff --git a/docs/VPythonDocs/index.html b/docs/VPythonDocs/index.html index 0f3587bc..6fb69e46 100644 --- a/docs/VPythonDocs/index.html +++ b/docs/VPythonDocs/index.html @@ -59,10 +59,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
@@ -77,9 +78,10 @@

Using VPython to create 3D animations

-

VPython makes it unusually easy to write programs that generate navigable real-time 3D animations. It is based on the Python programming language which is widely used in introductory programming courses thanks to its clean design, and it is also widely used in science and business. At glowscript.org, click "Example programs" to see how VPython is used. Here is an 8-minute introduction to VPython by Bruce Sherwood: tinyurl.com/VPintro

+

VPython makes it unusually easy to write programs that generate navigable real-time 3D animations. It is based on the Python programming language which is widely used in introductory programming courses thanks to its clean design, and it is also widely used in science and business. At glowscript.org, click "Example programs" to see how VPython is used. tinyurl.com/VPintro is an 8-minute introduction to VPython by Bruce Sherwood. No software installation is required to use GlowScript VPython, as it runs in your browser. One can also use VPython with installed Python ("VPython 7").

+

This documentation is written in terms of Python syntax, because almost all GlowScript users write their programs using Python, but one can also write GlowScript programs in JavaScript. This article explains how to interpret the documentation for use in JavaScript programs.

On the left is complete documentation for VPython.

-

For a quick introduction, see the following YouTube videos, but be aware that for the current version of VPython the name of the module is "vpython", not "visual", and the graphics display is shown in a browser tab rather than in a bare window. (For GlowScript VPython, you can omit importing vpython.)

+

For a quick introduction, see the following YouTube videos, but when viewing the English-language videos be aware that for the current version of VPython the name of the module is "vpython", not "visual", and the graphics display is shown in a browser tab rather than in a bare window. (Also, for GlowScript VPython, you can omit importing vpython.)

3D Objects (Spanish version Objetos 3D by Javier Carro)

Variable Assignment (Spanish version Asignación de Variables by Javier Carro)

@@ -90,98 +92,63 @@

Lists, Part 1 (Spanish verstion Listas 1 by Javier Carro)

Lists, Part 2

-

Classic VPython was originated by David Scherer in 2000. In 2011 David Scherer and Bruce Sherwood initiated the development of GlowScript, a similar programming environment but which runs in a browser. In 2014 it became possible to use RapydScript, a programming language very similar to Python, to support VPython programs in the GlowScript environment.

-

Here is an overview of the project, and here is a log of developments. Here is the open source for this project. There is also technical documentation about the GlowScript environment, including how to use JavaScript or RapydScript for your programs.

-

There is also VPython 7 originated by John Coady in 2014 and under continuing development by John Coady, Ruth Chabay, Bruce Sherwood, Steve Spicklemire, and Matt Craig. It uses GlowScript VPython syntax but with standard Python, thereby providing access to standard Python modules. For details see vpython.org. Also of interest is a discussion about plans for the future evolution of VPython.

-

This - documentation describes both GlowScript VPython and VPython 7.

-

There is a series of GlowScript VPython tutorials by Rhett Allain in the context of predicting motion computationally, at the level of an introductory physics course. Using tools at trinket.io it is easy to add both editing and execution of GlowScript VPython to your own web pages, and Allain in his physics blog for Wired magazine has shown examples of this.

-

 

+

There is a series of GlowScript VPython tutorials by Rhett Allain in the context of predicting motion computationally, at the level of an introductory physics course. His tutorials use tools at trinket.io that embed writing and running GlowScript VPython programs in a notebook-like environment. It is easy to use Trinkets to add both editing and execution of GlowScript VPython to your own web pages, and Allain in his physics blog for Wired magazine has shown examples of this.

+

+

Getting started

To write a VPython program, sign in at glowscript.org. It is recommended to use the Chrome or Edge browser, as they provide the most useful error messages, though programs can be written and run in all browsers, including on smartphones and tablets. In some cases program errors are visible only if you press Shift-Ctrl-J to display the browser console.

* You will see the sentence "You are signed in as <your user name> and your programs are here." Click on here.

* Click Create New Program, which will create a new program in your MyPrograms folder. (Programs in your Private folder are not accessible to others.) Choose a name for the program, which should not include spaces or underscores.

-

* Below the line GlowScript 2.8 VPython, type box(). Click Run this program to run your program. You will see a white box on a black background.

+

* Below the line GlowScript 3.0 VPython, type box(). Click Run this program to run your program. You will see a white box on a black background.

* Use the right button (or CTRL-drag left button) of the mouse to rotate the camera to view the scene from different angles.

-

* To zoom in and out use two buttons, or ALT/OPTION-drag, or the mouse scrollwheel. Touch screen: swipe or two-finger rotate; pinch/extend to zoom.
-

+

* To zoom in and out use two buttons, or ALT/OPTION-drag, or the mouse scrollwheel. Touch screen: swipe or two-finger rotate; pinch/extend to zoom.

+

* To pan lef/right or up/down, drag the mouse with the SHIFT key held down.

Using the text editor

Here is a list of keyboard shortcuts for find, replace, etc. While editing, press Ctrl-1 (Cmd-1 on Mac) to run your program in the same window. Press Ctrl-2 (Cmd-2 on Mac) to run your program in a separate window, which lets you view your program and its execution side by side. If you change your program, press Ctrl-2 again in the editor display to re-run the program with the new changes. GlowScript uses the ACE text editor. Because ACE doesn't work on mobile devices, a simpler editor is used there.

-

A particularly useful shortcut is Ctrl-/ (Cmd-/ on Mac). Select one or more lines in your program and use this keypress to toggle whether those lines are commented out or not. Also, select one or more lines and press Tab to indent or Shift-Tab to unindent.

-

 

-

Letting others run your programs

+

A particularly useful shortcut is Ctrl-/ (Cmd-/ on Mac). Select one or more lines in your program and use this keypress to toggle whether those lines are commented in or out. Also, select one or more lines and press Tab to indent or Shift-Tab to unindent.

+

Letting others run your programs

While viewing the text of your program, click Share this program to see how to let other people run your program. For people to run your program by linking to it, the program must be in a public folder or be exported to your own web site. In fact, the code available on the share page can simply be pasted into a file and saved with the extension ".html", and then you can run the program simply by doubleclicking the html file.

 

-
+

Descriptions of the options available in the left margin

Introduction: The basics of Python and VPython.

-

Tutorial: More on VPython, +

A VPython tutorial: More on VPython, including making an animation

+

Introductory Videos: The videos listed above, easily accessible from throughout the Help

Pictures of 3D objects: What the objects look like

Choose a 3D object: Details of cylinder, box, etc. Start with cylinder for an overview.

-

Work with 3D objects: Issues that apply to all 3D objects: color, material, etc.

-

Windows, Events, & Files: Creating/modifying - windows; handling mouse/ keyboard events; reading/writing files

-

Vector operations: Magnitude, dot and cross product, rotation, etc.

-

Graphs: Making graphs of data.

-

factorial/combin: Special functions used in probability calculations.

-

What's new: VPython in GlowScript, plus the history of VPython..

+

Work with 3D objects: Issues that apply to all 3D objects: color, material, etc. Key elements include these:

+

    Vector operations: Magnitude, dot and cross product, rotation, etc.

+

    Graphs: Making graphs of data.

+

    Math functions: Includes factorial/combin statistics functions

+

Canvases/Events: Creating/modifying + windows; handling mouse/ keyboard events

-

Be sure to explore the many GlowScript example programs, written using JavaScript, RapydScript, or VPython. The VPython option is based on the RapydScript-NG Python-to-JavaScript compiler. For most programs, RapydScript is nearly the same as Python, but there are differences which can be seen in the RapydScript-NG documentation.

-

In general, Python modules cannot be imported into VPython programs, because GlowScript VPython functions in a JavaScript environment. However, one can import the Python "random" module into a VPython program, provided by the RapydScript-NG tool that converts Python to JavaScript. One cannot use the form "from random import *" but must use "import random" or "import random as rr" (or other name) or "from random import randint, random" (or other list of functions).

+

Be sure to explore the many GlowScript example programs, written using Python or JavaScript. The VPython option is based on the RapydScript-NG Python-to-JavaScript compiler.

+

As mentioned earlier, trinket.io offers another environment for writing GlowScript VPython programs. Click "New Trinket", then choose "GlowScript" and pick Python for normal text editing or Blocks for prompted editing.

+

In general, Python modules cannot be imported into GlowScript VPython programs because they function in a JavaScript environment. However, one can import the Python "random" module into a VPython program, provided by the RapydScript-NG tool that converts Python to JavaScript. One cannot use the form "from random import *" but must use "import random" or "import random as rr" (or other name) or "from random import randint, random" (or other list of functions). Not all of the functions provided by the Python random module are available.

 

-

CAUTION

-

Do not use "wait" or "_" as a variable name. All GlowScript languages (VPython, RapydScrpt, JavaScript) use "wait" or "_" as a special signal for the compilation process. This signal is inserted for you where needed.

+

For those with Python and/or previous VPython experience

+

If you are an experienced Python programmer and/or have extensive experience with older "Classic VPython" (VPython 6 or earlier), do read this article on the differences.

 

-

For experienced programmers

-

As a convenience to novice programmers to provide everything that is needed to get started, VPython by default imports all of the VPython features and includes standard math functions such as sqrt. The documentation is written as though "from vpython import *" were present. Also provided are clock(), random(), and arange().

-

You can however import selectively, as shown in the following examples, which are compatible with VPython 7. (To help with converting from Classic VPython, VPython 6, you can refer to "vis" or "visual" instead of "vpython".)

-

import vpython
- import vpython as vp # "vp" is any name of your choice
- from vpython import box, color

-

When using the form "from vpython import .....", if canvas is not specified, it is added, as GlowScript VPython cannot run without canvas.

+

Using GlowScript without an internet connection; use by developers

+

There is an article that explains how to use GlowScript without an internet connection, including information for how developers can use this capability.

 

-
-

For those who have used Classic VPython

-

A few Classic VPython objects are not currently available in VPython: convex, faces, and frame. The objects vertex, triangle, and quad represent a more powerful alternative to faces. Many applications of frame can be handled with the compound object.

-

One way to deal with differences is to check the elements of the "version" variable that is available in all versions of VPython:

-

Classic VPython:    version is ['X.Y', 'release']
- GlowScript VPython: version is ['X.Y', 'glowscript']
- VPython 7:          version is ['X.Y.Z', 'jupyter']
- and in VPython 7, the version of the GlowScript
- graphics library is given by
-                  GSversion is ['X.Y', 'glowscript']

-

The curve and points objects are somewhat different from Classic VPython. Note that now the list of points in a curve object is not a numpy array, so that a loop is required to change all of the points.

-

To handle mouse events one cannot use scene.getevent() but must use scene.bind(), which is available in all versions of VPython, starting with Classic VPython 6. Also available are scene.pause() and scene.waitfor('click') and related options.

-

In GlowScript VPython it is not possible to import arbitrary Python modules such as numpy, and any program that uses numpy will have to be modifed. However, loops are fast in the JavaScript language to which GlowScript programs compile, so if you are using numpy solely for the speed of array manipulation, you may be able to replace a numpy calculation easily and efficiently with a loop.

-

The difference between RapydScript and VPython programs in the GlowScript context is that the VPython option mimics important elements of the syntax and semantics of Classic VPython programs, whereas the RapydScript option implements the same semantics for 3D objects as that of JavaScript programs. For example, in a RapydScript program the sphere object has a size attribute but no radius attribute, and like box, the default bounding box of the sphere is 1x1x1. Also, changing the length of the axis in a RapydScript program has no effect on the size (except for an arrow, which has a special axis_and_length attribute), but in a VPython program, as in Classic VPython, changing the length of the axis also changes the length of the object (the first component of the object's size).

-

GlowScript by default processes VPython programs as though they had the following statements at the start of the program (which you don't need to include; they will be ignored):

-

from __future__ import division, print_function
- from vpython import *

-
-

GlowScript treats 3/2 as 1.5 as in Python 3.x, not 1 as in the Python 2.x language, and the print statement must take the Python 3.x form of print('hello') rather than the Python 2.x form of print 'hello'.

-
-

Many programs written in Classic VPython 6 will run in GlowScript VPython or VPython 7 without change after being run through a conversion program written in Python. This program converts (x,y,z) => vector(x,y,z) and obj.x => obj.pos.x. These changes are necessary because GlowScript does not recognize (x,y,z) as a vector nor obj.x as a shorthand for obj.pos.x. The program also converts display => canvas and gdisplay => graph. The program also converts scene.mouse.getclick() => scene.waitfor('click'), which works in both environments.

-

In GlowScript VPython and VPython 7 you can use the shorthand "vec" for "vector". If you wish to use a GlowScript program containing "vec" in the Classic VPython environment, just add the statement "vec = vector" at the start of the program.

+

The Architecture of GlowScript

+

Here is a brief overview of the GlowScript architecture. Much more extensive technical details of the GlowScript architecture are available here, which includes a video of a workshop on the topic.There is also an article that describes how pixel-level transparency and mouse picking were implemented.

+

 

+

Brief history

+

VPython was originated by David Scherer in 2000. In 2011 David Scherer and Bruce Sherwood initiated the development of GlowScript, a similar programming environment but which runs in a browser. Originally, programs had to be written in JavaScript, but in 2014 it became possible to use Python; currently GlowScript programs can be written either in Python or in JavaScript. Here is a log of major developments and here is the open source for this project. There is a blog article "A time line for VPython development". Bruce Sherwood is the lead developer.

+

VPython can also be used with installed Python, thanks to work originated by John Coady in 2014 and under continuing development by John Coady, Ruth Chabay, Bruce Sherwood, Steve Spicklemire, and Matt Craig. It uses GlowScript VPython syntax but with standard Python, thereby providing access to standard Python modules. This flavor of VPython is called "VPython 7". For details see vpython.org. This documentation is valid for both GlowScript VPython (browser-based) and for VPython 7 (installed Python).

 

Credits

-

Salvatore di Dio demonstrated in his RapydGlow experiment
-     (http://salvatore.pythonanywhere.com/RapydGlow)
- how he was able to use the RapydScript Python-to-JavaScript compiler with GlowScript graphics. This inspired the implementation of the VPython (vpython.org) API at glowscript.org. He provided the file papercomp.js for operator overloading, based on the work of
-     Jürg Lehni (PaperScript: http://scratchdisk.com/posts/operator-overloading).
- He also assembled support for operator overloading and the ability to write synchronous code in the file transform-all.js, based on the work of
-     Bruno Jouhier (Streamline: https://github.com/Sage/streamlinejs), and
-     Marijn Haverbeke (Acorn.js: https://github.com/marijnh).
- Supporting the VPython API in a browser is possible thanks to the work of
-     Alexander Tsepkov (RapydScript: https://github.com/atsepkov/RapydScript) and
-     Charles Law (browser-based RapydScript: https://github.com/charleslaw/RapydScript_web).

-

In January 2017 the original RapydScript compiler was replaced with RapydScript-NG by Kovid Goyal, which comes closer to handling true Python syntax.

-

When the GlowScript project was launched in 2011 by David Scherer and Bruce Sherwood,
-Scherer implemented operator overloading and synchronous code using libraries existing at that time. In 2015 it became necessary to upgrade to newer libraries because compilation failed on some browsers; Salvatore di Dio provided crucial help in this update. In January 2017 the operator overloading machinery was further updated.

+

Salvatore di Dio demonstrated in his RapydGlow experiment http://salvatore.pythonanywhere.com/RapydGlow how he was able to use the RapydScript Python-to-JavaScript compiler with GlowScript graphics. This inspired the implementation of the VPython (vpython.org) API at glowscript.org. He provided the file papercomp.js for operator overloading, based on the work of Jürg Lehni (PaperScript: http://scratchdisk.com/posts/operator-overloading. He also assembled support for operator overloading and the ability to write synchronous code in the file transform-all.js, based on the work of Bruno Jouhier (Streamline: https://github.com/Sage/streamlinejs), and Marijn Haverbeke (Acorn.js: https://github.com/marijnh). Supporting the VPython API in a browser is possible thanks to the work of Alexander Tsepkov (RapydScript: https://github.com/atsepkov/RapydScript) and Charles Law (browser-based RapydScript: https://github.com/charleslaw/RapydScript_web).

+

In January 2017 the original RapydScript compiler was replaced with RapydScript-NG by Kovid Goyal, which comes closer to handling true Python syntax. Goyal has been exceptionally supportive, often fixing a reported bug within just a few hours. He is also the developer of Calibre, a widely used tool for converting among ebook formats.

+

When the GlowScript project was launched in 2011 by David Scherer and Bruce Sherwood, Scherer implemented operator overloading and synchronous code using libraries existing at that time. In 2015 it became necessary to upgrade to newer libraries because compilation failed on some browsers; Salvatore di Dio provided crucial help in this update. In January 2017 the operator overloading machinery was further updated.

 

VPython documentation was produced by Ruth Chabay, diff --git a/docs/VPythonDocs/keyboard.html b/docs/VPythonDocs/keyboard.html index 5f434f04..90cad97f 100644 --- a/docs/VPythonDocs/keyboard.html +++ b/docs/VPythonDocs/keyboard.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/label.html b/docs/VPythonDocs/label.html index 1ff44ece..e1289088 100644 --- a/docs/VPythonDocs/label.html +++ b/docs/VPythonDocs/label.html @@ -37,10 +37,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/license.txt b/docs/VPythonDocs/license.txt index abd319fa..8ef65c2b 100644 --- a/docs/VPythonDocs/license.txt +++ b/docs/VPythonDocs/license.txt @@ -35,6 +35,7 @@ in the file transform-all.js, based on the work of Supporting the VPython API in a browser is possible thanks to the work of Alexander Tsepkov (RapydScript: https://bitbucket.org/pyjeon/rapydscript) and Charles Law (browser-based RapydScript: http://pyjeon.pythonanywhere.com/static/rapydscript_online/index.html). + Kovid Goyal (RapdScript-NG) RapydScript-NG: https://github.com/kovidgoyal/rapydscript-ng When the GlowScript project was launched in 2011 by David Scherer and Bruce Sherwood, Scherer implemented operator overloading and synchronous code using libraries existing at that time. @@ -46,3 +47,29 @@ For explanation of poly2tri, see http://sites-final.uclouvain.be/mema/Poly2Tri Font manipulation: https://github.com/nodebox/opentype.js Public-domain sans serif font Roboto-Medium.ttf from http://www.1001freefonts.com/roboto.font Public-domain serif font NimbusRomNo9L-Med.otf from http://www.1001fonts.com/nimbus-roman-no9-l-font.html + +Information about RapydScript and RapydScript-NG: +Copyright (c) 2015-, Kovid Goyal +Copyright (c) 2013-2014, Alexander Tsepkov +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 THE COPYRIGHT HOLDER 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. \ No newline at end of file diff --git a/docs/VPythonDocs/lights.html b/docs/VPythonDocs/lights.html index 4fc6c973..45708f09 100644 --- a/docs/VPythonDocs/lights.html +++ b/docs/VPythonDocs/lights.html @@ -33,10 +33,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/local.html b/docs/VPythonDocs/local.html new file mode 100644 index 00000000..79012fe5 --- /dev/null +++ b/docs/VPythonDocs/local.html @@ -0,0 +1,117 @@ + + + +VPython Help + + + + + + + + +
+
+

  Home

+

  If you're new to Python
+   and VPython: Introduction

+

  A VPython tutorial

+

  Introductory Videos

+

  Pictures of 3D objects

+

  

+

  

+

  

+

  VPython 7 web site
+   VPython license
+
+

+ +
+ +
+ +
+
+

Running locally, plus information for developers

+
+
+

When internet access is missing or poor, you may find it useful to run locally, independent of the internet. At vpython.org, in the section on using VPython without installing software, see the instructions for how to use GlowScript without an internet connection. Before going offline, use the download options at glowscript.org to get local copies of your programs.

+

Another option is to install Python and the VPython 7 module. At vpython.org see the section on using VPython with installed Python. As long as you don't import Python modules other than vpython, you will also be able to run the program at glowscript.org without having to make changes.

+

Yet another option is to follow the instructions below. Even if you do not wish to help develop VPython, you might want to install the GlowScript machinery on your computer, to be able to use it without access to the internet.

+

 

+

For developers
+ If you want to be able to contribute to developing GlowScript, here are the (rather complex) steps required to be able to run locally with changes that you make to the GlowScript code, almost all of which is written in JavaScript (there is also some Python server code and some html code). An excellent, up to date textbook on JavaScript is available at javascript.info.

+

(1) Watch a YouTube overview of the VPython architecture:
+     tinyurl.com/GSarchitecture
+ At a later time you should also study this document:
+     GlowScriptOverview.md

+

(2) Download the GlowScript source files
+ At the glowscript repository on GitHub, https://github.com/vpython/glowscript, click "Clone or download" and then clone the repository, or click on "Download ZIP" and unpack the contents of the glowscript-master folder into a new local folder named glowscript.

+

(3) Install the Google Cloud SDK for Python
+ At developers.google.com/appengine/downloads choose Standard environment Python for your platform. Next, if you have not already installed the Google Cloud SDK ("Software Development Kit"), do this:
+ 1) + Click the Download button for "Install and initialize Google Cloud SDK" and then click "Cloud SDK installer". Run this installer, which will install a Python 2.7 (which is required by the Google software) unless you uncheck "Bundled Python". Let it execute "gcloud init" for you.
+ 3) + In a command-line terminal, execute the following statement (on Mac or Linux, you may need to preface this command with "sudo"):
+     gcloud components install app-engine-python

+

(4) Using gcloud with Google App Engine
+ To run GlowScript, execute
+     dev_appserver.py /..../glowscript/app.yaml
+ where the location of the GlowScript code is at
+     /..../glowscript (on Windows, use backslashes instead of slashes).
+
+ Then start a browser and enter + "localhost:8080" to run GlowScript.
+
+ Alternatively, change directory ("cd") to the glowscript folder you downloaded, and execute
+     dev_appserver.py app.yaml
+
+ More precisely, 8080 is the default port number. At the start of ide/api.py, if the variable "localport" is XXXX instead of 8080, to start up the application you must execute
+      dev_appserver.py --port=XXXX /..../glowscript/app.yaml
+ and the browser must point to "localhost:XXXX".

+

(5) Testing your changes
+ Suppose the current version of GlowScript is 3.0. Change the version number in a program to 3.1dev; that is, 0.1 greater than the current 3.0, plus dev. When you run the program, it will use your latest JavaScript changes. If you make further changes to the JavaScript code, just re-execute a test program to get the latest changes. You don't have to restart the application.
+
+ If you want to remake/update the existing version 3.0, or create a new version 3.1, see MakingNewVersion.txt in the docs folder of the GlowScript GitHub repository. Note that use of the build program requires that there be an appropriate version of node in the build-tools folder.
+
+ It is very useful to insert console.log(....) at critical points in the JavaScript code, which will generate output to the web page that is viewable if you turn on the browser developer console. On Chrome or Edge just press Ctrl-Shift-j.

+

(6) Save your test programs
+ Updates to the Google software can have the effect that you lose the VPython programs you used for testing purposes. On Windows these programs are stored in C:\Users\YourName\AppData\Local\Temp\appengine.glowscript. On Mac, look for datastore.db in /private/var/folders/..... It is highly recommended that you keep a copy of the programs folder before updating the Google software.

+


+

+
+

+

+

Important: The "original App Engine SDK" described below, with its graphical user interface, will no longer be available after July 30, 2020, at which time it will be necessary to use the "gcloud" mechanism documented above.

+

* Install the Google App Engine SDK for Python
+ At developers.google.com/appengine/downloads, download the package for your platform. Choose Standard environment Python, then scroll down and click "Download and install the original App Engine SDK for Python". If using Linux, unpack to a folder whose name will probably be google_appengine.
+

+

* On Windows and Mac, the Google App Engine installer includes an app "Google APP Engine Launcher" which simplifies launching GlowScript.
+
+ On Windows, there will be a Google App Engine Launcher icon on your desktop, or in your Start menu. Run the app.
+
+ On Mac, drag the GoogleAppEngineLauncher out of the installer package (for example, drag it into the Applications folder), then double-click it. When asked, accept the offer to create some symlinks.
+
+ In the Launcher, choose File > Add Existing Application and specify the glowscript folder. Make a note of the Port number. Click Add. In ide/api.py and untrusted/run.js, search for "localhost:" and adjust the port number to the number assigned by the launcher.
+
+ With the glowscript entry selected in the launcher, click the green Run button. When the Browse button lights up, click it, which will run your standard browser (which should be Chrome or Edge for best error reporting).
+
+ Click Sign in, then click Login and use the name "test". Write or import a program and check that it runs properly.

+

* On Ubuntu, in a terminal cd to the google_appengine folder and execute
+ python dev_appserver.py ../glowscript
+
+ Next open a browser, preferably an up-to-date version of Chrome (which gives the best error reporting).
+
+ Enter as a URL "localhost:8080"
+
+ Click Sign in, then click Login and use the name "test".

+
+ +
+
+ + + diff --git a/docs/VPythonDocs/math.html b/docs/VPythonDocs/math.html index a3e2535b..dc2ec7ec 100644 --- a/docs/VPythonDocs/math.html +++ b/docs/VPythonDocs/math.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
@@ -64,26 +65,60 @@

Math Functions

combin(x,y)   # x!/(y!*(x-y)!)
max(a,b,c,..) # maximum of these
min(a,b,c,..) # minimum of these

-

Many of the quantities above are short forms of the JavaScript functions Math.abs(x), Math.sqrt(x), etc. Here are details of the factorial and combin functions.

-

 

+

Many of the quantities above are short forms of the JavaScript functions Math.abs(x), Math.sqrt(x), etc.

+
+
+

In general, Python modules cannot be imported into VPython programs, because GlowScript VPython functions in a JavaScript environment. However, one can import the Python "random" module into a VPython program, provided by the RapydScript-NG tool that converts Python to JavaScript. One cannot use the form "from random import *" but must use "import random" or "import random as rr" (or other name) or "from random import randint, uniform" (or other list of functions). Here is documentation of the Python random module, however only seed_state, get_random_byte, seed, random, randrange, randint, uniform, choice, shuffle, and sample have been implemented in GlowScript. You do not need to import the random module in order to be able to use the random() function described above.

-

 

There are functions for converting between degrees and radians, where there are 2*pi radians in 360 degrees:

radians(360)  # equal to 2*pi
- degrees(2*pi) # equal to 360

-

 

+ degrees(2*pi) # equal to 360

See JavaScript documentation on the Date object which provides methods for determining the current day etc.

Here is a way to determine elapsed time in seconds, with microsecond accuracy, using the clock() function that is also available in the standard Python "time" module. The displayed text is approximately 1.5:

t1 = clock()
sleep(1.5)
t2 = clock()
- print(t2-t1)

+ print(t2-t1)

There is also a function msclock() which gives the time in milliseconds instead of seconds.

-

 

You can use LaTeX to display mathematical expressions on the page.

-
- +

Here are functions that are useful in statistical calculations:

+
+
+

print(factorial(4)) # gives 24
+ print(combin(10,2)) # gives 45

+

The factorial function factorial(N) + is N!; 4! is (4)(3)(2)(1) = 24, and 0! is defined to be 1.
+ The combin function is combin(a,b) = a!/(b!*(a-b)!)
.

+

A major use of these functions is in calculating the number + of ways of arranging a group of objects. For example, if there are 5 numbered + balls in a sack, there are factorial(5) = + 5! = 5*4*3*2*1 = 120 ways of taking them sequentially out of the sack (5 + possibilities for the first ball, 4 for the next, and so on).

+

If on the other hand the 5 balls are not numbered, but 2 + + are green and 3 are red, of the 120 ways of picking the balls there are + + 2! indistinguishable ways of arranging the green balls and 3! ways of arranging + + the red balls, so the number of different arrangements of the balls is combin(5,2) = 5!/(3!*2!) = 10.

+

Logically, the combin function is just a combination of + + factorial functions. However, cancellations in the numerator and denominator + + make it possible to evaluate the combin function for values of its arguments + + that would overflow the factorial function, due to the limited size of floating-point + + numbers. For example, combin(5,2) = 5!/(3!*2!) + + = (5*4)/(2*1) = (2.5*4) = 10, and we didn't have to evaluate any of the factorials fully.

+

 

+


+

+
+
+
diff --git a/docs/VPythonDocs/mouse.html b/docs/VPythonDocs/mouse.html index 25a93063..2662bf64 100644 --- a/docs/VPythonDocs/mouse.html +++ b/docs/VPythonDocs/mouse.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/mouse_click.html b/docs/VPythonDocs/mouse_click.html index f73645f0..9aa4428b 100644 --- a/docs/VPythonDocs/mouse_click.html +++ b/docs/VPythonDocs/mouse_click.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/mouse_drag.html b/docs/VPythonDocs/mouse_drag.html index 7a5f5f92..021590c1 100644 --- a/docs/VPythonDocs/mouse_drag.html +++ b/docs/VPythonDocs/mouse_drag.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/new_features.html b/docs/VPythonDocs/olderhistory.html similarity index 94% rename from docs/VPythonDocs/new_features.html rename to docs/VPythonDocs/olderhistory.html index 4cb57192..d3e9b3b1 100644 --- a/docs/VPythonDocs/new_features.html +++ b/docs/VPythonDocs/olderhistory.html @@ -49,25 +49,22 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
- +
VPython in - GlowScript
Log of the development of Classic VPython
 
-

Supporting VPython programs in GlowScript is new as of November 2014. It became possible thanks to the development of the Python look-alike compiler, RapydScript. Help with RapydScript by Alexander Tsepkov, Charles Law, and Salvatore di Dio is gratefully acknowledged.

-

Below is information about the development of VPython. GlowScript was originated by David Scherer and Bruce Sherwood in 2011. In 2014 Adam Thompson contributed important versioning of the jquery libraries.

-

Here is a log of GlowScript developments.

-

Credits

+

Credits

VPython was initially created by David Scherer in the spring of 2000. Assisting him were David Andersen, Ruth Chabay, Ari Heitner, Ian Peters, and Bruce Sherwood.

Starting in 2002, Jonathan Brandmeyer made several major contributions to VPython 3, including changing the connection between Python and C++ diff --git a/docs/VPythonDocs/options.html b/docs/VPythonDocs/options.html index 6edae739..9821eabf 100644 --- a/docs/VPythonDocs/options.html +++ b/docs/VPythonDocs/options.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/points.html b/docs/VPythonDocs/points.html index cc954e32..4a57077c 100644 --- a/docs/VPythonDocs/points.html +++ b/docs/VPythonDocs/points.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/primitives.html b/docs/VPythonDocs/primitives.html index 25a6d942..5df0ebf7 100644 --- a/docs/VPythonDocs/primitives.html +++ b/docs/VPythonDocs/primitives.html @@ -35,10 +35,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/pyramid.html b/docs/VPythonDocs/pyramid.html index 03027b76..fdac75ae 100644 --- a/docs/VPythonDocs/pyramid.html +++ b/docs/VPythonDocs/pyramid.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/rate.html b/docs/VPythonDocs/rate.html index 86bdf27f..05d30a47 100644 --- a/docs/VPythonDocs/rate.html +++ b/docs/VPythonDocs/rate.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/ring.html b/docs/VPythonDocs/ring.html index 65a55a2a..1c9db020 100644 --- a/docs/VPythonDocs/ring.html +++ b/docs/VPythonDocs/ring.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/rotation.html b/docs/VPythonDocs/rotation.html index e6434331..23a1f0ce 100644 --- a/docs/VPythonDocs/rotation.html +++ b/docs/VPythonDocs/rotation.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/shapes.html b/docs/VPythonDocs/shapes.html index bbbaefb7..f1f3c12c 100644 --- a/docs/VPythonDocs/shapes.html +++ b/docs/VPythonDocs/shapes.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/sphere.html b/docs/VPythonDocs/sphere.html index 8a19eead..c4032344 100644 --- a/docs/VPythonDocs/sphere.html +++ b/docs/VPythonDocs/sphere.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/technical.html b/docs/VPythonDocs/technical.html new file mode 100644 index 00000000..fe63dce7 --- /dev/null +++ b/docs/VPythonDocs/technical.html @@ -0,0 +1,133 @@ + + + +VPython Help + + + + + + + +
+
+

  Home

+

  If you're new to Python
+   and VPython: Introduction

+

  A VPython tutorial

+

  Introductory Videos

+

  Pictures of 3D objects

+

  

+

  

+

  

+

  VPython 7 web site
+   VPython license
+
+

+ +
+ +
+ +
+
+

Technical issues

+

Here are discussions of two technical aspects of GlowScript, which may be of interest to other software developers.

+

Pixel-level transparency based on depth peeling

+

Handling transparency correctly in WebGL is challenging. A standard technique is to order the centers of objects according to their z depth from the camera and render back to front. This approach can make serious errors in the case of intersecting or enclosing transparent objects, where some parts of one object are in front of a second object, and other parts are behind the second object.

+

A better approach is called "depth peeling", in which transparency is dealt with at the pixel level rather than at the object level. Consider for example a transparent sphere enclosing an opaque box, and carry out the following operations:

+

1) Render the pixels of the opaque box to a texture, which we'll call a color texture. This of course takes into consideration the lights in the scene. Call this color texture C0. Note that all opacity values (the "a" in rgba) are 1.0 for this opaque object.

+

2) Render the z depths (distance from the camera) to a texture, which we'll call a depth texture. That is, given the depth of a pixel, the fragment shader stores a false color into the texture, a false color whose 4 bytes represents in some form the depth. Call this depth texture D0.

+

3) Render the transparent object (the sphere) to a texture C1, but using information in the depth texture D0. In the fragment shader, read the (false color) depth from D0, and if the z depth of the transparent sphere pixel is not in front of the opaque box pixel, discard the pixel (using the "discard" statement in the fragment shader). Upon completion of this render step, C1 contains color and opacity information (rgba) for the front-most transparent surface, a hemisphere. This is called a "depth peel".

+

4) We now have two color textures, C0 and C1, which we can merge to form a scene with an opaque box and a transparent hemisphere in front of the box. Render a simple quad object (two triangles) that fill the canvas. In the fragment shader, read the color information from C0 and C1. Store a pixel color that is determined like this, where (1.0-C1.a) is the transparency of the transparent layer:

+

vec3 color = C1.rgb*C1.a +
+             (1.0-C1.a)*C0.rgb;
+ gl_FragColor = vec4 (color, 1.0);

+

These four steps illustrate the basic idea. In GlowScript, four transparent depth peels are performed rather than one, and 10 separate renders are carried out:

+

C0 -- opaque color texture
+ D0 -- opaque depth texture
+ C1 -- frontmost transparent color texture
+ D1 -- frontmost transparent depth texture, corresponding to C1
+ C2 -- transparent color texture for the next deeper "peel" after C1; if the pixel does not have a depth between that of D0 and D1, the pixel is discarded
+ D2 -- transparent depth texture corresponding to C2
+ C3 -- next deeper transparent color texture; discard a pixel if z not between D0 and D2
+ D3 -- transparent depth texture corresponding to C3
+ C4 -- deepest transparent color texture; discard a pixel if z not between D0 and D3

+

MERGE -- The final render is a merge of C0, C1, C2, C3, and C4:

+

vec3 color = C1.rgb*C1.a +
+    (1.0-C1.a)*(C2.rgb*C2.a +
+    (1.0-C2.a)*(C3.rgb*C3.a +
+    (1.0-C3.a)*(C4.rgb*C4.a +
+    (1.0-C4.a)*C0.rgb)));
+ gl_FragColor = vec4 (color, 1.0);

+

It may be that C2, C3, and C4 are all empty, but there is no obvious inexpensive way to get the information needed to tell the CPU to avoid scheduling those extra renders, because readPixels is very expensive. If there are more than four transparent layers, this algorithm will not treat them properly. However, note that the fifth and later peels will contribute little to the final pixel color, being partially occluded by four transparent layers in front.

+

Before starting the many renders the objects are sorted into opaque and transparent lists, and if there are no transparent objects a simple C0 render is all that is needed. Moreover, this simple render can exploit antialiasing, whereas the storage into textures for depth peeling unfortunately turns off antialiasing.

+

It is remarkable that doing 10 separate renders runs adequately fast for real-time rendering of moderately complicated scenes. For example, displaying a 10x10x10 grid of rotating transparent boxes can run at around 20 frames per second on ordinary computers, depending on the graphics card.

+

In OpenGL it is possible to create several textures in one render, but WegGL permits attaching just one texture to a framebuffer object, hence a large number of separate renders are needed.

+

To see this algorithm in action, run this Transparency example program.

+

Note that the code for this transparency demo is remarkably short. GlowScript is aimed at making it feasible for nonexpert programmers to exploit WebGL to generate navigable real-time 3D animations.

+

At https://www.glowscript.org/docs/GlowScriptDocs/technical.html, the key files dealing with depth peeling are lib/glow/WebGLRender.js and the shader programs in the shaders folder.

+

It is possible to implement "Fast Approximate Anti-Aliasing" (FXAA) to get around the problem that the use of framebuffer objects turns off anti-aliasing:
+ http://www.codinghorror.com/blog/2011/12/fast-approximate-anti-aliasing-fxaa.html

+

This has not been tried in GlowScript.

+

Mouse picking
+

+

Here is how mouse picking has been implemented in GlowScript. For an object with id number N, create a false color like this:

+

function id_to_falsecolor(N) { + // convert integer object id to floating RGBA
+    let R=0, G=0, B=0
+    if (N >= 16777216) {
+       R = Math.floor(N/16777216)
+       N -= R*16777216
+    }
+    if (N >= 65536) {
+       G = Math.floor(N/65536)
+       N -= G*65536
+    }
+    if (N >= 256) {
+       B = Math.floor(N/256)
+       N -= B*256
+    }
+    return [R/255, G/255, B/255, N/255]
+ }

+

We want to render the false colors of the objects to a texture the size of the canvas (need not be powers of 2):

+

let pick_texture = gl.createTexture()
+ gl.bindTexture(gl.TEXTURE_2D, pick_texture )

+

gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
+ 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)

+

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null)
+ gl.bindTexture(gl.TEXTURE_2D, null)

+

Set up a framebuffer to render to:

+

let pickFramebuffer = gl.createFramebuffer()
+ gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer)

+

// create depth buffer:
+ let pickRenderbuffer = gl.createRenderbuffer()
+ gl.bindRenderbuffer(gl.RENDERBUFFER, pickRenderbuffer)
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height)
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, pickRenderbuffer)

+

gl.bindRenderbuffer(gl.RENDERBUFFER, null)
+ gl.bindFramebuffer(gl.FRAMEBUFFER, null)

+

At the start of a render cycle execute this:

+

gl.bindFramebuffer(gl.FRAMEBUFFER, pickFramebuffer)
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, + pick_texture, 0)

+

After rendering all the objects, with no lighting calculations (so that all pixels of an object have the same false color), get the id number of the object under the mouse like this:

+

let pixels = new Uint8Array(4)
+ gl.readPixels(canvas.mouse.__pickx, canvas.mouse.__picky, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixels)
+ let id = 16777216*pixels[0] + 65536*pixels[1] + 256*pixels[2] + pixels[3]

+

A non-power-of-two texture has restrictions; see http://www.khronos.org/webgl/wiki/WebGL_and_OpenGL_Differences.
+ Important note: This destroys antialiasing, so render to texture is fully useful only for doing some computations, unless we do our own antialiasing.

+

Note that antialiasing being turned off is actually what one wants for mouse picking because you don't want an object with id of 10 that is next to an object of id 30 to get picked with an id of 20, which could happen with antialiasing turned on, due to the averaging of neighboring colors.

+
+
+
+

 

+
+
+ +
+
+ + + diff --git a/docs/VPythonDocs/text.html b/docs/VPythonDocs/text.html index ce217d36..ca404029 100644 --- a/docs/VPythonDocs/text.html +++ b/docs/VPythonDocs/text.html @@ -37,10 +37,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/text_output.html b/docs/VPythonDocs/text_output.html index 2019f705..cbede8e9 100644 --- a/docs/VPythonDocs/text_output.html +++ b/docs/VPythonDocs/text_output.html @@ -37,10 +37,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/textures.html b/docs/VPythonDocs/textures.html index 7a152730..469f54f6 100644 --- a/docs/VPythonDocs/textures.html +++ b/docs/VPythonDocs/textures.html @@ -31,10 +31,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/trail.html b/docs/VPythonDocs/trail.html index 478725ae..fef8487e 100644 --- a/docs/VPythonDocs/trail.html +++ b/docs/VPythonDocs/trail.html @@ -26,10 +26,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/triangle.html b/docs/VPythonDocs/triangle.html index 580890a7..e35d551c 100644 --- a/docs/VPythonDocs/triangle.html +++ b/docs/VPythonDocs/triangle.html @@ -31,10 +31,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/using_javascript.html b/docs/VPythonDocs/using_javascript.html new file mode 100644 index 00000000..115d1acc --- /dev/null +++ b/docs/VPythonDocs/using_javascript.html @@ -0,0 +1,125 @@ + + + +VPython Help + + + + + + + +
+
+

  Home

+

  If you're new to Python
+   and VPython: Introduction

+

  A VPython tutorial

+

  Introductory Videos

+

  Pictures of 3D objects

+

  

+

  

+

  

+

  VPython 7 web site
+   VPython license
+
+

+ +
+ +
+ +
+

Writing GlowScript programs using JavaScript

+

To write GlowScript programs using JavaScript instead of VPython, change the first line of the program to the form "GlowScript X.Y JavaScript", where "X.Y" is the current version of GlowScript.

+

The GlowScript documentation describes the syntax to use when writing VPython code. Here is the relationship between the VPython documentation and what you would write in JavaScript:

+
+
+
+

b = box(pos=vec(2,1,0, color=color.cyan)          # VPython
+ b.axis = vec(1,1,0) +

+

let b = box({pos:vec(2,1,0), color:color.cyan})  // JavaScript
+b.axis = vec(1,1,0)

+

At the moment, the ACE editor used at glowscript.org is an old version that doesn't recognize some (now valid) elements of JavaScript, including in particular async, await, and clas, and as a result statements containing these elements are marked as being in error. Evidently glowscript.org needs to upgrade its use of ACE.

+

Using async and await

+

An animation loop must contain a rate(), sleep(), scene.pause(), or scene.waitfor() statement; otherwise the browser will lock up, and it is difficult to kill the browser. Moreover, these statements must be preceded by await, which is inserted automatically when VPython programs are transpiled to JavaScript but must be entered explicitly into a JavaScript program. Here is what these JavaScript statements must look like, including the three other GlowScript functions that take time to complete and therefore also need await:

+

    await rate(30)
+    await sleep(2)
+     await scene.pause()
+    await scene.waitfor('click')
+    await scene.capture(filename)
+    await get_library(webaddress)
+    await read_local_file(scene.title.anchor)

+

If you write your own function or class method that includes any of these waiting statements, you must prepend async to the function or method declaration, and all calls to these functions or methods must be prepended with await, as with the GlowScript functions shown above and in the runnable html file shown at the end of this article.
+
+ At glowscript.org your program is wrapped in an async function, which makes it possible to use await outside any of your functions. If you do not use glowscript.org to prepare your JavaScript program, you may need to wrap your program in an async function, as shown in the runnable html file below. It is not possible to use await outside an async function.
+
+ Currently, when editing a JavaScript program at glowscript.org, the use of "class" or "=>" causes a warning symbol to the left of the line, which can be ignored. +

+

Operator overloading for vectors

+

Something that is automatic at glowscript.org for JavaScript programs as well as for VPython programs is the "operator overloading" that permits vector operations such as "let v = v1+v2", where v1 and v2 are vectors. If you do not use glowscript.org to prepare your JavaScript program, you will need to write this statement in the form "v1.add(v2)". Similarly, "v1-v2" would be written "v1.sub(v2)", 5*v would be written "v.multiply(5)", and v/5 would be written "v.divide(5)". An alternative is to pass your program through glowscript.org and click "Share or export this program" to obtain an operator-overloaded version of your program.

+

New in GlowScript 3.0: linkage of axis and size; default sphere radius now 1

+

Starting with GlowScript version 3.0, JavaScript programs, like VPython programs, link changes in an object's axis to its size, and changes in its size to its axis. Prior to version 3.0, JavaScript programs did not perform such linkage, and the arrow object had a special attribute "axis_and_length" instead of "axis". Using axis_and_length now will cause an error.
+
+ A related matter is that, for historical reasons, the default radius of a VPython sphere is 1, which is now also the default + radius of a JavaScript sphere. Formerly a JavaScript sphere did not have a radius attribute, and its default size was vec(1,1,1), so the radius was 0.5.

+

JavaScript class "constructor" method

+

When you create a JavaScript class instance the arguments are sent to a method named "constructor". Neither the class itself nor its constructor method can be of type async, which means that in the constructor method you cannot use await. If you do need to use await in some part of the initialization of a class instance, write the program like this:

+

class C {
+    constructor(n) {
+        C.n = n      // a class variable
+        this.x = 20  // a class instance variable
+    }
+     async init(y) {
+        this.y = y
+        print("Sleep...")
+        await sleep(2)
+        print(C.n, this.x, this.y) // displays 10 20 30
+    }
+} +
+let a = new C(10)
+ await a.init(30)

+

Passing methods as arguments to other functions

+

Suppose you create a class named C with an instance named c1 and a method c1.m. You might wish to create a reference in the form let cm = c1.m (no parentheses) and pass it to a function f in the form f(cm). In that case, you need to write the assignment to cm like this: let cm = c1.m.bind(c1). Again, this is done automatically for VPython programs.

+

A runnable html file

+

If you store the following program in an .html file and then double-click the file to invoke a browser, you should see a rotating cube (adjust the version number for the glow library appropriately):

+

<div id="glowscript" class="glowscript">
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <link type="text/css" href="https://s3.amazonaws.com/glowscript/css/redmond/2.1/jquery-ui.custom.css" rel="stylesheet" />
+ <link type="text/css" href="https://s3.amazonaws.com/glowscript/css/ide.css" rel="stylesheet" />
+ <script type="text/javascript" src="https://s3.amazonaws.com/glowscript/lib/jquery/2.1/jquery.min.js"></script>
+ <script type="text/javascript" src="https://s3.amazonaws.com/glowscript/lib/jquery/2.1/jquery-ui.custom.min.js"></script>
+ <script type="text/javascript" src="https://s3.amazonaws.com/glowscript/package/glow.3.0.min.js"></script>
+ <script type="text/javascript">
+ window.__context = { glowscript_container: $("#glowscript").removeAttr("id") }
+
+ async function __main__() { // async wrapper permits use of await outside your own functions
+
+ var vector = vec // optional: makes vector a synonym of the fundamental vec
+ let scene = canvas()
+ let b = box({color:color.cyan})
+ async function f(obj) { // needs async because f() contains an await
+    let t = clock()
+     while (true) {
+        await rate(100)
+         obj.rotate({angle:0.01, axis:vec(0,1,0)})
+        if (clock()-t > 3) break
+     }
+    return 25
+ }
+ let x = await f(b) // needs await (inside async __main__) because f() contains an await
+ print(x)
+ } // end of __main__ wrapper
+ __main__()
+ </script>
+ </div>

+


+

+ +
+
+ + + diff --git a/docs/VPythonDocs/vector.html b/docs/VPythonDocs/vector.html index eed20410..4b71a499 100644 --- a/docs/VPythonDocs/vector.html +++ b/docs/VPythonDocs/vector.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/docs/VPythonDocs/videos.html b/docs/VPythonDocs/videos.html index a6080bee..34b932b6 100644 --- a/docs/VPythonDocs/videos.html +++ b/docs/VPythonDocs/videos.html @@ -20,10 +20,11 @@

  

  

  

-

  What's new

-

  Classic VPython web site
+

  VPython 7 web site
  VPython license
-   Python web site

+
+

+
diff --git a/ide/api.py b/ide/api.py index a5cebe6e..5ba3ffe3 100644 --- a/ide/api.py +++ b/ide/api.py @@ -472,7 +472,7 @@ def post(self): def upgradeProgram(self, p): if not p.source.startswith("GlowScript 2.7\n"): - p.source = "GlowScript 2.9 VPython\n" + p.source + p.source = "GlowScript 3.0 VPython\n" + p.source return True #(r'/api/user/([^/]+)/folder/([^/]+)/program/([^/]+)/oldfolder/([^/]+)/oldprogram/([^/]+)/option/([^/]+)', ApiUserProgramCopy), diff --git a/ide/ide.js b/ide/ide.js index 4ec87caa..5e78ba21 100644 --- a/ide/ide.js +++ b/ide/ide.js @@ -31,7 +31,7 @@ $(function () { var rest = source.substr( header.length+1 ) var ret = { version: null, - lang: '', // 'vpython' (default) or 'rapydscript' or 'javascript' or a string that is neither (e.g. when editing header) + lang: '', // 'vpython' (default) or 'javascript' or a string that is neither (e.g. when editing header) source: rest, ok: false, unpackaged: false, @@ -49,7 +49,7 @@ $(function () { ret.lang = 'javascript' // the default if no language is specified if (elements.length == 3) { ret.lang = elements[2].toLowerCase() - if (!(ret.lang == 'javascript' || ret.lang == 'coffeescript' || ret.lang == 'rapydscript' || ret.lang == 'vpython')) return ret + if (!(ret.lang == 'javascript' || ret.lang == 'vpython')) return ret } var ver = elements[1] var okv = parseVersionHeader.okVersions[ver] @@ -65,7 +65,7 @@ $(function () { } } - parseVersionHeader.defaultVersion = "2.9" + parseVersionHeader.defaultVersion = "3.0" parseVersionHeader.defaultHeader = "GlowScript " + parseVersionHeader.defaultVersion+' VPython' parseVersionHeader.errorMessage = "GlowScript " + parseVersionHeader.defaultVersion // Map each version that can be loaded to a packaged version (usually itself), or "unpackaged" if it is the current development version @@ -88,6 +88,7 @@ $(function () { "2.7": "2.7", "2.8": "2.8", "2.9": "2.9", + "3.0": "3.0", "0.4dev" : "0.4", "0.5dev" : "0.5", "0.6dev" : "0.6", @@ -104,7 +105,8 @@ $(function () { "2.7dev" : "2.7", "2.8dev" : "2.8", "2.9dev" : "2.9", - "3.0dev" : "unpackaged" + "3.0dev" : "3.0", + "3.1dev" : "unpackaged" } /******** Functions to talk to the API on the server ***********/ @@ -1119,7 +1121,7 @@ $(function () { if (header.unpackaged) page.find(".embedWarning").text("Embedding programs with development versions of GlowScript is not recommended. They will likely be broken by further changes, and the packages used for embedding may not match the packages used to run in an development version.") var compiler_url - if (header.lang == 'vpython' || header.lang == 'rapydscript') { + if (header.lang == 'vpython') { compiler_url = "../package/RScompiler." + header.version + ".min.js" } else compiler_url = "../package/compiler." + header.version + ".min.js" window.glowscript_compile = undefined @@ -1147,16 +1149,6 @@ $(function () { var divid = "glowscript" var remove = header.version==='0.3' ? '' : '.removeAttr("id")' var main - if (header.lang == 'coffeescript') { - // The CoffeeScript -> JavaScript converter wraps the code in an extra protective layer, in addition - // to the wrapper imposed by GlowScript. The following code effectively unwraps the extra layer. - // There's probably a far more elegant way to deal with this.... - var fname = '__RUN_GLOWSCRIPT' - main = fname+'()()' - embedScript = embedScript.slice(0,where+1) + fname + ' = ' + embedScript.slice(where+2,embedScript.length) - where = embedScript.indexOf('}).call(this)') - embedScript = embedScript.slice(0,where+1) + embedScript.slice(where+13,embedScript.length) - } var v = Number(header.version.substr(0,3)) if (v >= 2.9) main = '__main__()' // Starting August 2019, no longer using Streamine else if (v == 2.8) main = 'main(function(err) {;})' // Starting June 2019, using up-to-date Streamline file @@ -1172,13 +1164,12 @@ $(function () { var runner = '' var exporturl = "https://www."+website+".org/" if (v >= 2.5) exporturl = "https://s3.amazonaws.com/glowscript/" - if (header.lang == 'vpython' || header.lang == 'rapydscript') + if (header.lang == 'vpython') runner = '\n' var embedHTML = ( '
\n' + '\n' + - '\n' + - '\n' + + '\n' + '\n' + mathjax + '\n' + @@ -1248,7 +1239,7 @@ $(function () { page.find(".prog-datetime").text(date_to_string(progData.datetime)) // program is the name of the file; progData.source is the program source in that file var lang = parseVersionHeader(progData.source).lang - if (!(lang == 'javascript' || lang == 'coffeescript' || lang == 'rapydscript' || lang == 'vpython')) lang = 'javascript' + if (!(lang == 'javascript' || lang == 'vpython')) lang = 'javascript' if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) { var editor = GSedit @@ -1296,8 +1287,8 @@ $(function () { /*********** Customization of the ACE editor *************/ // See https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode - // mode-javascript.js and mode-coffee.js are loaded by ide/index.html. - // These modules in turn load worker-javascript.js and worker-coffee.js in lib/ace. + // mode-javascript.js is loaded by ide/index.html. + // These modules in turn load worker-javascript.js in lib/ace. // See lib/ace/FileSource.txt for where to find updated ACE files, and how they // were modified in minor ways for GlowScript use. var customACEMode = function(lang, source) { // lang is "javascript" or some fragment @@ -1335,13 +1326,12 @@ $(function () { define('ace/mode/visualjs_highlight_rules', function (ace_require, exports, module) { var oop = ace_require("ace/lib/oop") var Rules - if (lang == 'rapydscript' || lang == 'vpython') Rules = ace_require("ace/mode/python_highlight_rules").PythonHighlightRules - else if (lang == 'coffeescript') Rules = ace_require("ace/mode/coffee_highlight_rules").CoffeeHighlightRules + if (lang == 'vpython') Rules = ace_require("ace/mode/python_highlight_rules").PythonHighlightRules else Rules = ace_require("ace/mode/javascript_highlight_rules").JavaScriptHighlightRules var VisualHighlightRules = function () { this.$rules = (new Rules()).getRules() - if (lang == 'rapydscript' || lang == 'vpython') this.$rules.start = [{ regex: /GlowScript\s+[\d\.]*[dev]*\s+[A-Za-z]*/, token: "keyword.version_header" } ].concat(this.$rules.start) + if (lang == 'vpython') this.$rules.start = [{ regex: /GlowScript\s+[\d\.]*[dev]*\s+[A-Za-z]*/, token: "keyword.version_header" } ].concat(this.$rules.start) else this.$rules.start = [{ regex: /GlowScript\s+[\d\.]*[dev]*/, token: "keyword.version_header" } ].concat(this.$rules.start) for(var id in libraryWords) { this.$rules.start = [{ regex: id, token: libraryWords[id] } ].concat(this.$rules.start) @@ -1355,7 +1345,7 @@ $(function () { //------------------------------------------------------------------------------------------------------ define('ace/mode/visualjs', function (ace_require, exports, module) { var oop = ace_require("ace/lib/oop") - if (lang == 'rapydscript' || lang == 'vpython') var BaseMode = ace_require("ace/mode/python").Mode + if (lang == 'vpython') var BaseMode = ace_require("ace/mode/python").Mode else var BaseMode = ace_require("ace/mode/javascript").Mode var Tokenizer = ace_require("ace/tokenizer").Tokenizer var VisualHighlightRules = ace_require("ace/mode/visualjs_highlight_rules").VisualHighlightRules @@ -1379,8 +1369,8 @@ $(function () { var doc = session.getDocument() if (worker !== undefined && worker !== null) worker.$doc = doc // must set this in order to be able to execute worker.terminate() - //if (lang == 'rapydscript' || lang == 'vpython') worker.call("setValue", ['']) - //else worker.call("setValue", [lintPrefix]) + if (lang == 'vpython') worker.call("setValue", ['']) + else worker.call("setValue", [lintPrefix]) worker.call("setValue", [lintPrefix]) var header = null @@ -1393,7 +1383,7 @@ $(function () { if (e.data.range.start.row === 0) { // Could note that language has changed, suggest reloading the page header = parseVersionHeader(doc.getValue()) - if ((header.lang == 'javascript' || header.lang == 'coffeescript' || header.lang == 'rapydscript' || header.lang == 'vpython') && header.lang != lang) + if ((header.lang == 'javascript' || header.lang == 'vpython') && header.lang != lang) alert("Reload the page to switch to editing " + header.lang) else if (header.isCurrent) headerError = null @@ -1429,7 +1419,7 @@ $(function () { session.clearAnnotations() }) - // JavaScript (no conflict with worker.on options for CoffeeScript): + // JavaScript worker.on("jslint", function (results) { var errors = []; if (headerError) errors.push(headerError) diff --git a/ide/index.html b/ide/index.html index 7225327d..19b7565c 100644 --- a/ide/index.html +++ b/ide/index.html @@ -5,7 +5,6 @@ - @@ -51,13 +50,11 @@

glowscript.org

- +

GlowScript is an easy-to-use, powerful environment for creating 3D animations and publishing them on the web. Here at glowscript.org, you can write and run GlowScript programs right in your browser, store them in the - cloud for free, and easily share them with others. - Thanks to the RapydScript-NG - compiler, you can use VPython here.

+ cloud for free, and easily share them with others.

@@ -78,7 +75,7 @@

glowscript.org

-

G l o w S c r i p t   2.9

+

G l o w S c r i p t   3.0

Example programs | Forum
@@ -284,9 +281,8 @@

G l o w S c r i p t   2.9

- - + diff --git a/lib/ace/FileSource.txt b/lib/ace/FileSource.txt index facbfeab..6b1829e9 100644 --- a/lib/ace/FileSource.txt +++ b/lib/ace/FileSource.txt @@ -1,4 +1,4 @@ -The originals of the ACE files used by GlowScript are found here: +The originals of the ACE files used by GlowScript were found here: https://github.com/ajaxorg/ace-builds/tree/master/src (At https://github.com/ajaxorg/ace-builds are src-min, src-noconflict, and src-min-noconflict, @@ -20,4 +20,7 @@ Small modifications to the ACE files for GlowScript purposes: Note that between May 2011 and August 2012 there were significant changes to ACE which required different (simpler) modifications than had been made in 2011. This occurred again in 2014. + +Currently, built files are at https://github.com/ajaxorg/ace-builds/ + \ No newline at end of file diff --git a/lib/ace/mode-coffee.js b/lib/ace/mode-coffee.js deleted file mode 100644 index 52c5c3bb..00000000 --- a/lib/ace/mode-coffee.js +++ /dev/null @@ -1,527 +0,0 @@ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * https://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is Ajax.org Code Editor (ACE). - * - * The Initial Developer of the Original Code is - * Ajax.org B.V. - * Portions created by the Initial Developer are Copyright (C) 2010 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * Satoshi Murakami - * - * Alternatively, the contents of this file may be used under the terms of - * either the GNU General Public License Version 2 or later (the "GPL"), or - * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -define('ace/mode/coffee', ['ace_require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/coffee_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/coffee', 'ace/range', 'ace/mode/text', 'ace/worker/worker_client', 'ace/lib/oop'], function(ace_require, exports, module) { - - -var Tokenizer = ace_require("../tokenizer").Tokenizer; -var Rules = ace_require("./coffee_highlight_rules").CoffeeHighlightRules; -var Outdent = ace_require("./matching_brace_outdent").MatchingBraceOutdent; -var PythonFoldMode = ace_require("./folding/coffee").FoldMode; -var Range = ace_require("../range").Range; -var TextMode = ace_require("./text").Mode; -var WorkerClient = ace_require("../worker/worker_client").WorkerClient; -var oop = ace_require("../lib/oop"); - -function Mode() { - this.$tokenizer = new Tokenizer(new Rules().getRules()); - this.$outdent = new Outdent(); - this.foldingRules = new PythonFoldMode("=|=>|->|\\s*class [^#]*"); -} - -oop.inherits(Mode, TextMode); - -(function() { - - var indenter = /(?:[({[=:]|[-=]>|\b(?:else|switch|try|catch(?:\s*[$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)?|finally))\s*$/; - var commentLine = /^(\s*)#/; - var hereComment = /^\s*###(?!#)/; - var indentation = /^\s*/; - - this.getNextLineIndent = function(state, line, tab) { - var indent = this.$getIndent(line); - var tokens = this.$tokenizer.getLineTokens(line, state).tokens; - - if (!(tokens.length && tokens[tokens.length - 1].type === 'comment') && - state === 'start' && indenter.test(line)) - indent += tab; - return indent; - }; - - this.toggleCommentLines = function(state, doc, startRow, endRow){ - console.log("toggle"); - var range = new Range(0, 0, 0, 0); - for (var i = startRow; i <= endRow; ++i) { - var line = doc.getLine(i); - if (hereComment.test(line)) - continue; - - if (commentLine.test(line)) - line = line.replace(commentLine, '$1'); - else - line = line.replace(indentation, '$&#'); - - range.end.row = range.start.row = i; - range.end.column = line.length + 1; - doc.replace(range, line); - } - }; - - this.checkOutdent = function(state, line, input) { - return this.$outdent.checkOutdent(line, input); - }; - - this.autoOutdent = function(state, doc, row) { - this.$outdent.autoOutdent(doc, row); - }; - - this.createWorker = function(session) { - var worker = new WorkerClient(["ace"], "ace/mode/coffee_worker", "Worker"); - worker.attachToDocument(session.getDocument()); - - worker.on("error", function(e) { - session.setAnnotations([e.data]); - }); - - worker.on("ok", function(e) { - session.clearAnnotations(); - }); - - return worker; - }; - -}).call(Mode.prototype); - -exports.Mode = Mode; - -}); - -define('ace/mode/coffee_highlight_rules', ['ace_require', 'exports', 'module' , 'ace/lib/lang', 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(ace_require, exports, module) { - - - var lang = ace_require("../lib/lang"); - var oop = ace_require("../lib/oop"); - var TextHighlightRules = ace_require("./text_highlight_rules").TextHighlightRules; - - oop.inherits(CoffeeHighlightRules, TextHighlightRules); - - function CoffeeHighlightRules() { - var identifier = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*"; - var stringfill = { - token : "string", - merge : true, - regex : ".+" - }; - - var keywords = lang.arrayToMap(( - "this|throw|then|try|typeof|super|switch|return|break|by)|continue|" + - "catch|class|in|instanceof|is|isnt|if|else|extends|for|forown|" + - "finally|function|while|when|new|no|not|delete|debugger|do|loop|of|off|" + - "or|on|unless|until|and|yes").split("|") - ); - - var langConstant = lang.arrayToMap(( - "true|false|null|undefined").split("|") - ); - - var illegal = lang.arrayToMap(( - "case|const|default|function|var|void|with|enum|export|implements|" + - "interface|let|package|private|protected|public|static|yield|" + - "__hasProp|extends|slice|bind|indexOf").split("|") - ); - - var supportClass = lang.arrayToMap(( - "Array|Boolean|Date|Function|Number|Object|RegExp|ReferenceError|" + - "RangeError|String|SyntaxError|Error|EvalError|TypeError|URIError").split("|") - ); - - var supportFunction = lang.arrayToMap(( - "Math|JSON|isNaN|isFinite|parseInt|parseFloat|encodeURI|" + - "encodeURIComponent|decodeURI|decodeURIComponent|RangeError|String|" + - "SyntaxError|Error|EvalError|TypeError|URIError").split("|") - ); - - this.$rules = { - start : [ - { - token : "identifier", - regex : "(?:(?:\\.|::)\\s*)" + identifier - }, { - token : "variable", - regex : "@(?:" + identifier + ")?" - }, { - token: function(value) { - if (keywords.hasOwnProperty(value)) - return "keyword"; - else if (langConstant.hasOwnProperty(value)) - return "constant.language"; - else if (illegal.hasOwnProperty(value)) - return "invalid.illegal"; - else if (supportClass.hasOwnProperty(value)) - return "language.support.class"; - else if (supportFunction.hasOwnProperty(value)) - return "language.support.function"; - else - return "identifier"; - }, - regex : identifier - }, { - token : "constant.numeric", - regex : "(?:0x[\\da-fA-F]+|(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?)" - }, { - token : "string", - merge : true, - regex : "'''", - next : "qdoc" - }, { - token : "string", - merge : true, - regex : '"""', - next : "qqdoc" - }, { - token : "string", - merge : true, - regex : "'", - next : "qstring" - }, { - token : "string", - merge : true, - regex : '"', - next : "qqstring" - }, { - token : "string", - merge : true, - regex : "`", - next : "js" - }, { - token : "string.regex", - merge : true, - regex : "///", - next : "heregex" - }, { - token : "string.regex", - regex : "/(?!\\s)[^[/\\n\\\\]*(?: (?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[/\\n\\\\]*)*/[imgy]{0,4}(?!\\w)" - }, { - token : "comment", - merge : true, - regex : "###(?!#)", - next : "comment" - }, { - token : "comment", - regex : "#.*" - }, { - token : "punctuation.operator", - regex : "\\?|\\:|\\,|\\." - }, { - token : "keyword.operator", - regex : "(?:[\\-=]>|[-+*/%<>&|^!?=]=|>>>=?|\\-\\-|\\+\\+|::|&&=|\\|\\|=|<<=|>>=|\\?\\.|\\.{2,3}|[!*+-=><])" - }, { - token : "paren.lparen", - regex : "[({[]" - }, { - token : "paren.rparen", - regex : "[\\]})]" - }, { - token : "text", - regex : "\\s+" - }], - - qdoc : [{ - token : "string", - regex : ".*?'''", - next : "start" - }, stringfill], - - qqdoc : [{ - token : "string", - regex : '.*?"""', - next : "start" - }, stringfill], - - qstring : [{ - token : "string", - regex : "[^\\\\']*(?:\\\\.[^\\\\']*)*'", - merge : true, - next : "start" - }, stringfill], - - qqstring : [{ - token : "string", - regex : '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"', - merge : true, - next : "start" - }, stringfill], - - js : [{ - token : "string", - merge : true, - regex : "[^\\\\`]*(?:\\\\.[^\\\\`]*)*`", - next : "start" - }, stringfill], - - heregex : [{ - token : "string.regex", - regex : '.*?///[imgy]{0,4}', - next : "start" - }, { - token : "comment.regex", - regex : "\\s+(?:#.*)?" - }, { - token : "string.regex", - merge : true, - regex : "\\S+" - }], - - comment : [{ - token : "comment", - regex : '.*?###', - next : "start" - }, { - token : "comment", - merge : true, - regex : ".+" - }] - }; - } - - exports.CoffeeHighlightRules = CoffeeHighlightRules; -}); - -define('ace/mode/matching_brace_outdent', ['ace_require', 'exports', 'module' , 'ace/range'], function(ace_require, exports, module) { - - -var Range = ace_require("../range").Range; - -var MatchingBraceOutdent = function() {}; - -(function() { - - this.checkOutdent = function(line, input) { - if (! /^\s+$/.test(line)) - return false; - - return /^\s*\}/.test(input); - }; - - this.autoOutdent = function(doc, row) { - var line = doc.getLine(row); - var match = line.match(/^(\s*\})/); - - if (!match) return 0; - - var column = match[1].length; - var openBracePos = doc.findMatchingBracket({row: row, column: column}); - - if (!openBracePos || openBracePos.row == row) return 0; - - var indent = this.$getIndent(doc.getLine(openBracePos.row)); - doc.replace(new Range(row, 0, row, column-1), indent); - }; - - this.$getIndent = function(line) { - var match = line.match(/^(\s+)/); - if (match) { - return match[1]; - } - - return ""; - }; - -}).call(MatchingBraceOutdent.prototype); - -exports.MatchingBraceOutdent = MatchingBraceOutdent; -}); - -define('ace/mode/folding/coffee', ['ace_require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range'], function(ace_require, exports, module) { - - -var oop = ace_require("../../lib/oop"); -var BaseFoldMode = ace_require("./fold_mode").FoldMode; -var Range = ace_require("../../range").Range; - -var FoldMode = exports.FoldMode = function() {}; -oop.inherits(FoldMode, BaseFoldMode); - -(function() { - - this.getFoldWidgetRange = function(session, foldStyle, row) { - var range = this.indentationBlock(session, row); - if (range) - return range; - - var re = /\S/; - var line = session.getLine(row); - var startLevel = line.search(re); - if (startLevel == -1 || line[startLevel] != "#") - return; - - var startColumn = line.length; - var maxRow = session.getLength(); - var startRow = row; - var endRow = row; - - while (++row < maxRow) { - line = session.getLine(row); - var level = line.search(re); - - if (level == -1) - continue; - - if (line[level] != "#") - break; - - endRow = row; - } - - if (endRow > startRow) { - var endColumn = session.getLine(endRow).length; - return new Range(startRow, startColumn, endRow, endColumn); - } - }; - - // must return "" if there's no fold, to enable caching - this.getFoldWidget = function(session, foldStyle, row) { - var line = session.getLine(row); - var indent = line.search(/\S/); - var next = session.getLine(row + 1); - var prev = session.getLine(row - 1); - var prevIndent = prev.search(/\S/); - var nextIndent = next.search(/\S/); - - if (indent == -1) { - session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; - return ""; - } - - // documentation comments - if (prevIndent == -1) { - if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { - session.foldWidgets[row - 1] = ""; - session.foldWidgets[row + 1] = ""; - return "start"; - } - } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { - if (session.getLine(row - 2).search(/\S/) == -1) { - session.foldWidgets[row - 1] = "start"; - session.foldWidgets[row + 1] = ""; - return "" - } - } - - if (prevIndent!= -1 && prevIndent < indent) - session.foldWidgets[row - 1] = "start"; - else - session.foldWidgets[row - 1] = ""; - - if (indent < nextIndent) - return "start"; - else - return ""; - }; - -}).call(FoldMode.prototype); - -}); - -define('ace/mode/folding/fold_mode', ['ace_require', 'exports', 'module' , 'ace/range'], function(ace_require, exports, module) { - - -var Range = ace_require("../../range").Range; - -var FoldMode = exports.FoldMode = function() {}; - -(function() { - - this.foldingStartMarker = null; - this.foldingStopMarker = null; - - // must return "" if there's no fold, to enable caching - this.getFoldWidget = function(session, foldStyle, row) { - var line = session.getLine(row); - if (this.foldingStartMarker.test(line)) - return "start"; - if (foldStyle == "markbeginend" - && this.foldingStopMarker - && this.foldingStopMarker.test(line)) - return "end"; - return ""; - }; - - this.getFoldWidgetRange = function(session, foldStyle, row) { - return null; - }; - - this.indentationBlock = function(session, row, column) { - var re = /\S/; - var line = session.getLine(row); - var startLevel = line.search(re); - if (startLevel == -1) - return; - - var startColumn = column || line.length; - var maxRow = session.getLength(); - var startRow = row; - var endRow = row; - - while (++row < maxRow) { - var level = session.getLine(row).search(re); - - if (level == -1) - continue; - - if (level <= startLevel) - break; - - endRow = row; - } - - if (endRow > startRow) { - var endColumn = session.getLine(endRow).length; - return new Range(startRow, startColumn, endRow, endColumn); - } - }; - - this.openingBracketBlock = function(session, bracket, row, column, typeRe) { - var start = {row: row, column: column + 1}; - var end = session.$findClosingBracket(bracket, start, typeRe); - if (!end) - return; - - var fw = session.foldWidgets[end.row]; - if (fw == null) - fw = this.getFoldWidget(session, end.row); - - if (fw == "start" && end.row > start.row) { - end.row --; - end.column = session.getLine(end.row).length; - } - return Range.fromPoints(start, end); - }; - -}).call(FoldMode.prototype); - -}); \ No newline at end of file diff --git a/lib/ace/mode-javascript.js b/lib/ace/mode-javascript.js index 8b8bf44b..78d82e51 100644 --- a/lib/ace/mode-javascript.js +++ b/lib/ace/mode-javascript.js @@ -196,7 +196,7 @@ var JavaScriptHighlightRules = function() { ); var keywords = lang.arrayToMap( - ("break|case|catch|continue|default|delete|do|else|finally|for|function|" + + ("async|await|break|case|catch|class|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" + "const|yield|import|get|set").split("|") ); @@ -208,7 +208,7 @@ var JavaScriptHighlightRules = function() { ("__parent__|__count__|escape|unescape|with|__proto__").split("|") ); - var definitions = lang.arrayToMap(("const|let|var|function").split("|")); + var definitions = lang.arrayToMap(("class|const|let|var|function").split("|")); var buildinConstants = lang.arrayToMap( ("null|Infinity|NaN|undefined").split("|") diff --git a/lib/ace/worker-coffee.js b/lib/ace/worker-coffee.js deleted file mode 100644 index 2b1558e0..00000000 --- a/lib/ace/worker-coffee.js +++ /dev/null @@ -1,7179 +0,0 @@ -"no use strict"; - -// Small modification by Bruce Sherwood, 2012 August 14, for GlowScript (glowscript.org). -// Search for GlowScript, where we skip the header line ("GlowScript X.Y CoffeeScript"). - -var console = { - log: function(msg) { - postMessage({type: "log", data: msg}); - } -}; -var window = { - console: console -}; - -var normalizeModule = function(parentId, moduleName) { - // normalize plugin requires - if (moduleName.indexOf("!") !== -1) { - var chunks = moduleName.split("!"); - return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]); - } - // normalize relative requires - if (moduleName.charAt(0) == ".") { - var base = parentId.split("/").slice(0, -1).join("/"); - var moduleName = base + "/" + moduleName; - - while(moduleName.indexOf(".") !== -1 && previous != moduleName) { - var previous = moduleName; - var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); - } - } - - return moduleName; -}; - -var require = function(parentId, id) { - var id = normalizeModule(parentId, id); - - var module = require.modules[id]; - if (module) { - if (!module.initialized) { - module.exports = module.factory().exports; - module.initialized = true; - } - return module.exports; - } - - var chunks = id.split("/"); - chunks[0] = require.tlns[chunks[0]] || chunks[0]; - var path = chunks.join("/") + ".js"; - - require.id = id; - importScripts(path); - return require(parentId, id); -}; - -require.modules = {}; -require.tlns = {}; - -var define = function(id, deps, factory) { - if (arguments.length == 2) { - factory = deps; - } else if (arguments.length == 1) { - factory = id; - id = require.id; - } - - if (id.indexOf("text!") === 0) - return; - - var req = function(deps, factory) { - return require(id, deps, factory); - }; - - require.modules[id] = { - factory: function() { - var module = { - exports: {} - }; - var returnExports = factory(req, module.exports, module); - if (returnExports) - module.exports = returnExports; - return module; - } - }; -}; - -function initBaseUrls(topLevelNamespaces) { - require.tlns = topLevelNamespaces; -} - -function initSender() { - - var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter; - var oop = require(null, "ace/lib/oop"); - - var Sender = function() {}; - - (function() { - - oop.implement(this, EventEmitter); - - this.callback = function(data, callbackId) { - postMessage({ - type: "call", - id: callbackId, - data: data - }); - }; - - this.emit = function(name, data) { - postMessage({ - type: "event", - name: name, - data: data - }); - }; - - }).call(Sender.prototype); - - return new Sender(); -} - -var main; -var sender; - -onmessage = function(e) { - var msg = e.data; - if (msg.command) { - main[msg.command].apply(main, msg.args); - } - else if (msg.init) { - initBaseUrls(msg.tlns); - require(null, "ace/lib/fixoldbrowsers"); - sender = initSender(); - var clazz = require(null, msg.module)[msg.classname]; - main = new clazz(sender); - } - else if (msg.event && sender) { - sender._emit(msg.event, msg.data); - } -}; -// vim:set ts=4 sts=4 sw=4 st: -// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License -// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) -// -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified -// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License -// -- Irakli Gozalishvili Copyright (C) 2010 MIT License - -/*! - Copyright (c) 2009, 280 North Inc. http://280north.com/ - MIT License. http://github.com/280north/narwhal/blob/master/README.md -*/ - -define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) { - - -require("./regexp"); -require("./es5-shim"); - -}); - -define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) { - - - //--------------------------------- - // Private variables - //--------------------------------- - - var real = { - exec: RegExp.prototype.exec, - test: RegExp.prototype.test, - match: String.prototype.match, - replace: String.prototype.replace, - split: String.prototype.split - }, - compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups - compliantLastIndexIncrement = function () { - var x = /^/g; - real.test.call(x, ""); - return !x.lastIndex; - }(); - - if (compliantLastIndexIncrement && compliantExecNpcg) - return; - - //--------------------------------- - // Overriden native methods - //--------------------------------- - - // Adds named capture support (with backreferences returned as `result.name`), and fixes two - // cross-browser issues per ES3: - // - Captured values for nonparticipating capturing groups should be returned as `undefined`, - // rather than the empty string. - // - `lastIndex` should not be incremented after zero-length matches. - RegExp.prototype.exec = function (str) { - var match = real.exec.apply(this, arguments), - name, r2; - if ( typeof(str) == 'string' && match) { - // Fix browsers whose `exec` methods don't consistently return `undefined` for - // nonparticipating capturing groups - if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { - r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", "")); - // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed - // matching due to characters outside the match - real.replace.call(str.slice(match.index), r2, function () { - for (var i = 1; i < arguments.length - 2; i++) { - if (arguments[i] === undefined) - match[i] = undefined; - } - }); - } - // Attach named capture properties - if (this._xregexp && this._xregexp.captureNames) { - for (var i = 1; i < match.length; i++) { - name = this._xregexp.captureNames[i - 1]; - if (name) - match[name] = match[i]; - } - } - // Fix browsers that increment `lastIndex` after zero-length matches - if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) - this.lastIndex--; - } - return match; - }; - - // Don't override `test` if it won't change anything - if (!compliantLastIndexIncrement) { - // Fix browser bug in native method - RegExp.prototype.test = function (str) { - // Use the native `exec` to skip some processing overhead, even though the overriden - // `exec` would take care of the `lastIndex` fix - var match = real.exec.call(this, str); - // Fix browsers that increment `lastIndex` after zero-length matches - if (match && this.global && !match[0].length && (this.lastIndex > match.index)) - this.lastIndex--; - return !!match; - }; - } - - //--------------------------------- - // Private helper functions - //--------------------------------- - - function getNativeFlags (regex) { - return (regex.global ? "g" : "") + - (regex.ignoreCase ? "i" : "") + - (regex.multiline ? "m" : "") + - (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 - (regex.sticky ? "y" : ""); - }; - - function indexOf (array, item, from) { - if (Array.prototype.indexOf) // Use the native array method if available - return array.indexOf(item, from); - for (var i = from || 0; i < array.length; i++) { - if (array[i] === item) - return i; - } - return -1; - }; - -}); -// vim: ts=4 sts=4 sw=4 expandtab -// -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License -// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) -// -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA -// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License -// -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License -// -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License -// -- kossnocorp Sasha Koss XXX TODO License or CLA -// -- bryanforbes Bryan Forbes XXX TODO License or CLA -// -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence -// -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License -// -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License -// -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain) -// -- iwyg XXX TODO License or CLA -// -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License -// -- xavierm02 Montillet Xavier XXX TODO License or CLA -// -- Raynos Raynos XXX TODO License or CLA -// -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License -// -- rwldrn Rick Waldron Copyright (C) 2011 MIT License -// -- lexer Alexey Zakharov XXX TODO License or CLA - -/*! - Copyright (c) 2009, 280 North Inc. http://280north.com/ - MIT License. http://github.com/280north/narwhal/blob/master/README.md -*/ - -define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) { - -/* - * Brings an environment as close to ECMAScript 5 compliance - * as is possible with the facilities of erstwhile engines. - * - * Annotated ES5: http://es5.github.com/ (specific links below) - * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf - * - * @module - */ - -/*whatsupdoc*/ - -// -// Function -// ======== -// - -// ES-5 15.3.4.5 -// http://es5.github.com/#x15.3.4.5 - -if (!Function.prototype.bind) { - Function.prototype.bind = function bind(that) { // .length is 1 - // 1. Let Target be the this value. - var target = this; - // 2. If IsCallable(Target) is false, throw a TypeError exception. - if (typeof target != "function") - throw new TypeError(); // TODO message - // 3. Let A be a new (possibly empty) internal list of all of the - // argument values provided after thisArg (arg1, arg2 etc), in order. - // XXX slicedArgs will stand in for "A" if used - var args = slice.call(arguments, 1); // for normal call - // 4. Let F be a new native ECMAScript object. - // 11. Set the [[Prototype]] internal property of F to the standard - // built-in Function prototype object as specified in 15.3.3.1. - // 12. Set the [[Call]] internal property of F as described in - // 15.3.4.5.1. - // 13. Set the [[Construct]] internal property of F as described in - // 15.3.4.5.2. - // 14. Set the [[HasInstance]] internal property of F as described in - // 15.3.4.5.3. - var bound = function () { - - if (this instanceof bound) { - // 15.3.4.5.2 [[Construct]] - // When the [[Construct]] internal method of a function object, - // F that was created using the bind function is called with a - // list of arguments ExtraArgs, the following steps are taken: - // 1. Let target be the value of F's [[TargetFunction]] - // internal property. - // 2. If target has no [[Construct]] internal method, a - // TypeError exception is thrown. - // 3. Let boundArgs be the value of F's [[BoundArgs]] internal - // property. - // 4. Let args be a new list containing the same values as the - // list boundArgs in the same order followed by the same - // values as the list ExtraArgs in the same order. - // 5. Return the result of calling the [[Construct]] internal - // method of target providing args as the arguments. - - var F = function(){}; - F.prototype = target.prototype; - var self = new F; - - var result = target.apply( - self, - args.concat(slice.call(arguments)) - ); - if (result !== null && Object(result) === result) - return result; - return self; - - } else { - // 15.3.4.5.1 [[Call]] - // When the [[Call]] internal method of a function object, F, - // which was created using the bind function is called with a - // this value and a list of arguments ExtraArgs, the following - // steps are taken: - // 1. Let boundArgs be the value of F's [[BoundArgs]] internal - // property. - // 2. Let boundThis be the value of F's [[BoundThis]] internal - // property. - // 3. Let target be the value of F's [[TargetFunction]] internal - // property. - // 4. Let args be a new list containing the same values as the - // list boundArgs in the same order followed by the same - // values as the list ExtraArgs in the same order. - // 5. Return the result of calling the [[Call]] internal method - // of target providing boundThis as the this value and - // providing args as the arguments. - - // equiv: target.call(this, ...boundArgs, ...args) - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - - } - - }; - // XXX bound.length is never writable, so don't even try - // - // 15. If the [[Class]] internal property of Target is "Function", then - // a. Let L be the length property of Target minus the length of A. - // b. Set the length own property of F to either 0 or L, whichever is - // larger. - // 16. Else set the length own property of F to 0. - // 17. Set the attributes of the length own property of F to the values - // specified in 15.3.5.1. - - // TODO - // 18. Set the [[Extensible]] internal property of F to true. - - // TODO - // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3). - // 20. Call the [[DefineOwnProperty]] internal method of F with - // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]: - // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and - // false. - // 21. Call the [[DefineOwnProperty]] internal method of F with - // arguments "arguments", PropertyDescriptor {[[Get]]: thrower, - // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false}, - // and false. - - // TODO - // NOTE Function objects created using Function.prototype.bind do not - // have a prototype property or the [[Code]], [[FormalParameters]], and - // [[Scope]] internal properties. - // XXX can't delete prototype in pure-js. - - // 22. Return F. - return bound; - }; -} - -// Shortcut to an often accessed properties, in order to avoid multiple -// dereference that costs universally. -// _Please note: Shortcuts are defined after `Function.prototype.bind` as we -// us it in defining shortcuts. -var call = Function.prototype.call; -var prototypeOfArray = Array.prototype; -var prototypeOfObject = Object.prototype; -var slice = prototypeOfArray.slice; -var toString = call.bind(prototypeOfObject.toString); -var owns = call.bind(prototypeOfObject.hasOwnProperty); - -// If JS engine supports accessors creating shortcuts. -var defineGetter; -var defineSetter; -var lookupGetter; -var lookupSetter; -var supportsAccessors; -if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { - defineGetter = call.bind(prototypeOfObject.__defineGetter__); - defineSetter = call.bind(prototypeOfObject.__defineSetter__); - lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); - lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); -} - -// -// Array -// ===== -// - -// ES5 15.4.3.2 -// http://es5.github.com/#x15.4.3.2 -// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray -if (!Array.isArray) { - Array.isArray = function isArray(obj) { - return toString(obj) == "[object Array]"; - }; -} - -// The IsCallable() check in the Array functions -// has been replaced with a strict check on the -// internal class of the object to trap cases where -// the provided function was actually a regular -// expression literal, which in V8 and -// JavaScriptCore is a typeof "function". Only in -// V8 are regular expression literals permitted as -// reduce parameters, so it is desirable in the -// general case for the shim to match the more -// strict and common behavior of rejecting regular -// expressions. - -// ES5 15.4.4.18 -// http://es5.github.com/#x15.4.4.18 -// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach -if (!Array.prototype.forEach) { - Array.prototype.forEach = function forEach(fun /*, thisp*/) { - var self = toObject(this), - thisp = arguments[1], - i = 0, - length = self.length >>> 0; - - // If no callback function or if callback is not a callable function - if (toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - while (i < length) { - if (i in self) { - // Invoke the callback function with call, passing arguments: - // context, property value, property key, thisArg object context - fun.call(thisp, self[i], i, self); - } - i++; - } - }; -} - -// ES5 15.4.4.19 -// http://es5.github.com/#x15.4.4.19 -// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map -if (!Array.prototype.map) { - Array.prototype.map = function map(fun /*, thisp*/) { - var self = toObject(this), - length = self.length >>> 0, - result = Array(length), - thisp = arguments[1]; - - // If no callback function or if callback is not a callable function - if (toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - for (var i = 0; i < length; i++) { - if (i in self) - result[i] = fun.call(thisp, self[i], i, self); - } - return result; - }; -} - -// ES5 15.4.4.20 -// http://es5.github.com/#x15.4.4.20 -// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter -if (!Array.prototype.filter) { - Array.prototype.filter = function filter(fun /*, thisp */) { - var self = toObject(this), - length = self.length >>> 0, - result = [], - thisp = arguments[1]; - - // If no callback function or if callback is not a callable function - if (toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - for (var i = 0; i < length; i++) { - if (i in self && fun.call(thisp, self[i], i, self)) - result.push(self[i]); - } - return result; - }; -} - -// ES5 15.4.4.16 -// http://es5.github.com/#x15.4.4.16 -// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every -if (!Array.prototype.every) { - Array.prototype.every = function every(fun /*, thisp */) { - var self = toObject(this), - length = self.length >>> 0, - thisp = arguments[1]; - - // If no callback function or if callback is not a callable function - if (toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - for (var i = 0; i < length; i++) { - if (i in self && !fun.call(thisp, self[i], i, self)) - return false; - } - return true; - }; -} - -// ES5 15.4.4.17 -// http://es5.github.com/#x15.4.4.17 -// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some -if (!Array.prototype.some) { - Array.prototype.some = function some(fun /*, thisp */) { - var self = toObject(this), - length = self.length >>> 0, - thisp = arguments[1]; - - // If no callback function or if callback is not a callable function - if (toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - for (var i = 0; i < length; i++) { - if (i in self && fun.call(thisp, self[i], i, self)) - return true; - } - return false; - }; -} - -// ES5 15.4.4.21 -// http://es5.github.com/#x15.4.4.21 -// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce -if (!Array.prototype.reduce) { - Array.prototype.reduce = function reduce(fun /*, initial*/) { - var self = toObject(this), - length = self.length >>> 0; - - // If no callback function or if callback is not a callable function - if (toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - // no value to return if no initial value and an empty array - if (!length && arguments.length == 1) - throw new TypeError(); // TODO message - - var i = 0; - var result; - if (arguments.length >= 2) { - result = arguments[1]; - } else { - do { - if (i in self) { - result = self[i++]; - break; - } - - // if array contains no values, no initial value to return - if (++i >= length) - throw new TypeError(); // TODO message - } while (true); - } - - for (; i < length; i++) { - if (i in self) - result = fun.call(void 0, result, self[i], i, self); - } - - return result; - }; -} - -// ES5 15.4.4.22 -// http://es5.github.com/#x15.4.4.22 -// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight -if (!Array.prototype.reduceRight) { - Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { - var self = toObject(this), - length = self.length >>> 0; - - // If no callback function or if callback is not a callable function - if (toString(fun) != "[object Function]") { - throw new TypeError(); // TODO message - } - - // no value to return if no initial value, empty array - if (!length && arguments.length == 1) - throw new TypeError(); // TODO message - - var result, i = length - 1; - if (arguments.length >= 2) { - result = arguments[1]; - } else { - do { - if (i in self) { - result = self[i--]; - break; - } - - // if array contains no values, no initial value to return - if (--i < 0) - throw new TypeError(); // TODO message - } while (true); - } - - do { - if (i in this) - result = fun.call(void 0, result, self[i], i, self); - } while (i--); - - return result; - }; -} - -// ES5 15.4.4.14 -// http://es5.github.com/#x15.4.4.14 -// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf -if (!Array.prototype.indexOf) { - Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { - var self = toObject(this), - length = self.length >>> 0; - - if (!length) - return -1; - - var i = 0; - if (arguments.length > 1) - i = toInteger(arguments[1]); - - // handle negative indices - i = i >= 0 ? i : Math.max(0, length + i); - for (; i < length; i++) { - if (i in self && self[i] === sought) { - return i; - } - } - return -1; - }; -} - -// ES5 15.4.4.15 -// http://es5.github.com/#x15.4.4.15 -// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf -if (!Array.prototype.lastIndexOf) { - Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { - var self = toObject(this), - length = self.length >>> 0; - - if (!length) - return -1; - var i = length - 1; - if (arguments.length > 1) - i = Math.min(i, toInteger(arguments[1])); - // handle negative indices - i = i >= 0 ? i : length - Math.abs(i); - for (; i >= 0; i--) { - if (i in self && sought === self[i]) - return i; - } - return -1; - }; -} - -// -// Object -// ====== -// - -// ES5 15.2.3.2 -// http://es5.github.com/#x15.2.3.2 -if (!Object.getPrototypeOf) { - // https://github.com/kriskowal/es5-shim/issues#issue/2 - // http://ejohn.org/blog/objectgetprototypeof/ - // recommended by fschaefer on github - Object.getPrototypeOf = function getPrototypeOf(object) { - return object.__proto__ || ( - object.constructor ? - object.constructor.prototype : - prototypeOfObject - ); - }; -} - -// ES5 15.2.3.3 -// http://es5.github.com/#x15.2.3.3 -if (!Object.getOwnPropertyDescriptor) { - var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + - "non-object: "; - Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { - if ((typeof object != "object" && typeof object != "function") || object === null) - throw new TypeError(ERR_NON_OBJECT + object); - // If object does not owns property return undefined immediately. - if (!owns(object, property)) - return; - - var descriptor, getter, setter; - - // If object has a property then it's for sure both `enumerable` and - // `configurable`. - descriptor = { enumerable: true, configurable: true }; - - // If JS engine supports accessor properties then property may be a - // getter or setter. - if (supportsAccessors) { - // Unfortunately `__lookupGetter__` will return a getter even - // if object has own non getter property along with a same named - // inherited getter. To avoid misbehavior we temporary remove - // `__proto__` so that `__lookupGetter__` will return getter only - // if it's owned by an object. - var prototype = object.__proto__; - object.__proto__ = prototypeOfObject; - - var getter = lookupGetter(object, property); - var setter = lookupSetter(object, property); - - // Once we have getter and setter we can put values back. - object.__proto__ = prototype; - - if (getter || setter) { - if (getter) descriptor.get = getter; - if (setter) descriptor.set = setter; - - // If it was accessor property we're done and return here - // in order to avoid adding `value` to the descriptor. - return descriptor; - } - } - - // If we got this far we know that object has an own property that is - // not an accessor so we set it as a value and return descriptor. - descriptor.value = object[property]; - return descriptor; - }; -} - -// ES5 15.2.3.4 -// http://es5.github.com/#x15.2.3.4 -if (!Object.getOwnPropertyNames) { - Object.getOwnPropertyNames = function getOwnPropertyNames(object) { - return Object.keys(object); - }; -} - -// ES5 15.2.3.5 -// http://es5.github.com/#x15.2.3.5 -if (!Object.create) { - Object.create = function create(prototype, properties) { - var object; - if (prototype === null) { - object = { "__proto__": null }; - } else { - if (typeof prototype != "object") - throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); - var Type = function () {}; - Type.prototype = prototype; - object = new Type(); - // IE has no built-in implementation of `Object.getPrototypeOf` - // neither `__proto__`, but this manually setting `__proto__` will - // guarantee that `Object.getPrototypeOf` will work as expected with - // objects created using `Object.create` - object.__proto__ = prototype; - } - if (properties !== void 0) - Object.defineProperties(object, properties); - return object; - }; -} - -// ES5 15.2.3.6 -// http://es5.github.com/#x15.2.3.6 - -// Patch for WebKit and IE8 standard mode -// Designed by hax -// related issue: https://github.com/kriskowal/es5-shim/issues#issue/5 -// IE8 Reference: -// http://msdn.microsoft.com/en-us/library/dd282900.aspx -// http://msdn.microsoft.com/en-us/library/dd229916.aspx -// WebKit Bugs: -// https://bugs.webkit.org/show_bug.cgi?id=36423 - -function doesDefinePropertyWork(object) { - try { - Object.defineProperty(object, "sentinel", {}); - return "sentinel" in object; - } catch (exception) { - // returns falsy - } -} - -// check whether defineProperty works if it's given. Otherwise, -// shim partially. -if (Object.defineProperty) { - var definePropertyWorksOnObject = doesDefinePropertyWork({}); - var definePropertyWorksOnDom = typeof document == "undefined" || - doesDefinePropertyWork(document.createElement("div")); - if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { - var definePropertyFallback = Object.defineProperty; - } -} - -if (!Object.defineProperty || definePropertyFallback) { - var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; - var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " - var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + - "on this javascript engine"; - - Object.defineProperty = function defineProperty(object, property, descriptor) { - if ((typeof object != "object" && typeof object != "function") || object === null) - throw new TypeError(ERR_NON_OBJECT_TARGET + object); - if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) - throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); - - // make a valiant attempt to use the real defineProperty - // for I8's DOM elements. - if (definePropertyFallback) { - try { - return definePropertyFallback.call(Object, object, property, descriptor); - } catch (exception) { - // try the shim if the real one doesn't work - } - } - - // If it's a data property. - if (owns(descriptor, "value")) { - // fail silently if "writable", "enumerable", or "configurable" - // are requested but not supported - /* - // alternate approach: - if ( // can't implement these features; allow false but not true - !(owns(descriptor, "writable") ? descriptor.writable : true) || - !(owns(descriptor, "enumerable") ? descriptor.enumerable : true) || - !(owns(descriptor, "configurable") ? descriptor.configurable : true) - ) - throw new RangeError( - "This implementation of Object.defineProperty does not " + - "support configurable, enumerable, or writable." - ); - */ - - if (supportsAccessors && (lookupGetter(object, property) || - lookupSetter(object, property))) - { - // As accessors are supported only on engines implementing - // `__proto__` we can safely override `__proto__` while defining - // a property to make sure that we don't hit an inherited - // accessor. - var prototype = object.__proto__; - object.__proto__ = prototypeOfObject; - // Deleting a property anyway since getter / setter may be - // defined on object itself. - delete object[property]; - object[property] = descriptor.value; - // Setting original `__proto__` back now. - object.__proto__ = prototype; - } else { - object[property] = descriptor.value; - } - } else { - if (!supportsAccessors) - throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); - // If we got that far then getters and setters can be defined !! - if (owns(descriptor, "get")) - defineGetter(object, property, descriptor.get); - if (owns(descriptor, "set")) - defineSetter(object, property, descriptor.set); - } - - return object; - }; -} - -// ES5 15.2.3.7 -// http://es5.github.com/#x15.2.3.7 -if (!Object.defineProperties) { - Object.defineProperties = function defineProperties(object, properties) { - for (var property in properties) { - if (owns(properties, property)) - Object.defineProperty(object, property, properties[property]); - } - return object; - }; -} - -// ES5 15.2.3.8 -// http://es5.github.com/#x15.2.3.8 -if (!Object.seal) { - Object.seal = function seal(object) { - // this is misleading and breaks feature-detection, but - // allows "securable" code to "gracefully" degrade to working - // but insecure code. - return object; - }; -} - -// ES5 15.2.3.9 -// http://es5.github.com/#x15.2.3.9 -if (!Object.freeze) { - Object.freeze = function freeze(object) { - // this is misleading and breaks feature-detection, but - // allows "securable" code to "gracefully" degrade to working - // but insecure code. - return object; - }; -} - -// detect a Rhino bug and patch it -try { - Object.freeze(function () {}); -} catch (exception) { - Object.freeze = (function freeze(freezeObject) { - return function freeze(object) { - if (typeof object == "function") { - return object; - } else { - return freezeObject(object); - } - }; - })(Object.freeze); -} - -// ES5 15.2.3.10 -// http://es5.github.com/#x15.2.3.10 -if (!Object.preventExtensions) { - Object.preventExtensions = function preventExtensions(object) { - // this is misleading and breaks feature-detection, but - // allows "securable" code to "gracefully" degrade to working - // but insecure code. - return object; - }; -} - -// ES5 15.2.3.11 -// http://es5.github.com/#x15.2.3.11 -if (!Object.isSealed) { - Object.isSealed = function isSealed(object) { - return false; - }; -} - -// ES5 15.2.3.12 -// http://es5.github.com/#x15.2.3.12 -if (!Object.isFrozen) { - Object.isFrozen = function isFrozen(object) { - return false; - }; -} - -// ES5 15.2.3.13 -// http://es5.github.com/#x15.2.3.13 -if (!Object.isExtensible) { - Object.isExtensible = function isExtensible(object) { - // 1. If Type(O) is not Object throw a TypeError exception. - if (Object(object) === object) { - throw new TypeError(); // TODO message - } - // 2. Return the Boolean value of the [[Extensible]] internal property of O. - var name = ''; - while (owns(object, name)) { - name += '?'; - } - object[name] = true; - var returnValue = owns(object, name); - delete object[name]; - return returnValue; - }; -} - -// ES5 15.2.3.14 -// http://es5.github.com/#x15.2.3.14 -if (!Object.keys) { - // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation - var hasDontEnumBug = true, - dontEnums = [ - "toString", - "toLocaleString", - "valueOf", - "hasOwnProperty", - "isPrototypeOf", - "propertyIsEnumerable", - "constructor" - ], - dontEnumsLength = dontEnums.length; - - for (var key in {"toString": null}) - hasDontEnumBug = false; - - Object.keys = function keys(object) { - - if ((typeof object != "object" && typeof object != "function") || object === null) - throw new TypeError("Object.keys called on a non-object"); - - var keys = []; - for (var name in object) { - if (owns(object, name)) { - keys.push(name); - } - } - - if (hasDontEnumBug) { - for (var i = 0, ii = dontEnumsLength; i < ii; i++) { - var dontEnum = dontEnums[i]; - if (owns(object, dontEnum)) { - keys.push(dontEnum); - } - } - } - - return keys; - }; - -} - -// -// Date -// ==== -// - -// ES5 15.9.5.43 -// http://es5.github.com/#x15.9.5.43 -// This function returns a String value represent the instance in time -// represented by this Date object. The format of the String is the Date Time -// string format defined in 15.9.1.15. All fields are present in the String. -// The time zone is always UTC, denoted by the suffix Z. If the time value of -// this object is not a finite Number a RangeError exception is thrown. -if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) { - Date.prototype.toISOString = function toISOString() { - var result, length, value, year; - if (!isFinite(this)) - throw new RangeError; - - // the date time string format is specified in 15.9.1.15. - result = [this.getUTCMonth() + 1, this.getUTCDate(), - this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()]; - year = this.getUTCFullYear(); - year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6); - - length = result.length; - while (length--) { - value = result[length]; - // pad months, days, hours, minutes, and seconds to have two digits. - if (value < 10) - result[length] = "0" + value; - } - // pad milliseconds to have three digits. - return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." + - ("000" + this.getUTCMilliseconds()).slice(-3) + "Z"; - } -} - -// ES5 15.9.4.4 -// http://es5.github.com/#x15.9.4.4 -if (!Date.now) { - Date.now = function now() { - return new Date().getTime(); - }; -} - -// ES5 15.9.5.44 -// http://es5.github.com/#x15.9.5.44 -// This function provides a String representation of a Date object for use by -// JSON.stringify (15.12.3). -if (!Date.prototype.toJSON) { - Date.prototype.toJSON = function toJSON(key) { - // When the toJSON method is called with argument key, the following - // steps are taken: - - // 1. Let O be the result of calling ToObject, giving it the this - // value as its argument. - // 2. Let tv be ToPrimitive(O, hint Number). - // 3. If tv is a Number and is not finite, return null. - // XXX - // 4. Let toISO be the result of calling the [[Get]] internal method of - // O with argument "toISOString". - // 5. If IsCallable(toISO) is false, throw a TypeError exception. - if (typeof this.toISOString != "function") - throw new TypeError(); // TODO message - // 6. Return the result of calling the [[Call]] internal method of - // toISO with O as the this value and an empty argument list. - return this.toISOString(); - - // NOTE 1 The argument is ignored. - - // NOTE 2 The toJSON function is intentionally generic; it does not - // require that its this value be a Date object. Therefore, it can be - // transferred to other kinds of objects for use as a method. However, - // it does require that any such object have a toISOString method. An - // object is free to use the argument key to filter its - // stringification. - }; -} - -// ES5 15.9.4.2 -// http://es5.github.com/#x15.9.4.2 -// based on work shared by Daniel Friesen (dantman) -// http://gist.github.com/303249 -if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) { - // XXX global assignment won't work in embeddings that use - // an alternate object for the context. - Date = (function(NativeDate) { - - // Date.length === 7 - var Date = function Date(Y, M, D, h, m, s, ms) { - var length = arguments.length; - if (this instanceof NativeDate) { - var date = length == 1 && String(Y) === Y ? // isString(Y) - // We explicitly pass it through parse: - new NativeDate(Date.parse(Y)) : - // We have to manually make calls depending on argument - // length here - length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) : - length >= 6 ? new NativeDate(Y, M, D, h, m, s) : - length >= 5 ? new NativeDate(Y, M, D, h, m) : - length >= 4 ? new NativeDate(Y, M, D, h) : - length >= 3 ? new NativeDate(Y, M, D) : - length >= 2 ? new NativeDate(Y, M) : - length >= 1 ? new NativeDate(Y) : - new NativeDate(); - // Prevent mixups with unfixed Date object - date.constructor = Date; - return date; - } - return NativeDate.apply(this, arguments); - }; - - // 15.9.1.15 Date Time String Format. - var isoDateExpression = new RegExp("^" + - "(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year - "(?:-(\\d{2})" + // optional month capture - "(?:-(\\d{2})" + // optional day capture - "(?:" + // capture hours:minutes:seconds.milliseconds - "T(\\d{2})" + // hours capture - ":(\\d{2})" + // minutes capture - "(?:" + // optional :seconds.milliseconds - ":(\\d{2})" + // seconds capture - "(?:\\.(\\d{3}))?" + // milliseconds capture - ")?" + - "(?:" + // capture UTC offset component - "Z|" + // UTC capture - "(?:" + // offset specifier +/-hours:minutes - "([-+])" + // sign capture - "(\\d{2})" + // hours offset capture - ":(\\d{2})" + // minutes offset capture - ")" + - ")?)?)?)?" + - "$"); - - // Copy any custom methods a 3rd party library may have added - for (var key in NativeDate) - Date[key] = NativeDate[key]; - - // Copy "native" methods explicitly; they may be non-enumerable - Date.now = NativeDate.now; - Date.UTC = NativeDate.UTC; - Date.prototype = NativeDate.prototype; - Date.prototype.constructor = Date; - - // Upgrade Date.parse to handle simplified ISO 8601 strings - Date.parse = function parse(string) { - var match = isoDateExpression.exec(string); - if (match) { - match.shift(); // kill match[0], the full match - // parse months, days, hours, minutes, seconds, and milliseconds - for (var i = 1; i < 7; i++) { - // provide default values if necessary - match[i] = +(match[i] || (i < 3 ? 1 : 0)); - // match[1] is the month. Months are 0-11 in JavaScript - // `Date` objects, but 1-12 in ISO notation, so we - // decrement. - if (i == 1) - match[i]--; - } - - // parse the UTC offset component - var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop(); - - // compute the explicit time zone offset if specified - var offset = 0; - if (sign) { - // detect invalid offsets and return early - if (hourOffset > 23 || minuteOffset > 59) - return NaN; - - // express the provided time zone offset in minutes. The offset is - // negative for time zones west of UTC; positive otherwise. - offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1); - } - - // Date.UTC for years between 0 and 99 converts year to 1900 + year - // The Gregorian calendar has a 400-year cycle, so - // to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...), - // where 12622780800000 - number of milliseconds in Gregorian calendar 400 years - var year = +match[0]; - if (0 <= year && year <= 99) { - match[0] = year + 400; - return NativeDate.UTC.apply(this, match) + offset - 12622780800000; - } - - // compute a new UTC date value, accounting for the optional offset - return NativeDate.UTC.apply(this, match) + offset; - } - return NativeDate.parse.apply(this, arguments); - }; - - return Date; - })(Date); -} - -// -// String -// ====== -// - -// ES5 15.5.4.20 -// http://es5.github.com/#x15.5.4.20 -var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + - "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + - "\u2029\uFEFF"; -if (!String.prototype.trim || ws.trim()) { - // http://blog.stevenlevithan.com/archives/faster-trim-javascript - // http://perfectionkills.com/whitespace-deviations/ - ws = "[" + ws + "]"; - var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), - trimEndRegexp = new RegExp(ws + ws + "*$"); - String.prototype.trim = function trim() { - return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); - }; -} - -// -// Util -// ====== -// - -// ES5 9.4 -// http://es5.github.com/#x9.4 -// http://jsperf.com/to-integer -var toInteger = function (n) { - n = +n; - if (n !== n) // isNaN - n = 0; - else if (n !== 0 && n !== (1/0) && n !== -(1/0)) - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - return n; -}; - -var prepareString = "a"[0] != "a", - // ES5 9.9 - // http://es5.github.com/#x9.9 - toObject = function (o) { - if (o == null) { // this matches both null and undefined - throw new TypeError(); // TODO message - } - // If the implementation doesn't support by-index access of - // string characters (ex. IE < 7), split the string - if (prepareString && typeof o == "string" && o) { - return o.split(""); - } - return Object(o); - }; -}); - -define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) { - - -var EventEmitter = {}; - -EventEmitter._emit = -EventEmitter._dispatchEvent = function(eventName, e) { - this._eventRegistry = this._eventRegistry || {}; - this._defaultHandlers = this._defaultHandlers || {}; - - var listeners = this._eventRegistry[eventName] || []; - var defaultHandler = this._defaultHandlers[eventName]; - if (!listeners.length && !defaultHandler) - return; - - e = e || {}; - e.type = eventName; - - if (!e.stopPropagation) { - e.stopPropagation = function() { - this.propagationStopped = true; - }; - } - - if (!e.preventDefault) { - e.preventDefault = function() { - this.defaultPrevented = true; - }; - } - - for (var i=0; i= length) { - position.row = Math.max(0, length - 1); - position.column = this.getLine(length-1).length; - } - return position; - }; - this.insert = function(position, text) { - if (!text || text.length === 0) - return position; - - position = this.$clipPosition(position); - - // only detect new lines if the document has no line break yet - if (this.getLength() <= 1) - this.$detectNewLine(text); - - var lines = this.$split(text); - var firstLine = lines.splice(0, 1)[0]; - var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0]; - - position = this.insertInLine(position, firstLine); - if (lastLine !== null) { - position = this.insertNewLine(position); // terminate first line - position = this.insertLines(position.row, lines); - position = this.insertInLine(position, lastLine || ""); - } - return position; - }; - this.insertLines = function(row, lines) { - if (lines.length == 0) - return {row: row, column: 0}; - - // apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF) - // to circumvent that we have to break huge inserts into smaller chunks here - if (lines.length > 0xFFFF) { - var end = this.insertLines(row, lines.slice(0xFFFF)); - lines = lines.slice(0, 0xFFFF); - } - - var args = [row, 0]; - args.push.apply(args, lines); - this.$lines.splice.apply(this.$lines, args); - - var range = new Range(row, 0, row + lines.length, 0); - var delta = { - action: "insertLines", - range: range, - lines: lines - }; - this._emit("change", { data: delta }); - return end || range.end; - }; - this.insertNewLine = function(position) { - position = this.$clipPosition(position); - var line = this.$lines[position.row] || ""; - - this.$lines[position.row] = line.substring(0, position.column); - this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length)); - - var end = { - row : position.row + 1, - column : 0 - }; - - var delta = { - action: "insertText", - range: Range.fromPoints(position, end), - text: this.getNewLineCharacter() - }; - this._emit("change", { data: delta }); - - return end; - }; - this.insertInLine = function(position, text) { - if (text.length == 0) - return position; - - var line = this.$lines[position.row] || ""; - - this.$lines[position.row] = line.substring(0, position.column) + text - + line.substring(position.column); - - var end = { - row : position.row, - column : position.column + text.length - }; - - var delta = { - action: "insertText", - range: Range.fromPoints(position, end), - text: text - }; - this._emit("change", { data: delta }); - - return end; - }; - this.remove = function(range) { - // clip to document - range.start = this.$clipPosition(range.start); - range.end = this.$clipPosition(range.end); - - if (range.isEmpty()) - return range.start; - - var firstRow = range.start.row; - var lastRow = range.end.row; - - if (range.isMultiLine()) { - var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1; - var lastFullRow = lastRow - 1; - - if (range.end.column > 0) - this.removeInLine(lastRow, 0, range.end.column); - - if (lastFullRow >= firstFullRow) - this.removeLines(firstFullRow, lastFullRow); - - if (firstFullRow != firstRow) { - this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length); - this.removeNewLine(range.start.row); - } - } - else { - this.removeInLine(firstRow, range.start.column, range.end.column); - } - return range.start; - }; - this.removeInLine = function(row, startColumn, endColumn) { - if (startColumn == endColumn) - return; - - var range = new Range(row, startColumn, row, endColumn); - var line = this.getLine(row); - var removed = line.substring(startColumn, endColumn); - var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length); - this.$lines.splice(row, 1, newLine); - - var delta = { - action: "removeText", - range: range, - text: removed - }; - this._emit("change", { data: delta }); - return range.start; - }; - this.removeLines = function(firstRow, lastRow) { - var range = new Range(firstRow, 0, lastRow + 1, 0); - var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1); - - var delta = { - action: "removeLines", - range: range, - nl: this.getNewLineCharacter(), - lines: removed - }; - this._emit("change", { data: delta }); - return removed; - }; - this.removeNewLine = function(row) { - var firstLine = this.getLine(row); - var secondLine = this.getLine(row+1); - - var range = new Range(row, firstLine.length, row+1, 0); - var line = firstLine + secondLine; - - this.$lines.splice(row, 2, line); - - var delta = { - action: "removeText", - range: range, - text: this.getNewLineCharacter() - }; - this._emit("change", { data: delta }); - }; - this.replace = function(range, text) { - if (text.length == 0 && range.isEmpty()) - return range.start; - - // Shortcut: If the text we want to insert is the same as it is already - // in the document, we don't have to replace anything. - if (text == this.getTextRange(range)) - return range.end; - - this.remove(range); - if (text) { - var end = this.insert(range.start, text); - } - else { - end = range.start; - } - - return end; - }; - this.applyDeltas = function(deltas) { - for (var i=0; i=0; i--) { - var delta = deltas[i]; - - var range = Range.fromPoints(delta.range.start, delta.range.end); - - if (delta.action == "insertLines") - this.removeLines(range.start.row, range.end.row - 1); - else if (delta.action == "insertText") - this.remove(range); - else if (delta.action == "removeLines") - this.insertLines(range.start.row, delta.lines); - else if (delta.action == "removeText") - this.insert(range.start, delta.text); - } - }; - -}).call(Document.prototype); - -exports.Document = Document; -}); - -define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) { - - -/** - * class Range - * - * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. - * - **/ - -/** - * new Range(startRow, startColumn, endRow, endColumn) - * - startRow (Number): The starting row - * - startColumn (Number): The starting column - * - endRow (Number): The ending row - * - endColumn (Number): The ending column - * - * Creates a new `Range` object with the given starting and ending row and column points. - * - **/ -var Range = function(startRow, startColumn, endRow, endColumn) { - this.start = { - row: startRow, - column: startColumn - }; - - this.end = { - row: endRow, - column: endColumn - }; -}; - -(function() { - /** - * Range.isEqual(range) -> Boolean - * - range (Range): A range to check against - * - * Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`. - * - **/ - this.isEqual = function(range) { - return this.start.row == range.start.row && - this.end.row == range.end.row && - this.start.column == range.start.column && - this.end.column == range.end.column - }; - this.toString = function() { - return ("Range: [" + this.start.row + "/" + this.start.column + - "] -> [" + this.end.row + "/" + this.end.column + "]"); - }; - - this.contains = function(row, column) { - return this.compare(row, column) == 0; - }; - this.compareRange = function(range) { - var cmp, - end = range.end, - start = range.start; - - cmp = this.compare(end.row, end.column); - if (cmp == 1) { - cmp = this.compare(start.row, start.column); - if (cmp == 1) { - return 2; - } else if (cmp == 0) { - return 1; - } else { - return 0; - } - } else if (cmp == -1) { - return -2; - } else { - cmp = this.compare(start.row, start.column); - if (cmp == -1) { - return -1; - } else if (cmp == 1) { - return 42; - } else { - return 0; - } - } - } - - /** related to: Range.compare - * Range.comparePoint(p) -> Number - * - p (Range): A point to compare with - * + (Number): This method returns one of the following numbers:
- * * `0` if the two points are exactly equal
- * * `-1` if `p.row` is less then the calling range
- * * `1` if `p.row` is greater than the calling range
- *
- * If the starting row of the calling range is equal to `p.row`, and:
- * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`
- * * Otherwise, it returns -1
- *
- * If the ending row of the calling range is equal to `p.row`, and:
- * * `p.column` is less than or equal to the calling range's ending column, this returns `0`
- * * Otherwise, it returns 1
- * - * Checks the row and column points of `p` with the row and column points of the calling range. - * - * - * - **/ - this.comparePoint = function(p) { - return this.compare(p.row, p.column); - } - - /** related to: Range.comparePoint - * Range.containsRange(range) -> Boolean - * - range (Range): A range to compare with - * - * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. - * - **/ - this.containsRange = function(range) { - return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; - } - - /** - * Range.intersects(range) -> Boolean - * - range (Range): A range to compare with - * - * Returns `true` if passed in `range` intersects with the one calling this method. - * - **/ - this.intersects = function(range) { - var cmp = this.compareRange(range); - return (cmp == -1 || cmp == 0 || cmp == 1); - } - - /** - * Range.isEnd(row, column) -> Boolean - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * - * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. - * - **/ - this.isEnd = function(row, column) { - return this.end.row == row && this.end.column == column; - } - - /** - * Range.isStart(row, column) -> Boolean - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * - * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. - * - **/ - this.isStart = function(row, column) { - return this.start.row == row && this.start.column == column; - } - - /** - * Range.setStart(row, column) - * - row (Number): A row point to set - * - column (Number): A column point to set - * - * Sets the starting row and column for the range. - * - **/ - this.setStart = function(row, column) { - if (typeof row == "object") { - this.start.column = row.column; - this.start.row = row.row; - } else { - this.start.row = row; - this.start.column = column; - } - } - - /** - * Range.setEnd(row, column) - * - row (Number): A row point to set - * - column (Number): A column point to set - * - * Sets the starting row and column for the range. - * - **/ - this.setEnd = function(row, column) { - if (typeof row == "object") { - this.end.column = row.column; - this.end.row = row.row; - } else { - this.end.row = row; - this.end.column = column; - } - } - - /** related to: Range.compare - * Range.inside(row, column) -> Boolean - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * - * Returns `true` if the `row` and `column` are within the given range. - * - **/ - this.inside = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isEnd(row, column) || this.isStart(row, column)) { - return false; - } else { - return true; - } - } - return false; - } - - /** related to: Range.compare - * Range.insideStart(row, column) -> Boolean - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * - * Returns `true` if the `row` and `column` are within the given range's starting points. - * - **/ - this.insideStart = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isEnd(row, column)) { - return false; - } else { - return true; - } - } - return false; - } - - /** related to: Range.compare - * Range.insideEnd(row, column) -> Boolean - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * - * Returns `true` if the `row` and `column` are within the given range's ending points. - * - **/ - this.insideEnd = function(row, column) { - if (this.compare(row, column) == 0) { - if (this.isStart(row, column)) { - return false; - } else { - return true; - } - } - return false; - } - - /** - * Range.compare(row, column) -> Number - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * + (Number): This method returns one of the following numbers:
- * * `0` if the two points are exactly equal
- * * `-1` if `p.row` is less then the calling range
- * * `1` if `p.row` is greater than the calling range
- *
- * If the starting row of the calling range is equal to `p.row`, and:
- * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`
- * * Otherwise, it returns -1
- *
- * If the ending row of the calling range is equal to `p.row`, and:
- * * `p.column` is less than or equal to the calling range's ending column, this returns `0`
- * * Otherwise, it returns 1 - * - * Checks the row and column points with the row and column points of the calling range. - * - * - **/ - this.compare = function(row, column) { - if (!this.isMultiLine()) { - if (row === this.start.row) { - return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); - }; - } - - if (row < this.start.row) - return -1; - - if (row > this.end.row) - return 1; - - if (this.start.row === row) - return column >= this.start.column ? 0 : -1; - - if (this.end.row === row) - return column <= this.end.column ? 0 : 1; - - return 0; - }; - this.compareStart = function(row, column) { - if (this.start.row == row && this.start.column == column) { - return -1; - } else { - return this.compare(row, column); - } - } - - /** - * Range.compareEnd(row, column) -> Number - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * + (Number): This method returns one of the following numbers:
- * * `0` if the two points are exactly equal
- * * `-1` if `p.row` is less then the calling range
- * * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.
- *
- * If the starting row of the calling range is equal to `p.row`, and:
- * * `p.column` is greater than or equal to the calling range's starting column, this returns `0`
- * * Otherwise, it returns -1
- *
- * If the ending row of the calling range is equal to `p.row`, and:
- * * `p.column` is less than or equal to the calling range's ending column, this returns `0`
- * * Otherwise, it returns 1 - * - * Checks the row and column points with the row and column points of the calling range. - * - * - **/ - this.compareEnd = function(row, column) { - if (this.end.row == row && this.end.column == column) { - return 1; - } else { - return this.compare(row, column); - } - } - - /** - * Range.compareInside(row, column) -> Number - * - row (Number): A row point to compare with - * - column (Number): A column point to compare with - * + (Number): This method returns one of the following numbers:
- * * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`
- * * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`
- *
- * Otherwise, it returns the value after calling [[Range.compare `compare()`]]. - * - * Checks the row and column points with the row and column points of the calling range. - * - * - * - **/ - this.compareInside = function(row, column) { - if (this.end.row == row && this.end.column == column) { - return 1; - } else if (this.start.row == row && this.start.column == column) { - return -1; - } else { - return this.compare(row, column); - } - } - - /** - * Range.clipRows(firstRow, lastRow) -> Range - * - firstRow (Number): The starting row - * - lastRow (Number): The ending row - * - * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. - * - **/ - this.clipRows = function(firstRow, lastRow) { - if (this.end.row > lastRow) { - var end = { - row: lastRow+1, - column: 0 - }; - } - - if (this.start.row > lastRow) { - var start = { - row: lastRow+1, - column: 0 - }; - } - - if (this.start.row < firstRow) { - var start = { - row: firstRow, - column: 0 - }; - } - - if (this.end.row < firstRow) { - var end = { - row: firstRow, - column: 0 - }; - } - return Range.fromPoints(start || this.start, end || this.end); - }; - this.extend = function(row, column) { - var cmp = this.compare(row, column); - - if (cmp == 0) - return this; - else if (cmp == -1) - var start = {row: row, column: column}; - else - var end = {row: row, column: column}; - - return Range.fromPoints(start || this.start, end || this.end); - }; - - this.isEmpty = function() { - return (this.start.row == this.end.row && this.start.column == this.end.column); - }; - this.isMultiLine = function() { - return (this.start.row !== this.end.row); - }; - this.clone = function() { - return Range.fromPoints(this.start, this.end); - }; - this.collapseRows = function() { - if (this.end.column == 0) - return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) - else - return new Range(this.start.row, 0, this.end.row, 0) - }; - this.toScreenRange = function(session) { - var screenPosStart = - session.documentToScreenPosition(this.start); - var screenPosEnd = - session.documentToScreenPosition(this.end); - - return new Range( - screenPosStart.row, screenPosStart.column, - screenPosEnd.row, screenPosEnd.column - ); - }; - -}).call(Range.prototype); -Range.fromPoints = function(start, end) { - return new Range(start.row, start.column, end.row, end.column); -}; - -exports.Range = Range; -}); - -define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) { - - -var oop = require("./lib/oop"); -var EventEmitter = require("./lib/event_emitter").EventEmitter; - -/** - * new Anchor(doc, row, column) - * - doc (Document): The document to associate with the anchor - * - row (Number): The starting row position - * - column (Number): The starting column position - * - * Creates a new `Anchor` and associates it with a document. - * - **/ - -var Anchor = exports.Anchor = function(doc, row, column) { - this.document = doc; - - if (typeof column == "undefined") - this.setPosition(row.row, row.column); - else - this.setPosition(row, column); - - this.$onChange = this.onChange.bind(this); - doc.on("change", this.$onChange); -}; - -(function() { - - oop.implement(this, EventEmitter); - - this.getPosition = function() { - return this.$clipPositionToDocument(this.row, this.column); - }; - - this.getDocument = function() { - return this.document; - }; - - this.onChange = function(e) { - var delta = e.data; - var range = delta.range; - - if (range.start.row == range.end.row && range.start.row != this.row) - return; - - if (range.start.row > this.row) - return; - - if (range.start.row == this.row && range.start.column > this.column) - return; - - var row = this.row; - var column = this.column; - - if (delta.action === "insertText") { - if (range.start.row === row && range.start.column <= column) { - if (range.start.row === range.end.row) { - column += range.end.column - range.start.column; - } - else { - column -= range.start.column; - row += range.end.row - range.start.row; - } - } - else if (range.start.row !== range.end.row && range.start.row < row) { - row += range.end.row - range.start.row; - } - } else if (delta.action === "insertLines") { - if (range.start.row <= row) { - row += range.end.row - range.start.row; - } - } - else if (delta.action == "removeText") { - if (range.start.row == row && range.start.column < column) { - if (range.end.column >= column) - column = range.start.column; - else - column = Math.max(0, column - (range.end.column - range.start.column)); - - } else if (range.start.row !== range.end.row && range.start.row < row) { - if (range.end.row == row) { - column = Math.max(0, column - range.end.column) + range.start.column; - } - row -= (range.end.row - range.start.row); - } - else if (range.end.row == row) { - row -= range.end.row - range.start.row; - column = Math.max(0, column - range.end.column) + range.start.column; - } - } else if (delta.action == "removeLines") { - if (range.start.row <= row) { - if (range.end.row <= row) - row -= range.end.row - range.start.row; - else { - row = range.start.row; - column = 0; - } - } - } - - this.setPosition(row, column, true); - }; - - this.setPosition = function(row, column, noClip) { - var pos; - if (noClip) { - pos = { - row: row, - column: column - }; - } - else { - pos = this.$clipPositionToDocument(row, column); - } - - if (this.row == pos.row && this.column == pos.column) - return; - - var old = { - row: this.row, - column: this.column - }; - - this.row = pos.row; - this.column = pos.column; - this._emit("change", { - old: old, - value: pos - }); - }; - - this.detach = function() { - this.document.removeEventListener("change", this.$onChange); - }; - - this.$clipPositionToDocument = function(row, column) { - var pos = {}; - - if (row >= this.document.getLength()) { - pos.row = Math.max(0, this.document.getLength() - 1); - pos.column = this.document.getLine(pos.row).length; - } - else if (row < 0) { - pos.row = 0; - pos.column = 0; - } - else { - pos.row = row; - pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); - } - - if (column < 0) - pos.column = 0; - - return pos; - }; - -}).call(Anchor.prototype); - -}); - -define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) { - - -exports.stringReverse = function(string) { - return string.split("").reverse().join(""); -}; - -exports.stringRepeat = function (string, count) { - return new Array(count + 1).join(string); -}; - -var trimBeginRegexp = /^\s\s*/; -var trimEndRegexp = /\s\s*$/; - -exports.stringTrimLeft = function (string) { - return string.replace(trimBeginRegexp, ''); -}; - -exports.stringTrimRight = function (string) { - return string.replace(trimEndRegexp, ''); -}; - -exports.copyObject = function(obj) { - var copy = {}; - for (var key in obj) { - copy[key] = obj[key]; - } - return copy; -}; - -exports.copyArray = function(array){ - var copy = []; - for (var i=0, l=array.length; i= 0 || __indexOf.call(COFFEE_KEYWORDS, id) >= 0)) { - tag = id.toUpperCase(); - if (tag === 'WHEN' && (_ref3 = this.tag(), __indexOf.call(LINE_BREAK, _ref3) >= 0)) { - tag = 'LEADING_WHEN'; - } else if (tag === 'FOR') { - this.seenFor = true; - } else if (tag === 'UNLESS') { - tag = 'IF'; - } else if (__indexOf.call(UNARY, tag) >= 0) { - tag = 'UNARY'; - } else if (__indexOf.call(RELATION, tag) >= 0) { - if (tag !== 'INSTANCEOF' && this.seenFor) { - tag = 'FOR' + tag; - this.seenFor = false; - } else { - tag = 'RELATION'; - if (this.value() === '!') { - this.tokens.pop(); - id = '!' + id; - } - } - } - } - if (__indexOf.call(JS_FORBIDDEN, id) >= 0) { - if (forcedIdentifier) { - tag = 'IDENTIFIER'; - id = new String(id); - id.reserved = true; - } else if (__indexOf.call(RESERVED, id) >= 0) { - this.error("reserved word \"" + id + "\""); - } - } - if (!forcedIdentifier) { - if (__indexOf.call(COFFEE_ALIASES, id) >= 0) id = COFFEE_ALIAS_MAP[id]; - tag = (function() { - switch (id) { - case '!': - return 'UNARY'; - case '==': - case '!=': - return 'COMPARE'; - case '&&': - case '||': - return 'LOGIC'; - case 'true': - case 'false': - case 'null': - case 'undefined': - return 'BOOL'; - case 'break': - case 'continue': - return 'STATEMENT'; - default: - return tag; - } - })(); - } - this.token(tag, id); - if (colon) this.token(':', ':'); - return input.length; - }; - - Lexer.prototype.numberToken = function() { - var binaryLiteral, lexedLength, match, number, octalLiteral; - if (!(match = NUMBER.exec(this.chunk))) return 0; - number = match[0]; - if (/E/.test(number)) { - this.error("exponential notation '" + number + "' must be indicated with a lowercase 'e'"); - } else if (/[BOX]/.test(number)) { - this.error("radix prefix '" + number + "' must be lowercase"); - } else if (/^0[89]/.test(number)) { - this.error("decimal literal '" + number + "' must not be prefixed with '0'"); - } else if (/^0[0-7]/.test(number)) { - this.error("octal literal '" + number + "' must be prefixed with '0o'"); - } - lexedLength = number.length; - if (octalLiteral = /0o([0-7]+)/.exec(number)) { - number = (parseInt(octalLiteral[1], 8)).toString(); - } - if (binaryLiteral = /0b([01]+)/.exec(number)) { - number = (parseInt(binaryLiteral[1], 2)).toString(); - } - this.token('NUMBER', number); - return lexedLength; - }; - - Lexer.prototype.stringToken = function() { - var match, octalEsc, string; - switch (this.chunk.charAt(0)) { - case "'": - if (!(match = SIMPLESTR.exec(this.chunk))) return 0; - this.token('STRING', (string = match[0]).replace(MULTILINER, '\\\n')); - break; - case '"': - if (!(string = this.balancedString(this.chunk, '"'))) return 0; - if (0 < string.indexOf('#{', 1)) { - this.interpolateString(string.slice(1, -1)); - } else { - this.token('STRING', this.escapeLines(string)); - } - break; - default: - return 0; - } - if (octalEsc = /^(?:\\.|[^\\])*\\[0-7]/.test(string)) { - this.error("octal escape sequences " + string + " are not allowed"); - } - this.line += count(string, '\n'); - return string.length; - }; - - Lexer.prototype.heredocToken = function() { - var doc, heredoc, match, quote; - if (!(match = HEREDOC.exec(this.chunk))) return 0; - heredoc = match[0]; - quote = heredoc.charAt(0); - doc = this.sanitizeHeredoc(match[2], { - quote: quote, - indent: null - }); - if (quote === '"' && 0 <= doc.indexOf('#{')) { - this.interpolateString(doc, { - heredoc: true - }); - } else { - this.token('STRING', this.makeString(doc, quote, true)); - } - this.line += count(heredoc, '\n'); - return heredoc.length; - }; - - Lexer.prototype.commentToken = function() { - var comment, here, match; - if (!(match = this.chunk.match(COMMENT))) return 0; - comment = match[0], here = match[1]; - if (here) { - this.token('HERECOMMENT', this.sanitizeHeredoc(here, { - herecomment: true, - indent: Array(this.indent + 1).join(' ') - })); - } - this.line += count(comment, '\n'); - return comment.length; - }; - - Lexer.prototype.jsToken = function() { - var match, script; - if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) { - return 0; - } - this.token('JS', (script = match[0]).slice(1, -1)); - return script.length; - }; - - Lexer.prototype.regexToken = function() { - var flags, length, match, prev, regex, _ref2, _ref3; - if (this.chunk.charAt(0) !== '/') return 0; - if (match = HEREGEX.exec(this.chunk)) { - length = this.heregexToken(match); - this.line += count(match[0], '\n'); - return length; - } - prev = last(this.tokens); - if (prev && (_ref2 = prev[0], __indexOf.call((prev.spaced ? NOT_REGEX : NOT_SPACED_REGEX), _ref2) >= 0)) { - return 0; - } - if (!(match = REGEX.exec(this.chunk))) return 0; - _ref3 = match, match = _ref3[0], regex = _ref3[1], flags = _ref3[2]; - if (regex.slice(0, 2) === '/*') { - this.error('Cannot use /* ... */ comments in CoffeeScript, nor can a regular expression begin with `*`'); - } - if (regex === '//') regex = '/(?:)/'; - this.token('REGEX', "" + regex + flags); - return match.length; - }; - - Lexer.prototype.heregexToken = function(match) { - var body, flags, heregex, re, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4, _ref5; - heregex = match[0], body = match[1], flags = match[2]; - if (0 > body.indexOf('#{')) { - re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/'); - if (re.match(/^\*/)) { - this.error('regular expressions cannot begin with `*`'); - } - this.token('REGEX', "/" + (re || '(?:)') + "/" + flags); - return heregex.length; - } - this.token('IDENTIFIER', 'RegExp'); - this.tokens.push(['CALL_START', '(']); - tokens = []; - _ref2 = this.interpolateString(body, { - regex: true - }); - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - _ref3 = _ref2[_i], tag = _ref3[0], value = _ref3[1]; - if (tag === 'TOKENS') { - tokens.push.apply(tokens, value); - } else { - if (!(value = value.replace(HEREGEX_OMIT, ''))) continue; - value = value.replace(/\\/g, '\\\\'); - tokens.push(['STRING', this.makeString(value, '"', true)]); - } - tokens.push(['+', '+']); - } - tokens.pop(); - if (((_ref4 = tokens[0]) != null ? _ref4[0] : void 0) !== 'STRING') { - this.tokens.push(['STRING', '""'], ['+', '+']); - } - (_ref5 = this.tokens).push.apply(_ref5, tokens); - if (flags) this.tokens.push([',', ','], ['STRING', '"' + flags + '"']); - this.token(')', ')'); - return heregex.length; - }; - - Lexer.prototype.lineToken = function() { - var diff, indent, match, noNewlines, prev, size; - if (!(match = MULTI_DENT.exec(this.chunk))) return 0; - indent = match[0]; - this.line += count(indent, '\n'); - this.seenFor = false; - prev = last(this.tokens, 1); - size = indent.length - 1 - indent.lastIndexOf('\n'); - noNewlines = this.unfinished(); - if (size - this.indebt === this.indent) { - if (noNewlines) { - this.suppressNewlines(); - } else { - this.newlineToken(); - } - return indent.length; - } - if (size > this.indent) { - if (noNewlines) { - this.indebt = size - this.indent; - this.suppressNewlines(); - return indent.length; - } - diff = size - this.indent + this.outdebt; - this.token('INDENT', diff); - this.indents.push(diff); - this.ends.push('OUTDENT'); - this.outdebt = this.indebt = 0; - } else { - this.indebt = 0; - this.outdentToken(this.indent - size, noNewlines); - } - this.indent = size; - return indent.length; - }; - - Lexer.prototype.outdentToken = function(moveOut, noNewlines) { - var dent, len; - while (moveOut > 0) { - len = this.indents.length - 1; - if (this.indents[len] === void 0) { - moveOut = 0; - } else if (this.indents[len] === this.outdebt) { - moveOut -= this.outdebt; - this.outdebt = 0; - } else if (this.indents[len] < this.outdebt) { - this.outdebt -= this.indents[len]; - moveOut -= this.indents[len]; - } else { - dent = this.indents.pop() - this.outdebt; - moveOut -= dent; - this.outdebt = 0; - this.pair('OUTDENT'); - this.token('OUTDENT', dent); - } - } - if (dent) this.outdebt -= moveOut; - while (this.value() === ';') { - this.tokens.pop(); - } - if (!(this.tag() === 'TERMINATOR' || noNewlines)) { - this.token('TERMINATOR', '\n'); - } - return this; - }; - - Lexer.prototype.whitespaceToken = function() { - var match, nline, prev; - if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) { - return 0; - } - prev = last(this.tokens); - if (prev) prev[match ? 'spaced' : 'newLine'] = true; - if (match) { - return match[0].length; - } else { - return 0; - } - }; - - Lexer.prototype.newlineToken = function() { - while (this.value() === ';') { - this.tokens.pop(); - } - if (this.tag() !== 'TERMINATOR') this.token('TERMINATOR', '\n'); - return this; - }; - - Lexer.prototype.suppressNewlines = function() { - if (this.value() === '\\') this.tokens.pop(); - return this; - }; - - Lexer.prototype.literalToken = function() { - var match, prev, tag, value, _ref2, _ref3, _ref4, _ref5; - if (match = OPERATOR.exec(this.chunk)) { - value = match[0]; - if (CODE.test(value)) this.tagParameters(); - } else { - value = this.chunk.charAt(0); - } - tag = value; - prev = last(this.tokens); - if (value === '=' && prev) { - if (!prev[1].reserved && (_ref2 = prev[1], __indexOf.call(JS_FORBIDDEN, _ref2) >= 0)) { - this.error("reserved word \"" + (this.value()) + "\" can't be assigned"); - } - if ((_ref3 = prev[1]) === '||' || _ref3 === '&&') { - prev[0] = 'COMPOUND_ASSIGN'; - prev[1] += '='; - return value.length; - } - } - if (value === ';') { - this.seenFor = false; - tag = 'TERMINATOR'; - } else if (__indexOf.call(MATH, value) >= 0) { - tag = 'MATH'; - } else if (__indexOf.call(COMPARE, value) >= 0) { - tag = 'COMPARE'; - } else if (__indexOf.call(COMPOUND_ASSIGN, value) >= 0) { - tag = 'COMPOUND_ASSIGN'; - } else if (__indexOf.call(UNARY, value) >= 0) { - tag = 'UNARY'; - } else if (__indexOf.call(SHIFT, value) >= 0) { - tag = 'SHIFT'; - } else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) { - tag = 'LOGIC'; - } else if (prev && !prev.spaced) { - if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) { - if (prev[0] === '?') prev[0] = 'FUNC_EXIST'; - tag = 'CALL_START'; - } else if (value === '[' && (_ref5 = prev[0], __indexOf.call(INDEXABLE, _ref5) >= 0)) { - tag = 'INDEX_START'; - switch (prev[0]) { - case '?': - prev[0] = 'INDEX_SOAK'; - } - } - } - switch (value) { - case '(': - case '{': - case '[': - this.ends.push(INVERSES[value]); - break; - case ')': - case '}': - case ']': - this.pair(value); - } - this.token(tag, value); - return value.length; - }; - - Lexer.prototype.sanitizeHeredoc = function(doc, options) { - var attempt, herecomment, indent, match, _ref2; - indent = options.indent, herecomment = options.herecomment; - if (herecomment) { - if (HEREDOC_ILLEGAL.test(doc)) { - this.error("block comment cannot contain \"*/\", starting"); - } - if (doc.indexOf('\n') <= 0) return doc; - } else { - while (match = HEREDOC_INDENT.exec(doc)) { - attempt = match[1]; - if (indent === null || (0 < (_ref2 = attempt.length) && _ref2 < indent.length)) { - indent = attempt; - } - } - } - if (indent) doc = doc.replace(RegExp("\\n" + indent, "g"), '\n'); - if (!herecomment) doc = doc.replace(/^\n/, ''); - return doc; - }; - - Lexer.prototype.tagParameters = function() { - var i, stack, tok, tokens; - if (this.tag() !== ')') return this; - stack = []; - tokens = this.tokens; - i = tokens.length; - tokens[--i][0] = 'PARAM_END'; - while (tok = tokens[--i]) { - switch (tok[0]) { - case ')': - stack.push(tok); - break; - case '(': - case 'CALL_START': - if (stack.length) { - stack.pop(); - } else if (tok[0] === '(') { - tok[0] = 'PARAM_START'; - return this; - } else { - return this; - } - } - } - return this; - }; - - Lexer.prototype.closeIndentation = function() { - return this.outdentToken(this.indent); - }; - - Lexer.prototype.balancedString = function(str, end) { - var continueCount, i, letter, match, prev, stack, _i, _ref2; - continueCount = 0; - stack = [end]; - for (i = _i = 1, _ref2 = str.length; 1 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 1 <= _ref2 ? ++_i : --_i) { - if (continueCount) { - --continueCount; - continue; - } - switch (letter = str.charAt(i)) { - case '\\': - ++continueCount; - continue; - case end: - stack.pop(); - if (!stack.length) return str.slice(0, i + 1 || 9e9); - end = stack[stack.length - 1]; - continue; - } - if (end === '}' && (letter === '"' || letter === "'")) { - stack.push(end = letter); - } else if (end === '}' && letter === '/' && (match = HEREGEX.exec(str.slice(i)) || REGEX.exec(str.slice(i)))) { - continueCount += match[0].length - 1; - } else if (end === '}' && letter === '{') { - stack.push(end = '}'); - } else if (end === '"' && prev === '#' && letter === '{') { - stack.push(end = '}'); - } - prev = letter; - } - return this.error("missing " + (stack.pop()) + ", starting"); - }; - - Lexer.prototype.interpolateString = function(str, options) { - var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4; - if (options == null) options = {}; - heredoc = options.heredoc, regex = options.regex; - tokens = []; - pi = 0; - i = -1; - while (letter = str.charAt(i += 1)) { - if (letter === '\\') { - i += 1; - continue; - } - if (!(letter === '#' && str.charAt(i + 1) === '{' && (expr = this.balancedString(str.slice(i + 1), '}')))) { - continue; - } - if (pi < i) tokens.push(['NEOSTRING', str.slice(pi, i)]); - inner = expr.slice(1, -1); - if (inner.length) { - nested = new Lexer().tokenize(inner, { - line: this.line, - rewrite: false - }); - nested.pop(); - if (((_ref2 = nested[0]) != null ? _ref2[0] : void 0) === 'TERMINATOR') { - nested.shift(); - } - if (len = nested.length) { - if (len > 1) { - nested.unshift(['(', '(', this.line]); - nested.push([')', ')', this.line]); - } - tokens.push(['TOKENS', nested]); - } - } - i += expr.length; - pi = i + 1; - } - if ((i > pi && pi < str.length)) tokens.push(['NEOSTRING', str.slice(pi)]); - if (regex) return tokens; - if (!tokens.length) return this.token('STRING', '""'); - if (tokens[0][0] !== 'NEOSTRING') tokens.unshift(['', '']); - if (interpolated = tokens.length > 1) this.token('(', '('); - for (i = _i = 0, _len = tokens.length; _i < _len; i = ++_i) { - _ref3 = tokens[i], tag = _ref3[0], value = _ref3[1]; - if (i) this.token('+', '+'); - if (tag === 'TOKENS') { - (_ref4 = this.tokens).push.apply(_ref4, value); - } else { - this.token('STRING', this.makeString(value, '"', heredoc)); - } - } - if (interpolated) this.token(')', ')'); - return tokens; - }; - - Lexer.prototype.pair = function(tag) { - var size, wanted; - if (tag !== (wanted = last(this.ends))) { - if ('OUTDENT' !== wanted) this.error("unmatched " + tag); - this.indent -= size = last(this.indents); - this.outdentToken(size, true); - return this.pair(tag); - } - return this.ends.pop(); - }; - - Lexer.prototype.token = function(tag, value) { - return this.tokens.push([tag, value, this.line]); - }; - - Lexer.prototype.tag = function(index, tag) { - var tok; - return (tok = last(this.tokens, index)) && (tag ? tok[0] = tag : tok[0]); - }; - - Lexer.prototype.value = function(index, val) { - var tok; - return (tok = last(this.tokens, index)) && (val ? tok[1] = val : tok[1]); - }; - - Lexer.prototype.unfinished = function() { - var _ref2; - return LINE_CONTINUER.test(this.chunk) || ((_ref2 = this.tag()) === '\\' || _ref2 === '.' || _ref2 === '?.' || _ref2 === 'UNARY' || _ref2 === 'MATH' || _ref2 === '+' || _ref2 === '-' || _ref2 === 'SHIFT' || _ref2 === 'RELATION' || _ref2 === 'COMPARE' || _ref2 === 'LOGIC' || _ref2 === 'THROW' || _ref2 === 'EXTENDS'); - }; - - Lexer.prototype.escapeLines = function(str, heredoc) { - return str.replace(MULTILINER, heredoc ? '\\n' : ''); - }; - - Lexer.prototype.makeString = function(body, quote, heredoc) { - if (!body) return quote + quote; - body = body.replace(/\\([\s\S])/g, function(match, contents) { - if (contents === '\n' || contents === quote) { - return contents; - } else { - return match; - } - }); - body = body.replace(RegExp("" + quote, "g"), '\\$&'); - return quote + this.escapeLines(body, heredoc) + quote; - }; - - Lexer.prototype.error = function(message) { - throw SyntaxError("" + message + " on line " + (this.line + 1)); - }; - - return Lexer; - - })(); - - JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super']; - - COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when']; - - COFFEE_ALIAS_MAP = { - and: '&&', - or: '||', - is: '==', - isnt: '!=', - not: '!', - yes: 'true', - no: 'false', - on: 'true', - off: 'false' - }; - - COFFEE_ALIASES = (function() { - var _results; - _results = []; - for (key in COFFEE_ALIAS_MAP) { - _results.push(key); - } - return _results; - })(); - - COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES); - - RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf', 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', 'yield']; - - STRICT_PROSCRIBED = ['arguments', 'eval']; - - JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED); - - exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED); - - exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED; - - IDENTIFIER = /^([$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)([^\n\S]*:(?!:))?/; - - NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i; - - HEREDOC = /^("""|''')([\s\S]*?)(?:\n[^\n\S]*)?\1/; - - OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/; - - WHITESPACE = /^[^\n\S]+/; - - COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/; - - CODE = /^[-=]>/; - - MULTI_DENT = /^(?:\n[^\n\S]*)+/; - - SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/; - - JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/; - - REGEX = /^(\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/)([imgy]{0,4})(?!\w)/; - - HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/; - - HEREGEX_OMIT = /\s+(?:#.*)?/g; - - MULTILINER = /\n/g; - - HEREDOC_INDENT = /\n+([^\n\S]*)/g; - - HEREDOC_ILLEGAL = /\*\//; - - LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/; - - TRAILING_SPACES = /\s+$/; - - COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|=']; - - UNARY = ['!', '~', 'NEW', 'TYPEOF', 'DELETE', 'DO']; - - LOGIC = ['&&', '||', '&', '|', '^']; - - SHIFT = ['<<', '>>', '>>>']; - - COMPARE = ['==', '!=', '<', '>', '<=', '>=']; - - MATH = ['*', '/', '%']; - - RELATION = ['IN', 'OF', 'INSTANCEOF']; - - BOOL = ['TRUE', 'FALSE', 'NULL', 'UNDEFINED']; - - NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', '++', '--', ']']; - - NOT_SPACED_REGEX = NOT_REGEX.concat(')', '}', 'THIS', 'IDENTIFIER', 'STRING'); - - CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER']; - - INDEXABLE = CALLABLE.concat('NUMBER', 'BOOL'); - - LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR']; - - -}); - -define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(require, exports, module) { -// Generated by CoffeeScript 1.2.1-pre - - var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_BLOCK, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, left, rite, _i, _len, _ref, - __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, - __slice = [].slice; - - exports.Rewriter = (function() { - - Rewriter.name = 'Rewriter'; - - function Rewriter() {} - - Rewriter.prototype.rewrite = function(tokens) { - this.tokens = tokens; - this.removeLeadingNewlines(); - this.removeMidExpressionNewlines(); - this.closeOpenCalls(); - this.closeOpenIndexes(); - this.addImplicitIndentation(); - this.tagPostfixConditionals(); - this.addImplicitBraces(); - this.addImplicitParentheses(); - return this.tokens; - }; - - Rewriter.prototype.scanTokens = function(block) { - var i, token, tokens; - tokens = this.tokens; - i = 0; - while (token = tokens[i]) { - i += block.call(this, token, i, tokens); - } - return true; - }; - - Rewriter.prototype.detectEnd = function(i, condition, action) { - var levels, token, tokens, _ref, _ref1; - tokens = this.tokens; - levels = 0; - while (token = tokens[i]) { - if (levels === 0 && condition.call(this, token, i)) { - return action.call(this, token, i); - } - if (!token || levels < 0) return action.call(this, token, i - 1); - if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) { - levels += 1; - } else if (_ref1 = token[0], __indexOf.call(EXPRESSION_END, _ref1) >= 0) { - levels -= 1; - } - i += 1; - } - return i - 1; - }; - - Rewriter.prototype.removeLeadingNewlines = function() { - var i, tag, _i, _len, _ref; - _ref = this.tokens; - for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { - tag = _ref[i][0]; - if (tag !== 'TERMINATOR') break; - } - if (i) return this.tokens.splice(0, i); - }; - - Rewriter.prototype.removeMidExpressionNewlines = function() { - return this.scanTokens(function(token, i, tokens) { - var _ref; - if (!(token[0] === 'TERMINATOR' && (_ref = this.tag(i + 1), __indexOf.call(EXPRESSION_CLOSE, _ref) >= 0))) { - return 1; - } - tokens.splice(i, 1); - return 0; - }); - }; - - Rewriter.prototype.closeOpenCalls = function() { - var action, condition; - condition = function(token, i) { - var _ref; - return ((_ref = token[0]) === ')' || _ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')'; - }; - action = function(token, i) { - return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END'; - }; - return this.scanTokens(function(token, i) { - if (token[0] === 'CALL_START') this.detectEnd(i + 1, condition, action); - return 1; - }); - }; - - Rewriter.prototype.closeOpenIndexes = function() { - var action, condition; - condition = function(token, i) { - var _ref; - return (_ref = token[0]) === ']' || _ref === 'INDEX_END'; - }; - action = function(token, i) { - return token[0] = 'INDEX_END'; - }; - return this.scanTokens(function(token, i) { - if (token[0] === 'INDEX_START') this.detectEnd(i + 1, condition, action); - return 1; - }); - }; - - Rewriter.prototype.addImplicitBraces = function() { - var action, condition, sameLine, stack, start, startIndent, startsLine; - stack = []; - start = null; - startsLine = null; - sameLine = true; - startIndent = 0; - condition = function(token, i) { - var one, tag, three, two, _ref, _ref1; - _ref = this.tokens.slice(i + 1, (i + 3) + 1 || 9e9), one = _ref[0], two = _ref[1], three = _ref[2]; - if ('HERECOMMENT' === (one != null ? one[0] : void 0)) return false; - tag = token[0]; - if (__indexOf.call(LINEBREAKS, tag) >= 0) sameLine = false; - return (((tag === 'TERMINATOR' || tag === 'OUTDENT') || (__indexOf.call(IMPLICIT_END, tag) >= 0 && sameLine)) && ((!startsLine && this.tag(i - 1) !== ',') || !((two != null ? two[0] : void 0) === ':' || (one != null ? one[0] : void 0) === '@' && (three != null ? three[0] : void 0) === ':'))) || (tag === ',' && one && ((_ref1 = one[0]) !== 'IDENTIFIER' && _ref1 !== 'NUMBER' && _ref1 !== 'STRING' && _ref1 !== '@' && _ref1 !== 'TERMINATOR' && _ref1 !== 'OUTDENT')); - }; - action = function(token, i) { - var tok; - tok = this.generate('}', '}', token[2]); - return this.tokens.splice(i, 0, tok); - }; - return this.scanTokens(function(token, i, tokens) { - var ago, idx, prevTag, tag, tok, value, _ref, _ref1; - if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) { - stack.push([(tag === 'INDENT' && this.tag(i - 1) === '{' ? '{' : tag), i]); - return 1; - } - if (__indexOf.call(EXPRESSION_END, tag) >= 0) { - start = stack.pop(); - return 1; - } - if (!(tag === ':' && ((ago = this.tag(i - 2)) === ':' || ((_ref1 = stack[stack.length - 1]) != null ? _ref1[0] : void 0) !== '{'))) { - return 1; - } - sameLine = true; - stack.push(['{']); - idx = ago === '@' ? i - 2 : i - 1; - while (this.tag(idx - 2) === 'HERECOMMENT') { - idx -= 2; - } - prevTag = this.tag(idx - 1); - startsLine = !prevTag || (__indexOf.call(LINEBREAKS, prevTag) >= 0); - value = new String('{'); - value.generated = true; - tok = this.generate('{', value, token[2]); - tokens.splice(idx, 0, tok); - this.detectEnd(i + 2, condition, action); - return 2; - }); - }; - - Rewriter.prototype.addImplicitParentheses = function() { - var action, condition, noCall, seenControl, seenSingle; - noCall = seenSingle = seenControl = false; - condition = function(token, i) { - var post, tag, _ref, _ref1; - tag = token[0]; - if (!seenSingle && token.fromThen) return true; - if (tag === 'IF' || tag === 'ELSE' || tag === 'CATCH' || tag === '->' || tag === '=>' || tag === 'CLASS') { - seenSingle = true; - } - if (tag === 'IF' || tag === 'ELSE' || tag === 'SWITCH' || tag === 'TRY' || tag === '=') { - seenControl = true; - } - if ((tag === '.' || tag === '?.' || tag === '::') && this.tag(i - 1) === 'OUTDENT') { - return true; - } - return !token.generated && this.tag(i - 1) !== ',' && (__indexOf.call(IMPLICIT_END, tag) >= 0 || (tag === 'INDENT' && !seenControl)) && (tag !== 'INDENT' || (((_ref = this.tag(i - 2)) !== 'CLASS' && _ref !== 'EXTENDS') && (_ref1 = this.tag(i - 1), __indexOf.call(IMPLICIT_BLOCK, _ref1) < 0) && !((post = this.tokens[i + 1]) && post.generated && post[0] === '{'))); - }; - action = function(token, i) { - return this.tokens.splice(i, 0, this.generate('CALL_END', ')', token[2])); - }; - return this.scanTokens(function(token, i, tokens) { - var callObject, current, next, prev, tag, _ref, _ref1, _ref2; - tag = token[0]; - if (tag === 'CLASS' || tag === 'IF' || tag === 'FOR' || tag === 'WHILE') { - noCall = true; - } - _ref = tokens.slice(i - 1, (i + 1) + 1 || 9e9), prev = _ref[0], current = _ref[1], next = _ref[2]; - callObject = !noCall && tag === 'INDENT' && next && next.generated && next[0] === '{' && prev && (_ref1 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref1) >= 0); - seenSingle = false; - seenControl = false; - if (__indexOf.call(LINEBREAKS, tag) >= 0) noCall = false; - if (prev && !prev.spaced && tag === '?') token.call = true; - if (token.fromThen) return 1; - if (!(callObject || (prev != null ? prev.spaced : void 0) && (prev.call || (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) { - return 1; - } - tokens.splice(i, 0, this.generate('CALL_START', '(', token[2])); - this.detectEnd(i + 1, condition, action); - if (prev[0] === '?') prev[0] = 'FUNC_EXIST'; - return 2; - }); - }; - - Rewriter.prototype.addImplicitIndentation = function() { - var action, condition, indent, outdent, starter; - starter = indent = outdent = null; - condition = function(token, i) { - var _ref; - return token[1] !== ';' && (_ref = token[0], __indexOf.call(SINGLE_CLOSERS, _ref) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN')); - }; - action = function(token, i) { - return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent); - }; - return this.scanTokens(function(token, i, tokens) { - var tag, _ref, _ref1; - tag = token[0]; - if (tag === 'TERMINATOR' && this.tag(i + 1) === 'THEN') { - tokens.splice(i, 1); - return 0; - } - if (tag === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') { - tokens.splice.apply(tokens, [i, 0].concat(__slice.call(this.indentation(token)))); - return 2; - } - if (tag === 'CATCH' && ((_ref = this.tag(i + 2)) === 'OUTDENT' || _ref === 'TERMINATOR' || _ref === 'FINALLY')) { - tokens.splice.apply(tokens, [i + 2, 0].concat(__slice.call(this.indentation(token)))); - return 4; - } - if (__indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) { - starter = tag; - _ref1 = this.indentation(token, true), indent = _ref1[0], outdent = _ref1[1]; - if (starter === 'THEN') indent.fromThen = true; - tokens.splice(i + 1, 0, indent); - this.detectEnd(i + 2, condition, action); - if (tag === 'THEN') tokens.splice(i, 1); - return 1; - } - return 1; - }); - }; - - Rewriter.prototype.tagPostfixConditionals = function() { - var action, condition, original; - original = null; - condition = function(token, i) { - var _ref; - return (_ref = token[0]) === 'TERMINATOR' || _ref === 'INDENT'; - }; - action = function(token, i) { - if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) { - return original[0] = 'POST_' + original[0]; - } - }; - return this.scanTokens(function(token, i) { - if (token[0] !== 'IF') return 1; - original = token; - this.detectEnd(i + 1, condition, action); - return 1; - }); - }; - - Rewriter.prototype.indentation = function(token, implicit) { - var indent, outdent; - if (implicit == null) implicit = false; - indent = ['INDENT', 2, token[2]]; - outdent = ['OUTDENT', 2, token[2]]; - if (implicit) indent.generated = outdent.generated = true; - return [indent, outdent]; - }; - - Rewriter.prototype.generate = function(tag, value, line) { - var tok; - tok = [tag, value, line]; - tok.generated = true; - return tok; - }; - - Rewriter.prototype.tag = function(i) { - var _ref; - return (_ref = this.tokens[i]) != null ? _ref[0] : void 0; - }; - - return Rewriter; - - })(); - - BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']]; - - exports.INVERSES = INVERSES = {}; - - EXPRESSION_START = []; - - EXPRESSION_END = []; - - for (_i = 0, _len = BALANCED_PAIRS.length; _i < _len; _i++) { - _ref = BALANCED_PAIRS[_i], left = _ref[0], rite = _ref[1]; - EXPRESSION_START.push(INVERSES[rite] = left); - EXPRESSION_END.push(INVERSES[left] = rite); - } - - EXPRESSION_CLOSE = ['CATCH', 'WHEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END); - - IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS']; - - IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'JS', 'REGEX', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'UNARY', 'SUPER', '@', '->', '=>', '[', '(', '{', '--', '++']; - - IMPLICIT_UNSPACED_CALL = ['+', '-']; - - IMPLICIT_BLOCK = ['->', '=>', '{', '[', ',']; - - IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR']; - - SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN']; - - SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN']; - - LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT']; - - -}); - -define('ace/mode/coffee/helpers', ['require', 'exports', 'module' ], function(require, exports, module) { -// Generated by CoffeeScript 1.2.1-pre - - var extend, flatten; - - exports.starts = function(string, literal, start) { - return literal === string.substr(start, literal.length); - }; - - exports.ends = function(string, literal, back) { - var len; - len = literal.length; - return literal === string.substr(string.length - len - (back || 0), len); - }; - - exports.compact = function(array) { - var item, _i, _len, _results; - _results = []; - for (_i = 0, _len = array.length; _i < _len; _i++) { - item = array[_i]; - if (item) _results.push(item); - } - return _results; - }; - - exports.count = function(string, substr) { - var num, pos; - num = pos = 0; - if (!substr.length) return 1 / 0; - while (pos = 1 + string.indexOf(substr, pos)) { - num++; - } - return num; - }; - - exports.merge = function(options, overrides) { - return extend(extend({}, options), overrides); - }; - - extend = exports.extend = function(object, properties) { - var key, val; - for (key in properties) { - val = properties[key]; - object[key] = val; - } - return object; - }; - - exports.flatten = flatten = function(array) { - var element, flattened, _i, _len; - flattened = []; - for (_i = 0, _len = array.length; _i < _len; _i++) { - element = array[_i]; - if (element instanceof Array) { - flattened = flattened.concat(flatten(element)); - } else { - flattened.push(element); - } - } - return flattened; - }; - - exports.del = function(obj, key) { - var val; - val = obj[key]; - delete obj[key]; - return val; - }; - - exports.last = function(array, back) { - return array[array.length - (back || 0) - 1]; - }; - - -}); - -define('ace/mode/coffee/parser', ['require', 'exports', 'module' ], function(require, exports, module) { -/* Jison generated parser */ - -undefined -var parser = {trace: function trace() { }, -yy: {}, -symbols_: {"error":2,"Root":3,"Body":4,"Block":5,"TERMINATOR":6,"Line":7,"Expression":8,"Statement":9,"Return":10,"Comment":11,"STATEMENT":12,"Value":13,"Invocation":14,"Code":15,"Operation":16,"Assign":17,"If":18,"Try":19,"While":20,"For":21,"Switch":22,"Class":23,"Throw":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"STRING":31,"Literal":32,"JS":33,"REGEX":34,"DEBUGGER":35,"BOOL":36,"Assignable":37,"=":38,"AssignObj":39,"ObjAssignable":40,":":41,"ThisProperty":42,"RETURN":43,"HERECOMMENT":44,"PARAM_START":45,"ParamList":46,"PARAM_END":47,"FuncGlyph":48,"->":49,"=>":50,"OptComma":51,",":52,"Param":53,"ParamVar":54,"...":55,"Array":56,"Object":57,"Splat":58,"SimpleAssignable":59,"Accessor":60,"Parenthetical":61,"Range":62,"This":63,".":64,"?.":65,"::":66,"Index":67,"INDEX_START":68,"IndexValue":69,"INDEX_END":70,"INDEX_SOAK":71,"Slice":72,"{":73,"AssignList":74,"}":75,"CLASS":76,"EXTENDS":77,"OptFuncExist":78,"Arguments":79,"SUPER":80,"FUNC_EXIST":81,"CALL_START":82,"CALL_END":83,"ArgList":84,"THIS":85,"@":86,"[":87,"]":88,"RangeDots":89,"..":90,"Arg":91,"SimpleArgs":92,"TRY":93,"Catch":94,"FINALLY":95,"CATCH":96,"THROW":97,"(":98,")":99,"WhileSource":100,"WHILE":101,"WHEN":102,"UNTIL":103,"Loop":104,"LOOP":105,"ForBody":106,"FOR":107,"ForStart":108,"ForSource":109,"ForVariables":110,"OWN":111,"ForValue":112,"FORIN":113,"FOROF":114,"BY":115,"SWITCH":116,"Whens":117,"ELSE":118,"When":119,"LEADING_WHEN":120,"IfBlock":121,"IF":122,"POST_IF":123,"UNARY":124,"-":125,"+":126,"--":127,"++":128,"?":129,"MATH":130,"SHIFT":131,"COMPARE":132,"LOGIC":133,"RELATION":134,"COMPOUND_ASSIGN":135,"$accept":0,"$end":1}, -terminals_: {2:"error",6:"TERMINATOR",12:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"DEBUGGER",36:"BOOL",38:"=",41:":",43:"RETURN",44:"HERECOMMENT",45:"PARAM_START",47:"PARAM_END",49:"->",50:"=>",52:",",55:"...",64:".",65:"?.",66:"::",68:"INDEX_START",70:"INDEX_END",71:"INDEX_SOAK",73:"{",75:"}",76:"CLASS",77:"EXTENDS",80:"SUPER",81:"FUNC_EXIST",82:"CALL_START",83:"CALL_END",85:"THIS",86:"@",87:"[",88:"]",90:"..",93:"TRY",95:"FINALLY",96:"CATCH",97:"THROW",98:"(",99:")",101:"WHILE",102:"WHEN",103:"UNTIL",105:"LOOP",107:"FOR",111:"OWN",113:"FORIN",114:"FOROF",115:"BY",116:"SWITCH",118:"ELSE",120:"LEADING_WHEN",122:"IF",123:"POST_IF",124:"UNARY",125:"-",126:"+",127:"--",128:"++",129:"?",130:"MATH",131:"SHIFT",132:"COMPARE",133:"LOGIC",134:"RELATION",135:"COMPOUND_ASSIGN"}, -productions_: [0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[32,1],[17,3],[17,4],[17,5],[39,1],[39,3],[39,5],[39,1],[40,1],[40,1],[40,1],[10,2],[10,1],[11,1],[15,5],[15,2],[48,1],[48,1],[51,0],[51,1],[46,0],[46,1],[46,3],[53,1],[53,2],[53,3],[54,1],[54,1],[54,1],[54,1],[58,2],[59,1],[59,2],[59,2],[59,1],[37,1],[37,1],[37,1],[13,1],[13,1],[13,1],[13,1],[13,1],[60,2],[60,2],[60,2],[60,1],[60,1],[67,3],[67,2],[69,1],[69,1],[57,4],[74,0],[74,1],[74,3],[74,4],[74,6],[23,1],[23,2],[23,3],[23,4],[23,2],[23,3],[23,4],[23,5],[14,3],[14,3],[14,1],[14,2],[78,0],[78,1],[79,2],[79,4],[63,1],[63,1],[42,2],[56,2],[56,4],[89,1],[89,1],[62,5],[72,3],[72,2],[72,2],[72,1],[84,1],[84,3],[84,4],[84,4],[84,6],[91,1],[91,1],[92,1],[92,3],[19,2],[19,3],[19,4],[19,5],[94,3],[24,2],[61,3],[61,5],[100,2],[100,4],[100,2],[100,4],[20,2],[20,2],[20,2],[20,1],[104,2],[104,2],[21,2],[21,2],[21,2],[106,2],[106,2],[108,2],[108,3],[112,1],[112,1],[112,1],[110,1],[110,3],[109,2],[109,2],[109,4],[109,4],[109,4],[109,6],[109,6],[22,5],[22,7],[22,4],[22,6],[117,1],[117,2],[119,3],[119,4],[121,3],[121,5],[18,1],[18,3],[18,3],[18,3],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,5],[16,3]], -performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { - -var $0 = $$.length - 1; -switch (yystate) { -case 1:return this.$ = new yy.Block; -break; -case 2:return this.$ = $$[$0]; -break; -case 3:return this.$ = $$[$0-1]; -break; -case 4:this.$ = yy.Block.wrap([$$[$0]]); -break; -case 5:this.$ = $$[$0-2].push($$[$0]); -break; -case 6:this.$ = $$[$0-1]; -break; -case 7:this.$ = $$[$0]; -break; -case 8:this.$ = $$[$0]; -break; -case 9:this.$ = $$[$0]; -break; -case 10:this.$ = $$[$0]; -break; -case 11:this.$ = new yy.Literal($$[$0]); -break; -case 12:this.$ = $$[$0]; -break; -case 13:this.$ = $$[$0]; -break; -case 14:this.$ = $$[$0]; -break; -case 15:this.$ = $$[$0]; -break; -case 16:this.$ = $$[$0]; -break; -case 17:this.$ = $$[$0]; -break; -case 18:this.$ = $$[$0]; -break; -case 19:this.$ = $$[$0]; -break; -case 20:this.$ = $$[$0]; -break; -case 21:this.$ = $$[$0]; -break; -case 22:this.$ = $$[$0]; -break; -case 23:this.$ = $$[$0]; -break; -case 24:this.$ = new yy.Block; -break; -case 25:this.$ = $$[$0-1]; -break; -case 26:this.$ = new yy.Literal($$[$0]); -break; -case 27:this.$ = new yy.Literal($$[$0]); -break; -case 28:this.$ = new yy.Literal($$[$0]); -break; -case 29:this.$ = $$[$0]; -break; -case 30:this.$ = new yy.Literal($$[$0]); -break; -case 31:this.$ = new yy.Literal($$[$0]); -break; -case 32:this.$ = new yy.Literal($$[$0]); -break; -case 33:this.$ = (function () { - var val; - val = new yy.Literal($$[$0]); - if ($$[$0] === 'undefined') val.isUndefined = true; - return val; - }()); -break; -case 34:this.$ = new yy.Assign($$[$0-2], $$[$0]); -break; -case 35:this.$ = new yy.Assign($$[$0-3], $$[$0]); -break; -case 36:this.$ = new yy.Assign($$[$0-4], $$[$0-1]); -break; -case 37:this.$ = new yy.Value($$[$0]); -break; -case 38:this.$ = new yy.Assign(new yy.Value($$[$0-2]), $$[$0], 'object'); -break; -case 39:this.$ = new yy.Assign(new yy.Value($$[$0-4]), $$[$0-1], 'object'); -break; -case 40:this.$ = $$[$0]; -break; -case 41:this.$ = $$[$0]; -break; -case 42:this.$ = $$[$0]; -break; -case 43:this.$ = $$[$0]; -break; -case 44:this.$ = new yy.Return($$[$0]); -break; -case 45:this.$ = new yy.Return; -break; -case 46:this.$ = new yy.Comment($$[$0]); -break; -case 47:this.$ = new yy.Code($$[$0-3], $$[$0], $$[$0-1]); -break; -case 48:this.$ = new yy.Code([], $$[$0], $$[$0-1]); -break; -case 49:this.$ = 'func'; -break; -case 50:this.$ = 'boundfunc'; -break; -case 51:this.$ = $$[$0]; -break; -case 52:this.$ = $$[$0]; -break; -case 53:this.$ = []; -break; -case 54:this.$ = [$$[$0]]; -break; -case 55:this.$ = $$[$0-2].concat($$[$0]); -break; -case 56:this.$ = new yy.Param($$[$0]); -break; -case 57:this.$ = new yy.Param($$[$0-1], null, true); -break; -case 58:this.$ = new yy.Param($$[$0-2], $$[$0]); -break; -case 59:this.$ = $$[$0]; -break; -case 60:this.$ = $$[$0]; -break; -case 61:this.$ = $$[$0]; -break; -case 62:this.$ = $$[$0]; -break; -case 63:this.$ = new yy.Splat($$[$0-1]); -break; -case 64:this.$ = new yy.Value($$[$0]); -break; -case 65:this.$ = $$[$0-1].add($$[$0]); -break; -case 66:this.$ = new yy.Value($$[$0-1], [].concat($$[$0])); -break; -case 67:this.$ = $$[$0]; -break; -case 68:this.$ = $$[$0]; -break; -case 69:this.$ = new yy.Value($$[$0]); -break; -case 70:this.$ = new yy.Value($$[$0]); -break; -case 71:this.$ = $$[$0]; -break; -case 72:this.$ = new yy.Value($$[$0]); -break; -case 73:this.$ = new yy.Value($$[$0]); -break; -case 74:this.$ = new yy.Value($$[$0]); -break; -case 75:this.$ = $$[$0]; -break; -case 76:this.$ = new yy.Access($$[$0]); -break; -case 77:this.$ = new yy.Access($$[$0], 'soak'); -break; -case 78:this.$ = [new yy.Access(new yy.Literal('prototype')), new yy.Access($$[$0])]; -break; -case 79:this.$ = new yy.Access(new yy.Literal('prototype')); -break; -case 80:this.$ = $$[$0]; -break; -case 81:this.$ = $$[$0-1]; -break; -case 82:this.$ = yy.extend($$[$0], { - soak: true - }); -break; -case 83:this.$ = new yy.Index($$[$0]); -break; -case 84:this.$ = new yy.Slice($$[$0]); -break; -case 85:this.$ = new yy.Obj($$[$0-2], $$[$0-3].generated); -break; -case 86:this.$ = []; -break; -case 87:this.$ = [$$[$0]]; -break; -case 88:this.$ = $$[$0-2].concat($$[$0]); -break; -case 89:this.$ = $$[$0-3].concat($$[$0]); -break; -case 90:this.$ = $$[$0-5].concat($$[$0-2]); -break; -case 91:this.$ = new yy.Class; -break; -case 92:this.$ = new yy.Class(null, null, $$[$0]); -break; -case 93:this.$ = new yy.Class(null, $$[$0]); -break; -case 94:this.$ = new yy.Class(null, $$[$0-1], $$[$0]); -break; -case 95:this.$ = new yy.Class($$[$0]); -break; -case 96:this.$ = new yy.Class($$[$0-1], null, $$[$0]); -break; -case 97:this.$ = new yy.Class($$[$0-2], $$[$0]); -break; -case 98:this.$ = new yy.Class($$[$0-3], $$[$0-1], $$[$0]); -break; -case 99:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); -break; -case 100:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]); -break; -case 101:this.$ = new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]); -break; -case 102:this.$ = new yy.Call('super', $$[$0]); -break; -case 103:this.$ = false; -break; -case 104:this.$ = true; -break; -case 105:this.$ = []; -break; -case 106:this.$ = $$[$0-2]; -break; -case 107:this.$ = new yy.Value(new yy.Literal('this')); -break; -case 108:this.$ = new yy.Value(new yy.Literal('this')); -break; -case 109:this.$ = new yy.Value(new yy.Literal('this'), [new yy.Access($$[$0])], 'this'); -break; -case 110:this.$ = new yy.Arr([]); -break; -case 111:this.$ = new yy.Arr($$[$0-2]); -break; -case 112:this.$ = 'inclusive'; -break; -case 113:this.$ = 'exclusive'; -break; -case 114:this.$ = new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]); -break; -case 115:this.$ = new yy.Range($$[$0-2], $$[$0], $$[$0-1]); -break; -case 116:this.$ = new yy.Range($$[$0-1], null, $$[$0]); -break; -case 117:this.$ = new yy.Range(null, $$[$0], $$[$0-1]); -break; -case 118:this.$ = new yy.Range(null, null, $$[$0]); -break; -case 119:this.$ = [$$[$0]]; -break; -case 120:this.$ = $$[$0-2].concat($$[$0]); -break; -case 121:this.$ = $$[$0-3].concat($$[$0]); -break; -case 122:this.$ = $$[$0-2]; -break; -case 123:this.$ = $$[$0-5].concat($$[$0-2]); -break; -case 124:this.$ = $$[$0]; -break; -case 125:this.$ = $$[$0]; -break; -case 126:this.$ = $$[$0]; -break; -case 127:this.$ = [].concat($$[$0-2], $$[$0]); -break; -case 128:this.$ = new yy.Try($$[$0]); -break; -case 129:this.$ = new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]); -break; -case 130:this.$ = new yy.Try($$[$0-2], null, null, $$[$0]); -break; -case 131:this.$ = new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]); -break; -case 132:this.$ = [$$[$0-1], $$[$0]]; -break; -case 133:this.$ = new yy.Throw($$[$0]); -break; -case 134:this.$ = new yy.Parens($$[$0-1]); -break; -case 135:this.$ = new yy.Parens($$[$0-2]); -break; -case 136:this.$ = new yy.While($$[$0]); -break; -case 137:this.$ = new yy.While($$[$0-2], { - guard: $$[$0] - }); -break; -case 138:this.$ = new yy.While($$[$0], { - invert: true - }); -break; -case 139:this.$ = new yy.While($$[$0-2], { - invert: true, - guard: $$[$0] - }); -break; -case 140:this.$ = $$[$0-1].addBody($$[$0]); -break; -case 141:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); -break; -case 142:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]])); -break; -case 143:this.$ = $$[$0]; -break; -case 144:this.$ = new yy.While(new yy.Literal('true')).addBody($$[$0]); -break; -case 145:this.$ = new yy.While(new yy.Literal('true')).addBody(yy.Block.wrap([$$[$0]])); -break; -case 146:this.$ = new yy.For($$[$0-1], $$[$0]); -break; -case 147:this.$ = new yy.For($$[$0-1], $$[$0]); -break; -case 148:this.$ = new yy.For($$[$0], $$[$0-1]); -break; -case 149:this.$ = { - source: new yy.Value($$[$0]) - }; -break; -case 150:this.$ = (function () { - $$[$0].own = $$[$0-1].own; - $$[$0].name = $$[$0-1][0]; - $$[$0].index = $$[$0-1][1]; - return $$[$0]; - }()); -break; -case 151:this.$ = $$[$0]; -break; -case 152:this.$ = (function () { - $$[$0].own = true; - return $$[$0]; - }()); -break; -case 153:this.$ = $$[$0]; -break; -case 154:this.$ = new yy.Value($$[$0]); -break; -case 155:this.$ = new yy.Value($$[$0]); -break; -case 156:this.$ = [$$[$0]]; -break; -case 157:this.$ = [$$[$0-2], $$[$0]]; -break; -case 158:this.$ = { - source: $$[$0] - }; -break; -case 159:this.$ = { - source: $$[$0], - object: true - }; -break; -case 160:this.$ = { - source: $$[$0-2], - guard: $$[$0] - }; -break; -case 161:this.$ = { - source: $$[$0-2], - guard: $$[$0], - object: true - }; -break; -case 162:this.$ = { - source: $$[$0-2], - step: $$[$0] - }; -break; -case 163:this.$ = { - source: $$[$0-4], - guard: $$[$0-2], - step: $$[$0] - }; -break; -case 164:this.$ = { - source: $$[$0-4], - step: $$[$0-2], - guard: $$[$0] - }; -break; -case 165:this.$ = new yy.Switch($$[$0-3], $$[$0-1]); -break; -case 166:this.$ = new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]); -break; -case 167:this.$ = new yy.Switch(null, $$[$0-1]); -break; -case 168:this.$ = new yy.Switch(null, $$[$0-3], $$[$0-1]); -break; -case 169:this.$ = $$[$0]; -break; -case 170:this.$ = $$[$0-1].concat($$[$0]); -break; -case 171:this.$ = [[$$[$0-1], $$[$0]]]; -break; -case 172:this.$ = [[$$[$0-2], $$[$0-1]]]; -break; -case 173:this.$ = new yy.If($$[$0-1], $$[$0], { - type: $$[$0-2] - }); -break; -case 174:this.$ = $$[$0-4].addElse(new yy.If($$[$0-1], $$[$0], { - type: $$[$0-2] - })); -break; -case 175:this.$ = $$[$0]; -break; -case 176:this.$ = $$[$0-2].addElse($$[$0]); -break; -case 177:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { - type: $$[$0-1], - statement: true - }); -break; -case 178:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), { - type: $$[$0-1], - statement: true - }); -break; -case 179:this.$ = new yy.Op($$[$0-1], $$[$0]); -break; -case 180:this.$ = new yy.Op('-', $$[$0]); -break; -case 181:this.$ = new yy.Op('+', $$[$0]); -break; -case 182:this.$ = new yy.Op('--', $$[$0]); -break; -case 183:this.$ = new yy.Op('++', $$[$0]); -break; -case 184:this.$ = new yy.Op('--', $$[$0-1], null, true); -break; -case 185:this.$ = new yy.Op('++', $$[$0-1], null, true); -break; -case 186:this.$ = new yy.Existence($$[$0-1]); -break; -case 187:this.$ = new yy.Op('+', $$[$0-2], $$[$0]); -break; -case 188:this.$ = new yy.Op('-', $$[$0-2], $$[$0]); -break; -case 189:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 190:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 191:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 192:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]); -break; -case 193:this.$ = (function () { - if ($$[$0-1].charAt(0) === '!') { - return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert(); - } else { - return new yy.Op($$[$0-1], $$[$0-2], $$[$0]); - } - }()); -break; -case 194:this.$ = new yy.Assign($$[$0-2], $$[$0], $$[$0-1]); -break; -case 195:this.$ = new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]); -break; -case 196:this.$ = new yy.Extends($$[$0-2], $$[$0]); -break; -} -}, -table: [{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[3]},{1:[2,2],6:[1,72]},{6:[1,73]},{1:[2,4],6:[2,4],26:[2,4],99:[2,4]},{4:75,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[1,74],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,7],6:[2,7],26:[2,7],99:[2,7],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,8],6:[2,8],26:[2,8],99:[2,8],100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,12],6:[2,12],25:[2,12],26:[2,12],47:[2,12],52:[2,12],55:[2,12],60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,12],71:[1,98],75:[2,12],78:90,81:[1,92],82:[2,103],83:[2,12],88:[2,12],90:[2,12],99:[2,12],101:[2,12],102:[2,12],103:[2,12],107:[2,12],115:[2,12],123:[2,12],125:[2,12],126:[2,12],129:[2,12],130:[2,12],131:[2,12],132:[2,12],133:[2,12],134:[2,12]},{1:[2,13],6:[2,13],25:[2,13],26:[2,13],47:[2,13],52:[2,13],55:[2,13],60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,13],71:[1,98],75:[2,13],78:99,81:[1,92],82:[2,103],83:[2,13],88:[2,13],90:[2,13],99:[2,13],101:[2,13],102:[2,13],103:[2,13],107:[2,13],115:[2,13],123:[2,13],125:[2,13],126:[2,13],129:[2,13],130:[2,13],131:[2,13],132:[2,13],133:[2,13],134:[2,13]},{1:[2,14],6:[2,14],25:[2,14],26:[2,14],47:[2,14],52:[2,14],55:[2,14],70:[2,14],75:[2,14],83:[2,14],88:[2,14],90:[2,14],99:[2,14],101:[2,14],102:[2,14],103:[2,14],107:[2,14],115:[2,14],123:[2,14],125:[2,14],126:[2,14],129:[2,14],130:[2,14],131:[2,14],132:[2,14],133:[2,14],134:[2,14]},{1:[2,15],6:[2,15],25:[2,15],26:[2,15],47:[2,15],52:[2,15],55:[2,15],70:[2,15],75:[2,15],83:[2,15],88:[2,15],90:[2,15],99:[2,15],101:[2,15],102:[2,15],103:[2,15],107:[2,15],115:[2,15],123:[2,15],125:[2,15],126:[2,15],129:[2,15],130:[2,15],131:[2,15],132:[2,15],133:[2,15],134:[2,15]},{1:[2,16],6:[2,16],25:[2,16],26:[2,16],47:[2,16],52:[2,16],55:[2,16],70:[2,16],75:[2,16],83:[2,16],88:[2,16],90:[2,16],99:[2,16],101:[2,16],102:[2,16],103:[2,16],107:[2,16],115:[2,16],123:[2,16],125:[2,16],126:[2,16],129:[2,16],130:[2,16],131:[2,16],132:[2,16],133:[2,16],134:[2,16]},{1:[2,17],6:[2,17],25:[2,17],26:[2,17],47:[2,17],52:[2,17],55:[2,17],70:[2,17],75:[2,17],83:[2,17],88:[2,17],90:[2,17],99:[2,17],101:[2,17],102:[2,17],103:[2,17],107:[2,17],115:[2,17],123:[2,17],125:[2,17],126:[2,17],129:[2,17],130:[2,17],131:[2,17],132:[2,17],133:[2,17],134:[2,17]},{1:[2,18],6:[2,18],25:[2,18],26:[2,18],47:[2,18],52:[2,18],55:[2,18],70:[2,18],75:[2,18],83:[2,18],88:[2,18],90:[2,18],99:[2,18],101:[2,18],102:[2,18],103:[2,18],107:[2,18],115:[2,18],123:[2,18],125:[2,18],126:[2,18],129:[2,18],130:[2,18],131:[2,18],132:[2,18],133:[2,18],134:[2,18]},{1:[2,19],6:[2,19],25:[2,19],26:[2,19],47:[2,19],52:[2,19],55:[2,19],70:[2,19],75:[2,19],83:[2,19],88:[2,19],90:[2,19],99:[2,19],101:[2,19],102:[2,19],103:[2,19],107:[2,19],115:[2,19],123:[2,19],125:[2,19],126:[2,19],129:[2,19],130:[2,19],131:[2,19],132:[2,19],133:[2,19],134:[2,19]},{1:[2,20],6:[2,20],25:[2,20],26:[2,20],47:[2,20],52:[2,20],55:[2,20],70:[2,20],75:[2,20],83:[2,20],88:[2,20],90:[2,20],99:[2,20],101:[2,20],102:[2,20],103:[2,20],107:[2,20],115:[2,20],123:[2,20],125:[2,20],126:[2,20],129:[2,20],130:[2,20],131:[2,20],132:[2,20],133:[2,20],134:[2,20]},{1:[2,21],6:[2,21],25:[2,21],26:[2,21],47:[2,21],52:[2,21],55:[2,21],70:[2,21],75:[2,21],83:[2,21],88:[2,21],90:[2,21],99:[2,21],101:[2,21],102:[2,21],103:[2,21],107:[2,21],115:[2,21],123:[2,21],125:[2,21],126:[2,21],129:[2,21],130:[2,21],131:[2,21],132:[2,21],133:[2,21],134:[2,21]},{1:[2,22],6:[2,22],25:[2,22],26:[2,22],47:[2,22],52:[2,22],55:[2,22],70:[2,22],75:[2,22],83:[2,22],88:[2,22],90:[2,22],99:[2,22],101:[2,22],102:[2,22],103:[2,22],107:[2,22],115:[2,22],123:[2,22],125:[2,22],126:[2,22],129:[2,22],130:[2,22],131:[2,22],132:[2,22],133:[2,22],134:[2,22]},{1:[2,23],6:[2,23],25:[2,23],26:[2,23],47:[2,23],52:[2,23],55:[2,23],70:[2,23],75:[2,23],83:[2,23],88:[2,23],90:[2,23],99:[2,23],101:[2,23],102:[2,23],103:[2,23],107:[2,23],115:[2,23],123:[2,23],125:[2,23],126:[2,23],129:[2,23],130:[2,23],131:[2,23],132:[2,23],133:[2,23],134:[2,23]},{1:[2,9],6:[2,9],26:[2,9],99:[2,9],101:[2,9],103:[2,9],107:[2,9],123:[2,9]},{1:[2,10],6:[2,10],26:[2,10],99:[2,10],101:[2,10],103:[2,10],107:[2,10],123:[2,10]},{1:[2,11],6:[2,11],26:[2,11],99:[2,11],101:[2,11],103:[2,11],107:[2,11],123:[2,11]},{1:[2,71],6:[2,71],25:[2,71],26:[2,71],38:[1,101],47:[2,71],52:[2,71],55:[2,71],64:[2,71],65:[2,71],66:[2,71],68:[2,71],70:[2,71],71:[2,71],75:[2,71],81:[2,71],82:[2,71],83:[2,71],88:[2,71],90:[2,71],99:[2,71],101:[2,71],102:[2,71],103:[2,71],107:[2,71],115:[2,71],123:[2,71],125:[2,71],126:[2,71],129:[2,71],130:[2,71],131:[2,71],132:[2,71],133:[2,71],134:[2,71]},{1:[2,72],6:[2,72],25:[2,72],26:[2,72],47:[2,72],52:[2,72],55:[2,72],64:[2,72],65:[2,72],66:[2,72],68:[2,72],70:[2,72],71:[2,72],75:[2,72],81:[2,72],82:[2,72],83:[2,72],88:[2,72],90:[2,72],99:[2,72],101:[2,72],102:[2,72],103:[2,72],107:[2,72],115:[2,72],123:[2,72],125:[2,72],126:[2,72],129:[2,72],130:[2,72],131:[2,72],132:[2,72],133:[2,72],134:[2,72]},{1:[2,73],6:[2,73],25:[2,73],26:[2,73],47:[2,73],52:[2,73],55:[2,73],64:[2,73],65:[2,73],66:[2,73],68:[2,73],70:[2,73],71:[2,73],75:[2,73],81:[2,73],82:[2,73],83:[2,73],88:[2,73],90:[2,73],99:[2,73],101:[2,73],102:[2,73],103:[2,73],107:[2,73],115:[2,73],123:[2,73],125:[2,73],126:[2,73],129:[2,73],130:[2,73],131:[2,73],132:[2,73],133:[2,73],134:[2,73]},{1:[2,74],6:[2,74],25:[2,74],26:[2,74],47:[2,74],52:[2,74],55:[2,74],64:[2,74],65:[2,74],66:[2,74],68:[2,74],70:[2,74],71:[2,74],75:[2,74],81:[2,74],82:[2,74],83:[2,74],88:[2,74],90:[2,74],99:[2,74],101:[2,74],102:[2,74],103:[2,74],107:[2,74],115:[2,74],123:[2,74],125:[2,74],126:[2,74],129:[2,74],130:[2,74],131:[2,74],132:[2,74],133:[2,74],134:[2,74]},{1:[2,75],6:[2,75],25:[2,75],26:[2,75],47:[2,75],52:[2,75],55:[2,75],64:[2,75],65:[2,75],66:[2,75],68:[2,75],70:[2,75],71:[2,75],75:[2,75],81:[2,75],82:[2,75],83:[2,75],88:[2,75],90:[2,75],99:[2,75],101:[2,75],102:[2,75],103:[2,75],107:[2,75],115:[2,75],123:[2,75],125:[2,75],126:[2,75],129:[2,75],130:[2,75],131:[2,75],132:[2,75],133:[2,75],134:[2,75]},{1:[2,101],6:[2,101],25:[2,101],26:[2,101],47:[2,101],52:[2,101],55:[2,101],64:[2,101],65:[2,101],66:[2,101],68:[2,101],70:[2,101],71:[2,101],75:[2,101],79:102,81:[2,101],82:[1,103],83:[2,101],88:[2,101],90:[2,101],99:[2,101],101:[2,101],102:[2,101],103:[2,101],107:[2,101],115:[2,101],123:[2,101],125:[2,101],126:[2,101],129:[2,101],130:[2,101],131:[2,101],132:[2,101],133:[2,101],134:[2,101]},{27:107,28:[1,71],42:108,46:104,47:[2,53],52:[2,53],53:105,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{5:113,25:[1,5]},{8:114,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:116,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:117,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:118,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:122,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{1:[2,68],6:[2,68],25:[2,68],26:[2,68],38:[2,68],47:[2,68],52:[2,68],55:[2,68],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,68],71:[2,68],75:[2,68],77:[1,126],81:[2,68],82:[2,68],83:[2,68],88:[2,68],90:[2,68],99:[2,68],101:[2,68],102:[2,68],103:[2,68],107:[2,68],115:[2,68],123:[2,68],125:[2,68],126:[2,68],127:[1,123],128:[1,124],129:[2,68],130:[2,68],131:[2,68],132:[2,68],133:[2,68],134:[2,68],135:[1,125]},{1:[2,175],6:[2,175],25:[2,175],26:[2,175],47:[2,175],52:[2,175],55:[2,175],70:[2,175],75:[2,175],83:[2,175],88:[2,175],90:[2,175],99:[2,175],101:[2,175],102:[2,175],103:[2,175],107:[2,175],115:[2,175],118:[1,127],123:[2,175],125:[2,175],126:[2,175],129:[2,175],130:[2,175],131:[2,175],132:[2,175],133:[2,175],134:[2,175]},{5:128,25:[1,5]},{5:129,25:[1,5]},{1:[2,143],6:[2,143],25:[2,143],26:[2,143],47:[2,143],52:[2,143],55:[2,143],70:[2,143],75:[2,143],83:[2,143],88:[2,143],90:[2,143],99:[2,143],101:[2,143],102:[2,143],103:[2,143],107:[2,143],115:[2,143],123:[2,143],125:[2,143],126:[2,143],129:[2,143],130:[2,143],131:[2,143],132:[2,143],133:[2,143],134:[2,143]},{5:130,25:[1,5]},{8:131,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,132],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,91],5:133,6:[2,91],13:119,14:120,25:[1,5],26:[2,91],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,47:[2,91],52:[2,91],55:[2,91],56:47,57:48,59:135,61:25,62:26,63:27,70:[2,91],73:[1,68],75:[2,91],77:[1,134],80:[1,28],83:[2,91],85:[1,56],86:[1,57],87:[1,55],88:[2,91],90:[2,91],98:[1,54],99:[2,91],101:[2,91],102:[2,91],103:[2,91],107:[2,91],115:[2,91],123:[2,91],125:[2,91],126:[2,91],129:[2,91],130:[2,91],131:[2,91],132:[2,91],133:[2,91],134:[2,91]},{8:136,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,45],6:[2,45],8:137,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,45],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,45],100:39,101:[2,45],103:[2,45],104:40,105:[1,65],106:41,107:[2,45],108:67,116:[1,42],121:37,122:[1,62],123:[2,45],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,46],6:[2,46],25:[2,46],26:[2,46],52:[2,46],75:[2,46],99:[2,46],101:[2,46],103:[2,46],107:[2,46],123:[2,46]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],38:[2,69],47:[2,69],52:[2,69],55:[2,69],64:[2,69],65:[2,69],66:[2,69],68:[2,69],70:[2,69],71:[2,69],75:[2,69],81:[2,69],82:[2,69],83:[2,69],88:[2,69],90:[2,69],99:[2,69],101:[2,69],102:[2,69],103:[2,69],107:[2,69],115:[2,69],123:[2,69],125:[2,69],126:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69]},{1:[2,70],6:[2,70],25:[2,70],26:[2,70],38:[2,70],47:[2,70],52:[2,70],55:[2,70],64:[2,70],65:[2,70],66:[2,70],68:[2,70],70:[2,70],71:[2,70],75:[2,70],81:[2,70],82:[2,70],83:[2,70],88:[2,70],90:[2,70],99:[2,70],101:[2,70],102:[2,70],103:[2,70],107:[2,70],115:[2,70],123:[2,70],125:[2,70],126:[2,70],129:[2,70],130:[2,70],131:[2,70],132:[2,70],133:[2,70],134:[2,70]},{1:[2,29],6:[2,29],25:[2,29],26:[2,29],47:[2,29],52:[2,29],55:[2,29],64:[2,29],65:[2,29],66:[2,29],68:[2,29],70:[2,29],71:[2,29],75:[2,29],81:[2,29],82:[2,29],83:[2,29],88:[2,29],90:[2,29],99:[2,29],101:[2,29],102:[2,29],103:[2,29],107:[2,29],115:[2,29],123:[2,29],125:[2,29],126:[2,29],129:[2,29],130:[2,29],131:[2,29],132:[2,29],133:[2,29],134:[2,29]},{1:[2,30],6:[2,30],25:[2,30],26:[2,30],47:[2,30],52:[2,30],55:[2,30],64:[2,30],65:[2,30],66:[2,30],68:[2,30],70:[2,30],71:[2,30],75:[2,30],81:[2,30],82:[2,30],83:[2,30],88:[2,30],90:[2,30],99:[2,30],101:[2,30],102:[2,30],103:[2,30],107:[2,30],115:[2,30],123:[2,30],125:[2,30],126:[2,30],129:[2,30],130:[2,30],131:[2,30],132:[2,30],133:[2,30],134:[2,30]},{1:[2,31],6:[2,31],25:[2,31],26:[2,31],47:[2,31],52:[2,31],55:[2,31],64:[2,31],65:[2,31],66:[2,31],68:[2,31],70:[2,31],71:[2,31],75:[2,31],81:[2,31],82:[2,31],83:[2,31],88:[2,31],90:[2,31],99:[2,31],101:[2,31],102:[2,31],103:[2,31],107:[2,31],115:[2,31],123:[2,31],125:[2,31],126:[2,31],129:[2,31],130:[2,31],131:[2,31],132:[2,31],133:[2,31],134:[2,31]},{1:[2,32],6:[2,32],25:[2,32],26:[2,32],47:[2,32],52:[2,32],55:[2,32],64:[2,32],65:[2,32],66:[2,32],68:[2,32],70:[2,32],71:[2,32],75:[2,32],81:[2,32],82:[2,32],83:[2,32],88:[2,32],90:[2,32],99:[2,32],101:[2,32],102:[2,32],103:[2,32],107:[2,32],115:[2,32],123:[2,32],125:[2,32],126:[2,32],129:[2,32],130:[2,32],131:[2,32],132:[2,32],133:[2,32],134:[2,32]},{1:[2,33],6:[2,33],25:[2,33],26:[2,33],47:[2,33],52:[2,33],55:[2,33],64:[2,33],65:[2,33],66:[2,33],68:[2,33],70:[2,33],71:[2,33],75:[2,33],81:[2,33],82:[2,33],83:[2,33],88:[2,33],90:[2,33],99:[2,33],101:[2,33],102:[2,33],103:[2,33],107:[2,33],115:[2,33],123:[2,33],125:[2,33],126:[2,33],129:[2,33],130:[2,33],131:[2,33],132:[2,33],133:[2,33],134:[2,33]},{4:138,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,139],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:140,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,107],6:[2,107],25:[2,107],26:[2,107],47:[2,107],52:[2,107],55:[2,107],64:[2,107],65:[2,107],66:[2,107],68:[2,107],70:[2,107],71:[2,107],75:[2,107],81:[2,107],82:[2,107],83:[2,107],88:[2,107],90:[2,107],99:[2,107],101:[2,107],102:[2,107],103:[2,107],107:[2,107],115:[2,107],123:[2,107],125:[2,107],126:[2,107],129:[2,107],130:[2,107],131:[2,107],132:[2,107],133:[2,107],134:[2,107]},{1:[2,108],6:[2,108],25:[2,108],26:[2,108],27:146,28:[1,71],47:[2,108],52:[2,108],55:[2,108],64:[2,108],65:[2,108],66:[2,108],68:[2,108],70:[2,108],71:[2,108],75:[2,108],81:[2,108],82:[2,108],83:[2,108],88:[2,108],90:[2,108],99:[2,108],101:[2,108],102:[2,108],103:[2,108],107:[2,108],115:[2,108],123:[2,108],125:[2,108],126:[2,108],129:[2,108],130:[2,108],131:[2,108],132:[2,108],133:[2,108],134:[2,108]},{25:[2,49]},{25:[2,50]},{1:[2,64],6:[2,64],25:[2,64],26:[2,64],38:[2,64],47:[2,64],52:[2,64],55:[2,64],64:[2,64],65:[2,64],66:[2,64],68:[2,64],70:[2,64],71:[2,64],75:[2,64],77:[2,64],81:[2,64],82:[2,64],83:[2,64],88:[2,64],90:[2,64],99:[2,64],101:[2,64],102:[2,64],103:[2,64],107:[2,64],115:[2,64],123:[2,64],125:[2,64],126:[2,64],127:[2,64],128:[2,64],129:[2,64],130:[2,64],131:[2,64],132:[2,64],133:[2,64],134:[2,64],135:[2,64]},{1:[2,67],6:[2,67],25:[2,67],26:[2,67],38:[2,67],47:[2,67],52:[2,67],55:[2,67],64:[2,67],65:[2,67],66:[2,67],68:[2,67],70:[2,67],71:[2,67],75:[2,67],77:[2,67],81:[2,67],82:[2,67],83:[2,67],88:[2,67],90:[2,67],99:[2,67],101:[2,67],102:[2,67],103:[2,67],107:[2,67],115:[2,67],123:[2,67],125:[2,67],126:[2,67],127:[2,67],128:[2,67],129:[2,67],130:[2,67],131:[2,67],132:[2,67],133:[2,67],134:[2,67],135:[2,67]},{8:147,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:148,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:149,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:150,8:151,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{27:156,28:[1,71],56:157,57:158,62:152,73:[1,68],87:[1,55],110:153,111:[1,154],112:155},{109:159,113:[1,160],114:[1,161]},{6:[2,86],11:165,25:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:162,75:[2,86],86:[1,111]},{1:[2,27],6:[2,27],25:[2,27],26:[2,27],41:[2,27],47:[2,27],52:[2,27],55:[2,27],64:[2,27],65:[2,27],66:[2,27],68:[2,27],70:[2,27],71:[2,27],75:[2,27],81:[2,27],82:[2,27],83:[2,27],88:[2,27],90:[2,27],99:[2,27],101:[2,27],102:[2,27],103:[2,27],107:[2,27],115:[2,27],123:[2,27],125:[2,27],126:[2,27],129:[2,27],130:[2,27],131:[2,27],132:[2,27],133:[2,27],134:[2,27]},{1:[2,28],6:[2,28],25:[2,28],26:[2,28],41:[2,28],47:[2,28],52:[2,28],55:[2,28],64:[2,28],65:[2,28],66:[2,28],68:[2,28],70:[2,28],71:[2,28],75:[2,28],81:[2,28],82:[2,28],83:[2,28],88:[2,28],90:[2,28],99:[2,28],101:[2,28],102:[2,28],103:[2,28],107:[2,28],115:[2,28],123:[2,28],125:[2,28],126:[2,28],129:[2,28],130:[2,28],131:[2,28],132:[2,28],133:[2,28],134:[2,28]},{1:[2,26],6:[2,26],25:[2,26],26:[2,26],38:[2,26],41:[2,26],47:[2,26],52:[2,26],55:[2,26],64:[2,26],65:[2,26],66:[2,26],68:[2,26],70:[2,26],71:[2,26],75:[2,26],77:[2,26],81:[2,26],82:[2,26],83:[2,26],88:[2,26],90:[2,26],99:[2,26],101:[2,26],102:[2,26],103:[2,26],107:[2,26],113:[2,26],114:[2,26],115:[2,26],123:[2,26],125:[2,26],126:[2,26],127:[2,26],128:[2,26],129:[2,26],130:[2,26],131:[2,26],132:[2,26],133:[2,26],134:[2,26],135:[2,26]},{1:[2,6],6:[2,6],7:169,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,6],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,6],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,3]},{1:[2,24],6:[2,24],25:[2,24],26:[2,24],47:[2,24],52:[2,24],55:[2,24],70:[2,24],75:[2,24],83:[2,24],88:[2,24],90:[2,24],95:[2,24],96:[2,24],99:[2,24],101:[2,24],102:[2,24],103:[2,24],107:[2,24],115:[2,24],118:[2,24],120:[2,24],123:[2,24],125:[2,24],126:[2,24],129:[2,24],130:[2,24],131:[2,24],132:[2,24],133:[2,24],134:[2,24]},{6:[1,72],26:[1,170]},{1:[2,186],6:[2,186],25:[2,186],26:[2,186],47:[2,186],52:[2,186],55:[2,186],70:[2,186],75:[2,186],83:[2,186],88:[2,186],90:[2,186],99:[2,186],101:[2,186],102:[2,186],103:[2,186],107:[2,186],115:[2,186],123:[2,186],125:[2,186],126:[2,186],129:[2,186],130:[2,186],131:[2,186],132:[2,186],133:[2,186],134:[2,186]},{8:171,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:172,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:173,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:174,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:175,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:176,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:177,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:178,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,142],6:[2,142],25:[2,142],26:[2,142],47:[2,142],52:[2,142],55:[2,142],70:[2,142],75:[2,142],83:[2,142],88:[2,142],90:[2,142],99:[2,142],101:[2,142],102:[2,142],103:[2,142],107:[2,142],115:[2,142],123:[2,142],125:[2,142],126:[2,142],129:[2,142],130:[2,142],131:[2,142],132:[2,142],133:[2,142],134:[2,142]},{1:[2,147],6:[2,147],25:[2,147],26:[2,147],47:[2,147],52:[2,147],55:[2,147],70:[2,147],75:[2,147],83:[2,147],88:[2,147],90:[2,147],99:[2,147],101:[2,147],102:[2,147],103:[2,147],107:[2,147],115:[2,147],123:[2,147],125:[2,147],126:[2,147],129:[2,147],130:[2,147],131:[2,147],132:[2,147],133:[2,147],134:[2,147]},{8:179,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,141],6:[2,141],25:[2,141],26:[2,141],47:[2,141],52:[2,141],55:[2,141],70:[2,141],75:[2,141],83:[2,141],88:[2,141],90:[2,141],99:[2,141],101:[2,141],102:[2,141],103:[2,141],107:[2,141],115:[2,141],123:[2,141],125:[2,141],126:[2,141],129:[2,141],130:[2,141],131:[2,141],132:[2,141],133:[2,141],134:[2,141]},{1:[2,146],6:[2,146],25:[2,146],26:[2,146],47:[2,146],52:[2,146],55:[2,146],70:[2,146],75:[2,146],83:[2,146],88:[2,146],90:[2,146],99:[2,146],101:[2,146],102:[2,146],103:[2,146],107:[2,146],115:[2,146],123:[2,146],125:[2,146],126:[2,146],129:[2,146],130:[2,146],131:[2,146],132:[2,146],133:[2,146],134:[2,146]},{79:180,82:[1,103]},{1:[2,65],6:[2,65],25:[2,65],26:[2,65],38:[2,65],47:[2,65],52:[2,65],55:[2,65],64:[2,65],65:[2,65],66:[2,65],68:[2,65],70:[2,65],71:[2,65],75:[2,65],77:[2,65],81:[2,65],82:[2,65],83:[2,65],88:[2,65],90:[2,65],99:[2,65],101:[2,65],102:[2,65],103:[2,65],107:[2,65],115:[2,65],123:[2,65],125:[2,65],126:[2,65],127:[2,65],128:[2,65],129:[2,65],130:[2,65],131:[2,65],132:[2,65],133:[2,65],134:[2,65],135:[2,65]},{82:[2,104]},{27:181,28:[1,71]},{27:182,28:[1,71]},{1:[2,79],6:[2,79],25:[2,79],26:[2,79],27:183,28:[1,71],38:[2,79],47:[2,79],52:[2,79],55:[2,79],64:[2,79],65:[2,79],66:[2,79],68:[2,79],70:[2,79],71:[2,79],75:[2,79],77:[2,79],81:[2,79],82:[2,79],83:[2,79],88:[2,79],90:[2,79],99:[2,79],101:[2,79],102:[2,79],103:[2,79],107:[2,79],115:[2,79],123:[2,79],125:[2,79],126:[2,79],127:[2,79],128:[2,79],129:[2,79],130:[2,79],131:[2,79],132:[2,79],133:[2,79],134:[2,79],135:[2,79]},{1:[2,80],6:[2,80],25:[2,80],26:[2,80],38:[2,80],47:[2,80],52:[2,80],55:[2,80],64:[2,80],65:[2,80],66:[2,80],68:[2,80],70:[2,80],71:[2,80],75:[2,80],77:[2,80],81:[2,80],82:[2,80],83:[2,80],88:[2,80],90:[2,80],99:[2,80],101:[2,80],102:[2,80],103:[2,80],107:[2,80],115:[2,80],123:[2,80],125:[2,80],126:[2,80],127:[2,80],128:[2,80],129:[2,80],130:[2,80],131:[2,80],132:[2,80],133:[2,80],134:[2,80],135:[2,80]},{8:185,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],55:[1,189],56:47,57:48,59:36,61:25,62:26,63:27,69:184,72:186,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],89:187,90:[1,188],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{67:190,68:[1,97],71:[1,98]},{79:191,82:[1,103]},{1:[2,66],6:[2,66],25:[2,66],26:[2,66],38:[2,66],47:[2,66],52:[2,66],55:[2,66],64:[2,66],65:[2,66],66:[2,66],68:[2,66],70:[2,66],71:[2,66],75:[2,66],77:[2,66],81:[2,66],82:[2,66],83:[2,66],88:[2,66],90:[2,66],99:[2,66],101:[2,66],102:[2,66],103:[2,66],107:[2,66],115:[2,66],123:[2,66],125:[2,66],126:[2,66],127:[2,66],128:[2,66],129:[2,66],130:[2,66],131:[2,66],132:[2,66],133:[2,66],134:[2,66],135:[2,66]},{6:[1,193],8:192,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,194],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,102],6:[2,102],25:[2,102],26:[2,102],47:[2,102],52:[2,102],55:[2,102],64:[2,102],65:[2,102],66:[2,102],68:[2,102],70:[2,102],71:[2,102],75:[2,102],81:[2,102],82:[2,102],83:[2,102],88:[2,102],90:[2,102],99:[2,102],101:[2,102],102:[2,102],103:[2,102],107:[2,102],115:[2,102],123:[2,102],125:[2,102],126:[2,102],129:[2,102],130:[2,102],131:[2,102],132:[2,102],133:[2,102],134:[2,102]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[1,195],84:196,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{47:[1,198],52:[1,199]},{47:[2,54],52:[2,54]},{38:[1,201],47:[2,56],52:[2,56],55:[1,200]},{38:[2,59],47:[2,59],52:[2,59],55:[2,59]},{38:[2,60],47:[2,60],52:[2,60],55:[2,60]},{38:[2,61],47:[2,61],52:[2,61],55:[2,61]},{38:[2,62],47:[2,62],52:[2,62],55:[2,62]},{27:146,28:[1,71]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,48],6:[2,48],25:[2,48],26:[2,48],47:[2,48],52:[2,48],55:[2,48],70:[2,48],75:[2,48],83:[2,48],88:[2,48],90:[2,48],99:[2,48],101:[2,48],102:[2,48],103:[2,48],107:[2,48],115:[2,48],123:[2,48],125:[2,48],126:[2,48],129:[2,48],130:[2,48],131:[2,48],132:[2,48],133:[2,48],134:[2,48]},{1:[2,179],6:[2,179],25:[2,179],26:[2,179],47:[2,179],52:[2,179],55:[2,179],70:[2,179],75:[2,179],83:[2,179],88:[2,179],90:[2,179],99:[2,179],100:85,101:[2,179],102:[2,179],103:[2,179],106:86,107:[2,179],108:67,115:[2,179],123:[2,179],125:[2,179],126:[2,179],129:[1,76],130:[2,179],131:[2,179],132:[2,179],133:[2,179],134:[2,179]},{100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,180],6:[2,180],25:[2,180],26:[2,180],47:[2,180],52:[2,180],55:[2,180],70:[2,180],75:[2,180],83:[2,180],88:[2,180],90:[2,180],99:[2,180],100:85,101:[2,180],102:[2,180],103:[2,180],106:86,107:[2,180],108:67,115:[2,180],123:[2,180],125:[2,180],126:[2,180],129:[1,76],130:[2,180],131:[2,180],132:[2,180],133:[2,180],134:[2,180]},{1:[2,181],6:[2,181],25:[2,181],26:[2,181],47:[2,181],52:[2,181],55:[2,181],70:[2,181],75:[2,181],83:[2,181],88:[2,181],90:[2,181],99:[2,181],100:85,101:[2,181],102:[2,181],103:[2,181],106:86,107:[2,181],108:67,115:[2,181],123:[2,181],125:[2,181],126:[2,181],129:[1,76],130:[2,181],131:[2,181],132:[2,181],133:[2,181],134:[2,181]},{1:[2,182],6:[2,182],25:[2,182],26:[2,182],47:[2,182],52:[2,182],55:[2,182],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,182],71:[2,68],75:[2,182],81:[2,68],82:[2,68],83:[2,182],88:[2,182],90:[2,182],99:[2,182],101:[2,182],102:[2,182],103:[2,182],107:[2,182],115:[2,182],123:[2,182],125:[2,182],126:[2,182],129:[2,182],130:[2,182],131:[2,182],132:[2,182],133:[2,182],134:[2,182]},{60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:90,81:[1,92],82:[2,103]},{60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:99,81:[1,92],82:[2,103]},{64:[2,71],65:[2,71],66:[2,71],68:[2,71],71:[2,71],81:[2,71],82:[2,71]},{1:[2,183],6:[2,183],25:[2,183],26:[2,183],47:[2,183],52:[2,183],55:[2,183],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,183],71:[2,68],75:[2,183],81:[2,68],82:[2,68],83:[2,183],88:[2,183],90:[2,183],99:[2,183],101:[2,183],102:[2,183],103:[2,183],107:[2,183],115:[2,183],123:[2,183],125:[2,183],126:[2,183],129:[2,183],130:[2,183],131:[2,183],132:[2,183],133:[2,183],134:[2,183]},{1:[2,184],6:[2,184],25:[2,184],26:[2,184],47:[2,184],52:[2,184],55:[2,184],70:[2,184],75:[2,184],83:[2,184],88:[2,184],90:[2,184],99:[2,184],101:[2,184],102:[2,184],103:[2,184],107:[2,184],115:[2,184],123:[2,184],125:[2,184],126:[2,184],129:[2,184],130:[2,184],131:[2,184],132:[2,184],133:[2,184],134:[2,184]},{1:[2,185],6:[2,185],25:[2,185],26:[2,185],47:[2,185],52:[2,185],55:[2,185],70:[2,185],75:[2,185],83:[2,185],88:[2,185],90:[2,185],99:[2,185],101:[2,185],102:[2,185],103:[2,185],107:[2,185],115:[2,185],123:[2,185],125:[2,185],126:[2,185],129:[2,185],130:[2,185],131:[2,185],132:[2,185],133:[2,185],134:[2,185]},{8:202,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,203],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:204,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:205,25:[1,5],122:[1,206]},{1:[2,128],6:[2,128],25:[2,128],26:[2,128],47:[2,128],52:[2,128],55:[2,128],70:[2,128],75:[2,128],83:[2,128],88:[2,128],90:[2,128],94:207,95:[1,208],96:[1,209],99:[2,128],101:[2,128],102:[2,128],103:[2,128],107:[2,128],115:[2,128],123:[2,128],125:[2,128],126:[2,128],129:[2,128],130:[2,128],131:[2,128],132:[2,128],133:[2,128],134:[2,128]},{1:[2,140],6:[2,140],25:[2,140],26:[2,140],47:[2,140],52:[2,140],55:[2,140],70:[2,140],75:[2,140],83:[2,140],88:[2,140],90:[2,140],99:[2,140],101:[2,140],102:[2,140],103:[2,140],107:[2,140],115:[2,140],123:[2,140],125:[2,140],126:[2,140],129:[2,140],130:[2,140],131:[2,140],132:[2,140],133:[2,140],134:[2,140]},{1:[2,148],6:[2,148],25:[2,148],26:[2,148],47:[2,148],52:[2,148],55:[2,148],70:[2,148],75:[2,148],83:[2,148],88:[2,148],90:[2,148],99:[2,148],101:[2,148],102:[2,148],103:[2,148],107:[2,148],115:[2,148],123:[2,148],125:[2,148],126:[2,148],129:[2,148],130:[2,148],131:[2,148],132:[2,148],133:[2,148],134:[2,148]},{25:[1,210],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{117:211,119:212,120:[1,213]},{1:[2,92],6:[2,92],25:[2,92],26:[2,92],47:[2,92],52:[2,92],55:[2,92],70:[2,92],75:[2,92],83:[2,92],88:[2,92],90:[2,92],99:[2,92],101:[2,92],102:[2,92],103:[2,92],107:[2,92],115:[2,92],123:[2,92],125:[2,92],126:[2,92],129:[2,92],130:[2,92],131:[2,92],132:[2,92],133:[2,92],134:[2,92]},{8:214,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,95],5:215,6:[2,95],25:[1,5],26:[2,95],47:[2,95],52:[2,95],55:[2,95],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,95],71:[2,68],75:[2,95],77:[1,216],81:[2,68],82:[2,68],83:[2,95],88:[2,95],90:[2,95],99:[2,95],101:[2,95],102:[2,95],103:[2,95],107:[2,95],115:[2,95],123:[2,95],125:[2,95],126:[2,95],129:[2,95],130:[2,95],131:[2,95],132:[2,95],133:[2,95],134:[2,95]},{1:[2,133],6:[2,133],25:[2,133],26:[2,133],47:[2,133],52:[2,133],55:[2,133],70:[2,133],75:[2,133],83:[2,133],88:[2,133],90:[2,133],99:[2,133],100:85,101:[2,133],102:[2,133],103:[2,133],106:86,107:[2,133],108:67,115:[2,133],123:[2,133],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,44],6:[2,44],26:[2,44],99:[2,44],100:85,101:[2,44],103:[2,44],106:86,107:[2,44],108:67,123:[2,44],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,72],99:[1,217]},{4:218,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,124],25:[2,124],52:[2,124],55:[1,220],88:[2,124],89:219,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,110],6:[2,110],25:[2,110],26:[2,110],38:[2,110],47:[2,110],52:[2,110],55:[2,110],64:[2,110],65:[2,110],66:[2,110],68:[2,110],70:[2,110],71:[2,110],75:[2,110],81:[2,110],82:[2,110],83:[2,110],88:[2,110],90:[2,110],99:[2,110],101:[2,110],102:[2,110],103:[2,110],107:[2,110],113:[2,110],114:[2,110],115:[2,110],123:[2,110],125:[2,110],126:[2,110],129:[2,110],130:[2,110],131:[2,110],132:[2,110],133:[2,110],134:[2,110]},{6:[2,51],25:[2,51],51:221,52:[1,222],88:[2,51]},{6:[2,119],25:[2,119],26:[2,119],52:[2,119],83:[2,119],88:[2,119]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:223,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,125],25:[2,125],26:[2,125],52:[2,125],83:[2,125],88:[2,125]},{1:[2,109],6:[2,109],25:[2,109],26:[2,109],38:[2,109],41:[2,109],47:[2,109],52:[2,109],55:[2,109],64:[2,109],65:[2,109],66:[2,109],68:[2,109],70:[2,109],71:[2,109],75:[2,109],77:[2,109],81:[2,109],82:[2,109],83:[2,109],88:[2,109],90:[2,109],99:[2,109],101:[2,109],102:[2,109],103:[2,109],107:[2,109],115:[2,109],123:[2,109],125:[2,109],126:[2,109],127:[2,109],128:[2,109],129:[2,109],130:[2,109],131:[2,109],132:[2,109],133:[2,109],134:[2,109],135:[2,109]},{5:224,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,136],6:[2,136],25:[2,136],26:[2,136],47:[2,136],52:[2,136],55:[2,136],70:[2,136],75:[2,136],83:[2,136],88:[2,136],90:[2,136],99:[2,136],100:85,101:[1,63],102:[1,225],103:[1,64],106:86,107:[1,66],108:67,115:[2,136],123:[2,136],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,138],6:[2,138],25:[2,138],26:[2,138],47:[2,138],52:[2,138],55:[2,138],70:[2,138],75:[2,138],83:[2,138],88:[2,138],90:[2,138],99:[2,138],100:85,101:[1,63],102:[1,226],103:[1,64],106:86,107:[1,66],108:67,115:[2,138],123:[2,138],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,144],6:[2,144],25:[2,144],26:[2,144],47:[2,144],52:[2,144],55:[2,144],70:[2,144],75:[2,144],83:[2,144],88:[2,144],90:[2,144],99:[2,144],101:[2,144],102:[2,144],103:[2,144],107:[2,144],115:[2,144],123:[2,144],125:[2,144],126:[2,144],129:[2,144],130:[2,144],131:[2,144],132:[2,144],133:[2,144],134:[2,144]},{1:[2,145],6:[2,145],25:[2,145],26:[2,145],47:[2,145],52:[2,145],55:[2,145],70:[2,145],75:[2,145],83:[2,145],88:[2,145],90:[2,145],99:[2,145],100:85,101:[1,63],102:[2,145],103:[1,64],106:86,107:[1,66],108:67,115:[2,145],123:[2,145],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,149],6:[2,149],25:[2,149],26:[2,149],47:[2,149],52:[2,149],55:[2,149],70:[2,149],75:[2,149],83:[2,149],88:[2,149],90:[2,149],99:[2,149],101:[2,149],102:[2,149],103:[2,149],107:[2,149],115:[2,149],123:[2,149],125:[2,149],126:[2,149],129:[2,149],130:[2,149],131:[2,149],132:[2,149],133:[2,149],134:[2,149]},{113:[2,151],114:[2,151]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],110:227,112:155},{52:[1,228],113:[2,156],114:[2,156]},{52:[2,153],113:[2,153],114:[2,153]},{52:[2,154],113:[2,154],114:[2,154]},{52:[2,155],113:[2,155],114:[2,155]},{1:[2,150],6:[2,150],25:[2,150],26:[2,150],47:[2,150],52:[2,150],55:[2,150],70:[2,150],75:[2,150],83:[2,150],88:[2,150],90:[2,150],99:[2,150],101:[2,150],102:[2,150],103:[2,150],107:[2,150],115:[2,150],123:[2,150],125:[2,150],126:[2,150],129:[2,150],130:[2,150],131:[2,150],132:[2,150],133:[2,150],134:[2,150]},{8:229,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:230,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],51:231,52:[1,232],75:[2,51]},{6:[2,87],25:[2,87],26:[2,87],52:[2,87],75:[2,87]},{6:[2,37],25:[2,37],26:[2,37],41:[1,233],52:[2,37],75:[2,37]},{6:[2,40],25:[2,40],26:[2,40],52:[2,40],75:[2,40]},{6:[2,41],25:[2,41],26:[2,41],41:[2,41],52:[2,41],75:[2,41]},{6:[2,42],25:[2,42],26:[2,42],41:[2,42],52:[2,42],75:[2,42]},{6:[2,43],25:[2,43],26:[2,43],41:[2,43],52:[2,43],75:[2,43]},{1:[2,5],6:[2,5],26:[2,5],99:[2,5]},{1:[2,25],6:[2,25],25:[2,25],26:[2,25],47:[2,25],52:[2,25],55:[2,25],70:[2,25],75:[2,25],83:[2,25],88:[2,25],90:[2,25],95:[2,25],96:[2,25],99:[2,25],101:[2,25],102:[2,25],103:[2,25],107:[2,25],115:[2,25],118:[2,25],120:[2,25],123:[2,25],125:[2,25],126:[2,25],129:[2,25],130:[2,25],131:[2,25],132:[2,25],133:[2,25],134:[2,25]},{1:[2,187],6:[2,187],25:[2,187],26:[2,187],47:[2,187],52:[2,187],55:[2,187],70:[2,187],75:[2,187],83:[2,187],88:[2,187],90:[2,187],99:[2,187],100:85,101:[2,187],102:[2,187],103:[2,187],106:86,107:[2,187],108:67,115:[2,187],123:[2,187],125:[2,187],126:[2,187],129:[1,76],130:[1,79],131:[2,187],132:[2,187],133:[2,187],134:[2,187]},{1:[2,188],6:[2,188],25:[2,188],26:[2,188],47:[2,188],52:[2,188],55:[2,188],70:[2,188],75:[2,188],83:[2,188],88:[2,188],90:[2,188],99:[2,188],100:85,101:[2,188],102:[2,188],103:[2,188],106:86,107:[2,188],108:67,115:[2,188],123:[2,188],125:[2,188],126:[2,188],129:[1,76],130:[1,79],131:[2,188],132:[2,188],133:[2,188],134:[2,188]},{1:[2,189],6:[2,189],25:[2,189],26:[2,189],47:[2,189],52:[2,189],55:[2,189],70:[2,189],75:[2,189],83:[2,189],88:[2,189],90:[2,189],99:[2,189],100:85,101:[2,189],102:[2,189],103:[2,189],106:86,107:[2,189],108:67,115:[2,189],123:[2,189],125:[2,189],126:[2,189],129:[1,76],130:[2,189],131:[2,189],132:[2,189],133:[2,189],134:[2,189]},{1:[2,190],6:[2,190],25:[2,190],26:[2,190],47:[2,190],52:[2,190],55:[2,190],70:[2,190],75:[2,190],83:[2,190],88:[2,190],90:[2,190],99:[2,190],100:85,101:[2,190],102:[2,190],103:[2,190],106:86,107:[2,190],108:67,115:[2,190],123:[2,190],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[2,190],132:[2,190],133:[2,190],134:[2,190]},{1:[2,191],6:[2,191],25:[2,191],26:[2,191],47:[2,191],52:[2,191],55:[2,191],70:[2,191],75:[2,191],83:[2,191],88:[2,191],90:[2,191],99:[2,191],100:85,101:[2,191],102:[2,191],103:[2,191],106:86,107:[2,191],108:67,115:[2,191],123:[2,191],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,191],133:[2,191],134:[1,83]},{1:[2,192],6:[2,192],25:[2,192],26:[2,192],47:[2,192],52:[2,192],55:[2,192],70:[2,192],75:[2,192],83:[2,192],88:[2,192],90:[2,192],99:[2,192],100:85,101:[2,192],102:[2,192],103:[2,192],106:86,107:[2,192],108:67,115:[2,192],123:[2,192],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[2,192],134:[1,83]},{1:[2,193],6:[2,193],25:[2,193],26:[2,193],47:[2,193],52:[2,193],55:[2,193],70:[2,193],75:[2,193],83:[2,193],88:[2,193],90:[2,193],99:[2,193],100:85,101:[2,193],102:[2,193],103:[2,193],106:86,107:[2,193],108:67,115:[2,193],123:[2,193],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,193],133:[2,193],134:[2,193]},{1:[2,178],6:[2,178],25:[2,178],26:[2,178],47:[2,178],52:[2,178],55:[2,178],70:[2,178],75:[2,178],83:[2,178],88:[2,178],90:[2,178],99:[2,178],100:85,101:[1,63],102:[2,178],103:[1,64],106:86,107:[1,66],108:67,115:[2,178],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,177],6:[2,177],25:[2,177],26:[2,177],47:[2,177],52:[2,177],55:[2,177],70:[2,177],75:[2,177],83:[2,177],88:[2,177],90:[2,177],99:[2,177],100:85,101:[1,63],102:[2,177],103:[1,64],106:86,107:[1,66],108:67,115:[2,177],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,99],6:[2,99],25:[2,99],26:[2,99],47:[2,99],52:[2,99],55:[2,99],64:[2,99],65:[2,99],66:[2,99],68:[2,99],70:[2,99],71:[2,99],75:[2,99],81:[2,99],82:[2,99],83:[2,99],88:[2,99],90:[2,99],99:[2,99],101:[2,99],102:[2,99],103:[2,99],107:[2,99],115:[2,99],123:[2,99],125:[2,99],126:[2,99],129:[2,99],130:[2,99],131:[2,99],132:[2,99],133:[2,99],134:[2,99]},{1:[2,76],6:[2,76],25:[2,76],26:[2,76],38:[2,76],47:[2,76],52:[2,76],55:[2,76],64:[2,76],65:[2,76],66:[2,76],68:[2,76],70:[2,76],71:[2,76],75:[2,76],77:[2,76],81:[2,76],82:[2,76],83:[2,76],88:[2,76],90:[2,76],99:[2,76],101:[2,76],102:[2,76],103:[2,76],107:[2,76],115:[2,76],123:[2,76],125:[2,76],126:[2,76],127:[2,76],128:[2,76],129:[2,76],130:[2,76],131:[2,76],132:[2,76],133:[2,76],134:[2,76],135:[2,76]},{1:[2,77],6:[2,77],25:[2,77],26:[2,77],38:[2,77],47:[2,77],52:[2,77],55:[2,77],64:[2,77],65:[2,77],66:[2,77],68:[2,77],70:[2,77],71:[2,77],75:[2,77],77:[2,77],81:[2,77],82:[2,77],83:[2,77],88:[2,77],90:[2,77],99:[2,77],101:[2,77],102:[2,77],103:[2,77],107:[2,77],115:[2,77],123:[2,77],125:[2,77],126:[2,77],127:[2,77],128:[2,77],129:[2,77],130:[2,77],131:[2,77],132:[2,77],133:[2,77],134:[2,77],135:[2,77]},{1:[2,78],6:[2,78],25:[2,78],26:[2,78],38:[2,78],47:[2,78],52:[2,78],55:[2,78],64:[2,78],65:[2,78],66:[2,78],68:[2,78],70:[2,78],71:[2,78],75:[2,78],77:[2,78],81:[2,78],82:[2,78],83:[2,78],88:[2,78],90:[2,78],99:[2,78],101:[2,78],102:[2,78],103:[2,78],107:[2,78],115:[2,78],123:[2,78],125:[2,78],126:[2,78],127:[2,78],128:[2,78],129:[2,78],130:[2,78],131:[2,78],132:[2,78],133:[2,78],134:[2,78],135:[2,78]},{70:[1,234]},{55:[1,189],70:[2,83],89:235,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{70:[2,84]},{8:236,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,118],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{12:[2,112],28:[2,112],30:[2,112],31:[2,112],33:[2,112],34:[2,112],35:[2,112],36:[2,112],43:[2,112],44:[2,112],45:[2,112],49:[2,112],50:[2,112],70:[2,112],73:[2,112],76:[2,112],80:[2,112],85:[2,112],86:[2,112],87:[2,112],93:[2,112],97:[2,112],98:[2,112],101:[2,112],103:[2,112],105:[2,112],107:[2,112],116:[2,112],122:[2,112],124:[2,112],125:[2,112],126:[2,112],127:[2,112],128:[2,112]},{12:[2,113],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],70:[2,113],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{1:[2,82],6:[2,82],25:[2,82],26:[2,82],38:[2,82],47:[2,82],52:[2,82],55:[2,82],64:[2,82],65:[2,82],66:[2,82],68:[2,82],70:[2,82],71:[2,82],75:[2,82],77:[2,82],81:[2,82],82:[2,82],83:[2,82],88:[2,82],90:[2,82],99:[2,82],101:[2,82],102:[2,82],103:[2,82],107:[2,82],115:[2,82],123:[2,82],125:[2,82],126:[2,82],127:[2,82],128:[2,82],129:[2,82],130:[2,82],131:[2,82],132:[2,82],133:[2,82],134:[2,82],135:[2,82]},{1:[2,100],6:[2,100],25:[2,100],26:[2,100],47:[2,100],52:[2,100],55:[2,100],64:[2,100],65:[2,100],66:[2,100],68:[2,100],70:[2,100],71:[2,100],75:[2,100],81:[2,100],82:[2,100],83:[2,100],88:[2,100],90:[2,100],99:[2,100],101:[2,100],102:[2,100],103:[2,100],107:[2,100],115:[2,100],123:[2,100],125:[2,100],126:[2,100],129:[2,100],130:[2,100],131:[2,100],132:[2,100],133:[2,100],134:[2,100]},{1:[2,34],6:[2,34],25:[2,34],26:[2,34],47:[2,34],52:[2,34],55:[2,34],70:[2,34],75:[2,34],83:[2,34],88:[2,34],90:[2,34],99:[2,34],100:85,101:[2,34],102:[2,34],103:[2,34],106:86,107:[2,34],108:67,115:[2,34],123:[2,34],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:237,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:238,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,105],6:[2,105],25:[2,105],26:[2,105],47:[2,105],52:[2,105],55:[2,105],64:[2,105],65:[2,105],66:[2,105],68:[2,105],70:[2,105],71:[2,105],75:[2,105],81:[2,105],82:[2,105],83:[2,105],88:[2,105],90:[2,105],99:[2,105],101:[2,105],102:[2,105],103:[2,105],107:[2,105],115:[2,105],123:[2,105],125:[2,105],126:[2,105],129:[2,105],130:[2,105],131:[2,105],132:[2,105],133:[2,105],134:[2,105]},{6:[2,51],25:[2,51],51:239,52:[1,222],83:[2,51]},{6:[2,124],25:[2,124],26:[2,124],52:[2,124],55:[1,240],83:[2,124],88:[2,124],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{48:241,49:[1,58],50:[1,59]},{27:107,28:[1,71],42:108,53:242,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{47:[2,57],52:[2,57]},{8:243,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,194],6:[2,194],25:[2,194],26:[2,194],47:[2,194],52:[2,194],55:[2,194],70:[2,194],75:[2,194],83:[2,194],88:[2,194],90:[2,194],99:[2,194],100:85,101:[2,194],102:[2,194],103:[2,194],106:86,107:[2,194],108:67,115:[2,194],123:[2,194],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:244,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,196],6:[2,196],25:[2,196],26:[2,196],47:[2,196],52:[2,196],55:[2,196],70:[2,196],75:[2,196],83:[2,196],88:[2,196],90:[2,196],99:[2,196],100:85,101:[2,196],102:[2,196],103:[2,196],106:86,107:[2,196],108:67,115:[2,196],123:[2,196],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,176],6:[2,176],25:[2,176],26:[2,176],47:[2,176],52:[2,176],55:[2,176],70:[2,176],75:[2,176],83:[2,176],88:[2,176],90:[2,176],99:[2,176],101:[2,176],102:[2,176],103:[2,176],107:[2,176],115:[2,176],123:[2,176],125:[2,176],126:[2,176],129:[2,176],130:[2,176],131:[2,176],132:[2,176],133:[2,176],134:[2,176]},{8:245,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,129],6:[2,129],25:[2,129],26:[2,129],47:[2,129],52:[2,129],55:[2,129],70:[2,129],75:[2,129],83:[2,129],88:[2,129],90:[2,129],95:[1,246],99:[2,129],101:[2,129],102:[2,129],103:[2,129],107:[2,129],115:[2,129],123:[2,129],125:[2,129],126:[2,129],129:[2,129],130:[2,129],131:[2,129],132:[2,129],133:[2,129],134:[2,129]},{5:247,25:[1,5]},{27:248,28:[1,71]},{117:249,119:212,120:[1,213]},{26:[1,250],118:[1,251],119:252,120:[1,213]},{26:[2,169],118:[2,169],120:[2,169]},{8:254,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],92:253,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,93],5:255,6:[2,93],25:[1,5],26:[2,93],47:[2,93],52:[2,93],55:[2,93],70:[2,93],75:[2,93],83:[2,93],88:[2,93],90:[2,93],99:[2,93],100:85,101:[1,63],102:[2,93],103:[1,64],106:86,107:[1,66],108:67,115:[2,93],123:[2,93],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,96],6:[2,96],25:[2,96],26:[2,96],47:[2,96],52:[2,96],55:[2,96],70:[2,96],75:[2,96],83:[2,96],88:[2,96],90:[2,96],99:[2,96],101:[2,96],102:[2,96],103:[2,96],107:[2,96],115:[2,96],123:[2,96],125:[2,96],126:[2,96],129:[2,96],130:[2,96],131:[2,96],132:[2,96],133:[2,96],134:[2,96]},{8:256,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,134],6:[2,134],25:[2,134],26:[2,134],47:[2,134],52:[2,134],55:[2,134],64:[2,134],65:[2,134],66:[2,134],68:[2,134],70:[2,134],71:[2,134],75:[2,134],81:[2,134],82:[2,134],83:[2,134],88:[2,134],90:[2,134],99:[2,134],101:[2,134],102:[2,134],103:[2,134],107:[2,134],115:[2,134],123:[2,134],125:[2,134],126:[2,134],129:[2,134],130:[2,134],131:[2,134],132:[2,134],133:[2,134],134:[2,134]},{6:[1,72],26:[1,257]},{8:258,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,63],12:[2,113],25:[2,63],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],52:[2,63],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],88:[2,63],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{6:[1,260],25:[1,261],88:[1,259]},{6:[2,52],8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[2,52],26:[2,52],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[2,52],85:[1,56],86:[1,57],87:[1,55],88:[2,52],91:262,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],26:[2,51],51:263,52:[1,222]},{1:[2,173],6:[2,173],25:[2,173],26:[2,173],47:[2,173],52:[2,173],55:[2,173],70:[2,173],75:[2,173],83:[2,173],88:[2,173],90:[2,173],99:[2,173],101:[2,173],102:[2,173],103:[2,173],107:[2,173],115:[2,173],118:[2,173],123:[2,173],125:[2,173],126:[2,173],129:[2,173],130:[2,173],131:[2,173],132:[2,173],133:[2,173],134:[2,173]},{8:264,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:265,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{113:[2,152],114:[2,152]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],112:266},{1:[2,158],6:[2,158],25:[2,158],26:[2,158],47:[2,158],52:[2,158],55:[2,158],70:[2,158],75:[2,158],83:[2,158],88:[2,158],90:[2,158],99:[2,158],100:85,101:[2,158],102:[1,267],103:[2,158],106:86,107:[2,158],108:67,115:[1,268],123:[2,158],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,159],6:[2,159],25:[2,159],26:[2,159],47:[2,159],52:[2,159],55:[2,159],70:[2,159],75:[2,159],83:[2,159],88:[2,159],90:[2,159],99:[2,159],100:85,101:[2,159],102:[1,269],103:[2,159],106:86,107:[2,159],108:67,115:[2,159],123:[2,159],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,271],25:[1,272],75:[1,270]},{6:[2,52],11:165,25:[2,52],26:[2,52],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:273,40:164,42:168,44:[1,46],75:[2,52],86:[1,111]},{8:274,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,275],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,81],6:[2,81],25:[2,81],26:[2,81],38:[2,81],47:[2,81],52:[2,81],55:[2,81],64:[2,81],65:[2,81],66:[2,81],68:[2,81],70:[2,81],71:[2,81],75:[2,81],77:[2,81],81:[2,81],82:[2,81],83:[2,81],88:[2,81],90:[2,81],99:[2,81],101:[2,81],102:[2,81],103:[2,81],107:[2,81],115:[2,81],123:[2,81],125:[2,81],126:[2,81],127:[2,81],128:[2,81],129:[2,81],130:[2,81],131:[2,81],132:[2,81],133:[2,81],134:[2,81],135:[2,81]},{8:276,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,116],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,117],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,35],6:[2,35],25:[2,35],26:[2,35],47:[2,35],52:[2,35],55:[2,35],70:[2,35],75:[2,35],83:[2,35],88:[2,35],90:[2,35],99:[2,35],100:85,101:[2,35],102:[2,35],103:[2,35],106:86,107:[2,35],108:67,115:[2,35],123:[2,35],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,277],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],83:[1,278]},{6:[2,63],25:[2,63],26:[2,63],52:[2,63],83:[2,63],88:[2,63]},{5:279,25:[1,5]},{47:[2,55],52:[2,55]},{47:[2,58],52:[2,58],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,280],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:281,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:282,25:[1,5]},{1:[2,130],6:[2,130],25:[2,130],26:[2,130],47:[2,130],52:[2,130],55:[2,130],70:[2,130],75:[2,130],83:[2,130],88:[2,130],90:[2,130],99:[2,130],101:[2,130],102:[2,130],103:[2,130],107:[2,130],115:[2,130],123:[2,130],125:[2,130],126:[2,130],129:[2,130],130:[2,130],131:[2,130],132:[2,130],133:[2,130],134:[2,130]},{5:283,25:[1,5]},{26:[1,284],118:[1,285],119:252,120:[1,213]},{1:[2,167],6:[2,167],25:[2,167],26:[2,167],47:[2,167],52:[2,167],55:[2,167],70:[2,167],75:[2,167],83:[2,167],88:[2,167],90:[2,167],99:[2,167],101:[2,167],102:[2,167],103:[2,167],107:[2,167],115:[2,167],123:[2,167],125:[2,167],126:[2,167],129:[2,167],130:[2,167],131:[2,167],132:[2,167],133:[2,167],134:[2,167]},{5:286,25:[1,5]},{26:[2,170],118:[2,170],120:[2,170]},{5:287,25:[1,5],52:[1,288]},{25:[2,126],52:[2,126],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,94],6:[2,94],25:[2,94],26:[2,94],47:[2,94],52:[2,94],55:[2,94],70:[2,94],75:[2,94],83:[2,94],88:[2,94],90:[2,94],99:[2,94],101:[2,94],102:[2,94],103:[2,94],107:[2,94],115:[2,94],123:[2,94],125:[2,94],126:[2,94],129:[2,94],130:[2,94],131:[2,94],132:[2,94],133:[2,94],134:[2,94]},{1:[2,97],5:289,6:[2,97],25:[1,5],26:[2,97],47:[2,97],52:[2,97],55:[2,97],70:[2,97],75:[2,97],83:[2,97],88:[2,97],90:[2,97],99:[2,97],100:85,101:[1,63],102:[2,97],103:[1,64],106:86,107:[1,66],108:67,115:[2,97],123:[2,97],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{99:[1,290]},{88:[1,291],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,111],6:[2,111],25:[2,111],26:[2,111],38:[2,111],47:[2,111],52:[2,111],55:[2,111],64:[2,111],65:[2,111],66:[2,111],68:[2,111],70:[2,111],71:[2,111],75:[2,111],81:[2,111],82:[2,111],83:[2,111],88:[2,111],90:[2,111],99:[2,111],101:[2,111],102:[2,111],103:[2,111],107:[2,111],113:[2,111],114:[2,111],115:[2,111],123:[2,111],125:[2,111],126:[2,111],129:[2,111],130:[2,111],131:[2,111],132:[2,111],133:[2,111],134:[2,111]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],91:292,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:293,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,120],25:[2,120],26:[2,120],52:[2,120],83:[2,120],88:[2,120]},{6:[1,260],25:[1,261],26:[1,294]},{1:[2,137],6:[2,137],25:[2,137],26:[2,137],47:[2,137],52:[2,137],55:[2,137],70:[2,137],75:[2,137],83:[2,137],88:[2,137],90:[2,137],99:[2,137],100:85,101:[1,63],102:[2,137],103:[1,64],106:86,107:[1,66],108:67,115:[2,137],123:[2,137],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,139],6:[2,139],25:[2,139],26:[2,139],47:[2,139],52:[2,139],55:[2,139],70:[2,139],75:[2,139],83:[2,139],88:[2,139],90:[2,139],99:[2,139],100:85,101:[1,63],102:[2,139],103:[1,64],106:86,107:[1,66],108:67,115:[2,139],123:[2,139],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{113:[2,157],114:[2,157]},{8:295,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:296,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:297,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,85],6:[2,85],25:[2,85],26:[2,85],38:[2,85],47:[2,85],52:[2,85],55:[2,85],64:[2,85],65:[2,85],66:[2,85],68:[2,85],70:[2,85],71:[2,85],75:[2,85],81:[2,85],82:[2,85],83:[2,85],88:[2,85],90:[2,85],99:[2,85],101:[2,85],102:[2,85],103:[2,85],107:[2,85],113:[2,85],114:[2,85],115:[2,85],123:[2,85],125:[2,85],126:[2,85],129:[2,85],130:[2,85],131:[2,85],132:[2,85],133:[2,85],134:[2,85]},{11:165,27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:298,40:164,42:168,44:[1,46],86:[1,111]},{6:[2,86],11:165,25:[2,86],26:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:299,86:[1,111]},{6:[2,88],25:[2,88],26:[2,88],52:[2,88],75:[2,88]},{6:[2,38],25:[2,38],26:[2,38],52:[2,38],75:[2,38],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:300,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,115],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,36],6:[2,36],25:[2,36],26:[2,36],47:[2,36],52:[2,36],55:[2,36],70:[2,36],75:[2,36],83:[2,36],88:[2,36],90:[2,36],99:[2,36],101:[2,36],102:[2,36],103:[2,36],107:[2,36],115:[2,36],123:[2,36],125:[2,36],126:[2,36],129:[2,36],130:[2,36],131:[2,36],132:[2,36],133:[2,36],134:[2,36]},{1:[2,106],6:[2,106],25:[2,106],26:[2,106],47:[2,106],52:[2,106],55:[2,106],64:[2,106],65:[2,106],66:[2,106],68:[2,106],70:[2,106],71:[2,106],75:[2,106],81:[2,106],82:[2,106],83:[2,106],88:[2,106],90:[2,106],99:[2,106],101:[2,106],102:[2,106],103:[2,106],107:[2,106],115:[2,106],123:[2,106],125:[2,106],126:[2,106],129:[2,106],130:[2,106],131:[2,106],132:[2,106],133:[2,106],134:[2,106]},{1:[2,47],6:[2,47],25:[2,47],26:[2,47],47:[2,47],52:[2,47],55:[2,47],70:[2,47],75:[2,47],83:[2,47],88:[2,47],90:[2,47],99:[2,47],101:[2,47],102:[2,47],103:[2,47],107:[2,47],115:[2,47],123:[2,47],125:[2,47],126:[2,47],129:[2,47],130:[2,47],131:[2,47],132:[2,47],133:[2,47],134:[2,47]},{1:[2,195],6:[2,195],25:[2,195],26:[2,195],47:[2,195],52:[2,195],55:[2,195],70:[2,195],75:[2,195],83:[2,195],88:[2,195],90:[2,195],99:[2,195],101:[2,195],102:[2,195],103:[2,195],107:[2,195],115:[2,195],123:[2,195],125:[2,195],126:[2,195],129:[2,195],130:[2,195],131:[2,195],132:[2,195],133:[2,195],134:[2,195]},{1:[2,174],6:[2,174],25:[2,174],26:[2,174],47:[2,174],52:[2,174],55:[2,174],70:[2,174],75:[2,174],83:[2,174],88:[2,174],90:[2,174],99:[2,174],101:[2,174],102:[2,174],103:[2,174],107:[2,174],115:[2,174],118:[2,174],123:[2,174],125:[2,174],126:[2,174],129:[2,174],130:[2,174],131:[2,174],132:[2,174],133:[2,174],134:[2,174]},{1:[2,131],6:[2,131],25:[2,131],26:[2,131],47:[2,131],52:[2,131],55:[2,131],70:[2,131],75:[2,131],83:[2,131],88:[2,131],90:[2,131],99:[2,131],101:[2,131],102:[2,131],103:[2,131],107:[2,131],115:[2,131],123:[2,131],125:[2,131],126:[2,131],129:[2,131],130:[2,131],131:[2,131],132:[2,131],133:[2,131],134:[2,131]},{1:[2,132],6:[2,132],25:[2,132],26:[2,132],47:[2,132],52:[2,132],55:[2,132],70:[2,132],75:[2,132],83:[2,132],88:[2,132],90:[2,132],95:[2,132],99:[2,132],101:[2,132],102:[2,132],103:[2,132],107:[2,132],115:[2,132],123:[2,132],125:[2,132],126:[2,132],129:[2,132],130:[2,132],131:[2,132],132:[2,132],133:[2,132],134:[2,132]},{1:[2,165],6:[2,165],25:[2,165],26:[2,165],47:[2,165],52:[2,165],55:[2,165],70:[2,165],75:[2,165],83:[2,165],88:[2,165],90:[2,165],99:[2,165],101:[2,165],102:[2,165],103:[2,165],107:[2,165],115:[2,165],123:[2,165],125:[2,165],126:[2,165],129:[2,165],130:[2,165],131:[2,165],132:[2,165],133:[2,165],134:[2,165]},{5:301,25:[1,5]},{26:[1,302]},{6:[1,303],26:[2,171],118:[2,171],120:[2,171]},{8:304,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,98],6:[2,98],25:[2,98],26:[2,98],47:[2,98],52:[2,98],55:[2,98],70:[2,98],75:[2,98],83:[2,98],88:[2,98],90:[2,98],99:[2,98],101:[2,98],102:[2,98],103:[2,98],107:[2,98],115:[2,98],123:[2,98],125:[2,98],126:[2,98],129:[2,98],130:[2,98],131:[2,98],132:[2,98],133:[2,98],134:[2,98]},{1:[2,135],6:[2,135],25:[2,135],26:[2,135],47:[2,135],52:[2,135],55:[2,135],64:[2,135],65:[2,135],66:[2,135],68:[2,135],70:[2,135],71:[2,135],75:[2,135],81:[2,135],82:[2,135],83:[2,135],88:[2,135],90:[2,135],99:[2,135],101:[2,135],102:[2,135],103:[2,135],107:[2,135],115:[2,135],123:[2,135],125:[2,135],126:[2,135],129:[2,135],130:[2,135],131:[2,135],132:[2,135],133:[2,135],134:[2,135]},{1:[2,114],6:[2,114],25:[2,114],26:[2,114],47:[2,114],52:[2,114],55:[2,114],64:[2,114],65:[2,114],66:[2,114],68:[2,114],70:[2,114],71:[2,114],75:[2,114],81:[2,114],82:[2,114],83:[2,114],88:[2,114],90:[2,114],99:[2,114],101:[2,114],102:[2,114],103:[2,114],107:[2,114],115:[2,114],123:[2,114],125:[2,114],126:[2,114],129:[2,114],130:[2,114],131:[2,114],132:[2,114],133:[2,114],134:[2,114]},{6:[2,121],25:[2,121],26:[2,121],52:[2,121],83:[2,121],88:[2,121]},{6:[2,51],25:[2,51],26:[2,51],51:305,52:[1,222]},{6:[2,122],25:[2,122],26:[2,122],52:[2,122],83:[2,122],88:[2,122]},{1:[2,160],6:[2,160],25:[2,160],26:[2,160],47:[2,160],52:[2,160],55:[2,160],70:[2,160],75:[2,160],83:[2,160],88:[2,160],90:[2,160],99:[2,160],100:85,101:[2,160],102:[2,160],103:[2,160],106:86,107:[2,160],108:67,115:[1,306],123:[2,160],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,162],6:[2,162],25:[2,162],26:[2,162],47:[2,162],52:[2,162],55:[2,162],70:[2,162],75:[2,162],83:[2,162],88:[2,162],90:[2,162],99:[2,162],100:85,101:[2,162],102:[1,307],103:[2,162],106:86,107:[2,162],108:67,115:[2,162],123:[2,162],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,161],6:[2,161],25:[2,161],26:[2,161],47:[2,161],52:[2,161],55:[2,161],70:[2,161],75:[2,161],83:[2,161],88:[2,161],90:[2,161],99:[2,161],100:85,101:[2,161],102:[2,161],103:[2,161],106:86,107:[2,161],108:67,115:[2,161],123:[2,161],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,89],25:[2,89],26:[2,89],52:[2,89],75:[2,89]},{6:[2,51],25:[2,51],26:[2,51],51:308,52:[1,232]},{26:[1,309],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,310]},{1:[2,168],6:[2,168],25:[2,168],26:[2,168],47:[2,168],52:[2,168],55:[2,168],70:[2,168],75:[2,168],83:[2,168],88:[2,168],90:[2,168],99:[2,168],101:[2,168],102:[2,168],103:[2,168],107:[2,168],115:[2,168],123:[2,168],125:[2,168],126:[2,168],129:[2,168],130:[2,168],131:[2,168],132:[2,168],133:[2,168],134:[2,168]},{26:[2,172],118:[2,172],120:[2,172]},{25:[2,127],52:[2,127],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],26:[1,311]},{8:312,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:313,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[1,271],25:[1,272],26:[1,314]},{6:[2,39],25:[2,39],26:[2,39],52:[2,39],75:[2,39]},{1:[2,166],6:[2,166],25:[2,166],26:[2,166],47:[2,166],52:[2,166],55:[2,166],70:[2,166],75:[2,166],83:[2,166],88:[2,166],90:[2,166],99:[2,166],101:[2,166],102:[2,166],103:[2,166],107:[2,166],115:[2,166],123:[2,166],125:[2,166],126:[2,166],129:[2,166],130:[2,166],131:[2,166],132:[2,166],133:[2,166],134:[2,166]},{6:[2,123],25:[2,123],26:[2,123],52:[2,123],83:[2,123],88:[2,123]},{1:[2,163],6:[2,163],25:[2,163],26:[2,163],47:[2,163],52:[2,163],55:[2,163],70:[2,163],75:[2,163],83:[2,163],88:[2,163],90:[2,163],99:[2,163],100:85,101:[2,163],102:[2,163],103:[2,163],106:86,107:[2,163],108:67,115:[2,163],123:[2,163],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,164],6:[2,164],25:[2,164],26:[2,164],47:[2,164],52:[2,164],55:[2,164],70:[2,164],75:[2,164],83:[2,164],88:[2,164],90:[2,164],99:[2,164],100:85,101:[2,164],102:[2,164],103:[2,164],106:86,107:[2,164],108:67,115:[2,164],123:[2,164],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,90],25:[2,90],26:[2,90],52:[2,90],75:[2,90]}], -defaultActions: {58:[2,49],59:[2,50],73:[2,3],92:[2,104],186:[2,84]}, -parseError: function parseError(str, hash) { - throw new Error(str); -}, -parse: function parse(input) { - var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; - this.lexer.setInput(input); - this.lexer.yy = this.yy; - this.yy.lexer = this.lexer; - if (typeof this.lexer.yylloc == "undefined") - this.lexer.yylloc = {}; - var yyloc = this.lexer.yylloc; - lstack.push(yyloc); - if (typeof this.yy.parseError === "function") - this.parseError = this.yy.parseError; - function popStack(n) { - stack.length = stack.length - 2 * n; - vstack.length = vstack.length - n; - lstack.length = lstack.length - n; - } - function lex() { - var token; - token = self.lexer.lex() || 1; - if (typeof token !== "number") { - token = self.symbols_[token] || token; - } - return token; - } - var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; - while (true) { - state = stack[stack.length - 1]; - if (this.defaultActions[state]) { - action = this.defaultActions[state]; - } else { - if (symbol == null) - symbol = lex(); - action = table[state] && table[state][symbol]; - } - if (typeof action === "undefined" || !action.length || !action[0]) { - if (!recovering) { - expected = []; - for (p in table[state]) - if (this.terminals_[p] && p > 2) { - expected.push("'" + this.terminals_[p] + "'"); - } - var errStr = ""; - if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + this.terminals_[symbol] + "'"; - } else { - errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected "+ (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); - } - if (errStr != "") this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); - } - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - if (typeof r !== "undefined") { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; -} -}; - -module.exports = parser; - - -}); - -define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coffee/scope', 'ace/mode/coffee/lexer', 'ace/mode/coffee/helpers'], function(require, exports, module) { -// Generated by CoffeeScript 1.2.1-pre - - var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, starts, unfoldSoak, utility, _ref, _ref1, - __hasProp = {}.hasOwnProperty, - __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }, - __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; - - Scope = require('./scope').Scope; - - _ref = require('./lexer'), RESERVED = _ref.RESERVED, STRICT_PROSCRIBED = _ref.STRICT_PROSCRIBED; - - _ref1 = require('./helpers'), compact = _ref1.compact, flatten = _ref1.flatten, extend = _ref1.extend, merge = _ref1.merge, del = _ref1.del, starts = _ref1.starts, ends = _ref1.ends, last = _ref1.last; - - exports.extend = extend; - - YES = function() { - return true; - }; - - NO = function() { - return false; - }; - - THIS = function() { - return this; - }; - - NEGATE = function() { - this.negated = !this.negated; - return this; - }; - - exports.Base = Base = (function() { - - Base.name = 'Base'; - - function Base() {} - - Base.prototype.compile = function(o, lvl) { - var node; - o = extend({}, o); - if (lvl) o.level = lvl; - node = this.unfoldSoak(o) || this; - node.tab = o.indent; - if (o.level === LEVEL_TOP || !node.isStatement(o)) { - return node.compileNode(o); - } else { - return node.compileClosure(o); - } - }; - - Base.prototype.compileClosure = function(o) { - if (this.jumps()) { - throw SyntaxError('cannot use a pure statement in an expression.'); - } - o.sharedScope = true; - return Closure.wrap(this).compileNode(o); - }; - - Base.prototype.cache = function(o, level, reused) { - var ref, sub; - if (!this.isComplex()) { - ref = level ? this.compile(o, level) : this; - return [ref, ref]; - } else { - ref = new Literal(reused || o.scope.freeVariable('ref')); - sub = new Assign(ref, this); - if (level) { - return [sub.compile(o, level), ref.value]; - } else { - return [sub, ref]; - } - } - }; - - Base.prototype.compileLoopReference = function(o, name) { - var src, tmp; - src = tmp = this.compile(o, LEVEL_LIST); - if (!((-Infinity < +src && +src < Infinity) || IDENTIFIER.test(src) && o.scope.check(src, true))) { - src = "" + (tmp = o.scope.freeVariable(name)) + " = " + src; - } - return [src, tmp]; - }; - - Base.prototype.makeReturn = function(res) { - var me; - me = this.unwrapAll(); - if (res) { - return new Call(new Literal("" + res + ".push"), [me]); - } else { - return new Return(me); - } - }; - - Base.prototype.contains = function(pred) { - var contains; - contains = false; - this.traverseChildren(false, function(node) { - if (pred(node)) { - contains = true; - return false; - } - }); - return contains; - }; - - Base.prototype.containsType = function(type) { - return this instanceof type || this.contains(function(node) { - return node instanceof type; - }); - }; - - Base.prototype.lastNonComment = function(list) { - var i; - i = list.length; - while (i--) { - if (!(list[i] instanceof Comment)) return list[i]; - } - return null; - }; - - Base.prototype.toString = function(idt, name) { - var tree; - if (idt == null) idt = ''; - if (name == null) name = this.constructor.name; - tree = '\n' + idt + name; - if (this.soak) tree += '?'; - this.eachChild(function(node) { - return tree += node.toString(idt + TAB); - }); - return tree; - }; - - Base.prototype.eachChild = function(func) { - var attr, child, _i, _j, _len, _len1, _ref2, _ref3; - if (!this.children) return this; - _ref2 = this.children; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - attr = _ref2[_i]; - if (this[attr]) { - _ref3 = flatten([this[attr]]); - for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { - child = _ref3[_j]; - if (func(child) === false) return this; - } - } - } - return this; - }; - - Base.prototype.traverseChildren = function(crossScope, func) { - return this.eachChild(function(child) { - if (func(child) === false) return false; - return child.traverseChildren(crossScope, func); - }); - }; - - Base.prototype.invert = function() { - return new Op('!', this); - }; - - Base.prototype.unwrapAll = function() { - var node; - node = this; - while (node !== (node = node.unwrap())) { - continue; - } - return node; - }; - - Base.prototype.children = []; - - Base.prototype.isStatement = NO; - - Base.prototype.jumps = NO; - - Base.prototype.isComplex = YES; - - Base.prototype.isChainable = NO; - - Base.prototype.isAssignable = NO; - - Base.prototype.unwrap = THIS; - - Base.prototype.unfoldSoak = NO; - - Base.prototype.assigns = NO; - - return Base; - - })(); - - exports.Block = Block = (function(_super) { - - __extends(Block, _super); - - Block.name = 'Block'; - - function Block(nodes) { - this.expressions = compact(flatten(nodes || [])); - } - - Block.prototype.children = ['expressions']; - - Block.prototype.push = function(node) { - this.expressions.push(node); - return this; - }; - - Block.prototype.pop = function() { - return this.expressions.pop(); - }; - - Block.prototype.unshift = function(node) { - this.expressions.unshift(node); - return this; - }; - - Block.prototype.unwrap = function() { - if (this.expressions.length === 1) { - return this.expressions[0]; - } else { - return this; - } - }; - - Block.prototype.isEmpty = function() { - return !this.expressions.length; - }; - - Block.prototype.isStatement = function(o) { - var exp, _i, _len, _ref2; - _ref2 = this.expressions; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - exp = _ref2[_i]; - if (exp.isStatement(o)) return true; - } - return false; - }; - - Block.prototype.jumps = function(o) { - var exp, _i, _len, _ref2; - _ref2 = this.expressions; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - exp = _ref2[_i]; - if (exp.jumps(o)) return exp; - } - }; - - Block.prototype.makeReturn = function(res) { - var expr, len; - len = this.expressions.length; - while (len--) { - expr = this.expressions[len]; - if (!(expr instanceof Comment)) { - this.expressions[len] = expr.makeReturn(res); - if (expr instanceof Return && !expr.expression) { - this.expressions.splice(len, 1); - } - break; - } - } - return this; - }; - - Block.prototype.compile = function(o, level) { - if (o == null) o = {}; - if (o.scope) { - return Block.__super__.compile.call(this, o, level); - } else { - return this.compileRoot(o); - } - }; - - Block.prototype.compileNode = function(o) { - var code, codes, node, top, _i, _len, _ref2; - this.tab = o.indent; - top = o.level === LEVEL_TOP; - codes = []; - _ref2 = this.expressions; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - node = _ref2[_i]; - node = node.unwrapAll(); - node = node.unfoldSoak(o) || node; - if (node instanceof Block) { - codes.push(node.compileNode(o)); - } else if (top) { - node.front = true; - code = node.compile(o); - if (!node.isStatement(o)) { - code = "" + this.tab + code + ";"; - if (node instanceof Literal) code = "" + code + "\n"; - } - codes.push(code); - } else { - codes.push(node.compile(o, LEVEL_LIST)); - } - } - if (top) { - if (this.spaced) { - return "\n" + (codes.join('\n\n')) + "\n"; - } else { - return codes.join('\n'); - } - } - code = codes.join(', ') || 'void 0'; - if (codes.length > 1 && o.level >= LEVEL_LIST) { - return "(" + code + ")"; - } else { - return code; - } - }; - - Block.prototype.compileRoot = function(o) { - var code, exp, i, prelude, preludeExps, rest; - o.indent = o.bare ? '' : TAB; - o.scope = new Scope(null, this, null); - o.level = LEVEL_TOP; - this.spaced = true; - prelude = ""; - if (!o.bare) { - preludeExps = (function() { - var _i, _len, _ref2, _results; - _ref2 = this.expressions; - _results = []; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - exp = _ref2[i]; - if (!(exp.unwrap() instanceof Comment)) break; - _results.push(exp); - } - return _results; - }).call(this); - rest = this.expressions.slice(preludeExps.length); - this.expressions = preludeExps; - if (preludeExps.length) { - prelude = "" + (this.compileNode(merge(o, { - indent: '' - }))) + "\n"; - } - this.expressions = rest; - } - code = this.compileWithDeclarations(o); - if (o.bare) return code; - return "" + prelude + "(function() {\n" + code + "\n}).call(this);\n"; - }; - - Block.prototype.compileWithDeclarations = function(o) { - var assigns, code, declars, exp, i, post, rest, scope, spaced, _i, _len, _ref2, _ref3, _ref4; - code = post = ''; - _ref2 = this.expressions; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - exp = _ref2[i]; - exp = exp.unwrap(); - if (!(exp instanceof Comment || exp instanceof Literal)) break; - } - o = merge(o, { - level: LEVEL_TOP - }); - if (i) { - rest = this.expressions.splice(i, 9e9); - _ref3 = [this.spaced, false], spaced = _ref3[0], this.spaced = _ref3[1]; - _ref4 = [this.compileNode(o), spaced], code = _ref4[0], this.spaced = _ref4[1]; - this.expressions = rest; - } - post = this.compileNode(o); - scope = o.scope; - if (scope.expressions === this) { - declars = o.scope.hasDeclarations(); - assigns = scope.hasAssignments; - if (declars || assigns) { - if (i) code += '\n'; - code += "" + this.tab + "var "; - if (declars) code += scope.declaredVariables().join(', '); - if (assigns) { - if (declars) code += ",\n" + (this.tab + TAB); - code += scope.assignedVariables().join(",\n" + (this.tab + TAB)); - } - code += ';\n'; - } - } - return code + post; - }; - - Block.wrap = function(nodes) { - if (nodes.length === 1 && nodes[0] instanceof Block) return nodes[0]; - return new Block(nodes); - }; - - return Block; - - })(Base); - - exports.Literal = Literal = (function(_super) { - - __extends(Literal, _super); - - Literal.name = 'Literal'; - - function Literal(value) { - this.value = value; - } - - Literal.prototype.makeReturn = function() { - if (this.isStatement()) { - return this; - } else { - return Literal.__super__.makeReturn.apply(this, arguments); - } - }; - - Literal.prototype.isAssignable = function() { - return IDENTIFIER.test(this.value); - }; - - Literal.prototype.isStatement = function() { - var _ref2; - return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger'; - }; - - Literal.prototype.isComplex = NO; - - Literal.prototype.assigns = function(name) { - return name === this.value; - }; - - Literal.prototype.jumps = function(o) { - if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) { - return this; - } - if (this.value === 'continue' && !(o != null ? o.loop : void 0)) return this; - }; - - Literal.prototype.compileNode = function(o) { - var code, _ref2; - code = this.isUndefined ? o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0' : this.value === 'this' ? ((_ref2 = o.scope.method) != null ? _ref2.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value; - if (this.isStatement()) { - return "" + this.tab + code + ";"; - } else { - return code; - } - }; - - Literal.prototype.toString = function() { - return ' "' + this.value + '"'; - }; - - return Literal; - - })(Base); - - exports.Return = Return = (function(_super) { - - __extends(Return, _super); - - Return.name = 'Return'; - - function Return(expr) { - if (expr && !expr.unwrap().isUndefined) this.expression = expr; - } - - Return.prototype.children = ['expression']; - - Return.prototype.isStatement = YES; - - Return.prototype.makeReturn = THIS; - - Return.prototype.jumps = THIS; - - Return.prototype.compile = function(o, level) { - var expr, _ref2; - expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0; - if (expr && !(expr instanceof Return)) { - return expr.compile(o, level); - } else { - return Return.__super__.compile.call(this, o, level); - } - }; - - Return.prototype.compileNode = function(o) { - return this.tab + ("return" + [this.expression ? " " + (this.expression.compile(o, LEVEL_PAREN)) : void 0] + ";"); - }; - - return Return; - - })(Base); - - exports.Value = Value = (function(_super) { - - __extends(Value, _super); - - Value.name = 'Value'; - - function Value(base, props, tag) { - if (!props && base instanceof Value) return base; - this.base = base; - this.properties = props || []; - if (tag) this[tag] = true; - return this; - } - - Value.prototype.children = ['base', 'properties']; - - Value.prototype.add = function(props) { - this.properties = this.properties.concat(props); - return this; - }; - - Value.prototype.hasProperties = function() { - return !!this.properties.length; - }; - - Value.prototype.isArray = function() { - return !this.properties.length && this.base instanceof Arr; - }; - - Value.prototype.isComplex = function() { - return this.hasProperties() || this.base.isComplex(); - }; - - Value.prototype.isAssignable = function() { - return this.hasProperties() || this.base.isAssignable(); - }; - - Value.prototype.isSimpleNumber = function() { - return this.base instanceof Literal && SIMPLENUM.test(this.base.value); - }; - - Value.prototype.isString = function() { - return this.base instanceof Literal && IS_STRING.test(this.base.value); - }; - - Value.prototype.isAtomic = function() { - var node, _i, _len, _ref2; - _ref2 = this.properties.concat(this.base); - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - node = _ref2[_i]; - if (node.soak || node instanceof Call) return false; - } - return true; - }; - - Value.prototype.isStatement = function(o) { - return !this.properties.length && this.base.isStatement(o); - }; - - Value.prototype.assigns = function(name) { - return !this.properties.length && this.base.assigns(name); - }; - - Value.prototype.jumps = function(o) { - return !this.properties.length && this.base.jumps(o); - }; - - Value.prototype.isObject = function(onlyGenerated) { - if (this.properties.length) return false; - return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated); - }; - - Value.prototype.isSplice = function() { - return last(this.properties) instanceof Slice; - }; - - Value.prototype.unwrap = function() { - if (this.properties.length) { - return this; - } else { - return this.base; - } - }; - - Value.prototype.cacheReference = function(o) { - var base, bref, name, nref; - name = last(this.properties); - if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) { - return [this, this]; - } - base = new Value(this.base, this.properties.slice(0, -1)); - if (base.isComplex()) { - bref = new Literal(o.scope.freeVariable('base')); - base = new Value(new Parens(new Assign(bref, base))); - } - if (!name) return [base, bref]; - if (name.isComplex()) { - nref = new Literal(o.scope.freeVariable('name')); - name = new Index(new Assign(nref, name.index)); - nref = new Index(nref); - } - return [base.add(name), new Value(bref || base.base, [nref || name])]; - }; - - Value.prototype.compileNode = function(o) { - var code, prop, props, _i, _len; - this.base.front = this.front; - props = this.properties; - code = this.base.compile(o, props.length ? LEVEL_ACCESS : null); - if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) { - code = "" + code + "."; - } - for (_i = 0, _len = props.length; _i < _len; _i++) { - prop = props[_i]; - code += prop.compile(o); - } - return code; - }; - - Value.prototype.unfoldSoak = function(o) { - var result, - _this = this; - if (this.unfoldedSoak != null) return this.unfoldedSoak; - result = (function() { - var fst, i, ifn, prop, ref, snd, _i, _len, _ref2; - if (ifn = _this.base.unfoldSoak(o)) { - Array.prototype.push.apply(ifn.body.properties, _this.properties); - return ifn; - } - _ref2 = _this.properties; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - prop = _ref2[i]; - if (!prop.soak) continue; - prop.soak = false; - fst = new Value(_this.base, _this.properties.slice(0, i)); - snd = new Value(_this.base, _this.properties.slice(i)); - if (fst.isComplex()) { - ref = new Literal(o.scope.freeVariable('ref')); - fst = new Parens(new Assign(ref, fst)); - snd.base = ref; - } - return new If(new Existence(fst), snd, { - soak: true - }); - } - return null; - })(); - return this.unfoldedSoak = result || false; - }; - - return Value; - - })(Base); - - exports.Comment = Comment = (function(_super) { - - __extends(Comment, _super); - - Comment.name = 'Comment'; - - function Comment(comment) { - this.comment = comment; - } - - Comment.prototype.isStatement = YES; - - Comment.prototype.makeReturn = THIS; - - Comment.prototype.compileNode = function(o, level) { - var code; - code = '/*' + multident(this.comment, this.tab) + ("\n" + this.tab + "*/\n"); - if ((level || o.level) === LEVEL_TOP) code = o.indent + code; - return code; - }; - - return Comment; - - })(Base); - - exports.Call = Call = (function(_super) { - - __extends(Call, _super); - - Call.name = 'Call'; - - function Call(variable, args, soak) { - this.args = args != null ? args : []; - this.soak = soak; - this.isNew = false; - this.isSuper = variable === 'super'; - this.variable = this.isSuper ? null : variable; - } - - Call.prototype.children = ['variable', 'args']; - - Call.prototype.newInstance = function() { - var base, _ref2; - base = ((_ref2 = this.variable) != null ? _ref2.base : void 0) || this.variable; - if (base instanceof Call && !base.isNew) { - base.newInstance(); - } else { - this.isNew = true; - } - return this; - }; - - Call.prototype.superReference = function(o) { - var accesses, method, name; - method = o.scope.method; - if (!method) throw SyntaxError('cannot call super outside of a function.'); - name = method.name; - if (name == null) { - throw SyntaxError('cannot call super on an anonymous function.'); - } - if (method.klass) { - accesses = [new Access(new Literal('__super__'))]; - if (method["static"]) { - accesses.push(new Access(new Literal('constructor'))); - } - accesses.push(new Access(new Literal(name))); - return (new Value(new Literal(method.klass), accesses)).compile(o); - } else { - return "" + name + ".__super__.constructor"; - } - }; - - Call.prototype.unfoldSoak = function(o) { - var call, ifn, left, list, rite, _i, _len, _ref2, _ref3; - if (this.soak) { - if (this.variable) { - if (ifn = unfoldSoak(o, this, 'variable')) return ifn; - _ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1]; - } else { - left = new Literal(this.superReference(o)); - rite = new Value(left); - } - rite = new Call(rite, this.args); - rite.isNew = this.isNew; - left = new Literal("typeof " + (left.compile(o)) + " === \"function\""); - return new If(left, new Value(rite), { - soak: true - }); - } - call = this; - list = []; - while (true) { - if (call.variable instanceof Call) { - list.push(call); - call = call.variable; - continue; - } - if (!(call.variable instanceof Value)) break; - list.push(call); - if (!((call = call.variable.base) instanceof Call)) break; - } - _ref3 = list.reverse(); - for (_i = 0, _len = _ref3.length; _i < _len; _i++) { - call = _ref3[_i]; - if (ifn) { - if (call.variable instanceof Call) { - call.variable = ifn; - } else { - call.variable.base = ifn; - } - } - ifn = unfoldSoak(o, call, 'variable'); - } - return ifn; - }; - - Call.prototype.filterImplicitObjects = function(list) { - var node, nodes, obj, prop, properties, _i, _j, _len, _len1, _ref2; - nodes = []; - for (_i = 0, _len = list.length; _i < _len; _i++) { - node = list[_i]; - if (!((typeof node.isObject === "function" ? node.isObject() : void 0) && node.base.generated)) { - nodes.push(node); - continue; - } - obj = null; - _ref2 = node.base.properties; - for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { - prop = _ref2[_j]; - if (prop instanceof Assign || prop instanceof Comment) { - if (!obj) nodes.push(obj = new Obj(properties = [], true)); - properties.push(prop); - } else { - nodes.push(prop); - obj = null; - } - } - } - return nodes; - }; - - Call.prototype.compileNode = function(o) { - var arg, args, code, _ref2; - if ((_ref2 = this.variable) != null) _ref2.front = this.front; - if (code = Splat.compileSplattedArray(o, this.args, true)) { - return this.compileSplat(o, code); - } - args = this.filterImplicitObjects(this.args); - args = ((function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = args.length; _i < _len; _i++) { - arg = args[_i]; - _results.push(arg.compile(o, LEVEL_LIST)); - } - return _results; - })()).join(', '); - if (this.isSuper) { - return this.superReference(o) + (".call(this" + (args && ', ' + args) + ")"); - } else { - return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")"); - } - }; - - Call.prototype.compileSuper = function(args, o) { - return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")"; - }; - - Call.prototype.compileSplat = function(o, splatArgs) { - var base, fun, idt, name, ref; - if (this.isSuper) { - return "" + (this.superReference(o)) + ".apply(this, " + splatArgs + ")"; - } - if (this.isNew) { - idt = this.tab + TAB; - return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args), t = typeof result;\n" + idt + "return t == \"object\" || t == \"function\" ? result || child : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function(){})"; - } - base = new Value(this.variable); - if ((name = base.properties.pop()) && base.isComplex()) { - ref = o.scope.freeVariable('ref'); - fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o)); - } else { - fun = base.compile(o, LEVEL_ACCESS); - if (SIMPLENUM.test(fun)) fun = "(" + fun + ")"; - if (name) { - ref = fun; - fun += name.compile(o); - } else { - ref = 'null'; - } - } - return "" + fun + ".apply(" + ref + ", " + splatArgs + ")"; - }; - - return Call; - - })(Base); - - exports.Extends = Extends = (function(_super) { - - __extends(Extends, _super); - - Extends.name = 'Extends'; - - function Extends(child, parent) { - this.child = child; - this.parent = parent; - } - - Extends.prototype.children = ['child', 'parent']; - - Extends.prototype.compile = function(o) { - return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o); - }; - - return Extends; - - })(Base); - - exports.Access = Access = (function(_super) { - - __extends(Access, _super); - - Access.name = 'Access'; - - function Access(name, tag) { - this.name = name; - this.name.asKey = true; - this.soak = tag === 'soak'; - } - - Access.prototype.children = ['name']; - - Access.prototype.compile = function(o) { - var name; - name = this.name.compile(o); - if (IDENTIFIER.test(name)) { - return "." + name; - } else { - return "[" + name + "]"; - } - }; - - Access.prototype.isComplex = NO; - - return Access; - - })(Base); - - exports.Index = Index = (function(_super) { - - __extends(Index, _super); - - Index.name = 'Index'; - - function Index(index) { - this.index = index; - } - - Index.prototype.children = ['index']; - - Index.prototype.compile = function(o) { - return "[" + (this.index.compile(o, LEVEL_PAREN)) + "]"; - }; - - Index.prototype.isComplex = function() { - return this.index.isComplex(); - }; - - return Index; - - })(Base); - - exports.Range = Range = (function(_super) { - - __extends(Range, _super); - - Range.name = 'Range'; - - Range.prototype.children = ['from', 'to']; - - function Range(from, to, tag) { - this.from = from; - this.to = to; - this.exclusive = tag === 'exclusive'; - this.equals = this.exclusive ? '' : '='; - } - - Range.prototype.compileVariables = function(o) { - var step, _ref2, _ref3, _ref4, _ref5; - o = merge(o, { - top: true - }); - _ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1]; - _ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1]; - if (step = del(o, 'step')) { - _ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1]; - } - _ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1]; - if (this.stepVar) return this.stepNum = this.stepVar.match(SIMPLENUM); - }; - - Range.prototype.compileNode = function(o) { - var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, stepPart, to, varPart, _ref2, _ref3; - if (!this.fromVar) this.compileVariables(o); - if (!o.index) return this.compileArray(o); - known = this.fromNum && this.toNum; - idx = del(o, 'index'); - idxName = del(o, 'name'); - namedIndex = idxName && idxName !== idx; - varPart = "" + idx + " = " + this.fromC; - if (this.toC !== this.toVar) varPart += ", " + this.toC; - if (this.step !== this.stepVar) varPart += ", " + this.step; - _ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1]; - condPart = this.stepNum ? +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar); - stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? "" + idx + "++" : "" + idx + "--" : namedIndex ? "" + cond + " ? ++" + idx + " : --" + idx : "" + cond + " ? " + idx + "++ : " + idx + "--"; - if (namedIndex) varPart = "" + idxName + " = " + varPart; - if (namedIndex) stepPart = "" + idxName + " = " + stepPart; - return "" + varPart + "; " + condPart + "; " + stepPart; - }; - - Range.prototype.compileArray = function(o) { - var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results; - if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) { - range = (function() { - _results = []; - for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); } - return _results; - }).apply(this); - if (this.exclusive) range.pop(); - return "[" + (range.join(', ')) + "]"; - } - idt = this.tab + TAB; - i = o.scope.freeVariable('i'); - result = o.scope.freeVariable('results'); - pre = "\n" + idt + result + " = [];"; - if (this.fromNum && this.toNum) { - o.index = i; - body = this.compileNode(o); - } else { - vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : ''); - cond = "" + this.fromVar + " <= " + this.toVar; - body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--"; - } - post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent; - hasArgs = function(node) { - return node != null ? node.contains(function(n) { - return n instanceof Literal && n.value === 'arguments' && !n.asKey; - }) : void 0; - }; - if (hasArgs(this.from) || hasArgs(this.to)) args = ', arguments'; - return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")"; - }; - - return Range; - - })(Base); - - exports.Slice = Slice = (function(_super) { - - __extends(Slice, _super); - - Slice.name = 'Slice'; - - Slice.prototype.children = ['range']; - - function Slice(range) { - this.range = range; - Slice.__super__.constructor.call(this); - } - - Slice.prototype.compileNode = function(o) { - var compiled, from, fromStr, to, toStr, _ref2; - _ref2 = this.range, to = _ref2.to, from = _ref2.from; - fromStr = from && from.compile(o, LEVEL_PAREN) || '0'; - compiled = to && to.compile(o, LEVEL_PAREN); - if (to && !(!this.range.exclusive && +compiled === -1)) { - toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? "" + (+compiled + 1) : (compiled = to.compile(o, LEVEL_ACCESS), "" + compiled + " + 1 || 9e9")); - } - return ".slice(" + fromStr + (toStr || '') + ")"; - }; - - return Slice; - - })(Base); - - exports.Obj = Obj = (function(_super) { - - __extends(Obj, _super); - - Obj.name = 'Obj'; - - function Obj(props, generated) { - this.generated = generated != null ? generated : false; - this.objects = this.properties = props || []; - } - - Obj.prototype.children = ['properties']; - - Obj.prototype.compileNode = function(o) { - var i, idt, indent, join, lastNoncom, node, obj, prop, propName, propNames, props, _i, _j, _len, _len1, _ref2; - props = this.properties; - propNames = []; - _ref2 = this.properties; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - prop = _ref2[_i]; - if (prop.isComplex()) prop = prop.variable; - if (prop != null) { - propName = prop.unwrapAll().value.toString(); - if (__indexOf.call(propNames, propName) >= 0) { - throw SyntaxError("multiple object literal properties named \"" + propName + "\""); - } - propNames.push(propName); - } - } - if (!props.length) return (this.front ? '({})' : '{}'); - if (this.generated) { - for (_j = 0, _len1 = props.length; _j < _len1; _j++) { - node = props[_j]; - if (node instanceof Value) { - throw new Error('cannot have an implicit value in an implicit object'); - } - } - } - idt = o.indent += TAB; - lastNoncom = this.lastNonComment(this.properties); - props = (function() { - var _k, _len2, _results; - _results = []; - for (i = _k = 0, _len2 = props.length; _k < _len2; i = ++_k) { - prop = props[i]; - join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n'; - indent = prop instanceof Comment ? '' : idt; - if (prop instanceof Value && prop["this"]) { - prop = new Assign(prop.properties[0].name, prop, 'object'); - } - if (!(prop instanceof Comment)) { - if (!(prop instanceof Assign)) prop = new Assign(prop, prop, 'object'); - (prop.variable.base || prop.variable).asKey = true; - } - _results.push(indent + prop.compile(o, LEVEL_TOP) + join); - } - return _results; - })(); - props = props.join(''); - obj = "{" + (props && '\n' + props + '\n' + this.tab) + "}"; - if (this.front) { - return "(" + obj + ")"; - } else { - return obj; - } - }; - - Obj.prototype.assigns = function(name) { - var prop, _i, _len, _ref2; - _ref2 = this.properties; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - prop = _ref2[_i]; - if (prop.assigns(name)) return true; - } - return false; - }; - - return Obj; - - })(Base); - - exports.Arr = Arr = (function(_super) { - - __extends(Arr, _super); - - Arr.name = 'Arr'; - - function Arr(objs) { - this.objects = objs || []; - } - - Arr.prototype.children = ['objects']; - - Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects; - - Arr.prototype.compileNode = function(o) { - var code, obj, objs; - if (!this.objects.length) return '[]'; - o.indent += TAB; - objs = this.filterImplicitObjects(this.objects); - if (code = Splat.compileSplattedArray(o, objs)) return code; - code = ((function() { - var _i, _len, _results; - _results = []; - for (_i = 0, _len = objs.length; _i < _len; _i++) { - obj = objs[_i]; - _results.push(obj.compile(o, LEVEL_LIST)); - } - return _results; - })()).join(', '); - if (code.indexOf('\n') >= 0) { - return "[\n" + o.indent + code + "\n" + this.tab + "]"; - } else { - return "[" + code + "]"; - } - }; - - Arr.prototype.assigns = function(name) { - var obj, _i, _len, _ref2; - _ref2 = this.objects; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - obj = _ref2[_i]; - if (obj.assigns(name)) return true; - } - return false; - }; - - return Arr; - - })(Base); - - exports.Class = Class = (function(_super) { - - __extends(Class, _super); - - Class.name = 'Class'; - - function Class(variable, parent, body) { - this.variable = variable; - this.parent = parent; - this.body = body != null ? body : new Block; - this.boundFuncs = []; - this.body.classBody = true; - } - - Class.prototype.children = ['variable', 'parent', 'body']; - - Class.prototype.determineName = function() { - var decl, tail; - if (!this.variable) return null; - decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value; - if (__indexOf.call(STRICT_PROSCRIBED, decl) >= 0) { - throw SyntaxError("variable name may not be " + decl); - } - return decl && (decl = IDENTIFIER.test(decl) && decl); - }; - - Class.prototype.setContext = function(name) { - return this.body.traverseChildren(false, function(node) { - if (node.classBody) return false; - if (node instanceof Literal && node.value === 'this') { - return node.value = name; - } else if (node instanceof Code) { - node.klass = name; - if (node.bound) return node.context = name; - } - }); - }; - - Class.prototype.addBoundFunctions = function(o) { - var bvar, lhs, _i, _len, _ref2, _results; - if (this.boundFuncs.length) { - _ref2 = this.boundFuncs; - _results = []; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - bvar = _ref2[_i]; - lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o); - _results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)"))); - } - return _results; - } - }; - - Class.prototype.addProperties = function(node, name, o) { - var assign, base, exprs, func, props; - props = node.base.properties.slice(0); - exprs = (function() { - var _results; - _results = []; - while (assign = props.shift()) { - if (assign instanceof Assign) { - base = assign.variable.base; - delete assign.context; - func = assign.value; - if (base.value === 'constructor') { - if (this.ctor) { - throw new Error('cannot define more than one constructor in a class'); - } - if (func.bound) { - throw new Error('cannot define a constructor as a bound function'); - } - if (func instanceof Code) { - assign = this.ctor = func; - } else { - this.externalCtor = o.scope.freeVariable('class'); - assign = new Assign(new Literal(this.externalCtor), func); - } - } else { - if (assign.variable["this"]) { - func["static"] = true; - if (func.bound) func.context = name; - } else { - assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), new Access(base)]); - if (func instanceof Code && func.bound) { - this.boundFuncs.push(base); - func.bound = false; - } - } - } - } - _results.push(assign); - } - return _results; - }).call(this); - return compact(exprs); - }; - - Class.prototype.walkBody = function(name, o) { - var _this = this; - return this.traverseChildren(false, function(child) { - var exps, i, node, _i, _len, _ref2; - if (child instanceof Class) return false; - if (child instanceof Block) { - _ref2 = exps = child.expressions; - for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) { - node = _ref2[i]; - if (node instanceof Value && node.isObject(true)) { - exps[i] = _this.addProperties(node, name, o); - } - } - return child.expressions = exps = flatten(exps); - } - }); - }; - - Class.prototype.hoistDirectivePrologue = function() { - var expressions, index, node; - index = 0; - expressions = this.body.expressions; - while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) { - ++index; - } - return this.directives = expressions.splice(0, index); - }; - - Class.prototype.ensureConstructor = function(name) { - if (!this.ctor) { - this.ctor = new Code; - if (this.parent) { - this.ctor.body.push(new Literal("" + name + ".__super__.constructor.apply(this, arguments)")); - } - if (this.externalCtor) { - this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)")); - } - this.ctor.body.makeReturn(); - this.body.expressions.unshift(this.ctor); - } - this.ctor.ctor = this.ctor.name = name; - this.ctor.klass = null; - return this.ctor.noReturn = true; - }; - - Class.prototype.compileNode = function(o) { - var call, decl, klass, lname, name, params, _ref2; - decl = this.determineName(); - name = decl || '_Class'; - if (name.reserved) name = "_" + name; - lname = new Literal(name); - this.hoistDirectivePrologue(); - this.setContext(name); - this.walkBody(name, o); - this.ensureConstructor(name); - this.body.spaced = true; - if (!(this.ctor instanceof Code)) this.body.expressions.unshift(this.ctor); - if (decl) { - this.body.expressions.unshift(new Assign(new Value(new Literal(name), [new Access(new Literal('name'))]), new Literal("'" + name + "'"))); - } - this.body.expressions.push(lname); - (_ref2 = this.body.expressions).unshift.apply(_ref2, this.directives); - this.addBoundFunctions(o); - call = Closure.wrap(this.body); - if (this.parent) { - this.superClass = new Literal(o.scope.freeVariable('super', false)); - this.body.expressions.unshift(new Extends(lname, this.superClass)); - call.args.push(this.parent); - params = call.variable.params || call.variable.base.params; - params.push(new Param(this.superClass)); - } - klass = new Parens(call, true); - if (this.variable) klass = new Assign(this.variable, klass); - return klass.compile(o); - }; - - return Class; - - })(Base); - - exports.Assign = Assign = (function(_super) { - - __extends(Assign, _super); - - Assign.name = 'Assign'; - - function Assign(variable, value, context, options) { - var forbidden, name, _ref2; - this.variable = variable; - this.value = value; - this.context = context; - this.param = options && options.param; - this.subpattern = options && options.subpattern; - forbidden = (_ref2 = (name = this.variable.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0); - if (forbidden && this.context !== 'object') { - throw SyntaxError("variable name may not be \"" + name + "\""); - } - } - - Assign.prototype.children = ['variable', 'value']; - - Assign.prototype.isStatement = function(o) { - return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0; - }; - - Assign.prototype.assigns = function(name) { - return this[this.context === 'object' ? 'value' : 'variable'].assigns(name); - }; - - Assign.prototype.unfoldSoak = function(o) { - return unfoldSoak(o, this, 'variable'); - }; - - Assign.prototype.compileNode = function(o) { - var isValue, match, name, val, varBase, _ref2, _ref3, _ref4, _ref5; - if (isValue = this.variable instanceof Value) { - if (this.variable.isArray() || this.variable.isObject()) { - return this.compilePatternMatch(o); - } - if (this.variable.isSplice()) return this.compileSplice(o); - if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') { - return this.compileConditional(o); - } - } - name = this.variable.compile(o, LEVEL_LIST); - if (!this.context) { - if (!(varBase = this.variable.unwrapAll()).isAssignable()) { - throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned."); - } - if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) { - if (this.param) { - o.scope.add(name, 'var'); - } else { - o.scope.find(name); - } - } - } - if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) { - if (match[1]) this.value.klass = match[1]; - this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5]; - } - val = this.value.compile(o, LEVEL_LIST); - if (this.context === 'object') return "" + name + ": " + val; - val = name + (" " + (this.context || '=') + " ") + val; - if (o.level <= LEVEL_LIST) { - return val; - } else { - return "(" + val + ")"; - } - }; - - Assign.prototype.compilePatternMatch = function(o) { - var acc, assigns, code, i, idx, isObject, ivar, name, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; - top = o.level === LEVEL_TOP; - value = this.value; - objects = this.variable.base.objects; - if (!(olen = objects.length)) { - code = value.compile(o); - if (o.level >= LEVEL_OP) { - return "(" + code + ")"; - } else { - return code; - } - } - isObject = this.variable.isObject(); - if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) { - if (obj instanceof Assign) { - _ref2 = obj, (_ref3 = _ref2.variable, idx = _ref3.base), obj = _ref2.value; - } else { - if (obj.base instanceof Parens) { - _ref4 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref4[0], idx = _ref4[1]; - } else { - idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0); - } - } - acc = IDENTIFIER.test(idx.unwrap().value || 0); - value = new Value(value); - value.properties.push(new (acc ? Access : Index)(idx)); - if (_ref5 = obj.unwrap().value, __indexOf.call(RESERVED, _ref5) >= 0) { - throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (value.compile(o))); - } - return new Assign(obj, value, null, { - param: this.param - }).compile(o, LEVEL_TOP); - } - vvar = value.compile(o, LEVEL_LIST); - assigns = []; - splat = false; - if (!IDENTIFIER.test(vvar) || this.variable.assigns(vvar)) { - assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar); - vvar = ref; - } - for (i = _i = 0, _len = objects.length; _i < _len; i = ++_i) { - obj = objects[i]; - idx = i; - if (isObject) { - if (obj instanceof Assign) { - _ref6 = obj, (_ref7 = _ref6.variable, idx = _ref7.base), obj = _ref6.value; - } else { - if (obj.base instanceof Parens) { - _ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref8[0], idx = _ref8[1]; - } else { - idx = obj["this"] ? obj.properties[0].name : obj; - } - } - } - if (!splat && obj instanceof Splat) { - name = obj.name.unwrap().value; - obj = obj.unwrap(); - val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i; - if (rest = olen - i - 1) { - ivar = o.scope.freeVariable('i'); - val += ", " + ivar + " = " + vvar + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])"; - } else { - val += ") : []"; - } - val = new Literal(val); - splat = "" + ivar + "++"; - } else { - name = obj.unwrap().value; - if (obj instanceof Splat) { - obj = obj.name.compile(o); - throw new SyntaxError("multiple splats are disallowed in an assignment: " + obj + "..."); - } - if (typeof idx === 'number') { - idx = new Literal(splat || idx); - acc = false; - } else { - acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0); - } - val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]); - } - if ((name != null) && __indexOf.call(RESERVED, name) >= 0) { - throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (val.compile(o))); - } - assigns.push(new Assign(obj, val, null, { - param: this.param, - subpattern: true - }).compile(o, LEVEL_LIST)); - } - if (!(top || this.subpattern)) assigns.push(vvar); - code = assigns.join(', '); - if (o.level < LEVEL_LIST) { - return code; - } else { - return "(" + code + ")"; - } - }; - - Assign.prototype.compileConditional = function(o) { - var left, right, _ref2; - _ref2 = this.variable.cacheReference(o), left = _ref2[0], right = _ref2[1]; - if (left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) { - throw new Error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been defined."); - } - if (__indexOf.call(this.context, "?") >= 0) o.isExistentialEquals = true; - return new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compile(o); - }; - - Assign.prototype.compileSplice = function(o) { - var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4; - _ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive; - name = this.variable.compile(o); - _ref3 = (from != null ? from.cache(o, LEVEL_OP) : void 0) || ['0', '0'], fromDecl = _ref3[0], fromRef = _ref3[1]; - if (to) { - if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) { - to = +to.compile(o) - +fromRef; - if (!exclusive) to += 1; - } else { - to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef; - if (!exclusive) to += ' + 1'; - } - } else { - to = "9e9"; - } - _ref4 = this.value.cache(o, LEVEL_LIST), valDef = _ref4[0], valRef = _ref4[1]; - code = "[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat(" + valDef + ")), " + valRef; - if (o.level > LEVEL_TOP) { - return "(" + code + ")"; - } else { - return code; - } - }; - - return Assign; - - })(Base); - - exports.Code = Code = (function(_super) { - - __extends(Code, _super); - - Code.name = 'Code'; - - function Code(params, body, tag) { - this.params = params || []; - this.body = body || new Block; - this.bound = tag === 'boundfunc'; - if (this.bound) this.context = '_this'; - } - - Code.prototype.children = ['params', 'body']; - - Code.prototype.isStatement = function() { - return !!this.ctor; - }; - - Code.prototype.jumps = NO; - - Code.prototype.compileNode = function(o) { - var code, exprs, i, idt, lit, name, p, param, params, ref, splats, uniqs, val, wasEmpty, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8; - o.scope = new Scope(o.scope, this.body, this); - o.scope.shared = del(o, 'sharedScope'); - o.indent += TAB; - delete o.bare; - delete o.isExistentialEquals; - params = []; - exprs = []; - _ref2 = this.paramNames(); - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - name = _ref2[_i]; - if (!o.scope.check(name)) o.scope.parameter(name); - } - _ref3 = this.params; - for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { - param = _ref3[_j]; - if (!param.splat) continue; - _ref4 = this.params; - for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) { - p = _ref4[_k]; - if (p.name.value) o.scope.add(p.name.value, 'var', true); - } - splats = new Assign(new Value(new Arr((function() { - var _l, _len3, _ref5, _results; - _ref5 = this.params; - _results = []; - for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { - p = _ref5[_l]; - _results.push(p.asReference(o)); - } - return _results; - }).call(this))), new Value(new Literal('arguments'))); - break; - } - _ref5 = this.params; - for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { - param = _ref5[_l]; - if (param.isComplex()) { - val = ref = param.asReference(o); - if (param.value) val = new Op('?', ref, param.value); - exprs.push(new Assign(new Value(param.name), val, '=', { - param: true - })); - } else { - ref = param; - if (param.value) { - lit = new Literal(ref.name.value + ' == null'); - val = new Assign(new Value(param.name), param.value, '='); - exprs.push(new If(lit, val)); - } - } - if (!splats) params.push(ref); - } - wasEmpty = this.body.isEmpty(); - if (splats) exprs.unshift(splats); - if (exprs.length) { - (_ref6 = this.body.expressions).unshift.apply(_ref6, exprs); - } - for (i = _m = 0, _len4 = params.length; _m < _len4; i = ++_m) { - p = params[i]; - o.scope.parameter(params[i] = p.compile(o)); - } - uniqs = []; - _ref7 = this.paramNames(); - for (_n = 0, _len5 = _ref7.length; _n < _len5; _n++) { - name = _ref7[_n]; - if (__indexOf.call(uniqs, name) >= 0) { - throw SyntaxError("multiple parameters named '" + name + "'"); - } - uniqs.push(name); - } - if (!(wasEmpty || this.noReturn)) this.body.makeReturn(); - if (this.bound) { - if ((_ref8 = o.scope.parent.method) != null ? _ref8.bound : void 0) { - this.bound = this.context = o.scope.parent.method.context; - } else if (!this["static"]) { - o.scope.parent.assign('_this', 'this'); - } - } - idt = o.indent; - code = 'function'; - if (this.ctor) code += ' ' + this.name; - code += '(' + params.join(', ') + ') {'; - if (!this.body.isEmpty()) { - code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab; - } - code += '}'; - if (this.ctor) return this.tab + code; - if (this.front || (o.level >= LEVEL_ACCESS)) { - return "(" + code + ")"; - } else { - return code; - } - }; - - Code.prototype.paramNames = function() { - var names, param, _i, _len, _ref2; - names = []; - _ref2 = this.params; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - param = _ref2[_i]; - names.push.apply(names, param.names()); - } - return names; - }; - - Code.prototype.traverseChildren = function(crossScope, func) { - if (crossScope) { - return Code.__super__.traverseChildren.call(this, crossScope, func); - } - }; - - return Code; - - })(Base); - - exports.Param = Param = (function(_super) { - - __extends(Param, _super); - - Param.name = 'Param'; - - function Param(name, value, splat) { - var _ref2; - this.name = name; - this.value = value; - this.splat = splat; - if (_ref2 = (name = this.name.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { - throw SyntaxError("parameter name \"" + name + "\" is not allowed"); - } - } - - Param.prototype.children = ['name', 'value']; - - Param.prototype.compile = function(o) { - return this.name.compile(o, LEVEL_LIST); - }; - - Param.prototype.asReference = function(o) { - var node; - if (this.reference) return this.reference; - node = this.name; - if (node["this"]) { - node = node.properties[0].name; - if (node.value.reserved) { - node = new Literal(o.scope.freeVariable(node.value)); - } - } else if (node.isComplex()) { - node = new Literal(o.scope.freeVariable('arg')); - } - node = new Value(node); - if (this.splat) node = new Splat(node); - return this.reference = node; - }; - - Param.prototype.isComplex = function() { - return this.name.isComplex(); - }; - - Param.prototype.names = function(name) { - var atParam, names, obj, _i, _len, _ref2; - if (name == null) name = this.name; - atParam = function(obj) { - var value; - value = obj.properties[0].name.value; - if (value.reserved) { - return []; - } else { - return [value]; - } - }; - if (name instanceof Literal) return [name.value]; - if (name instanceof Value) return atParam(name); - names = []; - _ref2 = name.objects; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - obj = _ref2[_i]; - if (obj instanceof Assign) { - names.push(obj.variable.base.value); - } else if (obj.isArray() || obj.isObject()) { - names.push.apply(names, this.names(obj.base)); - } else if (obj["this"]) { - names.push.apply(names, atParam(obj)); - } else { - names.push(obj.base.value); - } - } - return names; - }; - - return Param; - - })(Base); - - exports.Splat = Splat = (function(_super) { - - __extends(Splat, _super); - - Splat.name = 'Splat'; - - Splat.prototype.children = ['name']; - - Splat.prototype.isAssignable = YES; - - function Splat(name) { - this.name = name.compile ? name : new Literal(name); - } - - Splat.prototype.assigns = function(name) { - return this.name.assigns(name); - }; - - Splat.prototype.compile = function(o) { - if (this.index != null) { - return this.compileParam(o); - } else { - return this.name.compile(o); - } - }; - - Splat.prototype.unwrap = function() { - return this.name; - }; - - Splat.compileSplattedArray = function(o, list, apply) { - var args, base, code, i, index, node, _i, _len; - index = -1; - while ((node = list[++index]) && !(node instanceof Splat)) { - continue; - } - if (index >= list.length) return ''; - if (list.length === 1) { - code = list[0].compile(o, LEVEL_LIST); - if (apply) return code; - return "" + (utility('slice')) + ".call(" + code + ")"; - } - args = list.slice(index); - for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) { - node = args[i]; - code = node.compile(o, LEVEL_LIST); - args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]"; - } - if (index === 0) { - return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")"); - } - base = (function() { - var _j, _len1, _ref2, _results; - _ref2 = list.slice(0, index); - _results = []; - for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { - node = _ref2[_j]; - _results.push(node.compile(o, LEVEL_LIST)); - } - return _results; - })(); - return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")"; - }; - - return Splat; - - })(Base); - - exports.While = While = (function(_super) { - - __extends(While, _super); - - While.name = 'While'; - - function While(condition, options) { - this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition; - this.guard = options != null ? options.guard : void 0; - } - - While.prototype.children = ['condition', 'guard', 'body']; - - While.prototype.isStatement = YES; - - While.prototype.makeReturn = function(res) { - if (res) { - return While.__super__.makeReturn.apply(this, arguments); - } else { - this.returns = !this.jumps({ - loop: true - }); - return this; - } - }; - - While.prototype.addBody = function(body) { - this.body = body; - return this; - }; - - While.prototype.jumps = function() { - var expressions, node, _i, _len; - expressions = this.body.expressions; - if (!expressions.length) return false; - for (_i = 0, _len = expressions.length; _i < _len; _i++) { - node = expressions[_i]; - if (node.jumps({ - loop: true - })) return node; - } - return false; - }; - - While.prototype.compileNode = function(o) { - var body, code, rvar, set; - o.indent += TAB; - set = ''; - body = this.body; - if (body.isEmpty()) { - body = ''; - } else { - if (this.returns) { - body.makeReturn(rvar = o.scope.freeVariable('results')); - set = "" + this.tab + rvar + " = [];\n"; - } - if (this.guard) { - if (body.expressions.length > 1) { - body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); - } else { - if (this.guard) body = Block.wrap([new If(this.guard, body)]); - } - } - body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab; - } - code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}"); - if (this.returns) code += "\n" + this.tab + "return " + rvar + ";"; - return code; - }; - - return While; - - })(Base); - - exports.Op = Op = (function(_super) { - var CONVERSIONS, INVERSIONS; - - __extends(Op, _super); - - Op.name = 'Op'; - - function Op(op, first, second, flip) { - if (op === 'in') return new In(first, second); - if (op === 'do') return this.generateDo(first); - if (op === 'new') { - if (first instanceof Call && !first["do"] && !first.isNew) { - return first.newInstance(); - } - if (first instanceof Code && first.bound || first["do"]) { - first = new Parens(first); - } - } - this.operator = CONVERSIONS[op] || op; - this.first = first; - this.second = second; - this.flip = !!flip; - return this; - } - - CONVERSIONS = { - '==': '===', - '!=': '!==', - 'of': 'in' - }; - - INVERSIONS = { - '!==': '===', - '===': '!==' - }; - - Op.prototype.children = ['first', 'second']; - - Op.prototype.isSimpleNumber = NO; - - Op.prototype.isUnary = function() { - return !this.second; - }; - - Op.prototype.isComplex = function() { - var _ref2; - return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex(); - }; - - Op.prototype.isChainable = function() { - var _ref2; - return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!=='; - }; - - Op.prototype.invert = function() { - var allInvertable, curr, fst, op, _ref2; - if (this.isChainable() && this.first.isChainable()) { - allInvertable = true; - curr = this; - while (curr && curr.operator) { - allInvertable && (allInvertable = curr.operator in INVERSIONS); - curr = curr.first; - } - if (!allInvertable) return new Parens(this).invert(); - curr = this; - while (curr && curr.operator) { - curr.invert = !curr.invert; - curr.operator = INVERSIONS[curr.operator]; - curr = curr.first; - } - return this; - } else if (op = INVERSIONS[this.operator]) { - this.operator = op; - if (this.first.unwrap() instanceof Op) this.first.invert(); - return this; - } else if (this.second) { - return new Parens(this).invert(); - } else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((_ref2 = fst.operator) === '!' || _ref2 === 'in' || _ref2 === 'instanceof')) { - return fst; - } else { - return new Op('!', this); - } - }; - - Op.prototype.unfoldSoak = function(o) { - var _ref2; - return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first'); - }; - - Op.prototype.generateDo = function(exp) { - var call, func, param, passedParams, ref, _i, _len, _ref2; - passedParams = []; - func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp; - _ref2 = func.params || []; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - param = _ref2[_i]; - if (param.value) { - passedParams.push(param.value); - delete param.value; - } else { - passedParams.push(param); - } - } - call = new Call(exp, passedParams); - call["do"] = true; - return call; - }; - - Op.prototype.compileNode = function(o) { - var code, isChain, _ref2, _ref3; - isChain = this.isChainable() && this.first.isChainable(); - if (!isChain) this.first.front = this.front; - if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) { - throw SyntaxError('delete operand may not be argument or var'); - } - if (((_ref2 = this.operator) === '--' || _ref2 === '++') && (_ref3 = this.first.unwrapAll().value, __indexOf.call(STRICT_PROSCRIBED, _ref3) >= 0)) { - throw SyntaxError('prefix increment/decrement may not have eval or arguments operand'); - } - if (this.isUnary()) return this.compileUnary(o); - if (isChain) return this.compileChain(o); - if (this.operator === '?') return this.compileExistence(o); - code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP); - if (o.level <= LEVEL_OP) { - return code; - } else { - return "(" + code + ")"; - } - }; - - Op.prototype.compileChain = function(o) { - var code, fst, shared, _ref2; - _ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1]; - fst = this.first.compile(o, LEVEL_OP); - code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP)); - return "(" + code + ")"; - }; - - Op.prototype.compileExistence = function(o) { - var fst, ref; - if (this.first.isComplex() && o.level > LEVEL_TOP) { - ref = new Literal(o.scope.freeVariable('ref')); - fst = new Parens(new Assign(ref, this.first)); - } else { - fst = this.first; - ref = fst; - } - return new If(new Existence(fst), ref, { - type: 'if' - }).addElse(this.second).compile(o); - }; - - Op.prototype.compileUnary = function(o) { - var op, parts, plusMinus; - if (o.level >= LEVEL_ACCESS) return (new Parens(this)).compile(o); - parts = [op = this.operator]; - plusMinus = op === '+' || op === '-'; - if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) { - parts.push(' '); - } - if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) { - this.first = new Parens(this.first); - } - parts.push(this.first.compile(o, LEVEL_OP)); - if (this.flip) parts.reverse(); - return parts.join(''); - }; - - Op.prototype.toString = function(idt) { - return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator); - }; - - return Op; - - })(Base); - - exports.In = In = (function(_super) { - - __extends(In, _super); - - In.name = 'In'; - - function In(object, array) { - this.object = object; - this.array = array; - } - - In.prototype.children = ['object', 'array']; - - In.prototype.invert = NEGATE; - - In.prototype.compileNode = function(o) { - var hasSplat, obj, _i, _len, _ref2; - if (this.array instanceof Value && this.array.isArray()) { - _ref2 = this.array.base.objects; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - obj = _ref2[_i]; - if (!(obj instanceof Splat)) continue; - hasSplat = true; - break; - } - if (!hasSplat) return this.compileOrTest(o); - } - return this.compileLoopTest(o); - }; - - In.prototype.compileOrTest = function(o) { - var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3; - if (this.array.base.objects.length === 0) return "" + (!!this.negated); - _ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1]; - _ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1]; - tests = (function() { - var _i, _len, _ref4, _results; - _ref4 = this.array.base.objects; - _results = []; - for (i = _i = 0, _len = _ref4.length; _i < _len; i = ++_i) { - item = _ref4[i]; - _results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_ACCESS)); - } - return _results; - }).call(this); - tests = tests.join(cnj); - if (o.level < LEVEL_OP) { - return tests; - } else { - return "(" + tests + ")"; - } - }; - - In.prototype.compileLoopTest = function(o) { - var code, ref, sub, _ref2; - _ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1]; - code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0'); - if (sub === ref) return code; - code = sub + ', ' + code; - if (o.level < LEVEL_LIST) { - return code; - } else { - return "(" + code + ")"; - } - }; - - In.prototype.toString = function(idt) { - return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : '')); - }; - - return In; - - })(Base); - - exports.Try = Try = (function(_super) { - - __extends(Try, _super); - - Try.name = 'Try'; - - function Try(attempt, error, recovery, ensure) { - this.attempt = attempt; - this.error = error; - this.recovery = recovery; - this.ensure = ensure; - } - - Try.prototype.children = ['attempt', 'recovery', 'ensure']; - - Try.prototype.isStatement = YES; - - Try.prototype.jumps = function(o) { - var _ref2; - return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0); - }; - - Try.prototype.makeReturn = function(res) { - if (this.attempt) this.attempt = this.attempt.makeReturn(res); - if (this.recovery) this.recovery = this.recovery.makeReturn(res); - return this; - }; - - Try.prototype.compileNode = function(o) { - var catchPart, ensurePart, errorPart, tryPart; - o.indent += TAB; - errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' '; - tryPart = this.attempt.compile(o, LEVEL_TOP); - catchPart = (function() { - var _ref2; - if (this.recovery) { - if (_ref2 = this.error.value, __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) { - throw SyntaxError("catch variable may not be \"" + this.error.value + "\""); - } - if (!o.scope.check(this.error.value)) { - o.scope.add(this.error.value, 'param'); - } - return " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"; - } else if (!(this.ensure || this.recovery)) { - return ' catch (_error) {}'; - } - }).call(this); - ensurePart = this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : ''; - return "" + this.tab + "try {\n" + tryPart + "\n" + this.tab + "}" + (catchPart || '') + ensurePart; - }; - - return Try; - - })(Base); - - exports.Throw = Throw = (function(_super) { - - __extends(Throw, _super); - - Throw.name = 'Throw'; - - function Throw(expression) { - this.expression = expression; - } - - Throw.prototype.children = ['expression']; - - Throw.prototype.isStatement = YES; - - Throw.prototype.jumps = NO; - - Throw.prototype.makeReturn = THIS; - - Throw.prototype.compileNode = function(o) { - return this.tab + ("throw " + (this.expression.compile(o)) + ";"); - }; - - return Throw; - - })(Base); - - exports.Existence = Existence = (function(_super) { - - __extends(Existence, _super); - - Existence.name = 'Existence'; - - function Existence(expression) { - this.expression = expression; - } - - Existence.prototype.children = ['expression']; - - Existence.prototype.invert = NEGATE; - - Existence.prototype.compileNode = function(o) { - var cmp, cnj, code, _ref2; - this.expression.front = this.front; - code = this.expression.compile(o, LEVEL_OP); - if (IDENTIFIER.test(code) && !o.scope.check(code)) { - _ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1]; - code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null"; - } else { - code = "" + code + " " + (this.negated ? '==' : '!=') + " null"; - } - if (o.level <= LEVEL_COND) { - return code; - } else { - return "(" + code + ")"; - } - }; - - return Existence; - - })(Base); - - exports.Parens = Parens = (function(_super) { - - __extends(Parens, _super); - - Parens.name = 'Parens'; - - function Parens(body) { - this.body = body; - } - - Parens.prototype.children = ['body']; - - Parens.prototype.unwrap = function() { - return this.body; - }; - - Parens.prototype.isComplex = function() { - return this.body.isComplex(); - }; - - Parens.prototype.compileNode = function(o) { - var bare, code, expr; - expr = this.body.unwrap(); - if (expr instanceof Value && expr.isAtomic()) { - expr.front = this.front; - return expr.compile(o); - } - code = expr.compile(o, LEVEL_PAREN); - bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns)); - if (bare) { - return code; - } else { - return "(" + code + ")"; - } - }; - - return Parens; - - })(Base); - - exports.For = For = (function(_super) { - - __extends(For, _super); - - For.name = 'For'; - - function For(body, source) { - var _ref2; - this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index; - this.body = Block.wrap([body]); - this.own = !!source.own; - this.object = !!source.object; - if (this.object) { - _ref2 = [this.index, this.name], this.name = _ref2[0], this.index = _ref2[1]; - } - if (this.index instanceof Value) { - throw SyntaxError('index cannot be a pattern matching expression'); - } - this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length; - this.pattern = this.name instanceof Value; - if (this.range && this.index) { - throw SyntaxError('indexes do not apply to range loops'); - } - if (this.range && this.pattern) { - throw SyntaxError('cannot pattern match over range loops'); - } - this.returns = false; - } - - For.prototype.children = ['body', 'source', 'guard', 'step']; - - For.prototype.compileNode = function(o) { - var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, kvar, kvarAssign, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2; - body = Block.wrap([this.body]); - lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0; - if (lastJumps && lastJumps instanceof Return) this.returns = false; - source = this.range ? this.source.base : this.source; - scope = o.scope; - name = this.name && this.name.compile(o, LEVEL_LIST); - index = this.index && this.index.compile(o, LEVEL_LIST); - if (name && !this.pattern) { - scope.find(name, { - immediate: true - }); - } - if (index) { - scope.find(index, { - immediate: true - }); - } - if (this.returns) rvar = scope.freeVariable('results'); - ivar = (this.object && index) || scope.freeVariable('i'); - kvar = (this.range && name) || index || ivar; - kvarAssign = kvar !== ivar ? "" + kvar + " = " : ""; - if (this.step && !this.range) stepvar = scope.freeVariable("step"); - if (this.pattern) name = ivar; - varPart = ''; - guardPart = ''; - defPart = ''; - idt1 = this.tab + TAB; - if (this.range) { - forPart = source.compile(merge(o, { - index: ivar, - name: name, - step: this.step - })); - } else { - svar = this.source.compile(o, LEVEL_LIST); - if ((name || this.own) && !IDENTIFIER.test(svar)) { - defPart = "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n"; - svar = ref; - } - if (name && !this.pattern) { - namePart = "" + name + " = " + svar + "[" + kvar + "]"; - } - if (!this.object) { - lvar = scope.freeVariable('len'); - forVarPart = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length"; - if (this.step) { - forVarPart += ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP)); - } - stepPart = "" + kvarAssign + (this.step ? "" + ivar + " += " + stepvar : (kvar !== ivar ? "++" + ivar : "" + ivar + "++")); - forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart; - } - } - if (this.returns) { - resultPart = "" + this.tab + rvar + " = [];\n"; - returnResult = "\n" + this.tab + "return " + rvar + ";"; - body.makeReturn(rvar); - } - if (this.guard) { - if (body.expressions.length > 1) { - body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue"))); - } else { - if (this.guard) body = Block.wrap([new If(this.guard, body)]); - } - } - if (this.pattern) { - body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + kvar + "]"))); - } - defPart += this.pluckDirectCall(o, body); - if (namePart) varPart = "\n" + idt1 + namePart + ";"; - if (this.object) { - forPart = "" + kvar + " in " + svar; - if (this.own) { - guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + kvar + ")) continue;"; - } - } - body = body.compile(merge(o, { - indent: idt1 - }), LEVEL_TOP); - if (body) body = '\n' + body + '\n'; - return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || ''); - }; - - For.prototype.pluckDirectCall = function(o, body) { - var base, defs, expr, fn, idx, ref, val, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7; - defs = ''; - _ref2 = body.expressions; - for (idx = _i = 0, _len = _ref2.length; _i < _len; idx = ++_i) { - expr = _ref2[idx]; - expr = expr.unwrapAll(); - if (!(expr instanceof Call)) continue; - val = expr.variable.unwrapAll(); - if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) { - continue; - } - fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val; - ref = new Literal(o.scope.freeVariable('fn')); - base = new Value(ref); - if (val.base) _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1]; - body.expressions[idx] = new Call(base, expr.args); - defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n'; - } - return defs; - }; - - return For; - - })(While); - - exports.Switch = Switch = (function(_super) { - - __extends(Switch, _super); - - Switch.name = 'Switch'; - - function Switch(subject, cases, otherwise) { - this.subject = subject; - this.cases = cases; - this.otherwise = otherwise; - } - - Switch.prototype.children = ['subject', 'cases', 'otherwise']; - - Switch.prototype.isStatement = YES; - - Switch.prototype.jumps = function(o) { - var block, conds, _i, _len, _ref2, _ref3, _ref4; - if (o == null) { - o = { - block: true - }; - } - _ref2 = this.cases; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - _ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1]; - if (block.jumps(o)) return block; - } - return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0; - }; - - Switch.prototype.makeReturn = function(res) { - var pair, _i, _len, _ref2, _ref3; - _ref2 = this.cases; - for (_i = 0, _len = _ref2.length; _i < _len; _i++) { - pair = _ref2[_i]; - pair[1].makeReturn(res); - } - if (res) { - this.otherwise || (this.otherwise = new Block([new Literal('void 0')])); - } - if ((_ref3 = this.otherwise) != null) _ref3.makeReturn(res); - return this; - }; - - Switch.prototype.compileNode = function(o) { - var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _j, _len, _len1, _ref2, _ref3, _ref4, _ref5; - idt1 = o.indent + TAB; - idt2 = o.indent = idt1 + TAB; - code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n"); - _ref3 = this.cases; - for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) { - _ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1]; - _ref5 = flatten([conditions]); - for (_j = 0, _len1 = _ref5.length; _j < _len1; _j++) { - cond = _ref5[_j]; - if (!this.subject) cond = cond.invert(); - code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n"); - } - if (body = block.compile(o, LEVEL_TOP)) code += body + '\n'; - if (i === this.cases.length - 1 && !this.otherwise) break; - expr = this.lastNonComment(block.expressions); - if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) { - continue; - } - code += idt2 + 'break;\n'; - } - if (this.otherwise && this.otherwise.expressions.length) { - code += idt1 + ("default:\n" + (this.otherwise.compile(o, LEVEL_TOP)) + "\n"); - } - return code + this.tab + '}'; - }; - - return Switch; - - })(Base); - - exports.If = If = (function(_super) { - - __extends(If, _super); - - If.name = 'If'; - - function If(condition, body, options) { - this.body = body; - if (options == null) options = {}; - this.condition = options.type === 'unless' ? condition.invert() : condition; - this.elseBody = null; - this.isChain = false; - this.soak = options.soak; - } - - If.prototype.children = ['condition', 'body', 'elseBody']; - - If.prototype.bodyNode = function() { - var _ref2; - return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0; - }; - - If.prototype.elseBodyNode = function() { - var _ref2; - return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0; - }; - - If.prototype.addElse = function(elseBody) { - if (this.isChain) { - this.elseBodyNode().addElse(elseBody); - } else { - this.isChain = elseBody instanceof If; - this.elseBody = this.ensureBlock(elseBody); - } - return this; - }; - - If.prototype.isStatement = function(o) { - var _ref2; - return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0); - }; - - If.prototype.jumps = function(o) { - var _ref2; - return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0); - }; - - If.prototype.compileNode = function(o) { - if (this.isStatement(o)) { - return this.compileStatement(o); - } else { - return this.compileExpression(o); - } - }; - - If.prototype.makeReturn = function(res) { - if (res) { - this.elseBody || (this.elseBody = new Block([new Literal('void 0')])); - } - this.body && (this.body = new Block([this.body.makeReturn(res)])); - this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)])); - return this; - }; - - If.prototype.ensureBlock = function(node) { - if (node instanceof Block) { - return node; - } else { - return new Block([node]); - } - }; - - If.prototype.compileStatement = function(o) { - var body, bodyc, child, cond, exeq, ifPart, _ref2; - child = del(o, 'chainChild'); - exeq = del(o, 'isExistentialEquals'); - if (exeq) { - return new If(this.condition.invert(), this.elseBodyNode(), { - type: 'if' - }).compile(o); - } - cond = this.condition.compile(o, LEVEL_PAREN); - o.indent += TAB; - body = this.ensureBlock(this.body); - bodyc = body.compile(o); - if (1 === ((_ref2 = body.expressions) != null ? _ref2.length : void 0) && !this.elseBody && !child && bodyc && cond && -1 === (bodyc.indexOf('\n')) && 80 > cond.length + bodyc.length) { - return "" + this.tab + "if (" + cond + ") " + (bodyc.replace(/^\s+/, '')); - } - if (bodyc) bodyc = "\n" + bodyc + "\n" + this.tab; - ifPart = "if (" + cond + ") {" + bodyc + "}"; - if (!child) ifPart = this.tab + ifPart; - if (!this.elseBody) return ifPart; - return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}"); - }; - - If.prototype.compileExpression = function(o) { - var alt, body, code, cond; - cond = this.condition.compile(o, LEVEL_COND); - body = this.bodyNode().compile(o, LEVEL_LIST); - alt = this.elseBodyNode() ? this.elseBodyNode().compile(o, LEVEL_LIST) : 'void 0'; - code = "" + cond + " ? " + body + " : " + alt; - if (o.level >= LEVEL_COND) { - return "(" + code + ")"; - } else { - return code; - } - }; - - If.prototype.unfoldSoak = function() { - return this.soak && this; - }; - - return If; - - })(Base); - - Closure = { - wrap: function(expressions, statement, noReturn) { - var args, call, func, mentionsArgs, meth; - if (expressions.jumps()) return expressions; - func = new Code([], Block.wrap([expressions])); - args = []; - if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) { - meth = new Literal(mentionsArgs ? 'apply' : 'call'); - args = [new Literal('this')]; - if (mentionsArgs) args.push(new Literal('arguments')); - func = new Value(func, [new Access(meth)]); - } - func.noReturn = noReturn; - call = new Call(func, args); - if (statement) { - return Block.wrap([call]); - } else { - return call; - } - }, - literalArgs: function(node) { - return node instanceof Literal && node.value === 'arguments' && !node.asKey; - }, - literalThis: function(node) { - return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound); - } - }; - - unfoldSoak = function(o, parent, name) { - var ifn; - if (!(ifn = parent[name].unfoldSoak(o))) return; - parent[name] = ifn.body; - ifn.body = new Value(parent); - return ifn; - }; - - UTILITIES = { - "extends": function() { - return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp')) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }"; - }, - bind: function() { - return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }'; - }, - indexOf: function() { - return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }"; - }, - hasProp: function() { - return '{}.hasOwnProperty'; - }, - slice: function() { - return '[].slice'; - } - }; - - LEVEL_TOP = 1; - - LEVEL_PAREN = 2; - - LEVEL_LIST = 3; - - LEVEL_COND = 4; - - LEVEL_OP = 5; - - LEVEL_ACCESS = 6; - - TAB = ' '; - - IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*"; - - IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$"); - - SIMPLENUM = /^[+-]?\d+$/; - - METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$"); - - IS_STRING = /^['"]/; - - utility = function(name) { - var ref; - ref = "__" + name; - Scope.root.assign(ref, UTILITIES[name]()); - return ref; - }; - - multident = function(code, tab) { - code = code.replace(/\n/g, '$&' + tab); - return code.replace(/\s+$/, ''); - }; - - -}); - -define('ace/mode/coffee/scope', ['require', 'exports', 'module' , 'ace/mode/coffee/helpers'], function(require, exports, module) { -// Generated by CoffeeScript 1.2.1-pre - - var Scope, extend, last, _ref; - - _ref = require('./helpers'), extend = _ref.extend, last = _ref.last; - - exports.Scope = Scope = (function() { - - Scope.name = 'Scope'; - - Scope.root = null; - - function Scope(parent, expressions, method) { - this.parent = parent; - this.expressions = expressions; - this.method = method; - this.variables = [ - { - name: 'arguments', - type: 'arguments' - } - ]; - this.positions = {}; - if (!this.parent) Scope.root = this; - } - - Scope.prototype.add = function(name, type, immediate) { - if (this.shared && !immediate) return this.parent.add(name, type, immediate); - if (Object.prototype.hasOwnProperty.call(this.positions, name)) { - return this.variables[this.positions[name]].type = type; - } else { - return this.positions[name] = this.variables.push({ - name: name, - type: type - }) - 1; - } - }; - - Scope.prototype.find = function(name, options) { - if (this.check(name, options)) return true; - this.add(name, 'var'); - return false; - }; - - Scope.prototype.parameter = function(name) { - if (this.shared && this.parent.check(name, true)) return; - return this.add(name, 'param'); - }; - - Scope.prototype.check = function(name, immediate) { - var found, _ref1; - found = !!this.type(name); - if (found || immediate) return found; - return !!((_ref1 = this.parent) != null ? _ref1.check(name) : void 0); - }; - - Scope.prototype.temporary = function(name, index) { - if (name.length > 1) { - return '_' + name + (index > 1 ? index - 1 : ''); - } else { - return '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a'); - } - }; - - Scope.prototype.type = function(name) { - var v, _i, _len, _ref1; - _ref1 = this.variables; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - v = _ref1[_i]; - if (v.name === name) return v.type; - } - return null; - }; - - Scope.prototype.freeVariable = function(name, reserve) { - var index, temp; - if (reserve == null) reserve = true; - index = 0; - while (this.check((temp = this.temporary(name, index)))) { - index++; - } - if (reserve) this.add(temp, 'var', true); - return temp; - }; - - Scope.prototype.assign = function(name, value) { - this.add(name, { - value: value, - assigned: true - }, true); - return this.hasAssignments = true; - }; - - Scope.prototype.hasDeclarations = function() { - return !!this.declaredVariables().length; - }; - - Scope.prototype.declaredVariables = function() { - var realVars, tempVars, v, _i, _len, _ref1; - realVars = []; - tempVars = []; - _ref1 = this.variables; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - v = _ref1[_i]; - if (v.type === 'var') { - (v.name.charAt(0) === '_' ? tempVars : realVars).push(v.name); - } - } - return realVars.sort().concat(tempVars.sort()); - }; - - Scope.prototype.assignedVariables = function() { - var v, _i, _len, _ref1, _results; - _ref1 = this.variables; - _results = []; - for (_i = 0, _len = _ref1.length; _i < _len; _i++) { - v = _ref1[_i]; - if (v.type.assigned) _results.push("" + v.name + " = " + v.type.value); - } - return _results; - }; - - return Scope; - - })(); - - -}); \ No newline at end of file diff --git a/lib/ace/worker-javascript.js b/lib/ace/worker-javascript.js index eae48aa5..9001244e 100644 --- a/lib/ace/worker-javascript.js +++ b/lib/ace/worker-javascript.js @@ -144,7 +144,7 @@ onmessage = function(e) { // -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified -// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License +// -- fschaefer Florian Sch�fer Copyright (C) 2010 MIT License // -- Irakli Gozalishvili Copyright (C) 2010 MIT License /*! @@ -266,7 +266,7 @@ define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, ex // -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License // -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project) // -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA -// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License +// -- fschaefer Florian Sch�fer Copyright (C) 2010 MIT License // -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License // -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License // -- kossnocorp Sasha Koss XXX TODO License or CLA @@ -9721,7 +9721,7 @@ var tokens = [ "^", "&", "==", "!=", "===", "!==", - "<", "<=", ">=", ">", + "<", "<=", ">=", ">", "=>", "<<", ">>", ">>>", "+", "-", "*", "/", "%", @@ -9745,8 +9745,8 @@ var tokens = [ "IDENTIFIER", "NUMBER", "STRING", "REGEXP", // Keywords. - "break", - "case", "catch", "const", "continue", + "async", "await", "break", + "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "export", "false", "finally", "for", "function", @@ -9775,8 +9775,8 @@ var strictKeywords = { }; var statementStartTokens = [ - "break", - "const", "continue", + "async", "await", "break", + "class", "const", "continue", "debugger", "do", "for", "if", diff --git a/lib/compiling/GScompiler.js b/lib/compiling/GScompiler.js index 5b6634ae..2452c9db 100644 --- a/lib/compiling/GScompiler.js +++ b/lib/compiling/GScompiler.js @@ -126,6 +126,14 @@ Also needed is a current copy of acorn (acorn.js), a parser of JavaScript used b window.call_acorn_parse = parse // Bruce Sherwood; makes acorn accessible to GlowScript compiler See ForInstalledPython/README.txt for how to obtain the plotly graphing library + +THE ACE EDITOR +Currently glowscript.org uses a very old version of the ACE editor, with old versions of +of mode-javascript.js, worker-javascript.js, and mode-python.js. It would be good to +update them. Note that at the start of the GlowScript project in 2011, "require" was +not common, and Bruce Sherwood changed require to ace_require in the ACE files. +See lib/ace/FileSource.txt. +Here are current ACE builds: https://github.com/ajaxorg/ace-builds/ */ /* @@ -229,7 +237,6 @@ where compile() was called, in untrusted/run.js. if (lang == 'rapydscript') throw new Error("GlowScript RapydScript is not available after GlowScript 2.9.Choose GlowScript VPython instead.") //if (lang == 'javascript') throw new Error("3.0dev does not yet work with JavaScript programs.") if (lang == 'vpython') classinstances.push('self') - //else classinstances.push('this') var c, lineno, lines, line, m, start var singlequote, doublequote, triplequote, backquote // backquote is ` used in JavaScript var parens = 0, brackets = 0, braces = 0 @@ -275,9 +282,7 @@ where compile() was called, in untrusted/run.js. if (line.slice(0,2) == '//') { lines[lineno] = '' continue - } - if (line.slice(0,2) == '//') continue - else if (line.slice(0,2) == '/*') { + } else if (line.slice(0,2) == '/*') { while (true) { if (lines[lineno].search('[*]/') >= 0) { lines[lineno] = '' @@ -628,8 +633,6 @@ where compile() was called, in untrusted/run.js. else if (classmethods.indexOf(f) >= 0) classmethods.push(p) else if (fcts.indexOf(f) >= 0) fcts.push(p) } - } else { // p = f not immediately followed by a left paren - ; } } @@ -743,7 +746,6 @@ where compile() was called, in untrusted/run.js. } } - // vp_primitives come in two flavors: "box" for JavaScript and "vp_box" for VPython var vp_primitives = ["box", "sphere", "simple_sphere", "cylinder", "pyramid", "cone", "helix", "ellipsoid", "ring", "arrow", "compound"] var vp_other = ["canvas", "vec", "vector", "rate", "sleep", "update", "color", "extrusion", "paths", "shapes", @@ -791,14 +793,13 @@ where compile() was called, in untrusted/run.js. //prog += " from __python__ import dict_literals, overload_getitem\n" // so that dictionaries behave like Python dictionaries prog += " window.__GSlang = 'vpython'\n" // WebGLRenderer needs to know at run time what models to create if ( VPython_import === null) { - for (var i = 0; i 0) { // e.g from vpython import box, cylinder vars += " vector=vec\n" for (var i=0; i= 0) vars += " "+name+"=vp_"+name+"\n" + if (n >= 0) vars += " "+name+"="+name+"\n" else vars += " "+name+"=undefined\n" } var hasvector = (VPython_names.indexOf('vector') >= 0) @@ -822,7 +823,7 @@ where compile() was called, in untrusted/run.js. vars += ' var '+VPython_import+'={' for (var i=0; i= 0) || // userclass() (period && classinstances.indexOf(prefix) < 0 && vpfcts.indexOf(name) >= 0) || // scene.pause(), scene.waitfor(), scene.capture() (period && prefix == VPython_import && fcts.indexOf(name) >= 0 && - fcts.indexOf(name) < 4) || // vp.rate/vp.sleep/vp.get_library/vp.read_local_file + fcts.indexOf(name) < 4) || // vp.rate/vp.sleep/vp.get_library/vp.read_local_file (period && no_await2.indexOf(name) < 0) || // scene.bind() - (!period && no_await.indexOf(name) < 0)) { // cos() + (!period && no_await.indexOf(name) < 0) || // cos() + (!period && no_await.indexOf(name) < 0 && no_await2.indexOf(name) < 0 && + fcts.indexOf(name) < 0)) { // probably a user function has been passed to a function ; } else { // no need to prepend await start += m.index+name.length+1 diff --git a/lib/glow/WebGLRenderer.js b/lib/glow/WebGLRenderer.js index fedb0659..d84fa8f6 100644 --- a/lib/glow/WebGLRenderer.js +++ b/lib/glow/WebGLRenderer.js @@ -233,24 +233,14 @@ } // Only create the models that will be used, because the renderer loops over models - if (window.__GSlang == 'vpython') { - object_models.vp_box = mbox - object_models.vp_pyramid = mpyramid - object_models.vp_cylinder = mcylinder - object_models.vp_cone = mcone - object_models.vp_sphere = msphere - object_models.vp_simple_sphere = msimple_sphere - object_models.vp_ellipsoid = msphere - object_models.vp_ring = mring - } else { - object_models.box = mbox - object_models.pyramid = mpyramid - object_models.cylinder = mcylinder - object_models.cone = mcone - object_models.sphere = msphere - object_models.simple_sphere = msimple_sphere - object_models.ring = mring - } + object_models.box = mbox + object_models.pyramid = mpyramid + object_models.cylinder = mcylinder + object_models.cone = mcone + object_models.sphere = msphere + object_models.simple_sphere = msimple_sphere + object_models.ellipsoid = msphere + object_models.ring = mring var models = this.models = {} for(var id in object_models) models[id] = object_models[id] @@ -493,8 +483,7 @@ a.arrow.pos = pos if (a.obj[a.attr] !== undefined) { if (!a.arrow.visible) a.arrow.visible = true - if (window.__GSlang == 'vpython') a.arrow.axis = a.obj[a.attr].multiply(a.scale) - else a.arrow.axis_and_length = a.obj[a.attr].multiply(a.scale) + a.arrow.axis = a.obj[a.attr].multiply(a.scale) } /* // TODO: The following needs revision after further discussion of the API: @@ -542,8 +531,7 @@ if (T.billboard) { var x = cross(cvs.__axis, cvs.__up) var y = cross(x, cvs.__axis) - if (window.__GSlang == 'vpython') T.axis = norm(x).multiply(mag(T.axis)) - else T.axis = x + T.axis = norm(x).multiply(mag(T.axis)) T.up = y } } diff --git a/lib/glow/api_misc.js b/lib/glow/api_misc.js index c7bfae5c..62fa7dbe 100644 --- a/lib/glow/api_misc.js +++ b/lib/glow/api_misc.js @@ -213,7 +213,7 @@ var arg = arguments[i] if (toType(arg) == "array") { arg = parsearray(arg) - } else if (window.__GSlang != 'javascript') { // vpython or rapydscript + } else if (window.__GSlang == 'vpython') { if (arg === null) arg = 'None' else if (toType(arg) == "boolean") arg = (arg) ? 'True' : 'False' else arg = convert(arg) @@ -348,7 +348,7 @@ for (var i=0; i 1e-6) { // change axis, which will also change up - if (isarrow) obj.axis_and_length = obj.axis_and_length.rotate({angle:angle, axis:rotaxis}) - else obj.axis = obj.__axis.rotate({angle:angle, axis:rotaxis}) // maintain special character of VPython axis + obj.axis = obj.__axis.rotate({angle:angle, axis:rotaxis}) // maintain special character of VPython axis } obj.up = obj.__up.rotate({angle:angle, axis:rotaxis}) window.__adjustupaxis = true @@ -624,7 +616,7 @@ var Y = this.__up.norm() var Z = X.cross(Y) var T = this.__pos - if (this instanceof ring || this instanceof vp_ring) { + if (this instanceof ring) { // Because a ring involves R1 and R2, we make a custom mesh and do our own scaling: var m = Mesh.makeRing_compound(this.__size) var matrix = [X.x, X.y, X.z, 0, Y.x, Y.y, Y.z, 0, Z.x, Z.y, Z.z, 0, T.x, T.y, T.z, 1] @@ -637,40 +629,12 @@ return this.__model.mesh.transformed(matrix); } } - }) - + }) + function box(args) { return initObject(this, box, args) } subclass(box, Primitive) box.prototype.__hasPosAtCenter = true - - function cylinder(args) { return initObject(this, cylinder, args) } - subclass(cylinder, Primitive) - - function cone(args) { return initObject(this, cone, args) } - subclass(cone, cylinder) - - function pyramid(args) { return initObject(this, pyramid, args) } - subclass(pyramid, box) - - function sphere(args) { return initObject(this, sphere, args) } - subclass(sphere, Primitive) - sphere.prototype.__hasPosAtCenter = true - - function simple_sphere(args) { return initObject(this, simple_sphere, args) } - subclass(simple_sphere, sphere) - property.declare( simple_sphere.prototype, { - radius: { - get: function() { return this.__size.__y/2 }, - set: function(value) { - this.size = vec(2*value,2*value,2*value) - this.__change() - } - } - }) - - function vp_box(args) { return initObject(this, vp_box, args) } - subclass(vp_box, box) - property.declare( vp_box.prototype, { + property.declare( box.prototype, { size: new attributeVectorSize(null, 1,1,1), length: { // Be careful not to alter the attributeVectorAxis character of this.axis @@ -731,12 +695,29 @@ } }) - function vp_pyramid(args) { return initObject(this, vp_pyramid, args) } - subclass(vp_pyramid, vp_box) + function pyramid(args) { return initObject(this, pyramid, args) } + subclass(pyramid, box) + + function cylinder(args) { return initObject(this, cylinder, args) } + subclass(cylinder, box) + property.declare( cylinder.prototype, { + size: new attributeVectorSize(null, 1,2,2), + radius: { + get: function() { return this.__size.__y/2 }, + set: function(value) { + this.__size.__y = this.__size.__z = 2*value + this.__change() + } + } + }) + + function cone(args) { return initObject(this, cone, args) } + subclass(cone, cylinder) - function vp_sphere(args) { return initObject(this, vp_sphere, args) } - subclass(vp_sphere, sphere) - property.declare( vp_sphere.prototype, { + function sphere(args) { return initObject(this, sphere, args) } + subclass(sphere, Primitive) + sphere.prototype.__hasPosAtCenter = true + property.declare( sphere.prototype, { axis: new attributeVectorAxis(null, 1,0,0), size: new attributeVector(null, 2,2,2), radius: { @@ -748,46 +729,28 @@ } }) - function vp_simple_sphere(args) { return initObject(this, vp_simple_sphere, args) } - subclass(vp_simple_sphere, simple_sphere) - property.declare( vp_simple_sphere.prototype, { + function simple_sphere(args) { return initObject(this, simple_sphere, args) } + subclass(simple_sphere, sphere) + property.declare( simple_sphere.prototype, { axis: new attributeVectorAxis(null, 1,0,0), size: new attributeVector(null, 2,2,2), }) - function vp_ellipsoid(args) { return initObject(this, vp_ellipsoid, args) } - subclass(vp_ellipsoid, vp_box) - property.declare( vp_ellipsoid.prototype, { + function ellipsoid(args) { return initObject(this, ellipsoid, args) } + subclass(ellipsoid, box) + property.declare( ellipsoid.prototype, { radius: { get: function() { throw new Error('An ellipsoid does not have a radius attribute.') }, set: function(value) { throw new Error('An ellipsoid does not have a radius attribute.') } } }) - function vp_cylinder(args) { return initObject(this, vp_cylinder, args) } - subclass(vp_cylinder, vp_box) - property.declare( vp_cylinder.prototype, { - size: new attributeVectorSize(null, 1,2,2), - radius: { - get: function() { return this.__size.__y/2 }, - set: function(value) { - this.__size.__y = this.__size.__z = 2*value - this.__change() - } - } - }) - - function vp_cone(args) { return initObject(this, vp_cone, args) } - subclass(vp_cone, vp_cylinder) - - function arrow_update(obj, vp) { // arrow or vp_arrow (in which case vp is true) + function arrow_update(obj) { var pos = obj.__pos - var color = obj.__color - var axis - if (vp) axis = obj.__axis - else axis = obj.__axis_and_length - var L = mag(axis) - var A = axis.norm() + var color = obj.__color + let axis = obj.__axis + var L = mag(axis) + var A = axis.norm() var sw = obj.__shaftwidth || L * .1 var hw = obj.__headwidth || sw * 2 var hl = obj.__headlength || sw * 3 @@ -807,10 +770,8 @@ var components = obj.__components if (!components) { - if (vp) components = obj.__components = [vp_box({ canvas:obj.canvas, __obj:obj }), - vp_pyramid({ canvas:obj.canvas, __obj:obj })] - else components = obj.__components = [box({ canvas:obj.canvas, __obj:obj }), - pyramid({ canvas:obj.canvas, __obj:obj })] + components = obj.__components = [box({ canvas:obj.canvas, __obj:obj }), + pyramid({ canvas:obj.canvas, __obj:obj })] } var shaft = components[0] var tip = components[1] @@ -818,10 +779,11 @@ shaft.pos = pos.add(A.multiply(.5 * (L - hl))) tip.pos = pos.add(A.multiply(L - hl)) // axis and up have already been adjusted if necessary for the arrow composite (virtual) object: - window.__adjustupaxis = false + //window.__adjustupaxis = false + console.log(axis, obj.__up) shaft.axis = tip.axis = axis shaft.up = tip.up = obj.__up - window.__adjustupaxis = true + //window.__adjustupaxis = true shaft.size = vec(L - hl, sw, sw) tip.size = vec(hl, hw, hw) shaft.color = tip.color = obj.color @@ -831,11 +793,11 @@ obj.size = vec(L, hw, hw) shaft.__update() - tip.__update() + tip.__update() } /* - * The handling of the arrow object is special. The arrow (or vp_arrow) + * The handling of the arrow object is special. The arrow * object itself does not get inserted into the to-be-rendered list. Rather, * only its components (box and pyramid) are handled in the usual way. The * box and pyramid objects have a special attribute, __obj, which points to @@ -857,7 +819,11 @@ } subclass(arrow, box) property.declare( arrow.prototype, { - __primitiveCount: 2, + __primitiveCount: 2, + axis_and_length: { + get: function() {throw new Error("As of GlowScript 3.0, arrow does not have an axis_and_length attribute.")}, + set: function(value) {throw new Error("As of GlowScript 3.0, arrow does not have an axis_and_length attribute.")} + }, shaftwidth: { get: function() { return this.__shaftwidth }, set: function(value) { @@ -879,47 +845,19 @@ this.__change() } }, - axis_and_length: new attributeVectorAxis(null, 1,0,0), - axis: { - get: function() { new Error("arrow has an axis_and_length attribute but no axis attribute") }, - set: function(value) { new Error("arrow has an axis_and_length attribute but no axis attribute") } - }, __change: function() { if (this.__components) { // make sure the components have been set up this.__components[0].__change() this.__components[1].__change() } }, - __update: function () { arrow_update(this, false) }, + __update: function () { arrow_update(this) }, __get_extent: function(ext) { if (!this.__components) this.__update() Autoscale.find_extent(this.__components[0], ext) Autoscale.find_extent(this.__components[1], ext) } }) - - function vp_arrow(args) { - if (!(this instanceof vp_arrow)) return new vp_arrow(args) // so vp_arrow() is like new vp_arrow() - this.__shaftwidth = 0 - this.__headwidth = 0 - this.__headlength = 0 - return initObject(this, vp_arrow, args) - } - subclass(vp_arrow, arrow) - property.declare( vp_arrow.prototype, { - axis: new attributeVectorAxis(null, 1,0,0), - axis_and_length: { - get: function() { new Error("arrow has an axis attribute but no axis_and_length attribute") }, - set: function(value) { new Error("arrow has an axis attribute but no axis_and_length attribute") } - }, - length: { - get: function() { return mag(this.__axis) }, - set: function(val) { - this.axis = this.__axis.norm().multiply(val) - } - }, - __update: function () { arrow_update(this, true) } - }) function text(args) { // 3D text object if (!(this instanceof text)) return new text(args) // so text() is like new text() @@ -1548,7 +1486,7 @@ temp = mesh.merge(comp.getTransformedMesh(), comp, 0) if (temp === null) compound_error(i) update_extent( self, temp ) - } else if (o.__components !== undefined) { // currently, only arrow and vp_arrow have components + } else if (o.__components !== undefined) { // currently, only arrow has components var c = o.__components for (var ci=0; ci -1) {\n return true;\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n};\nif (!RS_arraylike_creator.__module__) Object.defineProperties(RS_arraylike_creator, {\n __module__ : {value: "__main__"}\n});\n\nfunction options_object(f) {\n return (function() {\n var RS_anonfunc = function () {\n if (typeof arguments[arguments.length - 1] === "object") {\n arguments[RS_bound_index(arguments.length - 1, arguments)][RS_kwargs_symbol] = true;\n }\n return f.apply(this, arguments);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n};\nif (!options_object.__argnames__) Object.defineProperties(options_object, {\n __argnames__ : {value: ["f"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_id(x) {\n return x.RS_object_id;\n};\nif (!RS_id.__argnames__) Object.defineProperties(RS_id, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_dir(item) {\n var arr;\n arr = RS_list_decorate([]);\n for (var i in item) {\n arr.push(i);\n }\n return arr;\n};\nif (!RS_dir.__argnames__) Object.defineProperties(RS_dir, {\n __argnames__ : {value: ["item"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_ord(x) {\n var ans, second;\n ans = x.charCodeAt(0);\n if (55296 <= ans && ans <= 56319) {\n second = x.charCodeAt(1);\n if (56320 <= second && second <= 57343) {\n return (ans - 55296) * 1024 + second - 56320 + 65536;\n }\n throw new TypeError("string is missing the low surrogate char");\n }\n return ans;\n};\nif (!RS_ord.__argnames__) Object.defineProperties(RS_ord, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_chr(code) {\n if (code <= 65535) {\n return String.fromCharCode(code);\n }\n code -= 65536;\n return String.fromCharCode(55296 + (code >> 10), 56320 + (code & 1023));\n};\nif (!RS_chr.__argnames__) Object.defineProperties(RS_chr, {\n __argnames__ : {value: ["code"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_callable(x) {\n return typeof x === "function";\n};\nif (!RS_callable.__argnames__) Object.defineProperties(RS_callable, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_bin(x) {\n var ans;\n if (typeof x !== "number" || x % 1 !== 0) {\n throw new TypeError("integer required");\n }\n ans = x.toString(2);\n if (ans[0] === "-") {\n ans = "-" + "0b" + ans.slice(1);\n } else {\n ans = "0b" + ans;\n }\n return ans;\n};\nif (!RS_bin.__argnames__) Object.defineProperties(RS_bin, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_hex(x) {\n var ans;\n if (typeof x !== "number" || x % 1 !== 0) {\n throw new TypeError("integer required");\n }\n ans = x.toString(16);\n if (ans[0] === "-") {\n ans = "-" + "0x" + ans.slice(1);\n } else {\n ans = "0x" + ans;\n }\n return ans;\n};\nif (!RS_hex.__argnames__) Object.defineProperties(RS_hex, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_enumerate(iterable) {\n var ans, iterator;\n ans = {"_i":-1};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n if (RS_arraylike(iterable)) {\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i < iterable.length) {\n return {\'done\':false, \'value\':[this._i, iterable[this._i]]};\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n ans["_iterator"] = iterator;\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var r;\n r = this._iterator.next();\n if (r.done) {\n return {\'done\':true};\n }\n this._i += 1;\n return {\'done\':false, \'value\':[this._i, r.value]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n return RS_enumerate(Object.keys(iterable));\n};\nif (!RS_enumerate.__argnames__) Object.defineProperties(RS_enumerate, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_reversed(iterable) {\n var ans;\n if (RS_arraylike(iterable)) {\n ans = {"_i": iterable.length};\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i -= 1;\n if (this._i > -1) {\n return {\'done\':false, \'value\':iterable[this._i]};\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n throw new TypeError("reversed() can only be called on arrays or strings");\n};\nif (!RS_reversed.__argnames__) Object.defineProperties(RS_reversed, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_iter(iterable) {\n var ans;\n if (typeof iterable[RS_iterator_symbol] === "function") {\n return (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n }\n if (RS_arraylike(iterable)) {\n ans = {"_i":-1};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i < iterable.length) {\n return {\'done\':false, \'value\':iterable[this._i]};\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n return RS_iter(Object.keys(iterable));\n};\nif (!RS_iter.__argnames__) Object.defineProperties(RS_iter, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_range_next(step, length) {\n var RS_unpack;\n this._i += step;\n this._idx += 1;\n if (this._idx >= length) {\n RS_unpack = [this.__i, -1];\n this._i = RS_unpack[0];\n this._idx = RS_unpack[1];\n return {\'done\':true};\n }\n return {\'done\':false, \'value\':this._i};\n};\nif (!RS_range_next.__argnames__) Object.defineProperties(RS_range_next, {\n __argnames__ : {value: ["step", "length"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_range(start, stop, step) {\n var length, ans;\n if (arguments.length <= 1) {\n stop = start || 0;\n start = 0;\n }\n step = arguments[2] || 1;\n length = Math.max(Math.ceil((stop - start) / step), 0);\n ans = {start:start, step:step, stop:stop};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n var it;\n it = {"_i": start - step, "_idx": -1};\n it.next = RS_range_next.bind(it, step, length);\n it[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return it;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans.count = (function() {\n var RS_anonfunc = function (val) {\n if (!this._cached) {\n this._cached = list(this);\n }\n return this._cached.count(val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans.index = (function() {\n var RS_anonfunc = function (val) {\n if (!this._cached) {\n this._cached = list(this);\n }\n return this._cached.index(val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n if (typeof Proxy === "function") {\n ans = new Proxy(ans, (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function (obj, prop) {\n var iprop;\n if (typeof prop === "string") {\n iprop = parseInt(prop);\n if (!isNaN(iprop)) {\n prop = iprop;\n }\n }\n if (typeof prop === "number") {\n if (!obj._cached) {\n obj._cached = list(obj);\n }\n return (RS_expr_temp = obj._cached)[(typeof prop === "number" && prop < 0) ? RS_expr_temp.length + prop : prop];\n }\n return obj[(typeof prop === "number" && prop < 0) ? obj.length + prop : prop];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["obj", "prop"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this));\n }\n return ans;\n};\nif (!RS_range.__argnames__) Object.defineProperties(RS_range, {\n __argnames__ : {value: ["start", "stop", "step"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_getattr(obj, name, defval) {\n var ret;\n try {\n ret = obj[(typeof name === "number" && name < 0) ? obj.length + name : name];\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof TypeError) {\n if (defval === undefined) {\n throw new AttributeError("The attribute " + name + " is not present");\n }\n return defval;\n } else {\n throw RS_Exception;\n }\n }\n if (ret === undefined && !(name in obj)) {\n if (defval === undefined) {\n throw new AttributeError("The attribute " + name + " is not present");\n }\n ret = defval;\n }\n return ret;\n};\nif (!RS_getattr.__argnames__) Object.defineProperties(RS_getattr, {\n __argnames__ : {value: ["obj", "name", "defval"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_setattr(obj, name, value) {\n obj[(typeof name === "number" && name < 0) ? obj.length + name : name] = value;\n};\nif (!RS_setattr.__argnames__) Object.defineProperties(RS_setattr, {\n __argnames__ : {value: ["obj", "name", "value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_hasattr(obj, name) {\n return name in obj;\n};\nif (!RS_hasattr.__argnames__) Object.defineProperties(RS_hasattr, {\n __argnames__ : {value: ["obj", "name"]},\n __module__ : {value: "__main__"}\n});\n\nRS_len = (function() {\n var RS_anonfunc = function () {\n function len(obj) {\n if (RS_arraylike(obj)) {\n return obj.length;\n }\n if (typeof obj.__len__ === "function") {\n return obj.__len__();\n }\n if (obj instanceof Set || obj instanceof Map) {\n return obj.size;\n }\n return Object.keys(obj).length;\n };\n if (!len.__argnames__) Object.defineProperties(len, {\n __argnames__ : {value: ["obj"]},\n __module__ : {value: "__main__"}\n });\n\n function len5(obj) {\n if (RS_arraylike(obj)) {\n return obj.length;\n }\n if (typeof obj.__len__ === "function") {\n return obj.__len__();\n }\n return Object.keys(obj).length;\n };\n if (!len5.__argnames__) Object.defineProperties(len5, {\n __argnames__ : {value: ["obj"]},\n __module__ : {value: "__main__"}\n });\n\n return (typeof Set === "function" && typeof Map === "function") ? len : len5;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})()();\nfunction RS_get_module(name) {\n return RS_modules[(typeof name === "number" && name < 0) ? RS_modules.length + name : name];\n};\nif (!RS_get_module.__argnames__) Object.defineProperties(RS_get_module, {\n __argnames__ : {value: ["name"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_pow(x, y, z) {\n var ans;\n ans = Math.pow(x, y);\n if (z !== undefined) {\n ans %= z;\n }\n return ans;\n};\nif (!RS_pow.__argnames__) Object.defineProperties(RS_pow, {\n __argnames__ : {value: ["x", "y", "z"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_type(x) {\n return x.constructor;\n};\nif (!RS_type.__argnames__) Object.defineProperties(RS_type, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_divmod(x, y) {\n var d;\n if (y === 0) {\n throw new ZeroDivisionError("integer division or modulo by zero");\n }\n d = Math.floor(x / y);\n return [d, x - d * y];\n};\nif (!RS_divmod.__argnames__) Object.defineProperties(RS_divmod, {\n __argnames__ : {value: ["x", "y"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_max() {\n var kwargs = arguments[arguments.length-1];\n if (kwargs === null || typeof kwargs !== "object" || kwargs [RS_kwargs_symbol] !== true) kwargs = {};\n var args = Array.prototype.slice.call(arguments, 0);\n if (kwargs !== null && typeof kwargs === "object" && kwargs [RS_kwargs_symbol] === true) args.pop();\n var args, x;\n if (args.length === 0) {\n if (kwargs.defval !== undefined) {\n return kwargs.defval;\n }\n throw new TypeError("expected at least one argument");\n }\n if (args.length === 1) {\n args = args[0];\n }\n if (kwargs.key) {\n args = (function() {\n var RS_Iter = RS_Iterable(args), RS_Result = [], x;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n x = RS_Iter[RS_Index];\n RS_Result.push(kwargs.key(x));\n }\n RS_Result = RS_list_constructor(RS_Result);\n return RS_Result;\n })();\n }\n if (!Array.isArray(args)) {\n args = list(args);\n }\n if (args.length) {\n return this.apply(null, args);\n }\n if (kwargs.defval !== undefined) {\n return kwargs.defval;\n }\n throw new TypeError("expected at least one argument");\n};\nif (!RS_max.__handles_kwarg_interpolation__) Object.defineProperties(RS_max, {\n __handles_kwarg_interpolation__ : {value: true},\n __module__ : {value: "__main__"}\n});\n\nvar abs = Math.abs, max = RS_max.bind(Math.max), min = RS_max.bind(Math.min), bool = RS_bool, type = RS_type;\nvar float = RS_float, int = RS_int, arraylike = RS_arraylike_creator(), RS_arraylike = arraylike;\nvar print = RS_print, id = RS_id, get_module = RS_get_module, pow = RS_pow, divmod = RS_divmod;\nvar dir = RS_dir, ord = RS_ord, chr = RS_chr, bin = RS_bin, hex = RS_hex, callable = RS_callable;\nvar enumerate = RS_enumerate, iter = RS_iter, reversed = RS_reversed, len = RS_len;\nvar range = RS_range, getattr = RS_getattr, setattr = RS_setattr, hasattr = RS_hasattr;function RS_equals(a, b) {\n var RS_unpack, akeys, bkeys, key;\n if (a === b) {\n return true;\n }\n if (a && typeof a.__eq__ === "function") {\n return a.__eq__(b);\n }\n if (b && typeof b.__eq__ === "function") {\n return b.__eq__(a);\n }\n if (RS_arraylike(a) && RS_arraylike(b)) {\n if ((a.length !== b.length && (typeof a.length !== "object" || RS_not_equals(a.length, b.length)))) {\n return false;\n }\n for (var i=0; i < a.length; i++) {\n if (!(((a[(typeof i === "number" && i < 0) ? a.length + i : i] === b[(typeof i === "number" && i < 0) ? b.length + i : i] || typeof a[(typeof i === "number" && i < 0) ? a.length + i : i] === "object" && RS_equals(a[(typeof i === "number" && i < 0) ? a.length + i : i], b[(typeof i === "number" && i < 0) ? b.length + i : i]))))) {\n return false;\n }\n }\n return true;\n }\n if (typeof a === "object" && typeof b === "object" && a !== null && b !== null && (a.constructor === Object && b.constructor === Object || Object.getPrototypeOf(a) === null && Object.getPrototypeOf(b) === null)) {\n RS_unpack = [Object.keys(a), Object.keys(b)];\n akeys = RS_unpack[0];\n bkeys = RS_unpack[1];\n if (akeys.length !== bkeys.length) {\n return false;\n }\n for (var j=0; j < akeys.length; j++) {\n key = akeys[(typeof j === "number" && j < 0) ? akeys.length + j : j];\n if (!(((a[(typeof key === "number" && key < 0) ? a.length + key : key] === b[(typeof key === "number" && key < 0) ? b.length + key : key] || typeof a[(typeof key === "number" && key < 0) ? a.length + key : key] === "object" && RS_equals(a[(typeof key === "number" && key < 0) ? a.length + key : key], b[(typeof key === "number" && key < 0) ? b.length + key : key]))))) {\n return false;\n }\n }\n return true;\n }\n return false;\n};\nif (!RS_equals.__argnames__) Object.defineProperties(RS_equals, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_not_equals(a, b) {\n if (a === b) {\n return false;\n }\n if (a && typeof a.__ne__ === "function") {\n return a.__ne__(b);\n }\n if (b && typeof b.__ne__ === "function") {\n return b.__ne__(a);\n }\n return !RS_equals(a, b);\n};\nif (!RS_not_equals.__argnames__) Object.defineProperties(RS_not_equals, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "__main__"}\n});\n\nvar equals = RS_equals;\nfunction RS_list_extend(iterable) {\n var start, iterator, result;\n if (Array.isArray(iterable) || typeof iterable === "string") {\n start = this.length;\n this.length += iterable.length;\n for (var i = 0; i < iterable.length; i++) {\n (RS_expr_temp = this)[RS_bound_index(start + i, RS_expr_temp)] = iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i];\n }\n } else {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done) {\n this.push(result.value);\n result = iterator.next();\n }\n }\n};\nif (!RS_list_extend.__argnames__) Object.defineProperties(RS_list_extend, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_index(val, start, stop) {\n var idx;\n start = start || 0;\n if (start < 0) {\n start = this.length + start;\n }\n if (start < 0) {\n throw new ValueError(val + " is not in list");\n }\n if (stop === undefined) {\n idx = this.indexOf(val, start);\n if (idx === -1) {\n throw new ValueError(val + " is not in list");\n }\n return idx;\n }\n if (stop < 0) {\n stop = this.length + stop;\n }\n for (var i = start; i < stop; i++) {\n if (((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === val || typeof (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === "object" && RS_equals((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i], val))) {\n return i;\n }\n }\n throw new ValueError(val + " is not in list");\n};\nif (!RS_list_index.__argnames__) Object.defineProperties(RS_list_index, {\n __argnames__ : {value: ["val", "start", "stop"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_pop(index) {\n var ans;\n if (this.length === 0) {\n throw new IndexError("list is empty");\n }\n if (index === undefined) {\n index = -1;\n }\n ans = this.splice(index, 1);\n if (!ans.length) {\n throw new IndexError("pop index out of range");\n }\n return ans[0];\n};\nif (!RS_list_pop.__argnames__) Object.defineProperties(RS_list_pop, {\n __argnames__ : {value: ["index"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_remove(value) {\n var idx;\n idx = this.indexOf(value);\n if (idx === -1) {\n throw new ValueError(value + " not in list");\n }\n this.splice(idx, 1);\n};\nif (!RS_list_remove.__argnames__) Object.defineProperties(RS_list_remove, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_to_string() {\n return "[" + this.join(", ") + "]";\n};\nif (!RS_list_to_string.__module__) Object.defineProperties(RS_list_to_string, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_insert(index, val) {\n if (index < 0) {\n index += this.length;\n }\n index = min(this.length, max(index, 0));\n if (index === 0) {\n this.unshift(val);\n return;\n }\n for (var i = this.length; i > index; i--) {\n (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] = (RS_expr_temp = this)[RS_bound_index(i - 1, RS_expr_temp)];\n }\n (RS_expr_temp = this)[(typeof index === "number" && index < 0) ? RS_expr_temp.length + index : index] = val;\n};\nif (!RS_list_insert.__argnames__) Object.defineProperties(RS_list_insert, {\n __argnames__ : {value: ["index", "val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_copy() {\n return RS_list_constructor(this);\n};\nif (!RS_list_copy.__module__) Object.defineProperties(RS_list_copy, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_clear() {\n this.length = 0;\n};\nif (!RS_list_clear.__module__) Object.defineProperties(RS_list_clear, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_as_array() {\n return Array.prototype.slice.call(this);\n};\nif (!RS_list_as_array.__module__) Object.defineProperties(RS_list_as_array, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_count(value) {\n return this.reduce((function() {\n var RS_anonfunc = function (n, val) {\n return n + (val === value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["n", "val"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })(), 0);\n};\nif (!RS_list_count.__argnames__) Object.defineProperties(RS_list_count, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_sort_key(value) {\n var t;\n t = typeof value;\n if (t === "string" || t === "number") {\n return value;\n }\n return value.toString();\n};\nif (!RS_list_sort_key.__argnames__) Object.defineProperties(RS_list_sort_key, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_sort_cmp(a, b, ap, bp) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return ap - bp;\n};\nif (!RS_list_sort_cmp.__argnames__) Object.defineProperties(RS_list_sort_cmp, {\n __argnames__ : {value: ["a", "b", "ap", "bp"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_sort() {\n var key = (arguments[0] === undefined || ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? RS_list_sort.__defaults__.key : arguments[0];\n var reverse = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? RS_list_sort.__defaults__.reverse : arguments[1];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "key")){\n key = RS_kwargs_obj.key;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "reverse")){\n reverse = RS_kwargs_obj.reverse;\n }\n var mult, keymap, posmap, k;\n key = key || RS_list_sort_key;\n mult = (reverse) ? -1 : 1;\n keymap = dict();\n posmap = dict();\n for (var i=0; i < this.length; i++) {\n k = (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n keymap.set(k, key(k));\n posmap.set(k, i);\n }\n this.sort((function() {\n var RS_anonfunc = function (a, b) {\n return mult * RS_list_sort_cmp(keymap.get(a), keymap.get(b), posmap.get(a), posmap.get(b));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })());\n};\nif (!RS_list_sort.__defaults__) Object.defineProperties(RS_list_sort, {\n __defaults__ : {value: {key:null, reverse:false}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["key", "reverse"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_concat() {\n var ans;\n ans = Array.prototype.concat.apply(this, arguments);\n RS_list_decorate(ans);\n return ans;\n};\nif (!RS_list_concat.__module__) Object.defineProperties(RS_list_concat, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_slice() {\n var ans;\n ans = Array.prototype.slice.apply(this, arguments);\n RS_list_decorate(ans);\n return ans;\n};\nif (!RS_list_slice.__module__) Object.defineProperties(RS_list_slice, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_iterator(value) {\n var self;\n self = this;\n return (function(){\n var RS_d = {};\n RS_d["_i"] = -1;\n RS_d["_list"] = self;\n RS_d["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._list.length) {\n return (function(){\n var RS_d = {};\n RS_d["done"] = true;\n return RS_d;\n }).call(this);\n }\n return (function(){\n var RS_d = {};\n RS_d["done"] = false;\n RS_d["value"] = (RS_expr_temp = this._list)[RS_bound_index(this._i, RS_expr_temp)];\n return RS_d;\n }).call(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n};\nif (!RS_list_iterator.__argnames__) Object.defineProperties(RS_list_iterator, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_len() {\n return this.length;\n};\nif (!RS_list_len.__module__) Object.defineProperties(RS_list_len, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_contains(val) {\n for (var i = 0; i < this.length; i++) {\n if (((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === val || typeof (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === "object" && RS_equals((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i], val))) {\n return true;\n }\n }\n return false;\n};\nif (!RS_list_contains.__argnames__) Object.defineProperties(RS_list_contains, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_eq(other) {\n if (!RS_arraylike(other)) {\n return false;\n }\n if ((this.length !== other.length && (typeof this.length !== "object" || RS_not_equals(this.length, other.length)))) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (!((((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === other[(typeof i === "number" && i < 0) ? other.length + i : i] || typeof (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === "object" && RS_equals((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i], other[(typeof i === "number" && i < 0) ? other.length + i : i]))))) {\n return false;\n }\n }\n return true;\n};\nif (!RS_list_eq.__argnames__) Object.defineProperties(RS_list_eq, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_decorate(ans) {\n ans.append = Array.prototype.push;\n ans.toString = RS_list_to_string;\n ans.inspect = RS_list_to_string;\n ans.extend = RS_list_extend;\n ans.index = RS_list_index;\n ans.pypop = RS_list_pop;\n ans.remove = RS_list_remove;\n ans.insert = RS_list_insert;\n ans.copy = RS_list_copy;\n ans.clear = RS_list_clear;\n ans.count = RS_list_count;\n ans.concat = RS_list_concat;\n ans.pysort = RS_list_sort;\n ans.slice = RS_list_slice;\n ans.as_array = RS_list_as_array;\n ans.__len__ = RS_list_len;\n ans.__contains__ = RS_list_contains;\n ans.__eq__ = RS_list_eq;\n ans.constructor = RS_list_constructor;\n if (typeof ans[RS_iterator_symbol] !== "function") {\n ans[RS_iterator_symbol] = RS_list_iterator;\n }\n return ans;\n};\nif (!RS_list_decorate.__argnames__) Object.defineProperties(RS_list_decorate, {\n __argnames__ : {value: ["ans"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_constructor(iterable) {\n var ans, iterator, result;\n if (iterable === undefined) {\n ans = [];\n } else if (RS_arraylike(iterable)) {\n ans = new Array(iterable.length);\n for (var i = 0; i < iterable.length; i++) {\n ans[(typeof i === "number" && i < 0) ? ans.length + i : i] = iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i];\n }\n } else if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n ans = RS_list_decorate([]);\n result = iterator.next();\n while (!result.done) {\n ans.push(result.value);\n result = iterator.next();\n }\n } else if (typeof iterable === "number") {\n ans = new Array(iterable);\n } else {\n ans = Object.keys(iterable);\n }\n return RS_list_decorate(ans);\n};\nif (!RS_list_constructor.__argnames__) Object.defineProperties(RS_list_constructor, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_list_constructor.__name__ = "list";\nvar list = RS_list_constructor, list_wrap = RS_list_decorate;\nfunction sorted() {\n var iterable = ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true) ? undefined : arguments[0];\n var key = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? sorted.__defaults__.key : arguments[1];\n var reverse = (arguments[2] === undefined || ( 2 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? sorted.__defaults__.reverse : arguments[2];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "key")){\n key = RS_kwargs_obj.key;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "reverse")){\n reverse = RS_kwargs_obj.reverse;\n }\n var ans;\n ans = RS_list_constructor(iterable);\n ans.pysort(key, reverse);\n return ans;\n};\nif (!sorted.__defaults__) Object.defineProperties(sorted, {\n __defaults__ : {value: {key:null, reverse:false}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["iterable", "key", "reverse"]},\n __module__ : {value: "__main__"}\n});\n\nvar RS_global_object_id = 0, RS_set_implementation;\nfunction RS_set_keyfor(x) {\n var t, ans;\n t = typeof x;\n if (t === "string" || t === "number" || t === "boolean") {\n return "_" + t[0] + x;\n }\n if (x === null) {\n return "__!@#$0";\n }\n ans = x.RS_hash_key_prop;\n if (ans === undefined) {\n ans = "_!@#$" + (++RS_global_object_id);\n Object.defineProperty(x, "RS_hash_key_prop", (function(){\n var RS_d = {};\n RS_d["value"] = ans;\n return RS_d;\n }).call(this));\n }\n return ans;\n};\nif (!RS_set_keyfor.__argnames__) Object.defineProperties(RS_set_keyfor, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_set_polyfill() {\n this._store = {};\n this.size = 0;\n};\nif (!RS_set_polyfill.__module__) Object.defineProperties(RS_set_polyfill, {\n __module__ : {value: "__main__"}\n});\n\nRS_set_polyfill.prototype.add = (function() {\n var RS_anonfunc = function (x) {\n var key;\n key = RS_set_keyfor(x);\n if (!Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size += 1;\n (RS_expr_temp = this._store)[(typeof key === "number" && key < 0) ? RS_expr_temp.length + key : key] = x;\n }\n return this;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.clear = (function() {\n var RS_anonfunc = function (x) {\n this._store = {};\n this.size = 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.delete = (function() {\n var RS_anonfunc = function (x) {\n var key;\n key = RS_set_keyfor(x);\n if (Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size -= 1;\n delete this._store[key];\n return true;\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.has = (function() {\n var RS_anonfunc = function (x) {\n return Object.prototype.hasOwnProperty.call(this._store, RS_set_keyfor(x));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.values = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nif (typeof Set !== "function" || typeof Set.prototype.delete !== "function") {\n RS_set_implementation = RS_set_polyfill;\n} else {\n RS_set_implementation = Set;\n}\nfunction RS_set(iterable) {\n var ans, s, iterator, result, keys;\n if (this instanceof RS_set) {\n this.jsset = new RS_set_implementation;\n ans = this;\n if (iterable === undefined) {\n return ans;\n }\n s = ans.jsset;\n if (RS_arraylike(iterable)) {\n for (var i = 0; i < iterable.length; i++) {\n s.add(iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i]);\n }\n } else if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done) {\n s.add(result.value);\n result = iterator.next();\n }\n } else {\n keys = Object.keys(iterable);\n for (var j=0; j < keys.length; j++) {\n s.add(keys[(typeof j === "number" && j < 0) ? keys.length + j : j]);\n }\n }\n return ans;\n } else {\n return new RS_set(iterable);\n }\n};\nif (!RS_set.__argnames__) Object.defineProperties(RS_set, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_set.prototype.__name__ = "set";\nObject.defineProperties(RS_set.prototype, (function(){\n var RS_d = {};\n RS_d["length"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsset.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n RS_d["size"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsset.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n return RS_d;\n}).call(this));\nRS_set.prototype.__len__ = (function() {\n var RS_anonfunc = function () {\n return this.jsset.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.has = RS_set.prototype.__contains__ = (function() {\n var RS_anonfunc = function (x) {\n return this.jsset.has(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.add = (function() {\n var RS_anonfunc = function (x) {\n this.jsset.add(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.clear = (function() {\n var RS_anonfunc = function () {\n this.jsset.clear();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.copy = (function() {\n var RS_anonfunc = function () {\n return RS_set(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.discard = (function() {\n var RS_anonfunc = function (x) {\n this.jsset.delete(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this.jsset.values();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.difference = (function() {\n var RS_anonfunc = function () {\n var ans, s, iterator, r, x, has;\n ans = new RS_set;\n s = ans.jsset;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n has = false;\n for (var i = 0; i < arguments.length; i++) {\n if (arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n has = true;\n break;\n }\n }\n if (!has) {\n s.add(x);\n }\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.difference_update = (function() {\n var RS_anonfunc = function () {\n var s, remove, iterator, r, x;\n s = this.jsset;\n remove = [];\n iterator = s.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n for (var i = 0; i < arguments.length; i++) {\n if (arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n remove.push(x);\n break;\n }\n }\n r = iterator.next();\n }\n for (var j = 0; j < remove.length; j++) {\n s.delete(remove[(typeof j === "number" && j < 0) ? remove.length + j : j]);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.intersection = (function() {\n var RS_anonfunc = function () {\n var ans, s, iterator, r, x, has;\n ans = new RS_set;\n s = ans.jsset;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n has = true;\n for (var i = 0; i < arguments.length; i++) {\n if (!arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n has = false;\n break;\n }\n }\n if (has) {\n s.add(x);\n }\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.intersection_update = (function() {\n var RS_anonfunc = function () {\n var s, remove, iterator, r, x;\n s = this.jsset;\n remove = [];\n iterator = s.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n for (var i = 0; i < arguments.length; i++) {\n if (!arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n remove.push(x);\n break;\n }\n }\n r = iterator.next();\n }\n for (var j = 0; j < remove.length; j++) {\n s.delete(remove[(typeof j === "number" && j < 0) ? remove.length + j : j]);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.isdisjoint = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r, x;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n if (other.has(x)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.issubset = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r, x;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n if (!other.has(x)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.issuperset = (function() {\n var RS_anonfunc = function (other) {\n var s, iterator, r, x;\n s = this.jsset;\n iterator = other.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n if (!s.has(x)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.pop = (function() {\n var RS_anonfunc = function () {\n var iterator, r;\n iterator = this.jsset.values();\n r = iterator.next();\n if (r.done) {\n throw new KeyError("pop from an empty set");\n }\n this.jsset.delete(r.value);\n return r.value;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.remove = (function() {\n var RS_anonfunc = function (x) {\n if (!this.jsset.delete(x)) {\n throw new KeyError(x.toString());\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.symmetric_difference = (function() {\n var RS_anonfunc = function (other) {\n return this.union(other).difference(this.intersection(other));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.symmetric_difference_update = (function() {\n var RS_anonfunc = function (other) {\n var common;\n common = this.intersection(other);\n this.update(other);\n this.difference_update(common);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.union = (function() {\n var RS_anonfunc = function () {\n var ans;\n ans = RS_set(this);\n ans.update.apply(ans, arguments);\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.update = (function() {\n var RS_anonfunc = function () {\n var s, iterator, r;\n s = this.jsset;\n for (var i=0; i < arguments.length; i++) {\n iterator = arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i][RS_iterator_symbol]();\n r = iterator.next();\n while (!r.done) {\n s.add(r.value);\n r = iterator.next();\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.toString = RS_set.prototype.__repr__ = RS_set.prototype.__str__ = RS_set.prototype.inspect = (function() {\n var RS_anonfunc = function () {\n return "{" + list(this).join(", ") + "}";\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.__eq__ = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r;\n if (!other instanceof this.constructor) {\n return false;\n }\n if (other.size !== this.size) {\n return false;\n }\n if (other.size === 0) {\n return true;\n }\n iterator = other[RS_iterator_symbol]();\n r = iterator.next();\n while (!r.done) {\n if (!this.has(r.value)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nfunction RS_set_wrap(x) {\n var ans;\n ans = new RS_set;\n ans.jsset = x;\n return ans;\n};\nif (!RS_set_wrap.__argnames__) Object.defineProperties(RS_set_wrap, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nvar set = RS_set, set_wrap = RS_set_wrap;\nvar RS_dict_implementation;\nfunction RS_dict_polyfill() {\n this._store = {};\n this.size = 0;\n};\nif (!RS_dict_polyfill.__module__) Object.defineProperties(RS_dict_polyfill, {\n __module__ : {value: "__main__"}\n});\n\nRS_dict_polyfill.prototype.set = (function() {\n var RS_anonfunc = function (x, value) {\n var key;\n key = RS_set_keyfor(x);\n if (!Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size += 1;\n }\n (RS_expr_temp = this._store)[(typeof key === "number" && key < 0) ? RS_expr_temp.length + key : key] = [x, value];\n return this;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x", "value"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.clear = (function() {\n var RS_anonfunc = function (x) {\n this._store = {};\n this.size = 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.delete = (function() {\n var RS_anonfunc = function (x) {\n var key;\n key = RS_set_keyfor(x);\n if (Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size -= 1;\n delete this._store[key];\n return true;\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.has = (function() {\n var RS_anonfunc = function (x) {\n return Object.prototype.hasOwnProperty.call(this._store, RS_set_keyfor(x));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.get = (function() {\n var RS_anonfunc = function (x) {\n try {\n return (RS_expr_temp = this._store)[RS_bound_index(RS_set_keyfor(x), RS_expr_temp)][1];\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof TypeError) {\n return undefined;\n } else {\n throw RS_Exception;\n }\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.values = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]][1]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.keys = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]][0]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.entries = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nif (typeof Map !== "function" || typeof Map.prototype.delete !== "function") {\n RS_dict_implementation = RS_dict_polyfill;\n} else {\n RS_dict_implementation = Map;\n}\nfunction RS_dict() {\n var iterable = ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true) ? undefined : arguments[0];\n var kw = arguments[arguments.length-1];\n if (kw === null || typeof kw !== "object" || kw [RS_kwargs_symbol] !== true) kw = {};\n if (this instanceof RS_dict) {\n this.jsmap = new RS_dict_implementation;\n if (iterable !== undefined) {\n this.update(iterable);\n }\n this.update(kw);\n return this;\n } else {\n return RS_interpolate_kwargs_constructor.call(Object.create(RS_dict.prototype), false, RS_dict, [iterable].concat([RS_desugar_kwargs(kw)]));\n }\n};\nif (!RS_dict.__handles_kwarg_interpolation__) Object.defineProperties(RS_dict, {\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_dict.prototype.__name__ = "dict";\nObject.defineProperties(RS_dict.prototype, (function(){\n var RS_d = {};\n RS_d["length"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n RS_d["size"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n return RS_d;\n}).call(this));\nRS_dict.prototype.__len__ = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.has = RS_dict.prototype.__contains__ = (function() {\n var RS_anonfunc = function (x) {\n return this.jsmap.has(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.set = RS_dict.prototype.__setitem__ = (function() {\n var RS_anonfunc = function (key, value) {\n this.jsmap.set(key, value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "value"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.__delitem__ = (function() {\n var RS_anonfunc = function (key) {\n this.jsmap.delete(key);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.clear = (function() {\n var RS_anonfunc = function () {\n this.jsmap.clear();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.copy = (function() {\n var RS_anonfunc = function () {\n return RS_dict(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.keys = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.keys();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.values = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.values();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.items = RS_dict.prototype.entries = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.entries();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.keys();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.__getitem__ = (function() {\n var RS_anonfunc = function (key) {\n var ans;\n ans = this.jsmap.get(key);\n if (ans === undefined && !this.jsmap.has(key)) {\n throw new KeyError(key + "");\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.get = (function() {\n var RS_anonfunc = function (key, defval) {\n var ans;\n ans = this.jsmap.get(key);\n if (ans === undefined && !this.jsmap.has(key)) {\n return (defval === undefined) ? null : defval;\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "defval"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.set_default = (function() {\n var RS_anonfunc = function (key, defval) {\n var j;\n j = this.jsmap;\n if (!j.has(key)) {\n j.set(key, defval);\n return defval;\n }\n return j.get(key);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "defval"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.fromkeys = RS_dict.prototype.fromkeys = (function() {\n var RS_anonfunc = function () {\n var iterable = ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true) ? undefined : arguments[0];\n var value = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? RS_anonfunc.__defaults__.value : arguments[1];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "value")){\n value = RS_kwargs_obj.value;\n }\n var ans, iterator, r;\n ans = RS_dict();\n iterator = iter(iterable);\n r = iterator.next();\n while (!r.done) {\n ans.set(r.value, value);\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__defaults__) Object.defineProperties(RS_anonfunc, {\n __defaults__ : {value: {value:null}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["iterable", "value"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.pop = (function() {\n var RS_anonfunc = function (key, defval) {\n var ans;\n ans = this.jsmap.get(key);\n if (ans === undefined && !this.jsmap.has(key)) {\n if (defval === undefined) {\n throw new KeyError(key);\n }\n return defval;\n }\n this.jsmap.delete(key);\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "defval"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.popitem = (function() {\n var RS_anonfunc = function () {\n var r;\n r = this.jsmap.entries().next();\n if (r.done) {\n throw new KeyError("dict is empty");\n }\n this.jsmap.delete(r.value[0]);\n return r.value;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.update = (function() {\n var RS_anonfunc = function () {\n var m, iterable, iterator, result, keys;\n if (arguments.length === 0) {\n return;\n }\n m = this.jsmap;\n iterable = arguments[0];\n if (Array.isArray(iterable)) {\n for (var i = 0; i < iterable.length; i++) {\n m.set(iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i][0], iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i][1]);\n }\n } else if (iterable instanceof RS_dict) {\n iterator = iterable.items();\n result = iterator.next();\n while (!result.done) {\n m.set(result.value[0], result.value[1]);\n result = iterator.next();\n }\n } else if (typeof Map === "function" && iterable instanceof Map) {\n iterator = iterable.entries();\n result = iterator.next();\n while (!result.done) {\n m.set(result.value[0], result.value[1]);\n result = iterator.next();\n }\n } else if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done) {\n m.set(result.value[0], result.value[1]);\n result = iterator.next();\n }\n } else {\n keys = Object.keys(iterable);\n for (var j=0; j < keys.length; j++) {\n if (keys[(typeof j === "number" && j < 0) ? keys.length + j : j] !== RS_iterator_symbol) {\n m.set(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], iterable[RS_bound_index(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], iterable)]);\n }\n }\n }\n if (arguments.length > 1) {\n RS_dict.prototype.update.call(this, arguments[1]);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.toString = RS_dict.prototype.inspect = RS_dict.prototype.__str__ = RS_dict.prototype.__repr__ = (function() {\n var RS_anonfunc = function () {\n var entries, iterator, r;\n entries = [];\n iterator = this.jsmap.entries();\n r = iterator.next();\n while (!r.done) {\n entries.push(RS_repr(r.value[0]) + ": " + RS_repr(r.value[1]));\n r = iterator.next();\n }\n return "{" + entries.join(", ") + "}";\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.__eq__ = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r, x;\n if (!(other instanceof this.constructor)) {\n return false;\n }\n if (other.size !== this.size) {\n return false;\n }\n if (other.size === 0) {\n return true;\n }\n iterator = other.items();\n r = iterator.next();\n while (!r.done) {\n x = this.jsmap.get(r.value[0]);\n if (x === undefined && !this.jsmap.has(r.value[0]) || x !== r.value[1]) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.as_object = (function() {\n var RS_anonfunc = function (other) {\n var ans, iterator, r;\n ans = {};\n iterator = this.jsmap.entries();\n r = iterator.next();\n while (!r.done) {\n ans[RS_bound_index(r.value[0], ans)] = r.value[1];\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nfunction RS_dict_wrap(x) {\n var ans;\n ans = new RS_dict;\n ans.jsmap = x;\n return ans;\n};\nif (!RS_dict_wrap.__argnames__) Object.defineProperties(RS_dict_wrap, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nvar dict = RS_dict, dict_wrap = RS_dict_wrap;// }}}\nvar NameError;\nNameError = ReferenceError;\nfunction Exception() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n Exception.prototype.__init__.apply(this, arguments);\n}\nRS_extends(Exception, Error);\nException.prototype.__init__ = function __init__(message) {\n var self = this;\n self.message = message;\n self.stack = (new Error).stack;\n self.name = self.constructor.name;\n};\nif (!Exception.prototype.__init__.__argnames__) Object.defineProperties(Exception.prototype.__init__, {\n __argnames__ : {value: ["message"]},\n __module__ : {value: "__main__"}\n});\nException.__argnames__ = Exception.prototype.__init__.__argnames__;\nException.__handles_kwarg_interpolation__ = Exception.prototype.__init__.__handles_kwarg_interpolation__;\nException.prototype.__repr__ = function __repr__() {\n var self = this;\n return self.name + ": " + self.message;\n};\nif (!Exception.prototype.__repr__.__module__) Object.defineProperties(Exception.prototype.__repr__, {\n __module__ : {value: "__main__"}\n});\nException.prototype.__str__ = function __str__ () {\n if(Error.prototype.__str__) return Error.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(Exception.prototype, "__bases__", {value: [Error]});\n\nfunction AttributeError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AttributeError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(AttributeError, Exception);\nAttributeError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nAttributeError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nAttributeError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(AttributeError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction IndexError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n IndexError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(IndexError, Exception);\nIndexError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nIndexError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nIndexError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(IndexError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction KeyError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n KeyError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(KeyError, Exception);\nKeyError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nKeyError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nKeyError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(KeyError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction ValueError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n ValueError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(ValueError, Exception);\nValueError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nValueError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nValueError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(ValueError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction UnicodeDecodeError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n UnicodeDecodeError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(UnicodeDecodeError, Exception);\nUnicodeDecodeError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nUnicodeDecodeError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nUnicodeDecodeError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(UnicodeDecodeError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction AssertionError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AssertionError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(AssertionError, Exception);\nAssertionError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nAssertionError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nAssertionError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(AssertionError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction ZeroDivisionError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n ZeroDivisionError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(ZeroDivisionError, Exception);\nZeroDivisionError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nZeroDivisionError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nZeroDivisionError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(ZeroDivisionError.prototype, "__bases__", {value: [Exception]});\n\nvar RS_in, RS_desugar_kwargs, RS_exists;\nfunction RS_eslice(arr, step, start, end) {\n var is_string;\n if (typeof arr === "string" || arr instanceof String) {\n is_string = true;\n arr = arr.split("");\n }\n if (step < 0) {\n step = -step;\n arr = arr.slice().reverse();\n if (typeof start !== "undefined") {\n start = arr.length - start - 1;\n }\n if (typeof end !== "undefined") {\n end = arr.length - end - 1;\n }\n }\n if (typeof start === "undefined") {\n start = 0;\n }\n if (typeof end === "undefined") {\n end = arr.length;\n }\n arr = arr.slice(start, end).filter((function() {\n var RS_anonfunc = function (e, i) {\n return i % step === 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["e", "i"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })());\n if (is_string) {\n arr = arr.join("");\n }\n return arr;\n};\nif (!RS_eslice.__argnames__) Object.defineProperties(RS_eslice, {\n __argnames__ : {value: ["arr", "step", "start", "end"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_delslice(arr, step, start, end) {\n var is_string, RS_unpack, indices;\n if (typeof arr === "string" || arr instanceof String) {\n is_string = true;\n arr = arr.split("");\n }\n if (step < 0) {\n if (typeof start === "undefined") {\n start = arr.length;\n }\n if (typeof end === "undefined") {\n end = 0;\n }\n RS_unpack = [end, start, -step];\n start = RS_unpack[0];\n end = RS_unpack[1];\n step = RS_unpack[2];\n }\n if (typeof start === "undefined") {\n start = 0;\n }\n if (typeof end === "undefined") {\n end = arr.length;\n }\n if (step === 1) {\n arr.splice(start, end - start);\n } else {\n if (end > start) {\n indices = [];\n for (var i = start; i < end; i += step) {\n indices.push(i);\n }\n for (var i = indices.length - 1; i >= 0; i--) {\n arr.splice(indices[(typeof i === "number" && i < 0) ? indices.length + i : i], 1);\n }\n }\n }\n if (is_string) {\n arr = arr.join("");\n }\n return arr;\n};\nif (!RS_delslice.__argnames__) Object.defineProperties(RS_delslice, {\n __argnames__ : {value: ["arr", "step", "start", "end"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_flatten(arr) {\n var ans, value;\n ans = RS_list_decorate([]);\n for (var i=0; i < arr.length; i++) {\n value = arr[(typeof i === "number" && i < 0) ? arr.length + i : i];\n if (Array.isArray(value)) {\n ans = ans.concat(RS_flatten(value));\n } else {\n ans.push(value);\n }\n }\n return ans;\n};\nif (!RS_flatten.__argnames__) Object.defineProperties(RS_flatten, {\n __argnames__ : {value: ["arr"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_unpack_asarray(num, iterable) {\n var ans, iterator, result;\n if (RS_arraylike(iterable)) {\n return iterable;\n }\n ans = [];\n if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done && ans.length < num) {\n ans.push(result.value);\n result = iterator.next();\n }\n }\n return ans;\n};\nif (!RS_unpack_asarray.__argnames__) Object.defineProperties(RS_unpack_asarray, {\n __argnames__ : {value: ["num", "iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_extends(child, parent) {\n child.prototype = Object.create(parent.prototype);\n child.prototype.constructor = child;\n};\nif (!RS_extends.__argnames__) Object.defineProperties(RS_extends, {\n __argnames__ : {value: ["child", "parent"]},\n __module__ : {value: "__main__"}\n});\n\nRS_in = (function() {\n var RS_anonfunc = function () {\n if (typeof Map === "function" && typeof Set === "function") {\n return (function() {\n var RS_anonfunc = function (val, arr) {\n if (typeof arr === "string") {\n return arr.indexOf(val) !== -1;\n }\n if (typeof arr.__contains__ === "function") {\n return arr.__contains__(val);\n }\n if (arr instanceof Map || arr instanceof Set) {\n return arr.has(val);\n }\n if (RS_arraylike(arr)) {\n return RS_list_contains.call(arr, val);\n }\n return Object.prototype.hasOwnProperty.call(arr, val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val", "arr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n }\n return (function() {\n var RS_anonfunc = function (val, arr) {\n if (typeof arr === "string") {\n return arr.indexOf(val) !== -1;\n }\n if (typeof arr.__contains__ === "function") {\n return arr.__contains__(val);\n }\n if (RS_arraylike(arr)) {\n return RS_list_contains.call(arr, val);\n }\n return Object.prototype.hasOwnProperty.call(arr, val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val", "arr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})()();\nfunction RS_Iterable(iterable) {\n var iterator, ans, result;\n if (RS_arraylike(iterable)) {\n return iterable;\n }\n if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n ans = RS_list_decorate([]);\n result = iterator.next();\n while (!result.done) {\n ans.push(result.value);\n result = iterator.next();\n }\n return ans;\n }\n return Object.keys(iterable);\n};\nif (!RS_Iterable.__argnames__) Object.defineProperties(RS_Iterable, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_desugar_kwargs = (function() {\n var RS_anonfunc = function () {\n if (typeof Object.assign === "function") {\n return (function() {\n var RS_anonfunc = function () {\n var ans;\n ans = Object.create(null);\n ans[RS_kwargs_symbol] = true;\n for (var i = 0; i < arguments.length; i++) {\n Object.assign(ans, arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n }\n return (function() {\n var RS_anonfunc = function () {\n var ans, keys;\n ans = Object.create(null);\n ans[RS_kwargs_symbol] = true;\n for (var i = 0; i < arguments.length; i++) {\n keys = Object.keys(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n for (var j = 0; j < keys.length; j++) {\n ans[RS_bound_index(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], ans)] = (RS_expr_temp = arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i])[RS_bound_index(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], RS_expr_temp)];\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})()();\nfunction RS_interpolate_kwargs(f, supplied_args) {\n var has_prop, kwobj, args, prop;\n if (!f.__argnames__) {\n return f.apply(this, supplied_args);\n }\n has_prop = Object.prototype.hasOwnProperty;\n kwobj = supplied_args.pop();\n if (f.__handles_kwarg_interpolation__) {\n args = new Array(Math.max(supplied_args.length, f.__argnames__.length) + 1);\n args[args.length-1] = kwobj;\n for (var i = 0; i < args.length - 1; i++) {\n if (i < f.__argnames__.length) {\n prop = (RS_expr_temp = f.__argnames__)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n if (has_prop.call(kwobj, prop)) {\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = kwobj[(typeof prop === "number" && prop < 0) ? kwobj.length + prop : prop];\n delete kwobj[prop];\n } else if (i < supplied_args.length) {\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = supplied_args[(typeof i === "number" && i < 0) ? supplied_args.length + i : i];\n }\n } else {\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = supplied_args[(typeof i === "number" && i < 0) ? supplied_args.length + i : i];\n }\n }\n return f.apply(this, args);\n }\n for (var i = 0; i < f.__argnames__.length; i++) {\n prop = (RS_expr_temp = f.__argnames__)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n if (has_prop.call(kwobj, prop)) {\n supplied_args[(typeof i === "number" && i < 0) ? supplied_args.length + i : i] = kwobj[(typeof prop === "number" && prop < 0) ? kwobj.length + prop : prop];\n }\n }\n return f.apply(this, supplied_args);\n};\nif (!RS_interpolate_kwargs.__argnames__) Object.defineProperties(RS_interpolate_kwargs, {\n __argnames__ : {value: ["f", "supplied_args"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_interpolate_kwargs_constructor(apply, f, supplied_args) {\n if (apply) {\n f.apply(this, supplied_args);\n } else {\n RS_interpolate_kwargs.call(this, f, supplied_args);\n }\n return this;\n};\nif (!RS_interpolate_kwargs_constructor.__argnames__) Object.defineProperties(RS_interpolate_kwargs_constructor, {\n __argnames__ : {value: ["apply", "f", "supplied_args"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_getitem(obj, key) {\n if (obj.__getitem__) {\n return obj.__getitem__(key);\n }\n if (typeof key === "number" && key < 0) {\n key += obj.length;\n }\n return obj[(typeof key === "number" && key < 0) ? obj.length + key : key];\n};\nif (!RS_getitem.__argnames__) Object.defineProperties(RS_getitem, {\n __argnames__ : {value: ["obj", "key"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_setitem(obj, key, val) {\n if (obj.__setitem__) {\n obj.__setitem__(key, val);\n } else {\n if (typeof key === "number" && key < 0) {\n key += obj.length;\n }\n obj[(typeof key === "number" && key < 0) ? obj.length + key : key] = val;\n }\n};\nif (!RS_setitem.__argnames__) Object.defineProperties(RS_setitem, {\n __argnames__ : {value: ["obj", "key", "val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_delitem(obj, key) {\n if (obj.__delitem__) {\n obj.__delitem__(key);\n } else if (typeof obj.splice === "function") {\n obj.splice(key, 1);\n } else {\n if (typeof key === "number" && key < 0) {\n key += obj.length;\n }\n delete obj[key];\n }\n};\nif (!RS_delitem.__argnames__) Object.defineProperties(RS_delitem, {\n __argnames__ : {value: ["obj", "key"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_bound_index(idx, arr) {\n if (typeof idx === "number" && idx < 0) {\n idx += arr.length;\n }\n return idx;\n};\nif (!RS_bound_index.__argnames__) Object.defineProperties(RS_bound_index, {\n __argnames__ : {value: ["idx", "arr"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_splice(arr, val, start, end) {\n start = start || 0;\n if (start < 0) {\n start += arr.length;\n }\n if (end === undefined) {\n end = arr.length;\n }\n if (end < 0) {\n end += arr.length;\n }\n Array.prototype.splice.apply(arr, [start, end - start].concat(val));\n};\nif (!RS_splice.__argnames__) Object.defineProperties(RS_splice, {\n __argnames__ : {value: ["arr", "val", "start", "end"]},\n __module__ : {value: "__main__"}\n});\n\nRS_exists = (function(){\n var RS_d = {};\n RS_d["n"] = (function() {\n var RS_anonfunc = function (expr) {\n return expr !== undefined && expr !== null;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["d"] = (function() {\n var RS_anonfunc = function (expr) {\n if (expr === undefined || expr === null) {\n return Object.create(null);\n }\n return expr;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["c"] = (function() {\n var RS_anonfunc = function (expr) {\n if (typeof expr === "function") {\n return expr;\n }\n return (function() {\n var RS_anonfunc = function () {\n return undefined;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["g"] = (function() {\n var RS_anonfunc = function (expr) {\n if (expr === undefined || expr === null || typeof expr.__getitem__ !== "function") {\n return (function(){\n var RS_d = {};\n RS_d["__getitem__"] = (function() {\n var RS_anonfunc = function () {\n return undefined;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["e"] = (function() {\n var RS_anonfunc = function (expr, alt) {\n return (expr === undefined || expr === null) ? alt : expr;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr", "alt"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n}).call(this);\nfunction RS_mixin() {\n var seen, resolved_props, p, target, props, name;\n seen = Object.create(null);\n seen.__argnames__ = seen.__handles_kwarg_interpolation__ = seen.__init__ = seen.__annotations__ = seen.__doc__ = seen.__bind_methods__ = seen.__bases__ = seen.constructor = seen.__class__ = true;\n resolved_props = {};\n p = target = arguments[0].prototype;\n while (p && p !== Object.prototype) {\n props = Object.getOwnPropertyNames(p);\n for (var i = 0; i < props.length; i++) {\n seen[RS_bound_index(props[(typeof i === "number" && i < 0) ? props.length + i : i], seen)] = true;\n }\n p = Object.getPrototypeOf(p);\n }\n for (var c = 1; c < arguments.length; c++) {\n p = arguments[(typeof c === "number" && c < 0) ? arguments.length + c : c].prototype;\n while (p && p !== Object.prototype) {\n props = Object.getOwnPropertyNames(p);\n for (var i = 0; i < props.length; i++) {\n name = props[(typeof i === "number" && i < 0) ? props.length + i : i];\n if (seen[(typeof name === "number" && name < 0) ? seen.length + name : name]) {\n continue;\n }\n seen[(typeof name === "number" && name < 0) ? seen.length + name : name] = true;\n resolved_props[(typeof name === "number" && name < 0) ? resolved_props.length + name : name] = Object.getOwnPropertyDescriptor(p, name);\n }\n p = Object.getPrototypeOf(p);\n }\n }\n Object.defineProperties(target, resolved_props);\n};\nif (!RS_mixin.__module__) Object.defineProperties(RS_mixin, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_instanceof() {\n var obj, bases, q, cls, p;\n obj = arguments[0];\n bases = "";\n if (obj && obj.constructor && obj.constructor.prototype) {\n bases = obj.constructor.prototype.__bases__ || "";\n }\n for (var i = 1; i < arguments.length; i++) {\n q = arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i];\n if (obj instanceof q) {\n return true;\n }\n if ((q === Array || q === RS_list_constructor) && Array.isArray(obj)) {\n return true;\n }\n if (q === RS_str && (typeof obj === "string" || obj instanceof String)) {\n return true;\n }\n if (q === RS_int && typeof obj === "number" && Number.isInteger(obj)) {\n return true;\n }\n if (q === RS_float && typeof obj === "number" && !Number.isInteger(obj)) {\n return true;\n }\n if (bases.length > 1) {\n for (var c = 1; c < bases.length; c++) {\n cls = bases[(typeof c === "number" && c < 0) ? bases.length + c : c];\n while (cls) {\n if (q === cls) {\n return true;\n }\n p = Object.getPrototypeOf(cls.prototype);\n if (!p) {\n break;\n }\n cls = p.constructor;\n }\n }\n }\n }\n return false;\n};\nif (!RS_instanceof.__module__) Object.defineProperties(RS_instanceof, {\n __module__ : {value: "__main__"}\n});\nfunction sum(iterable, start) {\n var ans, iterator, r;\n if (Array.isArray(iterable)) {\n return iterable.reduce((function() {\n var RS_anonfunc = function (prev, cur) {\n return prev + cur;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["prev", "cur"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })(), start || 0);\n }\n ans = start || 0;\n iterator = iter(iterable);\n r = iterator.next();\n while (!r.done) {\n ans += r.value;\n r = iterator.next();\n }\n return ans;\n};\nif (!sum.__argnames__) Object.defineProperties(sum, {\n __argnames__ : {value: ["iterable", "start"]},\n __module__ : {value: "__main__"}\n});\n\nfunction map() {\n var iterators, func, args, ans;\n iterators = new Array(arguments.length - 1);\n func = arguments[0];\n args = new Array(arguments.length - 1);\n for (var i = 1; i < arguments.length; i++) {\n iterators[RS_bound_index(i - 1, iterators)] = iter(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n }\n ans = {\'_func\':func, \'_iterators\':iterators, \'_args\':args};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var r;\n for (var i = 0; i < this._iterators.length; i++) {\n r = (RS_expr_temp = this._iterators)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].next();\n if (r.done) {\n return {\'done\':true};\n }\n (RS_expr_temp = this._args)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] = r.value;\n }\n return {\'done\':false, \'value\':this._func.apply(undefined, this._args)};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n};\nif (!map.__module__) Object.defineProperties(map, {\n __module__ : {value: "__main__"}\n});\n\nfunction filter(func_or_none, iterable) {\n var func, ans;\n func = (func_or_none === null) ? RS_bool : func_or_none;\n ans = {\'_func\':func, \'_iterator\':RS_iter(iterable)};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var r;\n r = this._iterator.next();\n while (!r.done) {\n if (this._func(r.value)) {\n return r;\n }\n r = this._iterator.next();\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n};\nif (!filter.__argnames__) Object.defineProperties(filter, {\n __argnames__ : {value: ["func_or_none", "iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction zip() {\n var iterators, ans;\n iterators = new Array(arguments.length);\n for (var i = 0; i < arguments.length; i++) {\n iterators[(typeof i === "number" && i < 0) ? iterators.length + i : i] = iter(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n }\n ans = {\'_iterators\':iterators};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var args, r;\n args = new Array(this._iterators.length);\n for (var i = 0; i < this._iterators.length; i++) {\n r = (RS_expr_temp = this._iterators)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].next();\n if (r.done) {\n return {\'done\':true};\n }\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = r.value;\n }\n return {\'done\':false, \'value\':args};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n};\nif (!zip.__module__) Object.defineProperties(zip, {\n __module__ : {value: "__main__"}\n});\n\nfunction any(iterable) {\n var i;\n var RS_Iter0 = RS_Iterable(iterable);\n for (var RS_Index0 = 0; RS_Index0 < RS_Iter0.length; RS_Index0++) {\n i = RS_Iter0[RS_Index0];\n if (i) {\n return true;\n }\n }\n return false;\n};\nif (!any.__argnames__) Object.defineProperties(any, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction all(iterable) {\n var i;\n var RS_Iter1 = RS_Iterable(iterable);\n for (var RS_Index1 = 0; RS_Index1 < RS_Iter1.length; RS_Index1++) {\n i = RS_Iter1[RS_Index1];\n if (!i) {\n return false;\n }\n }\n return true;\n};\nif (!all.__argnames__) Object.defineProperties(all, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\nvar decimal_sep, define_str_func, RS_unpack, RS_orig_split, RS_orig_replace;\ndecimal_sep = 1.1.toLocaleString()[1];\nfunction RS_repr_js_builtin(x, as_array) {\n var ans, b, keys, key;\n ans = [];\n b = "{}";\n if (as_array) {\n b = "[]";\n for (var i = 0; i < x.length; i++) {\n ans.push(RS_repr(x[(typeof i === "number" && i < 0) ? x.length + i : i]));\n }\n } else {\n keys = Object.keys(x);\n for (var k = 0; k < keys.length; k++) {\n key = keys[(typeof k === "number" && k < 0) ? keys.length + k : k];\n ans.push(JSON.stringify(key) + ":" + RS_repr(x[(typeof key === "number" && key < 0) ? x.length + key : key]));\n }\n }\n return b[0] + ans.join(", ") + b[1];\n};\nif (!RS_repr_js_builtin.__argnames__) Object.defineProperties(RS_repr_js_builtin, {\n __argnames__ : {value: ["x", "as_array"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_html_element_to_string(elem) {\n var attrs, val, attr, ans;\n attrs = [];\n var RS_Iter0 = RS_Iterable(elem.attributes);\n for (var RS_Index0 = 0; RS_Index0 < RS_Iter0.length; RS_Index0++) {\n attr = RS_Iter0[RS_Index0];\n if (attr.specified) {\n val = attr.value;\n if (val.length > 10) {\n val = val.slice(0, 15) + "...";\n }\n val = JSON.stringify(val);\n attrs.push("" + RS_str.format("{}", attr.name) + "=" + RS_str.format("{}", val) + "");\n }\n }\n attrs = (attrs.length) ? " " + attrs.join(" ") : "";\n ans = "<" + RS_str.format("{}", elem.tagName) + "" + RS_str.format("{}", attrs) + ">";\n return ans;\n};\nif (!RS_html_element_to_string.__argnames__) Object.defineProperties(RS_html_element_to_string, {\n __argnames__ : {value: ["elem"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_repr(x) {\n var ans, name;\n if (x === null) {\n return "None";\n }\n if (x === undefined) {\n return "undefined";\n }\n ans = x;\n if (typeof x.__repr__ === "function") {\n ans = x.__repr__();\n } else if (x === true || x === false) {\n ans = (x) ? "True" : "False";\n } else if (Array.isArray(x)) {\n ans = RS_repr_js_builtin(x, true);\n } else if (typeof x === "function") {\n ans = x.toString();\n } else if (typeof x === "object" && !x.toString) {\n ans = RS_repr_js_builtin(x);\n } else {\n name = Object.prototype.toString.call(x).slice(8, -1);\n if (RS_not_equals("Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".indexOf(name), -1)) {\n return name + "([" + x.map((function() {\n var RS_anonfunc = function (i) {\n return str.format("0x{:02x}", i);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["i"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })()).join(", ") + "])";\n }\n if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) {\n ans = RS_html_element_to_string(x);\n } else {\n ans = (typeof x.toString === "function") ? x.toString() : x;\n }\n if (ans === "[object Object]") {\n return RS_repr_js_builtin(x);\n }\n try {\n ans = JSON.stringify(x);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n } \n }\n }\n return ans + "";\n};\nif (!RS_repr.__argnames__) Object.defineProperties(RS_repr, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_str(x) {\n var ans, name;\n if (x === null) {\n return "None";\n }\n if (x === undefined) {\n return "undefined";\n }\n ans = x;\n if (typeof x.__str__ === "function") {\n ans = x.__str__();\n } else if (typeof x.__repr__ === "function") {\n ans = x.__repr__();\n } else if (x === true || x === false) {\n ans = (x) ? "True" : "False";\n } else if (Array.isArray(x)) {\n ans = RS_repr_js_builtin(x, true);\n } else if (typeof x.toString === "function") {\n name = Object.prototype.toString.call(x).slice(8, -1);\n if (RS_not_equals("Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".indexOf(name), -1)) {\n return name + "([" + x.map((function() {\n var RS_anonfunc = function (i) {\n return str.format("0x{:02x}", i);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["i"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })()).join(", ") + "])";\n }\n if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) {\n ans = RS_html_element_to_string(x);\n } else {\n ans = x.toString();\n }\n if (ans === "[object Object]") {\n ans = RS_repr_js_builtin(x);\n }\n } else if (typeof x === "object" && !x.toString) {\n ans = RS_repr_js_builtin(x);\n }\n return ans + "";\n};\nif (!RS_str.__argnames__) Object.defineProperties(RS_str, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\ndefine_str_func = (function() {\n var RS_anonfunc = function (name, func) {\n var f;\n (RS_expr_temp = RS_str.prototype)[(typeof name === "number" && name < 0) ? RS_expr_temp.length + name : name] = func;\n RS_str[(typeof name === "number" && name < 0) ? RS_str.length + name : name] = f = func.call.bind(func);\n if (func.__argnames__) {\n Object.defineProperty(f, "__argnames__", (function(){\n var RS_d = {};\n RS_d["value"] = [\'string\'].concat(func.__argnames__);\n return RS_d;\n }).call(this));\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["name", "func"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_unpack = [String.prototype.split.call.bind(String.prototype.split), String.prototype.replace.call.bind(String.prototype.replace)];\nRS_orig_split = RS_unpack[0];\nRS_orig_replace = RS_unpack[1];\ndefine_str_func("format", (function() {\n var RS_anonfunc = function () {\n var template, args, kwargs, explicit, implicit, idx, split, ans, pos, in_brace, markup, ch;\n template = this;\n if (template === undefined) {\n throw new TypeError("Template is required");\n }\n args = Array.prototype.slice.call(arguments);\n kwargs = {};\n if (args[args.length-1] && args[args.length-1][RS_kwargs_symbol] !== undefined) {\n kwargs = args[args.length-1];\n args = args.slice(0, -1);\n }\n explicit = implicit = false;\n idx = 0;\n split = RS_orig_split;\n if (RS_str.format._template_resolve_pat === undefined) {\n RS_str.format._template_resolve_pat = /[.\\[]/;\n }\n function resolve(arg, object) {\n var RS_unpack, first, key, rest, ans;\n if (!arg) {\n return object;\n }\n RS_unpack = [arg[0], arg.slice(1)];\n first = RS_unpack[0];\n arg = RS_unpack[1];\n key = split(arg, RS_str.format._template_resolve_pat, 1)[0];\n rest = arg.slice(key.length);\n ans = (first === "[") ? object[RS_bound_index(key.slice(0, -1), object)] : getattr(object, key);\n if (ans === undefined) {\n throw new KeyError((first === "[") ? key.slice(0, -1) : key);\n }\n return resolve(rest, ans);\n };\n if (!resolve.__argnames__) Object.defineProperties(resolve, {\n __argnames__ : {value: ["arg", "object"]},\n __module__ : {value: "__main__"}\n });\n\n function resolve_format_spec(format_spec) {\n if (RS_str.format._template_resolve_fs_pat === undefined) {\n RS_str.format._template_resolve_fs_pat = /[{]([a-zA-Z0-9_]+)[}]/g;\n }\n return format_spec.replace(RS_str.format._template_resolve_fs_pat, (function() {\n var RS_anonfunc = function (match, key) {\n if (!Object.prototype.hasOwnProperty.call(kwargs, key)) {\n return "";\n }\n return "" + kwargs[(typeof key === "number" && key < 0) ? kwargs.length + key : key];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["match", "key"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })());\n };\n if (!resolve_format_spec.__argnames__) Object.defineProperties(resolve_format_spec, {\n __argnames__ : {value: ["format_spec"]},\n __module__ : {value: "__main__"}\n });\n\n function set_comma(ans, comma) {\n var sep;\n if (comma !== ",") {\n sep = 1234;\n sep = sep.toLocaleString(undefined, {useGrouping: true})[1];\n ans = str.replace(ans, sep, comma);\n }\n return ans;\n };\n if (!set_comma.__argnames__) Object.defineProperties(set_comma, {\n __argnames__ : {value: ["ans", "comma"]},\n __module__ : {value: "__main__"}\n });\n\n function safe_comma(value, comma) {\n try {\n return set_comma(value.toLocaleString(undefined, {useGrouping: true}), comma);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n return value.toString(10);\n } \n }\n };\n if (!safe_comma.__argnames__) Object.defineProperties(safe_comma, {\n __argnames__ : {value: ["value", "comma"]},\n __module__ : {value: "__main__"}\n });\n\n function safe_fixed(value, precision, comma) {\n if (!comma) {\n return value.toFixed(precision);\n }\n try {\n return set_comma(value.toLocaleString(undefined, {useGrouping: true, minimumFractionDigits: precision, maximumFractionDigits: precision}), comma);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n return value.toFixed(precision);\n } \n }\n };\n if (!safe_fixed.__argnames__) Object.defineProperties(safe_fixed, {\n __argnames__ : {value: ["value", "precision", "comma"]},\n __module__ : {value: "__main__"}\n });\n\n function apply_formatting(value, format_spec) {\n var RS_unpack, fill, align, sign, fhash, zeropad, width, comma, precision, ftype, is_numeric, is_int, lftype, code, prec, exp, nval, is_positive, left, right;\n if (format_spec.indexOf("{") !== -1) {\n format_spec = resolve_format_spec(format_spec);\n }\n if (RS_str.format._template_format_pat === undefined) {\n RS_str.format._template_format_pat = /([^{}](?=[<>=^]))?([<>=^])?([-+\\x20])?(\\#)?(0)?(\\d+)?([,_])?(?:\\.(\\d+))?([bcdeEfFgGnosxX%])?/;\n }\n try {\n RS_unpack = format_spec.match(RS_str.format._template_format_pat).slice(1);\nRS_unpack = RS_unpack_asarray(9, RS_unpack);\n fill = RS_unpack[0];\n align = RS_unpack[1];\n sign = RS_unpack[2];\n fhash = RS_unpack[3];\n zeropad = RS_unpack[4];\n width = RS_unpack[5];\n comma = RS_unpack[6];\n precision = RS_unpack[7];\n ftype = RS_unpack[8];\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof TypeError) {\n return value;\n } else {\n throw RS_Exception;\n }\n }\n if (zeropad) {\n fill = fill || "0";\n align = align || "=";\n } else {\n fill = fill || " ";\n align = align || ">";\n }\n is_numeric = Number(value) === value;\n is_int = is_numeric && value % 1 === 0;\n precision = parseInt(precision, 10);\n lftype = (ftype || "").toLowerCase();\n if (ftype === "n") {\n is_numeric = true;\n if (is_int) {\n if (comma) {\n throw new ValueError("Cannot specify \',\' with \'n\'");\n }\n value = parseInt(value, 10).toLocaleString();\n } else {\n value = parseFloat(value).toLocaleString();\n }\n } else if ([\'b\', \'c\', \'d\', \'o\', \'x\'].indexOf(lftype) !== -1) {\n value = parseInt(value, 10);\n is_numeric = true;\n if (!isNaN(value)) {\n if (ftype === "b") {\n value = (value >>> 0).toString(2);\n if (fhash) {\n value = "0b" + value;\n }\n } else if (ftype === "c") {\n if (value > 65535) {\n code = value - 65536;\n value = String.fromCharCode(55296 + (code >> 10), 56320 + (code & 1023));\n } else {\n value = String.fromCharCode(value);\n }\n } else if (ftype === "d") {\n if (comma) {\n value = safe_comma(value, comma);\n } else {\n value = value.toString(10);\n }\n } else if (ftype === "o") {\n value = value.toString(8);\n if (fhash) {\n value = "0o" + value;\n }\n } else if (lftype === "x") {\n value = value.toString(16);\n value = (ftype === "x") ? value.toLowerCase() : value.toUpperCase();\n if (fhash) {\n value = "0x" + value;\n }\n }\n }\n } else if ([\'e\',\'f\',\'g\',\'%\'].indexOf(lftype) !== -1) {\n is_numeric = true;\n value = parseFloat(value);\n prec = (isNaN(precision)) ? 6 : precision;\n if (lftype === "e") {\n value = value.toExponential(prec);\n value = (ftype === "E") ? value.toUpperCase() : value.toLowerCase();\n } else if (lftype === "f") {\n value = safe_fixed(value, prec, comma);\n value = (ftype === "F") ? value.toUpperCase() : value.toLowerCase();\n } else if (lftype === "%") {\n value *= 100;\n value = safe_fixed(value, prec, comma) + "%";\n } else if (lftype === "g") {\n prec = max(1, prec);\n exp = parseInt(split(value.toExponential(prec - 1).toLowerCase(), "e")[1], 10);\n if (-4 <= exp && exp < prec) {\n value = safe_fixed(value, prec - 1 - exp, comma);\n } else {\n value = value.toExponential(prec - 1);\n }\n value = value.replace(/0+$/g, "");\n if (value[value.length-1] === decimal_sep) {\n value = value.slice(0, -1);\n }\n if (ftype === "G") {\n value = value.toUpperCase();\n }\n }\n } else {\n if (comma) {\n value = parseInt(value, 10);\n if (isNaN(value)) {\n throw new ValueError("Must use numbers with , or _");\n }\n value = safe_comma(value, comma);\n }\n value += "";\n if (!isNaN(precision)) {\n value = value.slice(0, precision);\n }\n }\n value += "";\n if (is_numeric && sign) {\n nval = Number(value);\n is_positive = !isNaN(nval) && nval >= 0;\n if (is_positive && (sign === " " || sign === "+")) {\n value = sign + value;\n }\n }\n function repeat(char, num) {\n return (new Array(num+1)).join(char);\n };\n if (!repeat.__argnames__) Object.defineProperties(repeat, {\n __argnames__ : {value: ["char", "num"]},\n __module__ : {value: "__main__"}\n });\n\n if (is_numeric && width && width[0] === "0") {\n width = width.slice(1);\n RS_unpack = ["0", "="];\n fill = RS_unpack[0];\n align = RS_unpack[1];\n }\n width = parseInt(width || "-1", 10);\n if (isNaN(width)) {\n throw new ValueError("Invalid width specification: " + width);\n }\n if (fill && value.length < width) {\n if (align === "<") {\n value = value + repeat(fill, width - value.length);\n } else if (align === ">") {\n value = repeat(fill, width - value.length) + value;\n } else if (align === "^") {\n left = Math.floor((width - value.length) / 2);\n right = width - left - value.length;\n value = repeat(fill, left) + value + repeat(fill, right);\n } else if (align === "=") {\n if (RS_in(value[0], "+- ")) {\n value = value[0] + repeat(fill, width - value.length) + value.slice(1);\n } else {\n value = repeat(fill, width - value.length) + value;\n }\n } else {\n throw new ValueError("Unrecognized alignment: " + align);\n }\n }\n return value;\n };\n if (!apply_formatting.__argnames__) Object.defineProperties(apply_formatting, {\n __argnames__ : {value: ["value", "format_spec"]},\n __module__ : {value: "__main__"}\n });\n\n function parse_markup(markup) {\n var key, transformer, format_spec, pos, state, ch;\n key = transformer = format_spec = "";\n pos = 0;\n state = 0;\n while (pos < markup.length) {\n ch = markup[(typeof pos === "number" && pos < 0) ? markup.length + pos : pos];\n if (state === 0) {\n if (ch === "!") {\n state = 1;\n } else if (ch === ":") {\n state = 2;\n } else {\n key += ch;\n }\n } else if (state === 1) {\n if (ch === ":") {\n state = 2;\n } else {\n transformer += ch;\n }\n } else {\n format_spec += ch;\n }\n pos += 1;\n }\n return [key, transformer, format_spec];\n };\n if (!parse_markup.__argnames__) Object.defineProperties(parse_markup, {\n __argnames__ : {value: ["markup"]},\n __module__ : {value: "__main__"}\n });\n\n function render_markup(markup) {\n var RS_unpack, key, transformer, format_spec, lkey, nvalue, object, ans;\n RS_unpack = parse_markup(markup);\nRS_unpack = RS_unpack_asarray(3, RS_unpack);\n key = RS_unpack[0];\n transformer = RS_unpack[1];\n format_spec = RS_unpack[2];\n if (transformer && [\'a\', \'r\', \'s\'].indexOf(transformer) === -1) {\n throw new ValueError("Unknown conversion specifier: " + transformer);\n }\n lkey = key.length && split(key, /[.\\[]/, 1)[0];\n if (lkey) {\n explicit = true;\n if (implicit) {\n throw new ValueError("cannot switch from automatic field numbering to manual field specification");\n }\n nvalue = parseInt(lkey);\n object = (isNaN(nvalue)) ? kwargs[(typeof lkey === "number" && lkey < 0) ? kwargs.length + lkey : lkey] : args[(typeof nvalue === "number" && nvalue < 0) ? args.length + nvalue : nvalue];\n if (object === undefined) {\n if (isNaN(nvalue)) {\n throw new KeyError(lkey);\n }\n throw new IndexError(lkey);\n }\n object = resolve(key.slice(lkey.length), object);\n } else {\n implicit = true;\n if (explicit) {\n throw new ValueError("cannot switch from manual field specification to automatic field numbering");\n }\n if (idx >= args.length) {\n throw new IndexError("Not enough arguments to match template: " + template);\n }\n object = args[(typeof idx === "number" && idx < 0) ? args.length + idx : idx];\n idx += 1;\n }\n if (typeof object === "function") {\n object = object();\n }\n ans = "" + object;\n if (format_spec) {\n ans = apply_formatting(ans, format_spec);\n }\n return ans;\n };\n if (!render_markup.__argnames__) Object.defineProperties(render_markup, {\n __argnames__ : {value: ["markup"]},\n __module__ : {value: "__main__"}\n });\n\n ans = "";\n pos = 0;\n in_brace = 0;\n markup = "";\n while (pos < template.length) {\n ch = template[(typeof pos === "number" && pos < 0) ? template.length + pos : pos];\n if (in_brace) {\n if (ch === "{") {\n in_brace += 1;\n markup += "{";\n } else if (ch === "}") {\n in_brace -= 1;\n if (in_brace > 0) {\n markup += "}";\n } else {\n ans += render_markup(markup);\n }\n } else {\n markup += ch;\n }\n } else {\n if (ch === "{") {\n if (template[RS_bound_index(pos + 1, template)] === "{") {\n pos += 1;\n ans += "{";\n } else {\n in_brace = 1;\n markup = "";\n }\n } else {\n ans += ch;\n if (ch === "}" && template[RS_bound_index(pos + 1, template)] === "}") {\n pos += 1;\n }\n }\n }\n pos += 1;\n }\n if (in_brace) {\n throw new ValueError("expected \'}\' before end of string");\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("capitalize", (function() {\n var RS_anonfunc = function () {\n var string;\n string = this;\n if (string) {\n string = string[0].toUpperCase() + string.slice(1).toLowerCase();\n }\n return string;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("center", (function() {\n var RS_anonfunc = function (width, fill) {\n var left, right;\n left = Math.floor((width - this.length) / 2);\n right = width - left - this.length;\n fill = fill || " ";\n return new Array(left+1).join(fill) + this + new Array(right+1).join(fill);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width", "fill"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("count", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var string, RS_unpack, pos, step, ans;\n string = this;\n start = start || 0;\n end = end || string.length;\n if (start < 0 || end < 0) {\n string = string.slice(start, end);\n RS_unpack = [0, string.length];\n start = RS_unpack[0];\n end = RS_unpack[1];\n }\n pos = start;\n step = needle.length;\n if (!step) {\n return 0;\n }\n ans = 0;\n while (pos !== -1) {\n pos = string.indexOf(needle, pos);\n if (pos !== -1) {\n ans += 1;\n pos += step;\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("endswith", (function() {\n var RS_anonfunc = function (suffixes, start, end) {\n var string, q;\n string = this;\n start = start || 0;\n if (typeof suffixes === "string") {\n suffixes = [suffixes];\n }\n if (end !== undefined) {\n string = string.slice(0, end);\n }\n for (var i = 0; i < suffixes.length; i++) {\n q = suffixes[(typeof i === "number" && i < 0) ? suffixes.length + i : i];\n if (string.indexOf(q, Math.max(start, string.length - q.length)) !== -1) {\n return true;\n }\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["suffixes", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("startswith", (function() {\n var RS_anonfunc = function (prefixes, start, end) {\n var prefix;\n start = start || 0;\n if (typeof prefixes === "string") {\n prefixes = [prefixes];\n }\n for (var i = 0; i < prefixes.length; i++) {\n prefix = prefixes[(typeof i === "number" && i < 0) ? prefixes.length + i : i];\n end = (end === undefined) ? this.length : end;\n if (end - start >= prefix.length && prefix === this.slice(start, start + prefix.length)) {\n return true;\n }\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["prefixes", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("find", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n while (start < 0) {\n start += this.length;\n }\n ans = this.indexOf(needle, start);\n if (end !== undefined && ans !== -1) {\n while (end < 0) {\n end += this.length;\n }\n if (ans >= end - needle.length) {\n return -1;\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rfind", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n while (end < 0) {\n end += this.length;\n }\n ans = this.lastIndexOf(needle, end - 1);\n if (start !== undefined && ans !== -1) {\n while (start < 0) {\n start += this.length;\n }\n if (ans < start) {\n return -1;\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("index", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n ans = RS_str.prototype.find.apply(this, arguments);\n if (ans === -1) {\n throw new ValueError("substring not found");\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rindex", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n ans = RS_str.prototype.rfind.apply(this, arguments);\n if (ans === -1) {\n throw new ValueError("substring not found");\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("islower", (function() {\n var RS_anonfunc = function () {\n return this.length > 0 && this.toLowerCase() === this.toString();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("isupper", (function() {\n var RS_anonfunc = function () {\n return this.length > 0 && this.toUpperCase() === this.toString();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("isspace", (function() {\n var RS_anonfunc = function () {\n return this.length > 0 && /^\\s+$/.test(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("join", (function() {\n var RS_anonfunc = function (iterable) {\n var ans, r;\n if (Array.isArray(iterable)) {\n return iterable.join(this);\n }\n ans = "";\n r = iterable.next();\n while (!r.done) {\n if (ans) {\n ans += this;\n }\n ans += r.value;\n r = iterable.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("ljust", (function() {\n var RS_anonfunc = function (width, fill) {\n var string;\n string = this;\n if (width > string.length) {\n fill = fill || " ";\n string += new Array(width - string.length + 1).join(fill);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width", "fill"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rjust", (function() {\n var RS_anonfunc = function (width, fill) {\n var string;\n string = this;\n if (width > string.length) {\n fill = fill || " ";\n string = new Array(width - string.length + 1).join(fill) + string;\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width", "fill"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("lower", (function() {\n var RS_anonfunc = function () {\n return this.toLowerCase();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("upper", (function() {\n var RS_anonfunc = function () {\n return this.toUpperCase();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("lstrip", (function() {\n var RS_anonfunc = function (chars) {\n var string, pos;\n string = this;\n pos = 0;\n chars = chars || RS_str.whitespace;\n while (chars.indexOf(string[(typeof pos === "number" && pos < 0) ? string.length + pos : pos]) !== -1) {\n pos += 1;\n }\n if (pos) {\n string = string.slice(pos);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["chars"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rstrip", (function() {\n var RS_anonfunc = function (chars) {\n var string, pos;\n string = this;\n pos = string.length - 1;\n chars = chars || RS_str.whitespace;\n while (chars.indexOf(string[(typeof pos === "number" && pos < 0) ? string.length + pos : pos]) !== -1) {\n pos -= 1;\n }\n if (pos < string.length - 1) {\n string = string.slice(0, pos + 1);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["chars"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("strip", (function() {\n var RS_anonfunc = function (chars) {\n return RS_str.prototype.lstrip.call(RS_str.prototype.rstrip.call(this, chars), chars);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["chars"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("partition", (function() {\n var RS_anonfunc = function (sep) {\n var idx;\n idx = this.indexOf(sep);\n if (idx === -1) {\n return [this, "", ""];\n }\n return [this.slice(0, idx), sep, this.slice(idx + sep.length)];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rpartition", (function() {\n var RS_anonfunc = function (sep) {\n var idx;\n idx = this.lastIndexOf(sep);\n if (idx === -1) {\n return ["", "", this];\n }\n return [this.slice(0, idx), sep, this.slice(idx + sep.length)];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("replace", (function() {\n var RS_anonfunc = function (old, repl, count) {\n var string, pos, idx;\n string = this;\n if (count === 1) {\n return RS_orig_replace(string, old, repl);\n }\n if (count < 1) {\n return string;\n }\n count = count || Number.MAX_VALUE;\n pos = 0;\n while (count > 0) {\n count -= 1;\n idx = string.indexOf(old, pos);\n if (idx === -1) {\n break;\n }\n pos = idx + repl.length;\n string = string.slice(0, idx) + repl + string.slice(idx + old.length);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["old", "repl", "count"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("split", (function() {\n var RS_anonfunc = function (sep, maxsplit) {\n var split, ans, extra, parts;\n if (maxsplit === 0) {\n return RS_list_decorate([ this ]);\n }\n split = RS_orig_split;\n if (sep === undefined || sep === null) {\n if (maxsplit > 0) {\n ans = split(this, /(\\s+)/);\n extra = "";\n parts = [];\n for (var i = 0; i < ans.length; i++) {\n if (parts.length >= maxsplit + 1) {\n extra += ans[(typeof i === "number" && i < 0) ? ans.length + i : i];\n } else if (i % 2 === 0) {\n parts.push(ans[(typeof i === "number" && i < 0) ? ans.length + i : i]);\n }\n }\n parts[parts.length-1] += extra;\n ans = parts;\n } else {\n ans = split(this, /\\s+/);\n }\n } else {\n if (sep === "") {\n throw new ValueError("empty separator");\n }\n ans = split(this, sep);\n if (maxsplit > 0 && ans.length > maxsplit) {\n extra = ans.slice(maxsplit).join(sep);\n ans = ans.slice(0, maxsplit);\n ans.push(extra);\n }\n }\n return RS_list_decorate(ans);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep", "maxsplit"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rsplit", (function() {\n var RS_anonfunc = function (sep, maxsplit) {\n var split, ans, is_space, pos, current, spc, ch, end, idx;\n if (!maxsplit) {\n return RS_str.prototype.split.call(this, sep);\n }\n split = RS_orig_split;\n if (sep === undefined || sep === null) {\n if (maxsplit > 0) {\n ans = [];\n is_space = /\\s/;\n pos = this.length - 1;\n current = "";\n while (pos > -1 && maxsplit > 0) {\n spc = false;\n ch = (RS_expr_temp = this)[(typeof pos === "number" && pos < 0) ? RS_expr_temp.length + pos : pos];\n while (pos > -1 && is_space.test(ch)) {\n spc = true;\n ch = this[--pos];\n }\n if (spc) {\n if (current) {\n ans.push(current);\n maxsplit -= 1;\n }\n current = ch;\n } else {\n current += ch;\n }\n pos -= 1;\n }\n ans.push(this.slice(0, pos + 1) + current);\n ans.reverse();\n } else {\n ans = split(this, /\\s+/);\n }\n } else {\n if (sep === "") {\n throw new ValueError("empty separator");\n }\n ans = [];\n pos = end = this.length;\n while (pos > -1 && maxsplit > 0) {\n maxsplit -= 1;\n idx = this.lastIndexOf(sep, pos);\n if (idx === -1) {\n break;\n }\n ans.push(this.slice(idx + sep.length, end));\n pos = idx - 1;\n end = idx;\n }\n ans.push(this.slice(0, end));\n ans.reverse();\n }\n return RS_list_decorate(ans);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep", "maxsplit"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("splitlines", (function() {\n var RS_anonfunc = function (keepends) {\n var split, parts, ans;\n split = RS_orig_split;\n if (keepends) {\n parts = split(this, /((?:\\r?\\n)|\\r)/);\n ans = [];\n for (var i = 0; i < parts.length; i++) {\n if (i % 2 === 0) {\n ans.push(parts[(typeof i === "number" && i < 0) ? parts.length + i : i]);\n } else {\n ans[ans.length-1] += parts[(typeof i === "number" && i < 0) ? parts.length + i : i];\n }\n }\n } else {\n ans = split(this, /(?:\\r?\\n)|\\r/);\n }\n return RS_list_decorate(ans);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["keepends"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("swapcase", (function() {\n var RS_anonfunc = function () {\n var ans, a, b;\n ans = new Array(this.length);\n for (var i = 0; i < ans.length; i++) {\n a = (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n b = a.toLowerCase();\n if (a === b) {\n b = a.toUpperCase();\n }\n ans[(typeof i === "number" && i < 0) ? ans.length + i : i] = b;\n }\n return ans.join("");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("zfill", (function() {\n var RS_anonfunc = function (width) {\n var string;\n string = this;\n if (width > string.length) {\n string = new Array(width - string.length + 1).join("0") + string;\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\nRS_str.uchrs = (function() {\n var RS_anonfunc = function (string, with_positions) {\n return (function(){\n var RS_d = {};\n RS_d["_string"] = string;\n RS_d["_pos"] = 0;\n RS_d[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["next"] = (function() {\n var RS_anonfunc = function () {\n var length, pos, value, ans, extra;\n length = this._string.length;\n if (this._pos >= length) {\n return (function(){\n var RS_d = {};\n RS_d["done"] = true;\n return RS_d;\n }).call(this);\n }\n pos = this._pos;\n value = this._string.charCodeAt(this._pos++);\n ans = "\\ufffd";\n if (55296 <= value && value <= 56319) {\n if (this._pos < length) {\n extra = this._string.charCodeAt(this._pos++);\n if ((extra & 56320) === 56320) {\n ans = String.fromCharCode(value, extra);\n }\n }\n } else if ((value & 56320) !== 56320) {\n ans = String.fromCharCode(value);\n }\n if (with_positions) {\n return (function(){\n var RS_d = {};\n RS_d["done"] = false;\n RS_d["value"] = RS_list_decorate([ pos, ans ]);\n return RS_d;\n }).call(this);\n } else {\n return (function(){\n var RS_d = {};\n RS_d["done"] = false;\n RS_d["value"] = ans;\n return RS_d;\n }).call(this);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["string", "with_positions"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_str.uslice = (function() {\n var RS_anonfunc = function (string, start, end) {\n var items, iterator, r;\n items = [];\n iterator = RS_str.uchrs(string);\n r = iterator.next();\n while (!r.done) {\n items.push(r.value);\n r = iterator.next();\n }\n return items.slice(start || 0, (end === undefined) ? items.length : end).join("");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["string", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_str.ulen = (function() {\n var RS_anonfunc = function (string) {\n var iterator, r, ans;\n iterator = RS_str.uchrs(string);\n r = iterator.next();\n ans = 0;\n while (!r.done) {\n r = iterator.next();\n ans += 1;\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["string"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_str.ascii_lowercase = "abcdefghijklmnopqrstuvwxyz";\nRS_str.ascii_uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\nRS_str.ascii_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\nRS_str.digits = "0123456789";\nRS_str.punctuation = "!\\"#$%&\'()*+,-./:;<=>?@[\\\\]^_`{|}~";\nRS_str.printable = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\\"#$%&\'()*+,-./:;<=>?@[\\\\]^_`{|}~ \\t\\n\\r\\u000b\\f";\nRS_str.whitespace = " \\t\\n\\r\\u000b\\f";\ndefine_str_func = undefined;\nvar str = RS_str, repr = RS_repr;;\n var RS_modules = {};\n RS_modules.utils = {};\n RS_modules.errors = {};\n RS_modules.unicode_aliases = {};\n RS_modules.ast = {};\n RS_modules.string_interpolation = {};\n RS_modules.tokenizer = {};\n RS_modules.parse = {};\n RS_modules.output = {};\n RS_modules["output.stream"] = {};\n RS_modules["output.statements"] = {};\n RS_modules["output.exceptions"] = {};\n RS_modules["output.utils"] = {};\n RS_modules["output.loops"] = {};\n RS_modules["output.operators"] = {};\n RS_modules["output.functions"] = {};\n RS_modules["output.classes"] = {};\n RS_modules["output.literals"] = {};\n RS_modules["output.comments"] = {};\n RS_modules["output.modules"] = {};\n RS_modules["output.codegen"] = {};\n\n (function(){\n var __name__ = "utils";\n var has_prop, MAP;\n has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);\n function array_to_hash(a) {\n var ret, i;\n ret = Object.create(null);\n var RS_Iter0 = RS_Iterable(range(len(a)));\n for (var RS_Index0 = 0; RS_Index0 < RS_Iter0.length; RS_Index0++) {\n i = RS_Iter0[RS_Index0];\n ret[RS_bound_index(a[(typeof i === "number" && i < 0) ? a.length + i : i], ret)] = true;\n }\n return ret;\n };\n if (!array_to_hash.__argnames__) Object.defineProperties(array_to_hash, {\n __argnames__ : {value: ["a"]},\n __module__ : {value: "utils"}\n });\n\n function slice(a, start) {\n return Array.prototype.slice.call(a, start || 0);\n };\n if (!slice.__argnames__) Object.defineProperties(slice, {\n __argnames__ : {value: ["a", "start"]},\n __module__ : {value: "utils"}\n });\n\n function characters(str_) {\n return str_.split("");\n };\n if (!characters.__argnames__) Object.defineProperties(characters, {\n __argnames__ : {value: ["str_"]},\n __module__ : {value: "utils"}\n });\n\n function member(name, array) {\n var i;\n for (var RS_Index1 = array.length - 1; RS_Index1 > -1; RS_Index1-=1) {\n i = RS_Index1;\n if (array[(typeof i === "number" && i < 0) ? array.length + i : i] === name) {\n return true;\n }\n }\n return false;\n };\n if (!member.__argnames__) Object.defineProperties(member, {\n __argnames__ : {value: ["name", "array"]},\n __module__ : {value: "utils"}\n });\n\n function repeat_string(str_, i) {\n var d;\n if (i <= 0) {\n return "";\n }\n if (i === 1) {\n return str_;\n }\n d = repeat_string(str_, i >> 1);\n d += d;\n if (i & 1) {\n d += str_;\n }\n return d;\n };\n if (!repeat_string.__argnames__) Object.defineProperties(repeat_string, {\n __argnames__ : {value: ["str_", "i"]},\n __module__ : {value: "utils"}\n });\n\n function DefaultsError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n DefaultsError.prototype.__init__.apply(this, arguments);\n }\n RS_extends(DefaultsError, ValueError);\n DefaultsError.prototype.__init__ = function __init__(name, defs) {\n var self = this;\n ValueError.prototype.__init__.call(self, name + " is not a supported option. Supported options are: " + str(Object.keys(defs)));\n };\n if (!DefaultsError.prototype.__init__.__argnames__) Object.defineProperties(DefaultsError.prototype.__init__, {\n __argnames__ : {value: ["name", "defs"]},\n __module__ : {value: "utils"}\n });\n DefaultsError.__argnames__ = DefaultsError.prototype.__init__.__argnames__;\n DefaultsError.__handles_kwarg_interpolation__ = DefaultsError.prototype.__init__.__handles_kwarg_interpolation__;\n DefaultsError.prototype.__repr__ = function __repr__ () {\n if(ValueError.prototype.__repr__) return ValueError.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n DefaultsError.prototype.__str__ = function __str__ () {\n if(ValueError.prototype.__str__) return ValueError.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(DefaultsError.prototype, "__bases__", {value: [ValueError]});\n\n function defaults(args, defs, croak) {\n var ret, i;\n if (args === true) {\n args = Object.create(null);\n }\n ret = args || Object.create(null);\n if (croak) {\n var RS_Iter2 = RS_Iterable(ret);\n for (var RS_Index2 = 0; RS_Index2 < RS_Iter2.length; RS_Index2++) {\n i = RS_Iter2[RS_Index2];\n if (!has_prop(defs, i)) {\n throw new DefaultsError(i, defs);\n }\n }\n }\n var RS_Iter3 = RS_Iterable(defs);\n for (var RS_Index3 = 0; RS_Index3 < RS_Iter3.length; RS_Index3++) {\n i = RS_Iter3[RS_Index3];\n ret[(typeof i === "number" && i < 0) ? ret.length + i : i] = (args && has_prop(args, i)) ? args[(typeof i === "number" && i < 0) ? args.length + i : i] : defs[(typeof i === "number" && i < 0) ? defs.length + i : i];\n }\n return ret;\n };\n if (!defaults.__argnames__) Object.defineProperties(defaults, {\n __argnames__ : {value: ["args", "defs", "croak"]},\n __module__ : {value: "utils"}\n });\n\n function merge(obj, ext) {\n var i;\n var RS_Iter4 = RS_Iterable(ext);\n for (var RS_Index4 = 0; RS_Index4 < RS_Iter4.length; RS_Index4++) {\n i = RS_Iter4[RS_Index4];\n obj[(typeof i === "number" && i < 0) ? obj.length + i : i] = ext[(typeof i === "number" && i < 0) ? ext.length + i : i];\n }\n return obj;\n };\n if (!merge.__argnames__) Object.defineProperties(merge, {\n __argnames__ : {value: ["obj", "ext"]},\n __module__ : {value: "utils"}\n });\n\n function noop() {\n };\n if (!noop.__module__) Object.defineProperties(noop, {\n __module__ : {value: "utils"}\n });\n\n MAP = (function() {\n var RS_anonfunc = function () {\n var skip;\n function MAP(a, f, backwards) {\n var ret, top, i;\n ret = RS_list_decorate([]);\n top = RS_list_decorate([]);\n function doit() {\n var val, is_last;\n val = f(a[(typeof i === "number" && i < 0) ? a.length + i : i], i);\n is_last = RS_instanceof(val, Last);\n if (is_last) {\n val = val.v;\n }\n if (RS_instanceof(val, AtTop)) {\n val = val.v;\n if (RS_instanceof(val, Splice)) {\n top.push.apply(top, (backwards) ? val.v.slice().reverse() : val.v);\n } else {\n top.push(val);\n }\n } else if (val !== skip) {\n if (RS_instanceof(val, Splice)) {\n ret.push.apply(ret, (backwards) ? val.v.slice().reverse() : val.v);\n } else {\n ret.push(val);\n }\n }\n return is_last;\n };\n if (!doit.__module__) Object.defineProperties(doit, {\n __module__ : {value: "utils"}\n });\n\n if (Array.isArray(a)) {\n if (backwards) {\n for (var RS_Index5 = a.length - 1; RS_Index5 > -1; RS_Index5-=1) {\n i = RS_Index5;\n if (doit()) {\n break;\n }\n }\n ret.reverse();\n top.reverse();\n } else {\n var RS_Iter6 = RS_Iterable(range(len(a)));\n for (var RS_Index6 = 0; RS_Index6 < RS_Iter6.length; RS_Index6++) {\n i = RS_Iter6[RS_Index6];\n if (doit()) {\n break;\n }\n }\n }\n } else {\n var RS_Iter7 = RS_Iterable(a);\n for (var RS_Index7 = 0; RS_Index7 < RS_Iter7.length; RS_Index7++) {\n i = RS_Iter7[RS_Index7];\n if (doit()) {\n break;\n }\n }\n }\n return top.concat(ret);\n };\n if (!MAP.__argnames__) Object.defineProperties(MAP, {\n __argnames__ : {value: ["a", "f", "backwards"]},\n __module__ : {value: "utils"}\n });\n\n MAP.at_top = (function() {\n var RS_anonfunc = function (val) {\n return new AtTop(val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "utils"}\n });\n return RS_anonfunc;\n })();\n MAP.splice = (function() {\n var RS_anonfunc = function (val) {\n return new Splice(val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "utils"}\n });\n return RS_anonfunc;\n })();\n MAP.last = (function() {\n var RS_anonfunc = function (val) {\n return new Last(val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "utils"}\n });\n return RS_anonfunc;\n })();\n skip = MAP.skip = Object.create(null);\n function AtTop(val) {\n this.v = val;\n };\n if (!AtTop.__argnames__) Object.defineProperties(AtTop, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "utils"}\n });\n\n function Splice(val) {\n this.v = val;\n };\n if (!Splice.__argnames__) Object.defineProperties(Splice, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "utils"}\n });\n\n function Last(val) {\n this.v = val;\n };\n if (!Last.__argnames__) Object.defineProperties(Last, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "utils"}\n });\n\n return MAP;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "utils"}\n });\n return RS_anonfunc;\n })().call(this);\n function push_uniq(array, el) {\n if (array.indexOf(el) < 0) {\n array.push(el);\n }\n };\n if (!push_uniq.__argnames__) Object.defineProperties(push_uniq, {\n __argnames__ : {value: ["array", "el"]},\n __module__ : {value: "utils"}\n });\n\n function string_template(text, props) {\n return text.replace(/\\{(.+?)\\}/g, (function() {\n var RS_anonfunc = function (str_, p) {\n return props[(typeof p === "number" && p < 0) ? props.length + p : p];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["str_", "p"]},\n __module__ : {value: "utils"}\n });\n return RS_anonfunc;\n })());\n };\n if (!string_template.__argnames__) Object.defineProperties(string_template, {\n __argnames__ : {value: ["text", "props"]},\n __module__ : {value: "utils"}\n });\n\n function remove(array, el) {\n var i;\n for (var RS_Index8 = array.length - 1; RS_Index8 > -1; RS_Index8-=1) {\n i = RS_Index8;\n if (array[(typeof i === "number" && i < 0) ? array.length + i : i] === el) {\n array.splice(i, 1);\n }\n }\n };\n if (!remove.__argnames__) Object.defineProperties(remove, {\n __argnames__ : {value: ["array", "el"]},\n __module__ : {value: "utils"}\n });\n\n function mergeSort(array, cmp) {\n if (array.length < 2) {\n return array.slice();\n }\n function merge(a, b) {\n var r, ai, bi, i;\n r = RS_list_decorate([]);\n ai = 0;\n bi = 0;\n i = 0;\n while (ai < a.length && bi < b.length) {\n if (cmp(a[(typeof ai === "number" && ai < 0) ? a.length + ai : ai], b[(typeof bi === "number" && bi < 0) ? b.length + bi : bi]) <= 0) {\n r[(typeof i === "number" && i < 0) ? r.length + i : i] = a[(typeof ai === "number" && ai < 0) ? a.length + ai : ai];\n ai += 1;\n } else {\n r[(typeof i === "number" && i < 0) ? r.length + i : i] = b[(typeof bi === "number" && bi < 0) ? b.length + bi : bi];\n bi += 1;\n }\n i += 1;\n }\n if (ai < a.length) {\n r.push.apply(r, a.slice(ai));\n }\n if (bi < b.length) {\n r.push.apply(r, b.slice(bi));\n }\n return r;\n };\n if (!merge.__argnames__) Object.defineProperties(merge, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "utils"}\n });\n\n function _ms(a) {\n var m, left, right;\n if (a.length <= 1) {\n return a;\n }\n m = Math.floor(a.length / 2);\n left = a.slice(0, m);\n right = a.slice(m);\n left = _ms(left);\n right = _ms(right);\n return merge(left, right);\n };\n if (!_ms.__argnames__) Object.defineProperties(_ms, {\n __argnames__ : {value: ["a"]},\n __module__ : {value: "utils"}\n });\n\n return _ms(array);\n };\n if (!mergeSort.__argnames__) Object.defineProperties(mergeSort, {\n __argnames__ : {value: ["array", "cmp"]},\n __module__ : {value: "utils"}\n });\n\n function set_difference(a, b) {\n return a.filter((function() {\n var RS_anonfunc = function (el) {\n return b.indexOf(el) < 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["el"]},\n __module__ : {value: "utils"}\n });\n return RS_anonfunc;\n })());\n };\n if (!set_difference.__argnames__) Object.defineProperties(set_difference, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "utils"}\n });\n\n function set_intersection(a, b) {\n return a.filter((function() {\n var RS_anonfunc = function (el) {\n return b.indexOf(el) >= 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["el"]},\n __module__ : {value: "utils"}\n });\n return RS_anonfunc;\n })());\n };\n if (!set_intersection.__argnames__) Object.defineProperties(set_intersection, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "utils"}\n });\n\n function make_predicate(words) {\n var a, k;\n if (typeof words === "string") {\n words = words.split(" ");\n }\n a = Object.create(null);\n var RS_Iter9 = RS_Iterable(words);\n for (var RS_Index9 = 0; RS_Index9 < RS_Iter9.length; RS_Index9++) {\n k = RS_Iter9[RS_Index9];\n a[(typeof k === "number" && k < 0) ? a.length + k : k] = true;\n }\n return a;\n };\n if (!make_predicate.__argnames__) Object.defineProperties(make_predicate, {\n __argnames__ : {value: ["words"]},\n __module__ : {value: "utils"}\n });\n\n function cache_file_name(src, cache_dir) {\n if (cache_dir) {\n src = str.replace(src, "\\\\", "/");\n return cache_dir + "/" + str.lstrip(str.replace(src, "/", "-") + ".json", "-");\n }\n return src + "-cached";\n };\n if (!cache_file_name.__argnames__) Object.defineProperties(cache_file_name, {\n __argnames__ : {value: ["src", "cache_dir"]},\n __module__ : {value: "utils"}\n });\n\n RS_modules.utils.has_prop = has_prop;\n RS_modules.utils.MAP = MAP;\n RS_modules.utils.array_to_hash = array_to_hash;\n RS_modules.utils.slice = slice;\n RS_modules.utils.characters = characters;\n RS_modules.utils.member = member;\n RS_modules.utils.repeat_string = repeat_string;\n RS_modules.utils.DefaultsError = DefaultsError;\n RS_modules.utils.defaults = defaults;\n RS_modules.utils.merge = merge;\n RS_modules.utils.noop = noop;\n RS_modules.utils.push_uniq = push_uniq;\n RS_modules.utils.string_template = string_template;\n RS_modules.utils.remove = remove;\n RS_modules.utils.mergeSort = mergeSort;\n RS_modules.utils.set_difference = set_difference;\n RS_modules.utils.set_intersection = set_intersection;\n RS_modules.utils.make_predicate = make_predicate;\n RS_modules.utils.cache_file_name = cache_file_name;\n })();\n\n (function(){\n var __name__ = "errors";\n function SyntaxError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n SyntaxError.prototype.__init__.apply(this, arguments);\n }\n RS_extends(SyntaxError, Error);\n SyntaxError.prototype.__init__ = function __init__(message, filename, line, col, pos, is_eof) {\n var self = this;\n self.stack = (new Error).stack;\n self.message = message;\n self.line = line;\n self.col = col;\n self.pos = pos;\n self.is_eof = is_eof;\n self.filename = filename;\n self.lineNumber = line;\n self.fileName = filename;\n };\n if (!SyntaxError.prototype.__init__.__argnames__) Object.defineProperties(SyntaxError.prototype.__init__, {\n __argnames__ : {value: ["message", "filename", "line", "col", "pos", "is_eof"]},\n __module__ : {value: "errors"}\n });\n SyntaxError.__argnames__ = SyntaxError.prototype.__init__.__argnames__;\n SyntaxError.__handles_kwarg_interpolation__ = SyntaxError.prototype.__init__.__handles_kwarg_interpolation__;\n SyntaxError.prototype.toString = function toString() {\n var self = this;\n var ans;\n ans = self.message + " (line: " + self.line + ", col: " + self.col + ", pos: " + self.pos + ")";\n if (self.filename) {\n ans = self.filename + ":" + ans;\n }\n if (self.stack) {\n ans += "\\n\\n" + self.stack;\n }\n return ans;\n };\n if (!SyntaxError.prototype.toString.__module__) Object.defineProperties(SyntaxError.prototype.toString, {\n __module__ : {value: "errors"}\n });\n SyntaxError.prototype.__repr__ = function __repr__ () {\n if(Error.prototype.__repr__) return Error.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n SyntaxError.prototype.__str__ = function __str__ () {\n if(Error.prototype.__str__) return Error.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(SyntaxError.prototype, "__bases__", {value: [Error]});\n\n function ImportError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n ImportError.prototype.__init__.apply(this, arguments);\n }\n RS_extends(ImportError, SyntaxError);\n ImportError.prototype.__init__ = function __init__ () {\n SyntaxError.prototype.__init__ && SyntaxError.prototype.__init__.apply(this, arguments);\n };\n ImportError.prototype.__repr__ = function __repr__ () {\n if(SyntaxError.prototype.__repr__) return SyntaxError.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n ImportError.prototype.__str__ = function __str__ () {\n if(SyntaxError.prototype.__str__) return SyntaxError.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(ImportError.prototype, "__bases__", {value: [SyntaxError]});\n \n\n RS_modules.errors.SyntaxError = SyntaxError;\n RS_modules.errors.ImportError = ImportError;\n })();\n\n (function(){\n var __name__ = "unicode_aliases";\n var DB, ALIAS_MAP;\n DB = "\\n# NameAliases-8.0.0.txt\\n# Date: 2014-11-19, 01:30:00 GMT [KW, LI]\\n#\\n# This file is a normative contributory data file in the\\n# Unicode Character Database.\\n#\\n# Copyright (c) 2005-2014 Unicode, Inc.\\n# For terms of use, see http://www.unicode.org/terms_of_use.html\\n#\\n# This file defines the formal name aliases for Unicode characters.\\n#\\n# For informative aliases, see NamesList.txt\\n#\\n# The formal name aliases are divided into five types, each with a distinct label.\\n#\\n# Type Labels:\\n#\\n# 1. correction\\n# Corrections for serious problems in the character names\\n# 2. control\\n# ISO 6429 names for C0 and C1 control functions, and other\\n# commonly occurring names for control codes\\n# 3. alternate\\n# A few widely used alternate names for format characters\\n# 4. figment\\n# Several documented labels for C1 control code points which\\n# were never actually approved in any standard\\n# 5. abbreviation\\n# Commonly occurring abbreviations (or acronyms) for control codes,\\n# format characters, spaces, and variation selectors\\n#\\n# The formal name aliases are part of the Unicode character namespace, which\\n# includes the character names and the names of named character sequences.\\n# The inclusion of ISO 6429 names and other commonly occurring names and\\n# abbreviations for control codes and format characters as formal name aliases\\n# is to help avoid name collisions between Unicode character names and the\\n# labels which commonly appear in text and/or in implementations such as regex, for\\n# control codes (which for historical reasons have no Unicode character name)\\n# or for format characters.\\n#\\n# For documentation, see NamesList.html and http://www.unicode.org/reports/tr44/\\n#\\n# FORMAT\\n#\\n# Each line has three fields, as described here:\\n#\\n# First field: Code point\\n# Second field: Alias\\n# Third field: Type\\n#\\n# The type labels used are defined above. As for property values, comparisons\\n# of type labels should ignore case.\\n#\\n# The type labels can be mapped to other strings for display, if desired.\\n#\\n# In case multiple aliases are assigned, additional aliases\\n# are provided on separate lines. Parsers of this data file should\\n# take note that the same code point can (and does) occur more than once.\\n#\\n# Note that currently the only instances of multiple aliases of the same\\n# type for a single code point are either of type \\"control\\" or \\"abbreviation\\".\\n# An alias of type \\"abbreviation\\" can, in principle, be added for any code\\n# point, although currently aliases of type \\"correction\\" do not have\\n# any additional aliases of type \\"abbreviation\\". Such relationships\\n# are not enforced by stability policies.\\n#\\n#-----------------------------------------------------------------\\n\\n0000;NULL;control\\n0000;NUL;abbreviation\\n0001;START OF HEADING;control\\n0001;SOH;abbreviation\\n0002;START OF TEXT;control\\n0002;STX;abbreviation\\n0003;END OF TEXT;control\\n0003;ETX;abbreviation\\n0004;END OF TRANSMISSION;control\\n0004;EOT;abbreviation\\n0005;ENQUIRY;control\\n0005;ENQ;abbreviation\\n0006;ACKNOWLEDGE;control\\n0006;ACK;abbreviation\\n\\n# Note that no formal name alias for the ISO 6429 \\"BELL\\" is\\n# provided for U+0007, because of the existing name collision\\n# with U+1F514 BELL.\\n\\n0007;ALERT;control\\n0007;BEL;abbreviation\\n\\n0008;BACKSPACE;control\\n0008;BS;abbreviation\\n0009;CHARACTER TABULATION;control\\n0009;HORIZONTAL TABULATION;control\\n0009;HT;abbreviation\\n0009;TAB;abbreviation\\n000A;LINE FEED;control\\n000A;NEW LINE;control\\n000A;END OF LINE;control\\n000A;LF;abbreviation\\n000A;NL;abbreviation\\n000A;EOL;abbreviation\\n000B;LINE TABULATION;control\\n000B;VERTICAL TABULATION;control\\n000B;VT;abbreviation\\n000C;FORM FEED;control\\n000C;FF;abbreviation\\n000D;CARRIAGE RETURN;control\\n000D;CR;abbreviation\\n000E;SHIFT OUT;control\\n000E;LOCKING-SHIFT ONE;control\\n000E;SO;abbreviation\\n000F;SHIFT IN;control\\n000F;LOCKING-SHIFT ZERO;control\\n000F;SI;abbreviation\\n0010;DATA LINK ESCAPE;control\\n0010;DLE;abbreviation\\n0011;DEVICE CONTROL ONE;control\\n0011;DC1;abbreviation\\n0012;DEVICE CONTROL TWO;control\\n0012;DC2;abbreviation\\n0013;DEVICE CONTROL THREE;control\\n0013;DC3;abbreviation\\n0014;DEVICE CONTROL FOUR;control\\n0014;DC4;abbreviation\\n0015;NEGATIVE ACKNOWLEDGE;control\\n0015;NAK;abbreviation\\n0016;SYNCHRONOUS IDLE;control\\n0016;SYN;abbreviation\\n0017;END OF TRANSMISSION BLOCK;control\\n0017;ETB;abbreviation\\n0018;CANCEL;control\\n0018;CAN;abbreviation\\n0019;END OF MEDIUM;control\\n0019;EOM;abbreviation\\n001A;SUBSTITUTE;control\\n001A;SUB;abbreviation\\n001B;ESCAPE;control\\n001B;ESC;abbreviation\\n001C;INFORMATION SEPARATOR FOUR;control\\n001C;FILE SEPARATOR;control\\n001C;FS;abbreviation\\n001D;INFORMATION SEPARATOR THREE;control\\n001D;GROUP SEPARATOR;control\\n001D;GS;abbreviation\\n001E;INFORMATION SEPARATOR TWO;control\\n001E;RECORD SEPARATOR;control\\n001E;RS;abbreviation\\n001F;INFORMATION SEPARATOR ONE;control\\n001F;UNIT SEPARATOR;control\\n001F;US;abbreviation\\n0020;SP;abbreviation\\n007F;DELETE;control\\n007F;DEL;abbreviation\\n\\n# PADDING CHARACTER and HIGH OCTET PRESET represent\\n# architectural concepts initially proposed for early\\n# drafts of ISO/IEC 10646-1. They were never actually\\n# approved or standardized: hence their designation\\n# here as the \\"figment\\" type. Formal name aliases\\n# (and corresponding abbreviations) for these code\\n# points are included here because these names leaked\\n# out from the draft documents and were published in\\n# at least one RFC whose names for code points was\\n# implemented in Perl regex expressions.\\n\\n0080;PADDING CHARACTER;figment\\n0080;PAD;abbreviation\\n0081;HIGH OCTET PRESET;figment\\n0081;HOP;abbreviation\\n\\n0082;BREAK PERMITTED HERE;control\\n0082;BPH;abbreviation\\n0083;NO BREAK HERE;control\\n0083;NBH;abbreviation\\n0084;INDEX;control\\n0084;IND;abbreviation\\n0085;NEXT LINE;control\\n0085;NEL;abbreviation\\n0086;START OF SELECTED AREA;control\\n0086;SSA;abbreviation\\n0087;END OF SELECTED AREA;control\\n0087;ESA;abbreviation\\n0088;CHARACTER TABULATION SET;control\\n0088;HORIZONTAL TABULATION SET;control\\n0088;HTS;abbreviation\\n0089;CHARACTER TABULATION WITH JUSTIFICATION;control\\n0089;HORIZONTAL TABULATION WITH JUSTIFICATION;control\\n0089;HTJ;abbreviation\\n008A;LINE TABULATION SET;control\\n008A;VERTICAL TABULATION SET;control\\n008A;VTS;abbreviation\\n008B;PARTIAL LINE FORWARD;control\\n008B;PARTIAL LINE DOWN;control\\n008B;PLD;abbreviation\\n008C;PARTIAL LINE BACKWARD;control\\n008C;PARTIAL LINE UP;control\\n008C;PLU;abbreviation\\n008D;REVERSE LINE FEED;control\\n008D;REVERSE INDEX;control\\n008D;RI;abbreviation\\n008E;SINGLE SHIFT TWO;control\\n008E;SINGLE-SHIFT-2;control\\n008E;SS2;abbreviation\\n008F;SINGLE SHIFT THREE;control\\n008F;SINGLE-SHIFT-3;control\\n008F;SS3;abbreviation\\n0090;DEVICE CONTROL STRING;control\\n0090;DCS;abbreviation\\n0091;PRIVATE USE ONE;control\\n0091;PRIVATE USE-1;control\\n0091;PU1;abbreviation\\n0092;PRIVATE USE TWO;control\\n0092;PRIVATE USE-2;control\\n0092;PU2;abbreviation\\n0093;SET TRANSMIT STATE;control\\n0093;STS;abbreviation\\n0094;CANCEL CHARACTER;control\\n0094;CCH;abbreviation\\n0095;MESSAGE WAITING;control\\n0095;MW;abbreviation\\n0096;START OF GUARDED AREA;control\\n0096;START OF PROTECTED AREA;control\\n0096;SPA;abbreviation\\n0097;END OF GUARDED AREA;control\\n0097;END OF PROTECTED AREA;control\\n0097;EPA;abbreviation\\n0098;START OF STRING;control\\n0098;SOS;abbreviation\\n\\n# SINGLE GRAPHIC CHARACTER INTRODUCER is another\\n# architectural concept from early drafts of ISO/IEC 10646-1\\n# which was never approved and standardized.\\n\\n0099;SINGLE GRAPHIC CHARACTER INTRODUCER;figment\\n0099;SGC;abbreviation\\n\\n009A;SINGLE CHARACTER INTRODUCER;control\\n009A;SCI;abbreviation\\n009B;CONTROL SEQUENCE INTRODUCER;control\\n009B;CSI;abbreviation\\n009C;STRING TERMINATOR;control\\n009C;ST;abbreviation\\n009D;OPERATING SYSTEM COMMAND;control\\n009D;OSC;abbreviation\\n009E;PRIVACY MESSAGE;control\\n009E;PM;abbreviation\\n009F;APPLICATION PROGRAM COMMAND;control\\n009F;APC;abbreviation\\n00A0;NBSP;abbreviation\\n00AD;SHY;abbreviation\\n01A2;LATIN CAPITAL LETTER GHA;correction\\n01A3;LATIN SMALL LETTER GHA;correction\\n034F;CGJ;abbreviation\\n061C;ALM;abbreviation\\n0709;SYRIAC SUBLINEAR COLON SKEWED LEFT;correction\\n0CDE;KANNADA LETTER LLLA;correction\\n0E9D;LAO LETTER FO FON;correction\\n0E9F;LAO LETTER FO FAY;correction\\n0EA3;LAO LETTER RO;correction\\n0EA5;LAO LETTER LO;correction\\n0FD0;TIBETAN MARK BKA- SHOG GI MGO RGYAN;correction\\n180B;FVS1;abbreviation\\n180C;FVS2;abbreviation\\n180D;FVS3;abbreviation\\n180E;MVS;abbreviation\\n200B;ZWSP;abbreviation\\n200C;ZWNJ;abbreviation\\n200D;ZWJ;abbreviation\\n200E;LRM;abbreviation\\n200F;RLM;abbreviation\\n202A;LRE;abbreviation\\n202B;RLE;abbreviation\\n202C;PDF;abbreviation\\n202D;LRO;abbreviation\\n202E;RLO;abbreviation\\n202F;NNBSP;abbreviation\\n205F;MMSP;abbreviation\\n2060;WJ;abbreviation\\n2066;LRI;abbreviation\\n2067;RLI;abbreviation\\n2068;FSI;abbreviation\\n2069;PDI;abbreviation\\n2118;WEIERSTRASS ELLIPTIC FUNCTION;correction\\n2448;MICR ON US SYMBOL;correction\\n2449;MICR DASH SYMBOL;correction\\n2B7A;LEFTWARDS TRIANGLE-HEADED ARROW WITH DOUBLE VERTICAL STROKE;correction\\n2B7C;RIGHTWARDS TRIANGLE-HEADED ARROW WITH DOUBLE VERTICAL STROKE;correction\\nA015;YI SYLLABLE ITERATION MARK;correction\\nFE18;PRESENTATION FORM FOR VERTICAL RIGHT WHITE LENTICULAR BRACKET;correction\\nFE00;VS1;abbreviation\\nFE01;VS2;abbreviation\\nFE02;VS3;abbreviation\\nFE03;VS4;abbreviation\\nFE04;VS5;abbreviation\\nFE05;VS6;abbreviation\\nFE06;VS7;abbreviation\\nFE07;VS8;abbreviation\\nFE08;VS9;abbreviation\\nFE09;VS10;abbreviation\\nFE0A;VS11;abbreviation\\nFE0B;VS12;abbreviation\\nFE0C;VS13;abbreviation\\nFE0D;VS14;abbreviation\\nFE0E;VS15;abbreviation\\nFE0F;VS16;abbreviation\\nFEFF;BYTE ORDER MARK;alternate\\nFEFF;BOM;abbreviation\\nFEFF;ZWNBSP;abbreviation\\n122D4;CUNEIFORM SIGN NU11 TENU;correction\\n122D5;CUNEIFORM SIGN NU11 OVER NU11 BUR OVER BUR;correction\\n1D0C5;BYZANTINE MUSICAL SYMBOL FTHORA SKLIRON CHROMA VASIS;correction\\nE0100;VS17;abbreviation\\nE0101;VS18;abbreviation\\nE0102;VS19;abbreviation\\nE0103;VS20;abbreviation\\nE0104;VS21;abbreviation\\nE0105;VS22;abbreviation\\nE0106;VS23;abbreviation\\nE0107;VS24;abbreviation\\nE0108;VS25;abbreviation\\nE0109;VS26;abbreviation\\nE010A;VS27;abbreviation\\nE010B;VS28;abbreviation\\nE010C;VS29;abbreviation\\nE010D;VS30;abbreviation\\nE010E;VS31;abbreviation\\nE010F;VS32;abbreviation\\nE0110;VS33;abbreviation\\nE0111;VS34;abbreviation\\nE0112;VS35;abbreviation\\nE0113;VS36;abbreviation\\nE0114;VS37;abbreviation\\nE0115;VS38;abbreviation\\nE0116;VS39;abbreviation\\nE0117;VS40;abbreviation\\nE0118;VS41;abbreviation\\nE0119;VS42;abbreviation\\nE011A;VS43;abbreviation\\nE011B;VS44;abbreviation\\nE011C;VS45;abbreviation\\nE011D;VS46;abbreviation\\nE011E;VS47;abbreviation\\nE011F;VS48;abbreviation\\nE0120;VS49;abbreviation\\nE0121;VS50;abbreviation\\nE0122;VS51;abbreviation\\nE0123;VS52;abbreviation\\nE0124;VS53;abbreviation\\nE0125;VS54;abbreviation\\nE0126;VS55;abbreviation\\nE0127;VS56;abbreviation\\nE0128;VS57;abbreviation\\nE0129;VS58;abbreviation\\nE012A;VS59;abbreviation\\nE012B;VS60;abbreviation\\nE012C;VS61;abbreviation\\nE012D;VS62;abbreviation\\nE012E;VS63;abbreviation\\nE012F;VS64;abbreviation\\nE0130;VS65;abbreviation\\nE0131;VS66;abbreviation\\nE0132;VS67;abbreviation\\nE0133;VS68;abbreviation\\nE0134;VS69;abbreviation\\nE0135;VS70;abbreviation\\nE0136;VS71;abbreviation\\nE0137;VS72;abbreviation\\nE0138;VS73;abbreviation\\nE0139;VS74;abbreviation\\nE013A;VS75;abbreviation\\nE013B;VS76;abbreviation\\nE013C;VS77;abbreviation\\nE013D;VS78;abbreviation\\nE013E;VS79;abbreviation\\nE013F;VS80;abbreviation\\nE0140;VS81;abbreviation\\nE0141;VS82;abbreviation\\nE0142;VS83;abbreviation\\nE0143;VS84;abbreviation\\nE0144;VS85;abbreviation\\nE0145;VS86;abbreviation\\nE0146;VS87;abbreviation\\nE0147;VS88;abbreviation\\nE0148;VS89;abbreviation\\nE0149;VS90;abbreviation\\nE014A;VS91;abbreviation\\nE014B;VS92;abbreviation\\nE014C;VS93;abbreviation\\nE014D;VS94;abbreviation\\nE014E;VS95;abbreviation\\nE014F;VS96;abbreviation\\nE0150;VS97;abbreviation\\nE0151;VS98;abbreviation\\nE0152;VS99;abbreviation\\nE0153;VS100;abbreviation\\nE0154;VS101;abbreviation\\nE0155;VS102;abbreviation\\nE0156;VS103;abbreviation\\nE0157;VS104;abbreviation\\nE0158;VS105;abbreviation\\nE0159;VS106;abbreviation\\nE015A;VS107;abbreviation\\nE015B;VS108;abbreviation\\nE015C;VS109;abbreviation\\nE015D;VS110;abbreviation\\nE015E;VS111;abbreviation\\nE015F;VS112;abbreviation\\nE0160;VS113;abbreviation\\nE0161;VS114;abbreviation\\nE0162;VS115;abbreviation\\nE0163;VS116;abbreviation\\nE0164;VS117;abbreviation\\nE0165;VS118;abbreviation\\nE0166;VS119;abbreviation\\nE0167;VS120;abbreviation\\nE0168;VS121;abbreviation\\nE0169;VS122;abbreviation\\nE016A;VS123;abbreviation\\nE016B;VS124;abbreviation\\nE016C;VS125;abbreviation\\nE016D;VS126;abbreviation\\nE016E;VS127;abbreviation\\nE016F;VS128;abbreviation\\nE0170;VS129;abbreviation\\nE0171;VS130;abbreviation\\nE0172;VS131;abbreviation\\nE0173;VS132;abbreviation\\nE0174;VS133;abbreviation\\nE0175;VS134;abbreviation\\nE0176;VS135;abbreviation\\nE0177;VS136;abbreviation\\nE0178;VS137;abbreviation\\nE0179;VS138;abbreviation\\nE017A;VS139;abbreviation\\nE017B;VS140;abbreviation\\nE017C;VS141;abbreviation\\nE017D;VS142;abbreviation\\nE017E;VS143;abbreviation\\nE017F;VS144;abbreviation\\nE0180;VS145;abbreviation\\nE0181;VS146;abbreviation\\nE0182;VS147;abbreviation\\nE0183;VS148;abbreviation\\nE0184;VS149;abbreviation\\nE0185;VS150;abbreviation\\nE0186;VS151;abbreviation\\nE0187;VS152;abbreviation\\nE0188;VS153;abbreviation\\nE0189;VS154;abbreviation\\nE018A;VS155;abbreviation\\nE018B;VS156;abbreviation\\nE018C;VS157;abbreviation\\nE018D;VS158;abbreviation\\nE018E;VS159;abbreviation\\nE018F;VS160;abbreviation\\nE0190;VS161;abbreviation\\nE0191;VS162;abbreviation\\nE0192;VS163;abbreviation\\nE0193;VS164;abbreviation\\nE0194;VS165;abbreviation\\nE0195;VS166;abbreviation\\nE0196;VS167;abbreviation\\nE0197;VS168;abbreviation\\nE0198;VS169;abbreviation\\nE0199;VS170;abbreviation\\nE019A;VS171;abbreviation\\nE019B;VS172;abbreviation\\nE019C;VS173;abbreviation\\nE019D;VS174;abbreviation\\nE019E;VS175;abbreviation\\nE019F;VS176;abbreviation\\nE01A0;VS177;abbreviation\\nE01A1;VS178;abbreviation\\nE01A2;VS179;abbreviation\\nE01A3;VS180;abbreviation\\nE01A4;VS181;abbreviation\\nE01A5;VS182;abbreviation\\nE01A6;VS183;abbreviation\\nE01A7;VS184;abbreviation\\nE01A8;VS185;abbreviation\\nE01A9;VS186;abbreviation\\nE01AA;VS187;abbreviation\\nE01AB;VS188;abbreviation\\nE01AC;VS189;abbreviation\\nE01AD;VS190;abbreviation\\nE01AE;VS191;abbreviation\\nE01AF;VS192;abbreviation\\nE01B0;VS193;abbreviation\\nE01B1;VS194;abbreviation\\nE01B2;VS195;abbreviation\\nE01B3;VS196;abbreviation\\nE01B4;VS197;abbreviation\\nE01B5;VS198;abbreviation\\nE01B6;VS199;abbreviation\\nE01B7;VS200;abbreviation\\nE01B8;VS201;abbreviation\\nE01B9;VS202;abbreviation\\nE01BA;VS203;abbreviation\\nE01BB;VS204;abbreviation\\nE01BC;VS205;abbreviation\\nE01BD;VS206;abbreviation\\nE01BE;VS207;abbreviation\\nE01BF;VS208;abbreviation\\nE01C0;VS209;abbreviation\\nE01C1;VS210;abbreviation\\nE01C2;VS211;abbreviation\\nE01C3;VS212;abbreviation\\nE01C4;VS213;abbreviation\\nE01C5;VS214;abbreviation\\nE01C6;VS215;abbreviation\\nE01C7;VS216;abbreviation\\nE01C8;VS217;abbreviation\\nE01C9;VS218;abbreviation\\nE01CA;VS219;abbreviation\\nE01CB;VS220;abbreviation\\nE01CC;VS221;abbreviation\\nE01CD;VS222;abbreviation\\nE01CE;VS223;abbreviation\\nE01CF;VS224;abbreviation\\nE01D0;VS225;abbreviation\\nE01D1;VS226;abbreviation\\nE01D2;VS227;abbreviation\\nE01D3;VS228;abbreviation\\nE01D4;VS229;abbreviation\\nE01D5;VS230;abbreviation\\nE01D6;VS231;abbreviation\\nE01D7;VS232;abbreviation\\nE01D8;VS233;abbreviation\\nE01D9;VS234;abbreviation\\nE01DA;VS235;abbreviation\\nE01DB;VS236;abbreviation\\nE01DC;VS237;abbreviation\\nE01DD;VS238;abbreviation\\nE01DE;VS239;abbreviation\\nE01DF;VS240;abbreviation\\nE01E0;VS241;abbreviation\\nE01E1;VS242;abbreviation\\nE01E2;VS243;abbreviation\\nE01E3;VS244;abbreviation\\nE01E4;VS245;abbreviation\\nE01E5;VS246;abbreviation\\nE01E6;VS247;abbreviation\\nE01E7;VS248;abbreviation\\nE01E8;VS249;abbreviation\\nE01E9;VS250;abbreviation\\nE01EA;VS251;abbreviation\\nE01EB;VS252;abbreviation\\nE01EC;VS253;abbreviation\\nE01ED;VS254;abbreviation\\nE01EE;VS255;abbreviation\\nE01EF;VS256;abbreviation\\n\\n# EOF\\n";\n ALIAS_MAP = (function() {\n var RS_anonfunc = function () {\n var ans, line, parts, code_point;\n ans = {};\n var RS_Iter10 = RS_Iterable(DB.split("\\n"));\n for (var RS_Index10 = 0; RS_Index10 < RS_Iter10.length; RS_Index10++) {\n line = RS_Iter10[RS_Index10];\n line = line.trim();\n if (!line || line[0] === "#") {\n continue;\n }\n parts = line.split(";");\n if (parts.length >= 2) {\n code_point = parseInt(parts[0], 16);\n if (code_point !== undefined && parts[1]) {\n ans[RS_bound_index(parts[1].toLowerCase(), ans)] = code_point;\n }\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "unicode_aliases"}\n });\n return RS_anonfunc;\n })()();\n RS_modules.unicode_aliases.DB = DB;\n RS_modules.unicode_aliases.ALIAS_MAP = ALIAS_MAP;\n })();\n\n (function(){\n var __name__ = "ast";\n var noop = RS_modules.utils.noop;\n\n function is_node_type(node, typ) {\n return node instanceof typ;\n };\n if (!is_node_type.__argnames__) Object.defineProperties(is_node_type, {\n __argnames__ : {value: ["node", "typ"]},\n __module__ : {value: "ast"}\n });\n\n function AST() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST.prototype.__init__.apply(this, arguments);\n }\n AST.prototype.__init__ = function __init__(initializer) {\n var self = this;\n var obj;\n if (initializer) {\n obj = self;\n while (true) {\n obj = Object.getPrototypeOf(obj);\n if (obj === null) {\n break;\n }\n for (var i in obj.properties) {\n self[i] = initializer[i];\n }\n }\n }\n };\n if (!AST.prototype.__init__.__argnames__) Object.defineProperties(AST.prototype.__init__, {\n __argnames__ : {value: ["initializer"]},\n __module__ : {value: "ast"}\n });\n AST.__argnames__ = AST.prototype.__init__.__argnames__;\n AST.__handles_kwarg_interpolation__ = AST.prototype.__init__.__handles_kwarg_interpolation__;\n AST.prototype.clone = function clone() {\n var self = this;\n return new self.constructor(self);\n };\n if (!AST.prototype.clone.__module__) Object.defineProperties(AST.prototype.clone, {\n __module__ : {value: "ast"}\n });\n AST.prototype.__repr__ = function __repr__ () {\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST.prototype.__str__ = function __str__ () {\n return this.__repr__();\n };\n Object.defineProperty(AST.prototype, "__bases__", {value: []});\n AST.prototype.properties = Object.create(null);\n\n function AST_Token() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Token.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Token, AST);\n AST_Token.prototype.__init__ = function __init__ () {\n AST.prototype.__init__ && AST.prototype.__init__.apply(this, arguments);\n };\n AST_Token.prototype.__repr__ = function __repr__ () {\n if(AST.prototype.__repr__) return AST.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Token.prototype.__str__ = function __str__ () {\n if(AST.prototype.__str__) return AST.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Token.prototype, "__bases__", {value: [AST]});\n AST_Token.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["type"] = "The type of the token";\n RS_d["value"] = "The value of the token";\n RS_d["line"] = "The line number at which the token occurs";\n RS_d["col"] = "The column number at which the token occurs";\n RS_d["pos"] = "";\n RS_d["endpos"] = "";\n RS_d["nlb"] = "True iff there was a newline before this token";\n RS_d["comments_before"] = "True iff there were comments before this token";\n RS_d["file"] = "The filename in which this token occurs";\n RS_d["leading_whitespace"] = "The leading whitespace for the line on which this token occurs";\n return RS_d;\n }).call(this);\n\n function AST_Node() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Node.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Node, AST);\n AST_Node.prototype.__init__ = function __init__ () {\n AST.prototype.__init__ && AST.prototype.__init__.apply(this, arguments);\n };\n AST_Node.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self);\n };\n if (!AST_Node.prototype._walk.__argnames__) Object.defineProperties(AST_Node.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Node.prototype.walk = function walk(visitor) {\n var self = this;\n return self._walk(visitor);\n };\n if (!AST_Node.prototype.walk.__argnames__) Object.defineProperties(AST_Node.prototype.walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Node.prototype._dump = function _dump() {\n var self = this;\n var depth = (arguments[0] === undefined || ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? _dump.__defaults__.depth : arguments[0];\n var omit = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? _dump.__defaults__.omit : arguments[1];\n var offset = (arguments[2] === undefined || ( 2 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? _dump.__defaults__.offset : arguments[2];\n var include_name = (arguments[3] === undefined || ( 3 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? _dump.__defaults__.include_name : arguments[3];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "depth")){\n depth = RS_kwargs_obj.depth;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "omit")){\n omit = RS_kwargs_obj.omit;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "offset")){\n offset = RS_kwargs_obj.offset;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "include_name")){\n include_name = RS_kwargs_obj.include_name;\n }\n var p, reset, yellow, blue, green, red, magenta, pad, element, tname, property, key;\n p = console.log;\n reset = "\\u001b[0m";\n yellow = "\\u001b[33m";\n blue = "\\u001b[34m";\n green = "\\u001b[32m";\n red = "\\u001b[31m";\n magenta = "\\u001b[35m";\n pad = new Array(offset + 1).join(" ");\n if (include_name) {\n p(pad + yellow + self.constructor.name.slice(4) + reset);\n }\n var RS_Iter11 = RS_Iterable(self);\n for (var RS_Index11 = 0; RS_Index11 < RS_Iter11.length; RS_Index11++) {\n key = RS_Iter11[RS_Index11];\n if (RS_in(key, omit)) {\n continue;\n }\n if (Array.isArray(self[(typeof key === "number" && key < 0) ? self.length + key : key])) {\n if (self[(typeof key === "number" && key < 0) ? self.length + key : key].length) {\n p(pad + " " + blue + key + ": " + reset + "[");\n if (depth > 1) {\n var RS_Iter12 = RS_Iterable(self[(typeof key === "number" && key < 0) ? self.length + key : key]);\n for (var RS_Index12 = 0; RS_Index12 < RS_Iter12.length; RS_Index12++) {\n element = RS_Iter12[RS_Index12];\n element._dump(depth - 1, omit, offset + 1, true);\n }\n } else {\n var RS_Iter13 = RS_Iterable(self[(typeof key === "number" && key < 0) ? self.length + key : key]);\n for (var RS_Index13 = 0; RS_Index13 < RS_Iter13.length; RS_Index13++) {\n element = RS_Iter13[RS_Index13];\n p(pad + " " + yellow + element.constructor.name.slice(4) + reset);\n }\n }\n p(pad + " ]");\n } else {\n p(pad + " " + blue + key + ": " + reset + "[]");\n }\n } else if (self[(typeof key === "number" && key < 0) ? self.length + key : key]) {\n if (is_node_type(self[(typeof key === "number" && key < 0) ? self.length + key : key], AST)) {\n tname = self[(typeof key === "number" && key < 0) ? self.length + key : key].constructor.name.slice(4);\n if (tname === "Token") {\n p(pad + " " + blue + key + ": " + magenta + tname + reset);\n var RS_Iter14 = RS_Iterable(self[(typeof key === "number" && key < 0) ? self.length + key : key]);\n for (var RS_Index14 = 0; RS_Index14 < RS_Iter14.length; RS_Index14++) {\n property = RS_Iter14[RS_Index14];\n p(pad + " " + blue + property + ": " + reset + (RS_expr_temp = self[(typeof key === "number" && key < 0) ? self.length + key : key])[(typeof property === "number" && property < 0) ? RS_expr_temp.length + property : property]);\n }\n } else {\n p(pad + " " + blue + key + ": " + yellow + tname + reset);\n if (depth > 1) {\n self[(typeof key === "number" && key < 0) ? self.length + key : key]._dump(depth - 1, omit, offset + 1, false);\n }\n }\n } else if (typeof self[(typeof key === "number" && key < 0) ? self.length + key : key] === "string") {\n p(pad + " " + blue + key + ": " + green + "\\"" + self[(typeof key === "number" && key < 0) ? self.length + key : key] + "\\"" + reset);\n } else if (typeof self[(typeof key === "number" && key < 0) ? self.length + key : key] === "number") {\n p(pad + " " + blue + key + ": " + green + self[(typeof key === "number" && key < 0) ? self.length + key : key] + reset);\n } else {\n p(pad + " " + blue + key + ": " + red + self[(typeof key === "number" && key < 0) ? self.length + key : key] + reset);\n }\n } else {\n p(pad + " " + blue + key + ": " + reset + self[(typeof key === "number" && key < 0) ? self.length + key : key]);\n }\n }\n };\n if (!AST_Node.prototype._dump.__defaults__) Object.defineProperties(AST_Node.prototype._dump, {\n __defaults__ : {value: {depth:100, omit:(function(){\n var s = RS_set();\n s.jsset.add("start");\n s.jsset.add("end");\n return s;\n })(), offset:0, include_name:true}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["depth", "omit", "offset", "include_name"]},\n __module__ : {value: "ast"}\n });\n AST_Node.prototype.dump = function dump() {\n var self = this;\n var depth = (arguments[0] === undefined || ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? dump.__defaults__.depth : arguments[0];\n var omit = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? dump.__defaults__.omit : arguments[1];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "depth")){\n depth = RS_kwargs_obj.depth;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "omit")){\n omit = RS_kwargs_obj.omit;\n }\n return self._dump(depth, omit, 0, true);\n };\n if (!AST_Node.prototype.dump.__defaults__) Object.defineProperties(AST_Node.prototype.dump, {\n __defaults__ : {value: {depth:2, omit:Object.create(null)}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["depth", "omit"]},\n __module__ : {value: "ast"}\n });\n AST_Node.prototype.__repr__ = function __repr__ () {\n if(AST.prototype.__repr__) return AST.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Node.prototype.__str__ = function __str__ () {\n if(AST.prototype.__str__) return AST.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Node.prototype, "__bases__", {value: [AST]});\n AST_Node.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["start"] = "[AST_Token] The first token of this node";\n RS_d["end"] = "[AST_Token] The last token of this node";\n return RS_d;\n }).call(this);\n\n function AST_Statement() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Statement.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Statement, AST_Node);\n AST_Statement.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Statement.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Statement.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Statement.prototype, "__bases__", {value: [AST_Node]});\n\n function AST_Debugger() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Debugger.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Debugger, AST_Statement);\n AST_Debugger.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Debugger.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Debugger.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Debugger.prototype, "__bases__", {value: [AST_Statement]});\n\n function AST_Directive() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Directive.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Directive, AST_Statement);\n AST_Directive.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Directive.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Directive.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Directive.prototype, "__bases__", {value: [AST_Statement]});\n AST_Directive.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value"] = "[string] The value of this directive as a plain string (it\'s not an AST_String!)";\n RS_d["scope"] = "[AST_Scope/S] The scope that this directive affects";\n return RS_d;\n }).call(this);\n\n function AST_SimpleStatement() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SimpleStatement.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SimpleStatement, AST_Statement);\n AST_SimpleStatement.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_SimpleStatement.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.body._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_SimpleStatement.prototype._walk.__argnames__) Object.defineProperties(AST_SimpleStatement.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_SimpleStatement.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SimpleStatement.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SimpleStatement.prototype, "__bases__", {value: [AST_Statement]});\n AST_SimpleStatement.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["body"] = "[AST_Node] an expression node (should not be instanceof AST_Statement)";\n return RS_d;\n }).call(this);\n\n function AST_Assert() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Assert.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Assert, AST_Statement);\n AST_Assert.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Assert.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.condition._walk(visitor);\n if (self.message) {\n self.message._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Assert.prototype._walk.__argnames__) Object.defineProperties(AST_Assert.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Assert.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Assert.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Assert.prototype, "__bases__", {value: [AST_Statement]});\n AST_Assert.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = "[AST_Node] the expression that should be tested";\n RS_d["message"] = "[AST_Node*] the expression that is the error message or None";\n return RS_d;\n }).call(this);\n\n function walk_body(node, visitor) {\n var stat;\n if (is_node_type(node.body, AST_Statement)) {\n node.body._walk(visitor);\n } else if (node.body) {\n var RS_Iter15 = RS_Iterable(node.body);\n for (var RS_Index15 = 0; RS_Index15 < RS_Iter15.length; RS_Index15++) {\n stat = RS_Iter15[RS_Index15];\n stat._walk(visitor);\n }\n }\n };\n if (!walk_body.__argnames__) Object.defineProperties(walk_body, {\n __argnames__ : {value: ["node", "visitor"]},\n __module__ : {value: "ast"}\n });\n\n function AST_Block() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Block.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Block, AST_Statement);\n AST_Block.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Block.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n walk_body(self, visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Block.prototype._walk.__argnames__) Object.defineProperties(AST_Block.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Block.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Block.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Block.prototype, "__bases__", {value: [AST_Statement]});\n AST_Block.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["body"] = "[AST_Statement*] an array of statements";\n return RS_d;\n }).call(this);\n\n function AST_BlockStatement() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_BlockStatement.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_BlockStatement, AST_Block);\n AST_BlockStatement.prototype.__init__ = function __init__ () {\n AST_Block.prototype.__init__ && AST_Block.prototype.__init__.apply(this, arguments);\n };\n AST_BlockStatement.prototype.__repr__ = function __repr__ () {\n if(AST_Block.prototype.__repr__) return AST_Block.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_BlockStatement.prototype.__str__ = function __str__ () {\n if(AST_Block.prototype.__str__) return AST_Block.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_BlockStatement.prototype, "__bases__", {value: [AST_Block]});\n\n function AST_EmptyStatement() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_EmptyStatement.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_EmptyStatement, AST_Statement);\n AST_EmptyStatement.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_EmptyStatement.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self);\n };\n if (!AST_EmptyStatement.prototype._walk.__argnames__) Object.defineProperties(AST_EmptyStatement.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_EmptyStatement.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_EmptyStatement.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_EmptyStatement.prototype, "__bases__", {value: [AST_Statement]});\n AST_EmptyStatement.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["stype"] = "[string] the type of empty statement. Is ; for semicolons";\n return RS_d;\n }).call(this);\n\n function AST_StatementWithBody() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_StatementWithBody.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_StatementWithBody, AST_Statement);\n AST_StatementWithBody.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_StatementWithBody.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.body._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_StatementWithBody.prototype._walk.__argnames__) Object.defineProperties(AST_StatementWithBody.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_StatementWithBody.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_StatementWithBody.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_StatementWithBody.prototype, "__bases__", {value: [AST_Statement]});\n AST_StatementWithBody.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["body"] = "[AST_Statement] the body; this should always be present, even if it\'s an AST_EmptyStatement";\n return RS_d;\n }).call(this);\n\n function AST_DWLoop() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_DWLoop.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_DWLoop, AST_StatementWithBody);\n AST_DWLoop.prototype.__init__ = function __init__ () {\n AST_StatementWithBody.prototype.__init__ && AST_StatementWithBody.prototype.__init__.apply(this, arguments);\n };\n AST_DWLoop.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.condition._walk(visitor);\n self.body._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_DWLoop.prototype._walk.__argnames__) Object.defineProperties(AST_DWLoop.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_DWLoop.prototype.__repr__ = function __repr__ () {\n if(AST_StatementWithBody.prototype.__repr__) return AST_StatementWithBody.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_DWLoop.prototype.__str__ = function __str__ () {\n if(AST_StatementWithBody.prototype.__str__) return AST_StatementWithBody.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_DWLoop.prototype, "__bases__", {value: [AST_StatementWithBody]});\n AST_DWLoop.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = "[AST_Node] the loop condition. Should not be instanceof AST_Statement";\n return RS_d;\n }).call(this);\n\n function AST_Do() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Do.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Do, AST_DWLoop);\n AST_Do.prototype.__init__ = function __init__ () {\n AST_DWLoop.prototype.__init__ && AST_DWLoop.prototype.__init__.apply(this, arguments);\n };\n AST_Do.prototype.__repr__ = function __repr__ () {\n if(AST_DWLoop.prototype.__repr__) return AST_DWLoop.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Do.prototype.__str__ = function __str__ () {\n if(AST_DWLoop.prototype.__str__) return AST_DWLoop.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Do.prototype, "__bases__", {value: [AST_DWLoop]});\n\n function AST_While() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_While.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_While, AST_DWLoop);\n AST_While.prototype.__init__ = function __init__ () {\n AST_DWLoop.prototype.__init__ && AST_DWLoop.prototype.__init__.apply(this, arguments);\n };\n AST_While.prototype.__repr__ = function __repr__ () {\n if(AST_DWLoop.prototype.__repr__) return AST_DWLoop.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_While.prototype.__str__ = function __str__ () {\n if(AST_DWLoop.prototype.__str__) return AST_DWLoop.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_While.prototype, "__bases__", {value: [AST_DWLoop]});\n\n function AST_ForIn() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ForIn.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ForIn, AST_StatementWithBody);\n AST_ForIn.prototype.__init__ = function __init__ () {\n AST_StatementWithBody.prototype.__init__ && AST_StatementWithBody.prototype.__init__.apply(this, arguments);\n };\n AST_ForIn.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.init._walk(visitor);\n if (self.name) self.name._walk(visitor);\n self.object._walk(visitor);\n if (self.body) {\n self.body._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_ForIn.prototype._walk.__argnames__) Object.defineProperties(AST_ForIn.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_ForIn.prototype.__repr__ = function __repr__ () {\n if(AST_StatementWithBody.prototype.__repr__) return AST_StatementWithBody.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ForIn.prototype.__str__ = function __str__ () {\n if(AST_StatementWithBody.prototype.__str__) return AST_StatementWithBody.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ForIn.prototype, "__bases__", {value: [AST_StatementWithBody]});\n AST_ForIn.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["init"] = "[AST_Node] the `for/in` initialization code";\n RS_d["name"] = "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var";\n RS_d["object"] = "[AST_Node] the object that we\'re looping through";\n return RS_d;\n }).call(this);\n\n function AST_ForJS() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ForJS.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ForJS, AST_StatementWithBody);\n AST_ForJS.prototype.__init__ = function __init__ () {\n AST_StatementWithBody.prototype.__init__ && AST_StatementWithBody.prototype.__init__.apply(this, arguments);\n };\n AST_ForJS.prototype.__repr__ = function __repr__ () {\n if(AST_StatementWithBody.prototype.__repr__) return AST_StatementWithBody.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ForJS.prototype.__str__ = function __str__ () {\n if(AST_StatementWithBody.prototype.__str__) return AST_StatementWithBody.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ForJS.prototype, "__bases__", {value: [AST_StatementWithBody]});\n AST_ForJS.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = "[AST_Verbatim] raw JavaScript conditional";\n return RS_d;\n }).call(this);\n\n function AST_ListComprehension() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ListComprehension.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ListComprehension, AST_ForIn);\n AST_ListComprehension.prototype.__init__ = function __init__ () {\n AST_ForIn.prototype.__init__ && AST_ForIn.prototype.__init__.apply(this, arguments);\n };\n AST_ListComprehension.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.init._walk(visitor);\n self.object._walk(visitor);\n self.statement._walk(visitor);\n if (self.condition) self.condition._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_ListComprehension.prototype._walk.__argnames__) Object.defineProperties(AST_ListComprehension.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_ListComprehension.prototype.__repr__ = function __repr__ () {\n if(AST_ForIn.prototype.__repr__) return AST_ForIn.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ListComprehension.prototype.__str__ = function __str__ () {\n if(AST_ForIn.prototype.__str__) return AST_ForIn.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ListComprehension.prototype, "__bases__", {value: [AST_ForIn]});\n AST_ListComprehension.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = "[AST_Node] the `if` condition";\n RS_d["statement"] = "[AST_Node] statement to perform on each element before returning it";\n return RS_d;\n }).call(this);\n\n function AST_SetComprehension() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SetComprehension.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SetComprehension, AST_ListComprehension);\n AST_SetComprehension.prototype.__init__ = function __init__ () {\n AST_ListComprehension.prototype.__init__ && AST_ListComprehension.prototype.__init__.apply(this, arguments);\n };\n AST_SetComprehension.prototype.__repr__ = function __repr__ () {\n if(AST_ListComprehension.prototype.__repr__) return AST_ListComprehension.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SetComprehension.prototype.__str__ = function __str__ () {\n if(AST_ListComprehension.prototype.__str__) return AST_ListComprehension.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SetComprehension.prototype, "__bases__", {value: [AST_ListComprehension]});\n\n function AST_DictComprehension() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_DictComprehension.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_DictComprehension, AST_ListComprehension);\n AST_DictComprehension.prototype.__init__ = function __init__ () {\n AST_ListComprehension.prototype.__init__ && AST_ListComprehension.prototype.__init__.apply(this, arguments);\n };\n AST_DictComprehension.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.init._walk(visitor);\n self.object._walk(visitor);\n self.statement._walk(visitor);\n self.value_statement._walk(visitor);\n if (self.condition) self.condition._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_DictComprehension.prototype._walk.__argnames__) Object.defineProperties(AST_DictComprehension.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_DictComprehension.prototype.__repr__ = function __repr__ () {\n if(AST_ListComprehension.prototype.__repr__) return AST_ListComprehension.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_DictComprehension.prototype.__str__ = function __str__ () {\n if(AST_ListComprehension.prototype.__str__) return AST_ListComprehension.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_DictComprehension.prototype, "__bases__", {value: [AST_ListComprehension]});\n AST_DictComprehension.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value_statement"] = "[AST_Node] statement to perform on each value before returning it";\n RS_d["is_pydict"] = "[bool] True if this comprehension is for a python dict";\n RS_d["is_jshash"] = "[bool] True if this comprehension is for a js hash";\n return RS_d;\n }).call(this);\n\n function AST_GeneratorComprehension() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_GeneratorComprehension.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_GeneratorComprehension, AST_ListComprehension);\n AST_GeneratorComprehension.prototype.__init__ = function __init__ () {\n AST_ListComprehension.prototype.__init__ && AST_ListComprehension.prototype.__init__.apply(this, arguments);\n };\n AST_GeneratorComprehension.prototype.__repr__ = function __repr__ () {\n if(AST_ListComprehension.prototype.__repr__) return AST_ListComprehension.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_GeneratorComprehension.prototype.__str__ = function __str__ () {\n if(AST_ListComprehension.prototype.__str__) return AST_ListComprehension.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_GeneratorComprehension.prototype, "__bases__", {value: [AST_ListComprehension]});\n\n function AST_With() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_With.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_With, AST_StatementWithBody);\n AST_With.prototype.__init__ = function __init__ () {\n AST_StatementWithBody.prototype.__init__ && AST_StatementWithBody.prototype.__init__.apply(this, arguments);\n };\n AST_With.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var exp;\n var RS_Iter16 = RS_Iterable(self.clauses);\n for (var RS_Index16 = 0; RS_Index16 < RS_Iter16.length; RS_Index16++) {\n exp = RS_Iter16[RS_Index16];\n exp._walk(visitor);\n }\n self.body._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_With.prototype._walk.__argnames__) Object.defineProperties(AST_With.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_With.prototype.__repr__ = function __repr__ () {\n if(AST_StatementWithBody.prototype.__repr__) return AST_StatementWithBody.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_With.prototype.__str__ = function __str__ () {\n if(AST_StatementWithBody.prototype.__str__) return AST_StatementWithBody.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_With.prototype, "__bases__", {value: [AST_StatementWithBody]});\n AST_With.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["clauses"] = "[AST_WithClause*] the `with` clauses (comma separated)";\n return RS_d;\n }).call(this);\n\n function AST_WithClause() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_WithClause.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_WithClause, AST_Node);\n AST_WithClause.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_WithClause.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.expression._walk(visitor);\n if (self.alias) {\n self.alias._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_WithClause.prototype._walk.__argnames__) Object.defineProperties(AST_WithClause.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_WithClause.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_WithClause.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_WithClause.prototype, "__bases__", {value: [AST_Node]});\n AST_WithClause.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = "[AST_Node] the expression";\n RS_d["alias"] = "[AST_SymbolAlias?] optional alias for this expression";\n return RS_d;\n }).call(this);\n\n function AST_Scope() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Scope.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Scope, AST_Block);\n AST_Scope.prototype.__init__ = function __init__ () {\n AST_Block.prototype.__init__ && AST_Block.prototype.__init__.apply(this, arguments);\n };\n AST_Scope.prototype.__repr__ = function __repr__ () {\n if(AST_Block.prototype.__repr__) return AST_Block.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Scope.prototype.__str__ = function __str__ () {\n if(AST_Block.prototype.__str__) return AST_Block.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Scope.prototype, "__bases__", {value: [AST_Block]});\n AST_Scope.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["localvars"] = "[SymbolDef*] list of variables local to this scope";\n RS_d["docstrings"] = "[AST_String*] list of docstrings for this scope";\n return RS_d;\n }).call(this);\n\n function AST_Toplevel() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Toplevel.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Toplevel, AST_Scope);\n AST_Toplevel.prototype.__init__ = function __init__ () {\n AST_Scope.prototype.__init__ && AST_Scope.prototype.__init__.apply(this, arguments);\n };\n AST_Toplevel.prototype.__repr__ = function __repr__ () {\n if(AST_Scope.prototype.__repr__) return AST_Scope.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Toplevel.prototype.__str__ = function __str__ () {\n if(AST_Scope.prototype.__str__) return AST_Scope.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Toplevel.prototype, "__bases__", {value: [AST_Scope]});\n AST_Toplevel.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["globals"] = "[Object/S] a map of name -> SymbolDef for all undeclared names";\n RS_d["baselib"] = "[Object/s] a collection of used parts of baselib";\n RS_d["imports"] = "[Object/S] a map of module_id->AST_Toplevel for all imported modules (this represents all imported modules across all source files)";\n RS_d["imported_module_ids"] = "[string*] a list of module ids that were imported by this module, specifically";\n RS_d["nonlocalvars"] = "[String*] a list of all non-local variable names (names that come from the global scope)";\n RS_d["shebang"] = "[string] If #! line is present, it will be stored here";\n RS_d["import_order"] = "[number] The global order in which this scope was imported";\n RS_d["module_id"] = "[string] The id of this module";\n RS_d["exports"] = "[SymbolDef*] list of names exported from this module";\n RS_d["classes"] = "[Object/S] a map of class names to AST_Class for classes defined in this module";\n RS_d["filename"] = "[string] The absolute path to the file from which this module was read";\n RS_d["srchash"] = "[string] SHA1 hash of source code, used for caching";\n RS_d["comments_after"] = "[array] True iff there were comments before this token";\n return RS_d;\n }).call(this);\n\n function AST_Import() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Import.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Import, AST_Statement);\n AST_Import.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Import.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var arg;\n if (self.alias) {\n self.alias._walk(visitor);\n }\n if (self.argnames) {\n var RS_Iter17 = RS_Iterable(self.argnames);\n for (var RS_Index17 = 0; RS_Index17 < RS_Iter17.length; RS_Index17++) {\n arg = RS_Iter17[RS_Index17];\n arg._walk(visitor);\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Import.prototype._walk.__argnames__) Object.defineProperties(AST_Import.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Import.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Import.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Import.prototype, "__bases__", {value: [AST_Statement]});\n AST_Import.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["module"] = "[AST_SymbolVar] name of the module we\'re importing";\n RS_d["key"] = "[string] The key by which this module is stored in the global modules mapping";\n RS_d["alias"] = "[AST_SymbolAlias] The name this module is imported as, can be None. For import x as y statements.";\n RS_d["argnames"] = "[AST_ImportedVar*] names of objects to be imported";\n RS_d["body"] = "[AST_TopLevel] parsed contents of the imported file";\n return RS_d;\n }).call(this);\n\n function AST_Imports() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Imports.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Imports, AST_Statement);\n AST_Imports.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Imports.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var imp;\n var RS_Iter18 = RS_Iterable(self.imports);\n for (var RS_Index18 = 0; RS_Index18 < RS_Iter18.length; RS_Index18++) {\n imp = RS_Iter18[RS_Index18];\n imp._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Imports.prototype._walk.__argnames__) Object.defineProperties(AST_Imports.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Imports.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Imports.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Imports.prototype, "__bases__", {value: [AST_Statement]});\n AST_Imports.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["imports"] = "[AST_Import+] array of imports";\n return RS_d;\n }).call(this);\n\n function AST_Decorator() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Decorator.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Decorator, AST_Node);\n AST_Decorator.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Decorator.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n if (self.expression) {\n self.expression.walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Decorator.prototype._walk.__argnames__) Object.defineProperties(AST_Decorator.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Decorator.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Decorator.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Decorator.prototype, "__bases__", {value: [AST_Node]});\n AST_Decorator.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = "[AST_Node] the decorator expression";\n return RS_d;\n }).call(this);\n\n function AST_Lambda() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Lambda.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Lambda, AST_Scope);\n AST_Lambda.prototype.__init__ = function __init__ () {\n AST_Scope.prototype.__init__ && AST_Scope.prototype.__init__.apply(this, arguments);\n };\n AST_Lambda.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var d, arg;\n if (self.decorators) {\n var RS_Iter19 = RS_Iterable(self.decorators);\n for (var RS_Index19 = 0; RS_Index19 < RS_Iter19.length; RS_Index19++) {\n d = RS_Iter19[RS_Index19];\n d.walk(visitor);\n }\n }\n if (self.name) {\n self.name._walk(visitor);\n }\n var RS_Iter20 = RS_Iterable(self.argnames);\n for (var RS_Index20 = 0; RS_Index20 < RS_Iter20.length; RS_Index20++) {\n arg = RS_Iter20[RS_Index20];\n arg._walk(visitor);\n }\n if (self.argnames.starargs) {\n self.argnames.starargs._walk(visitor);\n }\n if (self.argnames.kwargs) {\n self.argnames.kwargs._walk(visitor);\n }\n walk_body(self, visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Lambda.prototype._walk.__argnames__) Object.defineProperties(AST_Lambda.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Lambda.prototype.__repr__ = function __repr__ () {\n if(AST_Scope.prototype.__repr__) return AST_Scope.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Lambda.prototype.__str__ = function __str__ () {\n if(AST_Scope.prototype.__str__) return AST_Scope.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Lambda.prototype, "__bases__", {value: [AST_Scope]});\n AST_Lambda.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "[AST_SymbolDeclaration?] the name of this function";\n RS_d["argnames"] = "[AST_SymbolFunarg*] array of function arguments";\n RS_d["decorators"] = "[AST_Decorator*] function decorators, if any";\n RS_d["is_generator"] = "[bool*] True iff this function is a generator";\n RS_d["is_expression"] = "[bool*] True iff this function is a function expression";\n RS_d["is_anonymous"] = "[bool*] True iff this function is an anonymous function";\n RS_d["return_annotation"] = "[AST_Node?] The return type annotation provided (if any)";\n return RS_d;\n }).call(this);\n\n function AST_Function() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Function.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Function, AST_Lambda);\n AST_Function.prototype.__init__ = function __init__ () {\n AST_Lambda.prototype.__init__ && AST_Lambda.prototype.__init__.apply(this, arguments);\n };\n AST_Function.prototype.__repr__ = function __repr__ () {\n if(AST_Lambda.prototype.__repr__) return AST_Lambda.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Function.prototype.__str__ = function __str__ () {\n if(AST_Lambda.prototype.__str__) return AST_Lambda.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Function.prototype, "__bases__", {value: [AST_Lambda]});\n\n function AST_Class() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Class.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Class, AST_Scope);\n AST_Class.prototype.__init__ = function __init__ () {\n AST_Scope.prototype.__init__ && AST_Scope.prototype.__init__.apply(this, arguments);\n };\n AST_Class.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var d;\n if (self.decorators) {\n var RS_Iter21 = RS_Iterable(self.decorators);\n for (var RS_Index21 = 0; RS_Index21 < RS_Iter21.length; RS_Index21++) {\n d = RS_Iter21[RS_Index21];\n d.walk(visitor);\n }\n }\n self.name._walk(visitor);\n walk_body(self, visitor);\n if (self.parent) self.parent._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Class.prototype._walk.__argnames__) Object.defineProperties(AST_Class.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Class.prototype.__repr__ = function __repr__ () {\n if(AST_Scope.prototype.__repr__) return AST_Scope.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Class.prototype.__str__ = function __str__ () {\n if(AST_Scope.prototype.__str__) return AST_Scope.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Class.prototype, "__bases__", {value: [AST_Scope]});\n AST_Class.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "[AST_SymbolDeclaration?] the name of this class";\n RS_d["init"] = "[AST_Function] constructor for the class";\n RS_d["parent"] = "[AST_Symbol?] parent class this class inherits from";\n RS_d["bases"] = "[AST_Symbol*] list of base classes this class inherits from";\n RS_d["static"] = "[dict] A hash whose keys are names of static methods for this class";\n RS_d["external"] = "[boolean] true if class is declared elsewhere, but will be within current scope at runtime";\n RS_d["bound"] = "[string*] list of methods that need to be bound to self";\n RS_d["decorators"] = "[AST_Decorator*] function decorators, if any";\n RS_d["module_id"] = "[string] The id of the module this class is defined in";\n RS_d["statements"] = "[AST_Node*] list of statements in the class scope (excluding method definitions)";\n RS_d["dynamic_properties"] = "[dict] map of dynamic property names to property descriptors of the form {getter:AST_Method, setter:AST_Method";\n RS_d["classvars"] = "[dict] map containing all class variables as keys, to be used to easily test for existence of a class variable";\n return RS_d;\n }).call(this);\n\n function AST_Method() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Method.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Method, AST_Lambda);\n AST_Method.prototype.__init__ = function __init__ () {\n AST_Lambda.prototype.__init__ && AST_Lambda.prototype.__init__.apply(this, arguments);\n };\n AST_Method.prototype.__repr__ = function __repr__ () {\n if(AST_Lambda.prototype.__repr__) return AST_Lambda.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Method.prototype.__str__ = function __str__ () {\n if(AST_Lambda.prototype.__str__) return AST_Lambda.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Method.prototype, "__bases__", {value: [AST_Lambda]});\n AST_Method.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = "[boolean] true if method is static";\n RS_d["is_getter"] = "[boolean] true if method is a property getter";\n RS_d["is_setter"] = "[boolean] true if method is a property setter";\n return RS_d;\n }).call(this);\n\n function AST_Jump() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Jump.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Jump, AST_Statement);\n AST_Jump.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Jump.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Jump.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Jump.prototype, "__bases__", {value: [AST_Statement]});\n\n function AST_Exit() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Exit.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Exit, AST_Jump);\n AST_Exit.prototype.__init__ = function __init__ () {\n AST_Jump.prototype.__init__ && AST_Jump.prototype.__init__.apply(this, arguments);\n };\n AST_Exit.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n if (self.value) {\n self.value._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Exit.prototype._walk.__argnames__) Object.defineProperties(AST_Exit.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Exit.prototype.__repr__ = function __repr__ () {\n if(AST_Jump.prototype.__repr__) return AST_Jump.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Exit.prototype.__str__ = function __str__ () {\n if(AST_Jump.prototype.__str__) return AST_Jump.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Exit.prototype, "__bases__", {value: [AST_Jump]});\n AST_Exit.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value"] = "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return";\n return RS_d;\n }).call(this);\n\n function AST_Return() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Return.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Return, AST_Exit);\n AST_Return.prototype.__init__ = function __init__ () {\n AST_Exit.prototype.__init__ && AST_Exit.prototype.__init__.apply(this, arguments);\n };\n AST_Return.prototype.__repr__ = function __repr__ () {\n if(AST_Exit.prototype.__repr__) return AST_Exit.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Return.prototype.__str__ = function __str__ () {\n if(AST_Exit.prototype.__str__) return AST_Exit.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Return.prototype, "__bases__", {value: [AST_Exit]});\n\n function AST_Yield() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Yield.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Yield, AST_Return);\n AST_Yield.prototype.__init__ = function __init__ () {\n AST_Return.prototype.__init__ && AST_Return.prototype.__init__.apply(this, arguments);\n };\n AST_Yield.prototype.__repr__ = function __repr__ () {\n if(AST_Return.prototype.__repr__) return AST_Return.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Yield.prototype.__str__ = function __str__ () {\n if(AST_Return.prototype.__str__) return AST_Return.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Yield.prototype, "__bases__", {value: [AST_Return]});\n AST_Yield.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["is_yield_from"] = "[bool] True iff this is a yield from, False otherwise";\n return RS_d;\n }).call(this);\n\n function AST_Throw() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Throw.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Throw, AST_Exit);\n AST_Throw.prototype.__init__ = function __init__ () {\n AST_Exit.prototype.__init__ && AST_Exit.prototype.__init__.apply(this, arguments);\n };\n AST_Throw.prototype.__repr__ = function __repr__ () {\n if(AST_Exit.prototype.__repr__) return AST_Exit.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Throw.prototype.__str__ = function __str__ () {\n if(AST_Exit.prototype.__str__) return AST_Exit.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Throw.prototype, "__bases__", {value: [AST_Exit]});\n\n function AST_LoopControl() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_LoopControl.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_LoopControl, AST_Jump);\n AST_LoopControl.prototype.__init__ = function __init__ () {\n AST_Jump.prototype.__init__ && AST_Jump.prototype.__init__.apply(this, arguments);\n };\n AST_LoopControl.prototype.__repr__ = function __repr__ () {\n if(AST_Jump.prototype.__repr__) return AST_Jump.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_LoopControl.prototype.__str__ = function __str__ () {\n if(AST_Jump.prototype.__str__) return AST_Jump.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_LoopControl.prototype, "__bases__", {value: [AST_Jump]});\n\n function AST_Break() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Break.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Break, AST_LoopControl);\n AST_Break.prototype.__init__ = function __init__ () {\n AST_LoopControl.prototype.__init__ && AST_LoopControl.prototype.__init__.apply(this, arguments);\n };\n AST_Break.prototype.__repr__ = function __repr__ () {\n if(AST_LoopControl.prototype.__repr__) return AST_LoopControl.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Break.prototype.__str__ = function __str__ () {\n if(AST_LoopControl.prototype.__str__) return AST_LoopControl.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Break.prototype, "__bases__", {value: [AST_LoopControl]});\n\n function AST_Continue() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Continue.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Continue, AST_LoopControl);\n AST_Continue.prototype.__init__ = function __init__ () {\n AST_LoopControl.prototype.__init__ && AST_LoopControl.prototype.__init__.apply(this, arguments);\n };\n AST_Continue.prototype.__repr__ = function __repr__ () {\n if(AST_LoopControl.prototype.__repr__) return AST_LoopControl.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Continue.prototype.__str__ = function __str__ () {\n if(AST_LoopControl.prototype.__str__) return AST_LoopControl.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Continue.prototype, "__bases__", {value: [AST_LoopControl]});\n\n function AST_If() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_If.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_If, AST_StatementWithBody);\n AST_If.prototype.__init__ = function __init__ () {\n AST_StatementWithBody.prototype.__init__ && AST_StatementWithBody.prototype.__init__.apply(this, arguments);\n };\n AST_If.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.condition._walk(visitor);\n self.body._walk(visitor);\n if (self.alternative) {\n self.alternative._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_If.prototype._walk.__argnames__) Object.defineProperties(AST_If.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_If.prototype.__repr__ = function __repr__ () {\n if(AST_StatementWithBody.prototype.__repr__) return AST_StatementWithBody.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_If.prototype.__str__ = function __str__ () {\n if(AST_StatementWithBody.prototype.__str__) return AST_StatementWithBody.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_If.prototype, "__bases__", {value: [AST_StatementWithBody]});\n AST_If.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = "[AST_Node] the `if` condition";\n RS_d["alternative"] = "[AST_Statement?] the `else` part, or null if not present";\n return RS_d;\n }).call(this);\n\n function AST_Try() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Try.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Try, AST_Block);\n AST_Try.prototype.__init__ = function __init__ () {\n AST_Block.prototype.__init__ && AST_Block.prototype.__init__.apply(this, arguments);\n };\n AST_Try.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n walk_body(self, visitor);\n if (self.bcatch) {\n self.bcatch._walk(visitor);\n }\n if (self.belse) {\n self.belse._walk(visitor);\n }\n if (self.bfinally) {\n self.bfinally._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Try.prototype._walk.__argnames__) Object.defineProperties(AST_Try.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Try.prototype.__repr__ = function __repr__ () {\n if(AST_Block.prototype.__repr__) return AST_Block.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Try.prototype.__str__ = function __str__ () {\n if(AST_Block.prototype.__str__) return AST_Block.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Try.prototype, "__bases__", {value: [AST_Block]});\n AST_Try.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["bcatch"] = "[AST_Catch?] the catch block, or null if not present";\n RS_d["bfinally"] = "[AST_Finally?] the finally block, or null if not present";\n RS_d["belse"] = "[AST_Else?] the else block for null if not present";\n return RS_d;\n }).call(this);\n\n function AST_Catch() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Catch.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Catch, AST_Block);\n AST_Catch.prototype.__init__ = function __init__ () {\n AST_Block.prototype.__init__ && AST_Block.prototype.__init__.apply(this, arguments);\n };\n AST_Catch.prototype.__repr__ = function __repr__ () {\n if(AST_Block.prototype.__repr__) return AST_Block.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Catch.prototype.__str__ = function __str__ () {\n if(AST_Block.prototype.__str__) return AST_Block.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Catch.prototype, "__bases__", {value: [AST_Block]});\n\n function AST_Except() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Except.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Except, AST_Block);\n AST_Except.prototype.__init__ = function __init__ () {\n AST_Block.prototype.__init__ && AST_Block.prototype.__init__.apply(this, arguments);\n };\n AST_Except.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(this, (function() {\n var RS_anonfunc = function () {\n var e;\n if (self.argname) {\n self.argname.walk(visitor);\n }\n if (self.errors) {\n var RS_Iter22 = RS_Iterable(self.errors);\n for (var RS_Index22 = 0; RS_Index22 < RS_Iter22.length; RS_Index22++) {\n e = RS_Iter22[RS_Index22];\n e.walk(visitor);\n }\n }\n walk_body(self, visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Except.prototype._walk.__argnames__) Object.defineProperties(AST_Except.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Except.prototype.__repr__ = function __repr__ () {\n if(AST_Block.prototype.__repr__) return AST_Block.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Except.prototype.__str__ = function __str__ () {\n if(AST_Block.prototype.__str__) return AST_Block.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Except.prototype, "__bases__", {value: [AST_Block]});\n AST_Except.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["argname"] = "[AST_SymbolCatch] symbol for the exception";\n RS_d["errors"] = "[AST_SymbolVar*] error classes to catch in this block";\n return RS_d;\n }).call(this);\n\n function AST_Finally() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Finally.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Finally, AST_Block);\n AST_Finally.prototype.__init__ = function __init__ () {\n AST_Block.prototype.__init__ && AST_Block.prototype.__init__.apply(this, arguments);\n };\n AST_Finally.prototype.__repr__ = function __repr__ () {\n if(AST_Block.prototype.__repr__) return AST_Block.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Finally.prototype.__str__ = function __str__ () {\n if(AST_Block.prototype.__str__) return AST_Block.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Finally.prototype, "__bases__", {value: [AST_Block]});\n\n function AST_Else() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Else.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Else, AST_Block);\n AST_Else.prototype.__init__ = function __init__ () {\n AST_Block.prototype.__init__ && AST_Block.prototype.__init__.apply(this, arguments);\n };\n AST_Else.prototype.__repr__ = function __repr__ () {\n if(AST_Block.prototype.__repr__) return AST_Block.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Else.prototype.__str__ = function __str__ () {\n if(AST_Block.prototype.__str__) return AST_Block.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Else.prototype, "__bases__", {value: [AST_Block]});\n\n function AST_Definitions() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Definitions.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Definitions, AST_Statement);\n AST_Definitions.prototype.__init__ = function __init__ () {\n AST_Statement.prototype.__init__ && AST_Statement.prototype.__init__.apply(this, arguments);\n };\n AST_Definitions.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var def_;\n var RS_Iter23 = RS_Iterable(self.definitions);\n for (var RS_Index23 = 0; RS_Index23 < RS_Iter23.length; RS_Index23++) {\n def_ = RS_Iter23[RS_Index23];\n def_._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Definitions.prototype._walk.__argnames__) Object.defineProperties(AST_Definitions.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Definitions.prototype.__repr__ = function __repr__ () {\n if(AST_Statement.prototype.__repr__) return AST_Statement.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Definitions.prototype.__str__ = function __str__ () {\n if(AST_Statement.prototype.__str__) return AST_Statement.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Definitions.prototype, "__bases__", {value: [AST_Statement]});\n AST_Definitions.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["definitions"] = "[AST_VarDef*] array of variable definitions";\n return RS_d;\n }).call(this);\n\n function AST_Var() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Var.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Var, AST_Definitions);\n AST_Var.prototype.__init__ = function __init__ () {\n AST_Definitions.prototype.__init__ && AST_Definitions.prototype.__init__.apply(this, arguments);\n };\n AST_Var.prototype.__repr__ = function __repr__ () {\n if(AST_Definitions.prototype.__repr__) return AST_Definitions.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Var.prototype.__str__ = function __str__ () {\n if(AST_Definitions.prototype.__str__) return AST_Definitions.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Var.prototype, "__bases__", {value: [AST_Definitions]});\n\n function AST_VarDef() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_VarDef.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_VarDef, AST_Node);\n AST_VarDef.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_VarDef.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.name._walk(visitor);\n if (self.value) {\n self.value._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_VarDef.prototype._walk.__argnames__) Object.defineProperties(AST_VarDef.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_VarDef.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_VarDef.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_VarDef.prototype, "__bases__", {value: [AST_Node]});\n AST_VarDef.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "[AST_SymbolVar|AST_SymbolNonlocal] name of the variable";\n RS_d["value"] = "[AST_Node?] initializer, or null if there\'s no initializer";\n return RS_d;\n }).call(this);\n\n function AST_BaseCall() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_BaseCall.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_BaseCall, AST_Node);\n AST_BaseCall.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_BaseCall.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_BaseCall.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_BaseCall.prototype, "__bases__", {value: [AST_Node]});\n AST_BaseCall.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["args"] = "[AST_Node*] array of arguments";\n return RS_d;\n }).call(this);\n\n function AST_Call() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Call.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Call, AST_BaseCall);\n AST_Call.prototype.__init__ = function __init__ () {\n AST_BaseCall.prototype.__init__ && AST_BaseCall.prototype.__init__.apply(this, arguments);\n };\n AST_Call.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var arg;\n self.expression._walk(visitor);\n var RS_Iter24 = RS_Iterable(self.args);\n for (var RS_Index24 = 0; RS_Index24 < RS_Iter24.length; RS_Index24++) {\n arg = RS_Iter24[RS_Index24];\n arg._walk(visitor);\n }\n if (self.args.kwargs) {\n var RS_Iter25 = RS_Iterable(self.args.kwargs);\n for (var RS_Index25 = 0; RS_Index25 < RS_Iter25.length; RS_Index25++) {\n arg = RS_Iter25[RS_Index25];\n arg[0]._walk(visitor);\n arg[1]._walk(visitor);\n }\n }\n if (self.args.kwarg_items) {\n var RS_Iter26 = RS_Iterable(self.args.kwarg_items);\n for (var RS_Index26 = 0; RS_Index26 < RS_Iter26.length; RS_Index26++) {\n arg = RS_Iter26[RS_Index26];\n arg._walk(visitor);\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Call.prototype._walk.__argnames__) Object.defineProperties(AST_Call.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Call.prototype.__repr__ = function __repr__ () {\n if(AST_BaseCall.prototype.__repr__) return AST_BaseCall.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Call.prototype.__str__ = function __str__ () {\n if(AST_BaseCall.prototype.__str__) return AST_BaseCall.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Call.prototype, "__bases__", {value: [AST_BaseCall]});\n AST_Call.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = "[AST_Node] expression to invoke as function";\n return RS_d;\n }).call(this);\n\n function AST_ClassCall() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ClassCall.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ClassCall, AST_BaseCall);\n AST_ClassCall.prototype.__init__ = function __init__ () {\n AST_BaseCall.prototype.__init__ && AST_BaseCall.prototype.__init__.apply(this, arguments);\n };\n AST_ClassCall.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var arg;\n if (self.expression) self.expression._walk(visitor);\n var RS_Iter27 = RS_Iterable(self.args);\n for (var RS_Index27 = 0; RS_Index27 < RS_Iter27.length; RS_Index27++) {\n arg = RS_Iter27[RS_Index27];\n arg._walk(visitor);\n }\n var RS_Iter28 = RS_Iterable(self.args.kwargs);\n for (var RS_Index28 = 0; RS_Index28 < RS_Iter28.length; RS_Index28++) {\n arg = RS_Iter28[RS_Index28];\n arg[0]._walk(visitor);\n arg[1]._walk(visitor);\n }\n var RS_Iter29 = RS_Iterable(self.args.kwarg_items);\n for (var RS_Index29 = 0; RS_Index29 < RS_Iter29.length; RS_Index29++) {\n arg = RS_Iter29[RS_Index29];\n arg._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_ClassCall.prototype._walk.__argnames__) Object.defineProperties(AST_ClassCall.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_ClassCall.prototype.__repr__ = function __repr__ () {\n if(AST_BaseCall.prototype.__repr__) return AST_BaseCall.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ClassCall.prototype.__str__ = function __str__ () {\n if(AST_BaseCall.prototype.__str__) return AST_BaseCall.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ClassCall.prototype, "__bases__", {value: [AST_BaseCall]});\n AST_ClassCall.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["class"] = "[string] name of the class method belongs to";\n RS_d["method"] = "[string] class method being called";\n RS_d["static"] = "[boolean] defines whether the method is static";\n return RS_d;\n }).call(this);\n\n function AST_New() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_New.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_New, AST_Call);\n AST_New.prototype.__init__ = function __init__ () {\n AST_Call.prototype.__init__ && AST_Call.prototype.__init__.apply(this, arguments);\n };\n AST_New.prototype.__repr__ = function __repr__ () {\n if(AST_Call.prototype.__repr__) return AST_Call.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_New.prototype.__str__ = function __str__ () {\n if(AST_Call.prototype.__str__) return AST_Call.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_New.prototype, "__bases__", {value: [AST_Call]});\n\n function AST_Seq() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Seq.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Seq, AST_Node);\n AST_Seq.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Seq.prototype.to_array = function to_array() {\n var self = this;\n var p, a;\n p = self;\n a = RS_list_decorate([]);\n while (p) {\n a.push(p.car);\n if (p.cdr && !(is_node_type(p.cdr, AST_Seq))) {\n a.push(p.cdr);\n break;\n }\n p = p.cdr;\n }\n return a;\n };\n if (!AST_Seq.prototype.to_array.__module__) Object.defineProperties(AST_Seq.prototype.to_array, {\n __module__ : {value: "ast"}\n });\n AST_Seq.prototype.add = function add(node) {\n var self = this;\n var p, cell;\n p = self;\n while (p) {\n if (!(is_node_type(p.cdr, AST_Seq))) {\n cell = AST_Seq.prototype.cons.call(p.cdr, node);\n return p.cdr = cell;\n }\n p = p.cdr;\n }\n };\n if (!AST_Seq.prototype.add.__argnames__) Object.defineProperties(AST_Seq.prototype.add, {\n __argnames__ : {value: ["node"]},\n __module__ : {value: "ast"}\n });\n AST_Seq.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.car._walk(visitor);\n if (self.cdr) {\n self.cdr._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Seq.prototype._walk.__argnames__) Object.defineProperties(AST_Seq.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Seq.prototype.cons = function cons(x, y) {\n var self = this;\n var seq;\n seq = new AST_Seq(x);\n seq.car = x;\n seq.cdr = y;\n return seq;\n };\n if (!AST_Seq.prototype.cons.__argnames__) Object.defineProperties(AST_Seq.prototype.cons, {\n __argnames__ : {value: ["x", "y"]},\n __module__ : {value: "ast"}\n });\n AST_Seq.prototype.from_array = function from_array(array) {\n var self = this;\n var ans, i, p;\n if (array.length === 0) {\n return null;\n }\n if (array.length === 1) {\n return array[0].clone();\n }\n ans = null;\n for (var RS_Index30 = array.length - 1; RS_Index30 > -1; RS_Index30-=1) {\n i = RS_Index30;\n ans = AST_Seq.prototype.cons.call(array[(typeof i === "number" && i < 0) ? array.length + i : i], ans);\n }\n p = ans;\n while (p) {\n if (p.cdr && !p.cdr.cdr) {\n p.cdr = p.cdr.car;\n break;\n }\n p = p.cdr;\n }\n return ans;\n };\n if (!AST_Seq.prototype.from_array.__argnames__) Object.defineProperties(AST_Seq.prototype.from_array, {\n __argnames__ : {value: ["array"]},\n __module__ : {value: "ast"}\n });\n AST_Seq.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Seq.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Seq.prototype, "__bases__", {value: [AST_Node]});\n AST_Seq.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["car"] = "[AST_Node] first element in sequence";\n RS_d["cdr"] = "[AST_Node] second element in sequence";\n return RS_d;\n }).call(this);\n\n function AST_PropAccess() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_PropAccess.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_PropAccess, AST_Node);\n AST_PropAccess.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_PropAccess.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_PropAccess.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_PropAccess.prototype, "__bases__", {value: [AST_Node]});\n AST_PropAccess.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = "[AST_Node] the “container” expression";\n RS_d["property"] = "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it\'s an arbitrary AST_Node";\n return RS_d;\n }).call(this);\n\n function AST_Dot() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Dot.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Dot, AST_PropAccess);\n AST_Dot.prototype.__init__ = function __init__ () {\n AST_PropAccess.prototype.__init__ && AST_PropAccess.prototype.__init__.apply(this, arguments);\n };\n AST_Dot.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.expression._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Dot.prototype._walk.__argnames__) Object.defineProperties(AST_Dot.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Dot.prototype.__repr__ = function __repr__ () {\n if(AST_PropAccess.prototype.__repr__) return AST_PropAccess.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Dot.prototype.__str__ = function __str__ () {\n if(AST_PropAccess.prototype.__str__) return AST_PropAccess.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Dot.prototype, "__bases__", {value: [AST_PropAccess]});\n\n function AST_Sub() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Sub.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Sub, AST_PropAccess);\n AST_Sub.prototype.__init__ = function __init__ () {\n AST_PropAccess.prototype.__init__ && AST_PropAccess.prototype.__init__.apply(this, arguments);\n };\n AST_Sub.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.expression._walk(visitor);\n self.property._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Sub.prototype._walk.__argnames__) Object.defineProperties(AST_Sub.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Sub.prototype.__repr__ = function __repr__ () {\n if(AST_PropAccess.prototype.__repr__) return AST_PropAccess.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Sub.prototype.__str__ = function __str__ () {\n if(AST_PropAccess.prototype.__str__) return AST_PropAccess.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Sub.prototype, "__bases__", {value: [AST_PropAccess]});\n\n function AST_ItemAccess() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ItemAccess.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ItemAccess, AST_PropAccess);\n AST_ItemAccess.prototype.__init__ = function __init__ () {\n AST_PropAccess.prototype.__init__ && AST_PropAccess.prototype.__init__.apply(this, arguments);\n };\n AST_ItemAccess.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.expression._walk(visitor);\n self.property._walk(visitor);\n if (self.assignment) {\n self.assignment._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_ItemAccess.prototype._walk.__argnames__) Object.defineProperties(AST_ItemAccess.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_ItemAccess.prototype.__repr__ = function __repr__ () {\n if(AST_PropAccess.prototype.__repr__) return AST_PropAccess.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ItemAccess.prototype.__str__ = function __str__ () {\n if(AST_PropAccess.prototype.__str__) return AST_PropAccess.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ItemAccess.prototype, "__bases__", {value: [AST_PropAccess]});\n AST_ItemAccess.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["assignment"] = "[AST_Node or None] Not None if this is an assignment (a[x] = y) rather than a simple access";\n return RS_d;\n }).call(this);\n\n function AST_Splice() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Splice.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Splice, AST_PropAccess);\n AST_Splice.prototype.__init__ = function __init__ () {\n AST_PropAccess.prototype.__init__ && AST_PropAccess.prototype.__init__.apply(this, arguments);\n };\n AST_Splice.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.expression._walk(visitor);\n self.property._walk(visitor);\n self.property2._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Splice.prototype._walk.__argnames__) Object.defineProperties(AST_Splice.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Splice.prototype.__repr__ = function __repr__ () {\n if(AST_PropAccess.prototype.__repr__) return AST_PropAccess.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Splice.prototype.__str__ = function __str__ () {\n if(AST_PropAccess.prototype.__str__) return AST_PropAccess.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Splice.prototype, "__bases__", {value: [AST_PropAccess]});\n AST_Splice.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["property2"] = "[AST_Node] the 2nd property to access - typically ending index for the array.";\n RS_d["assignment"] = "[AST_Node] The data being spliced in.";\n return RS_d;\n }).call(this);\n\n function AST_Unary() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Unary.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Unary, AST_Node);\n AST_Unary.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Unary.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.expression._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Unary.prototype._walk.__argnames__) Object.defineProperties(AST_Unary.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Unary.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Unary.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Unary.prototype, "__bases__", {value: [AST_Node]});\n AST_Unary.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["operator"] = "[string] the operator";\n RS_d["expression"] = "[AST_Node] expression that this unary operator applies to";\n RS_d["parenthesized"] = "[bool] Whether this unary expression was parenthesized";\n return RS_d;\n }).call(this);\n\n function AST_UnaryPrefix() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_UnaryPrefix.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_UnaryPrefix, AST_Unary);\n AST_UnaryPrefix.prototype.__init__ = function __init__ () {\n AST_Unary.prototype.__init__ && AST_Unary.prototype.__init__.apply(this, arguments);\n };\n AST_UnaryPrefix.prototype.__repr__ = function __repr__ () {\n if(AST_Unary.prototype.__repr__) return AST_Unary.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_UnaryPrefix.prototype.__str__ = function __str__ () {\n if(AST_Unary.prototype.__str__) return AST_Unary.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_UnaryPrefix.prototype, "__bases__", {value: [AST_Unary]});\n\n function AST_Binary() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Binary.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Binary, AST_Node);\n AST_Binary.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Binary.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.left._walk(visitor);\n self.right._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Binary.prototype._walk.__argnames__) Object.defineProperties(AST_Binary.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Binary.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Binary.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Binary.prototype, "__bases__", {value: [AST_Node]});\n AST_Binary.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["left"] = "[AST_Node] left-hand side expression";\n RS_d["operator"] = "[string] the operator";\n RS_d["right"] = "[AST_Node] right-hand side expression";\n return RS_d;\n }).call(this);\n\n function AST_Existential() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Existential.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Existential, AST_Node);\n AST_Existential.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Existential.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.expression._walk(visitor);\n if (self.after !== null && typeof self.after === "object") {\n self.after._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Existential.prototype._walk.__argnames__) Object.defineProperties(AST_Existential.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Existential.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Existential.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Existential.prototype, "__bases__", {value: [AST_Node]});\n AST_Existential.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = "[AST_Node] The expression whose existence we need to check";\n RS_d["after"] = "[None|string|AST_Node] is None when there is nothing following this operator, is a string when there is as AST_PropAccess following this operator, is an AST_Node if it is used a a shorthand for the conditional ternary, i.e. a ? b == a if a? else b";\n return RS_d;\n }).call(this);\n\n function AST_Conditional() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Conditional.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Conditional, AST_Node);\n AST_Conditional.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Conditional.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.condition._walk(visitor);\n self.consequent._walk(visitor);\n self.alternative._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Conditional.prototype._walk.__argnames__) Object.defineProperties(AST_Conditional.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Conditional.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Conditional.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Conditional.prototype, "__bases__", {value: [AST_Node]});\n AST_Conditional.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = "[AST_Node]";\n RS_d["consequent"] = "[AST_Node]";\n RS_d["alternative"] = "[AST_Node]";\n return RS_d;\n }).call(this);\n\n function AST_Assign() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Assign.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Assign, AST_Binary);\n AST_Assign.prototype.__init__ = function __init__ () {\n AST_Binary.prototype.__init__ && AST_Binary.prototype.__init__.apply(this, arguments);\n };\n AST_Assign.prototype.is_chained = function is_chained() {\n var self = this;\n return is_node_type(self.right, AST_Assign) || is_node_type(self.right, AST_Seq) && (is_node_type(self.right.car, AST_Assign) || is_node_type(self.right.cdr, AST_Assign));\n };\n if (!AST_Assign.prototype.is_chained.__module__) Object.defineProperties(AST_Assign.prototype.is_chained, {\n __module__ : {value: "ast"}\n });\n AST_Assign.prototype.traverse_chain = function traverse_chain() {\n var self = this;\n var right, left_hand_sides, next, assign;\n right = self.right;\n while (true) {\n if (is_node_type(right, AST_Assign)) {\n right = right.right;\n continue;\n }\n if (is_node_type(right, AST_Seq)) {\n if (is_node_type(right.car, AST_Assign)) {\n right = new AST_Seq((function(){\n var RS_d = Object.create(null);\n RS_d["car"] = right.car.right;\n RS_d["cdr"] = right.cdr;\n return RS_d;\n }).call(this));\n continue;\n }\n if (is_node_type(right.cdr, AST_Assign)) {\n right = right.cdr.right;\n continue;\n }\n }\n break;\n }\n left_hand_sides = [self.left];\n next = self.right;\n while (true) {\n if (is_node_type(next, AST_Assign)) {\n left_hand_sides.push(next.left);\n next = next.right;\n continue;\n }\n if (is_node_type(next, AST_Seq)) {\n if (is_node_type(next.cdr, AST_Assign)) {\n assign = next.cdr;\n left_hand_sides.push(new AST_Seq((function(){\n var RS_d = Object.create(null);\n RS_d["car"] = next.car;\n RS_d["cdr"] = assign.left;\n return RS_d;\n }).call(this)));\n next = assign.right;\n continue;\n }\n }\n break;\n }\n return [left_hand_sides, right];\n };\n if (!AST_Assign.prototype.traverse_chain.__module__) Object.defineProperties(AST_Assign.prototype.traverse_chain, {\n __module__ : {value: "ast"}\n });\n AST_Assign.prototype.__repr__ = function __repr__ () {\n if(AST_Binary.prototype.__repr__) return AST_Binary.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Assign.prototype.__str__ = function __str__ () {\n if(AST_Binary.prototype.__str__) return AST_Binary.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Assign.prototype, "__bases__", {value: [AST_Binary]});\n\n function AST_Array() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Array.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Array, AST_Node);\n AST_Array.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Array.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var el;\n var RS_Iter31 = RS_Iterable(self.elements);\n for (var RS_Index31 = 0; RS_Index31 < RS_Iter31.length; RS_Index31++) {\n el = RS_Iter31[RS_Index31];\n el._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Array.prototype._walk.__argnames__) Object.defineProperties(AST_Array.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Array.prototype.flatten = function flatten() {\n var self = this;\n function flatten(arr) {\n var ans, value;\n ans = RS_list_decorate([]);\n var RS_Iter32 = RS_Iterable(arr);\n for (var RS_Index32 = 0; RS_Index32 < RS_Iter32.length; RS_Index32++) {\n value = RS_Iter32[RS_Index32];\n if (is_node_type(value, AST_Seq)) {\n value = value.to_array();\n } else if (is_node_type(value, AST_Array)) {\n value = value.elements;\n }\n if (Array.isArray(value)) {\n ans = ans.concat(flatten(value));\n } else {\n ans.push(value);\n }\n }\n return ans;\n };\n if (!flatten.__argnames__) Object.defineProperties(flatten, {\n __argnames__ : {value: ["arr"]},\n __module__ : {value: "ast"}\n });\n\n return flatten(self.elements);\n };\n if (!AST_Array.prototype.flatten.__module__) Object.defineProperties(AST_Array.prototype.flatten, {\n __module__ : {value: "ast"}\n });\n AST_Array.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Array.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Array.prototype, "__bases__", {value: [AST_Node]});\n AST_Array.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = "[AST_Node*] array of elements";\n return RS_d;\n }).call(this);\n\n function AST_Object() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Object.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Object, AST_Node);\n AST_Object.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Object.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var prop;\n var RS_Iter33 = RS_Iterable(self.properties);\n for (var RS_Index33 = 0; RS_Index33 < RS_Iter33.length; RS_Index33++) {\n prop = RS_Iter33[RS_Index33];\n prop._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Object.prototype._walk.__argnames__) Object.defineProperties(AST_Object.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Object.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Object.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Object.prototype, "__bases__", {value: [AST_Node]});\n AST_Object.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["properties"] = "[AST_ObjectProperty*] array of properties";\n RS_d["is_pydict"] = "[bool] True if this object is a python dict literal";\n RS_d["is_jshash"] = "[bool] True if this object is a js hash literal";\n return RS_d;\n }).call(this);\n\n function AST_ExpressiveObject() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ExpressiveObject.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ExpressiveObject, AST_Object);\n AST_ExpressiveObject.prototype.__init__ = function __init__ () {\n AST_Object.prototype.__init__ && AST_Object.prototype.__init__.apply(this, arguments);\n };\n AST_ExpressiveObject.prototype.__repr__ = function __repr__ () {\n if(AST_Object.prototype.__repr__) return AST_Object.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ExpressiveObject.prototype.__str__ = function __str__ () {\n if(AST_Object.prototype.__str__) return AST_Object.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ExpressiveObject.prototype, "__bases__", {value: [AST_Object]});\n\n function AST_ObjectProperty() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ObjectProperty.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ObjectProperty, AST_Node);\n AST_ObjectProperty.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_ObjectProperty.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.key._walk(visitor);\n self.value._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_ObjectProperty.prototype._walk.__argnames__) Object.defineProperties(AST_ObjectProperty.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_ObjectProperty.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ObjectProperty.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ObjectProperty.prototype, "__bases__", {value: [AST_Node]});\n AST_ObjectProperty.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["key"] = "[AST_Node] the property expression";\n RS_d["value"] = "[AST_Node] property value. For setters and getters this is an AST_Function.";\n RS_d["quoted"] = "";\n return RS_d;\n }).call(this);\n\n function AST_ObjectKeyVal() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ObjectKeyVal.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ObjectKeyVal, AST_ObjectProperty);\n AST_ObjectKeyVal.prototype.__init__ = function __init__ () {\n AST_ObjectProperty.prototype.__init__ && AST_ObjectProperty.prototype.__init__.apply(this, arguments);\n };\n AST_ObjectKeyVal.prototype.__repr__ = function __repr__ () {\n if(AST_ObjectProperty.prototype.__repr__) return AST_ObjectProperty.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ObjectKeyVal.prototype.__str__ = function __str__ () {\n if(AST_ObjectProperty.prototype.__str__) return AST_ObjectProperty.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ObjectKeyVal.prototype, "__bases__", {value: [AST_ObjectProperty]});\n\n function AST_Set() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Set.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Set, AST_Node);\n AST_Set.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Set.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n var prop;\n var RS_Iter34 = RS_Iterable(self.items);\n for (var RS_Index34 = 0; RS_Index34 < RS_Iter34.length; RS_Index34++) {\n prop = RS_Iter34[RS_Index34];\n prop._walk(visitor);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_Set.prototype._walk.__argnames__) Object.defineProperties(AST_Set.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_Set.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Set.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Set.prototype, "__bases__", {value: [AST_Node]});\n AST_Set.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["items"] = "[AST_SetItem*] array of items";\n return RS_d;\n }).call(this);\n\n function AST_SetItem() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SetItem.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SetItem, AST_Node);\n AST_SetItem.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_SetItem.prototype._walk = function _walk(visitor) {\n var self = this;\n return visitor._visit(self, (function() {\n var RS_anonfunc = function () {\n self.value._walk(visitor);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })());\n };\n if (!AST_SetItem.prototype._walk.__argnames__) Object.defineProperties(AST_SetItem.prototype._walk, {\n __argnames__ : {value: ["visitor"]},\n __module__ : {value: "ast"}\n });\n AST_SetItem.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SetItem.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SetItem.prototype, "__bases__", {value: [AST_Node]});\n AST_SetItem.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value"] = "[AST_Node] The value of this item";\n return RS_d;\n }).call(this);\n\n function AST_Symbol() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Symbol.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Symbol, AST_Node);\n AST_Symbol.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Symbol.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Symbol.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Symbol.prototype, "__bases__", {value: [AST_Node]});\n AST_Symbol.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "[string] name of this symbol";\n RS_d["scope"] = "[AST_Scope/S] the current scope (not necessarily the definition scope)";\n RS_d["thedef"] = "[SymbolDef/S] the definition of this symbol";\n return RS_d;\n }).call(this);\n\n function AST_SymbolAlias() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolAlias.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolAlias, AST_Symbol);\n AST_SymbolAlias.prototype.__init__ = function __init__ () {\n AST_Symbol.prototype.__init__ && AST_Symbol.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolAlias.prototype.__repr__ = function __repr__ () {\n if(AST_Symbol.prototype.__repr__) return AST_Symbol.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolAlias.prototype.__str__ = function __str__ () {\n if(AST_Symbol.prototype.__str__) return AST_Symbol.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolAlias.prototype, "__bases__", {value: [AST_Symbol]});\n\n function AST_SymbolDeclaration() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolDeclaration.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolDeclaration, AST_Symbol);\n AST_SymbolDeclaration.prototype.__init__ = function __init__ () {\n AST_Symbol.prototype.__init__ && AST_Symbol.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolDeclaration.prototype.__repr__ = function __repr__ () {\n if(AST_Symbol.prototype.__repr__) return AST_Symbol.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolDeclaration.prototype.__str__ = function __str__ () {\n if(AST_Symbol.prototype.__str__) return AST_Symbol.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolDeclaration.prototype, "__bases__", {value: [AST_Symbol]});\n AST_SymbolDeclaration.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["init"] = "[AST_Node*/S] array of initializers for this declaration.";\n return RS_d;\n }).call(this);\n\n function AST_SymbolVar() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolVar.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolVar, AST_SymbolDeclaration);\n AST_SymbolVar.prototype.__init__ = function __init__ () {\n AST_SymbolDeclaration.prototype.__init__ && AST_SymbolDeclaration.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolVar.prototype.__repr__ = function __repr__ () {\n if(AST_SymbolDeclaration.prototype.__repr__) return AST_SymbolDeclaration.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolVar.prototype.__str__ = function __str__ () {\n if(AST_SymbolDeclaration.prototype.__str__) return AST_SymbolDeclaration.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolVar.prototype, "__bases__", {value: [AST_SymbolDeclaration]});\n\n function AST_ImportedVar() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_ImportedVar.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_ImportedVar, AST_SymbolVar);\n AST_ImportedVar.prototype.__init__ = function __init__ () {\n AST_SymbolVar.prototype.__init__ && AST_SymbolVar.prototype.__init__.apply(this, arguments);\n };\n AST_ImportedVar.prototype.__repr__ = function __repr__ () {\n if(AST_SymbolVar.prototype.__repr__) return AST_SymbolVar.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_ImportedVar.prototype.__str__ = function __str__ () {\n if(AST_SymbolVar.prototype.__str__) return AST_SymbolVar.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_ImportedVar.prototype, "__bases__", {value: [AST_SymbolVar]});\n AST_ImportedVar.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["alias"] = "AST_SymbolAlias the alias for this imported symbol";\n return RS_d;\n }).call(this);\n\n function AST_SymbolNonlocal() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolNonlocal.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolNonlocal, AST_SymbolDeclaration);\n AST_SymbolNonlocal.prototype.__init__ = function __init__ () {\n AST_SymbolDeclaration.prototype.__init__ && AST_SymbolDeclaration.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolNonlocal.prototype.__repr__ = function __repr__ () {\n if(AST_SymbolDeclaration.prototype.__repr__) return AST_SymbolDeclaration.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolNonlocal.prototype.__str__ = function __str__ () {\n if(AST_SymbolDeclaration.prototype.__str__) return AST_SymbolDeclaration.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolNonlocal.prototype, "__bases__", {value: [AST_SymbolDeclaration]});\n\n function AST_SymbolFunarg() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolFunarg.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolFunarg, AST_SymbolVar);\n AST_SymbolFunarg.prototype.__init__ = function __init__ () {\n AST_SymbolVar.prototype.__init__ && AST_SymbolVar.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolFunarg.prototype.__repr__ = function __repr__ () {\n if(AST_SymbolVar.prototype.__repr__) return AST_SymbolVar.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolFunarg.prototype.__str__ = function __str__ () {\n if(AST_SymbolVar.prototype.__str__) return AST_SymbolVar.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolFunarg.prototype, "__bases__", {value: [AST_SymbolVar]});\n AST_SymbolFunarg.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["annotation"] = "[AST_Node?] The annotation provided for this argument (if any)";\n return RS_d;\n }).call(this);\n\n function AST_SymbolDefun() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolDefun.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolDefun, AST_SymbolDeclaration);\n AST_SymbolDefun.prototype.__init__ = function __init__ () {\n AST_SymbolDeclaration.prototype.__init__ && AST_SymbolDeclaration.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolDefun.prototype.__repr__ = function __repr__ () {\n if(AST_SymbolDeclaration.prototype.__repr__) return AST_SymbolDeclaration.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolDefun.prototype.__str__ = function __str__ () {\n if(AST_SymbolDeclaration.prototype.__str__) return AST_SymbolDeclaration.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolDefun.prototype, "__bases__", {value: [AST_SymbolDeclaration]});\n\n function AST_SymbolLambda() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolLambda.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolLambda, AST_SymbolDeclaration);\n AST_SymbolLambda.prototype.__init__ = function __init__ () {\n AST_SymbolDeclaration.prototype.__init__ && AST_SymbolDeclaration.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolLambda.prototype.__repr__ = function __repr__ () {\n if(AST_SymbolDeclaration.prototype.__repr__) return AST_SymbolDeclaration.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolLambda.prototype.__str__ = function __str__ () {\n if(AST_SymbolDeclaration.prototype.__str__) return AST_SymbolDeclaration.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolLambda.prototype, "__bases__", {value: [AST_SymbolDeclaration]});\n\n function AST_SymbolCatch() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolCatch.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolCatch, AST_SymbolDeclaration);\n AST_SymbolCatch.prototype.__init__ = function __init__ () {\n AST_SymbolDeclaration.prototype.__init__ && AST_SymbolDeclaration.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolCatch.prototype.__repr__ = function __repr__ () {\n if(AST_SymbolDeclaration.prototype.__repr__) return AST_SymbolDeclaration.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolCatch.prototype.__str__ = function __str__ () {\n if(AST_SymbolDeclaration.prototype.__str__) return AST_SymbolDeclaration.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolCatch.prototype, "__bases__", {value: [AST_SymbolDeclaration]});\n\n function AST_SymbolRef() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_SymbolRef.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_SymbolRef, AST_Symbol);\n AST_SymbolRef.prototype.__init__ = function __init__ () {\n AST_Symbol.prototype.__init__ && AST_Symbol.prototype.__init__.apply(this, arguments);\n };\n AST_SymbolRef.prototype.__repr__ = function __repr__ () {\n if(AST_Symbol.prototype.__repr__) return AST_Symbol.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_SymbolRef.prototype.__str__ = function __str__ () {\n if(AST_Symbol.prototype.__str__) return AST_Symbol.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_SymbolRef.prototype, "__bases__", {value: [AST_Symbol]});\n AST_SymbolRef.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["parens"] = "[boolean/S] if true, this variable is wrapped in parentheses";\n return RS_d;\n }).call(this);\n\n function AST_This() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_This.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_This, AST_Symbol);\n AST_This.prototype.__init__ = function __init__ () {\n AST_Symbol.prototype.__init__ && AST_Symbol.prototype.__init__.apply(this, arguments);\n };\n AST_This.prototype.__repr__ = function __repr__ () {\n if(AST_Symbol.prototype.__repr__) return AST_Symbol.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_This.prototype.__str__ = function __str__ () {\n if(AST_Symbol.prototype.__str__) return AST_Symbol.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_This.prototype, "__bases__", {value: [AST_Symbol]});\n\n function AST_Constant() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Constant.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Constant, AST_Node);\n AST_Constant.prototype.__init__ = function __init__ () {\n AST_Node.prototype.__init__ && AST_Node.prototype.__init__.apply(this, arguments);\n };\n AST_Constant.prototype.__repr__ = function __repr__ () {\n if(AST_Node.prototype.__repr__) return AST_Node.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Constant.prototype.__str__ = function __str__ () {\n if(AST_Node.prototype.__str__) return AST_Node.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Constant.prototype, "__bases__", {value: [AST_Node]});\n\n function AST_String() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_String.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_String, AST_Constant);\n AST_String.prototype.__init__ = function __init__ () {\n AST_Constant.prototype.__init__ && AST_Constant.prototype.__init__.apply(this, arguments);\n };\n AST_String.prototype.__repr__ = function __repr__ () {\n if(AST_Constant.prototype.__repr__) return AST_Constant.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_String.prototype.__str__ = function __str__ () {\n if(AST_Constant.prototype.__str__) return AST_Constant.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_String.prototype, "__bases__", {value: [AST_Constant]});\n AST_String.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value"] = "[string] the contents of this string";\n return RS_d;\n }).call(this);\n\n function AST_Verbatim() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Verbatim.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Verbatim, AST_Constant);\n AST_Verbatim.prototype.__init__ = function __init__ () {\n AST_Constant.prototype.__init__ && AST_Constant.prototype.__init__.apply(this, arguments);\n };\n AST_Verbatim.prototype.__repr__ = function __repr__ () {\n if(AST_Constant.prototype.__repr__) return AST_Constant.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Verbatim.prototype.__str__ = function __str__ () {\n if(AST_Constant.prototype.__str__) return AST_Constant.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Verbatim.prototype, "__bases__", {value: [AST_Constant]});\n AST_Verbatim.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value"] = "[string] A string of raw JS code";\n return RS_d;\n }).call(this);\n\n function AST_Number() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Number.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Number, AST_Constant);\n AST_Number.prototype.__init__ = function __init__ () {\n AST_Constant.prototype.__init__ && AST_Constant.prototype.__init__.apply(this, arguments);\n };\n AST_Number.prototype.__repr__ = function __repr__ () {\n if(AST_Constant.prototype.__repr__) return AST_Constant.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Number.prototype.__str__ = function __str__ () {\n if(AST_Constant.prototype.__str__) return AST_Constant.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Number.prototype, "__bases__", {value: [AST_Constant]});\n AST_Number.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value"] = "[number] the numeric value";\n return RS_d;\n }).call(this);\n\n function AST_RegExp() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_RegExp.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_RegExp, AST_Constant);\n AST_RegExp.prototype.__init__ = function __init__ () {\n AST_Constant.prototype.__init__ && AST_Constant.prototype.__init__.apply(this, arguments);\n };\n AST_RegExp.prototype.__repr__ = function __repr__ () {\n if(AST_Constant.prototype.__repr__) return AST_Constant.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_RegExp.prototype.__str__ = function __str__ () {\n if(AST_Constant.prototype.__str__) return AST_Constant.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_RegExp.prototype, "__bases__", {value: [AST_Constant]});\n AST_RegExp.prototype.properties = (function(){\n var RS_d = Object.create(null);\n RS_d["value"] = "[RegExp] the actual regexp";\n return RS_d;\n }).call(this);\n\n function AST_Atom() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Atom.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Atom, AST_Constant);\n AST_Atom.prototype.__init__ = function __init__(initializer) {\n var self = this;\n if (initializer) {\n self.start = initializer.start;\n self.end = initializer.end;\n }\n };\n if (!AST_Atom.prototype.__init__.__argnames__) Object.defineProperties(AST_Atom.prototype.__init__, {\n __argnames__ : {value: ["initializer"]},\n __module__ : {value: "ast"}\n });\n AST_Atom.__argnames__ = AST_Atom.prototype.__init__.__argnames__;\n AST_Atom.__handles_kwarg_interpolation__ = AST_Atom.prototype.__init__.__handles_kwarg_interpolation__;\n AST_Atom.prototype.__repr__ = function __repr__ () {\n if(AST_Constant.prototype.__repr__) return AST_Constant.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Atom.prototype.__str__ = function __str__ () {\n if(AST_Constant.prototype.__str__) return AST_Constant.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Atom.prototype, "__bases__", {value: [AST_Constant]});\n\n function AST_Null() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Null.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Null, AST_Atom);\n AST_Null.prototype.__init__ = function __init__ () {\n AST_Atom.prototype.__init__ && AST_Atom.prototype.__init__.apply(this, arguments);\n };\n AST_Null.prototype.__repr__ = function __repr__ () {\n if(AST_Atom.prototype.__repr__) return AST_Atom.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Null.prototype.__str__ = function __str__ () {\n if(AST_Atom.prototype.__str__) return AST_Atom.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Null.prototype, "__bases__", {value: [AST_Atom]});\n AST_Null.prototype.value = null;\n\n function AST_NaN() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_NaN.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_NaN, AST_Atom);\n AST_NaN.prototype.__init__ = function __init__ () {\n AST_Atom.prototype.__init__ && AST_Atom.prototype.__init__.apply(this, arguments);\n };\n AST_NaN.prototype.__repr__ = function __repr__ () {\n if(AST_Atom.prototype.__repr__) return AST_Atom.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_NaN.prototype.__str__ = function __str__ () {\n if(AST_Atom.prototype.__str__) return AST_Atom.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_NaN.prototype, "__bases__", {value: [AST_Atom]});\n AST_NaN.prototype.value = NaN;\n\n function AST_Undefined() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Undefined.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Undefined, AST_Atom);\n AST_Undefined.prototype.__init__ = function __init__ () {\n AST_Atom.prototype.__init__ && AST_Atom.prototype.__init__.apply(this, arguments);\n };\n AST_Undefined.prototype.__repr__ = function __repr__ () {\n if(AST_Atom.prototype.__repr__) return AST_Atom.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Undefined.prototype.__str__ = function __str__ () {\n if(AST_Atom.prototype.__str__) return AST_Atom.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Undefined.prototype, "__bases__", {value: [AST_Atom]});\n AST_Undefined.prototype.value = undefined;\n\n function AST_Hole() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Hole.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Hole, AST_Atom);\n AST_Hole.prototype.__init__ = function __init__ () {\n AST_Atom.prototype.__init__ && AST_Atom.prototype.__init__.apply(this, arguments);\n };\n AST_Hole.prototype.__repr__ = function __repr__ () {\n if(AST_Atom.prototype.__repr__) return AST_Atom.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Hole.prototype.__str__ = function __str__ () {\n if(AST_Atom.prototype.__str__) return AST_Atom.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Hole.prototype, "__bases__", {value: [AST_Atom]});\n AST_Hole.prototype.value = undefined;\n\n function AST_Infinity() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Infinity.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Infinity, AST_Atom);\n AST_Infinity.prototype.__init__ = function __init__ () {\n AST_Atom.prototype.__init__ && AST_Atom.prototype.__init__.apply(this, arguments);\n };\n AST_Infinity.prototype.__repr__ = function __repr__ () {\n if(AST_Atom.prototype.__repr__) return AST_Atom.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Infinity.prototype.__str__ = function __str__ () {\n if(AST_Atom.prototype.__str__) return AST_Atom.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Infinity.prototype, "__bases__", {value: [AST_Atom]});\n AST_Infinity.prototype.value = Infinity;\n\n function AST_Boolean() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_Boolean.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_Boolean, AST_Atom);\n AST_Boolean.prototype.__init__ = function __init__ () {\n AST_Atom.prototype.__init__ && AST_Atom.prototype.__init__.apply(this, arguments);\n };\n AST_Boolean.prototype.__repr__ = function __repr__ () {\n if(AST_Atom.prototype.__repr__) return AST_Atom.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_Boolean.prototype.__str__ = function __str__ () {\n if(AST_Atom.prototype.__str__) return AST_Atom.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_Boolean.prototype, "__bases__", {value: [AST_Atom]});\n\n function AST_False() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_False.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_False, AST_Boolean);\n AST_False.prototype.__init__ = function __init__ () {\n AST_Boolean.prototype.__init__ && AST_Boolean.prototype.__init__.apply(this, arguments);\n };\n AST_False.prototype.__repr__ = function __repr__ () {\n if(AST_Boolean.prototype.__repr__) return AST_Boolean.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_False.prototype.__str__ = function __str__ () {\n if(AST_Boolean.prototype.__str__) return AST_Boolean.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_False.prototype, "__bases__", {value: [AST_Boolean]});\n AST_False.prototype.value = false;\n\n function AST_True() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AST_True.prototype.__init__.apply(this, arguments);\n }\n RS_extends(AST_True, AST_Boolean);\n AST_True.prototype.__init__ = function __init__ () {\n AST_Boolean.prototype.__init__ && AST_Boolean.prototype.__init__.apply(this, arguments);\n };\n AST_True.prototype.__repr__ = function __repr__ () {\n if(AST_Boolean.prototype.__repr__) return AST_Boolean.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n AST_True.prototype.__str__ = function __str__ () {\n if(AST_Boolean.prototype.__str__) return AST_Boolean.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(AST_True.prototype, "__bases__", {value: [AST_Boolean]});\n AST_True.prototype.value = true;\n\n function TreeWalker() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n TreeWalker.prototype.__init__.apply(this, arguments);\n }\n TreeWalker.prototype.__init__ = function __init__(callback) {\n var self = this;\n self.visit = callback;\n self.stack = RS_list_decorate([]);\n };\n if (!TreeWalker.prototype.__init__.__argnames__) Object.defineProperties(TreeWalker.prototype.__init__, {\n __argnames__ : {value: ["callback"]},\n __module__ : {value: "ast"}\n });\n TreeWalker.__argnames__ = TreeWalker.prototype.__init__.__argnames__;\n TreeWalker.__handles_kwarg_interpolation__ = TreeWalker.prototype.__init__.__handles_kwarg_interpolation__;\n TreeWalker.prototype._visit = function _visit(node, descend) {\n var self = this;\n var ret;\n self.stack.push(node);\n ret = self.visit(node, (descend) ? (function() {\n var RS_anonfunc = function () {\n descend.call(node);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })() : noop);\n if (!ret && descend) {\n descend.call(node);\n }\n self.stack.pop();\n return ret;\n };\n if (!TreeWalker.prototype._visit.__argnames__) Object.defineProperties(TreeWalker.prototype._visit, {\n __argnames__ : {value: ["node", "descend"]},\n __module__ : {value: "ast"}\n });\n TreeWalker.prototype.parent = function parent(n) {\n var self = this;\n return (RS_expr_temp = self.stack)[RS_bound_index(self.stack.length - 2 - (n || 0), RS_expr_temp)];\n };\n if (!TreeWalker.prototype.parent.__argnames__) Object.defineProperties(TreeWalker.prototype.parent, {\n __argnames__ : {value: ["n"]},\n __module__ : {value: "ast"}\n });\n TreeWalker.prototype.push = function push(node) {\n var self = this;\n self.stack.push(node);\n };\n if (!TreeWalker.prototype.push.__argnames__) Object.defineProperties(TreeWalker.prototype.push, {\n __argnames__ : {value: ["node"]},\n __module__ : {value: "ast"}\n });\n TreeWalker.prototype.pop = function pop() {\n var self = this;\n return self.stack.pop();\n };\n if (!TreeWalker.prototype.pop.__module__) Object.defineProperties(TreeWalker.prototype.pop, {\n __module__ : {value: "ast"}\n });\n TreeWalker.prototype.self = function self() {\n var s = this;\n return (RS_expr_temp = s.stack)[RS_bound_index(s.stack.length - 1, RS_expr_temp)];\n };\n if (!TreeWalker.prototype.self.__module__) Object.defineProperties(TreeWalker.prototype.self, {\n __module__ : {value: "ast"}\n });\n TreeWalker.prototype.find_parent = function find_parent(type) {\n var self = this;\n var stack, x, i;\n stack = self.stack;\n for (var RS_Index35 = stack.length - 1; RS_Index35 > -1; RS_Index35-=1) {\n i = RS_Index35;\n x = stack[(typeof i === "number" && i < 0) ? stack.length + i : i];\n if (is_node_type(x, type)) {\n return x;\n }\n }\n };\n if (!TreeWalker.prototype.find_parent.__argnames__) Object.defineProperties(TreeWalker.prototype.find_parent, {\n __argnames__ : {value: ["type"]},\n __module__ : {value: "ast"}\n });\n TreeWalker.prototype.in_boolean_context = function in_boolean_context() {\n var self = this;\n var stack, i, p;\n stack = self.stack;\n i = stack.length;\n self = stack[RS_bound_index(i -= 1, stack)];\n while (i > 0) {\n p = stack[RS_bound_index(i -= 1, stack)];\n if (is_node_type(p, AST_If) && p.condition === self || is_node_type(p, AST_Conditional) && p.condition === self || is_node_type(p, AST_DWLoop) && p.condition === self || is_node_type(p, AST_UnaryPrefix) && p.operator === "!" && p.expression === self) {\n return true;\n }\n if (!((is_node_type(p, AST_Binary) && (p.operator === "&&" || p.operator === "||")))) {\n return false;\n }\n self = p;\n }\n };\n if (!TreeWalker.prototype.in_boolean_context.__module__) Object.defineProperties(TreeWalker.prototype.in_boolean_context, {\n __module__ : {value: "ast"}\n });\n TreeWalker.prototype.__repr__ = function __repr__ () {\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n TreeWalker.prototype.__str__ = function __str__ () {\n return this.__repr__();\n };\n Object.defineProperty(TreeWalker.prototype, "__bases__", {value: []});\n\n function Found() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n Found.prototype.__init__.apply(this, arguments);\n }\n RS_extends(Found, Exception);\n Found.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n };\n Found.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n Found.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n };\n Object.defineProperty(Found.prototype, "__bases__", {value: [Exception]});\n \n\n function has_calls(expression) {\n if (!expression) {\n return false;\n }\n try {\n expression.walk(new TreeWalker((function() {\n var RS_anonfunc = function (node) {\n if (is_node_type(node, AST_BaseCall) || is_node_type(node, AST_ItemAccess)) {\n throw new Found;\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["node"]},\n __module__ : {value: "ast"}\n });\n return RS_anonfunc;\n })()));\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof Found) {\n return true;\n } else {\n throw RS_Exception;\n }\n }\n return false;\n };\n if (!has_calls.__argnames__) Object.defineProperties(has_calls, {\n __argnames__ : {value: ["expression"]},\n __module__ : {value: "ast"}\n });\n\n RS_modules.ast.is_node_type = is_node_type;\n RS_modules.ast.AST = AST;\n RS_modules.ast.AST_Token = AST_Token;\n RS_modules.ast.AST_Node = AST_Node;\n RS_modules.ast.AST_Statement = AST_Statement;\n RS_modules.ast.AST_Debugger = AST_Debugger;\n RS_modules.ast.AST_Directive = AST_Directive;\n RS_modules.ast.AST_SimpleStatement = AST_SimpleStatement;\n RS_modules.ast.AST_Assert = AST_Assert;\n RS_modules.ast.walk_body = walk_body;\n RS_modules.ast.AST_Block = AST_Block;\n RS_modules.ast.AST_BlockStatement = AST_BlockStatement;\n RS_modules.ast.AST_EmptyStatement = AST_EmptyStatement;\n RS_modules.ast.AST_StatementWithBody = AST_StatementWithBody;\n RS_modules.ast.AST_DWLoop = AST_DWLoop;\n RS_modules.ast.AST_Do = AST_Do;\n RS_modules.ast.AST_While = AST_While;\n RS_modules.ast.AST_ForIn = AST_ForIn;\n RS_modules.ast.AST_ForJS = AST_ForJS;\n RS_modules.ast.AST_ListComprehension = AST_ListComprehension;\n RS_modules.ast.AST_SetComprehension = AST_SetComprehension;\n RS_modules.ast.AST_DictComprehension = AST_DictComprehension;\n RS_modules.ast.AST_GeneratorComprehension = AST_GeneratorComprehension;\n RS_modules.ast.AST_With = AST_With;\n RS_modules.ast.AST_WithClause = AST_WithClause;\n RS_modules.ast.AST_Scope = AST_Scope;\n RS_modules.ast.AST_Toplevel = AST_Toplevel;\n RS_modules.ast.AST_Import = AST_Import;\n RS_modules.ast.AST_Imports = AST_Imports;\n RS_modules.ast.AST_Decorator = AST_Decorator;\n RS_modules.ast.AST_Lambda = AST_Lambda;\n RS_modules.ast.AST_Function = AST_Function;\n RS_modules.ast.AST_Class = AST_Class;\n RS_modules.ast.AST_Method = AST_Method;\n RS_modules.ast.AST_Jump = AST_Jump;\n RS_modules.ast.AST_Exit = AST_Exit;\n RS_modules.ast.AST_Return = AST_Return;\n RS_modules.ast.AST_Yield = AST_Yield;\n RS_modules.ast.AST_Throw = AST_Throw;\n RS_modules.ast.AST_LoopControl = AST_LoopControl;\n RS_modules.ast.AST_Break = AST_Break;\n RS_modules.ast.AST_Continue = AST_Continue;\n RS_modules.ast.AST_If = AST_If;\n RS_modules.ast.AST_Try = AST_Try;\n RS_modules.ast.AST_Catch = AST_Catch;\n RS_modules.ast.AST_Except = AST_Except;\n RS_modules.ast.AST_Finally = AST_Finally;\n RS_modules.ast.AST_Else = AST_Else;\n RS_modules.ast.AST_Definitions = AST_Definitions;\n RS_modules.ast.AST_Var = AST_Var;\n RS_modules.ast.AST_VarDef = AST_VarDef;\n RS_modules.ast.AST_BaseCall = AST_BaseCall;\n RS_modules.ast.AST_Call = AST_Call;\n RS_modules.ast.AST_ClassCall = AST_ClassCall;\n RS_modules.ast.AST_New = AST_New;\n RS_modules.ast.AST_Seq = AST_Seq;\n RS_modules.ast.AST_PropAccess = AST_PropAccess;\n RS_modules.ast.AST_Dot = AST_Dot;\n RS_modules.ast.AST_Sub = AST_Sub;\n RS_modules.ast.AST_ItemAccess = AST_ItemAccess;\n RS_modules.ast.AST_Splice = AST_Splice;\n RS_modules.ast.AST_Unary = AST_Unary;\n RS_modules.ast.AST_UnaryPrefix = AST_UnaryPrefix;\n RS_modules.ast.AST_Binary = AST_Binary;\n RS_modules.ast.AST_Existential = AST_Existential;\n RS_modules.ast.AST_Conditional = AST_Conditional;\n RS_modules.ast.AST_Assign = AST_Assign;\n RS_modules.ast.AST_Array = AST_Array;\n RS_modules.ast.AST_Object = AST_Object;\n RS_modules.ast.AST_ExpressiveObject = AST_ExpressiveObject;\n RS_modules.ast.AST_ObjectProperty = AST_ObjectProperty;\n RS_modules.ast.AST_ObjectKeyVal = AST_ObjectKeyVal;\n RS_modules.ast.AST_Set = AST_Set;\n RS_modules.ast.AST_SetItem = AST_SetItem;\n RS_modules.ast.AST_Symbol = AST_Symbol;\n RS_modules.ast.AST_SymbolAlias = AST_SymbolAlias;\n RS_modules.ast.AST_SymbolDeclaration = AST_SymbolDeclaration;\n RS_modules.ast.AST_SymbolVar = AST_SymbolVar;\n RS_modules.ast.AST_ImportedVar = AST_ImportedVar;\n RS_modules.ast.AST_SymbolNonlocal = AST_SymbolNonlocal;\n RS_modules.ast.AST_SymbolFunarg = AST_SymbolFunarg;\n RS_modules.ast.AST_SymbolDefun = AST_SymbolDefun;\n RS_modules.ast.AST_SymbolLambda = AST_SymbolLambda;\n RS_modules.ast.AST_SymbolCatch = AST_SymbolCatch;\n RS_modules.ast.AST_SymbolRef = AST_SymbolRef;\n RS_modules.ast.AST_This = AST_This;\n RS_modules.ast.AST_Constant = AST_Constant;\n RS_modules.ast.AST_String = AST_String;\n RS_modules.ast.AST_Verbatim = AST_Verbatim;\n RS_modules.ast.AST_Number = AST_Number;\n RS_modules.ast.AST_RegExp = AST_RegExp;\n RS_modules.ast.AST_Atom = AST_Atom;\n RS_modules.ast.AST_Null = AST_Null;\n RS_modules.ast.AST_NaN = AST_NaN;\n RS_modules.ast.AST_Undefined = AST_Undefined;\n RS_modules.ast.AST_Hole = AST_Hole;\n RS_modules.ast.AST_Infinity = AST_Infinity;\n RS_modules.ast.AST_Boolean = AST_Boolean;\n RS_modules.ast.AST_False = AST_False;\n RS_modules.ast.AST_True = AST_True;\n RS_modules.ast.TreeWalker = TreeWalker;\n RS_modules.ast.Found = Found;\n RS_modules.ast.has_calls = has_calls;\n })();\n\n (function(){\n var __name__ = "string_interpolation";\n function quoted_string(x) {\n return "\\"" + x.replace(/\\\\/g, "\\\\\\\\").replace(/"/g, "\\\\\\"").replace(/\\n/g, "\\\\n") + "\\"";\n };\n if (!quoted_string.__argnames__) Object.defineProperties(quoted_string, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "string_interpolation"}\n });\n\n function render_markup(markup) {\n var RS_unpack, pos, key, ch, fmtspec;\n RS_unpack = [0, ""];\n pos = RS_unpack[0];\n key = RS_unpack[1];\n while (pos < markup.length) {\n ch = markup[(typeof pos === "number" && pos < 0) ? markup.length + pos : pos];\n if (ch === "!" || ch === ":") {\n break;\n }\n key += ch;\n pos += 1;\n }\n fmtspec = markup.slice(pos);\n return "RS_str.format(\\"{" + fmtspec + "}\\", " + key + ")";\n };\n if (!render_markup.__argnames__) Object.defineProperties(render_markup, {\n __argnames__ : {value: ["markup"]},\n __module__ : {value: "string_interpolation"}\n });\n\n function interpolate(template, raise_error) {\n var pos, in_brace, markup, ans, ch;\n pos = in_brace = 0;\n markup = "";\n ans = [""];\n while (pos < template.length) {\n ch = template[(typeof pos === "number" && pos < 0) ? template.length + pos : pos];\n if (in_brace) {\n if (ch === "{") {\n in_brace += 1;\n markup += "{";\n } else if (ch === "}") {\n in_brace -= 1;\n if (in_brace > 0) {\n markup += "}";\n } else {\n ans.push([markup]);\n ans.push("");\n }\n } else {\n markup += ch;\n }\n } else {\n if (ch === "{") {\n if (template[RS_bound_index(pos + 1, template)] === "{") {\n pos += 1;\n ans[ans.length-1] += "{";\n } else {\n in_brace = 1;\n markup = "";\n }\n } else if (ch === "}") {\n if (template[RS_bound_index(pos + 1, template)] === "}") {\n pos += 1;\n ans[ans.length-1] += "}";\n } else {\n raise_error("f-string: single \'}\' is not allowed");\n }\n } else {\n ans[ans.length-1] += ch;\n }\n }\n pos += 1;\n }\n if (in_brace) {\n raise_error("expected \'}\' before end of string");\n }\n if (ans[ans.length-1] === "+") {\n ans[ans.length-1] = "";\n }\n for (var i = 0; i < ans.length; i++) {\n if (typeof ans[(typeof i === "number" && i < 0) ? ans.length + i : i] === "string") {\n ans[(typeof i === "number" && i < 0) ? ans.length + i : i] = quoted_string(ans[(typeof i === "number" && i < 0) ? ans.length + i : i]);\n } else {\n ans[(typeof i === "number" && i < 0) ? ans.length + i : i] = "+" + render_markup.apply(this, ans[(typeof i === "number" && i < 0) ? ans.length + i : i]) + "+";\n }\n }\n return ans.join("");\n };\n if (!interpolate.__argnames__) Object.defineProperties(interpolate, {\n __argnames__ : {value: ["template", "raise_error"]},\n __module__ : {value: "string_interpolation"}\n });\n\n RS_modules.string_interpolation.quoted_string = quoted_string;\n RS_modules.string_interpolation.render_markup = render_markup;\n RS_modules.string_interpolation.interpolate = interpolate;\n })();\n\n (function(){\n var __name__ = "tokenizer";\n var RE_HEX_NUMBER, RE_OCT_NUMBER, RE_DEC_NUMBER, OPERATOR_CHARS, ASCII_CONTROL_CHARS, HEX_PAT, NAME_PAT, OPERATORS, OP_MAP, WHITESPACE_CHARS, PUNC_BEFORE_EXPRESSION, PUNC_CHARS, KEYWORDS, KEYWORDS_ATOM, RESERVED_WORDS, KEYWORDS_BEFORE_EXPRESSION, ALL_KEYWORDS, IDENTIFIER_PAT, UNICODE, EX_EOF;\n var ALIAS_MAP = RS_modules.unicode_aliases.ALIAS_MAP;\n\n var make_predicate = RS_modules.utils.make_predicate;\n var characters = RS_modules.utils.characters;\n\n var AST_Token = RS_modules.ast.AST_Token;\n\n var SyntaxError = RS_modules.errors.SyntaxError;\n\n var interpolate = RS_modules.string_interpolation.interpolate;\n\n RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;\n RE_OCT_NUMBER = /^0[0-7]+$/;\n RE_DEC_NUMBER = /^\\d*\\.?\\d*(?:e[+-]?\\d*(?:\\d\\.?|\\.?\\d)\\d*)?$/i;\n OPERATOR_CHARS = make_predicate(characters("+-*&%=<>!?|~^@"));\n ASCII_CONTROL_CHARS = (function(){\n var RS_d = Object.create(null);\n RS_d["a"] = 7;\n RS_d["b"] = 8;\n RS_d["f"] = 12;\n RS_d["n"] = 10;\n RS_d["r"] = 13;\n RS_d["t"] = 9;\n RS_d["v"] = 11;\n return RS_d;\n }).call(this);\n HEX_PAT = /[a-fA-F0-9]/;\n NAME_PAT = /[a-zA-Z ]/;\n OPERATORS = make_predicate(RS_list_decorate([ "in", "instanceof", "typeof", "new", "void", "del", "+", "-", "not", "~", "&", "|", "^", "**", "*", "//", "/", "%", ">>", "<<", ">>>", "<", ">", "<=", ">=", "==", "is", "!=", "=", "+=", "-=", "//=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=", "and", "or", "@", "->" ]));\n OP_MAP = (function(){\n var RS_d = Object.create(null);\n RS_d["or"] = "||";\n RS_d["and"] = "&&";\n RS_d["not"] = "!";\n RS_d["del"] = "delete";\n RS_d["None"] = "null";\n RS_d["is"] = "===";\n return RS_d;\n }).call(this);\n WHITESPACE_CHARS = make_predicate(characters("  \\n\\r\\t\\f\\u000b​᠎           \\u202f  "));\n PUNC_BEFORE_EXPRESSION = make_predicate(characters("[{(,.;:"));\n PUNC_CHARS = make_predicate(characters("[]{}(),;:?"));\n KEYWORDS = "as assert break class continue def del do elif else except finally for from global if import in is new nonlocal pass raise return yield try while with or and not";\n KEYWORDS_ATOM = "False None True";\n RESERVED_WORDS = "break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof new return super switch this throw try typeof var void while with yield enum implements static private package let public protected interface await null true false";\n KEYWORDS_BEFORE_EXPRESSION = "return yield new del raise elif else if";\n ALL_KEYWORDS = KEYWORDS + " " + KEYWORDS_ATOM;\n KEYWORDS = make_predicate(KEYWORDS);\n RESERVED_WORDS = make_predicate(RESERVED_WORDS);\n KEYWORDS_BEFORE_EXPRESSION = make_predicate(KEYWORDS_BEFORE_EXPRESSION);\n KEYWORDS_ATOM = make_predicate(KEYWORDS_ATOM);\n IDENTIFIER_PAT = /^[a-z_$][_a-z0-9$]*$/i;\n function is_string_modifier(val) {\n var ch;\n var RS_Iter36 = RS_Iterable(val);\n for (var RS_Index36 = 0; RS_Index36 < RS_Iter36.length; RS_Index36++) {\n ch = RS_Iter36[RS_Index36];\n if ("vrufVRUF".indexOf(ch) === -1) {\n return false;\n }\n }\n return true;\n };\n if (!is_string_modifier.__argnames__) Object.defineProperties(is_string_modifier, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_letter(code) {\n return code >= 97 && code <= 122 || code >= 65 && code <= 90 || code >= 170 && UNICODE.letter.test(String.fromCharCode(code));\n };\n if (!is_letter.__argnames__) Object.defineProperties(is_letter, {\n __argnames__ : {value: ["code"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_digit(code) {\n return code >= 48 && code <= 57;\n };\n if (!is_digit.__argnames__) Object.defineProperties(is_digit, {\n __argnames__ : {value: ["code"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_alphanumeric_char(code) {\n return is_digit(code) || is_letter(code);\n };\n if (!is_alphanumeric_char.__argnames__) Object.defineProperties(is_alphanumeric_char, {\n __argnames__ : {value: ["code"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_unicode_combining_mark(ch) {\n return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);\n };\n if (!is_unicode_combining_mark.__argnames__) Object.defineProperties(is_unicode_combining_mark, {\n __argnames__ : {value: ["ch"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_unicode_connector_punctuation(ch) {\n return UNICODE.connector_punctuation.test(ch);\n };\n if (!is_unicode_connector_punctuation.__argnames__) Object.defineProperties(is_unicode_connector_punctuation, {\n __argnames__ : {value: ["ch"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_identifier(name) {\n return !RESERVED_WORDS[(typeof name === "number" && name < 0) ? RESERVED_WORDS.length + name : name] && !KEYWORDS[(typeof name === "number" && name < 0) ? KEYWORDS.length + name : name] && !KEYWORDS_ATOM[(typeof name === "number" && name < 0) ? KEYWORDS_ATOM.length + name : name] && IDENTIFIER_PAT.test(name);\n };\n if (!is_identifier.__argnames__) Object.defineProperties(is_identifier, {\n __argnames__ : {value: ["name"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_identifier_start(code) {\n return code === 36 || code === 95 || is_letter(code);\n };\n if (!is_identifier_start.__argnames__) Object.defineProperties(is_identifier_start, {\n __argnames__ : {value: ["code"]},\n __module__ : {value: "tokenizer"}\n });\n\n function is_identifier_char(ch) {\n var code;\n code = ch.charCodeAt(0);\n return is_identifier_start(code) || is_digit(code) || code === 8204 || code === 8205 || is_unicode_combining_mark(ch) || is_unicode_connector_punctuation(ch);\n };\n if (!is_identifier_char.__argnames__) Object.defineProperties(is_identifier_char, {\n __argnames__ : {value: ["ch"]},\n __module__ : {value: "tokenizer"}\n });\n\n function parse_js_number(num) {\n if (RE_HEX_NUMBER.test(num)) {\n return parseInt(num.substr(2), 16);\n } else if (RE_OCT_NUMBER.test(num)) {\n return parseInt(num.substr(1), 8);\n } else if (RE_DEC_NUMBER.test(num)) {\n return parseFloat(num);\n }\n };\n if (!parse_js_number.__argnames__) Object.defineProperties(parse_js_number, {\n __argnames__ : {value: ["num"]},\n __module__ : {value: "tokenizer"}\n });\n\n UNICODE = (function(){\n var RS_d = Object.create(null);\n RS_d["letter"] = new RegExp("[\\\\u0041-\\\\u005A\\\\u0061-\\\\u007A\\\\u00AA\\\\u00B5\\\\u00BA\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02C1\\\\u02C6-\\\\u02D1\\\\u02E0-\\\\u02E4\\\\u02EC\\\\u02EE\\\\u0370-\\\\u0374\\\\u0376\\\\u0377\\\\u037A-\\\\u037D\\\\u0386\\\\u0388-\\\\u038A\\\\u038C\\\\u038E-\\\\u03A1\\\\u03A3-\\\\u03F5\\\\u03F7-\\\\u0481\\\\u048A-\\\\u0523\\\\u0531-\\\\u0556\\\\u0559\\\\u0561-\\\\u0587\\\\u05D0-\\\\u05EA\\\\u05F0-\\\\u05F2\\\\u0621-\\\\u064A\\\\u066E\\\\u066F\\\\u0671-\\\\u06D3\\\\u06D5\\\\u06E5\\\\u06E6\\\\u06EE\\\\u06EF\\\\u06FA-\\\\u06FC\\\\u06FF\\\\u0710\\\\u0712-\\\\u072F\\\\u074D-\\\\u07A5\\\\u07B1\\\\u07CA-\\\\u07EA\\\\u07F4\\\\u07F5\\\\u07FA\\\\u0904-\\\\u0939\\\\u093D\\\\u0950\\\\u0958-\\\\u0961\\\\u0971\\\\u0972\\\\u097B-\\\\u097F\\\\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-\\\\u0C33\\\\u0C35-\\\\u0C39\\\\u0C3D\\\\u0C58\\\\u0C59\\\\u0C60\\\\u0C61\\\\u0C85-\\\\u0C8C\\\\u0C8E-\\\\u0C90\\\\u0C92-\\\\u0CA8\\\\u0CAA-\\\\u0CB3\\\\u0CB5-\\\\u0CB9\\\\u0CBD\\\\u0CDE\\\\u0CE0\\\\u0CE1\\\\u0D05-\\\\u0D0C\\\\u0D0E-\\\\u0D10\\\\u0D12-\\\\u0D28\\\\u0D2A-\\\\u0D39\\\\u0D3D\\\\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\\\\u0EDD\\\\u0F00\\\\u0F40-\\\\u0F47\\\\u0F49-\\\\u0F6C\\\\u0F88-\\\\u0F8B\\\\u1000-\\\\u102A\\\\u103F\\\\u1050-\\\\u1055\\\\u105A-\\\\u105D\\\\u1061\\\\u1065\\\\u1066\\\\u106E-\\\\u1070\\\\u1075-\\\\u1081\\\\u108E\\\\u10A0-\\\\u10C5\\\\u10D0-\\\\u10FA\\\\u10FC\\\\u1100-\\\\u1159\\\\u115F-\\\\u11A2\\\\u11A8-\\\\u11F9\\\\u1200-\\\\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-\\\\u1676\\\\u1681-\\\\u169A\\\\u16A0-\\\\u16EA\\\\u1700-\\\\u170C\\\\u170E-\\\\u1711\\\\u1720-\\\\u1731\\\\u1740-\\\\u1751\\\\u1760-\\\\u176C\\\\u176E-\\\\u1770\\\\u1780-\\\\u17B3\\\\u17D7\\\\u17DC\\\\u1820-\\\\u1877\\\\u1880-\\\\u18A8\\\\u18AA\\\\u1900-\\\\u191C\\\\u1950-\\\\u196D\\\\u1970-\\\\u1974\\\\u1980-\\\\u19A9\\\\u19C1-\\\\u19C7\\\\u1A00-\\\\u1A16\\\\u1B05-\\\\u1B33\\\\u1B45-\\\\u1B4B\\\\u1B83-\\\\u1BA0\\\\u1BAE\\\\u1BAF\\\\u1C00-\\\\u1C23\\\\u1C4D-\\\\u1C4F\\\\u1C5A-\\\\u1C7D\\\\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-\\\\u2094\\\\u2102\\\\u2107\\\\u210A-\\\\u2113\\\\u2115\\\\u2119-\\\\u211D\\\\u2124\\\\u2126\\\\u2128\\\\u212A-\\\\u212D\\\\u212F-\\\\u2139\\\\u213C-\\\\u213F\\\\u2145-\\\\u2149\\\\u214E\\\\u2183\\\\u2184\\\\u2C00-\\\\u2C2E\\\\u2C30-\\\\u2C5E\\\\u2C60-\\\\u2C6F\\\\u2C71-\\\\u2C7D\\\\u2C80-\\\\u2CE4\\\\u2D00-\\\\u2D25\\\\u2D30-\\\\u2D65\\\\u2D6F\\\\u2D80-\\\\u2D96\\\\u2DA0-\\\\u2DA6\\\\u2DA8-\\\\u2DAE\\\\u2DB0-\\\\u2DB6\\\\u2DB8-\\\\u2DBE\\\\u2DC0-\\\\u2DC6\\\\u2DC8-\\\\u2DCE\\\\u2DD0-\\\\u2DD6\\\\u2DD8-\\\\u2DDE\\\\u2E2F\\\\u3005\\\\u3006\\\\u3031-\\\\u3035\\\\u303B\\\\u303C\\\\u3041-\\\\u3096\\\\u309D-\\\\u309F\\\\u30A1-\\\\u30FA\\\\u30FC-\\\\u30FF\\\\u3105-\\\\u312D\\\\u3131-\\\\u318E\\\\u31A0-\\\\u31B7\\\\u31F0-\\\\u31FF\\\\u3400\\\\u4DB5\\\\u4E00\\\\u9FC3\\\\uA000-\\\\uA48C\\\\uA500-\\\\uA60C\\\\uA610-\\\\uA61F\\\\uA62A\\\\uA62B\\\\uA640-\\\\uA65F\\\\uA662-\\\\uA66E\\\\uA67F-\\\\uA697\\\\uA717-\\\\uA71F\\\\uA722-\\\\uA788\\\\uA78B\\\\uA78C\\\\uA7FB-\\\\uA801\\\\uA803-\\\\uA805\\\\uA807-\\\\uA80A\\\\uA80C-\\\\uA822\\\\uA840-\\\\uA873\\\\uA882-\\\\uA8B3\\\\uA90A-\\\\uA925\\\\uA930-\\\\uA946\\\\uAA00-\\\\uAA28\\\\uAA40-\\\\uAA42\\\\uAA44-\\\\uAA4B\\\\uAC00\\\\uD7A3\\\\uF900-\\\\uFA2D\\\\uFA30-\\\\uFA6A\\\\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]");\n RS_d["non_spacing_mark"] = new RegExp("[\\\\u0300-\\\\u036F\\\\u0483-\\\\u0487\\\\u0591-\\\\u05BD\\\\u05BF\\\\u05C1\\\\u05C2\\\\u05C4\\\\u05C5\\\\u05C7\\\\u0610-\\\\u061A\\\\u064B-\\\\u065E\\\\u0670\\\\u06D6-\\\\u06DC\\\\u06DF-\\\\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\\\\u09C1-\\\\u09C4\\\\u09CD\\\\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\\\\u0B3F\\\\u0B41-\\\\u0B44\\\\u0B4D\\\\u0B56\\\\u0B62\\\\u0B63\\\\u0B82\\\\u0BC0\\\\u0BCD\\\\u0C3E-\\\\u0C40\\\\u0C46-\\\\u0C48\\\\u0C4A-\\\\u0C4D\\\\u0C55\\\\u0C56\\\\u0C62\\\\u0C63\\\\u0CBC\\\\u0CBF\\\\u0CC6\\\\u0CCC\\\\u0CCD\\\\u0CE2\\\\u0CE3\\\\u0D41-\\\\u0D44\\\\u0D4D\\\\u0D62\\\\u0D63\\\\u0DCA\\\\u0DD2-\\\\u0DD4\\\\u0DD6\\\\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\\\\u20D0-\\\\u20DC\\\\u20E1\\\\u20E5-\\\\u20F0\\\\u2CEF-\\\\u2CF1\\\\u2DE0-\\\\u2DFF\\\\u302A-\\\\u302F\\\\u3099\\\\u309A\\\\uA66F\\\\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\\\\uFB1E\\\\uFE00-\\\\uFE0F\\\\uFE20-\\\\uFE26]");\n RS_d["space_combining_mark"] = new RegExp("[\\\\u0903\\\\u093E-\\\\u0940\\\\u0949-\\\\u094C\\\\u094E\\\\u0982\\\\u0983\\\\u09BE-\\\\u09C0\\\\u09C7\\\\u09C8\\\\u09CB\\\\u09CC\\\\u09D7\\\\u0A03\\\\u0A3E-\\\\u0A40\\\\u0A83\\\\u0ABE-\\\\u0AC0\\\\u0AC9\\\\u0ACB\\\\u0ACC\\\\u0B02\\\\u0B03\\\\u0B3E\\\\u0B40\\\\u0B47\\\\u0B48\\\\u0B4B\\\\u0B4C\\\\u0B57\\\\u0BBE\\\\u0BBF\\\\u0BC1\\\\u0BC2\\\\u0BC6-\\\\u0BC8\\\\u0BCA-\\\\u0BCC\\\\u0BD7\\\\u0C01-\\\\u0C03\\\\u0C41-\\\\u0C44\\\\u0C82\\\\u0C83\\\\u0CBE\\\\u0CC0-\\\\u0CC4\\\\u0CC7\\\\u0CC8\\\\u0CCA\\\\u0CCB\\\\u0CD5\\\\u0CD6\\\\u0D02\\\\u0D03\\\\u0D3E-\\\\u0D40\\\\u0D46-\\\\u0D48\\\\u0D4A-\\\\u0D4C\\\\u0D57\\\\u0D82\\\\u0D83\\\\u0DCF-\\\\u0DD1\\\\u0DD8-\\\\u0DDF\\\\u0DF2\\\\u0DF3\\\\u0F3E\\\\u0F3F\\\\u0F7F\\\\u102B\\\\u102C\\\\u1031\\\\u1038\\\\u103B\\\\u103C\\\\u1056\\\\u1057\\\\u1062-\\\\u1064\\\\u1067-\\\\u106D\\\\u1083\\\\u1084\\\\u1087-\\\\u108C\\\\u108F\\\\u109A-\\\\u109C\\\\u17B6\\\\u17BE-\\\\u17C5\\\\u17C7\\\\u17C8\\\\u1923-\\\\u1926\\\\u1929-\\\\u192B\\\\u1930\\\\u1931\\\\u1933-\\\\u1938\\\\u19B0-\\\\u19C0\\\\u19C8\\\\u19C9\\\\u1A19-\\\\u1A1B\\\\u1A55\\\\u1A57\\\\u1A61\\\\u1A63\\\\u1A64\\\\u1A6D-\\\\u1A72\\\\u1B04\\\\u1B35\\\\u1B3B\\\\u1B3D-\\\\u1B41\\\\u1B43\\\\u1B44\\\\u1B82\\\\u1BA1\\\\u1BA6\\\\u1BA7\\\\u1BAA\\\\u1C24-\\\\u1C2B\\\\u1C34\\\\u1C35\\\\u1CE1\\\\u1CF2\\\\uA823\\\\uA824\\\\uA827\\\\uA880\\\\uA881\\\\uA8B4-\\\\uA8C3\\\\uA952\\\\uA953\\\\uA983\\\\uA9B4\\\\uA9B5\\\\uA9BA\\\\uA9BB\\\\uA9BD-\\\\uA9C0\\\\uAA2F\\\\uAA30\\\\uAA33\\\\uAA34\\\\uAA4D\\\\uAA7B\\\\uABE3\\\\uABE4\\\\uABE6\\\\uABE7\\\\uABE9\\\\uABEA\\\\uABEC]");\n RS_d["connector_punctuation"] = new RegExp("[\\\\u005F\\\\u203F\\\\u2040\\\\u2054\\\\uFE33\\\\uFE34\\\\uFE4D-\\\\uFE4F\\\\uFF3F]");\n return RS_d;\n }).call(this);\n function is_token(token, type, val) {\n return token.type === type && (val === null || val === undefined || token.value === val);\n };\n if (!is_token.__argnames__) Object.defineProperties(is_token, {\n __argnames__ : {value: ["token", "type", "val"]},\n __module__ : {value: "tokenizer"}\n });\n\n EX_EOF = Object.create(null);\n function tokenizer(raw_text, filename) {\n var S, read_string, read_regexp;\n S = (function(){\n var RS_d = Object.create(null);\n RS_d["text"] = raw_text.replace(/\\r\\n?|[\\n\\u2028\\u2029]/g, "\\n").replace(/\\uFEFF/g, "");\n RS_d["filename"] = filename;\n RS_d["pos"] = 0;\n RS_d["tokpos"] = 0;\n RS_d["line"] = 1;\n RS_d["tokline"] = 0;\n RS_d["col"] = 0;\n RS_d["tokcol"] = 0;\n RS_d["newline_before"] = false;\n RS_d["regex_allowed"] = false;\n RS_d["comments_before"] = [];\n RS_d["whitespace_before"] = [];\n RS_d["newblock"] = false;\n RS_d["endblock"] = false;\n RS_d["indentation_matters"] = [ true ];\n RS_d["cached_whitespace"] = "";\n RS_d["prev"] = undefined;\n RS_d["index_or_slice"] = [ false ];\n RS_d["expecting_object_literal_key"] = false;\n return RS_d;\n }).call(this);\n function peek() {\n return S.text.charAt(S.pos);\n };\n if (!peek.__module__) Object.defineProperties(peek, {\n __module__ : {value: "tokenizer"}\n });\n\n function prevChar() {\n return S.text.charAt(S.tokpos - 1);\n };\n if (!prevChar.__module__) Object.defineProperties(prevChar, {\n __module__ : {value: "tokenizer"}\n });\n\n function next(signal_eof, in_string) {\n var ch;\n ch = S.text.charAt(S.pos);\n S.pos += 1;\n if (signal_eof && !ch) {\n throw EX_EOF;\n }\n if (ch === "\\n") {\n S.newline_before = S.newline_before || !in_string;\n S.line += 1;\n S.col = 0;\n } else {\n S.col += 1;\n }\n return ch;\n };\n if (!next.__argnames__) Object.defineProperties(next, {\n __argnames__ : {value: ["signal_eof", "in_string"]},\n __module__ : {value: "tokenizer"}\n });\n\n function find(what, signal_eof) {\n var pos;\n pos = S.text.indexOf(what, S.pos);\n if (signal_eof && pos === -1) {\n throw EX_EOF;\n }\n return pos;\n };\n if (!find.__argnames__) Object.defineProperties(find, {\n __argnames__ : {value: ["what", "signal_eof"]},\n __module__ : {value: "tokenizer"}\n });\n\n function start_token() {\n S.tokline = S.line;\n S.tokcol = S.col;\n S.tokpos = S.pos;\n };\n if (!start_token.__module__) Object.defineProperties(start_token, {\n __module__ : {value: "tokenizer"}\n });\n\n function token(type, value, is_comment, keep_newline) {\n var ret, i;\n S.regex_allowed = type === "operator" || type === "keyword" && KEYWORDS_BEFORE_EXPRESSION[(typeof value === "number" && value < 0) ? KEYWORDS_BEFORE_EXPRESSION.length + value : value] || type === "punc" && PUNC_BEFORE_EXPRESSION[(typeof value === "number" && value < 0) ? PUNC_BEFORE_EXPRESSION.length + value : value];\n if (type === "operator" && value === "is" && S.text.substr(S.pos).trimLeft().substr(0, 4).trimRight() === "not") {\n next_token();\n value = "!==";\n }\n if (type === "operator" && OP_MAP[(typeof value === "number" && value < 0) ? OP_MAP.length + value : value]) {\n value = OP_MAP[(typeof value === "number" && value < 0) ? OP_MAP.length + value : value];\n }\n ret = (function(){\n var RS_d = Object.create(null);\n RS_d["type"] = type;\n RS_d["value"] = value;\n RS_d["line"] = S.tokline;\n RS_d["col"] = S.tokcol;\n RS_d["pos"] = S.tokpos;\n RS_d["endpos"] = S.pos;\n RS_d["nlb"] = S.newline_before;\n RS_d["file"] = filename;\n RS_d["leading_whitespace"] = (RS_expr_temp = S.whitespace_before)[RS_expr_temp.length-1] || "";\n return RS_d;\n }).call(this);\n if (!is_comment) {\n ret.comments_before = S.comments_before;\n S.comments_before = [];\n for (var RS_Index37 = 0; RS_Index37 < ret.comments_before.length; RS_Index37++) {\n i = RS_Index37;\n ret.nlb = ret.nlb || (RS_expr_temp = ret.comments_before)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].nlb;\n }\n }\n if (!keep_newline) {\n S.newline_before = false;\n }\n if (type === "punc") {\n if (value === ":" && !(RS_expr_temp = S.index_or_slice)[RS_expr_temp.length-1] && !S.expecting_object_literal_key && (!S.text.substring(S.pos + 1, find("\\n")).trim() || !S.text.substring(S.pos + 1, find("#")).trim())) {\n S.newblock = true;\n S.indentation_matters.push(true);\n }\n if (value === "[") {\n if (S.prev && (S.prev.type === "name" || S.prev.type === "punc" && ")]".indexOf(S.prev.value) !== -1)) {\n S.index_or_slice.push(true);\n } else {\n S.index_or_slice.push(false);\n }\n S.indentation_matters.push(false);\n } else if (value === "{" || value === "(") {\n S.indentation_matters.push(false);\n } else if (value === "]") {\n S.index_or_slice.pop();\n S.indentation_matters.pop();\n } else if (value === "}" || value === ")") {\n S.indentation_matters.pop();\n }\n }\n S.prev = new AST_Token(ret);\n return S.prev;\n };\n if (!token.__argnames__) Object.defineProperties(token, {\n __argnames__ : {value: ["type", "value", "is_comment", "keep_newline"]},\n __module__ : {value: "tokenizer"}\n });\n\n function parse_whitespace() {\n var leading_whitespace, whitespace_exists, ch;\n leading_whitespace = "";\n whitespace_exists = false;\n while (WHITESPACE_CHARS[RS_bound_index(peek(), WHITESPACE_CHARS)]) {\n whitespace_exists = true;\n ch = next();\n if (ch === "\\n") {\n leading_whitespace = "";\n } else {\n leading_whitespace += ch;\n }\n }\n if (peek() !== "#") {\n if (!whitespace_exists) {\n leading_whitespace = S.cached_whitespace;\n } else {\n S.cached_whitespace = leading_whitespace;\n }\n if (S.newline_before || S.endblock) {\n return test_indent_token(leading_whitespace);\n }\n }\n };\n if (!parse_whitespace.__module__) Object.defineProperties(parse_whitespace, {\n __module__ : {value: "tokenizer"}\n });\n\n function test_indent_token(leading_whitespace) {\n var most_recent;\n most_recent = (RS_expr_temp = S.whitespace_before)[RS_expr_temp.length-1] || "";\n S.endblock = false;\n if ((RS_expr_temp = S.indentation_matters)[RS_expr_temp.length-1] && leading_whitespace !== most_recent) {\n if (S.newblock && leading_whitespace && leading_whitespace.indexOf(most_recent) === 0) {\n S.newblock = false;\n S.whitespace_before.push(leading_whitespace);\n return 1;\n } else if (most_recent && most_recent.indexOf(leading_whitespace) === 0) {\n S.endblock = true;\n S.whitespace_before.pop();\n return -1;\n } else {\n parse_error("Inconsistent indentation");\n }\n }\n return 0;\n };\n if (!test_indent_token.__argnames__) Object.defineProperties(test_indent_token, {\n __argnames__ : {value: ["leading_whitespace"]},\n __module__ : {value: "tokenizer"}\n });\n\n function read_while(pred) {\n var ret, i, ch;\n ret = "";\n i = 0;\n ch = "";\n while ((ch = peek()) && pred(ch, i)) {\n i += 1;\n ret += next();\n }\n return ret;\n };\n if (!read_while.__argnames__) Object.defineProperties(read_while, {\n __argnames__ : {value: ["pred"]},\n __module__ : {value: "tokenizer"}\n });\n\n function parse_error(err, is_eof) {\n throw new SyntaxError(err, filename, S.tokline, S.tokcol, S.tokpos, is_eof);\n };\n if (!parse_error.__argnames__) Object.defineProperties(parse_error, {\n __argnames__ : {value: ["err", "is_eof"]},\n __module__ : {value: "tokenizer"}\n });\n\n function read_num(prefix) {\n var has_e, has_x, has_dot, num, valid, seen;\n has_e = false;\n has_x = false;\n has_dot = prefix === ".";\n if (!prefix && peek() === "0" && S.text.charAt(S.pos + 1) === "b") {\n [next(), next()];\n num = read_while((function() {\n var RS_anonfunc = function (ch) {\n return ch === "0" || ch === "1";\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["ch"]},\n __module__ : {value: "tokenizer"}\n });\n return RS_anonfunc;\n })());\n valid = parseInt(num, 2);\n if (isNaN(valid)) {\n parse_error("Invalid syntax for a binary number");\n }\n return token("num", valid);\n }\n seen = [];\n num = read_while((function() {\n var RS_anonfunc = function (ch, i) {\n seen.push(ch);\n if (ch === "x" || ch === "X") {\n if (has_x || seen.length !== 2 || seen[0] !== "0") {\n return false;\n }\n has_x = true;\n return true;\n } else if (ch === "e" || ch === "E") {\n if (has_x) {\n return true;\n }\n if (has_e || (i === 0 || typeof i === "object" && RS_equals(i, 0))) {\n return false;\n }\n has_e = true;\n return true;\n } else if (ch === "-") {\n if (i === 0 && !prefix) {\n return true;\n }\n if (has_e && seen[RS_bound_index(i - 1, seen)].toLowerCase() === "e") {\n return true;\n }\n return false;\n } else if (ch === "+") {\n if (has_e && seen[RS_bound_index(i - 1, seen)].toLowerCase() === "e") {\n return true;\n }\n return false;\n } else if (ch === ".") {\n return (!has_dot && !has_x && !has_e) ? has_dot = true : false;\n }\n return is_alphanumeric_char(ch.charCodeAt(0));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["ch", "i"]},\n __module__ : {value: "tokenizer"}\n });\n return RS_anonfunc;\n })());\n if (prefix) {\n num = prefix + num;\n }\n valid = parse_js_number(num);\n if (!isNaN(valid)) {\n return token("num", valid);\n } else {\n parse_error("Invalid syntax: " + num);\n }\n };\n if (!read_num.__argnames__) Object.defineProperties(read_num, {\n __argnames__ : {value: ["prefix"]},\n __module__ : {value: "tokenizer"}\n });\n\n function read_hex_digits(count) {\n var ans, nval;\n ans = "";\n while (count > 0) {\n count -= 1;\n if (!HEX_PAT.test(peek())) {\n return ans;\n }\n ans += next();\n }\n nval = parseInt(ans, 16);\n if (nval > 1114111) {\n return ans;\n }\n return nval;\n };\n if (!read_hex_digits.__argnames__) Object.defineProperties(read_hex_digits, {\n __argnames__ : {value: ["count"]},\n __module__ : {value: "tokenizer"}\n });\n\n function read_escape_sequence() {\n var q, octal, code, name, key;\n q = next(true);\n if (q === "\\n") {\n return "";\n }\n if (q === "\\\\") {\n return q;\n }\n if ("\\"\'".indexOf(q) !== -1) {\n return q;\n }\n if (ASCII_CONTROL_CHARS[(typeof q === "number" && q < 0) ? ASCII_CONTROL_CHARS.length + q : q]) {\n return String.fromCharCode(ASCII_CONTROL_CHARS[(typeof q === "number" && q < 0) ? ASCII_CONTROL_CHARS.length + q : q]);\n }\n if ("0" <= q && q <= "7") {\n octal = q;\n if ("0" <= (RS_cond_temp = peek()) && RS_cond_temp <= "7") {\n octal += next();\n }\n if ("0" <= (RS_cond_temp = peek()) && RS_cond_temp <= "7") {\n octal += next();\n }\n code = parseInt(octal, 8);\n if (isNaN(code)) {\n return "\\\\" + octal;\n }\n return String.fromCharCode(code);\n }\n if (q === "x") {\n code = read_hex_digits(2);\n if (typeof code === "number") {\n return String.fromCharCode(code);\n }\n return "\\\\x" + code;\n }\n if (q === "u") {\n code = read_hex_digits(4);\n if (typeof code === "number") {\n return String.fromCharCode(code);\n }\n return "\\\\u" + code;\n }\n if (q === "U") {\n code = read_hex_digits(8);\n if (typeof code === "number") {\n if (code <= 65535) {\n return String.fromCharCode(code);\n }\n code -= 65536;\n return String.fromCharCode(55296 + (code >> 10), 56320 + (code & 1023));\n }\n return "\\\\U" + code;\n }\n if (q === "N" && peek() === "{") {\n next();\n name = read_while((function() {\n var RS_anonfunc = function (ch) {\n return NAME_PAT.test(ch);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["ch"]},\n __module__ : {value: "tokenizer"}\n });\n return RS_anonfunc;\n })());\n if (peek() !== "}") {\n return "\\\\N{" + name;\n }\n next();\n key = (name || "").toLowerCase();\n if (!name || !Object.prototype.hasOwnProperty.call(ALIAS_MAP, key)) {\n return "\\\\N{" + name + "}";\n }\n code = ALIAS_MAP[(typeof key === "number" && key < 0) ? ALIAS_MAP.length + key : key];\n if (code <= 65535) {\n return String.fromCharCode(code);\n }\n code -= 65536;\n return String.fromCharCode(55296 + (code >> 10), 56320 + (code & 1023));\n }\n return "\\\\" + q;\n };\n if (!read_escape_sequence.__module__) Object.defineProperties(read_escape_sequence, {\n __module__ : {value: "tokenizer"}\n });\n\n function with_eof_error(eof_error, cont) {\n return (function() {\n var RS_anonfunc = function () {\n try {\n return cont.apply(null, arguments);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n var ex = RS_Exception;\n if (ex === EX_EOF) {\n parse_error(eof_error, true);\n } else {\n throw RS_Exception;\n }\n } \n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "tokenizer"}\n });\n return RS_anonfunc;\n })();\n };\n if (!with_eof_error.__argnames__) Object.defineProperties(with_eof_error, {\n __argnames__ : {value: ["eof_error", "cont"]},\n __module__ : {value: "tokenizer"}\n });\n\n read_string = with_eof_error("Unterminated string constant", (function() {\n var RS_anonfunc = function (is_raw_literal, is_js_literal) {\n var quote, tok_type, ret, is_multiline, ch;\n quote = next();\n tok_type = (is_js_literal) ? "js" : "string";\n ret = "";\n is_multiline = false;\n if (peek() === quote) {\n next(true);\n if (peek() === quote) {\n next(true);\n is_multiline = true;\n } else {\n return token(tok_type, "");\n }\n }\n while (true) {\n ch = next(true, true);\n if (!ch) {\n break;\n }\n if (ch === "\\n" && !is_multiline) {\n parse_error("End of line while scanning string literal");\n }\n if (ch === "\\\\") {\n ret += (is_raw_literal) ? "\\\\" + next(true) : read_escape_sequence();\n continue;\n }\n if (ch === quote) {\n if (!is_multiline) {\n break;\n }\n if (peek() === quote) {\n next();\n if (peek() === quote) {\n next();\n break;\n } else {\n ch += quote;\n }\n }\n }\n ret += ch;\n }\n return token(tok_type, ret);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["is_raw_literal", "is_js_literal"]},\n __module__ : {value: "tokenizer"}\n });\n return RS_anonfunc;\n })());\n function handle_interpolated_string(string, start_tok) {\n function raise_error(err) {\n throw new SyntaxError(err, filename, start_tok.line, start_tok.col, start_tok.pos, false);\n };\n if (!raise_error.__argnames__) Object.defineProperties(raise_error, {\n __argnames__ : {value: ["err"]},\n __module__ : {value: "tokenizer"}\n });\n\n S.text = S.text.slice(0, S.pos) + "(" + interpolate(string, raise_error) + ")" + S.text.slice(S.pos);\n return token("punc", next());\n };\n if (!handle_interpolated_string.__argnames__) Object.defineProperties(handle_interpolated_string, {\n __argnames__ : {value: ["string", "start_tok"]},\n __module__ : {value: "tokenizer"}\n });\n\n function read_line_comment(shebang) {\n var i, ret;\n if (!shebang) {\n next();\n }\n i = find("\\n");\n if (i === -1) {\n ret = S.text.substr(S.pos);\n S.pos = S.text.length;\n } else {\n ret = S.text.substring(S.pos, i);\n S.pos = i;\n }\n return token((shebang) ? "shebang" : "comment1", ret, true);\n };\n if (!read_line_comment.__argnames__) Object.defineProperties(read_line_comment, {\n __argnames__ : {value: ["shebang"]},\n __module__ : {value: "tokenizer"}\n });\n\n function read_name() {\n var name, ch;\n name = ch = "";\n while ((ch = peek()) !== null) {\n if (ch === "\\\\") {\n if (S.text.charAt(S.pos + 1) === "\\n") {\n S.pos += 2;\n continue;\n }\n break;\n } else if (is_identifier_char(ch)) {\n name += next();\n } else {\n break;\n }\n }\n return name;\n };\n if (!read_name.__module__) Object.defineProperties(read_name, {\n __module__ : {value: "tokenizer"}\n });\n\n read_regexp = with_eof_error("Unterminated regular expression", (function() {\n var RS_anonfunc = function () {\n var prev_backslash, regexp, ch, in_class, verbose_regexp, in_comment, mods;\n prev_backslash = false;\n regexp = ch = "";\n in_class = false;\n verbose_regexp = false;\n in_comment = false;\n if (peek() === "/") {\n next(true);\n if (peek() === "/") {\n verbose_regexp = true;\n next(true);\n } else {\n mods = read_name();\n return token("regexp", new RegExp(regexp, mods));\n }\n }\n while (true) {\n ch = next(true);\n if (!ch) {\n break;\n }\n if (in_comment) {\n if (ch === "\\n") {\n in_comment = false;\n }\n continue;\n }\n if (prev_backslash) {\n regexp += "\\\\" + ch;\n prev_backslash = false;\n } else if (ch === "[") {\n in_class = true;\n regexp += ch;\n } else if (ch === "]" && in_class) {\n in_class = false;\n regexp += ch;\n } else if (ch === "/" && !in_class) {\n if (verbose_regexp) {\n if (peek() !== "/") {\n regexp += "\\\\/";\n continue;\n }\n next(true);\n if (peek() !== "/") {\n regexp += "\\\\/\\\\/";\n continue;\n }\n next(true);\n }\n break;\n } else if (ch === "\\\\") {\n prev_backslash = true;\n } else if (verbose_regexp && !in_class && " \\n\\r\\t".indexOf(ch) !== -1) {\n } else if (verbose_regexp && !in_class && ch === "#") {\n in_comment = true;\n } else {\n regexp += ch;\n }\n }\n mods = read_name();\n return token("regexp", new RegExp(regexp, mods));\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "tokenizer"}\n });\n return RS_anonfunc;\n })());\n function read_operator(prefix) {\n var op;\n function grow(op) {\n var bigger;\n if (!peek()) {\n return op;\n }\n bigger = op + peek();\n if (OPERATORS[(typeof bigger === "number" && bigger < 0) ? OPERATORS.length + bigger : bigger]) {\n next();\n return grow(bigger);\n } else {\n return op;\n }\n };\n if (!grow.__argnames__) Object.defineProperties(grow, {\n __argnames__ : {value: ["op"]},\n __module__ : {value: "tokenizer"}\n });\n\n op = grow(prefix || next());\n if (op === "->") {\n return token("punc", op);\n }\n return token("operator", op);\n };\n if (!read_operator.__argnames__) Object.defineProperties(read_operator, {\n __argnames__ : {value: ["prefix"]},\n __module__ : {value: "tokenizer"}\n });\n\n function handle_slash() {\n next();\n return (S.regex_allowed) ? read_regexp("") : read_operator("/");\n };\n if (!handle_slash.__module__) Object.defineProperties(handle_slash, {\n __module__ : {value: "tokenizer"}\n });\n\n function handle_dot() {\n next();\n return (is_digit(peek().charCodeAt(0))) ? read_num(".") : token("punc", ".");\n };\n if (!handle_dot.__module__) Object.defineProperties(handle_dot, {\n __module__ : {value: "tokenizer"}\n });\n\n function read_word() {\n var word;\n word = read_name();\n return (KEYWORDS_ATOM[(typeof word === "number" && word < 0) ? KEYWORDS_ATOM.length + word : word]) ? token("atom", word) : (!KEYWORDS[(typeof word === "number" && word < 0) ? KEYWORDS.length + word : word]) ? token("name", word) : (OPERATORS[(typeof word === "number" && word < 0) ? OPERATORS.length + word : word] && prevChar() !== ".") ? token("operator", word) : token("keyword", word);\n };\n if (!read_word.__module__) Object.defineProperties(read_word, {\n __module__ : {value: "tokenizer"}\n });\n\n function next_token() {\n var indent, ch, code, tmp_, regex_allowed, tok, mods, start_pos_for_string, stok;\n indent = parse_whitespace();\n if (indent === -1) {\n return token("punc", "}", false, true);\n }\n start_token();\n ch = peek();\n if (!ch) {\n return token("eof");\n }\n code = ch.charCodeAt(0);\n tmp_ = code;\n if (tmp_ === 34 || tmp_ === 39) {\n return read_string(false);\n } else if (tmp_ === 35) {\n if (S.pos === 0 && S.text.charAt(1) === "!") {\n return read_line_comment(true);\n }\n regex_allowed = S.regex_allowed;\n S.comments_before.push(read_line_comment());\n S.regex_allowed = regex_allowed;\n return next_token();\n } else if (tmp_ === 46) {\n return handle_dot();\n } else if (tmp_ === 47) {\n return handle_slash();\n }\n if (is_digit(code)) {\n return read_num();\n }\n if (PUNC_CHARS[(typeof ch === "number" && ch < 0) ? PUNC_CHARS.length + ch : ch]) {\n return token("punc", next());\n }\n if (OPERATOR_CHARS[(typeof ch === "number" && ch < 0) ? OPERATOR_CHARS.length + ch : ch]) {\n return read_operator();\n }\n if (code === 92 && S.text.charAt(S.pos + 1) === "\\n") {\n next();\n next();\n S.newline_before = false;\n return next_token();\n }\n if (is_identifier_start(code)) {\n tok = read_word();\n if ("\'\\"".indexOf(peek()) !== -1 && is_string_modifier(tok.value)) {\n mods = tok.value.toLowerCase();\n start_pos_for_string = S.tokpos;\n stok = read_string(mods.indexOf("r") !== -1, mods.indexOf("v") !== -1);\n tok.endpos = stok.endpos;\n if (stok.type !== "js" && mods.indexOf("f") !== -1) {\n tok.col += start_pos_for_string - tok.pos;\n return handle_interpolated_string(stok.value, tok);\n }\n tok.value = stok.value;\n tok.type = stok.type;\n }\n return tok;\n }\n parse_error("Unexpected character «" + ch + "»");\n };\n if (!next_token.__module__) Object.defineProperties(next_token, {\n __module__ : {value: "tokenizer"}\n });\n\n next_token.context = (function() {\n var RS_anonfunc = function (nc) {\n if (nc) {\n S = nc;\n }\n return S;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["nc"]},\n __module__ : {value: "tokenizer"}\n });\n return RS_anonfunc;\n })();\n return next_token;\n };\n if (!tokenizer.__argnames__) Object.defineProperties(tokenizer, {\n __argnames__ : {value: ["raw_text", "filename"]},\n __module__ : {value: "tokenizer"}\n });\n\n RS_modules.tokenizer.RE_HEX_NUMBER = RE_HEX_NUMBER;\n RS_modules.tokenizer.RE_OCT_NUMBER = RE_OCT_NUMBER;\n RS_modules.tokenizer.RE_DEC_NUMBER = RE_DEC_NUMBER;\n RS_modules.tokenizer.OPERATOR_CHARS = OPERATOR_CHARS;\n RS_modules.tokenizer.ASCII_CONTROL_CHARS = ASCII_CONTROL_CHARS;\n RS_modules.tokenizer.HEX_PAT = HEX_PAT;\n RS_modules.tokenizer.NAME_PAT = NAME_PAT;\n RS_modules.tokenizer.OPERATORS = OPERATORS;\n RS_modules.tokenizer.OP_MAP = OP_MAP;\n RS_modules.tokenizer.WHITESPACE_CHARS = WHITESPACE_CHARS;\n RS_modules.tokenizer.PUNC_BEFORE_EXPRESSION = PUNC_BEFORE_EXPRESSION;\n RS_modules.tokenizer.PUNC_CHARS = PUNC_CHARS;\n RS_modules.tokenizer.KEYWORDS = KEYWORDS;\n RS_modules.tokenizer.KEYWORDS_ATOM = KEYWORDS_ATOM;\n RS_modules.tokenizer.RESERVED_WORDS = RESERVED_WORDS;\n RS_modules.tokenizer.KEYWORDS_BEFORE_EXPRESSION = KEYWORDS_BEFORE_EXPRESSION;\n RS_modules.tokenizer.ALL_KEYWORDS = ALL_KEYWORDS;\n RS_modules.tokenizer.IDENTIFIER_PAT = IDENTIFIER_PAT;\n RS_modules.tokenizer.UNICODE = UNICODE;\n RS_modules.tokenizer.EX_EOF = EX_EOF;\n RS_modules.tokenizer.is_string_modifier = is_string_modifier;\n RS_modules.tokenizer.is_letter = is_letter;\n RS_modules.tokenizer.is_digit = is_digit;\n RS_modules.tokenizer.is_alphanumeric_char = is_alphanumeric_char;\n RS_modules.tokenizer.is_unicode_combining_mark = is_unicode_combining_mark;\n RS_modules.tokenizer.is_unicode_connector_punctuation = is_unicode_connector_punctuation;\n RS_modules.tokenizer.is_identifier = is_identifier;\n RS_modules.tokenizer.is_identifier_start = is_identifier_start;\n RS_modules.tokenizer.is_identifier_char = is_identifier_char;\n RS_modules.tokenizer.parse_js_number = parse_js_number;\n RS_modules.tokenizer.is_token = is_token;\n RS_modules.tokenizer.tokenizer = tokenizer;\n })();\n\n (function(){\n var __name__ = "parse";\n var COMPILER_VERSION, PYTHON_FLAGS, NATIVE_CLASSES, ERROR_CLASSES, COMMON_STATIC, FORBIDDEN_CLASS_VARS, UNARY_PREFIX, ASSIGNMENT, PRECEDENCE, STATEMENTS_WITH_LABELS, ATOMIC_START_TOKEN, compile_time_decorators;\n var make_predicate = RS_modules.utils.make_predicate;\n var array_to_hash = RS_modules.utils.array_to_hash;\n var defaults = RS_modules.utils.defaults;\n var has_prop = RS_modules.utils.has_prop;\n var cache_file_name = RS_modules.utils.cache_file_name;\n\n var SyntaxError = RS_modules.errors.SyntaxError;\n var ImportError = RS_modules.errors.ImportError;\n\n var AST_Array = RS_modules.ast.AST_Array;\n var AST_Assign = RS_modules.ast.AST_Assign;\n var AST_Binary = RS_modules.ast.AST_Binary;\n var AST_BlockStatement = RS_modules.ast.AST_BlockStatement;\n var AST_Break = RS_modules.ast.AST_Break;\n var AST_Call = RS_modules.ast.AST_Call;\n var AST_Catch = RS_modules.ast.AST_Catch;\n var AST_Class = RS_modules.ast.AST_Class;\n var AST_ClassCall = RS_modules.ast.AST_ClassCall;\n var AST_Conditional = RS_modules.ast.AST_Conditional;\n var AST_Constant = RS_modules.ast.AST_Constant;\n var AST_Continue = RS_modules.ast.AST_Continue;\n var AST_DWLoop = RS_modules.ast.AST_DWLoop;\n var AST_Debugger = RS_modules.ast.AST_Debugger;\n var AST_Decorator = RS_modules.ast.AST_Decorator;\n var AST_Definitions = RS_modules.ast.AST_Definitions;\n var AST_DictComprehension = RS_modules.ast.AST_DictComprehension;\n var AST_Directive = RS_modules.ast.AST_Directive;\n var AST_Do = RS_modules.ast.AST_Do;\n var AST_Dot = RS_modules.ast.AST_Dot;\n var AST_Else = RS_modules.ast.AST_Else;\n var AST_EmptyStatement = RS_modules.ast.AST_EmptyStatement;\n var AST_Except = RS_modules.ast.AST_Except;\n var AST_ExpressiveObject = RS_modules.ast.AST_ExpressiveObject;\n var AST_False = RS_modules.ast.AST_False;\n var AST_Finally = RS_modules.ast.AST_Finally;\n var AST_ForIn = RS_modules.ast.AST_ForIn;\n var AST_ForJS = RS_modules.ast.AST_ForJS;\n var AST_Function = RS_modules.ast.AST_Function;\n var AST_GeneratorComprehension = RS_modules.ast.AST_GeneratorComprehension;\n var AST_Hole = RS_modules.ast.AST_Hole;\n var AST_If = RS_modules.ast.AST_If;\n var AST_Import = RS_modules.ast.AST_Import;\n var AST_ImportedVar = RS_modules.ast.AST_ImportedVar;\n var AST_Imports = RS_modules.ast.AST_Imports;\n var AST_ListComprehension = RS_modules.ast.AST_ListComprehension;\n var AST_Method = RS_modules.ast.AST_Method;\n var AST_New = RS_modules.ast.AST_New;\n var AST_Null = RS_modules.ast.AST_Null;\n var AST_Number = RS_modules.ast.AST_Number;\n var AST_Object = RS_modules.ast.AST_Object;\n var AST_ObjectKeyVal = RS_modules.ast.AST_ObjectKeyVal;\n var AST_PropAccess = RS_modules.ast.AST_PropAccess;\n var AST_RegExp = RS_modules.ast.AST_RegExp;\n var AST_Return = RS_modules.ast.AST_Return;\n var AST_Scope = RS_modules.ast.AST_Scope;\n var AST_Set = RS_modules.ast.AST_Set;\n var AST_SetComprehension = RS_modules.ast.AST_SetComprehension;\n var AST_SetItem = RS_modules.ast.AST_SetItem;\n var AST_Seq = RS_modules.ast.AST_Seq;\n var AST_SimpleStatement = RS_modules.ast.AST_SimpleStatement;\n var AST_Splice = RS_modules.ast.AST_Splice;\n var AST_String = RS_modules.ast.AST_String;\n var AST_Sub = RS_modules.ast.AST_Sub;\n var AST_ItemAccess = RS_modules.ast.AST_ItemAccess;\n var AST_SymbolAlias = RS_modules.ast.AST_SymbolAlias;\n var AST_SymbolCatch = RS_modules.ast.AST_SymbolCatch;\n var AST_SymbolDefun = RS_modules.ast.AST_SymbolDefun;\n var AST_SymbolFunarg = RS_modules.ast.AST_SymbolFunarg;\n var AST_SymbolLambda = RS_modules.ast.AST_SymbolLambda;\n var AST_SymbolNonlocal = RS_modules.ast.AST_SymbolNonlocal;\n var AST_SymbolRef = RS_modules.ast.AST_SymbolRef;\n var AST_SymbolVar = RS_modules.ast.AST_SymbolVar;\n var AST_This = RS_modules.ast.AST_This;\n var AST_Throw = RS_modules.ast.AST_Throw;\n var AST_Toplevel = RS_modules.ast.AST_Toplevel;\n var AST_True = RS_modules.ast.AST_True;\n var AST_Try = RS_modules.ast.AST_Try;\n var AST_UnaryPrefix = RS_modules.ast.AST_UnaryPrefix;\n var AST_Undefined = RS_modules.ast.AST_Undefined;\n var AST_Var = RS_modules.ast.AST_Var;\n var AST_VarDef = RS_modules.ast.AST_VarDef;\n var AST_Verbatim = RS_modules.ast.AST_Verbatim;\n var AST_While = RS_modules.ast.AST_While;\n var AST_With = RS_modules.ast.AST_With;\n var AST_WithClause = RS_modules.ast.AST_WithClause;\n var AST_Yield = RS_modules.ast.AST_Yield;\n var AST_Assert = RS_modules.ast.AST_Assert;\n var AST_Existential = RS_modules.ast.AST_Existential;\n var is_node_type = RS_modules.ast.is_node_type;\n\n var tokenizer = RS_modules.tokenizer.tokenizer;\n var is_token = RS_modules.tokenizer.is_token;\n var RESERVED_WORDS = RS_modules.tokenizer.RESERVED_WORDS;\n\n COMPILER_VERSION = "6ed1f600c6e0e6225a4b6b4947d8a6816bb48365";\n PYTHON_FLAGS = (function(){\n var RS_d = Object.create(null);\n RS_d["dict_literals"] = true;\n RS_d["overload_getitem"] = true;\n RS_d["bound_methods"] = true;\n RS_d["hash_literals"] = true;\n return RS_d;\n }).call(this);\n function get_compiler_version() {\n return COMPILER_VERSION;\n };\n if (!get_compiler_version.__module__) Object.defineProperties(get_compiler_version, {\n __module__ : {value: "parse"}\n });\n\n function static_predicate(names) {\n return (function() {\n var RS_Iter = RS_Iterable(names.split(" ")), RS_Result = Object.create(null), k;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n k = RS_Iter[RS_Index];\n RS_Result[k] = (true);\n }\n return RS_Result;\n })();\n };\n if (!static_predicate.__argnames__) Object.defineProperties(static_predicate, {\n __argnames__ : {value: ["names"]},\n __module__ : {value: "parse"}\n });\n\n NATIVE_CLASSES = (function(){\n var RS_d = Object.create(null);\n RS_d["Image"] = Object.create(null);\n RS_d["FileReader"] = Object.create(null);\n RS_d["RegExp"] = Object.create(null);\n RS_d["Error"] = Object.create(null);\n RS_d["EvalError"] = Object.create(null);\n RS_d["InternalError"] = Object.create(null);\n RS_d["RangeError"] = Object.create(null);\n RS_d["ReferenceError"] = Object.create(null);\n RS_d["SyntaxError"] = Object.create(null);\n RS_d["TypeError"] = Object.create(null);\n RS_d["URIError"] = Object.create(null);\n RS_d["Object"] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = static_predicate("getOwnPropertyNames getOwnPropertyDescriptor getOwnPropertyDescriptors getOwnPropertySymbols keys entries values create defineProperty defineProperties getPrototypeOf setPrototypeOf assign seal isSealed is preventExtensions isExtensible freeze isFrozen");\n return RS_d;\n }).call(this);\n RS_d["String"] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = static_predicate("fromCharCode");\n return RS_d;\n }).call(this);\n RS_d["Array"] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = static_predicate("isArray from of");\n return RS_d;\n }).call(this);\n RS_d["Function"] = Object.create(null);\n RS_d["Date"] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = static_predicate("UTC now parse");\n return RS_d;\n }).call(this);\n RS_d["ArrayBuffer"] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = static_predicate("isView transfer");\n return RS_d;\n }).call(this);\n RS_d["DataView"] = Object.create(null);\n RS_d["Float32Array"] = Object.create(null);\n RS_d["Float64Array"] = Object.create(null);\n RS_d["Int16Array"] = Object.create(null);\n RS_d["Int32Array"] = Object.create(null);\n RS_d["Int8Array"] = Object.create(null);\n RS_d["Uint16Array"] = Object.create(null);\n RS_d["Uint32Array"] = Object.create(null);\n RS_d["Uint8Array"] = Object.create(null);\n RS_d["Uint8ClampedArray"] = Object.create(null);\n RS_d["Map"] = Object.create(null);\n RS_d["WeakMap"] = Object.create(null);\n RS_d["Proxy"] = Object.create(null);\n RS_d["Set"] = Object.create(null);\n RS_d["WeakSet"] = Object.create(null);\n RS_d["Promise"] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = static_predicate("all race reject resolve");\n return RS_d;\n }).call(this);\n RS_d["WebSocket"] = Object.create(null);\n RS_d["XMLHttpRequest"] = Object.create(null);\n RS_d["TextEncoder"] = Object.create(null);\n RS_d["TextDecoder"] = Object.create(null);\n RS_d["MouseEvent"] = Object.create(null);\n RS_d["Event"] = Object.create(null);\n RS_d["CustomEvent"] = Object.create(null);\n RS_d["Blob"] = Object.create(null);\n return RS_d;\n }).call(this);\n ERROR_CLASSES = (function(){\n var RS_d = Object.create(null);\n RS_d["Exception"] = Object.create(null);\n RS_d["AttributeError"] = Object.create(null);\n RS_d["IndexError"] = Object.create(null);\n RS_d["KeyError"] = Object.create(null);\n RS_d["ValueError"] = Object.create(null);\n RS_d["UnicodeDecodeError"] = Object.create(null);\n RS_d["AssertionError"] = Object.create(null);\n RS_d["ZeroDivisionError"] = Object.create(null);\n return RS_d;\n }).call(this);\n COMMON_STATIC = static_predicate("call apply bind toString");\n FORBIDDEN_CLASS_VARS = "prototype constructor".split(" ");\n UNARY_PREFIX = make_predicate("typeof void delete ~ - + ! @");\n ASSIGNMENT = make_predicate("= += -= /= //= *= %= >>= <<= >>>= |= ^= &=");\n PRECEDENCE = (function() {\n var RS_anonfunc = function (a, ret) {\n var b, j, i;\n for (var RS_Index38 = 0; RS_Index38 < a.length; RS_Index38++) {\n i = RS_Index38;\n b = a[(typeof i === "number" && i < 0) ? a.length + i : i];\n for (var RS_Index39 = 0; RS_Index39 < b.length; RS_Index39++) {\n j = RS_Index39;\n ret[RS_bound_index(b[(typeof j === "number" && j < 0) ? b.length + j : j], ret)] = i + 1;\n }\n }\n return ret;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["a", "ret"]},\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })()(RS_list_decorate([ RS_list_decorate([ "||" ]), RS_list_decorate([ "&&" ]), RS_list_decorate([ "|" ]), RS_list_decorate([ "^" ]), RS_list_decorate([ "&" ]), RS_list_decorate([ "==", "===", "!=", "!==" ]), RS_list_decorate([ "<", ">", "<=", ">=", "in", "nin", "instanceof" ]), RS_list_decorate([ ">>", "<<", ">>>" ]), RS_list_decorate([ "+", "-" ]), RS_list_decorate([ "*", "/", "//", "%" ]), RS_list_decorate([ "**" ]) ]), Object.create(null));\n STATEMENTS_WITH_LABELS = array_to_hash(RS_list_decorate([ "for", "do", "while", "switch" ]));\n ATOMIC_START_TOKEN = array_to_hash(RS_list_decorate([ "atom", "num", "string", "regexp", "name", "js" ]));\n compile_time_decorators = RS_list_decorate([ "staticmethod", "external", "property" ]);\n function has_simple_decorator(decorators, name) {\n var remove, s;\n remove = [];\n for (var i = 0; i < decorators.length; i++) {\n s = decorators[(typeof i === "number" && i < 0) ? decorators.length + i : i];\n if (is_node_type(s, AST_SymbolRef) && !s.parens && s.name === name) {\n remove.push(i);\n }\n }\n if (remove.length) {\n remove.reverse();\n for (var i = 0; i < remove.length; i++) {\n decorators.splice(remove[(typeof i === "number" && i < 0) ? remove.length + i : i], 1);\n }\n return true;\n }\n return false;\n };\n if (!has_simple_decorator.__argnames__) Object.defineProperties(has_simple_decorator, {\n __argnames__ : {value: ["decorators", "name"]},\n __module__ : {value: "parse"}\n });\n\n function has_setter_decorator(decorators, name) {\n var remove, s;\n remove = [];\n for (var i = 0; i < decorators.length; i++) {\n s = decorators[(typeof i === "number" && i < 0) ? decorators.length + i : i];\n if (is_node_type(s, AST_Dot) && is_node_type(s.expression, AST_SymbolRef) && s.expression.name === name && s.property === "setter") {\n remove.push(i);\n }\n }\n if (remove.length) {\n remove.reverse();\n for (var i = 0; i < remove.length; i++) {\n decorators.splice(remove[(typeof i === "number" && i < 0) ? remove.length + i : i], 1);\n }\n return true;\n }\n return false;\n };\n if (!has_setter_decorator.__argnames__) Object.defineProperties(has_setter_decorator, {\n __argnames__ : {value: ["decorators", "name"]},\n __module__ : {value: "parse"}\n });\n\n function create_parser_ctx(S, import_dirs, module_id, baselib_items, imported_module_ids, imported_modules, importing_modules, options) {\n function next() {\n S.prev = S.token;\n if (S.peeked.length) {\n S.token = S.peeked.shift();\n } else {\n S.token = S.input();\n }\n return S.token;\n };\n if (!next.__module__) Object.defineProperties(next, {\n __module__ : {value: "parse"}\n });\n\n function is_(type, value) {\n return is_token(S.token, type, value);\n };\n if (!is_.__argnames__) Object.defineProperties(is_, {\n __argnames__ : {value: ["type", "value"]},\n __module__ : {value: "parse"}\n });\n\n function peek() {\n if (!S.peeked.length) {\n S.peeked.push(S.input());\n }\n return S.peeked[0];\n };\n if (!peek.__module__) Object.defineProperties(peek, {\n __module__ : {value: "parse"}\n });\n\n function prev() {\n return S.prev;\n };\n if (!prev.__module__) Object.defineProperties(prev, {\n __module__ : {value: "parse"}\n });\n\n function croak(msg, line, col, pos, is_eof) {\n var ctx;\n ctx = S.input.context();\n throw new SyntaxError(msg, ctx.filename, (line !== undefined) ? line : ctx.tokline, (col !== undefined) ? col : ctx.tokcol, (pos !== undefined) ? pos : ctx.tokpos, is_eof);\n };\n if (!croak.__argnames__) Object.defineProperties(croak, {\n __argnames__ : {value: ["msg", "line", "col", "pos", "is_eof"]},\n __module__ : {value: "parse"}\n });\n\n function token_error(token, msg) {\n var is_eof;\n is_eof = token.type === "eof";\n croak(msg, token.line, token.col, undefined, is_eof);\n };\n if (!token_error.__argnames__) Object.defineProperties(token_error, {\n __argnames__ : {value: ["token", "msg"]},\n __module__ : {value: "parse"}\n });\n\n function unexpected(token) {\n if (token === undefined) {\n token = S.token;\n }\n token_error(token, "Unexpected token: " + token.type + " «" + token.value + "»");\n };\n if (!unexpected.__argnames__) Object.defineProperties(unexpected, {\n __argnames__ : {value: ["token"]},\n __module__ : {value: "parse"}\n });\n\n function expect_token(type, val) {\n if (is_(type, val)) {\n return next();\n }\n token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");\n };\n if (!expect_token.__argnames__) Object.defineProperties(expect_token, {\n __argnames__ : {value: ["type", "val"]},\n __module__ : {value: "parse"}\n });\n\n function expect(punc) {\n return expect_token("punc", punc);\n };\n if (!expect.__argnames__) Object.defineProperties(expect, {\n __argnames__ : {value: ["punc"]},\n __module__ : {value: "parse"}\n });\n\n function semicolon() {\n if (is_("punc", ";")) {\n next();\n S.token.nlb = true;\n }\n };\n if (!semicolon.__module__) Object.defineProperties(semicolon, {\n __module__ : {value: "parse"}\n });\n\n function embed_tokens(parser) {\n function with_embedded_tokens() {\n var start, expr, end;\n start = S.token;\n expr = parser();\n if (expr === undefined) {\n unexpected();\n }\n end = prev();\n expr.start = start;\n expr.end = end;\n return expr;\n };\n if (!with_embedded_tokens.__module__) Object.defineProperties(with_embedded_tokens, {\n __module__ : {value: "parse"}\n });\n\n return with_embedded_tokens;\n };\n if (!embed_tokens.__argnames__) Object.defineProperties(embed_tokens, {\n __argnames__ : {value: ["parser"]},\n __module__ : {value: "parse"}\n });\n\n function scan_for_top_level_callables(body) {\n var ans, opt, x, obj;\n ans = [];\n if (Array.isArray(body)) {\n var RS_Iter40 = RS_Iterable(body);\n for (var RS_Index40 = 0; RS_Index40 < RS_Iter40.length; RS_Index40++) {\n obj = RS_Iter40[RS_Index40];\n if (is_node_type(obj, AST_Function) || is_node_type(obj, AST_Class)) {\n if (obj.name) {\n ans.push(obj.name.name);\n } else {\n token_error(obj.start, "Top-level functions must have names");\n }\n } else {\n if (is_node_type(obj, AST_Scope)) {\n continue;\n }\n var RS_Iter41 = RS_Iterable(RS_list_decorate([ "body", "alternative" ]));\n for (var RS_Index41 = 0; RS_Index41 < RS_Iter41.length; RS_Index41++) {\n x = RS_Iter41[RS_Index41];\n opt = obj[(typeof x === "number" && x < 0) ? obj.length + x : x];\n if (opt) {\n ans = ans.concat(scan_for_top_level_callables(opt));\n }\n if (is_node_type(opt, AST_Assign) && !(is_node_type(opt.right, AST_Scope))) {\n ans = ans.concat(scan_for_top_level_callables(opt.right));\n }\n }\n }\n }\n } else if (body.body) {\n ans = ans.concat(scan_for_top_level_callables(body.body));\n if (body.alternative) {\n ans = ans.concat(scan_for_top_level_callables(body.alternative));\n }\n }\n return ans;\n };\n if (!scan_for_top_level_callables.__argnames__) Object.defineProperties(scan_for_top_level_callables, {\n __argnames__ : {value: ["body"]},\n __module__ : {value: "parse"}\n });\n\n function scan_for_classes(body) {\n var ans, obj;\n ans = Object.create(null);\n var RS_Iter42 = RS_Iterable(body);\n for (var RS_Index42 = 0; RS_Index42 < RS_Iter42.length; RS_Index42++) {\n obj = RS_Iter42[RS_Index42];\n if (is_node_type(obj, AST_Class)) {\n ans[RS_bound_index(obj.name.name, ans)] = obj;\n }\n }\n return ans;\n };\n if (!scan_for_classes.__argnames__) Object.defineProperties(scan_for_classes, {\n __argnames__ : {value: ["body"]},\n __module__ : {value: "parse"}\n });\n\n function scan_for_local_vars(body) {\n var localvars, seen, opt, option, clause, stmt, is_compound_assign, lhs;\n localvars = [];\n seen = Object.create(null);\n function push(x) {\n if (has_prop(seen, x)) {\n return;\n }\n seen[(typeof x === "number" && x < 0) ? seen.length + x : x] = true;\n localvars.push(x);\n };\n if (!push.__argnames__) Object.defineProperties(push, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "parse"}\n });\n\n function extend(arr) {\n var x;\n var RS_Iter43 = RS_Iterable(arr);\n for (var RS_Index43 = 0; RS_Index43 < RS_Iter43.length; RS_Index43++) {\n x = RS_Iter43[RS_Index43];\n push(x);\n }\n };\n if (!extend.__argnames__) Object.defineProperties(extend, {\n __argnames__ : {value: ["arr"]},\n __module__ : {value: "parse"}\n });\n\n function scan_in_array(arr) {\n var x;\n var RS_Iter44 = RS_Iterable(arr);\n for (var RS_Index44 = 0; RS_Index44 < RS_Iter44.length; RS_Index44++) {\n x = RS_Iter44[RS_Index44];\n if (is_node_type(x, AST_Seq)) {\n x = x.to_array();\n } else if (is_node_type(x, AST_Array)) {\n x = x.elements;\n }\n if (Array.isArray(x)) {\n scan_in_array(x);\n } else {\n if (!is_node_type(x, AST_PropAccess)) {\n push(x.name);\n }\n }\n }\n };\n if (!scan_in_array.__argnames__) Object.defineProperties(scan_in_array, {\n __argnames__ : {value: ["arr"]},\n __module__ : {value: "parse"}\n });\n\n function add_assign_lhs(lhs) {\n if (is_node_type(lhs, AST_Seq)) {\n lhs = new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = lhs.to_array();\n return RS_d;\n }).call(this));\n }\n if (is_node_type(lhs, AST_Array)) {\n push("RS_unpack");\n scan_in_array(lhs.elements);\n } else if (lhs.name) {\n push(lhs.name);\n }\n };\n if (!add_assign_lhs.__argnames__) Object.defineProperties(add_assign_lhs, {\n __argnames__ : {value: ["lhs"]},\n __module__ : {value: "parse"}\n });\n\n function add_for_in(stmt) {\n if (is_node_type(stmt.init, AST_Array)) {\n push("RS_unpack");\n scan_in_array(stmt.init.elements);\n } else {\n push(stmt.init.name);\n }\n };\n if (!add_for_in.__argnames__) Object.defineProperties(add_for_in, {\n __argnames__ : {value: ["stmt"]},\n __module__ : {value: "parse"}\n });\n\n if (Array.isArray(body)) {\n var RS_Iter45 = RS_Iterable(body);\n for (var RS_Index45 = 0; RS_Index45 < RS_Iter45.length; RS_Index45++) {\n stmt = RS_Iter45[RS_Index45];\n if (is_node_type(stmt, AST_Scope)) {\n continue;\n }\n var RS_Iter46 = RS_Iterable(RS_list_decorate([ "body", "alternative", "bcatch", "condition" ]));\n for (var RS_Index46 = 0; RS_Index46 < RS_Iter46.length; RS_Index46++) {\n option = RS_Iter46[RS_Index46];\n opt = stmt[(typeof option === "number" && option < 0) ? stmt.length + option : option];\n if (opt) {\n extend(scan_for_local_vars(opt));\n }\n if (is_node_type(opt, AST_Assign) && !(is_node_type(opt.right, AST_Scope))) {\n extend(scan_for_local_vars(opt.right));\n }\n }\n if (is_node_type(stmt, AST_ForIn)) {\n add_for_in(stmt);\n } else if (is_node_type(stmt, AST_DWLoop)) {\n extend(scan_for_local_vars(stmt));\n } else if (is_node_type(stmt, AST_With)) {\n [push("RS_with_exception"), push("RS_with_suppress")];\n var RS_Iter47 = RS_Iterable(stmt.clauses);\n for (var RS_Index47 = 0; RS_Index47 < RS_Iter47.length; RS_Index47++) {\n clause = RS_Iter47[RS_Index47];\n if (clause.alias) {\n push(clause.alias.name);\n }\n }\n }\n }\n } else if (body.body) {\n extend(scan_for_local_vars(body.body));\n if (body.alternative) {\n extend(scan_for_local_vars(body.alternative));\n }\n } else if (is_node_type(body, AST_Assign)) {\n if (body.is_chained()) {\n is_compound_assign = false;\n var RS_Iter48 = RS_Iterable(body.traverse_chain()[0]);\n for (var RS_Index48 = 0; RS_Index48 < RS_Iter48.length; RS_Index48++) {\n lhs = RS_Iter48[RS_Index48];\n add_assign_lhs(lhs);\n if (is_node_type(lhs, AST_Seq) || is_node_type(lhs, AST_Array)) {\n is_compound_assign = true;\n break;\n }\n }\n if (is_compound_assign) {\n push("RS_chain_assign_temp");\n }\n } else {\n add_assign_lhs(body.left);\n }\n if (!is_node_type(body.right, AST_Scope)) {\n extend(scan_for_local_vars(body.right));\n }\n } else if (is_node_type(body, AST_ForIn)) {\n add_for_in(body);\n }\n return localvars;\n };\n if (!scan_for_local_vars.__argnames__) Object.defineProperties(scan_for_local_vars, {\n __argnames__ : {value: ["body"]},\n __module__ : {value: "parse"}\n });\n\n function scan_for_nonlocal_defs(body) {\n var vardef, opt, option, stmt;\n vars = [];\n if (Array.isArray(body)) {\n var RS_Iter49 = RS_Iterable(body);\n for (var RS_Index49 = 0; RS_Index49 < RS_Iter49.length; RS_Index49++) {\n stmt = RS_Iter49[RS_Index49];\n if (is_node_type(stmt, AST_Scope)) {\n continue;\n }\n if (is_node_type(stmt, AST_Definitions)) {\n var RS_Iter50 = RS_Iterable(stmt.definitions);\n for (var RS_Index50 = 0; RS_Index50 < RS_Iter50.length; RS_Index50++) {\n vardef = RS_Iter50[RS_Index50];\n vars.push(vardef.name.name);\n }\n }\n var RS_Iter51 = RS_Iterable(RS_list_decorate([ "body", "alternative" ]));\n for (var RS_Index51 = 0; RS_Index51 < RS_Iter51.length; RS_Index51++) {\n option = RS_Iter51[RS_Index51];\n var vars;\n opt = stmt[(typeof option === "number" && option < 0) ? stmt.length + option : option];\n if (opt) {\n vars = vars.concat(scan_for_nonlocal_defs(opt));\n }\n }\n }\n } else if (body.body) {\n vars = vars.concat(scan_for_nonlocal_defs(body.body));\n if (body.alternative) {\n vars = vars.concat(scan_for_nonlocal_defs(body.alternative));\n }\n }\n return vars;\n };\n if (!scan_for_nonlocal_defs.__argnames__) Object.defineProperties(scan_for_nonlocal_defs, {\n __argnames__ : {value: ["body"]},\n __module__ : {value: "parse"}\n });\n\n function return_() {\n var value, is_end_of_statement;\n if (is_("punc", ";")) {\n semicolon();\n value = null;\n } else {\n is_end_of_statement = S.token.nlb || is_("eof") || is_("punc", "}");\n if (is_end_of_statement) {\n value = null;\n } else {\n value = expression(true);\n semicolon();\n }\n }\n return value;\n };\n if (!return_.__module__) Object.defineProperties(return_, {\n __module__ : {value: "parse"}\n });\n\n \n var statement = embed_tokens((function() {\n var RS_anonfunc = function statement() {\n var tmp_, p, while_cond, start, func, chain, cond, msg, tmp;\n if (S.token.type === "operator" && S.token.value.substr(0, 1) === "/") {\n token_error(S.token, "RapydScript does not support statements starting with regexp literals");\n }\n S.statement_starting_token = S.token;\n tmp_ = S.token.type;\n p = prev();\n if (p && !S.token.nlb && ATOMIC_START_TOKEN[RS_bound_index(p.type, ATOMIC_START_TOKEN)] && !is_("punc", ":")) {\n unexpected();\n }\n if (tmp_ === "string") {\n return simple_statement();\n } else if (tmp_ === "shebang") {\n tmp_ = S.token.value;\n next();\n return new AST_Directive((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = tmp_;\n return RS_d;\n }).call(this));\n } else if (tmp_ === "num" || tmp_ === "regexp" || tmp_ === "operator" || tmp_ === "atom" || tmp_ === "js") {\n return simple_statement();\n } else if (tmp_ === "punc") {\n tmp_ = S.token.value;\n if (tmp_ === ":") {\n return new AST_BlockStatement((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = S.token;\n RS_d["body"] = block_();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n } else if (tmp_ === "{" || tmp_ === "[" || tmp_ === "(") {\n return simple_statement();\n } else if (tmp_ === ";") {\n next();\n return new AST_EmptyStatement((function(){\n var RS_d = Object.create(null);\n RS_d["stype"] = ";";\n RS_d["start"] = prev();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n } else {\n unexpected();\n }\n } else if (tmp_ === "name") {\n if (is_token(peek(), "punc", ":")) token_error(peek(), "invalid syntax, colon not allowed here");\n return simple_statement();\n } else if (tmp_ === "keyword") {\n tmp_ = S.token.value;\n next();\n if (tmp_ === "break") {\n return break_cont(AST_Break);\n } else if (tmp_ === "continue") {\n return break_cont(AST_Continue);\n } else if (tmp_ === "debugger") {\n semicolon();\n return new AST_Debugger;\n } else if (tmp_ === "do") {\n return new AST_Do((function(){\n var RS_d = Object.create(null);\n RS_d["body"] = in_loop(statement);\n RS_d["condition"] = (function() {\n var RS_anonfunc = function () {\n var tmp;\n expect(".");\n expect_token("keyword", "while");\n tmp = expression(true);\n if (is_node_type(tmp, AST_Assign)) {\n croak("Assignments in do loop conditions are not allowed");\n }\n semicolon();\n return tmp;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })()();\n return RS_d;\n }).call(this));\n } else if (tmp_ === "while") {\n while_cond = expression(true);\n if (is_node_type(while_cond, AST_Assign)) {\n croak("Assignments in while loop conditions are not allowed");\n }\n if (!is_("punc", ":")) {\n croak("Expected a colon after the while statement");\n }\n return new AST_While((function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = while_cond;\n RS_d["body"] = in_loop(statement);\n return RS_d;\n }).call(this));\n } else if (tmp_ === "for") {\n if (is_("js")) {\n return for_js();\n }\n return for_();\n } else if (tmp_ === "from") {\n return import_(true);\n } else if (tmp_ === "import") {\n return import_(false);\n } else if (tmp_ === "class") {\n return class_();\n } else if (tmp_ === "def") {\n start = prev();\n func = function_((RS_expr_temp = S.in_class)[RS_expr_temp.length-1], false);\n func.start = start;\n func.end = prev();\n chain = subscripts(func, true);\n if (chain === func) {\n return func;\n } else {\n return new AST_SimpleStatement((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["body"] = chain;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n }\n } else if (tmp_ === "assert") {\n start = prev();\n cond = expression(false);\n msg = null;\n if (is_("punc", ",")) {\n next();\n msg = expression(false);\n }\n return new AST_Assert((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["condition"] = cond;\n RS_d["message"] = msg;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n } else if (tmp_ === "if") {\n return if_();\n } else if (tmp_ === "pass") {\n semicolon();\n return new AST_EmptyStatement((function(){\n var RS_d = Object.create(null);\n RS_d["stype"] = "pass";\n RS_d["start"] = prev();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n } else if (tmp_ === "return") {\n if (S.in_function === 0) {\n croak("\'return\' outside of function");\n }\n if ((RS_expr_temp = S.functions)[RS_expr_temp.length-1].is_generator) {\n croak("\'return\' not allowed in a function with yield");\n }\n (RS_expr_temp = S.functions)[RS_expr_temp.length-1].is_generator = false;\n return new AST_Return((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = return_();\n return RS_d;\n }).call(this));\n } else if (tmp_ === "yield") {\n return yield_();\n } else if (tmp_ === "raise") {\n if (S.token.nlb) {\n return new AST_Throw((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = new AST_SymbolCatch((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "RS_Exception";\n return RS_d;\n }).call(this));\n return RS_d;\n }).call(this));\n }\n tmp = expression(true);\n semicolon();\n return new AST_Throw((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = tmp;\n return RS_d;\n }).call(this));\n } else if (tmp_ === "try") {\n return try_();\n } else if (tmp_ === "nonlocal") {\n tmp = nonlocal_();\n semicolon();\n return tmp;\n } else if (tmp_ === "global") {\n tmp = nonlocal_(true);\n semicolon();\n return tmp;\n } else if (tmp_ === "with") {\n return with_();\n } else {\n unexpected();\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })());\n\n function with_() {\n var clauses, start, expr, alias, body;\n clauses = [];\n start = S.token;\n while (true) {\n if (is_("eof")) {\n unexpected();\n }\n expr = expression();\n alias = null;\n if (is_("keyword", "as")) {\n next();\n alias = as_symbol(AST_SymbolAlias);\n }\n clauses.push(new AST_WithClause((function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = expr;\n RS_d["alias"] = alias;\n return RS_d;\n }).call(this)));\n if (is_("punc", ",")) {\n next();\n continue;\n }\n if (!is_("punc", ":")) {\n unexpected();\n }\n break;\n }\n if (!clauses.length) {\n token_error(start, "with statement must have at least one clause");\n }\n body = statement();\n return new AST_With((function(){\n var RS_d = Object.create(null);\n RS_d["clauses"] = clauses;\n RS_d["body"] = body;\n return RS_d;\n }).call(this));\n };\n if (!with_.__module__) Object.defineProperties(with_, {\n __module__ : {value: "parse"}\n });\n\n function simple_statement(tmp) {\n tmp = expression(true);\n semicolon();\n return new AST_SimpleStatement((function(){\n var RS_d = Object.create(null);\n RS_d["body"] = tmp;\n return RS_d;\n }).call(this));\n };\n if (!simple_statement.__argnames__) Object.defineProperties(simple_statement, {\n __argnames__ : {value: ["tmp"]},\n __module__ : {value: "parse"}\n });\n\n function break_cont(t) {\n if (S.in_loop === 0) {\n croak(t.name.slice(4) + " not inside a loop or switch");\n }\n semicolon();\n return new t;\n };\n if (!break_cont.__argnames__) Object.defineProperties(break_cont, {\n __argnames__ : {value: ["t"]},\n __module__ : {value: "parse"}\n });\n\n function yield_() {\n var is_yield_from;\n if (S.in_function === 0) {\n croak("\'yield\' outside of function");\n }\n if ((RS_expr_temp = S.functions)[RS_expr_temp.length-1].is_generator === false) {\n croak("\'yield\' not allowed in a function with return");\n }\n (RS_expr_temp = S.functions)[RS_expr_temp.length-1].is_generator = true;\n is_yield_from = is_("keyword", "from");\n if (is_yield_from) {\n next();\n }\n return new AST_Yield((function(){\n var RS_d = Object.create(null);\n RS_d["is_yield_from"] = is_yield_from;\n RS_d["value"] = return_();\n return RS_d;\n }).call(this));\n };\n if (!yield_.__module__) Object.defineProperties(yield_, {\n __module__ : {value: "parse"}\n });\n\n function for_(list_comp) {\n var init, tmp;\n init = null;\n if (!is_("punc", ";")) {\n init = expression(true, true);\n if (is_node_type(init, AST_Seq)) {\n if (is_node_type(init.car, AST_SymbolRef) && is_node_type(init.cdr, AST_SymbolRef)) {\n tmp = init.to_array();\n } else {\n tmp = RS_list_decorate([ init ]);\n }\n init = new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = init.start;\n RS_d["elements"] = tmp;\n RS_d["end"] = init.end;\n return RS_d;\n }).call(this));\n }\n if (is_("operator", "in")) {\n if (is_node_type(init, AST_Var) && init.definitions.length > 1) {\n croak("Only one variable declaration allowed in for..in loop");\n }\n next();\n return for_in(init, list_comp);\n }\n }\n unexpected();\n };\n if (!for_.__argnames__) Object.defineProperties(for_, {\n __argnames__ : {value: ["list_comp"]},\n __module__ : {value: "parse"}\n });\n\n function for_in(init, list_comp) {\n var lhs, obj;\n lhs = (is_node_type(init, AST_Var)) ? init.definitions[0].name : null;\n obj = expression(true);\n if (list_comp) {\n return (function(){\n var RS_d = Object.create(null);\n RS_d["init"] = init;\n RS_d["name"] = lhs;\n RS_d["object"] = obj;\n return RS_d;\n }).call(this);\n }\n return new AST_ForIn((function(){\n var RS_d = Object.create(null);\n RS_d["init"] = init;\n RS_d["name"] = lhs;\n RS_d["object"] = obj;\n RS_d["body"] = in_loop(statement);\n return RS_d;\n }).call(this));\n };\n if (!for_in.__argnames__) Object.defineProperties(for_in, {\n __argnames__ : {value: ["init", "list_comp"]},\n __module__ : {value: "parse"}\n });\n\n function for_js() {\n var condition;\n condition = as_atom_node();\n return new AST_ForJS((function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = condition;\n RS_d["body"] = in_loop(statement);\n return RS_d;\n }).call(this));\n };\n if (!for_js.__module__) Object.defineProperties(for_js, {\n __module__ : {value: "parse"}\n });\n\n function get_class_in_scope(expr) {\n var s, referenced_path, class_name;\n if (is_node_type(expr, AST_SymbolRef)) {\n if (has_prop(NATIVE_CLASSES, expr.name)) {\n return NATIVE_CLASSES[RS_bound_index(expr.name, NATIVE_CLASSES)];\n }\n if (has_prop(ERROR_CLASSES, expr.name)) {\n return ERROR_CLASSES[RS_bound_index(expr.name, ERROR_CLASSES)];\n }\n for (var RS_Index52 = S.classes.length - 1; RS_Index52 > -1; RS_Index52-=1) {\n s = RS_Index52;\n if (has_prop((RS_expr_temp = S.classes)[(typeof s === "number" && s < 0) ? RS_expr_temp.length + s : s], expr.name)) {\n return (RS_expr_temp = (RS_expr_temp = S.classes)[(typeof s === "number" && s < 0) ? RS_expr_temp.length + s : s])[RS_bound_index(expr.name, RS_expr_temp)];\n }\n }\n } else if (is_node_type(expr, AST_Dot)) {\n referenced_path = RS_list_decorate([]);\n while (is_node_type(expr, AST_Dot)) {\n referenced_path.unshift(expr.property);\n expr = expr.expression;\n }\n if (is_node_type(expr, AST_SymbolRef)) {\n referenced_path.unshift(expr.name);\n if (len(referenced_path) > 1) {\n class_name = referenced_path.join(".");\n for (var RS_Index53 = S.classes.length - 1; RS_Index53 > -1; RS_Index53-=1) {\n s = RS_Index53;\n if (has_prop((RS_expr_temp = S.classes)[(typeof s === "number" && s < 0) ? RS_expr_temp.length + s : s], class_name)) {\n return (RS_expr_temp = (RS_expr_temp = S.classes)[(typeof s === "number" && s < 0) ? RS_expr_temp.length + s : s])[(typeof class_name === "number" && class_name < 0) ? RS_expr_temp.length + class_name : class_name];\n }\n }\n }\n }\n }\n return false;\n };\n if (!get_class_in_scope.__argnames__) Object.defineProperties(get_class_in_scope, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "parse"}\n });\n\n function import_error(message) {\n var ctx;\n ctx = S.input.context();\n throw new ImportError(message, ctx.filename, ctx.tokline, ctx.tokcol, ctx.tokpos);\n };\n if (!import_error.__argnames__) Object.defineProperties(import_error, {\n __argnames__ : {value: ["message"]},\n __module__ : {value: "parse"}\n });\n\n function do_import(key) {\n var package_module_id, src_code, filename, modpath, RS_unpack, data, location, cached, srchash, ikey, bitem;\n if (has_prop(imported_modules, key)) {\n return;\n }\n if (has_prop(importing_modules, key) && importing_modules[(typeof key === "number" && key < 0) ? importing_modules.length + key : key]) {\n import_error("Detected a recursive import of: " + key + " while importing: " + module_id);\n }\n package_module_id = key.split(".").slice(0, -1).join(".");\n if (len(package_module_id) > 0) {\n do_import(package_module_id);\n }\n if (options.for_linting) {\n imported_modules[(typeof key === "number" && key < 0) ? imported_modules.length + key : key] = (function(){\n var RS_d = Object.create(null);\n RS_d["is_cached"] = true;\n RS_d["classes"] = Object.create(null);\n RS_d["module_id"] = key;\n RS_d["exports"] = RS_list_decorate([]);\n RS_d["nonlocalvars"] = RS_list_decorate([]);\n RS_d["baselib"] = Object.create(null);\n RS_d["outputs"] = Object.create(null);\n RS_d["discard_asserts"] = options.discard_asserts;\n return RS_d;\n }).call(this);\n return;\n }\n function safe_read(base_path) {\n var RS_unpack, i, path;\n var RS_Iter54 = RS_Iterable(enumerate(RS_list_decorate([ base_path + ".pyj", base_path + "/__init__.pyj" ])));\n for (var RS_Index54 = 0; RS_Index54 < RS_Iter54.length; RS_Index54++) {\n RS_unpack = RS_Iter54[RS_Index54];\n i = RS_unpack[0];\n path = RS_unpack[1];\n try {\n return RS_list_decorate([ readfile(path, "utf-8"), path ]);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n var e = RS_Exception;\n if (e.code === "ENOENT" || e.code === "EPERM" || e.code === "EACCESS") {\n if (i === 1) {\n return [null, null];\n }\n }\n if (i === 1) {\n throw RS_Exception;\n }\n } \n }\n }\n };\n if (!safe_read.__argnames__) Object.defineProperties(safe_read, {\n __argnames__ : {value: ["base_path"]},\n __module__ : {value: "parse"}\n });\n\n src_code = filename = null;\n modpath = key.replace(/\\./g, "/");\n var RS_Iter55 = RS_Iterable(import_dirs);\n for (var RS_Index55 = 0; RS_Index55 < RS_Iter55.length; RS_Index55++) {\n location = RS_Iter55[RS_Index55];\n if (location) {\n RS_unpack = safe_read(location + "/" + modpath);\nRS_unpack = RS_unpack_asarray(2, RS_unpack);\n data = RS_unpack[0];\n filename = RS_unpack[1];\n if (data !== null) {\n src_code = data;\n break;\n }\n }\n }\n if (src_code === null) {\n import_error("Failed Import: \'" + key + "\' module doesn\'t exist in any of the import directories: " + import_dirs.join(":"));\n }\n try {\n cached = JSON.parse(readfile(cache_file_name(filename, options.module_cache_dir), "utf-8"));\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n cached = null;\n } \n }\n srchash = sha1sum(src_code);\n if (cached && cached.version === COMPILER_VERSION && cached.signature === srchash && cached.discard_asserts === !!options.discard_asserts) {\n var RS_Iter56 = RS_Iterable(cached.imported_module_ids);\n for (var RS_Index56 = 0; RS_Index56 < RS_Iter56.length; RS_Index56++) {\n ikey = RS_Iter56[RS_Index56];\n do_import(ikey);\n }\n imported_modules[(typeof key === "number" && key < 0) ? imported_modules.length + key : key] = (function(){\n var RS_d = Object.create(null);\n RS_d["is_cached"] = true;\n RS_d["classes"] = cached.classes;\n RS_d["outputs"] = cached.outputs;\n RS_d["module_id"] = key;\n RS_d["import_order"] = Object.keys(imported_modules).length;\n RS_d["nonlocalvars"] = cached.nonlocalvars;\n RS_d["baselib"] = cached.baselib;\n RS_d["exports"] = cached.exports;\n RS_d["discard_asserts"] = options.discard_asserts;\n RS_d["imported_module_ids"] = cached.imported_module_ids;\n return RS_d;\n }).call(this);\n } else {\n parse(src_code, (function(){\n var RS_d = Object.create(null);\n RS_d["filename"] = filename;\n RS_d["toplevel"] = null;\n RS_d["basedir"] = options.basedir;\n RS_d["libdir"] = options.libdir;\n RS_d["import_dirs"] = options.import_dirs;\n RS_d["module_id"] = key;\n RS_d["imported_modules"] = imported_modules;\n RS_d["importing_modules"] = importing_modules;\n RS_d["discard_asserts"] = options.discard_asserts;\n RS_d["module_cache_dir"] = options.module_cache_dir;\n return RS_d;\n }).call(this));\n }\n imported_modules[(typeof key === "number" && key < 0) ? imported_modules.length + key : key].srchash = srchash;\n var RS_Iter57 = RS_Iterable(Object.keys(imported_modules[(typeof key === "number" && key < 0) ? imported_modules.length + key : key].baselib));\n for (var RS_Index57 = 0; RS_Index57 < RS_Iter57.length; RS_Index57++) {\n bitem = RS_Iter57[RS_Index57];\n baselib_items[(typeof bitem === "number" && bitem < 0) ? baselib_items.length + bitem : bitem] = true;\n }\n };\n if (!do_import.__argnames__) Object.defineProperties(do_import, {\n __argnames__ : {value: ["key"]},\n __module__ : {value: "parse"}\n });\n\n function read_python_flags() {\n var bracketed, name, val;\n expect_token("keyword", "import");\n bracketed = is_("punc", "(");\n if (bracketed) {\n next();\n }\n while (true) {\n if (!is_("name")) {\n croak("Name expected");\n }\n name = S.token.value;\n val = (name.startsWith("no_")) ? false : true;\n if (!val) {\n name = name.slice(3);\n }\n if (!PYTHON_FLAGS) {\n croak("Unknown __python__ flag: " + name);\n }\n S.scoped_flags.set(name, val);\n next();\n if (is_("punc", ",")) {\n next();\n } else {\n if (bracketed) {\n if (is_("punc", ")")) {\n next();\n } else {\n continue;\n }\n }\n break;\n }\n }\n return new AST_EmptyStatement((function(){\n var RS_d = Object.create(null);\n RS_d["stype"] = "scoped_flags";\n RS_d["start"] = prev();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n };\n if (!read_python_flags.__module__) Object.defineProperties(read_python_flags, {\n __module__ : {value: "parse"}\n });\n\n function import_(from_import) {\n var ans, tok, tmp, name, last_tok, key, alias, aimp, RS_unpack, classes, argnames, bracketed, exports, symdef, aname, obj, argvar, cname, imp;\n ans = new AST_Imports((function(){\n var RS_d = Object.create(null);\n RS_d["imports"] = RS_list_decorate([]);\n return RS_d;\n }).call(this));\n while (true) {\n tok = tmp = name = last_tok = expression(false);\n key = "";\n while (is_node_type(tmp, AST_Dot)) {\n key = "." + tmp.property + key;\n tmp = last_tok = tmp.expression;\n }\n key = tmp.name + key;\n if (from_import && key === "__python__") {\n return read_python_flags();\n }\n alias = null;\n if (!from_import && is_("keyword", "as")) {\n next();\n alias = as_symbol(AST_SymbolAlias);\n }\n aimp = new AST_Import((function(){\n var RS_d = Object.create(null);\n RS_d["module"] = name;\n RS_d["key"] = key;\n RS_d["alias"] = alias;\n RS_d["argnames"] = null;\n RS_d["body"] = (function() {\n var RS_anonfunc = function () {\n return imported_modules[(typeof key === "number" && key < 0) ? imported_modules.length + key : key];\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this));\n RS_unpack = [tok.start, last_tok.end];\n aimp.start = RS_unpack[0];\n aimp.end = RS_unpack[1];\n ans.imports.push(aimp);\n if (from_import) {\n break;\n }\n if (is_("punc", ",")) {\n next();\n } else {\n break;\n }\n }\n var RS_Iter58 = RS_Iterable(ans["imports"]);\n for (var RS_Index58 = 0; RS_Index58 < RS_Iter58.length; RS_Index58++) {\n imp = RS_Iter58[RS_Index58];\n do_import(imp.key);\n if (imported_module_ids.indexOf(imp.key) === -1) {\n imported_module_ids.push(imp.key);\n }\n classes = imported_modules[(typeof key === "number" && key < 0) ? imported_modules.length + key : key].classes;\n if (from_import) {\n expect_token("keyword", "import");\n imp.argnames = argnames = RS_list_decorate([]);\n bracketed = is_("punc", "(");\n if (bracketed) {\n next();\n }\n exports = Object.create(null);\n var RS_Iter59 = RS_Iterable(imported_modules[(typeof key === "number" && key < 0) ? imported_modules.length + key : key].exports);\n for (var RS_Index59 = 0; RS_Index59 < RS_Iter59.length; RS_Index59++) {\n symdef = RS_Iter59[RS_Index59];\n exports[RS_bound_index(symdef.name, exports)] = true;\n }\n while (true) {\n aname = as_symbol(AST_ImportedVar);\n if (!options.for_linting && !has_prop(exports, aname.name)) {\n import_error("The symbol \\"" + aname.name + "\\" is not exported from the module: " + key);\n }\n if (is_("keyword", "as")) {\n next();\n aname.alias = as_symbol(AST_SymbolAlias);\n }\n argnames.push(aname);\n if (is_("punc", ",")) {\n next();\n } else {\n if (bracketed) {\n if (is_("punc", ")")) {\n next();\n } else {\n continue;\n }\n }\n break;\n }\n }\n var RS_Iter60 = RS_Iterable(argnames);\n for (var RS_Index60 = 0; RS_Index60 < RS_Iter60.length; RS_Index60++) {\n argvar = RS_Iter60[RS_Index60];\n obj = classes[RS_bound_index(argvar.name, classes)];\n if (obj) {\n key = (argvar.alias) ? argvar.alias.name : argvar.name;\n (RS_expr_temp = (RS_expr_temp = S.classes)[RS_expr_temp.length-1])[(typeof key === "number" && key < 0) ? RS_expr_temp.length + key : key] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = obj.static;\n RS_d["bound"] = obj.bound;\n RS_d["classvars"] = obj.classvars;\n return RS_d;\n }).call(this);\n }\n }\n } else {\n var RS_Iter61 = RS_Iterable(Object.keys(classes));\n for (var RS_Index61 = 0; RS_Index61 < RS_Iter61.length; RS_Index61++) {\n cname = RS_Iter61[RS_Index61];\n obj = classes[(typeof cname === "number" && cname < 0) ? classes.length + cname : cname];\n key = (imp.alias) ? imp.alias.name : imp.key;\n (RS_expr_temp = (RS_expr_temp = S.classes)[RS_expr_temp.length-1])[RS_bound_index(key + "." + obj.name.name, RS_expr_temp)] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = obj.static;\n RS_d["bound"] = obj.bound;\n RS_d["classvars"] = obj.classvars;\n return RS_d;\n }).call(this);\n }\n }\n }\n return ans;\n };\n if (!import_.__argnames__) Object.defineProperties(import_, {\n __argnames__ : {value: ["from_import"]},\n __module__ : {value: "parse"}\n });\n\n function class_() {\n var name, externaldecorator, class_details, bases, class_parent, a, docstrings, definition, descriptor, stmt, class_var_names, visitor;\n name = as_symbol(AST_SymbolDefun);\n if (!name) {\n unexpected();\n }\n externaldecorator = has_simple_decorator(S.decorators, "external");\n class_details = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = Object.create(null);\n RS_d["bound"] = [];\n RS_d["classvars"] = Object.create(null);\n RS_d["processing"] = name.name;\n RS_d["provisional_classvars"] = Object.create(null);\n return RS_d;\n }).call(this);\n bases = [];\n class_parent = null;\n if (is_("punc", "(")) {\n S.in_parenthesized_expr = true;\n next();\n while (true) {\n if (is_("punc", ")")) {\n S.in_parenthesized_expr = false;\n next();\n break;\n }\n a = expr_atom(false);\n if (class_parent === null) {\n class_parent = a;\n }\n bases.push(a);\n if (is_("punc", ",")) {\n next();\n continue;\n }\n }\n }\n docstrings = [];\n definition = new AST_Class((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = name;\n RS_d["docstrings"] = docstrings;\n RS_d["module_id"] = module_id;\n RS_d["dynamic_properties"] = Object.create(null);\n RS_d["parent"] = class_parent;\n RS_d["bases"] = bases;\n RS_d["localvars"] = RS_list_decorate([]);\n RS_d["classvars"] = class_details.classvars;\n RS_d["static"] = class_details.static;\n RS_d["external"] = externaldecorator;\n RS_d["bound"] = class_details.bound;\n RS_d["statements"] = RS_list_decorate([]);\n RS_d["decorators"] = (function() {\n var RS_anonfunc = function () {\n var d, decorator;\n d = RS_list_decorate([]);\n var RS_Iter62 = RS_Iterable(S.decorators);\n for (var RS_Index62 = 0; RS_Index62 < RS_Iter62.length; RS_Index62++) {\n decorator = RS_Iter62[RS_Index62];\n d.push(new AST_Decorator((function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = decorator;\n return RS_d;\n }).call(this)));\n }\n S.decorators = [];\n return d;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })()();\n RS_d["body"] = (function() {\n var RS_anonfunc = function (loop, labels) {\n var a;\n S.in_class.push(name.name);\n (RS_expr_temp = (RS_expr_temp = S.classes)[RS_bound_index(S.classes.length - 1, RS_expr_temp)])[RS_bound_index(name.name, RS_expr_temp)] = class_details;\n S.classes.push(Object.create(null));\n S.scoped_flags.push();\n S.in_function += 1;\n S.in_loop = 0;\n S.labels = RS_list_decorate([]);\n a = block_(docstrings);\n S.in_function -= 1;\n S.scoped_flags.pop();\n S.classes.pop();\n S.in_class.pop();\n S.in_loop = loop;\n S.labels = labels;\n return a;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["loop", "labels"]},\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })()(S.in_loop, S.labels);\n return RS_d;\n }).call(this));\n class_details.processing = false;\n var RS_Iter63 = RS_Iterable(definition.body);\n for (var RS_Index63 = 0; RS_Index63 < RS_Iter63.length; RS_Index63++) {\n stmt = RS_Iter63[RS_Index63];\n if (is_node_type(stmt, AST_Method)) {\n if (stmt.is_getter || stmt.is_setter) {\n descriptor = (RS_expr_temp = definition.dynamic_properties)[RS_bound_index(stmt.name.name, RS_expr_temp)];\n if (!descriptor) {\n descriptor = (RS_expr_temp = definition.dynamic_properties)[RS_bound_index(stmt.name.name, RS_expr_temp)] = Object.create(null);\n }\n descriptor[RS_bound_index((stmt.is_getter) ? "getter" : "setter", descriptor)] = stmt;\n } else if (stmt.name.name === "__init__") {\n definition.init = stmt;\n }\n }\n }\n class_var_names = Object.create(null);\n function walker() {\n function visit_node(node, descend) {\n var varname;\n if (is_node_type(node, AST_Method)) {\n class_var_names[RS_bound_index(node.name.name, class_var_names)] = true;\n return;\n }\n if (is_node_type(node, AST_Function)) {\n return;\n }\n if (is_node_type(node, AST_Assign) && is_node_type(node.left, AST_SymbolRef)) {\n varname = node.left.name;\n if (FORBIDDEN_CLASS_VARS.indexOf(varname) !== -1) {\n token_error(node.left.start, varname + " is not allowed as a class variable name");\n }\n class_var_names[(typeof varname === "number" && varname < 0) ? class_var_names.length + varname : varname] = true;\n (RS_expr_temp = definition.classvars)[(typeof varname === "number" && varname < 0) ? RS_expr_temp.length + varname : varname] = true;\n } else if (is_node_type(node, AST_SymbolRef) && has_prop(class_var_names, node.name)) {\n node.thedef = new AST_SymbolDefun((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = name.name + ".prototype." + node.name;\n return RS_d;\n }).call(this));\n }\n if (descend) {\n descend.call(node);\n }\n };\n if (!visit_node.__argnames__) Object.defineProperties(visit_node, {\n __argnames__ : {value: ["node", "descend"]},\n __module__ : {value: "parse"}\n });\n\n this._visit = visit_node;\n };\n if (!walker.__module__) Object.defineProperties(walker, {\n __module__ : {value: "parse"}\n });\n\n visitor = new walker;\n var RS_Iter64 = RS_Iterable(definition.body);\n for (var RS_Index64 = 0; RS_Index64 < RS_Iter64.length; RS_Index64++) {\n stmt = RS_Iter64[RS_Index64];\n if (!is_node_type(stmt, AST_Class)) {\n stmt.walk(visitor);\n definition.statements.push(stmt);\n }\n }\n return definition;\n };\n if (!class_.__module__) Object.defineProperties(class_, {\n __module__ : {value: "parse"}\n });\n\n function function_(in_class, is_expression) {\n var name, is_anonymous, staticmethod, property_getter, property_setter, staticloc, ctor, return_annotation, is_generator, docstrings, definition, assignments, j, i, nonlocals;\n name = (is_("name")) ? as_symbol((in_class) ? AST_SymbolDefun : AST_SymbolLambda) : null;\n if (in_class && !name) {\n croak("Cannot use anonymous function as class methods");\n }\n is_anonymous = !name;\n staticmethod = property_getter = property_setter = false;\n if (in_class) {\n staticloc = has_simple_decorator(S.decorators, "staticmethod");\n property_getter = has_simple_decorator(S.decorators, "property");\n property_setter = has_setter_decorator(S.decorators, name.name);\n if (staticloc) {\n if (property_getter || property_setter) {\n croak("A method cannot be both static and a property getter/setter");\n }\n (RS_expr_temp = (RS_expr_temp = (RS_expr_temp = S.classes)[RS_bound_index(S.classes.length - 2, RS_expr_temp)])[(typeof in_class === "number" && in_class < 0) ? RS_expr_temp.length + in_class : in_class].static)[RS_bound_index(name.name, RS_expr_temp)] = true;\n staticmethod = true;\n } else if (name.name !== "__init__" && S.scoped_flags.get("bound_methods")) {\n (RS_expr_temp = (RS_expr_temp = S.classes)[RS_bound_index(S.classes.length - 2, RS_expr_temp)])[(typeof in_class === "number" && in_class < 0) ? RS_expr_temp.length + in_class : in_class].bound.push(name.name);\n }\n }\n expect("(");\n S.in_parenthesized_expr = true;\n ctor = (in_class) ? AST_Method : AST_Function;\n return_annotation = null;\n is_generator = [];\n docstrings = [];\n definition = new ctor((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = name;\n RS_d["is_expression"] = is_expression;\n RS_d["is_anonymous"] = is_anonymous;\n RS_d["argnames"] = (function() {\n var RS_anonfunc = function (a) {\n var defaults, first, seen_names, def_line, current_arg_name, name_token;\n defaults = Object.create(null);\n first = true;\n seen_names = Object.create(null);\n def_line = S.input.context().tokline;\n current_arg_name = null;\n name_token = null;\n function get_arg() {\n var name_ctx, ntok, annotation, sym;\n current_arg_name = S.token.value;\n if (has_prop(seen_names, current_arg_name)) {\n token_error(prev(), "Can\'t repeat parameter names");\n }\n if (current_arg_name === "arguments") {\n token_error(prev(), "Can\'t use the name arguments as a parameter name, it is reserved by JavaScript");\n }\n seen_names[(typeof current_arg_name === "number" && current_arg_name < 0) ? seen_names.length + current_arg_name : current_arg_name] = true;\n name_token = S.token;\n name_ctx = S.input.context();\n ntok = peek();\n if (ntok.type === "punc" && ntok.value === ":") {\n next();\n expect(":");\n annotation = maybe_conditional();\n if (!is_token(name_token, "name")) {\n croak("Name expected", name_ctx.tokline);\n return null;\n }\n sym = new AST_SymbolFunarg((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = name_token.value;\n RS_d["start"] = S.token;\n RS_d["end"] = S.token;\n RS_d["annotation"] = annotation;\n return RS_d;\n }).call(this));\n return sym;\n } else {\n if (!is_("name")) {\n if (S.input.context().tokline !== def_line) {\n croak("Name expected", def_line);\n } else {\n croak("Name expected");\n }\n return null;\n }\n sym = new AST_SymbolFunarg((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = current_arg_name;\n RS_d["start"] = S.token;\n RS_d["end"] = S.token;\n RS_d["annotation"] = null;\n return RS_d;\n }).call(this));\n next();\n return sym;\n }\n };\n if (!get_arg.__module__) Object.defineProperties(get_arg, {\n __module__ : {value: "parse"}\n });\n\n while (!is_("punc", ")")) {\n if (first) {\n first = false;\n } else {\n expect(",");\n if (is_("punc", ")")) {\n break;\n }\n }\n if (is_("operator", "**")) {\n next();\n if (a.kwargs) {\n token_error(name_token, "Can\'t define multiple **kwargs in function definition");\n }\n a.kwargs = get_arg();\n } else if (is_("operator", "*")) {\n next();\n if (a.starargs) {\n token_error(name_token, "Can\'t define multiple *args in function definition");\n }\n if (a.kwargs) {\n token_error(name_token, "Can\'t define *args after **kwargs in function definition");\n }\n a.starargs = get_arg();\n } else {\n if (a.starargs || a.kwargs) {\n token_error(name_token, "Can\'t define a formal parameter after *args or **kwargs");\n }\n a.push(get_arg());\n if (is_("operator", "=")) {\n if (a.kwargs) {\n token_error(name_token, "Can\'t define an optional formal parameter after **kwargs");\n }\n next();\n defaults[(typeof current_arg_name === "number" && current_arg_name < 0) ? defaults.length + current_arg_name : current_arg_name] = expression(false);\n a.has_defaults = true;\n } else {\n if (a.has_defaults) {\n token_error(name_token, "Can\'t define required formal parameters after optional formal parameters");\n }\n }\n }\n }\n next();\n if (is_("punc", "->")) {\n next();\n return_annotation = maybe_conditional();\n }\n S.in_parenthesized_expr = false;\n a.defaults = defaults;\n a.is_simple_func = !a.starargs && !a.kwargs && !a.has_defaults;\n return a;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["a"]},\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })()([]);\n RS_d["localvars"] = RS_list_decorate([]);\n RS_d["decorators"] = (function() {\n var RS_anonfunc = function () {\n var d, decorator;\n d = [];\n var RS_Iter65 = RS_Iterable(S.decorators);\n for (var RS_Index65 = 0; RS_Index65 < RS_Iter65.length; RS_Index65++) {\n decorator = RS_Iter65[RS_Index65];\n d.push(new AST_Decorator((function(){\n var RS_d = Object.create(null);\n RS_d["expression"] = decorator;\n return RS_d;\n }).call(this)));\n }\n S.decorators = [];\n return d;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })()();\n RS_d["docstrings"] = docstrings;\n RS_d["body"] = (function() {\n var RS_anonfunc = function (loop, labels) {\n var a;\n S.in_class.push(false);\n S.classes.push(Object.create(null));\n S.scoped_flags.push();\n S.in_function += 1;\n S.functions.push(Object.create(null));\n S.in_loop = 0;\n S.labels = RS_list_decorate([]);\n a = block_(docstrings);\n S.in_function -= 1;\n S.scoped_flags.pop();\n is_generator.push(bool(S.functions.pop().is_generator));\n S.classes.pop();\n S.in_class.pop();\n S.in_loop = loop;\n S.labels = labels;\n return a;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["loop", "labels"]},\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })()(S.in_loop, S.labels);\n return RS_d;\n }).call(this));\n definition.return_annotation = return_annotation;\n definition.is_generator = is_generator[0];\n if (is_node_type(definition, AST_Method)) {\n definition.static = staticmethod;\n definition.is_getter = property_getter;\n definition.is_setter = property_setter;\n if (definition.argnames.length < 1 && !definition.static) {\n croak("Methods of a class must have at least one argument, traditionally named self");\n }\n if (definition.name && definition.name.name === "__init__") {\n if (definition.is_generator) {\n croak("The __init__ method of a class cannot be a generator (yield not allowed)");\n }\n if (property_getter || property_setter) {\n croak("The __init__ method of a class cannot be a property getter/setter");\n }\n }\n }\n if (definition.is_generator) {\n baselib_items["yield"] = true;\n }\n assignments = scan_for_local_vars(definition.body);\n for (var RS_Index66 = 0; RS_Index66 < assignments.length; RS_Index66++) {\n i = RS_Index66;\n for (var RS_Index67 = 0; RS_Index67 < definition.argnames.length + 1; RS_Index67++) {\n j = RS_Index67;\n if (j === definition.argnames.length) {\n definition.localvars.push(new_symbol(AST_SymbolVar, assignments[(typeof i === "number" && i < 0) ? assignments.length + i : i]));\n } else if (j < definition.argnames.length && assignments[(typeof i === "number" && i < 0) ? assignments.length + i : i] === (RS_expr_temp = definition.argnames)[(typeof j === "number" && j < 0) ? RS_expr_temp.length + j : j].name) {\n break;\n }\n }\n }\n nonlocals = scan_for_nonlocal_defs(definition.body);\n nonlocals = (function() {\n var RS_Iter = RS_Iterable(nonlocals), RS_Result = RS_set(), name;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n name = RS_Iter[RS_Index];\n RS_Result.add(name);\n }\n return RS_Result;\n })();\n definition.localvars = definition.localvars.filter((function() {\n var RS_anonfunc = function (v) {\n return !nonlocals.has(v.name);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["v"]},\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })());\n return definition;\n };\n if (!function_.__argnames__) Object.defineProperties(function_, {\n __argnames__ : {value: ["in_class", "is_expression"]},\n __module__ : {value: "parse"}\n });\n\n function if_() {\n var cond, body, belse;\n cond = expression(true);\n body = statement();\n belse = null;\n if (is_("keyword", "elif") || is_("keyword", "else")) {\n if (is_("keyword", "else")) {\n next();\n } else {\n S.token.value = "if";\n }\n belse = statement();\n }\n return new AST_If((function(){\n var RS_d = Object.create(null);\n RS_d["condition"] = cond;\n RS_d["body"] = body;\n RS_d["alternative"] = belse;\n return RS_d;\n }).call(this));\n };\n if (!if_.__module__) Object.defineProperties(if_, {\n __module__ : {value: "parse"}\n });\n\n function is_docstring(stmt) {\n if (is_node_type(stmt, AST_SimpleStatement)) {\n if (is_node_type(stmt.body, AST_String)) {\n return stmt.body;\n }\n }\n return false;\n };\n if (!is_docstring.__argnames__) Object.defineProperties(is_docstring, {\n __argnames__ : {value: ["stmt"]},\n __module__ : {value: "parse"}\n });\n\n function block_(docstrings) {\n var prev_whitespace, a, stmt, ds, current_whitespace;\n prev_whitespace = S.token.leading_whitespace;\n expect(":");\n a = [];\n if (!S.token.nlb) {\n while (!S.token.nlb) {\n if (is_("eof")) {\n unexpected();\n }\n stmt = statement();\n if (docstrings) {\n ds = is_docstring(stmt);\n if (ds) {\n docstrings.push(ds);\n continue;\n }\n }\n a.push(stmt);\n }\n } else {\n current_whitespace = S.token.leading_whitespace;\n if (current_whitespace.length === 0 || prev_whitespace === current_whitespace) {\n croak("Expected an indented block");\n }\n while (!is_("punc", "}")) {\n if (is_("eof")) {\n return a;\n }\n stmt = statement();\n if (docstrings) {\n ds = is_docstring(stmt);\n if (ds) {\n docstrings.push(ds);\n continue;\n }\n }\n a.push(stmt);\n }\n next();\n }\n return a;\n };\n if (!block_.__argnames__) Object.defineProperties(block_, {\n __argnames__ : {value: ["docstrings"]},\n __module__ : {value: "parse"}\n });\n\n function try_() {\n var body, bcatch, bfinally, belse, start, exceptions, name;\n body = block_();\n bcatch = [];\n bfinally = null;\n belse = null;\n while (is_("keyword", "except")) {\n start = S.token;\n next();\n exceptions = RS_list_decorate([]);\n if (!is_("punc", ":") && !is_("keyword", "as")) {\n exceptions.push(as_symbol(AST_SymbolVar));\n while (is_("punc", ",")) {\n next();\n exceptions.push(as_symbol(AST_SymbolVar));\n }\n }\n name = null;\n if (is_("keyword", "as")) {\n next();\n name = as_symbol(AST_SymbolCatch);\n }\n bcatch.push(new AST_Except((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["argname"] = name;\n RS_d["errors"] = exceptions;\n RS_d["body"] = block_();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)));\n }\n if (is_("keyword", "else")) {\n start = S.token;\n next();\n belse = new AST_Else((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["body"] = block_();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n }\n if (is_("keyword", "finally")) {\n start = S.token;\n next();\n bfinally = new AST_Finally((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["body"] = block_();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n }\n if (!bcatch.length && !bfinally) {\n croak("Missing except/finally blocks");\n }\n return new AST_Try((function(){\n var RS_d = Object.create(null);\n RS_d["body"] = body;\n RS_d["bcatch"] = (bcatch.length) ? new AST_Catch((function(){\n var RS_d = Object.create(null);\n RS_d["body"] = bcatch;\n return RS_d;\n }).call(this)) : null;\n RS_d["bfinally"] = bfinally;\n RS_d["belse"] = belse;\n return RS_d;\n }).call(this));\n };\n if (!try_.__module__) Object.defineProperties(try_, {\n __module__ : {value: "parse"}\n });\n\n function vardefs(symbol_class) {\n var a;\n a = RS_list_decorate([]);\n while (true) {\n a.push(new AST_VarDef((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = S.token;\n RS_d["name"] = as_symbol(symbol_class);\n RS_d["value"] = (is_("operator", "=")) ? (next(), expression(false)) : null;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)));\n if (!is_("punc", ",")) {\n break;\n }\n next();\n }\n return a;\n };\n if (!vardefs.__argnames__) Object.defineProperties(vardefs, {\n __argnames__ : {value: ["symbol_class"]},\n __module__ : {value: "parse"}\n });\n\n function nonlocal_(is_global) {\n var defs, vardef;\n defs = vardefs(AST_SymbolNonlocal);\n if (is_global) {\n var RS_Iter68 = RS_Iterable(defs);\n for (var RS_Index68 = 0; RS_Index68 < RS_Iter68.length; RS_Index68++) {\n vardef = RS_Iter68[RS_Index68];\n S.globals.push(vardef.name.name);\n }\n }\n return new AST_Var((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = prev();\n RS_d["definitions"] = defs;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n };\n if (!nonlocal_.__argnames__) Object.defineProperties(nonlocal_, {\n __argnames__ : {value: ["is_global"]},\n __module__ : {value: "parse"}\n });\n\n function new_() {\n var start, newexp, args;\n start = S.token;\n expect_token("operator", "new");\n newexp = expr_atom(false);\n if (is_("punc", "(")) {\n S.in_parenthesized_expr = true;\n next();\n args = func_call_list();\n S.in_parenthesized_expr = false;\n } else {\n args = func_call_list(true);\n }\n return subscripts(new AST_New((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = newexp;\n RS_d["args"] = args;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), true);\n };\n if (!new_.__module__) Object.defineProperties(new_, {\n __module__ : {value: "parse"}\n });\n\n function string_() {\n var strings, start;\n strings = [];\n start = S.token;\n while (true) {\n strings.push(S.token.value);\n if (peek().type !== "string") {\n break;\n }\n next();\n }\n return new AST_String((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["end"] = S.token;\n RS_d["value"] = strings.join("");\n return RS_d;\n }).call(this));\n };\n if (!string_.__module__) Object.defineProperties(string_, {\n __module__ : {value: "parse"}\n });\n\n function token_as_atom_node() {\n var tok, tmp_, tmp__;\n tok = S.token;\n tmp_ = tok.type;\n if (tmp_ === "name") {\n return token_as_symbol(tok, AST_SymbolRef);\n } else if (tmp_ === "num") {\n return new AST_Number((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = tok;\n RS_d["end"] = tok;\n RS_d["value"] = tok.value;\n return RS_d;\n }).call(this));\n } else if (tmp_ === "string") {\n return string_();\n } else if (tmp_ === "regexp") {\n return new AST_RegExp((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = tok;\n RS_d["end"] = tok;\n RS_d["value"] = tok.value;\n return RS_d;\n }).call(this));\n } else if (tmp_ === "atom") {\n tmp__ = tok.value;\n if (tmp__ === "False") {\n return new AST_False((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = tok;\n RS_d["end"] = tok;\n return RS_d;\n }).call(this));\n } else if (tmp__ === "True") {\n return new AST_True((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = tok;\n RS_d["end"] = tok;\n return RS_d;\n }).call(this));\n } else if (tmp__ === "None") {\n return new AST_Null((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = tok;\n RS_d["end"] = tok;\n return RS_d;\n }).call(this));\n }\n } else if (tmp_ === "js") {\n return new AST_Verbatim((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = tok;\n RS_d["end"] = tok;\n RS_d["value"] = tok.value;\n return RS_d;\n }).call(this));\n }\n token_error(tok, "Expecting an atomic token (number/string/bool/regexp/js/None)");\n };\n if (!token_as_atom_node.__module__) Object.defineProperties(token_as_atom_node, {\n __module__ : {value: "parse"}\n });\n\n function as_atom_node() {\n var ret;\n ret = token_as_atom_node();\n next();\n return ret;\n };\n if (!as_atom_node.__module__) Object.defineProperties(as_atom_node, {\n __module__ : {value: "parse"}\n });\n\n function expr_atom(allow_calls) {\n var start, tmp_, ex, ret, cls, func;\n if (is_("operator", "new")) {\n return new_();\n }\n start = S.token;\n if (is_("punc")) {\n tmp_ = start.value;\n if (tmp_ === "(") {\n S.in_parenthesized_expr = true;\n next();\n if (is_("punc", ")")) {\n next();\n return new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = RS_list_decorate([]);\n return RS_d;\n }).call(this));\n }\n ex = expression(true);\n if (is_("keyword", "for")) {\n ret = read_comprehension(new AST_GeneratorComprehension((function(){\n var RS_d = Object.create(null);\n RS_d["statement"] = ex;\n return RS_d;\n }).call(this)), ")");\n S.in_parenthesized_expr = false;\n return ret;\n }\n ex.start = start;\n ex.end = S.token;\n if (is_node_type(ex, AST_SymbolRef)) {\n ex.parens = true;\n }\n if (!is_node_type(ex, AST_GeneratorComprehension)) {\n expect(")");\n }\n if (is_node_type(ex, AST_UnaryPrefix)) {\n ex.parenthesized = true;\n }\n S.in_parenthesized_expr = false;\n return subscripts(ex, allow_calls);\n } else if (tmp_ === "[") {\n return subscripts(array_(), allow_calls);\n } else if (tmp_ === "{") {\n return subscripts(object_(), allow_calls);\n }\n unexpected();\n }\n if (is_("keyword", "class")) {\n next();\n cls = class_();\n cls.start = start;\n cls.end = prev();\n return subscripts(cls, allow_calls);\n }\n if (is_("keyword", "def")) {\n next();\n func = function_(false, true);\n func.start = start;\n func.end = prev();\n return subscripts(func, allow_calls);\n }\n if (is_("keyword", "yield")) {\n next();\n return yield_();\n }\n if (ATOMIC_START_TOKEN[RS_bound_index(S.token.type, ATOMIC_START_TOKEN)]) {\n return subscripts(as_atom_node(), allow_calls);\n }\n unexpected();\n };\n if (!expr_atom.__argnames__) Object.defineProperties(expr_atom, {\n __argnames__ : {value: ["allow_calls"]},\n __module__ : {value: "parse"}\n });\n\n function expr_list(closing, allow_trailing_comma, allow_empty, func_call) {\n var first, a, saw_starargs, tmp, arg;\n first = true;\n a = RS_list_decorate([]);\n saw_starargs = false;\n while (!is_("punc", closing)) {\n if (saw_starargs) {\n token_error(prev(), "*args must be the last argument in a function call");\n }\n if (first) {\n first = false;\n } else {\n expect(",");\n }\n if (allow_trailing_comma && is_("punc", closing)) {\n break;\n }\n if (is_("operator", "*") && func_call) {\n saw_starargs = true;\n next();\n }\n if (is_("punc", ",") && allow_empty) {\n a.push(new AST_Hole((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = S.token;\n RS_d["end"] = S.token;\n return RS_d;\n }).call(this)));\n } else {\n a.push(expression(false));\n }\n }\n if (func_call) {\n tmp = RS_list_decorate([]);\n tmp.kwargs = RS_list_decorate([]);\n var RS_Iter69 = RS_Iterable(a);\n for (var RS_Index69 = 0; RS_Index69 < RS_Iter69.length; RS_Index69++) {\n arg = RS_Iter69[RS_Index69];\n if (is_node_type(arg, AST_Assign)) {\n tmp.kwargs.push(RS_list_decorate([ arg.left, arg.right ]));\n } else {\n tmp.push(arg);\n }\n }\n a = tmp;\n }\n next();\n if (saw_starargs) {\n a.starargs = true;\n }\n return a;\n };\n if (!expr_list.__argnames__) Object.defineProperties(expr_list, {\n __argnames__ : {value: ["closing", "allow_trailing_comma", "allow_empty", "func_call"]},\n __module__ : {value: "parse"}\n });\n\n function func_call_list(empty) {\n var a, first, single_comprehension, arg;\n a = [];\n first = true;\n a.kwargs = [];\n a.kwarg_items = [];\n a.starargs = false;\n if (empty) {\n return a;\n }\n single_comprehension = false;\n while (!is_("punc", ")") && !is_("eof")) {\n if (!first) {\n expect(",");\n if (is_("punc", ")")) {\n break;\n }\n }\n if (is_("operator", "*")) {\n next();\n arg = expression(false);\n arg.is_array = true;\n a.push(arg);\n a.starargs = true;\n } else if (is_("operator", "**")) {\n next();\n a.kwarg_items.push(as_symbol(AST_SymbolRef, false));\n a.starargs = true;\n } else {\n arg = expression(false);\n if (is_node_type(arg, AST_Assign)) {\n a.kwargs.push(RS_list_decorate([ arg.left, arg.right ]));\n } else {\n if (is_("keyword", "for")) {\n if (!first) {\n croak("Generator expression must be parenthesized if not sole argument");\n }\n a.push(read_comprehension(new AST_GeneratorComprehension((function(){\n var RS_d = Object.create(null);\n RS_d["statement"] = arg;\n return RS_d;\n }).call(this)), ")"));\n single_comprehension = true;\n break;\n }\n a.push(arg);\n }\n }\n first = false;\n }\n if (!single_comprehension) {\n next();\n }\n return a;\n };\n if (!func_call_list.__argnames__) Object.defineProperties(func_call_list, {\n __argnames__ : {value: ["empty"]},\n __module__ : {value: "parse"}\n });\n\n \n var array_ = embed_tokens((function() {\n var RS_anonfunc = function array_() {\n var expr;\n expect("[");\n expr = RS_list_decorate([]);\n if (!is_("punc", "]")) {\n expr.push(expression(false));\n if (is_("keyword", "for")) {\n return read_comprehension(new AST_ListComprehension((function(){\n var RS_d = Object.create(null);\n RS_d["statement"] = expr[0];\n return RS_d;\n }).call(this)), "]");\n }\n if (!is_("punc", "]")) {\n expect(",");\n }\n }\n return new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = expr.concat(expr_list("]", true, true));\n return RS_d;\n }).call(this));\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })());\n\n \n var object_ = embed_tokens((function() {\n var RS_anonfunc = function object_() {\n var first, has_non_const_keys, is_pydict, is_jshash, a, start, ctx, orig, left, end;\n expect("{");\n first = true;\n has_non_const_keys = false;\n is_pydict = S.scoped_flags.get("dict_literals", false);\n is_jshash = S.scoped_flags.get("hash_literals", false);\n a = RS_list_decorate([]);\n while (!is_("punc", "}")) {\n if (!first) {\n expect(",");\n }\n if (is_("punc", "}")) {\n break;\n }\n first = false;\n start = S.token;\n ctx = S.input.context();\n orig = ctx.expecting_object_literal_key;\n ctx.expecting_object_literal_key = true;\n try {\n left = expression(false);\n } finally {\n ctx.expecting_object_literal_key = orig;\n }\n if (is_("keyword", "for")) {\n return read_comprehension(new AST_SetComprehension((function(){\n var RS_d = Object.create(null);\n RS_d["statement"] = left;\n return RS_d;\n }).call(this)), "}");\n }\n if (a.length === 0 && (is_("punc", ",") || is_("punc", "}"))) {\n end = prev();\n return set_(start, end, left);\n }\n if (!is_node_type(left, AST_Constant)) {\n has_non_const_keys = true;\n }\n expect(":");\n a.push(new AST_ObjectKeyVal((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["key"] = left;\n RS_d["value"] = expression(false);\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)));\n if (a.length === 1 && is_("keyword", "for")) {\n return dict_comprehension(a, is_pydict, is_jshash);\n }\n }\n next();\n return new ((has_non_const_keys) ? AST_ExpressiveObject : AST_Object)((function(){\n var RS_d = Object.create(null);\n RS_d["properties"] = a;\n RS_d["is_pydict"] = is_pydict;\n RS_d["is_jshash"] = is_jshash;\n return RS_d;\n }).call(this));\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })());\n\n function set_(start, end, expr) {\n var ostart, a;\n ostart = start;\n a = RS_list_decorate([ new AST_SetItem((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["end"] = end;\n RS_d["value"] = expr;\n return RS_d;\n }).call(this)) ]);\n while (!is_("punc", "}")) {\n expect(",");\n start = S.token;\n if (is_("punc", "}")) {\n break;\n }\n a.push(new AST_SetItem((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["value"] = expression(false);\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)));\n }\n next();\n return new AST_Set((function(){\n var RS_d = Object.create(null);\n RS_d["items"] = a;\n RS_d["start"] = ostart;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n };\n if (!set_.__argnames__) Object.defineProperties(set_, {\n __argnames__ : {value: ["start", "end", "expr"]},\n __module__ : {value: "parse"}\n });\n\n function read_comprehension(obj, terminator) {\n var forloop;\n if (is_node_type(obj, AST_GeneratorComprehension)) {\n baselib_items["yield"] = true;\n }\n S.in_comprehension = true;\n S.in_parenthesized_expr = false;\n expect_token("keyword", "for");\n forloop = for_(true);\n obj.init = forloop.init;\n obj.name = forloop.name;\n obj.object = forloop.object;\n obj.condition = (is_("punc", terminator)) ? null : (expect_token("keyword", "if"), \n expression(true));\n expect(terminator);\n S.in_comprehension = false;\n return obj;\n };\n if (!read_comprehension.__argnames__) Object.defineProperties(read_comprehension, {\n __argnames__ : {value: ["obj", "terminator"]},\n __module__ : {value: "parse"}\n });\n\n function dict_comprehension(a, is_pydict, is_jshash) {\n var RS_unpack, left, right;\n if (a.length) {\n RS_unpack = [a[0].key, a[0].value];\n left = RS_unpack[0];\n right = RS_unpack[1];\n } else {\n left = expression(false);\n if (!is_("punc", ":")) {\n return read_comprehension(new AST_SetComprehension((function(){\n var RS_d = Object.create(null);\n RS_d["statement"] = left;\n return RS_d;\n }).call(this)), "}");\n }\n expect(":");\n right = expression(false);\n }\n return read_comprehension(new AST_DictComprehension((function(){\n var RS_d = Object.create(null);\n RS_d["statement"] = left;\n RS_d["value_statement"] = right;\n RS_d["is_pydict"] = is_pydict;\n RS_d["is_jshash"] = is_jshash;\n return RS_d;\n }).call(this)), "}");\n };\n if (!dict_comprehension.__argnames__) Object.defineProperties(dict_comprehension, {\n __argnames__ : {value: ["a", "is_pydict", "is_jshash"]},\n __module__ : {value: "parse"}\n });\n\n function as_name() {\n var tmp, tmp_;\n tmp = S.token;\n next();\n tmp_ = tmp.type;\n if (tmp_ === "name" || tmp_ === "operator" || tmp_ === "keyword" || tmp_ === "atom") {\n return tmp.value;\n } else {\n unexpected();\n }\n };\n if (!as_name.__module__) Object.defineProperties(as_name, {\n __module__ : {value: "parse"}\n });\n\n function token_as_symbol(tok, ttype) {\n var name;\n name = tok.value;\n if (RESERVED_WORDS[(typeof name === "number" && name < 0) ? RESERVED_WORDS.length + name : name] && name !== "this") {\n croak(name + " is a reserved word");\n }\n return new ((name === "this") ? AST_This : ttype)((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = String(tok.value);\n RS_d["start"] = tok;\n RS_d["end"] = tok;\n return RS_d;\n }).call(this));\n };\n if (!token_as_symbol.__argnames__) Object.defineProperties(token_as_symbol, {\n __argnames__ : {value: ["tok", "ttype"]},\n __module__ : {value: "parse"}\n });\n\n function as_symbol(ttype, noerror) {\n var sym;\n if (!is_("name")) {\n if (!noerror) {\n croak("Name expected");\n }\n return null;\n }\n sym = token_as_symbol(S.token, ttype);\n next();\n return sym;\n };\n if (!as_symbol.__argnames__) Object.defineProperties(as_symbol, {\n __argnames__ : {value: ["ttype", "noerror"]},\n __module__ : {value: "parse"}\n });\n\n function new_symbol(type, name) {\n var sym;\n sym = new ((name === "this") ? AST_This : type)((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = String(name);\n RS_d["start"] = null;\n RS_d["end"] = null;\n return RS_d;\n }).call(this));\n return sym;\n };\n if (!new_symbol.__argnames__) Object.defineProperties(new_symbol, {\n __argnames__ : {value: ["type", "name"]},\n __module__ : {value: "parse"}\n });\n\n function is_static_method(cls, method) {\n if (has_prop(COMMON_STATIC, method) || cls.static && has_prop(cls.static, method)) {\n return true;\n } else {\n return false;\n }\n };\n if (!is_static_method.__argnames__) Object.defineProperties(is_static_method, {\n __argnames__ : {value: ["cls", "method"]},\n __module__ : {value: "parse"}\n });\n\n function getitem(expr, allow_calls) {\n var start, is_py_sub, slice_bounds, is_slice, i, assignment;\n start = expr.start;\n next();\n is_py_sub = S.scoped_flags.get("overload_getitem", false);\n slice_bounds = [];\n is_slice = false;\n if (is_("punc", ":")) {\n slice_bounds.push(null);\n } else {\n slice_bounds.push(expression(false));\n }\n if (is_("punc", ":")) {\n is_slice = true;\n next();\n if (is_("punc", ":")) {\n slice_bounds.push(null);\n } else if (!is_("punc", "]")) {\n slice_bounds.push(expression(false));\n }\n }\n if (is_("punc", ":")) {\n next();\n if (is_("punc", "]")) {\n unexpected();\n } else {\n slice_bounds.push(expression(false));\n }\n }\n expect("]");\n if (is_slice) {\n if (is_("operator", "=")) {\n next();\n return subscripts(new AST_Splice((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = expr;\n RS_d["property"] = slice_bounds[0] || new AST_Number((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = 0;\n return RS_d;\n }).call(this));\n RS_d["property2"] = slice_bounds[1];\n RS_d["assignment"] = expression(true);\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), allow_calls);\n } else if (slice_bounds.length === 3) {\n slice_bounds.unshift(slice_bounds.pop());\n if (!slice_bounds[slice_bounds.length-1]) {\n slice_bounds.pop();\n if (!slice_bounds[slice_bounds.length-1]) {\n slice_bounds.pop();\n }\n } else if (!slice_bounds[slice_bounds.length-2]) {\n slice_bounds[slice_bounds.length-2] = new AST_Undefined;\n }\n return subscripts(new AST_Call((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = new AST_SymbolRef((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = (S.in_delete) ? "RS_delslice" : "RS_eslice";\n return RS_d;\n }).call(this));\n RS_d["args"] = RS_list_decorate([ expr ]).concat(slice_bounds);\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), allow_calls);\n } else {\n slice_bounds = (function() {\n var RS_Iter = RS_Iterable(slice_bounds), RS_Result = [], i;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n i = RS_Iter[RS_Index];\n RS_Result.push((i === null) ? new AST_Number((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = 0;\n return RS_d;\n }).call(this)) : i);\n }\n RS_Result = RS_list_constructor(RS_Result);\n return RS_Result;\n })();\n if (S.in_delete) {\n return subscripts(new AST_Call((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = new AST_SymbolRef((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "RS_delslice";\n return RS_d;\n }).call(this));\n RS_d["args"] = RS_list_decorate([ expr, new AST_Number((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = 1;\n return RS_d;\n }).call(this)) ]).concat(slice_bounds);\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), allow_calls);\n }\n return subscripts(new AST_Call((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = new AST_Dot((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = expr;\n RS_d["property"] = "slice";\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n RS_d["args"] = slice_bounds;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), allow_calls);\n }\n } else {\n if (is_py_sub) {\n assignment = null;\n if (is_("operator") && S.token.value === "=") {\n next();\n assignment = expression(true);\n }\n return subscripts(new AST_ItemAccess((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = expr;\n RS_d["property"] = slice_bounds[0] || new AST_Number((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = 0;\n return RS_d;\n }).call(this));\n RS_d["assignment"] = assignment;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), allow_calls);\n }\n return subscripts(new AST_Sub((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = expr;\n RS_d["property"] = slice_bounds[0] || new AST_Number((function(){\n var RS_d = Object.create(null);\n RS_d["value"] = 0;\n return RS_d;\n }).call(this));\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), allow_calls);\n }\n };\n if (!getitem.__argnames__) Object.defineProperties(getitem, {\n __argnames__ : {value: ["expr", "allow_calls"]},\n __module__ : {value: "parse"}\n });\n\n function call_(expr) {\n var start, ret, c, funcname, tmp_, args;\n start = expr.start;\n S.in_parenthesized_expr = true;\n next();\n if (!expr.parens && get_class_in_scope(expr)) {\n ret = subscripts(new AST_New((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = expr;\n RS_d["args"] = func_call_list();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), true);\n S.in_parenthesized_expr = false;\n return ret;\n } else {\n if (is_node_type(expr, AST_Dot)) {\n c = get_class_in_scope(expr.expression);\n }\n if (c) {\n funcname = expr;\n ret = subscripts(new AST_ClassCall((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["class"] = expr.expression;\n RS_d["method"] = funcname.property;\n RS_d["static"] = is_static_method(c, funcname.property);\n RS_d["args"] = func_call_list();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), true);\n S.in_parenthesized_expr = false;\n return ret;\n } else if (is_node_type(expr, AST_SymbolRef)) {\n tmp_ = expr.name;\n if (tmp_ === "jstype") {\n ret = new AST_UnaryPrefix((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["operator"] = "typeof";\n RS_d["expression"] = func_call_list()[0];\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n S.in_parenthesized_expr = false;\n return ret;\n } else if (tmp_ === "isinstance") {\n args = func_call_list();\n if (args.length !== 2) {\n croak("isinstance() must be called with exactly two arguments");\n }\n ret = new AST_Binary((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["left"] = args[0];\n RS_d["operator"] = "instanceof";\n RS_d["right"] = args[1];\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n S.in_parenthesized_expr = false;\n return ret;\n }\n }\n ret = subscripts(new AST_Call((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["expression"] = expr;\n RS_d["args"] = func_call_list();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), true);\n S.in_parenthesized_expr = false;\n return ret;\n }\n };\n if (!call_.__argnames__) Object.defineProperties(call_, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "parse"}\n });\n\n function get_attr(expr, allow_calls) {\n var prop, c, classvars;\n next();\n prop = as_name();\n c = get_class_in_scope(expr);\n if (c) {\n classvars = (c.processing) ? c.provisional_classvars : c.classvars;\n if (classvars && classvars[prop]) {\n prop = "prototype." + prop;\n }\n }\n return subscripts(new AST_Dot((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = expr.start;\n RS_d["expression"] = expr;\n RS_d["property"] = prop;\n RS_d["end"] = prev();\n return RS_d;\n }).call(this)), allow_calls);\n };\n if (!get_attr.__argnames__) Object.defineProperties(get_attr, {\n __argnames__ : {value: ["expr", "allow_calls"]},\n __module__ : {value: "parse"}\n });\n\n function existential(expr, allow_calls) {\n var ans, ttype, val, is_py_sub;\n ans = new AST_Existential((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = expr.start;\n RS_d["end"] = S.token;\n RS_d["expression"] = expr;\n return RS_d;\n }).call(this));\n next();\n ttype = S.token.type;\n val = S.token.value;\n if (S.token.nlb || ttype === "keyword" || ttype === "operator" || ttype === "eof") {\n ans.after = null;\n return ans;\n }\n if (ttype === "punc") {\n if (val === ".") {\n ans.after = ".";\n } else if (val === "[") {\n is_py_sub = S.scoped_flags.get("overload_getitem", false);\n ans.after = (is_py_sub) ? "g" : "[";\n } else if (val === "(") {\n if (!allow_calls) {\n unexpected();\n }\n ans.after = "(";\n } else {\n ans.after = null;\n return ans;\n }\n return subscripts(ans, allow_calls);\n }\n ans.after = expression();\n return ans;\n };\n if (!existential.__argnames__) Object.defineProperties(existential, {\n __argnames__ : {value: ["expr", "allow_calls"]},\n __module__ : {value: "parse"}\n });\n\n function subscripts(expr, allow_calls) {\n if (is_("punc", ".")) {\n return get_attr(expr, allow_calls);\n }\n if (is_("punc", "[") && !S.token.nlb) {\n return getitem(expr, allow_calls);\n }\n if (allow_calls && is_("punc", "(") && !S.token.nlb) {\n return call_(expr);\n }\n if (is_("punc", "?")) {\n return existential(expr, allow_calls);\n }\n return expr;\n };\n if (!subscripts.__argnames__) Object.defineProperties(subscripts, {\n __argnames__ : {value: ["expr", "allow_calls"]},\n __module__ : {value: "parse"}\n });\n\n function maybe_unary(allow_calls) {\n var start, expr, is_parenthesized, ex, val;\n start = S.token;\n if (is_("operator", "@")) {\n if (S.parsing_decorator) {\n croak("Nested decorators are not allowed");\n }\n next();\n S.parsing_decorator = true;\n expr = expression();\n S.parsing_decorator = false;\n S.decorators.push(expr);\n return new AST_EmptyStatement((function(){\n var RS_d = Object.create(null);\n RS_d["stype"] = "@";\n RS_d["start"] = prev();\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n }\n if (is_("operator") && UNARY_PREFIX[RS_bound_index(start.value, UNARY_PREFIX)]) {\n next();\n is_parenthesized = is_("punc", "(");\n S.in_delete = start.value === "delete";\n expr = maybe_unary(allow_calls);\n S.in_delete = false;\n ex = make_unary(AST_UnaryPrefix, start.value, expr, is_parenthesized);\n ex.start = start;\n ex.end = prev();\n return ex;\n }\n val = expr_atom(allow_calls);\n return val;\n };\n if (!maybe_unary.__argnames__) Object.defineProperties(maybe_unary, {\n __argnames__ : {value: ["allow_calls"]},\n __module__ : {value: "parse"}\n });\n\n function make_unary(ctor, op, expr, is_parenthesized) {\n return new ctor((function(){\n var RS_d = Object.create(null);\n RS_d["operator"] = op;\n RS_d["expression"] = expr;\n RS_d["parenthesized"] = is_parenthesized;\n return RS_d;\n }).call(this));\n };\n if (!make_unary.__argnames__) Object.defineProperties(make_unary, {\n __argnames__ : {value: ["ctor", "op", "expr", "is_parenthesized"]},\n __module__ : {value: "parse"}\n });\n\n function expr_op(left, min_prec, no_in) {\n var op, prec, right, ret;\n op = (is_("operator")) ? S.token.value : null;\n if (op === "!" && peek().type === "operator" && peek().value === "in") {\n next();\n S.token.value = op = "nin";\n }\n if (no_in && (op === "in" || op === "nin")) {\n op = null;\n }\n prec = (op !== null) ? PRECEDENCE[(typeof op === "number" && op < 0) ? PRECEDENCE.length + op : op] : null;\n if (prec !== null && prec > min_prec) {\n next();\n right = expr_op(maybe_unary(true), prec, no_in);\n ret = new AST_Binary((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = left.start;\n RS_d["left"] = left;\n RS_d["operator"] = op;\n RS_d["right"] = right;\n RS_d["end"] = right.end;\n return RS_d;\n }).call(this));\n return expr_op(ret, min_prec, no_in);\n }\n return left;\n };\n if (!expr_op.__argnames__) Object.defineProperties(expr_op, {\n __argnames__ : {value: ["left", "min_prec", "no_in"]},\n __module__ : {value: "parse"}\n });\n\n function expr_ops(no_in) {\n return expr_op(maybe_unary(true), 0, no_in);\n };\n if (!expr_ops.__argnames__) Object.defineProperties(expr_ops, {\n __argnames__ : {value: ["no_in"]},\n __module__ : {value: "parse"}\n });\n\n function maybe_conditional(no_in) {\n var start, expr, ne, conditional;\n start = S.token;\n expr = expr_ops(no_in);\n if (is_("keyword", "if") && (S.in_parenthesized_expr || S.statement_starting_token !== S.token && !S.in_comprehension && !S.token.nlb)) {\n next();\n ne = expression(false);\n expect_token("keyword", "else");\n conditional = new AST_Conditional((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["condition"] = ne;\n RS_d["consequent"] = expr;\n RS_d["alternative"] = expression(false, no_in);\n RS_d["end"] = peek();\n return RS_d;\n }).call(this));\n return conditional;\n }\n return expr;\n };\n if (!maybe_conditional.__argnames__) Object.defineProperties(maybe_conditional, {\n __argnames__ : {value: ["no_in"]},\n __module__ : {value: "parse"}\n });\n\n function create_assign(data) {\n var ans, class_name, c, lhs;\n if (data.right && is_node_type(data.right, AST_Seq) && (is_node_type(data.right.car, AST_Assign) || is_node_type(data.right.cdr, AST_Assign)) && data.operator !== "=") {\n token_error(data.start, "Invalid assignment operator for chained assignment: " + data.operator);\n }\n ans = new AST_Assign(data);\n if (S.in_class.length && (RS_expr_temp = S.in_class)[RS_expr_temp.length-1]) {\n class_name = (RS_expr_temp = S.in_class)[RS_expr_temp.length-1];\n if (is_node_type(ans.left, AST_SymbolRef) && S.classes.length > 1) {\n c = (RS_expr_temp = (RS_expr_temp = S.classes)[RS_expr_temp.length-2])[(typeof class_name === "number" && class_name < 0) ? RS_expr_temp.length + class_name : class_name];\n if (c) {\n if (ans.is_chained()) {\n var RS_Iter70 = RS_Iterable(ans.traverse_chain()[0]);\n for (var RS_Index70 = 0; RS_Index70 < RS_Iter70.length; RS_Index70++) {\n lhs = RS_Iter70[RS_Index70];\n (RS_expr_temp = c.provisional_classvars)[RS_bound_index(lhs.name, RS_expr_temp)] = true;\n }\n } else {\n (RS_expr_temp = c.provisional_classvars)[RS_bound_index(ans.left.name, RS_expr_temp)] = true;\n }\n }\n }\n }\n return ans;\n };\n if (!create_assign.__argnames__) Object.defineProperties(create_assign, {\n __argnames__ : {value: ["data"]},\n __module__ : {value: "parse"}\n });\n\n function maybe_assign(no_in, only_plain_assignment) {\n var start, left, val;\n start = S.token;\n left = maybe_conditional(no_in);\n val = S.token.value;\n if (is_("operator") && ASSIGNMENT[(typeof val === "number" && val < 0) ? ASSIGNMENT.length + val : val]) {\n if (only_plain_assignment && val !== "=") {\n croak("Invalid assignment operator for chained assignment: " + val);\n }\n next();\n return create_assign((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["left"] = left;\n RS_d["operator"] = val;\n RS_d["right"] = maybe_assign(no_in, true);\n RS_d["end"] = prev();\n return RS_d;\n }).call(this));\n }\n return left;\n };\n if (!maybe_assign.__argnames__) Object.defineProperties(maybe_assign, {\n __argnames__ : {value: ["no_in", "only_plain_assignment"]},\n __module__ : {value: "parse"}\n });\n\n function expression(commas, no_in) {\n var start, expr, left;\n start = S.token;\n expr = maybe_assign(no_in);\n function build_seq(a) {\n if (a.length === 1) {\n return a[0];\n }\n return new AST_Seq((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["car"] = a.shift();\n RS_d["cdr"] = build_seq(a);\n RS_d["end"] = peek();\n return RS_d;\n }).call(this));\n };\n if (!build_seq.__argnames__) Object.defineProperties(build_seq, {\n __argnames__ : {value: ["a"]},\n __module__ : {value: "parse"}\n });\n\n if (commas) {\n left = [ expr ];\n while (is_("punc", ",") && !peek().nlb) {\n next();\n if (is_node_type(expr, AST_Assign)) {\n left[left.length-1] = left[left.length-1].left;\n return create_assign((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["left"] = (left.length === 1) ? left[0] : new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = left;\n return RS_d;\n }).call(this));\n RS_d["operator"] = expr.operator;\n RS_d["right"] = new AST_Seq((function(){\n var RS_d = Object.create(null);\n RS_d["car"] = expr.right;\n RS_d["cdr"] = expression(true, no_in);\n return RS_d;\n }).call(this));\n RS_d["end"] = peek();\n return RS_d;\n }).call(this));\n }\n expr = maybe_assign(no_in);\n left.push(expr);\n }\n if (left.length > 1 && is_node_type(left[left.length-1], AST_Assign)) {\n left[left.length-1] = left[left.length-1].left;\n return create_assign((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["left"] = new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = left;\n return RS_d;\n }).call(this));\n RS_d["operator"] = expr.operator;\n RS_d["right"] = expr.right;\n RS_d["end"] = peek();\n return RS_d;\n }).call(this));\n }\n return build_seq(left);\n }\n return expr;\n };\n if (!expression.__argnames__) Object.defineProperties(expression, {\n __argnames__ : {value: ["commas", "no_in"]},\n __module__ : {value: "parse"}\n });\n\n function in_loop(cont) {\n var ret;\n S.in_loop += 1;\n ret = cont();\n S.in_loop -= 1;\n return ret;\n };\n if (!in_loop.__argnames__) Object.defineProperties(in_loop, {\n __argnames__ : {value: ["cont"]},\n __module__ : {value: "parse"}\n });\n\n function run_parser() {\n var start, body, docstrings, first_token, toplevel, element, shebang, ds, end, seen_exports, item;\n start = S.token = next();\n body = [];\n docstrings = [];\n first_token = true;\n toplevel = options.toplevel;\n while (!is_("eof")) {\n element = statement();\n if (first_token && is_node_type(element, AST_Directive) && element.value.indexOf("#!") === 0) {\n shebang = element.value;\n } else {\n ds = !toplevel && is_docstring(element);\n if (ds) {\n docstrings.push(ds);\n } else {\n body.push(element);\n }\n }\n first_token = false;\n }\n end = prev();\n if (toplevel) {\n toplevel.body = toplevel.body.concat(body);\n toplevel.end = end;\n toplevel.docstrings;\n } else {\n toplevel = new AST_Toplevel((function(){\n var RS_d = Object.create(null);\n RS_d["start"] = start;\n RS_d["body"] = body;\n RS_d["shebang"] = shebang;\n RS_d["end"] = end;\n RS_d["docstrings"] = docstrings;\n return RS_d;\n }).call(this));\n }\n toplevel.nonlocalvars = scan_for_nonlocal_defs(toplevel.body).concat(S.globals);\n toplevel.localvars = RS_list_decorate([]);\n toplevel.exports = RS_list_decorate([]);\n seen_exports = Object.create(null);\n function add_item(item, isvar) {\n var symbol;\n if (toplevel.nonlocalvars.indexOf(item) < 0) {\n symbol = new_symbol(AST_SymbolVar, item);\n if (isvar) {\n toplevel.localvars.push(symbol);\n }\n if (!has_prop(seen_exports, item)) {\n toplevel.exports.push(symbol);\n seen_exports[(typeof item === "number" && item < 0) ? seen_exports.length + item : item] = true;\n }\n }\n };\n if (!add_item.__argnames__) Object.defineProperties(add_item, {\n __argnames__ : {value: ["item", "isvar"]},\n __module__ : {value: "parse"}\n });\n\n var RS_Iter71 = RS_Iterable(scan_for_local_vars(toplevel.body));\n for (var RS_Index71 = 0; RS_Index71 < RS_Iter71.length; RS_Index71++) {\n item = RS_Iter71[RS_Index71];\n add_item(item, true);\n }\n var RS_Iter72 = RS_Iterable(scan_for_top_level_callables(toplevel.body));\n for (var RS_Index72 = 0; RS_Index72 < RS_Iter72.length; RS_Index72++) {\n item = RS_Iter72[RS_Index72];\n add_item(item, false);\n }\n toplevel.filename = options.filename;\n toplevel.imported_module_ids = imported_module_ids;\n toplevel.classes = scan_for_classes(toplevel.body);\n toplevel.import_order = Object.keys(imported_modules).length;\n toplevel.module_id = module_id;\n imported_modules[(typeof module_id === "number" && module_id < 0) ? imported_modules.length + module_id : module_id] = toplevel;\n toplevel.imports = imported_modules;\n toplevel.baselib = baselib_items;\n toplevel.scoped_flags = S.scoped_flags.stack[0];\n importing_modules[(typeof module_id === "number" && module_id < 0) ? importing_modules.length + module_id : module_id] = false;\n toplevel.comments_after = S.token.comments_before || [];\n return toplevel;\n };\n if (!run_parser.__module__) Object.defineProperties(run_parser, {\n __module__ : {value: "parse"}\n });\n\n return run_parser;\n };\n if (!create_parser_ctx.__argnames__) Object.defineProperties(create_parser_ctx, {\n __argnames__ : {value: ["S", "import_dirs", "module_id", "baselib_items", "imported_module_ids", "imported_modules", "importing_modules", "options"]},\n __module__ : {value: "parse"}\n });\n\n function parse(text, options) {\n var import_dirs, x, location, module_id, baselib_items, imported_module_ids, imported_modules, importing_modules, S, obj, cname;\n options = defaults(options, (function(){\n var RS_d = Object.create(null);\n RS_d["filename"] = null;\n RS_d["module_id"] = "__main__";\n RS_d["toplevel"] = null;\n RS_d["for_linting"] = false;\n RS_d["import_dirs"] = [];\n RS_d["classes"] = undefined;\n RS_d["scoped_flags"] = Object.create(null);\n RS_d["discard_asserts"] = false;\n RS_d["module_cache_dir"] = "";\n return RS_d;\n }).call(this));\n import_dirs = (function() {\n var RS_Iter = RS_Iterable(options.import_dirs), RS_Result = [], x;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n x = RS_Iter[RS_Index];\n RS_Result.push(x);\n }\n RS_Result = RS_list_constructor(RS_Result);\n return RS_Result;\n })();\n var RS_Iter73 = RS_Iterable([options.libdir, options.basedir]);\n for (var RS_Index73 = 0; RS_Index73 < RS_Iter73.length; RS_Index73++) {\n location = RS_Iter73[RS_Index73];\n if (location) {\n import_dirs.push(location);\n }\n }\n module_id = options.module_id;\n baselib_items = Object.create(null);\n imported_module_ids = RS_list_decorate([]);\n imported_modules = options.imported_modules || Object.create(null);\n importing_modules = options.importing_modules || Object.create(null);\n importing_modules[(typeof module_id === "number" && module_id < 0) ? importing_modules.length + module_id : module_id] = true;\n S = (function(){\n var RS_d = Object.create(null);\n RS_d["input"] = (typeof text === "string") ? tokenizer(text, options.filename) : text;\n RS_d["token"] = null;\n RS_d["prev"] = null;\n RS_d["peeked"] = RS_list_decorate([]);\n RS_d["in_function"] = 0;\n RS_d["statement_starting_token"] = null;\n RS_d["in_comprehension"] = false;\n RS_d["in_parenthesized_expr"] = false;\n RS_d["in_delete"] = false;\n RS_d["in_loop"] = 0;\n RS_d["in_class"] = RS_list_decorate([ false ]);\n RS_d["classes"] = RS_list_decorate([ Object.create(null) ]);\n RS_d["functions"] = RS_list_decorate([ Object.create(null) ]);\n RS_d["labels"] = RS_list_decorate([]);\n RS_d["decorators"] = [];\n RS_d["parsing_decorator"] = false;\n RS_d["globals"] = [];\n RS_d["scoped_flags"] = (function(){\n var RS_d = Object.create(null);\n RS_d["stack"] = [options.scoped_flags || Object.create(null)];\n RS_d["push"] = (function() {\n var RS_anonfunc = function () {\n this.stack.push(Object.create(null));\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })();\n RS_d["pop"] = (function() {\n var RS_anonfunc = function () {\n this.stack.pop();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })();\n RS_d["get"] = (function() {\n var RS_anonfunc = function (name, defval) {\n var d, q;\n for (var i = this.stack.length - 1; i >= 0; i--) {\n d = (RS_expr_temp = this.stack)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n q = d[(typeof name === "number" && name < 0) ? d.length + name : name];\n if (q) {\n return q;\n }\n }\n return defval;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["name", "defval"]},\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })();\n RS_d["set"] = (function() {\n var RS_anonfunc = function (name, val) {\n (RS_expr_temp = (RS_expr_temp = this.stack)[RS_expr_temp.length-1])[(typeof name === "number" && name < 0) ? RS_expr_temp.length + name : name] = val;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["name", "val"]},\n __module__ : {value: "parse"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n return RS_d;\n }).call(this);\n if (options.classes) {\n var RS_Iter74 = RS_Iterable(options.classes);\n for (var RS_Index74 = 0; RS_Index74 < RS_Iter74.length; RS_Index74++) {\n cname = RS_Iter74[RS_Index74];\n obj = (RS_expr_temp = options.classes)[(typeof cname === "number" && cname < 0) ? RS_expr_temp.length + cname : cname];\n (RS_expr_temp = S.classes[0])[(typeof cname === "number" && cname < 0) ? RS_expr_temp.length + cname : cname] = (function(){\n var RS_d = Object.create(null);\n RS_d["static"] = obj.static;\n RS_d["bound"] = obj.bound;\n RS_d["classvars"] = obj.classvars;\n return RS_d;\n }).call(this);\n }\n }\n return create_parser_ctx(S, import_dirs, module_id, baselib_items, imported_module_ids, imported_modules, importing_modules, options)();\n };\n if (!parse.__argnames__) Object.defineProperties(parse, {\n __argnames__ : {value: ["text", "options"]},\n __module__ : {value: "parse"}\n });\n\n RS_modules.parse.COMPILER_VERSION = COMPILER_VERSION;\n RS_modules.parse.PYTHON_FLAGS = PYTHON_FLAGS;\n RS_modules.parse.NATIVE_CLASSES = NATIVE_CLASSES;\n RS_modules.parse.ERROR_CLASSES = ERROR_CLASSES;\n RS_modules.parse.COMMON_STATIC = COMMON_STATIC;\n RS_modules.parse.FORBIDDEN_CLASS_VARS = FORBIDDEN_CLASS_VARS;\n RS_modules.parse.UNARY_PREFIX = UNARY_PREFIX;\n RS_modules.parse.ASSIGNMENT = ASSIGNMENT;\n RS_modules.parse.PRECEDENCE = PRECEDENCE;\n RS_modules.parse.STATEMENTS_WITH_LABELS = STATEMENTS_WITH_LABELS;\n RS_modules.parse.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;\n RS_modules.parse.compile_time_decorators = compile_time_decorators;\n RS_modules.parse.get_compiler_version = get_compiler_version;\n RS_modules.parse.static_predicate = static_predicate;\n RS_modules.parse.has_simple_decorator = has_simple_decorator;\n RS_modules.parse.has_setter_decorator = has_setter_decorator;\n RS_modules.parse.create_parser_ctx = create_parser_ctx;\n RS_modules.parse.parse = parse;\n })();\n\n (function(){\n var __name__ = "output";\n\n })();\n\n (function(){\n var __name__ = "output.stream";\n var DANGEROUS, require_semi_colon_chars, output_stream_defaults;\n var make_predicate = RS_modules.utils.make_predicate;\n var defaults = RS_modules.utils.defaults;\n var repeat_string = RS_modules.utils.repeat_string;\n\n var is_identifier_char = RS_modules.tokenizer.is_identifier_char;\n\n DANGEROUS = /[\\u0000\\u00ad\\u0600-\\u0604\\u070f\\u17b4\\u17b5\\u200c-\\u200f\\u2028-\\u202f\\u2060-\\u206f\\ufeff\\ufff0-\\uffff]/g;\n function as_hex(code, sz) {\n var val;\n val = code.toString(16);\n if (val.length < sz) {\n val = "0".repeat(sz - val.length) + val;\n }\n return val;\n };\n if (!as_hex.__argnames__) Object.defineProperties(as_hex, {\n __argnames__ : {value: ["code", "sz"]},\n __module__ : {value: "output.stream"}\n });\n\n function to_ascii(str_, identifier) {\n return str_.replace(/[\\u0080-\\uffff]/g, (function() {\n var RS_anonfunc = function (ch) {\n var code;\n code = ch.charCodeAt(0).toString(16);\n if (code.length <= 2 && !identifier) {\n return "\\\\x" + as_hex(code, 2);\n } else {\n return "\\\\u" + as_hex(code, 4);\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["ch"]},\n __module__ : {value: "output.stream"}\n });\n return RS_anonfunc;\n })());\n };\n if (!to_ascii.__argnames__) Object.defineProperties(to_ascii, {\n __argnames__ : {value: ["str_", "identifier"]},\n __module__ : {value: "output.stream"}\n });\n\n function encode_string(str_) {\n return JSON.stringify(str_).replace(DANGEROUS, (function() {\n var RS_anonfunc = function (a) {\n return "\\\\u" + as_hex(a.charCodeAt(0), 4);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["a"]},\n __module__ : {value: "output.stream"}\n });\n return RS_anonfunc;\n })());\n };\n if (!encode_string.__argnames__) Object.defineProperties(encode_string, {\n __argnames__ : {value: ["str_"]},\n __module__ : {value: "output.stream"}\n });\n\n require_semi_colon_chars = make_predicate("( [ + * / - , .");\n output_stream_defaults = (function(){\n var RS_d = Object.create(null);\n RS_d["indent_start"] = 0;\n RS_d["indent_level"] = 4;\n RS_d["quote_keys"] = false;\n RS_d["space_colon"] = true;\n RS_d["ascii_only"] = false;\n RS_d["width"] = 80;\n RS_d["max_line_len"] = 32e3;\n RS_d["ie_proof"] = true;\n RS_d["beautify"] = false;\n RS_d["source_map"] = null;\n RS_d["bracketize"] = false;\n RS_d["semicolons"] = true;\n RS_d["comments"] = false;\n RS_d["preserve_line"] = false;\n RS_d["omit_baselib"] = false;\n RS_d["baselib_plain"] = null;\n RS_d["private_scope"] = true;\n RS_d["keep_docstrings"] = false;\n RS_d["discard_asserts"] = false;\n RS_d["module_cache_dir"] = "";\n RS_d["js_version"] = 5;\n RS_d["write_name"] = true;\n return RS_d;\n }).call(this);\n function OutputStream() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n OutputStream.prototype.__init__.apply(this, arguments);\n }\n OutputStream.prototype.__init__ = function __init__(options) {\n var self = this;\n self.options = defaults(options, output_stream_defaults, true);\n self._indentation = 0;\n self.current_col = 0;\n self.current_line = 1;\n self.current_pos = 0;\n self.OUTPUT = "";\n self.might_need_space = false;\n self.might_need_semicolon = false;\n self._last = null;\n self._stack = RS_list_decorate([]);\n self.index_counter = 0;\n self.with_counter = 0;\n self.try_else_counter = 0;\n };\n if (!OutputStream.prototype.__init__.__argnames__) Object.defineProperties(OutputStream.prototype.__init__, {\n __argnames__ : {value: ["options"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.__argnames__ = OutputStream.prototype.__init__.__argnames__;\n OutputStream.__handles_kwarg_interpolation__ = OutputStream.prototype.__init__.__handles_kwarg_interpolation__;\n OutputStream.prototype.new_try_else_counter = function new_try_else_counter() {\n var self = this;\n self.try_else_counter += 1;\n return "RS_try_else_" + self.try_else_counter;\n };\n if (!OutputStream.prototype.new_try_else_counter.__module__) Object.defineProperties(OutputStream.prototype.new_try_else_counter, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.make_name = function make_name(name) {\n var self = this;\n name = name.toString();\n if (self.options.ascii_only) {\n name = to_ascii(name, true);\n }\n return name;\n };\n if (!OutputStream.prototype.make_name.__argnames__) Object.defineProperties(OutputStream.prototype.make_name, {\n __argnames__ : {value: ["name"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.print_name = function print_name(name) {\n var self = this;\n self.print(self.make_name(name));\n };\n if (!OutputStream.prototype.print_name.__argnames__) Object.defineProperties(OutputStream.prototype.print_name, {\n __argnames__ : {value: ["name"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.make_indent = function make_indent(back) {\n var self = this;\n return repeat_string(" ", self.options.indent_start + self._indentation - back * self.options.indent_level);\n };\n if (!OutputStream.prototype.make_indent.__argnames__) Object.defineProperties(OutputStream.prototype.make_indent, {\n __argnames__ : {value: ["back"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.last_char = function last_char() {\n var self = this;\n return self._last.charAt(self._last.length - 1);\n };\n if (!OutputStream.prototype.last_char.__module__) Object.defineProperties(OutputStream.prototype.last_char, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.maybe_newline = function maybe_newline() {\n var self = this;\n if (self.options.max_line_len && self.current_col > self.options.max_line_len) {\n self.print("\\n");\n }\n };\n if (!OutputStream.prototype.maybe_newline.__module__) Object.defineProperties(OutputStream.prototype.maybe_newline, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.print = function print(str_) {\n var self = this;\n var ch, target_line, prev, a, n;\n str_ = String(str_);\n ch = str_.charAt(0);\n if (self.might_need_semicolon) {\n if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(self._last)) {\n if (self.options.semicolons || require_semi_colon_chars[(typeof ch === "number" && ch < 0) ? require_semi_colon_chars.length + ch : ch]) {\n self.OUTPUT += ";";\n self.current_col += 1;\n self.current_pos += 1;\n } else {\n self.OUTPUT += "\\n";\n self.current_pos += 1;\n self.current_line += 1;\n self.current_col = 0;\n }\n if (!self.options.beautify) {\n self.might_need_space = false;\n }\n }\n self.might_need_semicolon = false;\n self.maybe_newline();\n }\n if (!self.options.beautify && self.options.preserve_line && (RS_expr_temp = self._stack)[RS_bound_index(self._stack.length - 1, RS_expr_temp)]) {\n target_line = (RS_expr_temp = self._stack)[RS_bound_index(self._stack.length - 1, RS_expr_temp)].start.line;\n while (self.current_line < target_line) {\n self.OUTPUT += "\\n";\n self.current_pos += 1;\n self.current_line += 1;\n self.current_col = 0;\n self.might_need_space = false;\n }\n }\n if (self.might_need_space) {\n prev = self.last_char();\n if (is_identifier_char(prev) && (is_identifier_char(ch) || ch === "\\\\") || /^[\\+\\-\\/]$/.test(ch) && ch === prev) {\n self.OUTPUT += " ";\n self.current_col += 1;\n self.current_pos += 1;\n }\n self.might_need_space = false;\n }\n a = str_.split(/\\r?\\n/);\n n = a.length - 1;\n self.current_line += n;\n if (n === 0) {\n self.current_col += a[(typeof n === "number" && n < 0) ? a.length + n : n].length;\n } else {\n self.current_col = a[(typeof n === "number" && n < 0) ? a.length + n : n].length;\n }\n self.current_pos += str_.length;\n self._last = str_;\n self.OUTPUT += str_;\n };\n if (!OutputStream.prototype.print.__argnames__) Object.defineProperties(OutputStream.prototype.print, {\n __argnames__ : {value: ["str_"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.space = function space() {\n var self = this;\n if (self.options.beautify) {\n self.print(" ");\n } else {\n self.might_need_space = true;\n }\n };\n if (!OutputStream.prototype.space.__module__) Object.defineProperties(OutputStream.prototype.space, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.indent = function indent(half) {\n var self = this;\n if (self.options.beautify) {\n self.print(self.make_indent((half) ? .5 : 0));\n }\n };\n if (!OutputStream.prototype.indent.__argnames__) Object.defineProperties(OutputStream.prototype.indent, {\n __argnames__ : {value: ["half"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.with_indent = function with_indent(col, proceed) {\n var self = this;\n var save_indentation, ret;\n if (self.options.beautify) {\n if (col === true) {\n col = self.next_indent();\n }\n save_indentation = self._indentation;\n self._indentation = col;\n ret = proceed();\n self._indentation = save_indentation;\n return ret;\n } else {\n return proceed();\n }\n };\n if (!OutputStream.prototype.with_indent.__argnames__) Object.defineProperties(OutputStream.prototype.with_indent, {\n __argnames__ : {value: ["col", "proceed"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.indentation = function indentation() {\n var self = this;\n return self._indentation;\n };\n if (!OutputStream.prototype.indentation.__module__) Object.defineProperties(OutputStream.prototype.indentation, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.set_indentation = function set_indentation(val) {\n var self = this;\n if (self.options.beautify) {\n self._indentation = val;\n }\n };\n if (!OutputStream.prototype.set_indentation.__argnames__) Object.defineProperties(OutputStream.prototype.set_indentation, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.newline = function newline() {\n var self = this;\n if (self.options.beautify) {\n self.print("\\n");\n }\n };\n if (!OutputStream.prototype.newline.__module__) Object.defineProperties(OutputStream.prototype.newline, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.semicolon = function semicolon() {\n var self = this;\n if (self.options.beautify) {\n self.print(";");\n } else {\n self.might_need_semicolon = true;\n }\n };\n if (!OutputStream.prototype.semicolon.__module__) Object.defineProperties(OutputStream.prototype.semicolon, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.force_semicolon = function force_semicolon() {\n var self = this;\n self.might_need_semicolon = false;\n self.print(";");\n };\n if (!OutputStream.prototype.force_semicolon.__module__) Object.defineProperties(OutputStream.prototype.force_semicolon, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.next_indent = function next_indent() {\n var self = this;\n return self._indentation + self.options.indent_level;\n };\n if (!OutputStream.prototype.next_indent.__module__) Object.defineProperties(OutputStream.prototype.next_indent, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.spaced = function spaced() {\n var self = this;\n for (var i=0; i < arguments.length; i++) {\n if (i > 0) {\n self.space();\n }\n if (typeof arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].print === "function") {\n arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].print(self);\n } else {\n self.print(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n }\n }\n };\n if (!OutputStream.prototype.spaced.__module__) Object.defineProperties(OutputStream.prototype.spaced, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.end_statement = function end_statement() {\n var self = this;\n self.semicolon();\n self.newline();\n };\n if (!OutputStream.prototype.end_statement.__module__) Object.defineProperties(OutputStream.prototype.end_statement, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.with_block = function with_block(cont) {\n var self = this;\n var ret;\n ret = null;\n self.print("{");\n self.newline();\n self.with_indent(self.next_indent(), (function() {\n var RS_anonfunc = function () {\n ret = cont();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.stream"}\n });\n return RS_anonfunc;\n })());\n self.indent();\n self.print("}");\n return ret;\n };\n if (!OutputStream.prototype.with_block.__argnames__) Object.defineProperties(OutputStream.prototype.with_block, {\n __argnames__ : {value: ["cont"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.with_parens = function with_parens(cont) {\n var self = this;\n var ret;\n self.print("(");\n ret = cont();\n self.print(")");\n return ret;\n };\n if (!OutputStream.prototype.with_parens.__argnames__) Object.defineProperties(OutputStream.prototype.with_parens, {\n __argnames__ : {value: ["cont"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.with_square = function with_square(cont) {\n var self = this;\n var ret;\n self.print("[");\n ret = cont();\n self.print("]");\n return ret;\n };\n if (!OutputStream.prototype.with_square.__argnames__) Object.defineProperties(OutputStream.prototype.with_square, {\n __argnames__ : {value: ["cont"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.comma = function comma() {\n var self = this;\n self.print(",");\n self.space();\n };\n if (!OutputStream.prototype.comma.__module__) Object.defineProperties(OutputStream.prototype.comma, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.colon = function colon() {\n var self = this;\n self.print(":");\n if (self.options.space_colon) {\n self.space();\n }\n };\n if (!OutputStream.prototype.colon.__module__) Object.defineProperties(OutputStream.prototype.colon, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.dump_yield = function dump_yield() {\n var self = this;\n var code, ci;\n self.indent();\n self.spaced("var", "RS_regenerator", "=", "{}");\n self.end_statement();\n code = "RS_regenerator.regeneratorRuntime = " + regenerate(false, self.options.beautify);\n if (self.options.beautify) {\n code = code.replace(/\\/\\/.*$/gm, "\\n").replace(/^\\s*$/gm, "");\n ci = self.make_indent(0);\n code = (function() {\n var RS_Iter = RS_Iterable(code.split("\\n")), RS_Result = [], x;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n x = RS_Iter[RS_Index];\n RS_Result.push(ci + x);\n }\n RS_Result = RS_list_constructor(RS_Result);\n return RS_Result;\n })().join("\\n");\n }\n self.print(code + "})(RS_regenerator)");\n self.end_statement();\n };\n if (!OutputStream.prototype.dump_yield.__module__) Object.defineProperties(OutputStream.prototype.dump_yield, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.get = function get() {\n var self = this;\n return self.OUTPUT;\n };\n if (!OutputStream.prototype.get.__module__) Object.defineProperties(OutputStream.prototype.get, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.assign = function assign(name) {\n var self = this;\n if (typeof name === "string") {\n self.print(name);\n } else {\n name.print(self);\n }\n self.space();\n self.print("=");\n self.space();\n };\n if (!OutputStream.prototype.assign.__argnames__) Object.defineProperties(OutputStream.prototype.assign, {\n __argnames__ : {value: ["name"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.current_width = function current_width() {\n var self = this;\n return self.current_col - self._indentation;\n };\n if (!OutputStream.prototype.current_width.__module__) Object.defineProperties(OutputStream.prototype.current_width, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.should_break = function should_break() {\n var self = this;\n return self.options.width && self.current_width() >= self.options.width;\n };\n if (!OutputStream.prototype.should_break.__module__) Object.defineProperties(OutputStream.prototype.should_break, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.last = function last() {\n var self = this;\n return self._last;\n };\n if (!OutputStream.prototype.last.__module__) Object.defineProperties(OutputStream.prototype.last, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.print_string = function print_string(str_) {\n var self = this;\n self.print(encode_string(str_));\n };\n if (!OutputStream.prototype.print_string.__argnames__) Object.defineProperties(OutputStream.prototype.print_string, {\n __argnames__ : {value: ["str_"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.line = function line() {\n var self = this;\n return self.current_line;\n };\n if (!OutputStream.prototype.line.__module__) Object.defineProperties(OutputStream.prototype.line, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.col = function col() {\n var self = this;\n return self.current_col;\n };\n if (!OutputStream.prototype.col.__module__) Object.defineProperties(OutputStream.prototype.col, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.pos = function pos() {\n var self = this;\n return self.current_pos;\n };\n if (!OutputStream.prototype.pos.__module__) Object.defineProperties(OutputStream.prototype.pos, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.push_node = function push_node(node) {\n var self = this;\n self._stack.push(node);\n };\n if (!OutputStream.prototype.push_node.__argnames__) Object.defineProperties(OutputStream.prototype.push_node, {\n __argnames__ : {value: ["node"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.pop_node = function pop_node() {\n var self = this;\n return self._stack.pop();\n };\n if (!OutputStream.prototype.pop_node.__module__) Object.defineProperties(OutputStream.prototype.pop_node, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.stack = function stack() {\n var self = this;\n return self._stack;\n };\n if (!OutputStream.prototype.stack.__module__) Object.defineProperties(OutputStream.prototype.stack, {\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.parent = function parent(n) {\n var self = this;\n return (RS_expr_temp = self._stack)[RS_bound_index(self._stack.length - 2 - (n || 0), RS_expr_temp)];\n };\n if (!OutputStream.prototype.parent.__argnames__) Object.defineProperties(OutputStream.prototype.parent, {\n __argnames__ : {value: ["n"]},\n __module__ : {value: "output.stream"}\n });\n OutputStream.prototype.__repr__ = function __repr__ () {\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n };\n OutputStream.prototype.__str__ = function __str__ () {\n return this.__repr__();\n };\n Object.defineProperty(OutputStream.prototype, "__bases__", {value: []});\n OutputStream.prototype.toString = OutputStream.prototype.get;\n\n RS_modules["output.stream"].DANGEROUS = DANGEROUS;\n RS_modules["output.stream"].require_semi_colon_chars = require_semi_colon_chars;\n RS_modules["output.stream"].output_stream_defaults = output_stream_defaults;\n RS_modules["output.stream"].as_hex = as_hex;\n RS_modules["output.stream"].to_ascii = to_ascii;\n RS_modules["output.stream"].encode_string = encode_string;\n RS_modules["output.stream"].OutputStream = OutputStream;\n })();\n\n (function(){\n var __name__ = "output.statements";\n var AST_Definitions = RS_modules.ast.AST_Definitions;\n var AST_Scope = RS_modules.ast.AST_Scope;\n var AST_Method = RS_modules.ast.AST_Method;\n var AST_Except = RS_modules.ast.AST_Except;\n var AST_EmptyStatement = RS_modules.ast.AST_EmptyStatement;\n var AST_Statement = RS_modules.ast.AST_Statement;\n var AST_Seq = RS_modules.ast.AST_Seq;\n var AST_BaseCall = RS_modules.ast.AST_BaseCall;\n var AST_Dot = RS_modules.ast.AST_Dot;\n var AST_Sub = RS_modules.ast.AST_Sub;\n var AST_ItemAccess = RS_modules.ast.AST_ItemAccess;\n var AST_Conditional = RS_modules.ast.AST_Conditional;\n var AST_Binary = RS_modules.ast.AST_Binary;\n var AST_BlockStatement = RS_modules.ast.AST_BlockStatement;\n var is_node_type = RS_modules.ast.is_node_type;\n\n function force_statement(stat, output) {\n if (output.options.bracketize) {\n if (!stat || is_node_type(stat, AST_EmptyStatement)) {\n output.print("{}");\n } else if (is_node_type(stat, AST_BlockStatement)) {\n stat.print(output);\n } else {\n output.with_block((function() {\n var RS_anonfunc = function () {\n output.indent();\n stat.print(output);\n output.newline();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.statements"}\n });\n return RS_anonfunc;\n })());\n }\n } else {\n if (!stat || is_node_type(stat, AST_EmptyStatement)) {\n output.force_semicolon();\n } else {\n stat.print(output);\n }\n }\n };\n if (!force_statement.__argnames__) Object.defineProperties(force_statement, {\n __argnames__ : {value: ["stat", "output"]},\n __module__ : {value: "output.statements"}\n });\n\n function first_in_statement(output) {\n var a, i, node, p;\n a = output.stack();\n i = a.length;\n node = a[RS_bound_index(i -= 1, a)];\n p = a[RS_bound_index(i -= 1, a)];\n while (i > 0) {\n if (is_node_type(p, AST_Statement) && p.body === node) {\n return true;\n }\n if (is_node_type(p, AST_Seq) && p.car === node || is_node_type(p, AST_BaseCall) && p.expression === node || is_node_type(p, AST_Dot) && p.expression === node || is_node_type(p, AST_Sub) && p.expression === node || is_node_type(p, AST_ItemAccess) && p.expression === node || is_node_type(p, AST_Conditional) && p.condition === node || is_node_type(p, AST_Binary) && p.left === node) {\n node = p;\n p = a[RS_bound_index(i -= 1, a)];\n } else {\n return false;\n }\n }\n };\n if (!first_in_statement.__argnames__) Object.defineProperties(first_in_statement, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.statements"}\n });\n\n function declare_vars(vars, output) {\n var RS_unpack, i, arg;\n if (vars.length) {\n output.indent();\n output.print("var");\n output.space();\n var RS_Iter75 = RS_Iterable(enumerate(vars));\n for (var RS_Index75 = 0; RS_Index75 < RS_Iter75.length; RS_Index75++) {\n RS_unpack = RS_Iter75[RS_Index75];\n i = RS_unpack[0];\n arg = RS_unpack[1];\n if (i) {\n output.comma();\n }\n arg.print(output);\n }\n output.semicolon();\n output.newline();\n }\n };\n if (!declare_vars.__argnames__) Object.defineProperties(declare_vars, {\n __argnames__ : {value: ["vars", "output"]},\n __module__ : {value: "output.statements"}\n });\n\n function display_body(body, is_toplevel, output) {\n var last, RS_unpack, i, stmt;\n last = body.length - 1;\n var RS_Iter76 = RS_Iterable(enumerate(body));\n for (var RS_Index76 = 0; RS_Index76 < RS_Iter76.length; RS_Index76++) {\n RS_unpack = RS_Iter76[RS_Index76];\n i = RS_unpack[0];\n stmt = RS_unpack[1];\n if (!(is_node_type(stmt, AST_EmptyStatement)) && !(is_node_type(stmt, AST_Definitions))) {\n output.indent();\n stmt.print(output);\n if (!((i === last && is_toplevel))) {\n output.newline();\n }\n }\n }\n };\n if (!display_body.__argnames__) Object.defineProperties(display_body, {\n __argnames__ : {value: ["body", "is_toplevel", "output"]},\n __module__ : {value: "output.statements"}\n });\n\n function display_complex_body(node, is_toplevel, output, function_preamble) {\n var offset;\n offset = 0;\n if (is_node_type(node, AST_Method) && !node.static) {\n output.indent();\n output.print("var");\n output.space();\n output.assign(node.argnames[0]);\n output.print("this");\n output.semicolon();\n output.newline();\n offset += 1;\n }\n if (is_node_type(node, AST_Scope)) {\n function_preamble(node, output, offset);\n declare_vars(node.localvars, output);\n } else if (is_node_type(node, AST_Except)) {\n if (node.argname) {\n output.indent();\n output.print("var");\n output.space();\n output.assign(node.argname);\n output.print("RS_Exception");\n output.semicolon();\n output.newline();\n }\n }\n display_body(node.body, is_toplevel, output);\n };\n if (!display_complex_body.__argnames__) Object.defineProperties(display_complex_body, {\n __argnames__ : {value: ["node", "is_toplevel", "output", "function_preamble"]},\n __module__ : {value: "output.statements"}\n });\n\n function print_bracketed(node, output, complex, function_preamble, before, after) {\n if (node.body.length > 0) {\n output.with_block((function() {\n var RS_anonfunc = function () {\n if (before) {\n before(output);\n }\n if (complex) {\n display_complex_body(node, false, output, function_preamble);\n } else {\n display_body(node.body, false, output);\n }\n if (after) {\n after(output);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.statements"}\n });\n return RS_anonfunc;\n })());\n } else {\n if (before || after) {\n output.with_block((function() {\n var RS_anonfunc = function () {\n if (before) {\n before(output);\n }\n if (after) {\n after(output);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.statements"}\n });\n return RS_anonfunc;\n })());\n } else {\n output.print("{}");\n }\n }\n };\n if (!print_bracketed.__argnames__) Object.defineProperties(print_bracketed, {\n __argnames__ : {value: ["node", "output", "complex", "function_preamble", "before", "after"]},\n __module__ : {value: "output.statements"}\n });\n\n function print_with(self, output) {\n var exits, clause_name, clause;\n exits = [];\n [output.assign("RS_with_exception"), output.print("undefined"), output.end_statement()];\n var RS_Iter77 = RS_Iterable(self.clauses);\n for (var RS_Index77 = 0; RS_Index77 < RS_Iter77.length; RS_Index77++) {\n clause = RS_Iter77[RS_Index77];\n output.with_counter += 1;\n clause_name = "RS_with_clause_" + output.with_counter;\n exits.push(clause_name);\n [output.indent(), output.print("var "), output.assign(clause_name)];\n clause.expression.print(output);\n output.end_statement();\n output.indent();\n if (clause.alias) {\n output.assign(clause.alias.name);\n }\n output.print(clause_name + ".__enter__()");\n output.end_statement();\n }\n [output.indent(), output.print("try"), output.space()];\n output.with_block((function() {\n var RS_anonfunc = function () {\n output.indent();\n self._do_print_body(output);\n output.newline();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.statements"}\n });\n return RS_anonfunc;\n })());\n [output.space(), output.print("catch(e)")];\n output.with_block((function() {\n var RS_anonfunc = function () {\n [output.indent(), output.assign("RS_with_exception"), output.print("e"), output.end_statement()];\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.statements"}\n });\n return RS_anonfunc;\n })());\n [output.newline(), output.indent(), output.spaced("if", "(RS_with_exception", "===", "undefined)")];\n output.with_block((function() {\n var RS_anonfunc = function () {\n var clause;\n var RS_Iter78 = RS_Iterable(exits);\n for (var RS_Index78 = 0; RS_Index78 < RS_Iter78.length; RS_Index78++) {\n clause = RS_Iter78[RS_Index78];\n [output.indent(), output.print(clause + ".__exit__()"), output.end_statement()];\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.statements"}\n });\n return RS_anonfunc;\n })());\n [output.space(), output.print("else"), output.space()];\n output.with_block((function() {\n var RS_anonfunc = function () {\n var clause;\n [output.indent(), output.assign("RS_with_suppress"), output.print("false"), output.end_statement()];\n var RS_Iter79 = RS_Iterable(exits);\n for (var RS_Index79 = 0; RS_Index79 < RS_Iter79.length; RS_Index79++) {\n clause = RS_Iter79[RS_Index79];\n output.indent();\n output.spaced("RS_with_suppress", "|=", "RS_bool(" + clause + ".__exit__(RS_with_exception.constructor,", "RS_with_exception,", "RS_with_exception.stack))");\n output.end_statement();\n }\n [output.indent(), output.spaced("if", "(!RS_with_suppress)", "throw RS_with_exception"), \n output.end_statement()];\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.statements"}\n });\n return RS_anonfunc;\n })());\n };\n if (!print_with.__argnames__) Object.defineProperties(print_with, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.statements"}\n });\n\n function print_assert(self, output) {\n if (output.options.discard_asserts) {\n return;\n }\n [output.spaced("if", "(!("), self.condition.print(output), output.spaced("))", "throw new AssertionError")];\n if (self.message) {\n output.print("(");\n self.message.print(output);\n output.print(")");\n }\n output.end_statement();\n };\n if (!print_assert.__argnames__) Object.defineProperties(print_assert, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.statements"}\n });\n\n RS_modules["output.statements"].force_statement = force_statement;\n RS_modules["output.statements"].first_in_statement = first_in_statement;\n RS_modules["output.statements"].declare_vars = declare_vars;\n RS_modules["output.statements"].display_body = display_body;\n RS_modules["output.statements"].display_complex_body = display_complex_body;\n RS_modules["output.statements"].print_bracketed = print_bracketed;\n RS_modules["output.statements"].print_with = print_with;\n RS_modules["output.statements"].print_assert = print_assert;\n })();\n\n (function(){\n var __name__ = "output.exceptions";\n var print_bracketed = RS_modules["output.statements"].print_bracketed;\n\n function print_try(self, output) {\n var else_var_name;\n else_var_name = null;\n function update_output_var(output) {\n [output.indent(), output.assign(else_var_name), output.print("true"), output.end_statement()];\n };\n if (!update_output_var.__argnames__) Object.defineProperties(update_output_var, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.exceptions"}\n });\n\n if (self.belse) {\n else_var_name = output.new_try_else_counter();\n [output.assign("var " + else_var_name), output.print("false"), output.end_statement(), \n output.indent()];\n }\n output.print("try");\n output.space();\n print_bracketed(self, output, false, null, null, (else_var_name) ? update_output_var : null);\n if (self.bcatch) {\n output.space();\n print_catch(self.bcatch, output);\n }\n if (self.bfinally) {\n output.space();\n print_finally(self.bfinally, output, self.belse, else_var_name);\n } else if (self.belse) {\n output.newline();\n print_else(self.belse, else_var_name, output);\n }\n };\n if (!print_try.__argnames__) Object.defineProperties(print_try, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.exceptions"}\n });\n\n function print_catch(self, output) {\n output.print("catch");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("RS_Exception");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.exceptions"}\n });\n return RS_anonfunc;\n })());\n output.space();\n output.with_block((function() {\n var RS_anonfunc = function () {\n var no_default, RS_unpack, i, exception;\n output.indent();\n [output.spaced("RS_last_exception", "=", "RS_Exception"), output.end_statement()];\n output.indent();\n no_default = true;\n var RS_Iter80 = RS_Iterable(enumerate(self.body));\n for (var RS_Index80 = 0; RS_Index80 < RS_Iter80.length; RS_Index80++) {\n RS_unpack = RS_Iter80[RS_Index80];\n i = RS_unpack[0];\n exception = RS_unpack[1];\n if (i) {\n output.print("else ");\n }\n if (exception.errors.length) {\n output.print("if");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n var RS_unpack, i, err;\n var RS_Iter81 = RS_Iterable(enumerate(exception.errors));\n for (var RS_Index81 = 0; RS_Index81 < RS_Iter81.length; RS_Index81++) {\n RS_unpack = RS_Iter81[RS_Index81];\n i = RS_unpack[0];\n err = RS_unpack[1];\n if (i) {\n output.newline();\n output.indent();\n output.print("||");\n output.space();\n }\n output.print("RS_Exception");\n output.space();\n output.print("instanceof");\n output.space();\n if (err.name === "Exception") {\n output.print("Error");\n } else {\n err.print(output);\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.exceptions"}\n });\n return RS_anonfunc;\n })());\n output.space();\n } else {\n no_default = false;\n }\n print_bracketed(exception, output, true);\n output.space();\n }\n if (no_default) {\n output.print("else");\n output.space();\n output.with_block((function() {\n var RS_anonfunc = function () {\n output.indent();\n output.print("throw");\n output.space();\n output.print("RS_Exception");\n output.semicolon();\n output.newline();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.exceptions"}\n });\n return RS_anonfunc;\n })());\n }\n output.newline();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.exceptions"}\n });\n return RS_anonfunc;\n })());\n };\n if (!print_catch.__argnames__) Object.defineProperties(print_catch, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.exceptions"}\n });\n\n function print_finally(self, output, belse, else_var_name) {\n output.print("finally");\n output.space();\n if (else_var_name) {\n output.with_block((function() {\n var RS_anonfunc = function () {\n [output.indent(), output.print("try")];\n output.space();\n output.with_block((function() {\n var RS_anonfunc = function () {\n print_else(belse, else_var_name, output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.exceptions"}\n });\n return RS_anonfunc;\n })());\n print_finally(self, output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.exceptions"}\n });\n return RS_anonfunc;\n })());\n } else {\n print_bracketed(self, output);\n }\n };\n if (!print_finally.__argnames__) Object.defineProperties(print_finally, {\n __argnames__ : {value: ["self", "output", "belse", "else_var_name"]},\n __module__ : {value: "output.exceptions"}\n });\n\n function print_else(self, else_var_name, output) {\n [output.indent(), output.spaced("if", "(" + else_var_name + ")")];\n output.space();\n print_bracketed(self, output);\n };\n if (!print_else.__argnames__) Object.defineProperties(print_else, {\n __argnames__ : {value: ["self", "else_var_name", "output"]},\n __module__ : {value: "output.exceptions"}\n });\n\n RS_modules["output.exceptions"].print_try = print_try;\n RS_modules["output.exceptions"].print_catch = print_catch;\n RS_modules["output.exceptions"].print_finally = print_finally;\n RS_modules["output.exceptions"].print_else = print_else;\n })();\n\n (function(){\n var __name__ = "output.utils";\n var AST_BlockStatement = RS_modules.ast.AST_BlockStatement;\n var is_node_type = RS_modules.ast.is_node_type;\n\n function best_of(a) {\n var best, len_, i;\n best = a[0];\n len_ = best.length;\n for (var RS_Index82 = 1; RS_Index82 < a.length; RS_Index82++) {\n i = RS_Index82;\n if (a[(typeof i === "number" && i < 0) ? a.length + i : i].length < len_) {\n best = a[(typeof i === "number" && i < 0) ? a.length + i : i];\n len_ = best.length;\n }\n }\n return best;\n };\n if (!best_of.__argnames__) Object.defineProperties(best_of, {\n __argnames__ : {value: ["a"]},\n __module__ : {value: "output.utils"}\n });\n\n function make_num(num) {\n var str_, a, m;\n str_ = num.toString(10);\n a = RS_list_decorate([ str_.replace(/^0\\./, ".").replace("e+", "e") ]);\n m = null;\n if (Math.floor(num) === num) {\n if (num >= 0) {\n a.push("0x" + num.toString(16).toLowerCase(), "0" + num.toString(8));\n } else {\n a.push("-0x" + (-(num)).toString(16).toLowerCase(), "-0" + (-(num)).toString(8));\n }\n if (m = /^(.*?)(0+)$/.exec(num)) {\n a.push(m[1] + "e" + m[2].length);\n }\n } else if (m = /^0?\\.(0+)(.*)$/.exec(num)) {\n a.push(m[2] + "e-" + (m[1].length + m[2].length), str_.substr(str_.indexOf(".")));\n }\n return best_of(a);\n };\n if (!make_num.__argnames__) Object.defineProperties(make_num, {\n __argnames__ : {value: ["num"]},\n __module__ : {value: "output.utils"}\n });\n\n function make_block(stmt, output) {\n if (is_node_type(stmt, AST_BlockStatement)) {\n stmt.print(output);\n return;\n }\n output.with_block((function() {\n var RS_anonfunc = function () {\n output.indent();\n stmt.print(output);\n output.newline();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.utils"}\n });\n return RS_anonfunc;\n })());\n };\n if (!make_block.__argnames__) Object.defineProperties(make_block, {\n __argnames__ : {value: ["stmt", "output"]},\n __module__ : {value: "output.utils"}\n });\n\n function create_doctring(docstrings) {\n var ans, ds, lines, min_leading_whitespace, r, leading_whitespace, line, lw, RS_unpack, l;\n ans = [];\n var RS_Iter83 = RS_Iterable(docstrings);\n for (var RS_Index83 = 0; RS_Index83 < RS_Iter83.length; RS_Index83++) {\n ds = RS_Iter83[RS_Index83];\n ds = str.rstrip(ds.value);\n lines = [];\n min_leading_whitespace = "";\n var RS_Iter84 = RS_Iterable(ds.split(/$/gm));\n for (var RS_Index84 = 0; RS_Index84 < RS_Iter84.length; RS_Index84++) {\n line = RS_Iter84[RS_Index84];\n r = /^\\s+/.exec(line);\n leading_whitespace = "";\n if (r) {\n leading_whitespace = (r) ? r[0].replace(/[\\n\\r]/g, "") : "";\n line = line.slice(r[0].length);\n }\n if (!str.strip(line)) {\n lines.push(["", ""]);\n } else {\n leading_whitespace = leading_whitespace.replace(/\\t/g, " ");\n if (leading_whitespace && (!min_leading_whitespace || leading_whitespace.length < min_leading_whitespace.length)) {\n min_leading_whitespace = leading_whitespace;\n }\n lines.push([leading_whitespace, line]);\n }\n }\n var RS_Iter85 = RS_Iterable(lines);\n for (var RS_Index85 = 0; RS_Index85 < RS_Iter85.length; RS_Index85++) {\n RS_unpack = RS_Iter85[RS_Index85];\n lw = RS_unpack[0];\n l = RS_unpack[1];\n if (min_leading_whitespace) {\n lw = lw.slice(min_leading_whitespace.length);\n }\n ans.push(lw + l);\n }\n ans.push("");\n }\n return str.rstrip(ans.join("\\n"));\n };\n if (!create_doctring.__argnames__) Object.defineProperties(create_doctring, {\n __argnames__ : {value: ["docstrings"]},\n __module__ : {value: "output.utils"}\n });\n\n RS_modules["output.utils"].best_of = best_of;\n RS_modules["output.utils"].make_num = make_num;\n RS_modules["output.utils"].make_block = make_block;\n RS_modules["output.utils"].create_doctring = create_doctring;\n })();\n\n (function(){\n var __name__ = "output.loops";\n var AST_BaseCall = RS_modules.ast.AST_BaseCall;\n var AST_SymbolRef = RS_modules.ast.AST_SymbolRef;\n var AST_Array = RS_modules.ast.AST_Array;\n var AST_Unary = RS_modules.ast.AST_Unary;\n var AST_Number = RS_modules.ast.AST_Number;\n var has_calls = RS_modules.ast.has_calls;\n var AST_Seq = RS_modules.ast.AST_Seq;\n var AST_ListComprehension = RS_modules.ast.AST_ListComprehension;\n var is_node_type = RS_modules.ast.is_node_type;\n\n var OutputStream = RS_modules["output.stream"].OutputStream;\n\n function unpack_tuple(elems, output, in_statement) {\n var RS_unpack, i, elem;\n var RS_Iter86 = RS_Iterable(enumerate(elems));\n for (var RS_Index86 = 0; RS_Index86 < RS_Iter86.length; RS_Index86++) {\n RS_unpack = RS_Iter86[RS_Index86];\n i = RS_unpack[0];\n elem = RS_unpack[1];\n output.indent();\n output.assign(elem);\n output.print("RS_unpack");\n output.with_square((function() {\n var RS_anonfunc = function () {\n output.print(i);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n if (!in_statement || i < elems.length - 1) {\n output.semicolon();\n output.newline();\n }\n }\n };\n if (!unpack_tuple.__argnames__) Object.defineProperties(unpack_tuple, {\n __argnames__ : {value: ["elems", "output", "in_statement"]},\n __module__ : {value: "output.loops"}\n });\n\n function print_do_loop(self, output) {\n output.print("do");\n output.space();\n self._do_print_body(output);\n output.space();\n output.print("while");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.condition.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n output.semicolon();\n };\n if (!print_do_loop.__argnames__) Object.defineProperties(print_do_loop, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.loops"}\n });\n\n function print_while_loop(self, output) {\n output.print("while");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.condition.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n output.space();\n self._do_print_body(output);\n };\n if (!print_while_loop.__argnames__) Object.defineProperties(print_while_loop, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.loops"}\n });\n\n function is_simple_for_in(self) {\n if (is_node_type(self.object, AST_BaseCall) && is_node_type(self.object.expression, AST_SymbolRef) && self.object.expression.name === "dir" && self.object.args.length === 1) {\n return true;\n }\n return false;\n };\n if (!is_simple_for_in.__argnames__) Object.defineProperties(is_simple_for_in, {\n __argnames__ : {value: ["self"]},\n __module__ : {value: "output.loops"}\n });\n\n function is_simple_for(self) {\n var a, l;\n if (is_node_type(self.object, AST_BaseCall) && is_node_type(self.object.expression, AST_SymbolRef) && self.object.expression.name === "range" && !(is_node_type(self.init, AST_Array))) {\n a = self.object.args;\n l = a.length;\n if (l < 3 || is_node_type(a[2], AST_Number) || is_node_type(a[2], AST_Unary) && a[2].operator === "-" && is_node_type(a[2].expression, AST_Number)) {\n if (l === 1 && !has_calls(a[0]) || l > 1 && !has_calls(a[1])) {\n return true;\n }\n }\n }\n return false;\n };\n if (!is_simple_for.__argnames__) Object.defineProperties(is_simple_for, {\n __argnames__ : {value: ["self"]},\n __module__ : {value: "output.loops"}\n });\n\n function print_for_loop_body(output) {\n var self;\n self = this;\n output.with_block((function() {\n var RS_anonfunc = function () {\n var itervar, flat, stmt;\n if (!((self.simple_for_index || is_simple_for_in(self)))) {\n output.indent();\n if (output.options.js_version === 5) {\n itervar = "RS_Iter" + output.index_counter + "[RS_Index" + output.index_counter + "]";\n } else {\n itervar = "RS_Index" + output.index_counter;\n }\n if (is_node_type(self.init, AST_Array)) {\n flat = self.init.flatten();\n output.assign("RS_unpack");\n if (flat.length > self.init.elements.length) {\n output.print("RS_flatten(" + itervar + ")");\n } else {\n output.print(itervar);\n }\n output.end_statement();\n unpack_tuple(flat, output);\n } else {\n output.assign(self.init);\n output.print(itervar);\n output.end_statement();\n }\n output.index_counter += 1;\n }\n if (self.simple_for_index) {\n output.indent();\n output.assign(self.init);\n output.print(self.simple_for_index);\n output.end_statement();\n }\n var RS_Iter87 = RS_Iterable(self.body.body);\n for (var RS_Index87 = 0; RS_Index87 < RS_Iter87.length; RS_Index87++) {\n stmt = RS_Iter87[RS_Index87];\n output.indent();\n stmt.print(output);\n output.newline();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n };\n if (!print_for_loop_body.__argnames__) Object.defineProperties(print_for_loop_body, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.loops"}\n });\n\n function init_es6_itervar(output, itervar) {\n output.indent();\n output.spaced(itervar, "=", "((typeof", itervar + "[Symbol.iterator]", "===", "\\"function\\")", "?", "(" + itervar, "instanceof", "Map", "?", itervar + ".keys()", ":", itervar + ")", ":", "Object.keys(" + itervar + "))");\n output.end_statement();\n };\n if (!init_es6_itervar.__argnames__) Object.defineProperties(init_es6_itervar, {\n __argnames__ : {value: ["output", "itervar"]},\n __module__ : {value: "output.loops"}\n });\n\n function print_for_in(self, output) {\n var increment, args, tmp_, start, end, idx, itervar;\n function write_object() {\n if (self.object.constructor === AST_Seq) {\n new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = self.object.to_array();\n return RS_d;\n }).call(this)).print(output);\n } else {\n self.object.print(output);\n }\n };\n if (!write_object.__module__) Object.defineProperties(write_object, {\n __module__ : {value: "output.loops"}\n });\n\n if (is_simple_for(self)) {\n increment = null;\n args = self.object.args;\n tmp_ = args.length;\n if (tmp_ === 1) {\n start = 0;\n end = args[0];\n } else if (tmp_ === 2) {\n start = args[0];\n end = args[1];\n } else if (tmp_ === 3) {\n start = args[0];\n end = args[1];\n increment = args[2];\n }\n self.simple_for_index = idx = "RS_Index" + output.index_counter;\n output.index_counter += 1;\n output.print("for");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n [output.spaced("var", idx, "="), output.space()];\n (start.print) ? start.print(output) : output.print(start);\n output.semicolon();\n output.space();\n output.print(idx);\n output.space();\n (is_node_type(increment, AST_Unary)) ? output.print(">") : output.print("<");\n output.space();\n end.print(output);\n output.semicolon();\n output.space();\n output.print(idx);\n if (increment && (!(is_node_type(increment, AST_Unary)) || increment.expression.value !== "1")) {\n if (is_node_type(increment, AST_Unary)) {\n output.print("-=");\n increment.expression.print(output);\n } else {\n output.print("+=");\n increment.print(output);\n }\n } else {\n if (is_node_type(increment, AST_Unary)) {\n output.print("--");\n } else {\n output.print("++");\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n } else if (is_simple_for_in(self)) {\n output.print("for");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.init.print(output);\n output.space();\n output.print("in");\n output.space();\n self.object.args[0].print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n } else {\n if (output.options.js_version === 5) {\n output.assign("var RS_Iter" + output.index_counter);\n output.print("RS_Iterable");\n output.with_parens(write_object);\n output.semicolon();\n output.newline();\n output.indent();\n output.print("for");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("var");\n output.space();\n output.assign("RS_Index" + output.index_counter);\n output.print("0");\n output.semicolon();\n output.space();\n output.print("RS_Index" + output.index_counter);\n output.space();\n output.print("<");\n output.space();\n output.print("RS_Iter" + output.index_counter + ".length");\n output.semicolon();\n output.space();\n output.print("RS_Index" + output.index_counter + "++");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n } else {\n itervar = "RS_Iter" + output.index_counter;\n output.assign("var " + itervar);\n write_object();\n output.end_statement();\n init_es6_itervar(output, itervar);\n output.indent();\n output.spaced("for", "(var", "RS_Index" + output.index_counter, "of", itervar + ")");\n }\n }\n output.space();\n self._do_print_body(output);\n };\n if (!print_for_in.__argnames__) Object.defineProperties(print_for_in, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.loops"}\n });\n\n function print_list_comprehension(self, output) {\n var tname, result_obj, is_generator, es5, add_to_result, push_func;\n tname = self.constructor.name.slice(4);\n result_obj = (RS_expr_temp = (function(){\n var RS_d = Object.create(null);\n RS_d["ListComprehension"] = "[]";\n RS_d["DictComprehension"] = (self.is_jshash) ? "Object.create(null)" : "{}";\n RS_d["SetComprehension"] = "RS_set()";\n return RS_d;\n }).call(this))[(typeof tname === "number" && tname < 0) ? RS_expr_temp.length + tname : tname];\n is_generator = tname === "GeneratorComprehension";\n es5 = output.options.js_version === 5;\n if (tname === "DictComprehension") {\n if (self.is_pydict) {\n result_obj = "RS_dict()";\n add_to_result = (function() {\n var RS_anonfunc = function (output) {\n output.indent();\n output.print("RS_Result.set");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.statement.print(output);\n [output.space(), output.print(","), output.space()];\n output.with_parens((function() {\n var RS_anonfunc = function () {\n if (self.value_statement.constructor === AST_Seq) {\n output.with_square((function() {\n var RS_anonfunc = function () {\n self.value_statement.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n } else {\n self.value_statement.print(output);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })();\n } else {\n add_to_result = (function() {\n var RS_anonfunc = function (output) {\n output.indent();\n output.print("RS_Result");\n output.with_square((function() {\n var RS_anonfunc = function () {\n self.statement.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n [output.space(), output.print("="), output.space()];\n output.with_parens((function() {\n var RS_anonfunc = function () {\n if (self.value_statement.constructor === AST_Seq) {\n output.with_square((function() {\n var RS_anonfunc = function () {\n self.value_statement.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n } else {\n self.value_statement.print(output);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })();\n }\n } else {\n push_func = "RS_Result." + ((self.constructor === AST_ListComprehension) ? "push" : "add");\n if (is_generator) {\n push_func = "yield ";\n }\n add_to_result = (function() {\n var RS_anonfunc = function (output) {\n output.indent();\n output.print(push_func);\n output.with_parens((function() {\n var RS_anonfunc = function () {\n if (self.statement.constructor === AST_Seq) {\n output.with_square((function() {\n var RS_anonfunc = function () {\n self.statement.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n } else {\n self.statement.print(output);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })();\n }\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("function");\n output.print("()");\n output.space();\n output.with_block((function() {\n var RS_anonfunc = function () {\n var body_out, previous_indentation, i, transpiled, ci;\n body_out = output;\n if (is_generator) {\n if (es5) {\n body_out = new OutputStream((function(){\n var RS_d = Object.create(null);\n RS_d["beautify"] = true;\n return RS_d;\n }).call(this));\n }\n body_out.indent();\n [body_out.print("function* js_generator()"), body_out.space(), body_out.print("{")];\n body_out.newline();\n previous_indentation = output.indentation();\n output.set_indentation(output.next_indent());\n }\n body_out.indent();\n body_out.assign("var RS_Iter");\n if (es5) {\n body_out.print("RS_Iterable");\n body_out.with_parens((function() {\n var RS_anonfunc = function () {\n self.object.print(body_out);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n } else {\n self.object.print(body_out);\n }\n if (result_obj) {\n body_out.comma();\n body_out.assign("RS_Result");\n body_out.print(result_obj);\n }\n if (is_node_type(self.init, AST_Array)) {\n var RS_Iter88 = RS_Iterable(self.init.elements);\n for (var RS_Index88 = 0; RS_Index88 < RS_Iter88.length; RS_Index88++) {\n i = RS_Iter88[RS_Index88];\n body_out.comma();\n i.print(body_out);\n }\n } else {\n body_out.comma();\n self.init.print(body_out);\n }\n body_out.end_statement();\n if (!es5) {\n init_es6_itervar(body_out, "RS_Iter");\n }\n body_out.indent();\n body_out.print("for");\n body_out.space();\n body_out.with_parens((function() {\n var RS_anonfunc = function () {\n if (es5) {\n body_out.print("var");\n body_out.space();\n body_out.assign("RS_Index");\n body_out.print("0");\n body_out.semicolon();\n body_out.space();\n body_out.print("RS_Index");\n body_out.space();\n body_out.print("<");\n body_out.space();\n body_out.print("RS_Iter.length");\n body_out.semicolon();\n body_out.space();\n body_out.print("RS_Index++");\n } else {\n body_out.spaced("var", "RS_Index", "of", "RS_Iter");\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n body_out.space();\n body_out.with_block((function() {\n var RS_anonfunc = function () {\n var itervar, flat;\n body_out.indent();\n itervar = (es5) ? "RS_Iter[RS_Index]" : "RS_Index";\n if (is_node_type(self.init, AST_Array)) {\n flat = self.init.flatten();\n body_out.assign("RS_unpack");\n if (flat.length > self.init.elements.length) {\n body_out.print("RS_flatten(" + itervar + ")");\n } else {\n body_out.print(itervar);\n }\n body_out.end_statement();\n unpack_tuple(flat, body_out);\n } else {\n body_out.assign(self.init);\n body_out.print(itervar);\n body_out.end_statement();\n }\n if (self.condition) {\n body_out.indent();\n body_out.print("if");\n body_out.space();\n body_out.with_parens((function() {\n var RS_anonfunc = function () {\n self.condition.print(body_out);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n body_out.space();\n body_out.with_block((function() {\n var RS_anonfunc = function () {\n add_to_result(body_out);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n body_out.newline();\n } else {\n add_to_result(body_out);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n body_out.newline();\n if (self.constructor === AST_ListComprehension) {\n body_out.indent();\n body_out.spaced("RS_Result", "=", "RS_list_constructor(RS_Result)");\n body_out.end_statement();\n }\n if (!is_generator) {\n body_out.indent();\n body_out.print("return RS_Result");\n body_out.end_statement();\n }\n if (is_generator) {\n output.set_indentation(previous_indentation);\n [body_out.newline(), body_out.indent(), body_out.print("}")];\n if (es5) {\n transpiled = regenerate(body_out.get(), output.options.beautify).replace(/regeneratorRuntime.(wrap|mark)/g, "RS_regenerator.regeneratorRuntime.$1");\n if (output.options.beautify) {\n ci = output.make_indent(0);\n transpiled = (function() {\n var RS_Iter = RS_Iterable(transpiled.split("\\n")), RS_Result = [], x;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n x = RS_Iter[RS_Index];\n RS_Result.push(ci + x);\n }\n RS_Result = RS_list_constructor(RS_Result);\n return RS_Result;\n })().join("\\n");\n }\n output.print(transpiled);\n }\n [output.newline(), output.indent()];\n output.spaced("var", "result", "=", "js_generator.call(this)");\n output.end_statement();\n output.indent();\n output.spaced("result.send", "=", "result.next");\n output.end_statement();\n output.indent();\n output.spaced("return", "result");\n output.end_statement();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.loops"}\n });\n return RS_anonfunc;\n })());\n output.print("()");\n };\n if (!print_list_comprehension.__argnames__) Object.defineProperties(print_list_comprehension, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.loops"}\n });\n\n RS_modules["output.loops"].unpack_tuple = unpack_tuple;\n RS_modules["output.loops"].print_do_loop = print_do_loop;\n RS_modules["output.loops"].print_while_loop = print_while_loop;\n RS_modules["output.loops"].is_simple_for_in = is_simple_for_in;\n RS_modules["output.loops"].is_simple_for = is_simple_for;\n RS_modules["output.loops"].print_for_loop_body = print_for_loop_body;\n RS_modules["output.loops"].init_es6_itervar = init_es6_itervar;\n RS_modules["output.loops"].print_for_in = print_for_in;\n RS_modules["output.loops"].print_list_comprehension = print_list_comprehension;\n })();\n\n (function(){\n var __name__ = "output.operators";\n var comparators, function_ops, after_map;\n var AST_Array = RS_modules.ast.AST_Array;\n var AST_Assign = RS_modules.ast.AST_Assign;\n var AST_BaseCall = RS_modules.ast.AST_BaseCall;\n var AST_Binary = RS_modules.ast.AST_Binary;\n var AST_Conditional = RS_modules.ast.AST_Conditional;\n var AST_ItemAccess = RS_modules.ast.AST_ItemAccess;\n var AST_Number = RS_modules.ast.AST_Number;\n var AST_Object = RS_modules.ast.AST_Object;\n var AST_Return = RS_modules.ast.AST_Return;\n var AST_Seq = RS_modules.ast.AST_Seq;\n var AST_Set = RS_modules.ast.AST_Set;\n var AST_SimpleStatement = RS_modules.ast.AST_SimpleStatement;\n var AST_Statement = RS_modules.ast.AST_Statement;\n var AST_String = RS_modules.ast.AST_String;\n var AST_Sub = RS_modules.ast.AST_Sub;\n var AST_Symbol = RS_modules.ast.AST_Symbol;\n var AST_SymbolRef = RS_modules.ast.AST_SymbolRef;\n var AST_Unary = RS_modules.ast.AST_Unary;\n var is_node_type = RS_modules.ast.is_node_type;\n\n var unpack_tuple = RS_modules["output.loops"].unpack_tuple;\n\n function print_getattr(self, output, skip_expression) {\n var expr;\n if (!skip_expression) {\n expr = self.expression;\n expr.print(output);\n }\n if (is_node_type(expr, AST_Number) && expr.value >= 0) {\n if (!/[xa-f.]/i.test(output.last())) {\n output.print(".");\n }\n }\n output.print(".");\n output.print_name(self.property);\n };\n if (!print_getattr.__argnames__) Object.defineProperties(print_getattr, {\n __argnames__ : {value: ["self", "output", "skip_expression"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_getitem(self, output) {\n var expr, prop, is_negative_number, is_repeatable;\n expr = self.expression;\n prop = self.property;\n if (is_node_type(prop, AST_Number) || is_node_type(prop, AST_String) || is_node_type(prop, AST_SymbolRef) && prop.name && prop.name.startsWith("RS_")) {\n expr.print(output);\n [output.print("["), prop.print(output), output.print("]")];\n return;\n }\n is_negative_number = is_node_type(prop, AST_Unary) && prop.operator === "-" && is_node_type(prop.expression, AST_Number);\n is_repeatable = is_node_type(expr, AST_SymbolRef);\n if (is_repeatable) {\n expr.print(output);\n } else {\n [output.spaced("(RS_expr_temp", "=", expr), output.print(")")];\n expr = (function(){\n var RS_d = Object.create(null);\n RS_d["print"] = (function() {\n var RS_anonfunc = function () {\n output.print("RS_expr_temp");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n }\n if (is_negative_number) {\n [output.print("["), expr.print(output), output.print(".length"), prop.print(output), \n output.print("]")];\n return;\n }\n is_repeatable = is_node_type(prop, AST_SymbolRef);\n if (is_repeatable) {\n output.spaced("[(typeof", prop, "===", "\\"number\\"", "&&", prop);\n [output.spaced("", "<", "0)", "?", expr), output.spaced(".length", "+", prop, ":", prop)];\n output.print("]");\n } else {\n [output.print("[RS_bound_index("), prop.print(output), output.comma(), expr.print(output), \n output.print(")]")];\n }\n };\n if (!print_getitem.__argnames__) Object.defineProperties(print_getitem, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_rich_getitem(self, output) {\n var func;\n func = "RS_" + ((self.assignment) ? "setitem" : "getitem");\n output.print(func + "(");\n [self.expression.print(output), output.comma(), self.property.print(output)];\n if (self.assignment) {\n [output.comma(), self.assignment.print(output)];\n }\n output.print(")");\n };\n if (!print_rich_getitem.__argnames__) Object.defineProperties(print_rich_getitem, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_splice_assignment(self, output) {\n output.print("RS_splice(");\n [self.expression.print(output), output.comma(), self.assignment.print(output), output.comma()];\n (self.property) ? self.property.print(output) : output.print("0");\n if (self.property2) {\n output.comma();\n self.property2.print(output);\n }\n output.print(")");\n };\n if (!print_splice_assignment.__argnames__) Object.defineProperties(print_splice_assignment, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_delete(self, output) {\n if (is_node_type(self, AST_Symbol)) {\n [output.assign(self), output.print("undefined")];\n } else if (is_node_type(self, AST_Sub) || is_node_type(self, AST_ItemAccess)) {\n [output.print("RS_delitem("), self.expression.print(output), output.comma(), self.property.print(output), \n output.print(")")];\n } else {\n output.spaced("delete", self);\n }\n };\n if (!print_delete.__argnames__) Object.defineProperties(print_delete, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_unary_prefix(self, output) {\n var op;\n op = self.operator;\n if (op === "delete") {\n return print_delete(self.expression, output);\n }\n output.print(op);\n if (/^[a-z]/i.test(op)) {\n output.space();\n }\n if (self.parenthesized) {\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.expression.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })());\n } else {\n self.expression.print(output);\n }\n };\n if (!print_unary_prefix.__argnames__) Object.defineProperties(print_unary_prefix, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function write_instanceof(left, right, output) {\n function do_many(vals) {\n [output.print("RS_instanceof.apply(null,"), output.space()];\n [output.print("["), left.print(output), output.comma()];\n for (var i = 0; i < vals.length; i++) {\n vals[(typeof i === "number" && i < 0) ? vals.length + i : i].print(output);\n if (i !== vals.length - 1) {\n output.comma();\n }\n }\n output.print("])");\n };\n if (!do_many.__argnames__) Object.defineProperties(do_many, {\n __argnames__ : {value: ["vals"]},\n __module__ : {value: "output.operators"}\n });\n\n if (is_node_type(right, AST_Seq)) {\n do_many(right.to_array());\n } else if (is_node_type(right, AST_Array)) {\n do_many(right.elements);\n } else {\n output.print("RS_instanceof(");\n [left.print(output), output.comma(), right.print(output), output.print(")")];\n }\n };\n if (!write_instanceof.__argnames__) Object.defineProperties(write_instanceof, {\n __argnames__ : {value: ["left", "right", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function write_smart_equality(self, output) {\n function is_ok(x) {\n return !((is_node_type(x, AST_Array) || is_node_type(x, AST_Set) || is_node_type(x, AST_Object) || is_node_type(x, AST_Statement) || is_node_type(x, AST_Binary) || is_node_type(x, AST_Conditional) || is_node_type(x, AST_BaseCall)));\n };\n if (!is_ok.__argnames__) Object.defineProperties(is_ok, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "output.operators"}\n });\n\n if (is_ok(self.left) && is_ok(self.right)) {\n if (self.operator === "==") {\n output.print("(");\n output.spaced(self.left, "===", self.right, "||", "typeof", self.left, "===", "\\"object\\"", "&&", "RS_equals(");\n [self.left.print(output), output.print(","), output.space(), self.right.print(output), \n output.print("))")];\n } else {\n output.print("(");\n output.spaced(self.left, "!==", self.right, "&&", "(typeof", self.left, "!==", "\\"object\\"", "||", "RS_not_equals(");\n [self.left.print(output), output.print(","), output.space(), self.right.print(output), \n output.print(")))")];\n }\n } else {\n output.print("RS_" + ((self.operator === "==") ? "equals(" : "not_equals("));\n [self.left.print(output), output.print(","), output.space(), self.right.print(output), \n output.print(")")];\n }\n };\n if (!write_smart_equality.__argnames__) Object.defineProperties(write_smart_equality, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n comparators = (function(){\n var RS_d = Object.create(null);\n RS_d["<"] = true;\n RS_d[">"] = true;\n RS_d["<="] = true;\n RS_d[">="] = true;\n return RS_d;\n }).call(this);\n function_ops = (function(){\n var RS_d = Object.create(null);\n RS_d["in"] = "RS_in";\n RS_d["nin"] = "!RS_in";\n return RS_d;\n }).call(this);\n function print_binary_op(self, output) {\n var leftvar, left, nan_check;\n if (function_ops[RS_bound_index(self.operator, function_ops)]) {\n output.print(function_ops[RS_bound_index(self.operator, function_ops)]);\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.left.print(output);\n output.comma();\n self.right.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })());\n } else if (comparators[RS_bound_index(self.operator, comparators)] && is_node_type(self.left, AST_Binary) && comparators[RS_bound_index(self.left.operator, comparators)]) {\n if (is_node_type(self.left.right, AST_Symbol)) {\n self.left.print(output);\n leftvar = self.left.right.name;\n } else {\n self.left.left.print(output);\n output.space();\n output.print(self.left.operator);\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.assign("RS_cond_temp");\n self.left.right.print(output);\n leftvar = "RS_cond_temp";\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })());\n }\n output.space();\n output.print("&&");\n output.space();\n output.print(leftvar);\n output.space();\n output.print(self.operator);\n output.space();\n self.right.print(output);\n } else if (self.operator === "//") {\n output.print("Math.floor");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.left.print(output);\n output.space();\n output.print("/");\n output.space();\n self.right.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })());\n } else if (self.operator === "**") {\n left = self.left;\n if (is_node_type(self.left, AST_Unary) && !self.left.parenthesized) {\n left = self.left.expression;\n output.print(self.left.operator);\n }\n if (output.options.js_version > 6) {\n [output.print("(("), left.print(output), output.spaced(")", "**", "("), self.right.print(output), \n output.print("))")];\n } else {\n [output.print("Math.pow("), left.print(output), output.comma(), self.right.print(output), \n output.print(")")];\n }\n } else if (self.operator === "==" || self.operator === "!=") {\n write_smart_equality(self, output);\n } else if (self.operator === "instanceof") {\n write_instanceof(self.left, self.right, output);\n } else if (self.operator === "*" && is_node_type(self.left, AST_String)) {\n [self.left.print(output), output.print(".repeat("), self.right.print(output), output.print(")")];\n } else if (self.operator === "===" || self.operator === "!==") {\n nan_check = null;\n if (is_node_type(self.right, AST_Symbol) && self.right.name === "NaN") {\n nan_check = self.left;\n }\n if (is_node_type(self.left, AST_Symbol) && self.left.name === "NaN") {\n nan_check = self.right;\n }\n if (nan_check !== null) {\n output.spaced(nan_check, (self.operator === "===") ? "!==" : "===", nan_check);\n } else {\n output.spaced(self.left, self.operator, self.right);\n }\n } else {\n output.spaced(self.left, self.operator, self.right);\n }\n };\n if (!print_binary_op.__argnames__) Object.defineProperties(print_binary_op, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n after_map = (function(){\n var RS_d = Object.create(null);\n RS_d["."] = "d";\n RS_d["("] = "c";\n RS_d["["] = "d";\n RS_d["g"] = "g";\n RS_d["null"] = "n";\n return RS_d;\n }).call(this);\n function print_existential(self, output) {\n var key, after;\n key = (self.after === null || typeof self.after === "string") ? after_map[RS_bound_index(self.after, after_map)] : "e";\n if (is_node_type(self.expression, AST_SymbolRef)) {\n if (key === "n") {\n output.spaced("(typeof", self.expression, "!==", "\\"undefined\\"", "&&", self.expression, "!==", "null)");\n return;\n }\n if (key === "c") {\n output.spaced("(typeof", self.expression, "===", "\\"function\\"", "?", self.expression, ":", "(function(){return undefined;}))");\n return;\n }\n after = self.after;\n if (key === "d") {\n after = "Object.create(null)";\n } else if (key === "g") {\n after = "{__getitem__:function(){return undefined;}}";\n }\n output.spaced("(typeof", self.expression, "!==", "\\"undefined\\"", "&&", self.expression, "!==", "null", "?", self.expression, ":", after);\n output.print(")");\n return;\n }\n output.print("RS_exists." + key + "(");\n self.expression.print(output);\n if (key === "e") {\n [output.comma(), self.after.print(output)];\n }\n output.print(")");\n };\n if (!print_existential.__argnames__) Object.defineProperties(print_existential, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_assignment(self, output) {\n var flattened, left, flat;\n flattened = false;\n left = self.left;\n if (is_node_type(left, AST_Seq)) {\n left = new AST_Array((function(){\n var RS_d = Object.create(null);\n RS_d["elements"] = [left.car, left.cdr];\n return RS_d;\n }).call(this));\n }\n if (is_node_type(left, AST_Array)) {\n flat = left.flatten();\n flattened = flat.length > left.elements.length;\n output.print("RS_unpack");\n } else {\n left.print(output);\n }\n output.space();\n output.print(self.operator);\n output.space();\n if (flattened) {\n output.print("RS_flatten");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.right.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })());\n } else {\n self.right.print(output);\n }\n if (is_node_type(left, AST_Array)) {\n output.end_statement();\n if (!is_node_type(self.right, AST_Seq) && !is_node_type(self.right, AST_Array)) {\n output.assign("RS_unpack");\n [output.print("RS_unpack_asarray(" + flat.length), output.comma(), output.print("RS_unpack)")];\n output.end_statement();\n }\n unpack_tuple(flat, output, true);\n }\n };\n if (!print_assignment.__argnames__) Object.defineProperties(print_assignment, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_assign(self, output) {\n var RS_unpack, left_hand_sides, rhs, is_compound_assign, lhs, temp_rhs;\n if (self.operator === "//=") {\n output.assign(self.left);\n output.print("Math.floor");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.left.print(output);\n output.space();\n output.print("/");\n output.space();\n self.right.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })());\n return;\n }\n if (self.operator === "=" && self.is_chained()) {\n RS_unpack = self.traverse_chain();\nRS_unpack = RS_unpack_asarray(2, RS_unpack);\n left_hand_sides = RS_unpack[0];\n rhs = RS_unpack[1];\n is_compound_assign = false;\n var RS_Iter89 = RS_Iterable(left_hand_sides);\n for (var RS_Index89 = 0; RS_Index89 < RS_Iter89.length; RS_Index89++) {\n lhs = RS_Iter89[RS_Index89];\n if (is_node_type(lhs, AST_Seq) || is_node_type(lhs, AST_Array)) {\n is_compound_assign = true;\n break;\n }\n }\n if (is_compound_assign) {\n temp_rhs = new AST_SymbolRef((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "RS_chain_assign_temp";\n return RS_d;\n }).call(this));\n print_assignment(new AST_Assign((function(){\n var RS_d = Object.create(null);\n RS_d["left"] = temp_rhs;\n RS_d["operator"] = "=";\n RS_d["right"] = rhs;\n return RS_d;\n }).call(this)), output);\n var RS_Iter90 = RS_Iterable(left_hand_sides);\n for (var RS_Index90 = 0; RS_Index90 < RS_Iter90.length; RS_Index90++) {\n lhs = RS_Iter90[RS_Index90];\n [output.end_statement(), output.indent()];\n print_assignment(new AST_Assign((function(){\n var RS_d = Object.create(null);\n RS_d["left"] = lhs;\n RS_d["right"] = temp_rhs;\n RS_d["operator"] = self.operator;\n return RS_d;\n }).call(this)), output);\n }\n } else {\n var RS_Iter91 = RS_Iterable(left_hand_sides);\n for (var RS_Index91 = 0; RS_Index91 < RS_Iter91.length; RS_Index91++) {\n lhs = RS_Iter91[RS_Index91];\n output.spaced(lhs, "=", "");\n }\n rhs.print(output);\n }\n } else {\n print_assignment(self, output);\n }\n };\n if (!print_assign.__argnames__) Object.defineProperties(print_assign, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_conditional(self, output, condition, consequent, alternative) {\n var RS_unpack;\n RS_unpack = [self.condition, self.consequent, self.alternative];\n condition = RS_unpack[0];\n consequent = RS_unpack[1];\n alternative = RS_unpack[2];\n output.with_parens((function() {\n var RS_anonfunc = function () {\n condition.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })());\n output.space();\n output.print("?");\n output.space();\n consequent.print(output);\n output.space();\n output.colon();\n alternative.print(output);\n };\n if (!print_conditional.__argnames__) Object.defineProperties(print_conditional, {\n __argnames__ : {value: ["self", "output", "condition", "consequent", "alternative"]},\n __module__ : {value: "output.operators"}\n });\n\n function print_seq(output) {\n var self, p, print_seq;\n self = this;\n p = output.parent();\n print_seq = (function() {\n var RS_anonfunc = function () {\n self.car.print(output);\n if (self.cdr) {\n output.comma();\n if (output.should_break()) {\n output.newline();\n output.indent();\n }\n self.cdr.print(output);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.operators"}\n });\n return RS_anonfunc;\n })();\n if (is_node_type(p, AST_Binary) || is_node_type(p, AST_Return) || is_node_type(p, AST_Array) || is_node_type(p, AST_BaseCall) || is_node_type(p, AST_SimpleStatement)) {\n output.with_square(print_seq);\n } else {\n print_seq();\n }\n };\n if (!print_seq.__argnames__) Object.defineProperties(print_seq, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.operators"}\n });\n\n RS_modules["output.operators"].comparators = comparators;\n RS_modules["output.operators"].function_ops = function_ops;\n RS_modules["output.operators"].after_map = after_map;\n RS_modules["output.operators"].print_getattr = print_getattr;\n RS_modules["output.operators"].print_getitem = print_getitem;\n RS_modules["output.operators"].print_rich_getitem = print_rich_getitem;\n RS_modules["output.operators"].print_splice_assignment = print_splice_assignment;\n RS_modules["output.operators"].print_delete = print_delete;\n RS_modules["output.operators"].print_unary_prefix = print_unary_prefix;\n RS_modules["output.operators"].write_instanceof = write_instanceof;\n RS_modules["output.operators"].write_smart_equality = write_smart_equality;\n RS_modules["output.operators"].print_binary_op = print_binary_op;\n RS_modules["output.operators"].print_existential = print_existential;\n RS_modules["output.operators"].print_assignment = print_assignment;\n RS_modules["output.operators"].print_assign = print_assign;\n RS_modules["output.operators"].print_conditional = print_conditional;\n RS_modules["output.operators"].print_seq = print_seq;\n })();\n\n (function(){\n var __name__ = "output.functions";\n var anonfunc, module_name;\n var AST_ClassCall = RS_modules.ast.AST_ClassCall;\n var AST_New = RS_modules.ast.AST_New;\n var has_calls = RS_modules.ast.has_calls;\n var AST_Dot = RS_modules.ast.AST_Dot;\n var AST_SymbolRef = RS_modules.ast.AST_SymbolRef;\n var is_node_type = RS_modules.ast.is_node_type;\n\n var OutputStream = RS_modules["output.stream"].OutputStream;\n\n var print_bracketed = RS_modules["output.statements"].print_bracketed;\n\n var create_doctring = RS_modules["output.utils"].create_doctring;\n\n var print_getattr = RS_modules["output.operators"].print_getattr;\n\n anonfunc = "RS_anonfunc";\n module_name = "null";\n function set_module_name(x) {\n module_name = (x) ? "\\"" + x + "\\"" : "null";\n };\n if (!set_module_name.__argnames__) Object.defineProperties(set_module_name, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "output.functions"}\n });\n\n function decorate(decorators, output, func) {\n var pos;\n pos = 0;\n function wrap() {\n if (pos < decorators.length) {\n decorators[(typeof pos === "number" && pos < 0) ? decorators.length + pos : pos].expression.print(output);\n pos += 1;\n output.with_parens((function() {\n var RS_anonfunc = function () {\n wrap();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })());\n } else {\n func();\n }\n };\n if (!wrap.__module__) Object.defineProperties(wrap, {\n __module__ : {value: "output.functions"}\n });\n\n wrap();\n };\n if (!decorate.__argnames__) Object.defineProperties(decorate, {\n __argnames__ : {value: ["decorators", "output", "func"]},\n __module__ : {value: "output.functions"}\n });\n\n function function_args(argnames, output, strip_first) {\n output.with_parens((function() {\n var RS_anonfunc = function () {\n var RS_unpack, i, arg;\n if (argnames && argnames.length && (argnames.is_simple_func === true || argnames.is_simple_func === undefined)) {\n var RS_Iter92 = RS_Iterable(enumerate((strip_first) ? argnames.slice(1) : argnames));\n for (var RS_Index92 = 0; RS_Index92 < RS_Iter92.length; RS_Index92++) {\n RS_unpack = RS_Iter92[RS_Index92];\n i = RS_unpack[0];\n arg = RS_unpack[1];\n if (i) {\n output.comma();\n }\n arg.print(output);\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })());\n output.space();\n };\n if (!function_args.__argnames__) Object.defineProperties(function_args, {\n __argnames__ : {value: ["argnames", "output", "strip_first"]},\n __module__ : {value: "output.functions"}\n });\n\n function function_preamble(node, output, offset) {\n var a, fname, kw, i, RS_unpack, c, arg, dname, nargs;\n a = node.argnames;\n if (!a || a.is_simple_func) {\n return;\n }\n fname = (node.name) ? node.name.name : anonfunc;\n kw = "arguments[arguments.length-1]";\n var RS_Iter93 = RS_Iterable(enumerate(a));\n for (var RS_Index93 = 0; RS_Index93 < RS_Iter93.length; RS_Index93++) {\n RS_unpack = RS_Iter93[RS_Index93];\n c = RS_unpack[0];\n arg = RS_unpack[1];\n i = c - offset;\n if (i >= 0) {\n output.indent();\n output.print("var");\n output.space();\n output.assign(arg);\n if (Object.prototype.hasOwnProperty.call(a.defaults, arg.name)) {\n output.spaced("(arguments[" + i + "]", "===", "undefined", "||", "(", i, "===", "arguments.length-1", "&&", kw, "!==", "null", "&&", "typeof", kw, "===", "\\"object\\"", "&&", kw, "[RS_kwargs_symbol]", "===", "true))", "?", "");\n [output.print(fname + ".__defaults__."), arg.print(output)];\n [output.space(), output.print(":"), output.space()];\n } else {\n output.spaced("(", i, "===", "arguments.length-1", "&&", kw, "!==", "null", "&&", "typeof", kw, "===", "\\"object\\"", "&&", kw, "[RS_kwargs_symbol]", "===", "true)", "?", "undefined", ":", "");\n }\n output.print("arguments[" + i + "]");\n output.end_statement();\n }\n }\n if (a.kwargs || a.has_defaults) {\n kw = (a.kwargs) ? a.kwargs.name : "RS_kwargs_obj";\n output.indent();\n output.spaced("var", kw, "=", "arguments[arguments.length-1]");\n output.end_statement();\n output.indent();\n output.spaced("if", "(" + kw, "===", "null", "||", "typeof", kw, "!==", "\\"object\\"", "||", kw, "[RS_kwargs_symbol]", "!==", "true)", kw, "=", "{}");\n output.end_statement();\n if (a.has_defaults) {\n var RS_Iter94 = RS_Iterable(Object.keys(a.defaults));\n for (var RS_Index94 = 0; RS_Index94 < RS_Iter94.length; RS_Index94++) {\n dname = RS_Iter94[RS_Index94];\n output.indent();\n output.spaced("if", "(Object.prototype.hasOwnProperty.call(" + kw + ",", "\\"" + dname + "\\"))");\n output.with_block((function() {\n var RS_anonfunc = function () {\n output.indent();\n output.spaced(dname, "=", kw + "." + dname);\n output.end_statement();\n if (a.kwargs) {\n output.indent();\n output.spaced("delete", kw + "." + dname);\n output.end_statement();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })());\n output.newline();\n }\n }\n }\n if (a.starargs !== undefined) {\n nargs = a.length - offset;\n output.indent();\n output.spaced("var", a.starargs.name, "=", "Array.prototype.slice.call(arguments,", nargs + ")");\n output.end_statement();\n output.indent();\n output.spaced("if", "(" + kw, "!==", "null", "&&", "typeof", kw, "===", "\\"object\\"", "&&", kw, "[RS_kwargs_symbol]", "===", "true)", a.starargs.name);\n output.print(".pop()");\n output.end_statement();\n }\n };\n if (!function_preamble.__argnames__) Object.defineProperties(function_preamble, {\n __argnames__ : {value: ["node", "output", "offset"]},\n __module__ : {value: "output.functions"}\n });\n\n function has_annotations(self) {\n var arg;\n if (self.return_annotation) {\n return true;\n }\n var RS_Iter95 = RS_Iterable(self.argnames);\n for (var RS_Index95 = 0; RS_Index95 < RS_Iter95.length; RS_Index95++) {\n arg = RS_Iter95[RS_Index95];\n if (arg.annotation) {\n return true;\n }\n }\n return false;\n };\n if (!has_annotations.__argnames__) Object.defineProperties(has_annotations, {\n __argnames__ : {value: ["self"]},\n __module__ : {value: "output.functions"}\n });\n\n function function_annotation(self, output, strip_first, name) {\n var fname, props, defaults, dkeys, names;\n fname = name || ((self.name) ? self.name.name : anonfunc);\n props = Object.create(null);\n if (has_annotations(self)) {\n props.__annotations__ = (function() {\n var RS_anonfunc = function () {\n var RS_unpack, i, arg;\n output.print("{");\n if (self.argnames && self.argnames.length) {\n var RS_Iter96 = RS_Iterable(enumerate(self.argnames));\n for (var RS_Index96 = 0; RS_Index96 < RS_Iter96.length; RS_Index96++) {\n RS_unpack = RS_Iter96[RS_Index96];\n i = RS_unpack[0];\n arg = RS_unpack[1];\n if (arg.annotation) {\n arg.print(output);\n [output.print(":"), output.space()];\n arg.annotation.print(output);\n if (i < self.argnames.length - 1 || self.return_annotation) {\n output.comma();\n }\n }\n }\n }\n if (self.return_annotation) {\n [output.print("return:"), output.space()];\n self.return_annotation.print(output);\n }\n output.print("}");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })();\n }\n defaults = self.argnames.defaults;\n dkeys = Object.keys(self.argnames.defaults);\n if (dkeys.length) {\n props.__defaults__ = (function() {\n var RS_anonfunc = function () {\n var RS_unpack, i, k;\n output.print("{");\n var RS_Iter97 = RS_Iterable(enumerate(dkeys));\n for (var RS_Index97 = 0; RS_Index97 < RS_Iter97.length; RS_Index97++) {\n RS_unpack = RS_Iter97[RS_Index97];\n i = RS_unpack[0];\n k = RS_unpack[1];\n [output.print(k + ":"), defaults[(typeof k === "number" && k < 0) ? defaults.length + k : k].print(output)];\n if (i !== dkeys.length - 1) {\n output.comma();\n }\n }\n output.print("}");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })();\n }\n if (!self.argnames.is_simple_func) {\n props.__handles_kwarg_interpolation__ = (function() {\n var RS_anonfunc = function () {\n output.print("true");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })();\n }\n if (self.argnames.length > ((strip_first) ? 1 : 0)) {\n props.__argnames__ = (function() {\n var RS_anonfunc = function () {\n var RS_unpack, i, arg;\n output.print("[");\n var RS_Iter98 = RS_Iterable(enumerate(self.argnames));\n for (var RS_Index98 = 0; RS_Index98 < RS_Iter98.length; RS_Index98++) {\n RS_unpack = RS_Iter98[RS_Index98];\n i = RS_unpack[0];\n arg = RS_unpack[1];\n if (strip_first && i === 0) {\n continue;\n }\n output.print(JSON.stringify(arg.name));\n if (i !== self.argnames.length - 1) {\n output.comma();\n }\n }\n output.print("]");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })();\n }\n if (output.options.keep_docstrings && self.docstrings && self.docstrings.length) {\n props.__doc__ = (function() {\n var RS_anonfunc = function () {\n output.print(JSON.stringify(create_doctring(self.docstrings)));\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })();\n }\n props.__module__ = (function() {\n var RS_anonfunc = function () {\n output.print(module_name);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })();\n names = Object.keys(props);\n output.indent();\n output.spaced("if", "(!" + fname + "." + names[0] + ")", "Object.defineProperties(" + fname);\n output.comma();\n output.with_block((function() {\n var RS_anonfunc = function () {\n var name;\n for (var i = 0; i < names.length; i++) {\n name = names[(typeof i === "number" && i < 0) ? names.length + i : i];\n [output.indent(), output.spaced(name, ":", "{value:", ""), props[(typeof name === "number" && name < 0) ? props.length + name : name](), \n output.print("}")];\n if (i < names.length - 1) {\n output.print(",");\n }\n output.newline();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })());\n [output.print(")"), output.end_statement()];\n };\n if (!function_annotation.__argnames__) Object.defineProperties(function_annotation, {\n __argnames__ : {value: ["self", "output", "strip_first", "name"]},\n __module__ : {value: "output.functions"}\n });\n\n function function_definition(self, output, strip_first, as_expression) {\n var orig_indent;\n as_expression = as_expression || self.is_expression || self.is_anonymous;\n if (as_expression) {\n orig_indent = output.indentation();\n output.set_indentation(output.next_indent());\n [output.spaced("(function()", "{"), output.newline()];\n [output.indent(), output.spaced("var", anonfunc, "="), output.space()];\n }\n [output.print("function"), output.space()];\n if (self.name) {\n self.name.print(output);\n }\n if (self.is_generator) {\n [output.print("()"), output.space()];\n output.with_block((function() {\n var RS_anonfunc = function () {\n var temp, transpiled, ci;\n if (output.options.js_version >= 6) {\n output.indent();\n output.print("function* js_generator");\n function_args(self.argnames, output, strip_first);\n print_bracketed(self, output, true, function_preamble);\n } else {\n temp = new OutputStream((function(){\n var RS_d = Object.create(null);\n RS_d["beautify"] = true;\n return RS_d;\n }).call(this));\n temp.print("function* js_generator");\n function_args(self.argnames, temp, strip_first);\n print_bracketed(self, temp, true, function_preamble);\n transpiled = regenerate(temp.get(), output.options.beautify).replace(/regeneratorRuntime.(wrap|mark)/g, "RS_regenerator.regeneratorRuntime.$1");\n if (output.options.beautify) {\n ci = output.make_indent(0);\n transpiled = (function() {\n var RS_Iter = RS_Iterable(transpiled.split("\\n")), RS_Result = [], x;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n x = RS_Iter[RS_Index];\n RS_Result.push(ci + x);\n }\n RS_Result = RS_list_constructor(RS_Result);\n return RS_Result;\n })().join("\\n");\n }\n output.print(transpiled);\n }\n output.newline();\n output.indent();\n output.spaced("var", "result", "=", "js_generator.apply(this,", "arguments)");\n output.end_statement();\n output.indent();\n output.spaced("result.send", "=", "result.next");\n output.end_statement();\n output.indent();\n output.spaced("return", "result");\n output.end_statement();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })());\n } else {\n function_args(self.argnames, output, strip_first);\n print_bracketed(self, output, true, function_preamble);\n }\n if (as_expression) {\n output.end_statement();\n function_annotation(self, output, strip_first, anonfunc);\n [output.indent(), output.spaced("return", anonfunc), output.end_statement()];\n output.set_indentation(orig_indent);\n [output.indent(), output.print("})()")];\n }\n };\n if (!function_definition.__argnames__) Object.defineProperties(function_definition, {\n __argnames__ : {value: ["self", "output", "strip_first", "as_expression"]},\n __module__ : {value: "output.functions"}\n });\n\n function print_function(output) {\n var self;\n self = this;\n if (self.decorators && self.decorators.length) {\n output.print("var");\n output.space();\n output.assign(self.name.name);\n decorate(self.decorators, output, (function() {\n var RS_anonfunc = function () {\n function_definition(self, output, false, true);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n } else {\n function_definition(self, output, false);\n if (!self.is_expression && !self.is_anonymous) {\n output.end_statement();\n function_annotation(self, output, false);\n }\n }\n };\n if (!print_function.__argnames__) Object.defineProperties(print_function, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.functions"}\n });\n\n function find_this(expression) {\n if (is_node_type(expression, AST_Dot)) {\n return expression.expression;\n }\n if (!is_node_type(expression, AST_SymbolRef)) {\n return expression;\n }\n };\n if (!find_this.__argnames__) Object.defineProperties(find_this, {\n __argnames__ : {value: ["expression"]},\n __module__ : {value: "output.functions"}\n });\n\n function print_this(expression, output) {\n var obj;\n obj = find_this(expression);\n if (obj) {\n obj.print(output);\n } else {\n output.print("this");\n }\n };\n if (!print_this.__argnames__) Object.defineProperties(print_this, {\n __argnames__ : {value: ["expression", "output"]},\n __module__ : {value: "output.functions"}\n });\n\n function print_function_call(self, output) {\n var is_prototype_call, has_kwarg_items, has_kwarg_formals, has_kwargs, is_new, is_repeatable;\n is_prototype_call = false;\n function print_function_name(no_call) {\n if (is_node_type(self, AST_ClassCall)) {\n if (self.static) {\n self.class.print(output);\n output.print(".");\n output.print(self.method);\n } else {\n is_prototype_call = true;\n self.class.print(output);\n output.print(".prototype.");\n output.print(self.method);\n if (!no_call) {\n output.print(".call");\n }\n }\n } else {\n if (!is_repeatable) {\n output.print("RS_expr_temp");\n if (is_node_type(self.expression, AST_Dot)) {\n print_getattr(self.expression, output, true);\n }\n } else {\n self.expression.print(output);\n }\n }\n };\n if (!print_function_name.__argnames__) Object.defineProperties(print_function_name, {\n __argnames__ : {value: ["no_call"]},\n __module__ : {value: "output.functions"}\n });\n\n function print_kwargs() {\n var RS_unpack, i, kwname, pair;\n output.print("RS_desugar_kwargs(");\n if (has_kwarg_items) {\n var RS_Iter99 = RS_Iterable(enumerate(self.args.kwarg_items));\n for (var RS_Index99 = 0; RS_Index99 < RS_Iter99.length; RS_Index99++) {\n RS_unpack = RS_Iter99[RS_Index99];\n i = RS_unpack[0];\n kwname = RS_unpack[1];\n if (i > 0) {\n output.print(",");\n output.space();\n }\n kwname.print(output);\n }\n if (has_kwarg_formals) {\n output.print(",");\n output.space();\n }\n }\n if (has_kwarg_formals) {\n output.print("{");\n var RS_Iter100 = RS_Iterable(enumerate(self.args.kwargs));\n for (var RS_Index100 = 0; RS_Index100 < RS_Iter100.length; RS_Index100++) {\n RS_unpack = RS_Iter100[RS_Index100];\n i = RS_unpack[0];\n pair = RS_unpack[1];\n if (i) {\n output.comma();\n }\n pair[0].print(output);\n output.print(":");\n output.space();\n pair[1].print(output);\n }\n output.print("}");\n }\n output.print(")");\n };\n if (!print_kwargs.__module__) Object.defineProperties(print_kwargs, {\n __module__ : {value: "output.functions"}\n });\n\n function print_new(apply) {\n output.print("RS_interpolate_kwargs_constructor.call(");\n [output.print("Object.create("), self.expression.print(output), output.print(".prototype)")];\n output.comma();\n output.print((apply) ? "true" : "false");\n output.comma();\n };\n if (!print_new.__argnames__) Object.defineProperties(print_new, {\n __argnames__ : {value: ["apply"]},\n __module__ : {value: "output.functions"}\n });\n\n function do_print_this() {\n if (!is_repeatable) {\n output.print("RS_expr_temp");\n } else {\n print_this(self.expression, output);\n }\n output.comma();\n };\n if (!do_print_this.__module__) Object.defineProperties(do_print_this, {\n __module__ : {value: "output.functions"}\n });\n\n function print_positional_args() {\n var i, expr, is_first;\n i = 0;\n while (i < self.args.length) {\n expr = (RS_expr_temp = self.args)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n is_first = i === 0;\n if (!is_first) {\n output.print(".concat(");\n }\n if (expr.is_array) {\n expr.print(output);\n i += 1;\n } else {\n output.print("[");\n while (i < self.args.length && !(RS_expr_temp = self.args)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].is_array) {\n (RS_expr_temp = self.args)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].print(output);\n if (i + 1 < self.args.length && !(RS_expr_temp = self.args)[RS_bound_index(i + 1, RS_expr_temp)].is_array) {\n output.print(",");\n output.space();\n }\n i += 1;\n }\n output.print("]");\n }\n if (!is_first) {\n output.print(")");\n }\n }\n };\n if (!print_positional_args.__module__) Object.defineProperties(print_positional_args, {\n __module__ : {value: "output.functions"}\n });\n\n has_kwarg_items = self.args.kwarg_items && self.args.kwarg_items.length;\n has_kwarg_formals = self.args.kwargs && self.args.kwargs.length;\n has_kwargs = has_kwarg_items || has_kwarg_formals;\n is_new = is_node_type(self, AST_New);\n is_repeatable = true;\n if (is_new && !self.args.length && !has_kwargs && !self.args.starargs) {\n [output.print("new"), output.space()];\n print_function_name();\n return;\n }\n if (!has_kwargs && !self.args.starargs) {\n if (is_new) {\n [output.print("new"), output.space()];\n }\n print_function_name();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n var RS_unpack, i, a;\n var RS_Iter101 = RS_Iterable(enumerate(self.args));\n for (var RS_Index101 = 0; RS_Index101 < RS_Iter101.length; RS_Index101++) {\n RS_unpack = RS_Iter101[RS_Index101];\n i = RS_unpack[0];\n a = RS_unpack[1];\n if (i) {\n output.comma();\n }\n a.print(output);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.functions"}\n });\n return RS_anonfunc;\n })());\n return;\n }\n is_repeatable = is_new || !has_calls(self.expression);\n if (!is_repeatable) {\n [output.assign("(RS_expr_temp"), print_this(self.expression, output), output.comma()];\n }\n if (has_kwargs) {\n if (is_new) {\n print_new(false);\n } else {\n output.print("RS_interpolate_kwargs.call(");\n do_print_this();\n }\n print_function_name(true);\n output.comma();\n } else {\n if (is_new) {\n print_new(true);\n print_function_name(true);\n output.comma();\n } else {\n print_function_name(true);\n output.print(".apply(");\n do_print_this();\n }\n }\n if (is_prototype_call && self.args.length > 1) {\n self.args.shift();\n }\n print_positional_args();\n if (has_kwargs) {\n if (self.args.length) {\n output.print(".concat(");\n }\n output.print("[");\n print_kwargs();\n output.print("]");\n if (self.args.length) {\n output.print(")");\n }\n }\n output.print(")");\n if (!is_repeatable) {\n output.print(")");\n }\n };\n if (!print_function_call.__argnames__) Object.defineProperties(print_function_call, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.functions"}\n });\n\n RS_modules["output.functions"].anonfunc = anonfunc;\n RS_modules["output.functions"].module_name = module_name;\n RS_modules["output.functions"].set_module_name = set_module_name;\n RS_modules["output.functions"].decorate = decorate;\n RS_modules["output.functions"].function_args = function_args;\n RS_modules["output.functions"].function_preamble = function_preamble;\n RS_modules["output.functions"].has_annotations = has_annotations;\n RS_modules["output.functions"].function_annotation = function_annotation;\n RS_modules["output.functions"].function_definition = function_definition;\n RS_modules["output.functions"].print_function = print_function;\n RS_modules["output.functions"].find_this = find_this;\n RS_modules["output.functions"].print_this = print_this;\n RS_modules["output.functions"].print_function_call = print_function_call;\n })();\n\n (function(){\n var __name__ = "output.classes";\n var AST_Class = RS_modules.ast.AST_Class;\n var AST_Method = RS_modules.ast.AST_Method;\n var is_node_type = RS_modules.ast.is_node_type;\n\n var decorate = RS_modules["output.functions"].decorate;\n var function_definition = RS_modules["output.functions"].function_definition;\n var function_annotation = RS_modules["output.functions"].function_annotation;\n\n var create_doctring = RS_modules["output.utils"].create_doctring;\n\n var has_prop = RS_modules.utils.has_prop;\n\n function print_class(output) {\n var self, seen_methods, property_names, defined_methods, sname, attr, stmt;\n self = this;\n if (self.external) {\n return;\n }\n function class_def(method, is_var) {\n output.indent();\n self.name.print(output);\n if (!is_var && method && has_prop(self.static, method)) {\n output.assign("." + method);\n } else {\n if (is_var) {\n output.assign(".prototype[" + method + "]");\n } else {\n output.assign(".prototype" + ((method) ? "." + method : ""));\n }\n }\n };\n if (!class_def.__argnames__) Object.defineProperties(class_def, {\n __argnames__ : {value: ["method", "is_var"]},\n __module__ : {value: "output.classes"}\n });\n\n function define_method(stmt, is_property) {\n var name, is_static, strip_first, fname;\n name = stmt.name.name;\n if (!is_property) {\n class_def(name);\n }\n is_static = has_prop(self.static, name);\n strip_first = !is_static;\n if (stmt.decorators && stmt.decorators.length) {\n decorate(stmt.decorators, output, (function() {\n var RS_anonfunc = function () {\n function_definition(stmt, output, strip_first, true);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n } else {\n function_definition(stmt, output, strip_first);\n if (!is_property) {\n output.end_statement();\n fname = self.name.name + ((is_static) ? "." : ".prototype.") + name;\n function_annotation(stmt, output, strip_first, fname);\n }\n }\n };\n if (!define_method.__argnames__) Object.defineProperties(define_method, {\n __argnames__ : {value: ["stmt", "is_property"]},\n __module__ : {value: "output.classes"}\n });\n\n function define_default_method(name, body) {\n class_def(name);\n output.spaced("function", name, "()", "");\n output.with_block((function() {\n var RS_anonfunc = function () {\n [output.indent(), body()];\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n };\n if (!define_default_method.__argnames__) Object.defineProperties(define_default_method, {\n __argnames__ : {value: ["name", "body"]},\n __module__ : {value: "output.classes"}\n });\n\n function add_hidden_property(name, proceed) {\n [output.indent(), output.print("Object.defineProperty(")];\n [self.name.print(output), output.print(".prototype"), output.comma(), output.print(JSON.stringify(name)), \n output.comma()];\n [output.spaced("{value:", ""), proceed(), output.print("})"), output.end_statement()];\n };\n if (!add_hidden_property.__argnames__) Object.defineProperties(add_hidden_property, {\n __argnames__ : {value: ["name", "proceed"]},\n __module__ : {value: "output.classes"}\n });\n\n function write_constructor() {\n output.print("function");\n output.space();\n self.name.print(output);\n output.print("()");\n output.space();\n output.with_block((function() {\n var RS_anonfunc = function () {\n output.indent();\n output.spaced("if", "(this.RS_object_id", "===", "undefined)", "Object.defineProperty(this,", "\\"RS_object_id\\",", "{\\"value\\":++RS_object_counter})");\n output.end_statement();\n if (self.bound.length) {\n output.indent();\n [self.name.print(output), output.print(".prototype.__bind_methods__.call(this)")];\n output.end_statement();\n }\n output.indent();\n self.name.print(output);\n [output.print(".prototype.__init__.apply(this"), output.comma(), output.print("arguments)")];\n output.end_statement();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n };\n if (!write_constructor.__module__) Object.defineProperties(write_constructor, {\n __module__ : {value: "output.classes"}\n });\n\n if (self.decorators && self.decorators.length) {\n output.print("var ");\n output.assign(self.name);\n decorate(self.decorators, output, write_constructor);\n output.semicolon();\n } else {\n write_constructor();\n }\n output.newline();\n if (self.parent) {\n output.indent();\n output.print("RS_extends");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.name.print(output);\n output.comma();\n self.parent.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n }\n if (self.bound.length) {\n seen_methods = Object.create(null);\n add_hidden_property("__bind_methods__", (function() {\n var RS_anonfunc = function () {\n output.spaced("function", "()", "");\n output.with_block((function() {\n var RS_anonfunc = function () {\n var base, bname;\n if (self.bases.length) {\n for (var i = self.bases.length - 1; i >= 0; i--) {\n base = (RS_expr_temp = self.bases)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n [output.indent(), base.print(output), output.spaced(".prototype.__bind_methods__", "&&", "")];\n [base.print(output), output.print(".prototype.__bind_methods__.call(this)")];\n output.end_statement();\n }\n }\n var RS_Iter102 = RS_Iterable(self.bound);\n for (var RS_Index102 = 0; RS_Index102 < RS_Iter102.length; RS_Index102++) {\n bname = RS_Iter102[RS_Index102];\n if (seen_methods[(typeof bname === "number" && bname < 0) ? seen_methods.length + bname : bname] || (RS_expr_temp = self.dynamic_properties)[(typeof bname === "number" && bname < 0) ? RS_expr_temp.length + bname : bname]) {\n continue;\n }\n seen_methods[(typeof bname === "number" && bname < 0) ? seen_methods.length + bname : bname] = true;\n [output.indent(), output.assign("this." + bname)];\n [self.name.print(output), output.print(".prototype." + bname + ".bind(this)")];\n output.end_statement();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n }\n property_names = Object.keys(self.dynamic_properties);\n if (property_names.length) {\n output.indent();\n output.print("Object.defineProperties");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n [self.name.print(output), output.print(".prototype"), output.comma(), output.space(), \n output.with_block((function() {\n var RS_anonfunc = function () {\n var prop, name;\n var RS_Iter103 = RS_Iterable(property_names);\n for (var RS_Index103 = 0; RS_Index103 < RS_Iter103.length; RS_Index103++) {\n name = RS_Iter103[RS_Index103];\n prop = (RS_expr_temp = self.dynamic_properties)[(typeof name === "number" && name < 0) ? RS_expr_temp.length + name : name];\n [output.indent(), output.print(JSON.stringify(name) + ":"), output.space()];\n output.with_block((function() {\n var RS_anonfunc = function () {\n [output.indent(), output.print("\\"enumerable\\":"), output.space(), output.print("true"), \n output.comma(), output.newline()];\n if (prop.getter) {\n [output.indent(), output.print("\\"get\\":"), output.space()];\n [define_method(prop.getter, true), output.comma(), output.newline()];\n }\n [output.indent(), output.print("\\"set\\":"), output.space()];\n if (prop.setter) {\n [define_method(prop.setter, true), output.newline()];\n } else {\n [output.spaced("function", "()", "{", "throw new AttributeError(\\"can\'t set attribute\\")", "}"), \n output.newline()];\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n [output.comma(), output.newline()];\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })())];\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n }\n if (!self.init) {\n define_default_method("__init__", (function() {\n var RS_anonfunc = function () {\n if (self.parent) {\n self.parent.print(output);\n output.spaced(".prototype.__init__", "&&");\n [output.space(), self.parent.print(output)];\n output.print(".prototype.__init__.apply");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("this");\n output.comma();\n output.print("arguments");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n }\n defined_methods = Object.create(null);\n var RS_Iter104 = RS_Iterable(self.body);\n for (var RS_Index104 = 0; RS_Index104 < RS_Iter104.length; RS_Index104++) {\n stmt = RS_Iter104[RS_Index104];\n if (is_node_type(stmt, AST_Method)) {\n if (stmt.is_getter || stmt.is_setter) {\n continue;\n }\n define_method(stmt);\n defined_methods[RS_bound_index(stmt.name.name, defined_methods)] = true;\n sname = stmt.name.name;\n if (sname === "__init__") {\n var RS_Iter105 = RS_Iterable(RS_list_decorate([ ".__argnames__", ".__handles_kwarg_interpolation__" ]));\n for (var RS_Index105 = 0; RS_Index105 < RS_Iter105.length; RS_Index105++) {\n attr = RS_Iter105[RS_Index105];\n [output.indent(), self.name.print(output), output.assign(attr)];\n [self.name.print(output), output.print(".prototype.__init__" + attr), output.end_statement()];\n }\n }\n if (sname === "__iter__") {\n class_def("RS_iterator_symbol", true);\n self.name.print(output);\n output.print(".prototype." + stmt.name.name);\n output.end_statement();\n }\n } else if (is_node_type(stmt, AST_Class)) {\n console.error("Nested classes aren\'t supported yet");\n }\n }\n if (!defined_methods["__repr__"]) {\n define_default_method("__repr__", (function() {\n var RS_anonfunc = function () {\n if (self.parent) {\n [output.print("if("), self.parent.print(output), output.spaced(".prototype.__repr__)", "return", self.parent)];\n [output.print(".prototype.__repr__.call(this)"), output.end_statement()];\n }\n [output.indent(), output.spaced("return", "\\"<\\"", "+", "__name__", "+", "\\".\\"", "+", "this.constructor.name", "")];\n output.spaced("+", "\\" #\\"", "+", "this.RS_object_id", "+", "\\">\\"");\n output.end_statement();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n }\n if (!defined_methods["__str__"]) {\n define_default_method("__str__", (function() {\n var RS_anonfunc = function () {\n if (self.parent) {\n [output.print("if("), self.parent.print(output), output.spaced(".prototype.__str__)", "return", self.parent)];\n [output.print(".prototype.__str__.call(this)"), output.end_statement()];\n }\n output.spaced("return", "this.__repr__()");\n output.end_statement();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n }\n add_hidden_property("__bases__", (function() {\n var RS_anonfunc = function () {\n output.print("[");\n for (var i = 0; i < self.bases.length; i++) {\n (RS_expr_temp = self.bases)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].print(output);\n if (i < self.bases.length - 1) {\n output.comma();\n }\n }\n output.print("]");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n if (self.bases.length > 1) {\n output.indent();\n output.print("RS_mixin(");\n self.name.print(output);\n for (var i = 1; i < self.bases.length; i++) {\n output.comma();\n (RS_expr_temp = self.bases)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].print(output);\n }\n [output.print(")"), output.end_statement()];\n }\n if (self.docstrings && self.docstrings.length && output.options.keep_docstrings) {\n add_hidden_property("__doc__", (function() {\n var RS_anonfunc = function () {\n output.print(JSON.stringify(create_doctring(self.docstrings)));\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.classes"}\n });\n return RS_anonfunc;\n })());\n }\n var RS_Iter106 = RS_Iterable(self.statements);\n for (var RS_Index106 = 0; RS_Index106 < RS_Iter106.length; RS_Index106++) {\n stmt = RS_Iter106[RS_Index106];\n if (!is_node_type(stmt, AST_Method)) {\n output.indent();\n stmt.print(output);\n output.newline();\n }\n }\n };\n if (!print_class.__argnames__) Object.defineProperties(print_class, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.classes"}\n });\n\n RS_modules["output.classes"].print_class = print_class;\n })();\n\n (function(){\n var __name__ = "output.literals";\n var AST_Binary = RS_modules.ast.AST_Binary;\n var is_node_type = RS_modules.ast.is_node_type;\n\n function print_array(self, output) {\n output.print("RS_list_decorate");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.with_square((function() {\n var RS_anonfunc = function () {\n var a, len_, RS_unpack, i, exp;\n a = self.elements;\n len_ = a.length;\n if (len_ > 0) {\n output.space();\n }\n var RS_Iter107 = RS_Iterable(enumerate(a));\n for (var RS_Index107 = 0; RS_Index107 < RS_Iter107.length; RS_Index107++) {\n RS_unpack = RS_Iter107[RS_Index107];\n i = RS_unpack[0];\n exp = RS_unpack[1];\n if (i) {\n output.comma();\n }\n exp.print(output);\n }\n if (len_ > 0) {\n output.space();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n };\n if (!print_array.__argnames__) Object.defineProperties(print_array, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.literals"}\n });\n\n function print_obj_literal(self, output) {\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("function()");\n output.with_block((function() {\n var RS_anonfunc = function () {\n var RS_unpack, i, prop;\n output.indent();\n if (self.is_pydict) {\n output.spaced.apply(output, "var RS_d = RS_dict()".split(" "));\n } else {\n output.spaced("var", "RS_d", "=", (self.is_jshash) ? "Object.create(null)" : "{}");\n }\n output.end_statement();\n var RS_Iter108 = RS_Iterable(enumerate(self.properties));\n for (var RS_Index108 = 0; RS_Index108 < RS_Iter108.length; RS_Index108++) {\n RS_unpack = RS_Iter108[RS_Index108];\n i = RS_unpack[0];\n prop = RS_unpack[1];\n output.indent();\n if (self.is_pydict) {\n output.print("RS_d.set");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n prop.key.print(output);\n [output.print(","), output.space()];\n prop.value.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n } else {\n output.print("RS_d");\n output.with_square((function() {\n var RS_anonfunc = function () {\n prop.key.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n [output.space(), output.print("="), output.space()];\n prop.value.print(output);\n }\n output.end_statement();\n }\n output.indent();\n output.spaced("return", "RS_d");\n output.end_statement();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n output.print(".call(this)");\n };\n if (!print_obj_literal.__argnames__) Object.defineProperties(print_obj_literal, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.literals"}\n });\n\n function print_object(self, output) {\n if (self.is_pydict) {\n if (self.properties.length > 0) {\n print_obj_literal(self, output);\n } else {\n output.print("RS_dict()");\n }\n } else {\n if (self.properties.length > 0) {\n print_obj_literal(self, output);\n } else {\n output.print((self.is_jshash) ? "Object.create(null)" : "{}");\n }\n }\n };\n if (!print_object.__argnames__) Object.defineProperties(print_object, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.literals"}\n });\n\n function print_set(self, output) {\n if (self.items.length === 0) {\n output.print("RS_set()");\n return;\n }\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("function()");\n output.with_block((function() {\n var RS_anonfunc = function () {\n var item;\n output.indent();\n output.spaced.apply(output, "var s = RS_set()".split(" "));\n output.end_statement();\n var RS_Iter109 = RS_Iterable(self.items);\n for (var RS_Index109 = 0; RS_Index109 < RS_Iter109.length; RS_Index109++) {\n item = RS_Iter109[RS_Index109];\n output.indent();\n output.print("s.jsset.add");\n output.with_parens((function() {\n var RS_anonfunc = function () {\n item.value.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n output.end_statement();\n }\n output.indent();\n output.spaced("return", "s");\n output.end_statement();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.literals"}\n });\n return RS_anonfunc;\n })());\n output.print("()");\n };\n if (!print_set.__argnames__) Object.defineProperties(print_set, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.literals"}\n });\n\n function print_regexp(self, output) {\n var str_, p;\n str_ = self.value.toString();\n if (output.options.ascii_only) {\n str_ = output.to_ascii(str_);\n }\n output.print(str_);\n p = output.parent();\n if (is_node_type(p, AST_Binary) && /^in/.test(p.operator) && p.left === self) {\n output.print(" ");\n }\n };\n if (!print_regexp.__argnames__) Object.defineProperties(print_regexp, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.literals"}\n });\n\n RS_modules["output.literals"].print_array = print_array;\n RS_modules["output.literals"].print_obj_literal = print_obj_literal;\n RS_modules["output.literals"].print_object = print_object;\n RS_modules["output.literals"].print_set = print_set;\n RS_modules["output.literals"].print_regexp = print_regexp;\n })();\n\n (function(){\n var __name__ = "output.comments";\n var AST_Exit = RS_modules.ast.AST_Exit;\n var is_node_type = RS_modules.ast.is_node_type;\n\n function output_comments(comments, output, nlb) {\n var comm;\n var RS_Iter110 = RS_Iterable(comments);\n for (var RS_Index110 = 0; RS_Index110 < RS_Iter110.length; RS_Index110++) {\n comm = RS_Iter110[RS_Index110];\n if (comm.type === "comment1") {\n output.print("//" + comm.value + "\\n");\n output.indent();\n } else if (comm.type === "comment2") {\n output.print("/*" + comm.value + "*/");\n if (nlb) {\n output.print("\\n");\n output.indent();\n } else {\n output.space();\n }\n }\n }\n };\n if (!output_comments.__argnames__) Object.defineProperties(output_comments, {\n __argnames__ : {value: ["comments", "output", "nlb"]},\n __module__ : {value: "output.comments"}\n });\n\n function print_comments(self, output) {\n var c, start, comments;\n c = output.options.comments;\n if (c) {\n start = self.start;\n if (start && !start._comments_dumped) {\n start._comments_dumped = true;\n comments = start.comments_before;\n if (is_node_type(self, AST_Exit) && self.value && self.value.start.comments_before && self.value.start.comments_before.length > 0) {\n comments = (comments || []).concat(self.value.start.comments_before);\n self.value.start.comments_before = [];\n }\n if (c.test) {\n comments = comments.filter((function() {\n var RS_anonfunc = function (comment) {\n return c.test(comment.value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["comment"]},\n __module__ : {value: "output.comments"}\n });\n return RS_anonfunc;\n })());\n } else if (typeof c === "function") {\n comments = comments.filter((function() {\n var RS_anonfunc = function (comment) {\n return c(self, comment);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["comment"]},\n __module__ : {value: "output.comments"}\n });\n return RS_anonfunc;\n })());\n }\n output_comments(comments, output, start.nlb);\n }\n }\n };\n if (!print_comments.__argnames__) Object.defineProperties(print_comments, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.comments"}\n });\n\n RS_modules["output.comments"].output_comments = output_comments;\n RS_modules["output.comments"].print_comments = print_comments;\n })();\n\n (function(){\n var __name__ = "output.modules";\n var declare_vars = RS_modules["output.statements"].declare_vars;\n var display_body = RS_modules["output.statements"].display_body;\n\n var OutputStream = RS_modules["output.stream"].OutputStream;\n\n var create_doctring = RS_modules["output.utils"].create_doctring;\n\n var print_comments = RS_modules["output.comments"].print_comments;\n var output_comments = RS_modules["output.comments"].output_comments;\n\n var set_module_name = RS_modules["output.functions"].set_module_name;\n\n var get_compiler_version = RS_modules.parse.get_compiler_version;\n\n var cache_file_name = RS_modules.utils.cache_file_name;\n\n function write_imports(module, output) {\n var imports, import_id, nonlocalvars, name, module_, module_id;\n imports = RS_list_decorate([]);\n var RS_Iter111 = RS_Iterable(Object.keys(module.imports));\n for (var RS_Index111 = 0; RS_Index111 < RS_Iter111.length; RS_Index111++) {\n import_id = RS_Iter111[RS_Index111];\n imports.push((RS_expr_temp = module.imports)[(typeof import_id === "number" && import_id < 0) ? RS_expr_temp.length + import_id : import_id]);\n }\n imports.sort((function() {\n var RS_anonfunc = function (a, b) {\n var RS_unpack;\n RS_unpack = [a.import_order, b.import_order];\n a = RS_unpack[0];\n b = RS_unpack[1];\n return (a < b) ? -1 : (a > b) ? 1 : 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n if (imports.length > 1) {\n output.indent();\n output.print("var RS_modules = {};");\n output.newline();\n }\n nonlocalvars = Object.create(null);\n var RS_Iter112 = RS_Iterable(imports);\n for (var RS_Index112 = 0; RS_Index112 < RS_Iter112.length; RS_Index112++) {\n module_ = RS_Iter112[RS_Index112];\n var RS_Iter113 = RS_Iterable(module_.nonlocalvars);\n for (var RS_Index113 = 0; RS_Index113 < RS_Iter113.length; RS_Index113++) {\n name = RS_Iter113[RS_Index113];\n nonlocalvars[(typeof name === "number" && name < 0) ? nonlocalvars.length + name : name] = true;\n }\n }\n nonlocalvars = Object.getOwnPropertyNames(nonlocalvars).join(", ");\n if (nonlocalvars.length) {\n output.indent();\n output.print("var " + nonlocalvars);\n output.semicolon();\n output.newline();\n }\n var RS_Iter114 = RS_Iterable(imports);\n for (var RS_Index114 = 0; RS_Index114 < RS_Iter114.length; RS_Index114++) {\n module_ = RS_Iter114[RS_Index114];\n module_id = module_.module_id;\n if (module_id !== "__main__") {\n output.indent();\n if (module_id.indexOf(".") === -1) {\n output.print("RS_modules." + module_id);\n } else {\n output.print("RS_modules[\\"" + module_id + "\\"]");\n }\n [output.space(), output.print("="), output.space(), output.print("{}")];\n output.end_statement();\n }\n }\n var RS_Iter115 = RS_Iterable(imports);\n for (var RS_Index115 = 0; RS_Index115 < RS_Iter115.length; RS_Index115++) {\n module_ = RS_Iter115[RS_Index115];\n if (module_.module_id !== "__main__") {\n print_module(module_, output);\n }\n }\n };\n if (!write_imports.__argnames__) Object.defineProperties(write_imports, {\n __argnames__ : {value: ["module", "output"]},\n __module__ : {value: "output.modules"}\n });\n\n function write_main_name(output) {\n if (output.options.write_name) {\n output.newline();\n output.indent();\n output.print("var __name__ = \\"__main__\\"");\n output.semicolon();\n output.newline();\n output.newline();\n }\n };\n if (!write_main_name.__argnames__) Object.defineProperties(write_main_name, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.modules"}\n });\n\n function const_decl(js_version) {\n return "var";\n };\n if (!const_decl.__argnames__) Object.defineProperties(const_decl, {\n __argnames__ : {value: ["js_version"]},\n __module__ : {value: "output.modules"}\n });\n\n function declare_exports(module_id, exports, output, docstrings) {\n var seen, v, symbol;\n seen = Object.create(null);\n if (output.options.keep_docstrings && docstrings && docstrings.length) {\n exports.push((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = "__doc__";\n RS_d["refname"] = "RS_module_doc__";\n return RS_d;\n }).call(this));\n [output.newline(), output.indent()];\n v = const_decl(output.options.js_version);\n [output.assign(v + " RS_module_doc__"), output.print(JSON.stringify(create_doctring(docstrings)))];\n output.end_statement();\n }\n output.newline();\n var RS_Iter116 = RS_Iterable(exports);\n for (var RS_Index116 = 0; RS_Index116 < RS_Iter116.length; RS_Index116++) {\n symbol = RS_Iter116[RS_Index116];\n if (!Object.prototype.hasOwnProperty.call(seen, symbol.name)) {\n output.indent();\n if (module_id.indexOf(".") === -1) {\n output.print("RS_modules." + module_id + "." + symbol.name);\n } else {\n output.print("RS_modules[\\"" + module_id + "\\"]." + symbol.name);\n }\n [output.space(), output.print("="), output.space(), output.print(symbol.refname || symbol.name)];\n seen[RS_bound_index(symbol.name, seen)] = true;\n output.end_statement();\n }\n }\n };\n if (!declare_exports.__argnames__) Object.defineProperties(declare_exports, {\n __argnames__ : {value: ["module_id", "exports", "output", "docstrings"]},\n __module__ : {value: "output.modules"}\n });\n\n function prologue(module, output) {\n var v, needs_yield;\n if (output.options.omit_baselib) {\n return;\n }\n output.indent();\n v = const_decl(output.options.js_version);\n [output.print(v), output.space()];\n output.spaced.apply(output, "RS_iterator_symbol = (typeof Symbol === \\"function\\" && typeof Symbol.iterator === \\"symbol\\") ? Symbol.iterator : \\"iterator-Symbol-5d0927e5554349048cf0e3762a228256\\"".split(" "));\n output.end_statement();\n [output.indent(), output.print(v), output.space()];\n output.spaced.apply(output, "RS_kwargs_symbol = (typeof Symbol === \\"function\\") ? Symbol(\\"kwargs-object\\") : \\"kwargs-object-Symbol-5d0927e5554349048cf0e3762a228256\\"".split(" "));\n output.end_statement();\n [output.indent(), output.spaced("var", "RS_cond_temp,", "RS_expr_temp,", "RS_last_exception"), \n output.end_statement()];\n [output.indent(), output.spaced("var", "RS_object_counter", "=", "0"), output.end_statement()];\n if (output.options.js_version > 5) {\n [output.indent(), output.spaced("if(", "typeof", "HTMLCollection", "!==", "\\"undefined\\"", "&&", "typeof", "Symbol", "===", "\\"function\\")", "NodeList.prototype[Symbol.iterator]", "=", "HTMLCollection.prototype[Symbol.iterator]", "=", "NamedNodeMap.prototype[Symbol.iterator]", "=", "Array.prototype[Symbol.iterator]")];\n output.end_statement();\n }\n needs_yield = output.options.js_version < 6 && module.baselib["yield"];\n if (needs_yield) {\n output.dump_yield();\n }\n if (!output.options.baselib_plain) {\n throw new ValueError("The baselib is missing! Remember to set the baselib_plain field on the options for OutputStream");\n }\n output.print(output.options.baselib_plain);\n output.end_statement();\n };\n if (!prologue.__argnames__) Object.defineProperties(prologue, {\n __argnames__ : {value: ["module", "output"]},\n __module__ : {value: "output.modules"}\n });\n\n function print_top_level(self, output) {\n var is_main;\n set_module_name(self.module_id);\n is_main = self.module_id === "__main__";\n function write_docstrings() {\n var v;\n if (is_main && output.options.keep_docstrings && self.docstrings && self.docstrings.length) {\n [output.newline(), output.indent()];\n v = const_decl(output.options.js_version);\n [output.assign(v + " RS_module_doc__"), output.print(JSON.stringify(create_doctring(self.docstrings)))];\n output.end_statement();\n }\n };\n if (!write_docstrings.__module__) Object.defineProperties(write_docstrings, {\n __module__ : {value: "output.modules"}\n });\n\n if (output.options.private_scope && is_main) {\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("function()");\n output.with_block((function() {\n var RS_anonfunc = function () {\n output.indent();\n output.print("\\"use strict\\"");\n output.end_statement();\n prologue(self, output);\n write_imports(self, output);\n output.newline();\n output.indent();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("function()");\n output.with_block((function() {\n var RS_anonfunc = function () {\n write_main_name(output);\n output.newline();\n declare_vars(self.localvars, output);\n display_body(self.body, true, output);\n output.newline();\n write_docstrings();\n if (self.comments_after && self.comments_after.length) {\n output.indent();\n output_comments(self.comments_after, output);\n output.newline();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n output.print("();");\n output.newline();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n output.print("();");\n output.print("");\n } else {\n if (is_main) {\n prologue(self, output);\n write_imports(self, output);\n write_main_name(output);\n }\n declare_vars(self.localvars, output);\n display_body(self.body, true, output);\n if (self.comments_after && self.comments_after.length) {\n output_comments(self.comments_after, output);\n }\n }\n set_module_name();\n };\n if (!print_top_level.__argnames__) Object.defineProperties(print_top_level, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.modules"}\n });\n\n function print_module(self, output) {\n set_module_name(self.module_id);\n function output_module(output) {\n declare_vars(self.localvars, output);\n display_body(self.body, true, output);\n declare_exports(self.module_id, self.exports, output, self.docstrings);\n };\n if (!output_module.__argnames__) Object.defineProperties(output_module, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.modules"}\n });\n\n output.newline();\n output.indent();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n output.print("function()");\n output.with_block((function() {\n var RS_anonfunc = function () {\n var okey, cached, cobj, cname, symdef, co, raw, js_version, keep_docstrings, beautify;\n print_comments(self, output);\n if (output.options.write_name) {\n output.indent();\n output.print("var ");\n output.assign("__name__");\n output.print("\\"" + self.module_id + "\\"");\n output.semicolon();\n output.newline();\n }\n function output_key(beautify, keep_docstrings, js_version) {\n return "beautify:" + beautify + " keep_docstrings:" + keep_docstrings + " js_version:" + js_version;\n };\n if (!output_key.__argnames__) Object.defineProperties(output_key, {\n __argnames__ : {value: ["beautify", "keep_docstrings", "js_version"]},\n __module__ : {value: "output.modules"}\n });\n\n okey = output_key(output.options.beautify, output.options.keep_docstrings, output.options.js_version);\n if (self.is_cached && RS_in(okey, self.outputs)) {\n output.print((RS_expr_temp = self.outputs)[(typeof okey === "number" && okey < 0) ? RS_expr_temp.length + okey : okey]);\n } else {\n output_module(output);\n if (self.srchash && self.filename) {\n cached = (function(){\n var RS_d = Object.create(null);\n RS_d["version"] = get_compiler_version();\n RS_d["signature"] = self.srchash;\n RS_d["classes"] = Object.create(null);\n RS_d["baselib"] = self.baselib;\n RS_d["nonlocalvars"] = self.nonlocalvars;\n RS_d["imported_module_ids"] = self.imported_module_ids;\n RS_d["exports"] = RS_list_decorate([]);\n RS_d["outputs"] = Object.create(null);\n RS_d["discard_asserts"] = !!output.options.discard_asserts;\n return RS_d;\n }).call(this);\n var RS_Iter117 = RS_Iterable(Object.keys(self.classes));\n for (var RS_Index117 = 0; RS_Index117 < RS_Iter117.length; RS_Index117++) {\n cname = RS_Iter117[RS_Index117];\n cobj = (RS_expr_temp = self.classes)[(typeof cname === "number" && cname < 0) ? RS_expr_temp.length + cname : cname];\n (RS_expr_temp = cached.classes)[(typeof cname === "number" && cname < 0) ? RS_expr_temp.length + cname : cname] = (function(){\n var RS_d = Object.create(null);\n RS_d["name"] = (function(){\n var RS_d = Object.create(null);\n RS_d["name"] = cobj.name.name;\n return RS_d;\n }).call(this);\n RS_d["static"] = cobj.static;\n RS_d["bound"] = cobj.bound;\n RS_d["classvars"] = cobj.classvars;\n return RS_d;\n }).call(this);\n }\n var RS_Iter118 = RS_Iterable(self.exports);\n for (var RS_Index118 = 0; RS_Index118 < RS_Iter118.length; RS_Index118++) {\n symdef = RS_Iter118[RS_Index118];\n cached.exports.push((function(){\n var RS_d = Object.create(null);\n RS_d["name"] = symdef.name;\n return RS_d;\n }).call(this));\n }\n var RS_Iter119 = RS_Iterable(RS_list_decorate([ true, false ]));\n for (var RS_Index119 = 0; RS_Index119 < RS_Iter119.length; RS_Index119++) {\n beautify = RS_Iter119[RS_Index119];\n var RS_Iter120 = RS_Iterable(RS_list_decorate([ true, false ]));\n for (var RS_Index120 = 0; RS_Index120 < RS_Iter120.length; RS_Index120++) {\n keep_docstrings = RS_Iter120[RS_Index120];\n var RS_Iter121 = RS_Iterable(RS_list_decorate([ 5, 6 ]));\n for (var RS_Index121 = 0; RS_Index121 < RS_Iter121.length; RS_Index121++) {\n js_version = RS_Iter121[RS_Index121];\n co = new OutputStream((function(){\n var RS_d = Object.create(null);\n RS_d["beautify"] = beautify;\n RS_d["keep_docstrings"] = keep_docstrings;\n RS_d["js_version"] = js_version;\n RS_d["private_scope"] = false;\n RS_d["write_name"] = false;\n RS_d["discard_asserts"] = output.options.discard_asserts;\n return RS_d;\n }).call(this));\n co.with_indent(output.indentation(), (function() {\n var RS_anonfunc = function () {\n output_module(co);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n raw = co.get();\n (RS_expr_temp = cached.outputs)[RS_bound_index(output_key(beautify, keep_docstrings, js_version), RS_expr_temp)] = raw;\n }\n }\n }\n try {\n writefile(cache_file_name(self.filename, output.options.module_cache_dir), JSON.stringify(cached, null, "\\t"));\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof Error) {\n var e = RS_Exception;\n console.error("Failed to write output cache file:", self.filename + "-cached", "with error:", e);\n } else {\n throw RS_Exception;\n }\n }\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.modules"}\n });\n return RS_anonfunc;\n })());\n output.print("()");\n output.semicolon();\n output.newline();\n set_module_name();\n };\n if (!print_module.__argnames__) Object.defineProperties(print_module, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.modules"}\n });\n\n function print_imports(container, output) {\n var is_first_aname, akey, argname, parts, q, RS_unpack, i, part, self;\n is_first_aname = true;\n function add_aname(aname, key, from_import) {\n if (is_first_aname) {\n is_first_aname = false;\n } else {\n output.indent();\n }\n output.print("var ");\n output.assign(aname);\n if (key.indexOf(".") === -1) {\n [output.print("RS_modules."), output.print(key)];\n } else {\n [output.print("RS_modules[\\""), output.print(key), output.print("\\"]")];\n }\n if (from_import) {\n output.print(".");\n output.print(from_import);\n }\n output.end_statement();\n };\n if (!add_aname.__argnames__) Object.defineProperties(add_aname, {\n __argnames__ : {value: ["aname", "key", "from_import"]},\n __module__ : {value: "output.modules"}\n });\n\n var RS_Iter122 = RS_Iterable(container.imports);\n for (var RS_Index122 = 0; RS_Index122 < RS_Iter122.length; RS_Index122++) {\n self = RS_Iter122[RS_Index122];\n if (self.argnames) {\n var RS_Iter123 = RS_Iterable(self.argnames);\n for (var RS_Index123 = 0; RS_Index123 < RS_Iter123.length; RS_Index123++) {\n argname = RS_Iter123[RS_Index123];\n akey = (argname.alias) ? argname.alias.name : argname.name;\n add_aname(akey, self.key, argname.name);\n }\n } else {\n if (self.alias) {\n add_aname(self.alias.name, self.key, false);\n } else {\n parts = self.key.split(".");\n var RS_Iter124 = RS_Iterable(enumerate(parts));\n for (var RS_Index124 = 0; RS_Index124 < RS_Iter124.length; RS_Index124++) {\n RS_unpack = RS_Iter124[RS_Index124];\n i = RS_unpack[0];\n part = RS_unpack[1];\n if (i === 0) {\n add_aname(part, part, false);\n } else {\n q = parts.slice(0, i + 1).join(".");\n output.indent();\n output.spaced(q, "=", "RS_modules[\\"" + q + "\\"]");\n output.end_statement();\n }\n }\n }\n }\n }\n };\n if (!print_imports.__argnames__) Object.defineProperties(print_imports, {\n __argnames__ : {value: ["container", "output"]},\n __module__ : {value: "output.modules"}\n });\n\n RS_modules["output.modules"].write_imports = write_imports;\n RS_modules["output.modules"].write_main_name = write_main_name;\n RS_modules["output.modules"].const_decl = const_decl;\n RS_modules["output.modules"].declare_exports = declare_exports;\n RS_modules["output.modules"].prologue = prologue;\n RS_modules["output.modules"].print_top_level = print_top_level;\n RS_modules["output.modules"].print_module = print_module;\n RS_modules["output.modules"].print_imports = print_imports;\n })();\n\n (function(){\n var __name__ = "output.codegen";\n var noop = RS_modules.utils.noop;\n\n var PRECEDENCE = RS_modules.parse.PRECEDENCE;\n\n var AST_Array = RS_modules.ast.AST_Array;\n var AST_Assign = RS_modules.ast.AST_Assign;\n var AST_BaseCall = RS_modules.ast.AST_BaseCall;\n var AST_Binary = RS_modules.ast.AST_Binary;\n var AST_BlockStatement = RS_modules.ast.AST_BlockStatement;\n var AST_Break = RS_modules.ast.AST_Break;\n var AST_Class = RS_modules.ast.AST_Class;\n var AST_Conditional = RS_modules.ast.AST_Conditional;\n var AST_Constant = RS_modules.ast.AST_Constant;\n var AST_Continue = RS_modules.ast.AST_Continue;\n var AST_Debugger = RS_modules.ast.AST_Debugger;\n var AST_Definitions = RS_modules.ast.AST_Definitions;\n var AST_Directive = RS_modules.ast.AST_Directive;\n var AST_Do = RS_modules.ast.AST_Do;\n var AST_Dot = RS_modules.ast.AST_Dot;\n var is_node_type = RS_modules.ast.is_node_type;\n var AST_EmptyStatement = RS_modules.ast.AST_EmptyStatement;\n var AST_Exit = RS_modules.ast.AST_Exit;\n var AST_ExpressiveObject = RS_modules.ast.AST_ExpressiveObject;\n var AST_ForIn = RS_modules.ast.AST_ForIn;\n var AST_ForJS = RS_modules.ast.AST_ForJS;\n var AST_Function = RS_modules.ast.AST_Function;\n var AST_Hole = RS_modules.ast.AST_Hole;\n var AST_If = RS_modules.ast.AST_If;\n var AST_Imports = RS_modules.ast.AST_Imports;\n var AST_Infinity = RS_modules.ast.AST_Infinity;\n var AST_Lambda = RS_modules.ast.AST_Lambda;\n var AST_ListComprehension = RS_modules.ast.AST_ListComprehension;\n var AST_LoopControl = RS_modules.ast.AST_LoopControl;\n var AST_NaN = RS_modules.ast.AST_NaN;\n var AST_New = RS_modules.ast.AST_New;\n var AST_Node = RS_modules.ast.AST_Node;\n var AST_Number = RS_modules.ast.AST_Number;\n var AST_Object = RS_modules.ast.AST_Object;\n var AST_ObjectKeyVal = RS_modules.ast.AST_ObjectKeyVal;\n var AST_ObjectProperty = RS_modules.ast.AST_ObjectProperty;\n var AST_PropAccess = RS_modules.ast.AST_PropAccess;\n var AST_RegExp = RS_modules.ast.AST_RegExp;\n var AST_Return = RS_modules.ast.AST_Return;\n var AST_Set = RS_modules.ast.AST_Set;\n var AST_Seq = RS_modules.ast.AST_Seq;\n var AST_SimpleStatement = RS_modules.ast.AST_SimpleStatement;\n var AST_Splice = RS_modules.ast.AST_Splice;\n var AST_Statement = RS_modules.ast.AST_Statement;\n var AST_StatementWithBody = RS_modules.ast.AST_StatementWithBody;\n var AST_String = RS_modules.ast.AST_String;\n var AST_Sub = RS_modules.ast.AST_Sub;\n var AST_ItemAccess = RS_modules.ast.AST_ItemAccess;\n var AST_Symbol = RS_modules.ast.AST_Symbol;\n var AST_This = RS_modules.ast.AST_This;\n var AST_Throw = RS_modules.ast.AST_Throw;\n var AST_Toplevel = RS_modules.ast.AST_Toplevel;\n var AST_Try = RS_modules.ast.AST_Try;\n var AST_Unary = RS_modules.ast.AST_Unary;\n var AST_UnaryPrefix = RS_modules.ast.AST_UnaryPrefix;\n var AST_Undefined = RS_modules.ast.AST_Undefined;\n var AST_Var = RS_modules.ast.AST_Var;\n var AST_VarDef = RS_modules.ast.AST_VarDef;\n var AST_Assert = RS_modules.ast.AST_Assert;\n var AST_Verbatim = RS_modules.ast.AST_Verbatim;\n var AST_While = RS_modules.ast.AST_While;\n var AST_With = RS_modules.ast.AST_With;\n var AST_Yield = RS_modules.ast.AST_Yield;\n var TreeWalker = RS_modules.ast.TreeWalker;\n var AST_Existential = RS_modules.ast.AST_Existential;\n\n var print_try = RS_modules["output.exceptions"].print_try;\n\n var print_class = RS_modules["output.classes"].print_class;\n\n var print_array = RS_modules["output.literals"].print_array;\n var print_obj_literal = RS_modules["output.literals"].print_obj_literal;\n var print_object = RS_modules["output.literals"].print_object;\n var print_set = RS_modules["output.literals"].print_set;\n var print_regexp = RS_modules["output.literals"].print_regexp;\n\n var print_do_loop = RS_modules["output.loops"].print_do_loop;\n var print_while_loop = RS_modules["output.loops"].print_while_loop;\n var print_for_loop_body = RS_modules["output.loops"].print_for_loop_body;\n var print_for_in = RS_modules["output.loops"].print_for_in;\n var print_list_comprehension = RS_modules["output.loops"].print_list_comprehension;\n\n var print_top_level = RS_modules["output.modules"].print_top_level;\n var print_imports = RS_modules["output.modules"].print_imports;\n\n var print_comments = RS_modules["output.comments"].print_comments;\n\n var print_getattr = RS_modules["output.operators"].print_getattr;\n var print_getitem = RS_modules["output.operators"].print_getitem;\n var print_rich_getitem = RS_modules["output.operators"].print_rich_getitem;\n var print_splice_assignment = RS_modules["output.operators"].print_splice_assignment;\n var print_unary_prefix = RS_modules["output.operators"].print_unary_prefix;\n var print_binary_op = RS_modules["output.operators"].print_binary_op;\n var print_assign = RS_modules["output.operators"].print_assign;\n var print_conditional = RS_modules["output.operators"].print_conditional;\n var print_seq = RS_modules["output.operators"].print_seq;\n var print_existential = RS_modules["output.operators"].print_existential;\n\n var print_function = RS_modules["output.functions"].print_function;\n var print_function_call = RS_modules["output.functions"].print_function_call;\n\n var print_bracketed = RS_modules["output.statements"].print_bracketed;\n var first_in_statement = RS_modules["output.statements"].first_in_statement;\n var force_statement = RS_modules["output.statements"].force_statement;\n var print_with = RS_modules["output.statements"].print_with;\n var print_assert = RS_modules["output.statements"].print_assert;\n\n var make_block = RS_modules["output.utils"].make_block;\n var make_num = RS_modules["output.utils"].make_num;\n\n function generate_code() {\n function DEFPRINT(nodetype, generator) {\n nodetype.prototype._codegen = generator;\n };\n if (!DEFPRINT.__argnames__) Object.defineProperties(DEFPRINT, {\n __argnames__ : {value: ["nodetype", "generator"]},\n __module__ : {value: "output.codegen"}\n });\n\n AST_Node.prototype.print = (function() {\n var RS_anonfunc = function (stream, force_parens) {\n var self, generator;\n self = this;\n generator = self._codegen;\n stream.push_node(self);\n if (force_parens || self.needs_parens(stream)) {\n stream.with_parens((function() {\n var RS_anonfunc = function () {\n self.add_comments(stream);\n generator(self, stream);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n } else {\n self.add_comments(stream);\n generator(self, stream);\n }\n stream.pop_node();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["stream", "force_parens"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n AST_Node.prototype.add_comments = (function() {\n var RS_anonfunc = function (output) {\n if (!is_node_type(this, AST_Toplevel)) {\n print_comments(this, output);\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n function PARENS(nodetype, func) {\n nodetype.prototype.needs_parens = func;\n };\n if (!PARENS.__argnames__) Object.defineProperties(PARENS, {\n __argnames__ : {value: ["nodetype", "func"]},\n __module__ : {value: "output.codegen"}\n });\n\n PARENS(AST_Node, (function() {\n var RS_anonfunc = function () {\n return false;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_Function, (function() {\n var RS_anonfunc = function (output) {\n return first_in_statement(output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_Object, (function() {\n var RS_anonfunc = function (output) {\n return first_in_statement(output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_Unary, (function() {\n var RS_anonfunc = function (output) {\n var p;\n p = output.parent();\n return is_node_type(p, AST_PropAccess) && p.expression === this;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_Seq, (function() {\n var RS_anonfunc = function (output) {\n var p;\n p = output.parent();\n return is_node_type(p, AST_Unary) || is_node_type(p, AST_VarDef) || is_node_type(p, AST_Dot) || is_node_type(p, AST_ObjectProperty) || is_node_type(p, AST_Conditional);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_Binary, (function() {\n var RS_anonfunc = function (output) {\n var p, po, pp, so, sp;\n p = output.parent();\n if (is_node_type(p, AST_BaseCall) && p.expression === this) {\n return true;\n }\n if (is_node_type(p, AST_Unary)) {\n return true;\n }\n if (is_node_type(p, AST_PropAccess) && p.expression === this) {\n return true;\n }\n if (is_node_type(p, AST_Binary)) {\n po = p.operator;\n pp = PRECEDENCE[(typeof po === "number" && po < 0) ? PRECEDENCE.length + po : po];\n so = this.operator;\n sp = PRECEDENCE[(typeof so === "number" && so < 0) ? PRECEDENCE.length + so : so];\n if (pp > sp || pp === sp && this === p.right && !((so === po && (so === "*" || so === "&&" || so === "||")))) {\n return true;\n }\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_PropAccess, (function() {\n var RS_anonfunc = function (output) {\n var p;\n p = output.parent();\n if (is_node_type(p, AST_New) && p.expression === this) {\n try {\n this.walk(new TreeWalker((function() {\n var RS_anonfunc = function (node) {\n if (is_node_type(node, AST_BaseCall)) {\n throw p;\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["node"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })()));\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n var ex = RS_Exception;\n if (ex !== p) {\n throw ex;\n }\n return true;\n } \n }\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_BaseCall, (function() {\n var RS_anonfunc = function (output) {\n var p;\n p = output.parent();\n return is_node_type(p, AST_New) && p.expression === this;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_New, (function() {\n var RS_anonfunc = function (output) {\n var p;\n p = output.parent();\n if (this.args.length === 0 && (is_node_type(p, AST_PropAccess) || is_node_type(p, AST_BaseCall) && p.expression === this)) {\n return true;\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_Number, (function() {\n var RS_anonfunc = function (output) {\n var p;\n p = output.parent();\n if (this.value < 0 && is_node_type(p, AST_PropAccess) && p.expression === this) {\n return true;\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n PARENS(AST_NaN, (function() {\n var RS_anonfunc = function (output) {\n var p;\n p = output.parent();\n if (is_node_type(p, AST_PropAccess) && p.expression === this) {\n return true;\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n function assign_and_conditional_paren_rules(output) {\n var p;\n p = output.parent();\n if (is_node_type(p, AST_Unary)) {\n return true;\n }\n if (is_node_type(p, AST_Binary) && !(is_node_type(p, AST_Assign))) {\n return true;\n }\n if (is_node_type(p, AST_BaseCall) && p.expression === this) {\n return true;\n }\n if (is_node_type(p, AST_Conditional) && p.condition === this) {\n return true;\n }\n if (is_node_type(p, AST_PropAccess) && p.expression === this) {\n return true;\n }\n };\n if (!assign_and_conditional_paren_rules.__argnames__) Object.defineProperties(assign_and_conditional_paren_rules, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n\n PARENS(AST_Assign, assign_and_conditional_paren_rules);\n PARENS(AST_Conditional, assign_and_conditional_paren_rules);\n DEFPRINT(AST_Directive, (function() {\n var RS_anonfunc = function (self, output) {\n output.print_string(self.value);\n output.semicolon();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Debugger, (function() {\n var RS_anonfunc = function (self, output) {\n output.print("debugger");\n output.semicolon();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n AST_StatementWithBody.prototype._do_print_body = (function() {\n var RS_anonfunc = function (output) {\n force_statement(this.body, output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n DEFPRINT(AST_Statement, (function() {\n var RS_anonfunc = function (self, output) {\n self.body.print(output);\n output.semicolon();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Toplevel, print_top_level);\n DEFPRINT(AST_Imports, print_imports);\n DEFPRINT(AST_SimpleStatement, (function() {\n var RS_anonfunc = function (self, output) {\n if (!(is_node_type(self.body, AST_EmptyStatement))) {\n self.body.print(output);\n output.semicolon();\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_BlockStatement, (function() {\n var RS_anonfunc = function (self, output) {\n print_bracketed(self, output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_EmptyStatement, (function() {\n var RS_anonfunc = function (self, output) {\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Do, print_do_loop);\n DEFPRINT(AST_While, print_while_loop);\n AST_ForIn.prototype._do_print_body = print_for_loop_body;\n DEFPRINT(AST_ForIn, print_for_in);\n AST_ForJS.prototype._do_print_body = (function() {\n var RS_anonfunc = function (output) {\n var self;\n self = this;\n output.with_block((function() {\n var RS_anonfunc = function () {\n var stmt;\n var RS_Iter125 = RS_Iterable(self.body.body);\n for (var RS_Index125 = 0; RS_Index125 < RS_Iter125.length; RS_Index125++) {\n stmt = RS_Iter125[RS_Index125];\n output.indent();\n stmt.print(output);\n output.newline();\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n DEFPRINT(AST_ForJS, (function() {\n var RS_anonfunc = function (self, output) {\n output.print("for");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.condition.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n output.space();\n self._do_print_body(output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_ListComprehension, print_list_comprehension);\n DEFPRINT(AST_With, print_with);\n DEFPRINT(AST_Assert, print_assert);\n AST_Lambda.prototype._do_print = print_function;\n DEFPRINT(AST_Lambda, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n AST_Class.prototype._do_print = print_class;\n DEFPRINT(AST_Class, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n AST_Exit.prototype._do_print = (function() {\n var RS_anonfunc = function (output, kind) {\n var self;\n self = this;\n output.print(kind);\n if (self.value) {\n output.space();\n self.value.print(output);\n }\n output.semicolon();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output", "kind"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n DEFPRINT(AST_Yield, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output, "yield" + ((self.is_yield_from) ? "*" : ""));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Return, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output, "return");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Throw, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output, "throw");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n AST_LoopControl.prototype._do_print = (function() {\n var RS_anonfunc = function (output, kind) {\n output.print(kind);\n if (this.label) {\n output.space();\n this.label.print(output);\n }\n output.semicolon();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output", "kind"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n DEFPRINT(AST_Break, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output, "break");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Continue, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output, "continue");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n function make_then(self, output) {\n var b;\n if (output.options.bracketize) {\n make_block(self.body, output);\n return;\n }\n if (!self.body) {\n return output.force_semicolon();\n }\n if (is_node_type(self.body, AST_Do) && output.options.ie_proof) {\n make_block(self.body, output);\n return;\n }\n b = self.body;\n while (true) {\n if (is_node_type(b, AST_If)) {\n if (!b.alternative) {\n make_block(self.body, output);\n return;\n }\n b = b.alternative;\n } else if (is_node_type(b, AST_StatementWithBody)) {\n b = b.body;\n } else {\n break;\n }\n }\n force_statement(self.body, output);\n };\n if (!make_then.__argnames__) Object.defineProperties(make_then, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n\n DEFPRINT(AST_If, (function() {\n var RS_anonfunc = function (self, output) {\n output.print("if");\n output.space();\n output.with_parens((function() {\n var RS_anonfunc = function () {\n self.condition.print(output);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n output.space();\n if (self.alternative) {\n make_then(self, output);\n output.space();\n output.print("else");\n output.space();\n force_statement(self.alternative, output);\n } else {\n self._do_print_body(output);\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Try, print_try);\n AST_Definitions.prototype._do_print = (function() {\n var RS_anonfunc = function (output, kind) {\n var RS_unpack, i, def_, p, in_for, avoid_semicolon;\n output.print(kind);\n output.space();\n var RS_Iter126 = RS_Iterable(enumerate(this.definitions));\n for (var RS_Index126 = 0; RS_Index126 < RS_Iter126.length; RS_Index126++) {\n RS_unpack = RS_Iter126[RS_Index126];\n i = RS_unpack[0];\n def_ = RS_unpack[1];\n if (i) {\n output.comma();\n }\n def_.print(output);\n }\n p = output.parent();\n in_for = is_node_type(p, AST_ForIn);\n avoid_semicolon = in_for && p.init === this;\n if (!avoid_semicolon) {\n output.semicolon();\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["output", "kind"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n DEFPRINT(AST_Var, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output, "var");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n function parenthesize_for_noin(node, output, noin) {\n if (!noin) {\n node.print(output);\n } else {\n try {\n node.walk(new TreeWalker((function() {\n var RS_anonfunc = function (node) {\n if (is_node_type(node, AST_Binary) && node.operator === "in") {\n throw output;\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["node"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })()));\n node.print(output);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n var ex = RS_Exception;\n if (ex !== output) {\n throw ex;\n }\n node.print(output, true);\n } \n }\n }\n };\n if (!parenthesize_for_noin.__argnames__) Object.defineProperties(parenthesize_for_noin, {\n __argnames__ : {value: ["node", "output", "noin"]},\n __module__ : {value: "output.codegen"}\n });\n\n DEFPRINT(AST_VarDef, (function() {\n var RS_anonfunc = function (self, output) {\n var p, noin;\n self.name.print(output);\n if (self.value) {\n output.assign("");\n p = output.parent(1);\n noin = is_node_type(p, AST_ForIn);\n parenthesize_for_noin(self.value, output, noin);\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_BaseCall, print_function_call);\n AST_Seq.prototype._do_print = print_seq;\n DEFPRINT(AST_Seq, (function() {\n var RS_anonfunc = function (self, output) {\n self._do_print(output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Dot, print_getattr);\n DEFPRINT(AST_Sub, print_getitem);\n DEFPRINT(AST_ItemAccess, print_rich_getitem);\n DEFPRINT(AST_Splice, print_splice_assignment);\n DEFPRINT(AST_UnaryPrefix, print_unary_prefix);\n DEFPRINT(AST_Binary, print_binary_op);\n DEFPRINT(AST_Existential, print_existential);\n DEFPRINT(AST_Assign, print_assign);\n DEFPRINT(AST_Conditional, print_conditional);\n DEFPRINT(AST_Array, print_array);\n DEFPRINT(AST_ExpressiveObject, print_obj_literal);\n DEFPRINT(AST_Object, print_object);\n DEFPRINT(AST_ObjectKeyVal, (function() {\n var RS_anonfunc = function (self, output) {\n self.key.print(output);\n output.colon();\n self.value.print(output);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Set, print_set);\n AST_Symbol.prototype.definition = (function() {\n var RS_anonfunc = function () {\n return this.thedef;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })();\n DEFPRINT(AST_Symbol, (function() {\n var RS_anonfunc = function (self, output) {\n var def_;\n def_ = self.definition();\n output.print_name((def_) ? def_.mangled_name || def_.name : self.name);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Undefined, (function() {\n var RS_anonfunc = function (self, output) {\n output.print("void 0");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Hole, noop);\n DEFPRINT(AST_Infinity, (function() {\n var RS_anonfunc = function (self, output) {\n output.print("1/0");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_NaN, (function() {\n var RS_anonfunc = function (self, output) {\n output.print("0/0");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_This, (function() {\n var RS_anonfunc = function (self, output) {\n output.print("this");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Constant, (function() {\n var RS_anonfunc = function (self, output) {\n output.print(self.value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_String, (function() {\n var RS_anonfunc = function (self, output) {\n output.print_string(self.value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Verbatim, (function() {\n var RS_anonfunc = function (self, output) {\n output.print(self.value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_Number, (function() {\n var RS_anonfunc = function (self, output) {\n output.print(make_num(self.value));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["self", "output"]},\n __module__ : {value: "output.codegen"}\n });\n return RS_anonfunc;\n })());\n DEFPRINT(AST_RegExp, print_regexp);\n };\n if (!generate_code.__module__) Object.defineProperties(generate_code, {\n __module__ : {value: "output.codegen"}\n });\n\n RS_modules["output.codegen"].generate_code = generate_code;\n })();\n\n (function(){\n\n var __name__ = "__main__";\n\n\n var ast, ast_node;\n var DefaultsError = RS_modules.utils.DefaultsError;\n var string_template = RS_modules.utils.string_template;\n\n var ImportError = RS_modules.errors.ImportError;\n var SyntaxError = RS_modules.errors.SyntaxError;\n\n var ALL_KEYWORDS = RS_modules.tokenizer.ALL_KEYWORDS;\n var IDENTIFIER_PAT = RS_modules.tokenizer.IDENTIFIER_PAT;\n var tokenizer = RS_modules.tokenizer.tokenizer;\n\n var parse = RS_modules.parse.parse;\n var NATIVE_CLASSES = RS_modules.parse.NATIVE_CLASSES;\n var compile_time_decorators = RS_modules.parse.compile_time_decorators;\n\n var OutputStream = RS_modules["output.stream"].OutputStream;\n\n var generate_code = RS_modules["output.codegen"].generate_code;\n\n generate_code();\n if (typeof exports === "object") {\n exports.DefaultsError = DefaultsError;\n exports.parse = parse;\n exports.compile_time_decorators = compile_time_decorators;\n exports.OutputStream = OutputStream;\n exports.string_template = string_template;\n exports.ALL_KEYWORDS = ALL_KEYWORDS;\n exports.IDENTIFIER_PAT = IDENTIFIER_PAT;\n exports.NATIVE_CLASSES = NATIVE_CLASSES;\n exports.ImportError = ImportError;\n exports.SyntaxError = SyntaxError;\n exports.tokenizer = tokenizer;\n ast = RS_modules["ast"];\n var RS_Iter127 = RS_Iterable(ast);\n for (var RS_Index127 = 0; RS_Index127 < RS_Iter127.length; RS_Index127++) {\n ast_node = RS_Iter127[RS_Index127];\n if (ast_node.substr(0, 4) === "AST_") {\n exports[(typeof ast_node === "number" && ast_node < 0) ? exports.length + ast_node : ast_node] = ast[(typeof ast_node === "number" && ast_node < 0) ? ast.length + ast_node : ast_node];\n }\n }\n }\n })();\n})();',"baselib-plain-pretty.js":'var RS_len;\nfunction RS_bool(val) {\n return !!val;\n};\nif (!RS_bool.__argnames__) Object.defineProperties(RS_bool, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_print() {\n var parts;\n if (typeof console === "object") {\n parts = [];\n for (var i = 0; i < arguments.length; i++) {\n parts.push(RS_str(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]));\n }\n console.log(parts.join(" "));\n }\n};\nif (!RS_print.__module__) Object.defineProperties(RS_print, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_int(val, base) {\n var ans;\n if (typeof val === "number") {\n ans = val | 0;\n } else {\n ans = parseInt(val, base || 10);\n }\n if (isNaN(ans)) {\n throw new ValueError("Invalid literal for int with base " + (base || 10) + ": " + val);\n }\n return ans;\n};\nif (!RS_int.__argnames__) Object.defineProperties(RS_int, {\n __argnames__ : {value: ["val", "base"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_float(val) {\n var ans;\n if (typeof val === "number") {\n ans = val;\n } else {\n ans = parseFloat(val);\n }\n if (isNaN(ans)) {\n throw new ValueError("Could not convert string to float: " + arguments[0]);\n }\n return ans;\n};\nif (!RS_float.__argnames__) Object.defineProperties(RS_float, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_arraylike_creator() {\n var names;\n names = "Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".split(" ");\n if (typeof HTMLCollection === "function") {\n names = names.concat("HTMLCollection NodeList NamedNodeMap TouchList".split(" "));\n }\n return (function() {\n var RS_anonfunc = function (x) {\n if (Array.isArray(x) || typeof x === "string" || names.indexOf(Object.prototype.toString.call(x).slice(8, -1)) > -1) {\n return true;\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n};\nif (!RS_arraylike_creator.__module__) Object.defineProperties(RS_arraylike_creator, {\n __module__ : {value: "__main__"}\n});\n\nfunction options_object(f) {\n return (function() {\n var RS_anonfunc = function () {\n if (typeof arguments[arguments.length - 1] === "object") {\n arguments[RS_bound_index(arguments.length - 1, arguments)][RS_kwargs_symbol] = true;\n }\n return f.apply(this, arguments);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n};\nif (!options_object.__argnames__) Object.defineProperties(options_object, {\n __argnames__ : {value: ["f"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_id(x) {\n return x.RS_object_id;\n};\nif (!RS_id.__argnames__) Object.defineProperties(RS_id, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_dir(item) {\n var arr;\n arr = RS_list_decorate([]);\n for (var i in item) {\n arr.push(i);\n }\n return arr;\n};\nif (!RS_dir.__argnames__) Object.defineProperties(RS_dir, {\n __argnames__ : {value: ["item"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_ord(x) {\n var ans, second;\n ans = x.charCodeAt(0);\n if (55296 <= ans && ans <= 56319) {\n second = x.charCodeAt(1);\n if (56320 <= second && second <= 57343) {\n return (ans - 55296) * 1024 + second - 56320 + 65536;\n }\n throw new TypeError("string is missing the low surrogate char");\n }\n return ans;\n};\nif (!RS_ord.__argnames__) Object.defineProperties(RS_ord, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_chr(code) {\n if (code <= 65535) {\n return String.fromCharCode(code);\n }\n code -= 65536;\n return String.fromCharCode(55296 + (code >> 10), 56320 + (code & 1023));\n};\nif (!RS_chr.__argnames__) Object.defineProperties(RS_chr, {\n __argnames__ : {value: ["code"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_callable(x) {\n return typeof x === "function";\n};\nif (!RS_callable.__argnames__) Object.defineProperties(RS_callable, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_bin(x) {\n var ans;\n if (typeof x !== "number" || x % 1 !== 0) {\n throw new TypeError("integer required");\n }\n ans = x.toString(2);\n if (ans[0] === "-") {\n ans = "-" + "0b" + ans.slice(1);\n } else {\n ans = "0b" + ans;\n }\n return ans;\n};\nif (!RS_bin.__argnames__) Object.defineProperties(RS_bin, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_hex(x) {\n var ans;\n if (typeof x !== "number" || x % 1 !== 0) {\n throw new TypeError("integer required");\n }\n ans = x.toString(16);\n if (ans[0] === "-") {\n ans = "-" + "0x" + ans.slice(1);\n } else {\n ans = "0x" + ans;\n }\n return ans;\n};\nif (!RS_hex.__argnames__) Object.defineProperties(RS_hex, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_enumerate(iterable) {\n var ans, iterator;\n ans = {"_i":-1};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n if (RS_arraylike(iterable)) {\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i < iterable.length) {\n return {\'done\':false, \'value\':[this._i, iterable[this._i]]};\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n ans["_iterator"] = iterator;\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var r;\n r = this._iterator.next();\n if (r.done) {\n return {\'done\':true};\n }\n this._i += 1;\n return {\'done\':false, \'value\':[this._i, r.value]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n return RS_enumerate(Object.keys(iterable));\n};\nif (!RS_enumerate.__argnames__) Object.defineProperties(RS_enumerate, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_reversed(iterable) {\n var ans;\n if (RS_arraylike(iterable)) {\n ans = {"_i": iterable.length};\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i -= 1;\n if (this._i > -1) {\n return {\'done\':false, \'value\':iterable[this._i]};\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n throw new TypeError("reversed() can only be called on arrays or strings");\n};\nif (!RS_reversed.__argnames__) Object.defineProperties(RS_reversed, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_iter(iterable) {\n var ans;\n if (typeof iterable[RS_iterator_symbol] === "function") {\n return (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n }\n if (RS_arraylike(iterable)) {\n ans = {"_i":-1};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i < iterable.length) {\n return {\'done\':false, \'value\':iterable[this._i]};\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n }\n return RS_iter(Object.keys(iterable));\n};\nif (!RS_iter.__argnames__) Object.defineProperties(RS_iter, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_range_next(step, length) {\n var RS_unpack;\n this._i += step;\n this._idx += 1;\n if (this._idx >= length) {\n RS_unpack = [this.__i, -1];\n this._i = RS_unpack[0];\n this._idx = RS_unpack[1];\n return {\'done\':true};\n }\n return {\'done\':false, \'value\':this._i};\n};\nif (!RS_range_next.__argnames__) Object.defineProperties(RS_range_next, {\n __argnames__ : {value: ["step", "length"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_range(start, stop, step) {\n var length, ans;\n if (arguments.length <= 1) {\n stop = start || 0;\n start = 0;\n }\n step = arguments[2] || 1;\n length = Math.max(Math.ceil((stop - start) / step), 0);\n ans = {start:start, step:step, stop:stop};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n var it;\n it = {"_i": start - step, "_idx": -1};\n it.next = RS_range_next.bind(it, step, length);\n it[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return it;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans.count = (function() {\n var RS_anonfunc = function (val) {\n if (!this._cached) {\n this._cached = list(this);\n }\n return this._cached.count(val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans.index = (function() {\n var RS_anonfunc = function (val) {\n if (!this._cached) {\n this._cached = list(this);\n }\n return this._cached.index(val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n if (typeof Proxy === "function") {\n ans = new Proxy(ans, (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function (obj, prop) {\n var iprop;\n if (typeof prop === "string") {\n iprop = parseInt(prop);\n if (!isNaN(iprop)) {\n prop = iprop;\n }\n }\n if (typeof prop === "number") {\n if (!obj._cached) {\n obj._cached = list(obj);\n }\n return (RS_expr_temp = obj._cached)[(typeof prop === "number" && prop < 0) ? RS_expr_temp.length + prop : prop];\n }\n return obj[(typeof prop === "number" && prop < 0) ? obj.length + prop : prop];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["obj", "prop"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this));\n }\n return ans;\n};\nif (!RS_range.__argnames__) Object.defineProperties(RS_range, {\n __argnames__ : {value: ["start", "stop", "step"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_getattr(obj, name, defval) {\n var ret;\n try {\n ret = obj[(typeof name === "number" && name < 0) ? obj.length + name : name];\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof TypeError) {\n if (defval === undefined) {\n throw new AttributeError("The attribute " + name + " is not present");\n }\n return defval;\n } else {\n throw RS_Exception;\n }\n }\n if (ret === undefined && !(name in obj)) {\n if (defval === undefined) {\n throw new AttributeError("The attribute " + name + " is not present");\n }\n ret = defval;\n }\n return ret;\n};\nif (!RS_getattr.__argnames__) Object.defineProperties(RS_getattr, {\n __argnames__ : {value: ["obj", "name", "defval"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_setattr(obj, name, value) {\n obj[(typeof name === "number" && name < 0) ? obj.length + name : name] = value;\n};\nif (!RS_setattr.__argnames__) Object.defineProperties(RS_setattr, {\n __argnames__ : {value: ["obj", "name", "value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_hasattr(obj, name) {\n return name in obj;\n};\nif (!RS_hasattr.__argnames__) Object.defineProperties(RS_hasattr, {\n __argnames__ : {value: ["obj", "name"]},\n __module__ : {value: "__main__"}\n});\n\nRS_len = (function() {\n var RS_anonfunc = function () {\n function len(obj) {\n if (RS_arraylike(obj)) {\n return obj.length;\n }\n if (typeof obj.__len__ === "function") {\n return obj.__len__();\n }\n if (obj instanceof Set || obj instanceof Map) {\n return obj.size;\n }\n return Object.keys(obj).length;\n };\n if (!len.__argnames__) Object.defineProperties(len, {\n __argnames__ : {value: ["obj"]},\n __module__ : {value: "__main__"}\n });\n\n function len5(obj) {\n if (RS_arraylike(obj)) {\n return obj.length;\n }\n if (typeof obj.__len__ === "function") {\n return obj.__len__();\n }\n return Object.keys(obj).length;\n };\n if (!len5.__argnames__) Object.defineProperties(len5, {\n __argnames__ : {value: ["obj"]},\n __module__ : {value: "__main__"}\n });\n\n return (typeof Set === "function" && typeof Map === "function") ? len : len5;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})()();\nfunction RS_get_module(name) {\n return RS_modules[(typeof name === "number" && name < 0) ? RS_modules.length + name : name];\n};\nif (!RS_get_module.__argnames__) Object.defineProperties(RS_get_module, {\n __argnames__ : {value: ["name"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_pow(x, y, z) {\n var ans;\n ans = Math.pow(x, y);\n if (z !== undefined) {\n ans %= z;\n }\n return ans;\n};\nif (!RS_pow.__argnames__) Object.defineProperties(RS_pow, {\n __argnames__ : {value: ["x", "y", "z"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_type(x) {\n return x.constructor;\n};\nif (!RS_type.__argnames__) Object.defineProperties(RS_type, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_divmod(x, y) {\n var d;\n if (y === 0) {\n throw new ZeroDivisionError("integer division or modulo by zero");\n }\n d = Math.floor(x / y);\n return [d, x - d * y];\n};\nif (!RS_divmod.__argnames__) Object.defineProperties(RS_divmod, {\n __argnames__ : {value: ["x", "y"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_max() {\n var kwargs = arguments[arguments.length-1];\n if (kwargs === null || typeof kwargs !== "object" || kwargs [RS_kwargs_symbol] !== true) kwargs = {};\n var args = Array.prototype.slice.call(arguments, 0);\n if (kwargs !== null && typeof kwargs === "object" && kwargs [RS_kwargs_symbol] === true) args.pop();\n var args, x;\n if (args.length === 0) {\n if (kwargs.defval !== undefined) {\n return kwargs.defval;\n }\n throw new TypeError("expected at least one argument");\n }\n if (args.length === 1) {\n args = args[0];\n }\n if (kwargs.key) {\n args = (function() {\n var RS_Iter = RS_Iterable(args), RS_Result = [], x;\n for (var RS_Index = 0; RS_Index < RS_Iter.length; RS_Index++) {\n x = RS_Iter[RS_Index];\n RS_Result.push(kwargs.key(x));\n }\n RS_Result = RS_list_constructor(RS_Result);\n return RS_Result;\n })();\n }\n if (!Array.isArray(args)) {\n args = list(args);\n }\n if (args.length) {\n return this.apply(null, args);\n }\n if (kwargs.defval !== undefined) {\n return kwargs.defval;\n }\n throw new TypeError("expected at least one argument");\n};\nif (!RS_max.__handles_kwarg_interpolation__) Object.defineProperties(RS_max, {\n __handles_kwarg_interpolation__ : {value: true},\n __module__ : {value: "__main__"}\n});\n\nvar abs = Math.abs, max = RS_max.bind(Math.max), min = RS_max.bind(Math.min), bool = RS_bool, type = RS_type;\nvar float = RS_float, int = RS_int, arraylike = RS_arraylike_creator(), RS_arraylike = arraylike;\nvar print = RS_print, id = RS_id, get_module = RS_get_module, pow = RS_pow, divmod = RS_divmod;\nvar dir = RS_dir, ord = RS_ord, chr = RS_chr, bin = RS_bin, hex = RS_hex, callable = RS_callable;\nvar enumerate = RS_enumerate, iter = RS_iter, reversed = RS_reversed, len = RS_len;\nvar range = RS_range, getattr = RS_getattr, setattr = RS_setattr, hasattr = RS_hasattr;function RS_equals(a, b) {\n var RS_unpack, akeys, bkeys, key;\n if (a === b) {\n return true;\n }\n if (a && typeof a.__eq__ === "function") {\n return a.__eq__(b);\n }\n if (b && typeof b.__eq__ === "function") {\n return b.__eq__(a);\n }\n if (RS_arraylike(a) && RS_arraylike(b)) {\n if ((a.length !== b.length && (typeof a.length !== "object" || RS_not_equals(a.length, b.length)))) {\n return false;\n }\n for (var i=0; i < a.length; i++) {\n if (!(((a[(typeof i === "number" && i < 0) ? a.length + i : i] === b[(typeof i === "number" && i < 0) ? b.length + i : i] || typeof a[(typeof i === "number" && i < 0) ? a.length + i : i] === "object" && RS_equals(a[(typeof i === "number" && i < 0) ? a.length + i : i], b[(typeof i === "number" && i < 0) ? b.length + i : i]))))) {\n return false;\n }\n }\n return true;\n }\n if (typeof a === "object" && typeof b === "object" && a !== null && b !== null && (a.constructor === Object && b.constructor === Object || Object.getPrototypeOf(a) === null && Object.getPrototypeOf(b) === null)) {\n RS_unpack = [Object.keys(a), Object.keys(b)];\n akeys = RS_unpack[0];\n bkeys = RS_unpack[1];\n if (akeys.length !== bkeys.length) {\n return false;\n }\n for (var j=0; j < akeys.length; j++) {\n key = akeys[(typeof j === "number" && j < 0) ? akeys.length + j : j];\n if (!(((a[(typeof key === "number" && key < 0) ? a.length + key : key] === b[(typeof key === "number" && key < 0) ? b.length + key : key] || typeof a[(typeof key === "number" && key < 0) ? a.length + key : key] === "object" && RS_equals(a[(typeof key === "number" && key < 0) ? a.length + key : key], b[(typeof key === "number" && key < 0) ? b.length + key : key]))))) {\n return false;\n }\n }\n return true;\n }\n return false;\n};\nif (!RS_equals.__argnames__) Object.defineProperties(RS_equals, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_not_equals(a, b) {\n if (a === b) {\n return false;\n }\n if (a && typeof a.__ne__ === "function") {\n return a.__ne__(b);\n }\n if (b && typeof b.__ne__ === "function") {\n return b.__ne__(a);\n }\n return !RS_equals(a, b);\n};\nif (!RS_not_equals.__argnames__) Object.defineProperties(RS_not_equals, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "__main__"}\n});\n\nvar equals = RS_equals;\nfunction RS_list_extend(iterable) {\n var start, iterator, result;\n if (Array.isArray(iterable) || typeof iterable === "string") {\n start = this.length;\n this.length += iterable.length;\n for (var i = 0; i < iterable.length; i++) {\n (RS_expr_temp = this)[RS_bound_index(start + i, RS_expr_temp)] = iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i];\n }\n } else {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done) {\n this.push(result.value);\n result = iterator.next();\n }\n }\n};\nif (!RS_list_extend.__argnames__) Object.defineProperties(RS_list_extend, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_index(val, start, stop) {\n var idx;\n start = start || 0;\n if (start < 0) {\n start = this.length + start;\n }\n if (start < 0) {\n throw new ValueError(val + " is not in list");\n }\n if (stop === undefined) {\n idx = this.indexOf(val, start);\n if (idx === -1) {\n throw new ValueError(val + " is not in list");\n }\n return idx;\n }\n if (stop < 0) {\n stop = this.length + stop;\n }\n for (var i = start; i < stop; i++) {\n if (((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === val || typeof (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === "object" && RS_equals((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i], val))) {\n return i;\n }\n }\n throw new ValueError(val + " is not in list");\n};\nif (!RS_list_index.__argnames__) Object.defineProperties(RS_list_index, {\n __argnames__ : {value: ["val", "start", "stop"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_pop(index) {\n var ans;\n if (this.length === 0) {\n throw new IndexError("list is empty");\n }\n if (index === undefined) {\n index = -1;\n }\n ans = this.splice(index, 1);\n if (!ans.length) {\n throw new IndexError("pop index out of range");\n }\n return ans[0];\n};\nif (!RS_list_pop.__argnames__) Object.defineProperties(RS_list_pop, {\n __argnames__ : {value: ["index"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_remove(value) {\n var idx;\n idx = this.indexOf(value);\n if (idx === -1) {\n throw new ValueError(value + " not in list");\n }\n this.splice(idx, 1);\n};\nif (!RS_list_remove.__argnames__) Object.defineProperties(RS_list_remove, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_to_string() {\n return "[" + this.join(", ") + "]";\n};\nif (!RS_list_to_string.__module__) Object.defineProperties(RS_list_to_string, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_insert(index, val) {\n if (index < 0) {\n index += this.length;\n }\n index = min(this.length, max(index, 0));\n if (index === 0) {\n this.unshift(val);\n return;\n }\n for (var i = this.length; i > index; i--) {\n (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] = (RS_expr_temp = this)[RS_bound_index(i - 1, RS_expr_temp)];\n }\n (RS_expr_temp = this)[(typeof index === "number" && index < 0) ? RS_expr_temp.length + index : index] = val;\n};\nif (!RS_list_insert.__argnames__) Object.defineProperties(RS_list_insert, {\n __argnames__ : {value: ["index", "val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_copy() {\n return RS_list_constructor(this);\n};\nif (!RS_list_copy.__module__) Object.defineProperties(RS_list_copy, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_clear() {\n this.length = 0;\n};\nif (!RS_list_clear.__module__) Object.defineProperties(RS_list_clear, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_as_array() {\n return Array.prototype.slice.call(this);\n};\nif (!RS_list_as_array.__module__) Object.defineProperties(RS_list_as_array, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_count(value) {\n return this.reduce((function() {\n var RS_anonfunc = function (n, val) {\n return n + (val === value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["n", "val"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })(), 0);\n};\nif (!RS_list_count.__argnames__) Object.defineProperties(RS_list_count, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_sort_key(value) {\n var t;\n t = typeof value;\n if (t === "string" || t === "number") {\n return value;\n }\n return value.toString();\n};\nif (!RS_list_sort_key.__argnames__) Object.defineProperties(RS_list_sort_key, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_sort_cmp(a, b, ap, bp) {\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return ap - bp;\n};\nif (!RS_list_sort_cmp.__argnames__) Object.defineProperties(RS_list_sort_cmp, {\n __argnames__ : {value: ["a", "b", "ap", "bp"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_sort() {\n var key = (arguments[0] === undefined || ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? RS_list_sort.__defaults__.key : arguments[0];\n var reverse = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? RS_list_sort.__defaults__.reverse : arguments[1];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "key")){\n key = RS_kwargs_obj.key;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "reverse")){\n reverse = RS_kwargs_obj.reverse;\n }\n var mult, keymap, posmap, k;\n key = key || RS_list_sort_key;\n mult = (reverse) ? -1 : 1;\n keymap = dict();\n posmap = dict();\n for (var i=0; i < this.length; i++) {\n k = (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n keymap.set(k, key(k));\n posmap.set(k, i);\n }\n this.sort((function() {\n var RS_anonfunc = function (a, b) {\n return mult * RS_list_sort_cmp(keymap.get(a), keymap.get(b), posmap.get(a), posmap.get(b));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["a", "b"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })());\n};\nif (!RS_list_sort.__defaults__) Object.defineProperties(RS_list_sort, {\n __defaults__ : {value: {key:null, reverse:false}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["key", "reverse"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_concat() {\n var ans;\n ans = Array.prototype.concat.apply(this, arguments);\n RS_list_decorate(ans);\n return ans;\n};\nif (!RS_list_concat.__module__) Object.defineProperties(RS_list_concat, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_slice() {\n var ans;\n ans = Array.prototype.slice.apply(this, arguments);\n RS_list_decorate(ans);\n return ans;\n};\nif (!RS_list_slice.__module__) Object.defineProperties(RS_list_slice, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_iterator(value) {\n var self;\n self = this;\n return (function(){\n var RS_d = {};\n RS_d["_i"] = -1;\n RS_d["_list"] = self;\n RS_d["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._list.length) {\n return (function(){\n var RS_d = {};\n RS_d["done"] = true;\n return RS_d;\n }).call(this);\n }\n return (function(){\n var RS_d = {};\n RS_d["done"] = false;\n RS_d["value"] = (RS_expr_temp = this._list)[RS_bound_index(this._i, RS_expr_temp)];\n return RS_d;\n }).call(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n};\nif (!RS_list_iterator.__argnames__) Object.defineProperties(RS_list_iterator, {\n __argnames__ : {value: ["value"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_len() {\n return this.length;\n};\nif (!RS_list_len.__module__) Object.defineProperties(RS_list_len, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_contains(val) {\n for (var i = 0; i < this.length; i++) {\n if (((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === val || typeof (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === "object" && RS_equals((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i], val))) {\n return true;\n }\n }\n return false;\n};\nif (!RS_list_contains.__argnames__) Object.defineProperties(RS_list_contains, {\n __argnames__ : {value: ["val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_eq(other) {\n if (!RS_arraylike(other)) {\n return false;\n }\n if ((this.length !== other.length && (typeof this.length !== "object" || RS_not_equals(this.length, other.length)))) {\n return false;\n }\n for (var i = 0; i < this.length; i++) {\n if (!((((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === other[(typeof i === "number" && i < 0) ? other.length + i : i] || typeof (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] === "object" && RS_equals((RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i], other[(typeof i === "number" && i < 0) ? other.length + i : i]))))) {\n return false;\n }\n }\n return true;\n};\nif (!RS_list_eq.__argnames__) Object.defineProperties(RS_list_eq, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_decorate(ans) {\n ans.append = Array.prototype.push;\n ans.toString = RS_list_to_string;\n ans.inspect = RS_list_to_string;\n ans.extend = RS_list_extend;\n ans.index = RS_list_index;\n ans.pypop = RS_list_pop;\n ans.remove = RS_list_remove;\n ans.insert = RS_list_insert;\n ans.copy = RS_list_copy;\n ans.clear = RS_list_clear;\n ans.count = RS_list_count;\n ans.concat = RS_list_concat;\n ans.pysort = RS_list_sort;\n ans.slice = RS_list_slice;\n ans.as_array = RS_list_as_array;\n ans.__len__ = RS_list_len;\n ans.__contains__ = RS_list_contains;\n ans.__eq__ = RS_list_eq;\n ans.constructor = RS_list_constructor;\n if (typeof ans[RS_iterator_symbol] !== "function") {\n ans[RS_iterator_symbol] = RS_list_iterator;\n }\n return ans;\n};\nif (!RS_list_decorate.__argnames__) Object.defineProperties(RS_list_decorate, {\n __argnames__ : {value: ["ans"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_list_constructor(iterable) {\n var ans, iterator, result;\n if (iterable === undefined) {\n ans = [];\n } else if (RS_arraylike(iterable)) {\n ans = new Array(iterable.length);\n for (var i = 0; i < iterable.length; i++) {\n ans[(typeof i === "number" && i < 0) ? ans.length + i : i] = iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i];\n }\n } else if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n ans = RS_list_decorate([]);\n result = iterator.next();\n while (!result.done) {\n ans.push(result.value);\n result = iterator.next();\n }\n } else if (typeof iterable === "number") {\n ans = new Array(iterable);\n } else {\n ans = Object.keys(iterable);\n }\n return RS_list_decorate(ans);\n};\nif (!RS_list_constructor.__argnames__) Object.defineProperties(RS_list_constructor, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_list_constructor.__name__ = "list";\nvar list = RS_list_constructor, list_wrap = RS_list_decorate;\nfunction sorted() {\n var iterable = ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true) ? undefined : arguments[0];\n var key = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? sorted.__defaults__.key : arguments[1];\n var reverse = (arguments[2] === undefined || ( 2 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? sorted.__defaults__.reverse : arguments[2];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "key")){\n key = RS_kwargs_obj.key;\n }\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "reverse")){\n reverse = RS_kwargs_obj.reverse;\n }\n var ans;\n ans = RS_list_constructor(iterable);\n ans.pysort(key, reverse);\n return ans;\n};\nif (!sorted.__defaults__) Object.defineProperties(sorted, {\n __defaults__ : {value: {key:null, reverse:false}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["iterable", "key", "reverse"]},\n __module__ : {value: "__main__"}\n});\n\nvar RS_global_object_id = 0, RS_set_implementation;\nfunction RS_set_keyfor(x) {\n var t, ans;\n t = typeof x;\n if (t === "string" || t === "number" || t === "boolean") {\n return "_" + t[0] + x;\n }\n if (x === null) {\n return "__!@#$0";\n }\n ans = x.RS_hash_key_prop;\n if (ans === undefined) {\n ans = "_!@#$" + (++RS_global_object_id);\n Object.defineProperty(x, "RS_hash_key_prop", (function(){\n var RS_d = {};\n RS_d["value"] = ans;\n return RS_d;\n }).call(this));\n }\n return ans;\n};\nif (!RS_set_keyfor.__argnames__) Object.defineProperties(RS_set_keyfor, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_set_polyfill() {\n this._store = {};\n this.size = 0;\n};\nif (!RS_set_polyfill.__module__) Object.defineProperties(RS_set_polyfill, {\n __module__ : {value: "__main__"}\n});\n\nRS_set_polyfill.prototype.add = (function() {\n var RS_anonfunc = function (x) {\n var key;\n key = RS_set_keyfor(x);\n if (!Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size += 1;\n (RS_expr_temp = this._store)[(typeof key === "number" && key < 0) ? RS_expr_temp.length + key : key] = x;\n }\n return this;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.clear = (function() {\n var RS_anonfunc = function (x) {\n this._store = {};\n this.size = 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.delete = (function() {\n var RS_anonfunc = function (x) {\n var key;\n key = RS_set_keyfor(x);\n if (Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size -= 1;\n delete this._store[key];\n return true;\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.has = (function() {\n var RS_anonfunc = function (x) {\n return Object.prototype.hasOwnProperty.call(this._store, RS_set_keyfor(x));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set_polyfill.prototype.values = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nif (typeof Set !== "function" || typeof Set.prototype.delete !== "function") {\n RS_set_implementation = RS_set_polyfill;\n} else {\n RS_set_implementation = Set;\n}\nfunction RS_set(iterable) {\n var ans, s, iterator, result, keys;\n if (this instanceof RS_set) {\n this.jsset = new RS_set_implementation;\n ans = this;\n if (iterable === undefined) {\n return ans;\n }\n s = ans.jsset;\n if (RS_arraylike(iterable)) {\n for (var i = 0; i < iterable.length; i++) {\n s.add(iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i]);\n }\n } else if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done) {\n s.add(result.value);\n result = iterator.next();\n }\n } else {\n keys = Object.keys(iterable);\n for (var j=0; j < keys.length; j++) {\n s.add(keys[(typeof j === "number" && j < 0) ? keys.length + j : j]);\n }\n }\n return ans;\n } else {\n return new RS_set(iterable);\n }\n};\nif (!RS_set.__argnames__) Object.defineProperties(RS_set, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_set.prototype.__name__ = "set";\nObject.defineProperties(RS_set.prototype, (function(){\n var RS_d = {};\n RS_d["length"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsset.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n RS_d["size"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsset.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n return RS_d;\n}).call(this));\nRS_set.prototype.__len__ = (function() {\n var RS_anonfunc = function () {\n return this.jsset.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.has = RS_set.prototype.__contains__ = (function() {\n var RS_anonfunc = function (x) {\n return this.jsset.has(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.add = (function() {\n var RS_anonfunc = function (x) {\n this.jsset.add(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.clear = (function() {\n var RS_anonfunc = function () {\n this.jsset.clear();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.copy = (function() {\n var RS_anonfunc = function () {\n return RS_set(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.discard = (function() {\n var RS_anonfunc = function (x) {\n this.jsset.delete(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this.jsset.values();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.difference = (function() {\n var RS_anonfunc = function () {\n var ans, s, iterator, r, x, has;\n ans = new RS_set;\n s = ans.jsset;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n has = false;\n for (var i = 0; i < arguments.length; i++) {\n if (arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n has = true;\n break;\n }\n }\n if (!has) {\n s.add(x);\n }\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.difference_update = (function() {\n var RS_anonfunc = function () {\n var s, remove, iterator, r, x;\n s = this.jsset;\n remove = [];\n iterator = s.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n for (var i = 0; i < arguments.length; i++) {\n if (arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n remove.push(x);\n break;\n }\n }\n r = iterator.next();\n }\n for (var j = 0; j < remove.length; j++) {\n s.delete(remove[(typeof j === "number" && j < 0) ? remove.length + j : j]);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.intersection = (function() {\n var RS_anonfunc = function () {\n var ans, s, iterator, r, x, has;\n ans = new RS_set;\n s = ans.jsset;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n has = true;\n for (var i = 0; i < arguments.length; i++) {\n if (!arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n has = false;\n break;\n }\n }\n if (has) {\n s.add(x);\n }\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.intersection_update = (function() {\n var RS_anonfunc = function () {\n var s, remove, iterator, r, x;\n s = this.jsset;\n remove = [];\n iterator = s.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n for (var i = 0; i < arguments.length; i++) {\n if (!arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i].has(x)) {\n remove.push(x);\n break;\n }\n }\n r = iterator.next();\n }\n for (var j = 0; j < remove.length; j++) {\n s.delete(remove[(typeof j === "number" && j < 0) ? remove.length + j : j]);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.isdisjoint = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r, x;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n if (other.has(x)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.issubset = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r, x;\n iterator = this.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n if (!other.has(x)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.issuperset = (function() {\n var RS_anonfunc = function (other) {\n var s, iterator, r, x;\n s = this.jsset;\n iterator = other.jsset.values();\n r = iterator.next();\n while (!r.done) {\n x = r.value;\n if (!s.has(x)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.pop = (function() {\n var RS_anonfunc = function () {\n var iterator, r;\n iterator = this.jsset.values();\n r = iterator.next();\n if (r.done) {\n throw new KeyError("pop from an empty set");\n }\n this.jsset.delete(r.value);\n return r.value;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.remove = (function() {\n var RS_anonfunc = function (x) {\n if (!this.jsset.delete(x)) {\n throw new KeyError(x.toString());\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.symmetric_difference = (function() {\n var RS_anonfunc = function (other) {\n return this.union(other).difference(this.intersection(other));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.symmetric_difference_update = (function() {\n var RS_anonfunc = function (other) {\n var common;\n common = this.intersection(other);\n this.update(other);\n this.difference_update(common);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.union = (function() {\n var RS_anonfunc = function () {\n var ans;\n ans = RS_set(this);\n ans.update.apply(ans, arguments);\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.update = (function() {\n var RS_anonfunc = function () {\n var s, iterator, r;\n s = this.jsset;\n for (var i=0; i < arguments.length; i++) {\n iterator = arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i][RS_iterator_symbol]();\n r = iterator.next();\n while (!r.done) {\n s.add(r.value);\n r = iterator.next();\n }\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.toString = RS_set.prototype.__repr__ = RS_set.prototype.__str__ = RS_set.prototype.inspect = (function() {\n var RS_anonfunc = function () {\n return "{" + list(this).join(", ") + "}";\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_set.prototype.__eq__ = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r;\n if (!other instanceof this.constructor) {\n return false;\n }\n if (other.size !== this.size) {\n return false;\n }\n if (other.size === 0) {\n return true;\n }\n iterator = other[RS_iterator_symbol]();\n r = iterator.next();\n while (!r.done) {\n if (!this.has(r.value)) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nfunction RS_set_wrap(x) {\n var ans;\n ans = new RS_set;\n ans.jsset = x;\n return ans;\n};\nif (!RS_set_wrap.__argnames__) Object.defineProperties(RS_set_wrap, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nvar set = RS_set, set_wrap = RS_set_wrap;\nvar RS_dict_implementation;\nfunction RS_dict_polyfill() {\n this._store = {};\n this.size = 0;\n};\nif (!RS_dict_polyfill.__module__) Object.defineProperties(RS_dict_polyfill, {\n __module__ : {value: "__main__"}\n});\n\nRS_dict_polyfill.prototype.set = (function() {\n var RS_anonfunc = function (x, value) {\n var key;\n key = RS_set_keyfor(x);\n if (!Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size += 1;\n }\n (RS_expr_temp = this._store)[(typeof key === "number" && key < 0) ? RS_expr_temp.length + key : key] = [x, value];\n return this;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x", "value"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.clear = (function() {\n var RS_anonfunc = function (x) {\n this._store = {};\n this.size = 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.delete = (function() {\n var RS_anonfunc = function (x) {\n var key;\n key = RS_set_keyfor(x);\n if (Object.prototype.hasOwnProperty.call(this._store, key)) {\n this.size -= 1;\n delete this._store[key];\n return true;\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.has = (function() {\n var RS_anonfunc = function (x) {\n return Object.prototype.hasOwnProperty.call(this._store, RS_set_keyfor(x));\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.get = (function() {\n var RS_anonfunc = function (x) {\n try {\n return (RS_expr_temp = this._store)[RS_bound_index(RS_set_keyfor(x), RS_expr_temp)][1];\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof TypeError) {\n return undefined;\n } else {\n throw RS_Exception;\n }\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.values = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]][1]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.keys = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]][0]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict_polyfill.prototype.entries = (function() {\n var RS_anonfunc = function (x) {\n var ans;\n ans = {\'_keys\': Object.keys(this._store), \'_i\':-1, \'_s\':this._store};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n this._i += 1;\n if (this._i >= this._keys.length) {\n return {\'done\': true};\n }\n return {\'done\':false, \'value\':this._s[this._keys[this._i]]};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nif (typeof Map !== "function" || typeof Map.prototype.delete !== "function") {\n RS_dict_implementation = RS_dict_polyfill;\n} else {\n RS_dict_implementation = Map;\n}\nfunction RS_dict() {\n var iterable = ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true) ? undefined : arguments[0];\n var kw = arguments[arguments.length-1];\n if (kw === null || typeof kw !== "object" || kw [RS_kwargs_symbol] !== true) kw = {};\n if (this instanceof RS_dict) {\n this.jsmap = new RS_dict_implementation;\n if (iterable !== undefined) {\n this.update(iterable);\n }\n this.update(kw);\n return this;\n } else {\n return RS_interpolate_kwargs_constructor.call(Object.create(RS_dict.prototype), false, RS_dict, [iterable].concat([RS_desugar_kwargs(kw)]));\n }\n};\nif (!RS_dict.__handles_kwarg_interpolation__) Object.defineProperties(RS_dict, {\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_dict.prototype.__name__ = "dict";\nObject.defineProperties(RS_dict.prototype, (function(){\n var RS_d = {};\n RS_d["length"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n RS_d["size"] = (function(){\n var RS_d = {};\n RS_d["get"] = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n return RS_d;\n}).call(this));\nRS_dict.prototype.__len__ = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.size;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.has = RS_dict.prototype.__contains__ = (function() {\n var RS_anonfunc = function (x) {\n return this.jsmap.has(x);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.set = RS_dict.prototype.__setitem__ = (function() {\n var RS_anonfunc = function (key, value) {\n this.jsmap.set(key, value);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "value"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.__delitem__ = (function() {\n var RS_anonfunc = function (key) {\n this.jsmap.delete(key);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.clear = (function() {\n var RS_anonfunc = function () {\n this.jsmap.clear();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.copy = (function() {\n var RS_anonfunc = function () {\n return RS_dict(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.keys = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.keys();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.values = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.values();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.items = RS_dict.prototype.entries = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.entries();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this.jsmap.keys();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.__getitem__ = (function() {\n var RS_anonfunc = function (key) {\n var ans;\n ans = this.jsmap.get(key);\n if (ans === undefined && !this.jsmap.has(key)) {\n throw new KeyError(key + "");\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.get = (function() {\n var RS_anonfunc = function (key, defval) {\n var ans;\n ans = this.jsmap.get(key);\n if (ans === undefined && !this.jsmap.has(key)) {\n return (defval === undefined) ? null : defval;\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "defval"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.set_default = (function() {\n var RS_anonfunc = function (key, defval) {\n var j;\n j = this.jsmap;\n if (!j.has(key)) {\n j.set(key, defval);\n return defval;\n }\n return j.get(key);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "defval"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.fromkeys = RS_dict.prototype.fromkeys = (function() {\n var RS_anonfunc = function () {\n var iterable = ( 0 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true) ? undefined : arguments[0];\n var value = (arguments[1] === undefined || ( 1 === arguments.length-1 && arguments[arguments.length-1] !== null && typeof arguments[arguments.length-1] === "object" && arguments[arguments.length-1] [RS_kwargs_symbol] === true)) ? RS_anonfunc.__defaults__.value : arguments[1];\n var RS_kwargs_obj = arguments[arguments.length-1];\n if (RS_kwargs_obj === null || typeof RS_kwargs_obj !== "object" || RS_kwargs_obj [RS_kwargs_symbol] !== true) RS_kwargs_obj = {};\n if (Object.prototype.hasOwnProperty.call(RS_kwargs_obj, "value")){\n value = RS_kwargs_obj.value;\n }\n var ans, iterator, r;\n ans = RS_dict();\n iterator = iter(iterable);\n r = iterator.next();\n while (!r.done) {\n ans.set(r.value, value);\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__defaults__) Object.defineProperties(RS_anonfunc, {\n __defaults__ : {value: {value:null}},\n __handles_kwarg_interpolation__ : {value: true},\n __argnames__ : {value: ["iterable", "value"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.pop = (function() {\n var RS_anonfunc = function (key, defval) {\n var ans;\n ans = this.jsmap.get(key);\n if (ans === undefined && !this.jsmap.has(key)) {\n if (defval === undefined) {\n throw new KeyError(key);\n }\n return defval;\n }\n this.jsmap.delete(key);\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["key", "defval"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.popitem = (function() {\n var RS_anonfunc = function () {\n var r;\n r = this.jsmap.entries().next();\n if (r.done) {\n throw new KeyError("dict is empty");\n }\n this.jsmap.delete(r.value[0]);\n return r.value;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.update = (function() {\n var RS_anonfunc = function () {\n var m, iterable, iterator, result, keys;\n if (arguments.length === 0) {\n return;\n }\n m = this.jsmap;\n iterable = arguments[0];\n if (Array.isArray(iterable)) {\n for (var i = 0; i < iterable.length; i++) {\n m.set(iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i][0], iterable[(typeof i === "number" && i < 0) ? iterable.length + i : i][1]);\n }\n } else if (iterable instanceof RS_dict) {\n iterator = iterable.items();\n result = iterator.next();\n while (!result.done) {\n m.set(result.value[0], result.value[1]);\n result = iterator.next();\n }\n } else if (typeof Map === "function" && iterable instanceof Map) {\n iterator = iterable.entries();\n result = iterator.next();\n while (!result.done) {\n m.set(result.value[0], result.value[1]);\n result = iterator.next();\n }\n } else if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done) {\n m.set(result.value[0], result.value[1]);\n result = iterator.next();\n }\n } else {\n keys = Object.keys(iterable);\n for (var j=0; j < keys.length; j++) {\n if (keys[(typeof j === "number" && j < 0) ? keys.length + j : j] !== RS_iterator_symbol) {\n m.set(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], iterable[RS_bound_index(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], iterable)]);\n }\n }\n }\n if (arguments.length > 1) {\n RS_dict.prototype.update.call(this, arguments[1]);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.toString = RS_dict.prototype.inspect = RS_dict.prototype.__str__ = RS_dict.prototype.__repr__ = (function() {\n var RS_anonfunc = function () {\n var entries, iterator, r;\n entries = [];\n iterator = this.jsmap.entries();\n r = iterator.next();\n while (!r.done) {\n entries.push(RS_repr(r.value[0]) + ": " + RS_repr(r.value[1]));\n r = iterator.next();\n }\n return "{" + entries.join(", ") + "}";\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.__eq__ = (function() {\n var RS_anonfunc = function (other) {\n var iterator, r, x;\n if (!(other instanceof this.constructor)) {\n return false;\n }\n if (other.size !== this.size) {\n return false;\n }\n if (other.size === 0) {\n return true;\n }\n iterator = other.items();\n r = iterator.next();\n while (!r.done) {\n x = this.jsmap.get(r.value[0]);\n if (x === undefined && !this.jsmap.has(r.value[0]) || x !== r.value[1]) {\n return false;\n }\n r = iterator.next();\n }\n return true;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_dict.prototype.as_object = (function() {\n var RS_anonfunc = function (other) {\n var ans, iterator, r;\n ans = {};\n iterator = this.jsmap.entries();\n r = iterator.next();\n while (!r.done) {\n ans[RS_bound_index(r.value[0], ans)] = r.value[1];\n r = iterator.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["other"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nfunction RS_dict_wrap(x) {\n var ans;\n ans = new RS_dict;\n ans.jsmap = x;\n return ans;\n};\nif (!RS_dict_wrap.__argnames__) Object.defineProperties(RS_dict_wrap, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nvar dict = RS_dict, dict_wrap = RS_dict_wrap;// }}}\nvar NameError;\nNameError = ReferenceError;\nfunction Exception() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n Exception.prototype.__init__.apply(this, arguments);\n}\nRS_extends(Exception, Error);\nException.prototype.__init__ = function __init__(message) {\n var self = this;\n self.message = message;\n self.stack = (new Error).stack;\n self.name = self.constructor.name;\n};\nif (!Exception.prototype.__init__.__argnames__) Object.defineProperties(Exception.prototype.__init__, {\n __argnames__ : {value: ["message"]},\n __module__ : {value: "__main__"}\n});\nException.__argnames__ = Exception.prototype.__init__.__argnames__;\nException.__handles_kwarg_interpolation__ = Exception.prototype.__init__.__handles_kwarg_interpolation__;\nException.prototype.__repr__ = function __repr__() {\n var self = this;\n return self.name + ": " + self.message;\n};\nif (!Exception.prototype.__repr__.__module__) Object.defineProperties(Exception.prototype.__repr__, {\n __module__ : {value: "__main__"}\n});\nException.prototype.__str__ = function __str__ () {\n if(Error.prototype.__str__) return Error.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(Exception.prototype, "__bases__", {value: [Error]});\n\nfunction AttributeError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AttributeError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(AttributeError, Exception);\nAttributeError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nAttributeError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nAttributeError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(AttributeError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction IndexError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n IndexError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(IndexError, Exception);\nIndexError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nIndexError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nIndexError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(IndexError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction KeyError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n KeyError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(KeyError, Exception);\nKeyError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nKeyError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nKeyError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(KeyError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction ValueError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n ValueError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(ValueError, Exception);\nValueError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nValueError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nValueError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(ValueError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction UnicodeDecodeError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n UnicodeDecodeError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(UnicodeDecodeError, Exception);\nUnicodeDecodeError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nUnicodeDecodeError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nUnicodeDecodeError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(UnicodeDecodeError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction AssertionError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n AssertionError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(AssertionError, Exception);\nAssertionError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nAssertionError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nAssertionError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(AssertionError.prototype, "__bases__", {value: [Exception]});\n\n\nfunction ZeroDivisionError() {\n if (this.RS_object_id === undefined) Object.defineProperty(this, "RS_object_id", {"value":++RS_object_counter});\n ZeroDivisionError.prototype.__init__.apply(this, arguments);\n}\nRS_extends(ZeroDivisionError, Exception);\nZeroDivisionError.prototype.__init__ = function __init__ () {\n Exception.prototype.__init__ && Exception.prototype.__init__.apply(this, arguments);\n};\nZeroDivisionError.prototype.__repr__ = function __repr__ () {\n if(Exception.prototype.__repr__) return Exception.prototype.__repr__.call(this);\n return "<" + __name__ + "." + this.constructor.name + " #" + this.RS_object_id + ">";\n};\nZeroDivisionError.prototype.__str__ = function __str__ () {\n if(Exception.prototype.__str__) return Exception.prototype.__str__.call(this);\nreturn this.__repr__();\n};\nObject.defineProperty(ZeroDivisionError.prototype, "__bases__", {value: [Exception]});\n\nvar RS_in, RS_desugar_kwargs, RS_exists;\nfunction RS_eslice(arr, step, start, end) {\n var is_string;\n if (typeof arr === "string" || arr instanceof String) {\n is_string = true;\n arr = arr.split("");\n }\n if (step < 0) {\n step = -step;\n arr = arr.slice().reverse();\n if (typeof start !== "undefined") {\n start = arr.length - start - 1;\n }\n if (typeof end !== "undefined") {\n end = arr.length - end - 1;\n }\n }\n if (typeof start === "undefined") {\n start = 0;\n }\n if (typeof end === "undefined") {\n end = arr.length;\n }\n arr = arr.slice(start, end).filter((function() {\n var RS_anonfunc = function (e, i) {\n return i % step === 0;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["e", "i"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })());\n if (is_string) {\n arr = arr.join("");\n }\n return arr;\n};\nif (!RS_eslice.__argnames__) Object.defineProperties(RS_eslice, {\n __argnames__ : {value: ["arr", "step", "start", "end"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_delslice(arr, step, start, end) {\n var is_string, RS_unpack, indices;\n if (typeof arr === "string" || arr instanceof String) {\n is_string = true;\n arr = arr.split("");\n }\n if (step < 0) {\n if (typeof start === "undefined") {\n start = arr.length;\n }\n if (typeof end === "undefined") {\n end = 0;\n }\n RS_unpack = [end, start, -step];\n start = RS_unpack[0];\n end = RS_unpack[1];\n step = RS_unpack[2];\n }\n if (typeof start === "undefined") {\n start = 0;\n }\n if (typeof end === "undefined") {\n end = arr.length;\n }\n if (step === 1) {\n arr.splice(start, end - start);\n } else {\n if (end > start) {\n indices = [];\n for (var i = start; i < end; i += step) {\n indices.push(i);\n }\n for (var i = indices.length - 1; i >= 0; i--) {\n arr.splice(indices[(typeof i === "number" && i < 0) ? indices.length + i : i], 1);\n }\n }\n }\n if (is_string) {\n arr = arr.join("");\n }\n return arr;\n};\nif (!RS_delslice.__argnames__) Object.defineProperties(RS_delslice, {\n __argnames__ : {value: ["arr", "step", "start", "end"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_flatten(arr) {\n var ans, value;\n ans = RS_list_decorate([]);\n for (var i=0; i < arr.length; i++) {\n value = arr[(typeof i === "number" && i < 0) ? arr.length + i : i];\n if (Array.isArray(value)) {\n ans = ans.concat(RS_flatten(value));\n } else {\n ans.push(value);\n }\n }\n return ans;\n};\nif (!RS_flatten.__argnames__) Object.defineProperties(RS_flatten, {\n __argnames__ : {value: ["arr"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_unpack_asarray(num, iterable) {\n var ans, iterator, result;\n if (RS_arraylike(iterable)) {\n return iterable;\n }\n ans = [];\n if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n result = iterator.next();\n while (!result.done && ans.length < num) {\n ans.push(result.value);\n result = iterator.next();\n }\n }\n return ans;\n};\nif (!RS_unpack_asarray.__argnames__) Object.defineProperties(RS_unpack_asarray, {\n __argnames__ : {value: ["num", "iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_extends(child, parent) {\n child.prototype = Object.create(parent.prototype);\n child.prototype.constructor = child;\n};\nif (!RS_extends.__argnames__) Object.defineProperties(RS_extends, {\n __argnames__ : {value: ["child", "parent"]},\n __module__ : {value: "__main__"}\n});\n\nRS_in = (function() {\n var RS_anonfunc = function () {\n if (typeof Map === "function" && typeof Set === "function") {\n return (function() {\n var RS_anonfunc = function (val, arr) {\n if (typeof arr === "string") {\n return arr.indexOf(val) !== -1;\n }\n if (typeof arr.__contains__ === "function") {\n return arr.__contains__(val);\n }\n if (arr instanceof Map || arr instanceof Set) {\n return arr.has(val);\n }\n if (RS_arraylike(arr)) {\n return RS_list_contains.call(arr, val);\n }\n return Object.prototype.hasOwnProperty.call(arr, val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val", "arr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n }\n return (function() {\n var RS_anonfunc = function (val, arr) {\n if (typeof arr === "string") {\n return arr.indexOf(val) !== -1;\n }\n if (typeof arr.__contains__ === "function") {\n return arr.__contains__(val);\n }\n if (RS_arraylike(arr)) {\n return RS_list_contains.call(arr, val);\n }\n return Object.prototype.hasOwnProperty.call(arr, val);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["val", "arr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})()();\nfunction RS_Iterable(iterable) {\n var iterator, ans, result;\n if (RS_arraylike(iterable)) {\n return iterable;\n }\n if (typeof iterable[RS_iterator_symbol] === "function") {\n iterator = (typeof Map === "function" && iterable instanceof Map) ? iterable.keys() : iterable[RS_iterator_symbol]();\n ans = RS_list_decorate([]);\n result = iterator.next();\n while (!result.done) {\n ans.push(result.value);\n result = iterator.next();\n }\n return ans;\n }\n return Object.keys(iterable);\n};\nif (!RS_Iterable.__argnames__) Object.defineProperties(RS_Iterable, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nRS_desugar_kwargs = (function() {\n var RS_anonfunc = function () {\n if (typeof Object.assign === "function") {\n return (function() {\n var RS_anonfunc = function () {\n var ans;\n ans = Object.create(null);\n ans[RS_kwargs_symbol] = true;\n for (var i = 0; i < arguments.length; i++) {\n Object.assign(ans, arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n }\n return (function() {\n var RS_anonfunc = function () {\n var ans, keys;\n ans = Object.create(null);\n ans[RS_kwargs_symbol] = true;\n for (var i = 0; i < arguments.length; i++) {\n keys = Object.keys(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n for (var j = 0; j < keys.length; j++) {\n ans[RS_bound_index(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], ans)] = (RS_expr_temp = arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i])[RS_bound_index(keys[(typeof j === "number" && j < 0) ? keys.length + j : j], RS_expr_temp)];\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})()();\nfunction RS_interpolate_kwargs(f, supplied_args) {\n var has_prop, kwobj, args, prop;\n if (!f.__argnames__) {\n return f.apply(this, supplied_args);\n }\n has_prop = Object.prototype.hasOwnProperty;\n kwobj = supplied_args.pop();\n if (f.__handles_kwarg_interpolation__) {\n args = new Array(Math.max(supplied_args.length, f.__argnames__.length) + 1);\n args[args.length-1] = kwobj;\n for (var i = 0; i < args.length - 1; i++) {\n if (i < f.__argnames__.length) {\n prop = (RS_expr_temp = f.__argnames__)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n if (has_prop.call(kwobj, prop)) {\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = kwobj[(typeof prop === "number" && prop < 0) ? kwobj.length + prop : prop];\n delete kwobj[prop];\n } else if (i < supplied_args.length) {\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = supplied_args[(typeof i === "number" && i < 0) ? supplied_args.length + i : i];\n }\n } else {\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = supplied_args[(typeof i === "number" && i < 0) ? supplied_args.length + i : i];\n }\n }\n return f.apply(this, args);\n }\n for (var i = 0; i < f.__argnames__.length; i++) {\n prop = (RS_expr_temp = f.__argnames__)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n if (has_prop.call(kwobj, prop)) {\n supplied_args[(typeof i === "number" && i < 0) ? supplied_args.length + i : i] = kwobj[(typeof prop === "number" && prop < 0) ? kwobj.length + prop : prop];\n }\n }\n return f.apply(this, supplied_args);\n};\nif (!RS_interpolate_kwargs.__argnames__) Object.defineProperties(RS_interpolate_kwargs, {\n __argnames__ : {value: ["f", "supplied_args"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_interpolate_kwargs_constructor(apply, f, supplied_args) {\n if (apply) {\n f.apply(this, supplied_args);\n } else {\n RS_interpolate_kwargs.call(this, f, supplied_args);\n }\n return this;\n};\nif (!RS_interpolate_kwargs_constructor.__argnames__) Object.defineProperties(RS_interpolate_kwargs_constructor, {\n __argnames__ : {value: ["apply", "f", "supplied_args"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_getitem(obj, key) {\n if (obj.__getitem__) {\n return obj.__getitem__(key);\n }\n if (typeof key === "number" && key < 0) {\n key += obj.length;\n }\n return obj[(typeof key === "number" && key < 0) ? obj.length + key : key];\n};\nif (!RS_getitem.__argnames__) Object.defineProperties(RS_getitem, {\n __argnames__ : {value: ["obj", "key"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_setitem(obj, key, val) {\n if (obj.__setitem__) {\n obj.__setitem__(key, val);\n } else {\n if (typeof key === "number" && key < 0) {\n key += obj.length;\n }\n obj[(typeof key === "number" && key < 0) ? obj.length + key : key] = val;\n }\n};\nif (!RS_setitem.__argnames__) Object.defineProperties(RS_setitem, {\n __argnames__ : {value: ["obj", "key", "val"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_delitem(obj, key) {\n if (obj.__delitem__) {\n obj.__delitem__(key);\n } else if (typeof obj.splice === "function") {\n obj.splice(key, 1);\n } else {\n if (typeof key === "number" && key < 0) {\n key += obj.length;\n }\n delete obj[key];\n }\n};\nif (!RS_delitem.__argnames__) Object.defineProperties(RS_delitem, {\n __argnames__ : {value: ["obj", "key"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_bound_index(idx, arr) {\n if (typeof idx === "number" && idx < 0) {\n idx += arr.length;\n }\n return idx;\n};\nif (!RS_bound_index.__argnames__) Object.defineProperties(RS_bound_index, {\n __argnames__ : {value: ["idx", "arr"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_splice(arr, val, start, end) {\n start = start || 0;\n if (start < 0) {\n start += arr.length;\n }\n if (end === undefined) {\n end = arr.length;\n }\n if (end < 0) {\n end += arr.length;\n }\n Array.prototype.splice.apply(arr, [start, end - start].concat(val));\n};\nif (!RS_splice.__argnames__) Object.defineProperties(RS_splice, {\n __argnames__ : {value: ["arr", "val", "start", "end"]},\n __module__ : {value: "__main__"}\n});\n\nRS_exists = (function(){\n var RS_d = {};\n RS_d["n"] = (function() {\n var RS_anonfunc = function (expr) {\n return expr !== undefined && expr !== null;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["d"] = (function() {\n var RS_anonfunc = function (expr) {\n if (expr === undefined || expr === null) {\n return Object.create(null);\n }\n return expr;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["c"] = (function() {\n var RS_anonfunc = function (expr) {\n if (typeof expr === "function") {\n return expr;\n }\n return (function() {\n var RS_anonfunc = function () {\n return undefined;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["g"] = (function() {\n var RS_anonfunc = function (expr) {\n if (expr === undefined || expr === null || typeof expr.__getitem__ !== "function") {\n return (function(){\n var RS_d = {};\n RS_d["__getitem__"] = (function() {\n var RS_anonfunc = function () {\n return undefined;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["e"] = (function() {\n var RS_anonfunc = function (expr, alt) {\n return (expr === undefined || expr === null) ? alt : expr;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["expr", "alt"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n}).call(this);\nfunction RS_mixin() {\n var seen, resolved_props, p, target, props, name;\n seen = Object.create(null);\n seen.__argnames__ = seen.__handles_kwarg_interpolation__ = seen.__init__ = seen.__annotations__ = seen.__doc__ = seen.__bind_methods__ = seen.__bases__ = seen.constructor = seen.__class__ = true;\n resolved_props = {};\n p = target = arguments[0].prototype;\n while (p && p !== Object.prototype) {\n props = Object.getOwnPropertyNames(p);\n for (var i = 0; i < props.length; i++) {\n seen[RS_bound_index(props[(typeof i === "number" && i < 0) ? props.length + i : i], seen)] = true;\n }\n p = Object.getPrototypeOf(p);\n }\n for (var c = 1; c < arguments.length; c++) {\n p = arguments[(typeof c === "number" && c < 0) ? arguments.length + c : c].prototype;\n while (p && p !== Object.prototype) {\n props = Object.getOwnPropertyNames(p);\n for (var i = 0; i < props.length; i++) {\n name = props[(typeof i === "number" && i < 0) ? props.length + i : i];\n if (seen[(typeof name === "number" && name < 0) ? seen.length + name : name]) {\n continue;\n }\n seen[(typeof name === "number" && name < 0) ? seen.length + name : name] = true;\n resolved_props[(typeof name === "number" && name < 0) ? resolved_props.length + name : name] = Object.getOwnPropertyDescriptor(p, name);\n }\n p = Object.getPrototypeOf(p);\n }\n }\n Object.defineProperties(target, resolved_props);\n};\nif (!RS_mixin.__module__) Object.defineProperties(RS_mixin, {\n __module__ : {value: "__main__"}\n});\n\nfunction RS_instanceof() {\n var obj, bases, q, cls, p;\n obj = arguments[0];\n bases = "";\n if (obj && obj.constructor && obj.constructor.prototype) {\n bases = obj.constructor.prototype.__bases__ || "";\n }\n for (var i = 1; i < arguments.length; i++) {\n q = arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i];\n if (obj instanceof q) {\n return true;\n }\n if ((q === Array || q === RS_list_constructor) && Array.isArray(obj)) {\n return true;\n }\n if (q === RS_str && (typeof obj === "string" || obj instanceof String)) {\n return true;\n }\n if (q === RS_int && typeof obj === "number" && Number.isInteger(obj)) {\n return true;\n }\n if (q === RS_float && typeof obj === "number" && !Number.isInteger(obj)) {\n return true;\n }\n if (bases.length > 1) {\n for (var c = 1; c < bases.length; c++) {\n cls = bases[(typeof c === "number" && c < 0) ? bases.length + c : c];\n while (cls) {\n if (q === cls) {\n return true;\n }\n p = Object.getPrototypeOf(cls.prototype);\n if (!p) {\n break;\n }\n cls = p.constructor;\n }\n }\n }\n }\n return false;\n};\nif (!RS_instanceof.__module__) Object.defineProperties(RS_instanceof, {\n __module__ : {value: "__main__"}\n});\nfunction sum(iterable, start) {\n var ans, iterator, r;\n if (Array.isArray(iterable)) {\n return iterable.reduce((function() {\n var RS_anonfunc = function (prev, cur) {\n return prev + cur;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["prev", "cur"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })(), start || 0);\n }\n ans = start || 0;\n iterator = iter(iterable);\n r = iterator.next();\n while (!r.done) {\n ans += r.value;\n r = iterator.next();\n }\n return ans;\n};\nif (!sum.__argnames__) Object.defineProperties(sum, {\n __argnames__ : {value: ["iterable", "start"]},\n __module__ : {value: "__main__"}\n});\n\nfunction map() {\n var iterators, func, args, ans;\n iterators = new Array(arguments.length - 1);\n func = arguments[0];\n args = new Array(arguments.length - 1);\n for (var i = 1; i < arguments.length; i++) {\n iterators[RS_bound_index(i - 1, iterators)] = iter(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n }\n ans = {\'_func\':func, \'_iterators\':iterators, \'_args\':args};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var r;\n for (var i = 0; i < this._iterators.length; i++) {\n r = (RS_expr_temp = this._iterators)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].next();\n if (r.done) {\n return {\'done\':true};\n }\n (RS_expr_temp = this._args)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i] = r.value;\n }\n return {\'done\':false, \'value\':this._func.apply(undefined, this._args)};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n};\nif (!map.__module__) Object.defineProperties(map, {\n __module__ : {value: "__main__"}\n});\n\nfunction filter(func_or_none, iterable) {\n var func, ans;\n func = (func_or_none === null) ? RS_bool : func_or_none;\n ans = {\'_func\':func, \'_iterator\':RS_iter(iterable)};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var r;\n r = this._iterator.next();\n while (!r.done) {\n if (this._func(r.value)) {\n return r;\n }\n r = this._iterator.next();\n }\n return {\'done\':true};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n};\nif (!filter.__argnames__) Object.defineProperties(filter, {\n __argnames__ : {value: ["func_or_none", "iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction zip() {\n var iterators, ans;\n iterators = new Array(arguments.length);\n for (var i = 0; i < arguments.length; i++) {\n iterators[(typeof i === "number" && i < 0) ? iterators.length + i : i] = iter(arguments[(typeof i === "number" && i < 0) ? arguments.length + i : i]);\n }\n ans = {\'_iterators\':iterators};\n ans[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n ans["next"] = (function() {\n var RS_anonfunc = function () {\n var args, r;\n args = new Array(this._iterators.length);\n for (var i = 0; i < this._iterators.length; i++) {\n r = (RS_expr_temp = this._iterators)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i].next();\n if (r.done) {\n return {\'done\':true};\n }\n args[(typeof i === "number" && i < 0) ? args.length + i : i] = r.value;\n }\n return {\'done\':false, \'value\':args};\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return ans;\n};\nif (!zip.__module__) Object.defineProperties(zip, {\n __module__ : {value: "__main__"}\n});\n\nfunction any(iterable) {\n var i;\n var RS_Iter0 = RS_Iterable(iterable);\n for (var RS_Index0 = 0; RS_Index0 < RS_Iter0.length; RS_Index0++) {\n i = RS_Iter0[RS_Index0];\n if (i) {\n return true;\n }\n }\n return false;\n};\nif (!any.__argnames__) Object.defineProperties(any, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\n\nfunction all(iterable) {\n var i;\n var RS_Iter1 = RS_Iterable(iterable);\n for (var RS_Index1 = 0; RS_Index1 < RS_Iter1.length; RS_Index1++) {\n i = RS_Iter1[RS_Index1];\n if (!i) {\n return false;\n }\n }\n return true;\n};\nif (!all.__argnames__) Object.defineProperties(all, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n});\nvar decimal_sep, define_str_func, RS_unpack, RS_orig_split, RS_orig_replace;\ndecimal_sep = 1.1.toLocaleString()[1];\nfunction RS_repr_js_builtin(x, as_array) {\n var ans, b, keys, key;\n ans = [];\n b = "{}";\n if (as_array) {\n b = "[]";\n for (var i = 0; i < x.length; i++) {\n ans.push(RS_repr(x[(typeof i === "number" && i < 0) ? x.length + i : i]));\n }\n } else {\n keys = Object.keys(x);\n for (var k = 0; k < keys.length; k++) {\n key = keys[(typeof k === "number" && k < 0) ? keys.length + k : k];\n ans.push(JSON.stringify(key) + ":" + RS_repr(x[(typeof key === "number" && key < 0) ? x.length + key : key]));\n }\n }\n return b[0] + ans.join(", ") + b[1];\n};\nif (!RS_repr_js_builtin.__argnames__) Object.defineProperties(RS_repr_js_builtin, {\n __argnames__ : {value: ["x", "as_array"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_html_element_to_string(elem) {\n var attrs, val, attr, ans;\n attrs = [];\n var RS_Iter0 = RS_Iterable(elem.attributes);\n for (var RS_Index0 = 0; RS_Index0 < RS_Iter0.length; RS_Index0++) {\n attr = RS_Iter0[RS_Index0];\n if (attr.specified) {\n val = attr.value;\n if (val.length > 10) {\n val = val.slice(0, 15) + "...";\n }\n val = JSON.stringify(val);\n attrs.push("" + RS_str.format("{}", attr.name) + "=" + RS_str.format("{}", val) + "");\n }\n }\n attrs = (attrs.length) ? " " + attrs.join(" ") : "";\n ans = "<" + RS_str.format("{}", elem.tagName) + "" + RS_str.format("{}", attrs) + ">";\n return ans;\n};\nif (!RS_html_element_to_string.__argnames__) Object.defineProperties(RS_html_element_to_string, {\n __argnames__ : {value: ["elem"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_repr(x) {\n var ans, name;\n if (x === null) {\n return "None";\n }\n if (x === undefined) {\n return "undefined";\n }\n ans = x;\n if (typeof x.__repr__ === "function") {\n ans = x.__repr__();\n } else if (x === true || x === false) {\n ans = (x) ? "True" : "False";\n } else if (Array.isArray(x)) {\n ans = RS_repr_js_builtin(x, true);\n } else if (typeof x === "function") {\n ans = x.toString();\n } else if (typeof x === "object" && !x.toString) {\n ans = RS_repr_js_builtin(x);\n } else {\n name = Object.prototype.toString.call(x).slice(8, -1);\n if (RS_not_equals("Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".indexOf(name), -1)) {\n return name + "([" + x.map((function() {\n var RS_anonfunc = function (i) {\n return str.format("0x{:02x}", i);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["i"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })()).join(", ") + "])";\n }\n if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) {\n ans = RS_html_element_to_string(x);\n } else {\n ans = (typeof x.toString === "function") ? x.toString() : x;\n }\n if (ans === "[object Object]") {\n return RS_repr_js_builtin(x);\n }\n try {\n ans = JSON.stringify(x);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n } \n }\n }\n return ans + "";\n};\nif (!RS_repr.__argnames__) Object.defineProperties(RS_repr, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\nfunction RS_str(x) {\n var ans, name;\n if (x === null) {\n return "None";\n }\n if (x === undefined) {\n return "undefined";\n }\n ans = x;\n if (typeof x.__str__ === "function") {\n ans = x.__str__();\n } else if (typeof x.__repr__ === "function") {\n ans = x.__repr__();\n } else if (x === true || x === false) {\n ans = (x) ? "True" : "False";\n } else if (Array.isArray(x)) {\n ans = RS_repr_js_builtin(x, true);\n } else if (typeof x.toString === "function") {\n name = Object.prototype.toString.call(x).slice(8, -1);\n if (RS_not_equals("Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".indexOf(name), -1)) {\n return name + "([" + x.map((function() {\n var RS_anonfunc = function (i) {\n return str.format("0x{:02x}", i);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["i"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })()).join(", ") + "])";\n }\n if (typeof HTMLElement !== "undefined" && x instanceof HTMLElement) {\n ans = RS_html_element_to_string(x);\n } else {\n ans = x.toString();\n }\n if (ans === "[object Object]") {\n ans = RS_repr_js_builtin(x);\n }\n } else if (typeof x === "object" && !x.toString) {\n ans = RS_repr_js_builtin(x);\n }\n return ans + "";\n};\nif (!RS_str.__argnames__) Object.defineProperties(RS_str, {\n __argnames__ : {value: ["x"]},\n __module__ : {value: "__main__"}\n});\n\ndefine_str_func = (function() {\n var RS_anonfunc = function (name, func) {\n var f;\n (RS_expr_temp = RS_str.prototype)[(typeof name === "number" && name < 0) ? RS_expr_temp.length + name : name] = func;\n RS_str[(typeof name === "number" && name < 0) ? RS_str.length + name : name] = f = func.call.bind(func);\n if (func.__argnames__) {\n Object.defineProperty(f, "__argnames__", (function(){\n var RS_d = {};\n RS_d["value"] = [\'string\'].concat(func.__argnames__);\n return RS_d;\n }).call(this));\n }\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["name", "func"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_unpack = [String.prototype.split.call.bind(String.prototype.split), String.prototype.replace.call.bind(String.prototype.replace)];\nRS_orig_split = RS_unpack[0];\nRS_orig_replace = RS_unpack[1];\ndefine_str_func("format", (function() {\n var RS_anonfunc = function () {\n var template, args, kwargs, explicit, implicit, idx, split, ans, pos, in_brace, markup, ch;\n template = this;\n if (template === undefined) {\n throw new TypeError("Template is required");\n }\n args = Array.prototype.slice.call(arguments);\n kwargs = {};\n if (args[args.length-1] && args[args.length-1][RS_kwargs_symbol] !== undefined) {\n kwargs = args[args.length-1];\n args = args.slice(0, -1);\n }\n explicit = implicit = false;\n idx = 0;\n split = RS_orig_split;\n if (RS_str.format._template_resolve_pat === undefined) {\n RS_str.format._template_resolve_pat = /[.\\[]/;\n }\n function resolve(arg, object) {\n var RS_unpack, first, key, rest, ans;\n if (!arg) {\n return object;\n }\n RS_unpack = [arg[0], arg.slice(1)];\n first = RS_unpack[0];\n arg = RS_unpack[1];\n key = split(arg, RS_str.format._template_resolve_pat, 1)[0];\n rest = arg.slice(key.length);\n ans = (first === "[") ? object[RS_bound_index(key.slice(0, -1), object)] : getattr(object, key);\n if (ans === undefined) {\n throw new KeyError((first === "[") ? key.slice(0, -1) : key);\n }\n return resolve(rest, ans);\n };\n if (!resolve.__argnames__) Object.defineProperties(resolve, {\n __argnames__ : {value: ["arg", "object"]},\n __module__ : {value: "__main__"}\n });\n\n function resolve_format_spec(format_spec) {\n if (RS_str.format._template_resolve_fs_pat === undefined) {\n RS_str.format._template_resolve_fs_pat = /[{]([a-zA-Z0-9_]+)[}]/g;\n }\n return format_spec.replace(RS_str.format._template_resolve_fs_pat, (function() {\n var RS_anonfunc = function (match, key) {\n if (!Object.prototype.hasOwnProperty.call(kwargs, key)) {\n return "";\n }\n return "" + kwargs[(typeof key === "number" && key < 0) ? kwargs.length + key : key];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["match", "key"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })());\n };\n if (!resolve_format_spec.__argnames__) Object.defineProperties(resolve_format_spec, {\n __argnames__ : {value: ["format_spec"]},\n __module__ : {value: "__main__"}\n });\n\n function set_comma(ans, comma) {\n var sep;\n if (comma !== ",") {\n sep = 1234;\n sep = sep.toLocaleString(undefined, {useGrouping: true})[1];\n ans = str.replace(ans, sep, comma);\n }\n return ans;\n };\n if (!set_comma.__argnames__) Object.defineProperties(set_comma, {\n __argnames__ : {value: ["ans", "comma"]},\n __module__ : {value: "__main__"}\n });\n\n function safe_comma(value, comma) {\n try {\n return set_comma(value.toLocaleString(undefined, {useGrouping: true}), comma);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n return value.toString(10);\n } \n }\n };\n if (!safe_comma.__argnames__) Object.defineProperties(safe_comma, {\n __argnames__ : {value: ["value", "comma"]},\n __module__ : {value: "__main__"}\n });\n\n function safe_fixed(value, precision, comma) {\n if (!comma) {\n return value.toFixed(precision);\n }\n try {\n return set_comma(value.toLocaleString(undefined, {useGrouping: true, minimumFractionDigits: precision, maximumFractionDigits: precision}), comma);\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n {\n return value.toFixed(precision);\n } \n }\n };\n if (!safe_fixed.__argnames__) Object.defineProperties(safe_fixed, {\n __argnames__ : {value: ["value", "precision", "comma"]},\n __module__ : {value: "__main__"}\n });\n\n function apply_formatting(value, format_spec) {\n var RS_unpack, fill, align, sign, fhash, zeropad, width, comma, precision, ftype, is_numeric, is_int, lftype, code, prec, exp, nval, is_positive, left, right;\n if (format_spec.indexOf("{") !== -1) {\n format_spec = resolve_format_spec(format_spec);\n }\n if (RS_str.format._template_format_pat === undefined) {\n RS_str.format._template_format_pat = /([^{}](?=[<>=^]))?([<>=^])?([-+\\x20])?(\\#)?(0)?(\\d+)?([,_])?(?:\\.(\\d+))?([bcdeEfFgGnosxX%])?/;\n }\n try {\n RS_unpack = format_spec.match(RS_str.format._template_format_pat).slice(1);\nRS_unpack = RS_unpack_asarray(9, RS_unpack);\n fill = RS_unpack[0];\n align = RS_unpack[1];\n sign = RS_unpack[2];\n fhash = RS_unpack[3];\n zeropad = RS_unpack[4];\n width = RS_unpack[5];\n comma = RS_unpack[6];\n precision = RS_unpack[7];\n ftype = RS_unpack[8];\n } catch (RS_Exception) {\n RS_last_exception = RS_Exception;\n if (RS_Exception instanceof TypeError) {\n return value;\n } else {\n throw RS_Exception;\n }\n }\n if (zeropad) {\n fill = fill || "0";\n align = align || "=";\n } else {\n fill = fill || " ";\n align = align || ">";\n }\n is_numeric = Number(value) === value;\n is_int = is_numeric && value % 1 === 0;\n precision = parseInt(precision, 10);\n lftype = (ftype || "").toLowerCase();\n if (ftype === "n") {\n is_numeric = true;\n if (is_int) {\n if (comma) {\n throw new ValueError("Cannot specify \',\' with \'n\'");\n }\n value = parseInt(value, 10).toLocaleString();\n } else {\n value = parseFloat(value).toLocaleString();\n }\n } else if ([\'b\', \'c\', \'d\', \'o\', \'x\'].indexOf(lftype) !== -1) {\n value = parseInt(value, 10);\n is_numeric = true;\n if (!isNaN(value)) {\n if (ftype === "b") {\n value = (value >>> 0).toString(2);\n if (fhash) {\n value = "0b" + value;\n }\n } else if (ftype === "c") {\n if (value > 65535) {\n code = value - 65536;\n value = String.fromCharCode(55296 + (code >> 10), 56320 + (code & 1023));\n } else {\n value = String.fromCharCode(value);\n }\n } else if (ftype === "d") {\n if (comma) {\n value = safe_comma(value, comma);\n } else {\n value = value.toString(10);\n }\n } else if (ftype === "o") {\n value = value.toString(8);\n if (fhash) {\n value = "0o" + value;\n }\n } else if (lftype === "x") {\n value = value.toString(16);\n value = (ftype === "x") ? value.toLowerCase() : value.toUpperCase();\n if (fhash) {\n value = "0x" + value;\n }\n }\n }\n } else if ([\'e\',\'f\',\'g\',\'%\'].indexOf(lftype) !== -1) {\n is_numeric = true;\n value = parseFloat(value);\n prec = (isNaN(precision)) ? 6 : precision;\n if (lftype === "e") {\n value = value.toExponential(prec);\n value = (ftype === "E") ? value.toUpperCase() : value.toLowerCase();\n } else if (lftype === "f") {\n value = safe_fixed(value, prec, comma);\n value = (ftype === "F") ? value.toUpperCase() : value.toLowerCase();\n } else if (lftype === "%") {\n value *= 100;\n value = safe_fixed(value, prec, comma) + "%";\n } else if (lftype === "g") {\n prec = max(1, prec);\n exp = parseInt(split(value.toExponential(prec - 1).toLowerCase(), "e")[1], 10);\n if (-4 <= exp && exp < prec) {\n value = safe_fixed(value, prec - 1 - exp, comma);\n } else {\n value = value.toExponential(prec - 1);\n }\n value = value.replace(/0+$/g, "");\n if (value[value.length-1] === decimal_sep) {\n value = value.slice(0, -1);\n }\n if (ftype === "G") {\n value = value.toUpperCase();\n }\n }\n } else {\n if (comma) {\n value = parseInt(value, 10);\n if (isNaN(value)) {\n throw new ValueError("Must use numbers with , or _");\n }\n value = safe_comma(value, comma);\n }\n value += "";\n if (!isNaN(precision)) {\n value = value.slice(0, precision);\n }\n }\n value += "";\n if (is_numeric && sign) {\n nval = Number(value);\n is_positive = !isNaN(nval) && nval >= 0;\n if (is_positive && (sign === " " || sign === "+")) {\n value = sign + value;\n }\n }\n function repeat(char, num) {\n return (new Array(num+1)).join(char);\n };\n if (!repeat.__argnames__) Object.defineProperties(repeat, {\n __argnames__ : {value: ["char", "num"]},\n __module__ : {value: "__main__"}\n });\n\n if (is_numeric && width && width[0] === "0") {\n width = width.slice(1);\n RS_unpack = ["0", "="];\n fill = RS_unpack[0];\n align = RS_unpack[1];\n }\n width = parseInt(width || "-1", 10);\n if (isNaN(width)) {\n throw new ValueError("Invalid width specification: " + width);\n }\n if (fill && value.length < width) {\n if (align === "<") {\n value = value + repeat(fill, width - value.length);\n } else if (align === ">") {\n value = repeat(fill, width - value.length) + value;\n } else if (align === "^") {\n left = Math.floor((width - value.length) / 2);\n right = width - left - value.length;\n value = repeat(fill, left) + value + repeat(fill, right);\n } else if (align === "=") {\n if (RS_in(value[0], "+- ")) {\n value = value[0] + repeat(fill, width - value.length) + value.slice(1);\n } else {\n value = repeat(fill, width - value.length) + value;\n }\n } else {\n throw new ValueError("Unrecognized alignment: " + align);\n }\n }\n return value;\n };\n if (!apply_formatting.__argnames__) Object.defineProperties(apply_formatting, {\n __argnames__ : {value: ["value", "format_spec"]},\n __module__ : {value: "__main__"}\n });\n\n function parse_markup(markup) {\n var key, transformer, format_spec, pos, state, ch;\n key = transformer = format_spec = "";\n pos = 0;\n state = 0;\n while (pos < markup.length) {\n ch = markup[(typeof pos === "number" && pos < 0) ? markup.length + pos : pos];\n if (state === 0) {\n if (ch === "!") {\n state = 1;\n } else if (ch === ":") {\n state = 2;\n } else {\n key += ch;\n }\n } else if (state === 1) {\n if (ch === ":") {\n state = 2;\n } else {\n transformer += ch;\n }\n } else {\n format_spec += ch;\n }\n pos += 1;\n }\n return [key, transformer, format_spec];\n };\n if (!parse_markup.__argnames__) Object.defineProperties(parse_markup, {\n __argnames__ : {value: ["markup"]},\n __module__ : {value: "__main__"}\n });\n\n function render_markup(markup) {\n var RS_unpack, key, transformer, format_spec, lkey, nvalue, object, ans;\n RS_unpack = parse_markup(markup);\nRS_unpack = RS_unpack_asarray(3, RS_unpack);\n key = RS_unpack[0];\n transformer = RS_unpack[1];\n format_spec = RS_unpack[2];\n if (transformer && [\'a\', \'r\', \'s\'].indexOf(transformer) === -1) {\n throw new ValueError("Unknown conversion specifier: " + transformer);\n }\n lkey = key.length && split(key, /[.\\[]/, 1)[0];\n if (lkey) {\n explicit = true;\n if (implicit) {\n throw new ValueError("cannot switch from automatic field numbering to manual field specification");\n }\n nvalue = parseInt(lkey);\n object = (isNaN(nvalue)) ? kwargs[(typeof lkey === "number" && lkey < 0) ? kwargs.length + lkey : lkey] : args[(typeof nvalue === "number" && nvalue < 0) ? args.length + nvalue : nvalue];\n if (object === undefined) {\n if (isNaN(nvalue)) {\n throw new KeyError(lkey);\n }\n throw new IndexError(lkey);\n }\n object = resolve(key.slice(lkey.length), object);\n } else {\n implicit = true;\n if (explicit) {\n throw new ValueError("cannot switch from manual field specification to automatic field numbering");\n }\n if (idx >= args.length) {\n throw new IndexError("Not enough arguments to match template: " + template);\n }\n object = args[(typeof idx === "number" && idx < 0) ? args.length + idx : idx];\n idx += 1;\n }\n if (typeof object === "function") {\n object = object();\n }\n ans = "" + object;\n if (format_spec) {\n ans = apply_formatting(ans, format_spec);\n }\n return ans;\n };\n if (!render_markup.__argnames__) Object.defineProperties(render_markup, {\n __argnames__ : {value: ["markup"]},\n __module__ : {value: "__main__"}\n });\n\n ans = "";\n pos = 0;\n in_brace = 0;\n markup = "";\n while (pos < template.length) {\n ch = template[(typeof pos === "number" && pos < 0) ? template.length + pos : pos];\n if (in_brace) {\n if (ch === "{") {\n in_brace += 1;\n markup += "{";\n } else if (ch === "}") {\n in_brace -= 1;\n if (in_brace > 0) {\n markup += "}";\n } else {\n ans += render_markup(markup);\n }\n } else {\n markup += ch;\n }\n } else {\n if (ch === "{") {\n if (template[RS_bound_index(pos + 1, template)] === "{") {\n pos += 1;\n ans += "{";\n } else {\n in_brace = 1;\n markup = "";\n }\n } else {\n ans += ch;\n if (ch === "}" && template[RS_bound_index(pos + 1, template)] === "}") {\n pos += 1;\n }\n }\n }\n pos += 1;\n }\n if (in_brace) {\n throw new ValueError("expected \'}\' before end of string");\n }\n return ans;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("capitalize", (function() {\n var RS_anonfunc = function () {\n var string;\n string = this;\n if (string) {\n string = string[0].toUpperCase() + string.slice(1).toLowerCase();\n }\n return string;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("center", (function() {\n var RS_anonfunc = function (width, fill) {\n var left, right;\n left = Math.floor((width - this.length) / 2);\n right = width - left - this.length;\n fill = fill || " ";\n return new Array(left+1).join(fill) + this + new Array(right+1).join(fill);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width", "fill"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("count", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var string, RS_unpack, pos, step, ans;\n string = this;\n start = start || 0;\n end = end || string.length;\n if (start < 0 || end < 0) {\n string = string.slice(start, end);\n RS_unpack = [0, string.length];\n start = RS_unpack[0];\n end = RS_unpack[1];\n }\n pos = start;\n step = needle.length;\n if (!step) {\n return 0;\n }\n ans = 0;\n while (pos !== -1) {\n pos = string.indexOf(needle, pos);\n if (pos !== -1) {\n ans += 1;\n pos += step;\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("endswith", (function() {\n var RS_anonfunc = function (suffixes, start, end) {\n var string, q;\n string = this;\n start = start || 0;\n if (typeof suffixes === "string") {\n suffixes = [suffixes];\n }\n if (end !== undefined) {\n string = string.slice(0, end);\n }\n for (var i = 0; i < suffixes.length; i++) {\n q = suffixes[(typeof i === "number" && i < 0) ? suffixes.length + i : i];\n if (string.indexOf(q, Math.max(start, string.length - q.length)) !== -1) {\n return true;\n }\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["suffixes", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("startswith", (function() {\n var RS_anonfunc = function (prefixes, start, end) {\n var prefix;\n start = start || 0;\n if (typeof prefixes === "string") {\n prefixes = [prefixes];\n }\n for (var i = 0; i < prefixes.length; i++) {\n prefix = prefixes[(typeof i === "number" && i < 0) ? prefixes.length + i : i];\n end = (end === undefined) ? this.length : end;\n if (end - start >= prefix.length && prefix === this.slice(start, start + prefix.length)) {\n return true;\n }\n }\n return false;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["prefixes", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("find", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n while (start < 0) {\n start += this.length;\n }\n ans = this.indexOf(needle, start);\n if (end !== undefined && ans !== -1) {\n while (end < 0) {\n end += this.length;\n }\n if (ans >= end - needle.length) {\n return -1;\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rfind", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n while (end < 0) {\n end += this.length;\n }\n ans = this.lastIndexOf(needle, end - 1);\n if (start !== undefined && ans !== -1) {\n while (start < 0) {\n start += this.length;\n }\n if (ans < start) {\n return -1;\n }\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("index", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n ans = RS_str.prototype.find.apply(this, arguments);\n if (ans === -1) {\n throw new ValueError("substring not found");\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rindex", (function() {\n var RS_anonfunc = function (needle, start, end) {\n var ans;\n ans = RS_str.prototype.rfind.apply(this, arguments);\n if (ans === -1) {\n throw new ValueError("substring not found");\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["needle", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("islower", (function() {\n var RS_anonfunc = function () {\n return this.length > 0 && this.toLowerCase() === this.toString();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("isupper", (function() {\n var RS_anonfunc = function () {\n return this.length > 0 && this.toUpperCase() === this.toString();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("isspace", (function() {\n var RS_anonfunc = function () {\n return this.length > 0 && /^\\s+$/.test(this);\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("join", (function() {\n var RS_anonfunc = function (iterable) {\n var ans, r;\n if (Array.isArray(iterable)) {\n return iterable.join(this);\n }\n ans = "";\n r = iterable.next();\n while (!r.done) {\n if (ans) {\n ans += this;\n }\n ans += r.value;\n r = iterable.next();\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["iterable"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("ljust", (function() {\n var RS_anonfunc = function (width, fill) {\n var string;\n string = this;\n if (width > string.length) {\n fill = fill || " ";\n string += new Array(width - string.length + 1).join(fill);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width", "fill"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rjust", (function() {\n var RS_anonfunc = function (width, fill) {\n var string;\n string = this;\n if (width > string.length) {\n fill = fill || " ";\n string = new Array(width - string.length + 1).join(fill) + string;\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width", "fill"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("lower", (function() {\n var RS_anonfunc = function () {\n return this.toLowerCase();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("upper", (function() {\n var RS_anonfunc = function () {\n return this.toUpperCase();\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("lstrip", (function() {\n var RS_anonfunc = function (chars) {\n var string, pos;\n string = this;\n pos = 0;\n chars = chars || RS_str.whitespace;\n while (chars.indexOf(string[(typeof pos === "number" && pos < 0) ? string.length + pos : pos]) !== -1) {\n pos += 1;\n }\n if (pos) {\n string = string.slice(pos);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["chars"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rstrip", (function() {\n var RS_anonfunc = function (chars) {\n var string, pos;\n string = this;\n pos = string.length - 1;\n chars = chars || RS_str.whitespace;\n while (chars.indexOf(string[(typeof pos === "number" && pos < 0) ? string.length + pos : pos]) !== -1) {\n pos -= 1;\n }\n if (pos < string.length - 1) {\n string = string.slice(0, pos + 1);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["chars"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("strip", (function() {\n var RS_anonfunc = function (chars) {\n return RS_str.prototype.lstrip.call(RS_str.prototype.rstrip.call(this, chars), chars);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["chars"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("partition", (function() {\n var RS_anonfunc = function (sep) {\n var idx;\n idx = this.indexOf(sep);\n if (idx === -1) {\n return [this, "", ""];\n }\n return [this.slice(0, idx), sep, this.slice(idx + sep.length)];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rpartition", (function() {\n var RS_anonfunc = function (sep) {\n var idx;\n idx = this.lastIndexOf(sep);\n if (idx === -1) {\n return ["", "", this];\n }\n return [this.slice(0, idx), sep, this.slice(idx + sep.length)];\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("replace", (function() {\n var RS_anonfunc = function (old, repl, count) {\n var string, pos, idx;\n string = this;\n if (count === 1) {\n return RS_orig_replace(string, old, repl);\n }\n if (count < 1) {\n return string;\n }\n count = count || Number.MAX_VALUE;\n pos = 0;\n while (count > 0) {\n count -= 1;\n idx = string.indexOf(old, pos);\n if (idx === -1) {\n break;\n }\n pos = idx + repl.length;\n string = string.slice(0, idx) + repl + string.slice(idx + old.length);\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["old", "repl", "count"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("split", (function() {\n var RS_anonfunc = function (sep, maxsplit) {\n var split, ans, extra, parts;\n if (maxsplit === 0) {\n return RS_list_decorate([ this ]);\n }\n split = RS_orig_split;\n if (sep === undefined || sep === null) {\n if (maxsplit > 0) {\n ans = split(this, /(\\s+)/);\n extra = "";\n parts = [];\n for (var i = 0; i < ans.length; i++) {\n if (parts.length >= maxsplit + 1) {\n extra += ans[(typeof i === "number" && i < 0) ? ans.length + i : i];\n } else if (i % 2 === 0) {\n parts.push(ans[(typeof i === "number" && i < 0) ? ans.length + i : i]);\n }\n }\n parts[parts.length-1] += extra;\n ans = parts;\n } else {\n ans = split(this, /\\s+/);\n }\n } else {\n if (sep === "") {\n throw new ValueError("empty separator");\n }\n ans = split(this, sep);\n if (maxsplit > 0 && ans.length > maxsplit) {\n extra = ans.slice(maxsplit).join(sep);\n ans = ans.slice(0, maxsplit);\n ans.push(extra);\n }\n }\n return RS_list_decorate(ans);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep", "maxsplit"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("rsplit", (function() {\n var RS_anonfunc = function (sep, maxsplit) {\n var split, ans, is_space, pos, current, spc, ch, end, idx;\n if (!maxsplit) {\n return RS_str.prototype.split.call(this, sep);\n }\n split = RS_orig_split;\n if (sep === undefined || sep === null) {\n if (maxsplit > 0) {\n ans = [];\n is_space = /\\s/;\n pos = this.length - 1;\n current = "";\n while (pos > -1 && maxsplit > 0) {\n spc = false;\n ch = (RS_expr_temp = this)[(typeof pos === "number" && pos < 0) ? RS_expr_temp.length + pos : pos];\n while (pos > -1 && is_space.test(ch)) {\n spc = true;\n ch = this[--pos];\n }\n if (spc) {\n if (current) {\n ans.push(current);\n maxsplit -= 1;\n }\n current = ch;\n } else {\n current += ch;\n }\n pos -= 1;\n }\n ans.push(this.slice(0, pos + 1) + current);\n ans.reverse();\n } else {\n ans = split(this, /\\s+/);\n }\n } else {\n if (sep === "") {\n throw new ValueError("empty separator");\n }\n ans = [];\n pos = end = this.length;\n while (pos > -1 && maxsplit > 0) {\n maxsplit -= 1;\n idx = this.lastIndexOf(sep, pos);\n if (idx === -1) {\n break;\n }\n ans.push(this.slice(idx + sep.length, end));\n pos = idx - 1;\n end = idx;\n }\n ans.push(this.slice(0, end));\n ans.reverse();\n }\n return RS_list_decorate(ans);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["sep", "maxsplit"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("splitlines", (function() {\n var RS_anonfunc = function (keepends) {\n var split, parts, ans;\n split = RS_orig_split;\n if (keepends) {\n parts = split(this, /((?:\\r?\\n)|\\r)/);\n ans = [];\n for (var i = 0; i < parts.length; i++) {\n if (i % 2 === 0) {\n ans.push(parts[(typeof i === "number" && i < 0) ? parts.length + i : i]);\n } else {\n ans[ans.length-1] += parts[(typeof i === "number" && i < 0) ? parts.length + i : i];\n }\n }\n } else {\n ans = split(this, /(?:\\r?\\n)|\\r/);\n }\n return RS_list_decorate(ans);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["keepends"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("swapcase", (function() {\n var RS_anonfunc = function () {\n var ans, a, b;\n ans = new Array(this.length);\n for (var i = 0; i < ans.length; i++) {\n a = (RS_expr_temp = this)[(typeof i === "number" && i < 0) ? RS_expr_temp.length + i : i];\n b = a.toLowerCase();\n if (a === b) {\n b = a.toUpperCase();\n }\n ans[(typeof i === "number" && i < 0) ? ans.length + i : i] = b;\n }\n return ans.join("");\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\ndefine_str_func("zfill", (function() {\n var RS_anonfunc = function (width) {\n var string;\n string = this;\n if (width > string.length) {\n string = new Array(width - string.length + 1).join("0") + string;\n }\n return string;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["width"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})());\nRS_str.uchrs = (function() {\n var RS_anonfunc = function (string, with_positions) {\n return (function(){\n var RS_d = {};\n RS_d["_string"] = string;\n RS_d["_pos"] = 0;\n RS_d[RS_iterator_symbol] = (function() {\n var RS_anonfunc = function () {\n return this;\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n RS_d["next"] = (function() {\n var RS_anonfunc = function () {\n var length, pos, value, ans, extra;\n length = this._string.length;\n if (this._pos >= length) {\n return (function(){\n var RS_d = {};\n RS_d["done"] = true;\n return RS_d;\n }).call(this);\n }\n pos = this._pos;\n value = this._string.charCodeAt(this._pos++);\n ans = "\\ufffd";\n if (55296 <= value && value <= 56319) {\n if (this._pos < length) {\n extra = this._string.charCodeAt(this._pos++);\n if ((extra & 56320) === 56320) {\n ans = String.fromCharCode(value, extra);\n }\n }\n } else if ((value & 56320) !== 56320) {\n ans = String.fromCharCode(value);\n }\n if (with_positions) {\n return (function(){\n var RS_d = {};\n RS_d["done"] = false;\n RS_d["value"] = RS_list_decorate([ pos, ans ]);\n return RS_d;\n }).call(this);\n } else {\n return (function(){\n var RS_d = {};\n RS_d["done"] = false;\n RS_d["value"] = ans;\n return RS_d;\n }).call(this);\n }\n };\n if (!RS_anonfunc.__module__) Object.defineProperties(RS_anonfunc, {\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n })();\n return RS_d;\n }).call(this);\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["string", "with_positions"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_str.uslice = (function() {\n var RS_anonfunc = function (string, start, end) {\n var items, iterator, r;\n items = [];\n iterator = RS_str.uchrs(string);\n r = iterator.next();\n while (!r.done) {\n items.push(r.value);\n r = iterator.next();\n }\n return items.slice(start || 0, (end === undefined) ? items.length : end).join("");\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["string", "start", "end"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_str.ulen = (function() {\n var RS_anonfunc = function (string) {\n var iterator, r, ans;\n iterator = RS_str.uchrs(string);\n r = iterator.next();\n ans = 0;\n while (!r.done) {\n r = iterator.next();\n ans += 1;\n }\n return ans;\n };\n if (!RS_anonfunc.__argnames__) Object.defineProperties(RS_anonfunc, {\n __argnames__ : {value: ["string"]},\n __module__ : {value: "__main__"}\n });\n return RS_anonfunc;\n})();\nRS_str.ascii_lowercase = "abcdefghijklmnopqrstuvwxyz";\nRS_str.ascii_uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\nRS_str.ascii_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";\nRS_str.digits = "0123456789";\nRS_str.punctuation = "!\\"#$%&\'()*+,-./:;<=>?@[\\\\]^_`{|}~";\nRS_str.printable = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\\"#$%&\'()*+,-./:;<=>?@[\\\\]^_`{|}~ \\t\\n\\r\\u000b\\f";\nRS_str.whitespace = " \\t\\n\\r\\u000b\\f";\ndefine_str_func = undefined;\nvar str = RS_str, repr = RS_repr;',"tools/web_repl.js":"/* vim:fileencoding=utf-8\n * \n * Copyright (C) 2016 Kovid Goyal \n *\n * Distributed under terms of the BSD license\n */\n\"use strict\"; /*jshint node:true */\nvar vm = require('vm');\nvar embedded_compiler = require('tools/embedded_compiler.js');\n\nmodule.exports = function(compiler, baselib) {\n var ctx = vm.createContext();\n var LINE_CONTINUATION_CHARS = ':\\\\';\n var find_completions = null;\n var streaming_compiler = embedded_compiler(compiler, baselib, function(js) { return vm.runInContext(js, ctx); }, '__repl__');\n\n return {\n 'in_block_mode': false,\n\n 'replace_print': function replace_print(write_line_func) {\n ctx.print = function() {\n var parts = [];\n for (var i = 0; i < arguments.length; i++) \n parts.push(ctx.RS_str(arguments[i]));\n write_line_func(parts.join(' '));\n };\n },\n\n 'is_input_complete': function is_input_complete(source) {\n if (!source || !source.trim()) return false;\n var lines = source.split('\\n');\n var last_line = lines[lines.length - 1].trimRight();\n if (this.in_block_mode) {\n // In a block only exit after two blank lines\n if (lines.length < 2) return false;\n var second_last_line = lines[lines.length - 2].trimRight();\n var block_ended = !!(!last_line && !second_last_line);\n if (!block_ended) return false;\n this.in_block_mode = false;\n return true;\n }\n\n if (last_line && LINE_CONTINUATION_CHARS.indexOf(last_line.substr(last_line.length - 1)) > -1) {\n this.in_block_mode = true;\n return false;\n }\n try {\n compiler.parse(source, {'filename': '', 'basedir': '__stdlib__'});\n } catch(e) {\n if (e.is_eof && e.line === lines.length && e.col > 0) {\n return false;\n }\n this.in_block_mode = false;\n return true;\n }\n this.in_block_mode = false;\n return true;\n },\n\n 'compile': function web_repl_compile(code, opts) {\n opts = opts || {};\n opts.keep_docstrings = true;\n opts.filename = '';\n return streaming_compiler.compile(code, opts);\n },\n\n 'runjs': function runjs(code) {\n var ans = vm.runInContext(code, ctx);\n if (ans !== undefined || ans === null) {\n ctx.RS_repl_val = ans;\n var q = vm.runInContext('RS_repr(RS_repl_val)', ctx);\n ans = (q === 'undefined') ? ans.toString() : q;\n }\n return ans;\n },\n\n 'init_completions': function init_completions(completelib) {\n find_completions = completelib(compiler);\n },\n\n 'find_completions': function find_completions_(line) {\n return find_completions(line, ctx);\n },\n\n };\n};\n\n","tools/embedded_compiler.js":"/* vim:fileencoding=utf-8\n * \n * Copyright (C) 2016 Kovid Goyal \n *\n * Distributed under terms of the BSD license\n */\n\"use strict\"; /*jshint node:true */\n\nvar has_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty);\n\nmodule.exports = function(compiler, baselib, runjs, name) {\n var LINE_CONTINUATION_CHARS = ':\\\\';\n runjs = runjs || eval;\n runjs(print_ast(compiler.parse(''), true));\n runjs('var __name__ = \"' + (name || '__embedded__') + '\";');\n\n function print_ast(ast, keep_baselib, keep_docstrings, js_version, private_scope, write_name) {\n var output_options = {omit_baselib:!keep_baselib, write_name:!!write_name, private_scope:!!private_scope, beautify:true, js_version: (js_version || 6), keep_docstrings:keep_docstrings};\n if (keep_baselib) output_options.baselib_plain = baselib;\n var output = new compiler.OutputStream(output_options);\n ast.print(output);\n return output.get();\n }\n\n return {\n 'toplevel': null,\n\n 'compile': function streaming_compile(code, opts) {\n opts = opts || {};\n var classes = (this.toplevel) ? this.toplevel.classes : undefined;\n var scoped_flags = (this.toplevel) ? this.toplevel.scoped_flags: undefined;\n this.toplevel = compiler.parse(code, {\n 'filename': opts.filename || '',\n 'basedir': '__stdlib__',\n 'classes': classes,\n 'scoped_flags': scoped_flags,\n 'discard_asserts': opts.discard_asserts,\n });\n var ans = print_ast(this.toplevel, opts.keep_baselib, opts.keep_docstrings, opts.js_version, opts.private_scope, opts.write_name);\n if (classes) {\n var exports = {};\n var self = this;\n this.toplevel.exports.forEach(function (name) { exports[name] = true; });\n Object.getOwnPropertyNames(classes).forEach(function (name) {\n if (!has_prop(exports, name) && !has_prop(self.toplevel.classes, name))\n self.toplevel.classes[name] = classes[name];\n });\n }\n scoped_flags = this.toplevel.scoped_flags;\n \n return ans;\n },\n\n };\n};\n\n","tools/utils.js":"/* vim:fileencoding=utf-8\n * \n * Copyright (C) 2015 Kovid Goyal \n *\n * Distributed under terms of the BSD license\n */\n\"use strict\"; /*jshint node:true */\n\nvar comment_contents = /\\/\\*!?(?:\\@preserve)?[ \\t]*(?:\\r\\n|\\n)([\\s\\S]*?)(?:\\r\\n|\\n)[ \\t]*\\*\\//;\nvar colors = ['red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'];\n\nfunction ansi(code) {\n code = code || 0;\n return String.fromCharCode(27) + '[' + code + 'm';\n}\n\nfunction path_exists(path) {\n var fs = require('fs');\n try {\n fs.statSync(path);\n return true;\n } catch(e) {\n if (e.code != 'ENOENT') throw e;\n }\n}\n\nfunction colored(string, color, bold) {\n var prefix = [];\n if (bold) prefix.push(ansi(1));\n if (color) prefix.push(ansi(colors.indexOf(color) + 31));\n return prefix.join('') + string + ansi(0);\n}\n\nfunction supports_color(stdout) {\n stdout = stdout || process.stdout;\n\tif (stdout && !stdout.isTTY) {\n\t\treturn false;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\treturn false;\n\t}\n\n\tif ('COLORTERM' in process.env) {\n\t\treturn true;\n\t}\n\n\tif (process.env.TERM === 'dumb') {\n\t\treturn false;\n\t}\n\n\tif (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {\n\t\treturn true;\n\t}\n\n return false;\n\n}\n\nfunction safe_colored(string) {\n return string;\n}\n\nfunction repeat(str, num) {\n return new Array( num + 1 ).join( str );\n}\n\nfunction generators_available() {\n var gen;\n try {\n eval('gen = function *(){}'); // jshint ignore:line\n return typeof gen === 'function' && gen.constructor.name == 'GeneratorFunction';\n } catch(e) {\n return false;\n }\n}\n\nfunction wrap(lines, width) {\n\tvar ans = [];\n\tvar prev = '';\n\tlines.forEach(function (line) {\n\t\tline = prev + line;\n\t\tprev = '';\n\t\tif (line.length > width) {\n\t\t\tprev = line.substr(width);\n if (prev) prev += ' ';\n\t\t\tline = line.substr(0, width - 1);\n\t\t\tif (line.substr(line.length - 1 !== ' ')) line += '-';\n\t\t} \n\t\tans.push(line);\n\t});\n\tif (prev) ans = ans.concat(wrap([prev]));\n\treturn ans;\n}\n\nfunction merge() {\n // Simple merge of properties from all objects\n var ans = {};\n Array.prototype.slice.call(arguments).forEach(function (arg) {\n Object.keys(arg).forEach(function(key) {\n ans[key] = arg[key];\n });\n });\n return ans;\n}\n\nfunction get_import_dirs(paths_string, ignore_env) {\n var path = require('path');\n var paths = [];\n function merge(new_path) {\n if (paths.indexOf(new_path) == -1) paths.push(new_path);\n }\n if (!ignore_env && process && process.env && process.env.RAPYDSCRIPT_IMPORT_PATH) {\n process.env.RAPYDSCRIPT_IMPORT_PATH.split(path.delimiter).forEach(merge);\n }\n if (paths_string) paths_string.split(path.delimiter).forEach(merge);\n return paths;\n}\n\nexports.comment_contents = comment_contents;\nexports.repeat = repeat;\nexports.wrap = wrap;\nexports.merge = merge;\nexports.colored = colored;\nexports.safe_colored = (supports_color()) ? colored : safe_colored;\nexports.generators_available = generators_available;\nexports.get_import_dirs = get_import_dirs;\nexports.path_exists = path_exists;\n","tools/completer.js":"/* vim:fileencoding=utf-8\n * \n * Copyright (C) 2016 Kovid Goyal \n *\n * Distributed under terms of the BSD license\n */\n\n\nmodule.exports = function(compiler, options) {\n \"use strict\";\n var all_keywords = compiler.ALL_KEYWORDS.split(' ');\n var vm = require('vm');\n options = options || {};\n if (!options.enum_global) options.enum_global = \"var global = Function('return this')(); Object.getOwnPropertyNames(global);\";\n\n function global_names(ctx) {\n try {\n var ans = vm.runInContext(options.enum_global, ctx);\n ans = ans.concat(all_keywords);\n ans.sort();\n var seen = {};\n ans.filter(function (item) { \n if (Object.prototype.hasOwnProperty.call(seen, item)) return false;\n seen[item] = true;\n return true;\n });\n return ans;\n } catch(e) {\n console.log(e.stack || e.toString());\n }\n return [];\n }\n\n function object_names(obj, prefix) {\n if (obj === null || obj === undefined) return [];\n var groups = [], prefix_len = prefix.length, p;\n\n function prefix_filter(name) { return (prefix_len) ? (name.substr(0, prefix_len) === prefix) : true; }\n\n function add(o) {\n var items = Object.getOwnPropertyNames(o).filter(prefix_filter);\n if (items.length) groups.push(items);\n }\n\n if (typeof obj === 'object' || typeof obj === 'function') {\n add(obj);\n p = Object.getPrototypeOf(obj);\n } else p = obj.constructor ? obj.constructor.prototype : null; \n\n // Walk the prototype chain\n try {\n var sentinel = 5;\n while (p !== null && sentinel > 0) {\n add(p);\n p = Object.getPrototypeOf(p);\n // Circular refs possible? Let's guard against that.\n sentinel--;\n }\n } catch (e) {\n // console.error(\"completion error walking prototype chain:\" + e);\n }\n if (!groups.length) return [];\n var seen = {}, ans = [];\n function uniq(name) {\n if (Object.prototype.hasOwnProperty.call(seen, name)) return false;\n seen[name] = true;\n return true;\n }\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n group.sort();\n ans = ans.concat(group.filter(uniq));\n ans.push(''); // group separator\n\n }\n while (ans.length && ans[ans.length - 1] === '') ans.pop();\n return ans;\n }\n\n function prefix_matches(prefix, items) {\n var len = prefix.length;\n var ans = items.filter(function(item) { return item.substr(0, len) === prefix; });\n ans.sort();\n return ans;\n }\n\n function find_completions(line, ctx) {\n var t;\n try {\n t = compiler.tokenizer(line, '');\n } catch(e) { return []; }\n var tokens = [], token;\n while (true) {\n try {\n token = t();\n } catch (e) { return []; }\n if (token.type === 'eof') break;\n if (token.type === 'punc' && '(){},;:'.indexOf(token.value) > -1)\n tokens = [];\n tokens.push(token);\n }\n if (!tokens.length) {\n // New line or trailing space\n return [global_names(ctx), ''];\n }\n var last_tok = tokens[tokens.length - 1];\n if (last_tok.value === '.' || (last_tok.type === 'name' && compiler.IDENTIFIER_PAT.test(last_tok.value))) {\n last_tok = last_tok.value;\n if (last_tok === '.') {\n tokens.push({'value':''});\n last_tok = '';\n }\n if (tokens.length > 1 && tokens[tokens.length - 2].value === '.') {\n // A compound expression\n var prefix = '', result;\n tokens.slice(0, tokens.length - 2).forEach(function (tok) { prefix += tok.value; });\n if (prefix) {\n try {\n result = vm.runInContext(prefix, ctx, {'displayErrors':false});\n } catch(e) { return []; }\n return [object_names(result, last_tok), last_tok];\n }\n } else {\n return [prefix_matches(last_tok, global_names(ctx)), last_tok];\n }\n }\n return [];\n }\n\n return find_completions;\n};\n","tools/msgfmt.js":"/* vim:fileencoding=utf-8\n * \n * Copyright (C) 2015 Kovid Goyal \n *\n * Distributed under terms of the BSD license\n */\n\"use strict\"; /*jshint node:true */\n\nfunction unesc(string) {\n return string.replace(/\\\\\"/g, '\"').replace(/\\\\n/g, '\\n').replace(/\\\\r/g, '\\r').replace(/\\\\t/g, '\\t').replace(/\\\\\\\\/g, '\\\\');\n}\n\nfunction parse(data, on_error) {\n // Parse a PO file using a state machine (does not work for POT files). Also only extracts data useful\n // for JSON output.\n var plural_forms = null;\n var lines = data.split('\\n');\n var entries = [];\n var current_entry = create_entry();\n var lnum = 0;\n var nplurals = null;\n var language = null;\n\n function fatal() {\n var msg = Array.prototype.slice.call(arguments).join(' ');\n if (on_error) { on_error(msg); return; }\n console.error(msg);\n process.exit(1);\n }\n\n function create_entry() {\n return {msgid: null, fuzzy: false, msgstr:[], msgid_plural:null, lnum:null};\n }\n\n function parse_header() {\n var raw = current_entry.msgstr[0];\n if (raw === undefined) fatal('Header has no msgstr');\n raw.split('\\n').forEach(function(line) {\n if (line.startsWith('Plural-Forms:')) {\n plural_forms = line.slice('Plural-Forms:'.length).trim();\n var match = /^nplurals\\s*=\\s*(\\d+)\\s*;/.exec(plural_forms);\n if (!match || match[1] === undefined) fatal('Invalid Plural-Forms header:', plural_forms);\n nplurals = parseInt(match[1]);\n } \n else if (line.startsWith('Language:')) {\n language = line.slice('Language:'.length).trim();\n }\n });\n }\n\n function commit_entry() {\n if (current_entry.msgid) {\n if (current_entry.msgid_plural !== null) {\n if (nplurals === null) fatal('Plural-Forms header missing');\n for (var i = 0; i < nplurals; i++) {\n if (current_entry.msgstr[i] === undefined) fatal('Missing plural form for entry at line number:', lnum);\n }\n }\n entries.push(current_entry);\n } else if (current_entry.msgid === '') parse_header();\n current_entry = create_entry();\n }\n\n function read_string(line) {\n line = line.trim();\n if (!line || line[0] !== '\"' || line[line.length - 1] !== '\"') {\n fatal('Expecting a string at line number:', lnum);\n }\n return unesc(line.slice(1, -1));\n }\n\n function continuation(line, lines, append, after) {\n if (line[0] === '\"') append(read_string(line));\n else {\n state = after;\n after(line, lines);\n }\n }\n\n function start(line, lines) {\n if (line[0] === '#') {\n if (line[1] === ',') {\n line.slice(2).trimLeft().split(',').forEach(function(flag) {\n if (flag.trim().toLowerCase() === 'fuzzy') current_entry.fuzzy = true;\n });\n }\n } else if (line.startsWith('msgid ')) {\n current_entry.msgid = read_string(line.slice('msgid '.length));\n current_entry.lnum = lnum;\n state = function(line, lines) { \n continuation(line, lines, function(x) { current_entry.msgid += x; }, after_msgid);\n };\n } else {\n fatal('Expecting msgid at line number:', lnum);\n }\n }\n\n function after_msgid(line, lines) {\n if (line.startsWith('msgid_plural ')) {\n current_entry.msgid_plural = read_string(line.slice('msgid_plural '.length));\n state = function(line, lines) { \n continuation(line, lines, function(x) { current_entry.msgid_plural += x; }, msgstr);\n };\n } \n \n else if (line.startsWith('msgstr ') || line.startsWith('msgstr[')) {\n state = msgstr;\n msgstr(line, lines);\n } \n \n else fatal('Expecting either msgstr or msgid_plural at line number:', lnum);\n\n }\n\n function msgstr(line, lines) {\n if (line.startsWith('msgstr ')) {\n if (current_entry.msgid_plural !== null) fatal('Expecting msgstr[0] at line number:', lnum);\n current_entry.msgstr.push(read_string(line.slice('msgstr '.length)));\n state = function(line, lines) { \n continuation(line, lines, function(x) { current_entry.msgstr[current_entry.msgstr.length - 1] += x; }, msgstr);\n };\n } \n\n else if (line[0] === '#' || line.startsWith('msgid ')) {\n if (!current_entry.msgstr.length) fatal('Expecting msgstr at line number:', lnum);\n commit_entry();\n state = start;\n start(line, lines);\n }\n\n else if (line.startsWith('msgstr[')) {\n if (current_entry.msgid_plural === null) fatal('Expecting non-plural msgstr at line number:', lnum);\n var pnum = /^msgstr\\[(\\d+)\\] /.exec(line);\n if (!pnum || pnum[1] === undefined) fatal('Malformed msgstr at line number:', lnum);\n var idx = parseInt(pnum[1]);\n current_entry.msgstr[idx] = read_string(line.slice(pnum[0].length));\n state = function(line, lines) { \n continuation(line, lines, function(x) { current_entry.msgstr[idx] += x; }, msgstr);\n };\n }\n\n else fatal('Expecting msgstr or msgid at line number:', lnum);\n }\n\n var state = start;\n\n while (lines.length) {\n var line = lines.shift().trim();\n lnum += 1;\n if (!line) continue;\n state(line, lines);\n }\n commit_entry();\n if (language === null) fatal('No language specified in the header of this po file');\n return {entries:entries, plural_forms:plural_forms, nplurals:nplurals, language:language};\n}\n\nfunction read_stdin(cont) {\n var chunks = [];\n process.stdin.setEncoding('utf8');\n\n process.stdin.on('readable', function () { \n var chunk = process.stdin.read();\n if (chunk) chunks.push(chunk); \n });\n\n process.stdin.on('end', function() { cont(chunks.join('')); });\n}\n\nfunction serialize_catalog(catalog, options) {\n if (!options.use_fuzzy) catalog.entries = catalog.entries.filter(function(e) { return !e.fuzzy; });\n var entries = {};\n catalog.entries.forEach(function (entry) {\n entries[entry.msgid] = entry.msgstr;\n });\n return JSON.stringify({'plural_forms':catalog.plural_forms, 'entries':entries, 'language':catalog.language});\n}\n\nmodule.exports.cli = function(argv, base_path, src_path, lib_path) {\n read_stdin(function process(data) {\n var catalog = parse(data);\n console.log(serialize_catalog(catalog, argv));\n });\n};\n\nmodule.exports.parse = parse;\nmodule.exports.build = function(data, options) { return serialize_catalog(parse(data), options); };\n","tools/gettext.js":"/* vim:fileencoding=utf-8\n * \n * Copyright (C) 2015 Kovid Goyal \n *\n * Distributed under terms of the BSD license\n */\n\"use strict\"; /*jshint node:true */\n\nvar fs = require('fs');\nvar RapydScript = (typeof create_rapydscript_compiler === 'function') ? create_rapydscript_compiler() : require('./compiler').create_compiler();\nvar path = require('path');\n\nfunction parse_file(code, filename) {\n return RapydScript.parse(code, {\n filename: filename,\n basedir: path.dirname(filename),\n libdir: path.dirname(filename),\n for_linting: true,\n });\n}\n\nfunction detect_format(msgid) {\n var q = msgid.replace('{{', '');\n if (/\\{[0-9a-zA-Z_}]+/.test(q)) return 'python-brace-format';\n return null;\n}\n\nfunction Gettext(catalog, filename) {\n this._visit = function (node, cont) {\n if (node instanceof RapydScript.AST_Call && node.args && node.args.length && node.expression instanceof RapydScript.AST_Symbol) {\n var name = node.expression.name;\n if (name === '_' || name === 'gettext' || name === 'ngettext') {\n var nargs = (name === 'ngettext') ? 2 : 1;\n var line = node.start.line;\n for (var i = 0; i < nargs; i++) {\n if (!(node.args[i] instanceof RapydScript.AST_String)) {\n console.error('Translation function: ' + name + ' does not have a string literal argument at line: ' + line + ' of ' + filename);\n process.exit(1);\n }\n }\n var msgid = node.args[0].value;\n if (!Object.prototype.hasOwnProperty.call(catalog, msgid)) {\n catalog[msgid] = {\n 'locations': [],\n 'plural': null,\n 'format': detect_format(msgid),\n };\n }\n if (name === 'ngettext') catalog[msgid].plural = node.args[1].value;\n if (filename) catalog[msgid].locations.push(filename + ':' + line);\n }\n \n }\n if (cont !== undefined) cont();\n };\n}\n\nfunction gettext(catalog, code, filename) {\n var toplevel;\n\n try {\n toplevel = parse_file(code, filename);\n } catch(e) {\n if (e instanceof RapydScript.SyntaxError) {\n console.error('Failed to parse: ' + filename + ' with error: ' + e.line + ':' + e.col + ':' + e.message);\n process.exit(1);\n } else throw e;\n }\n\n if (toplevel) {\n var gt = new Gettext(catalog, filename);\n toplevel.walk(gt);\n }\n}\n\nfunction esc(string) {\n return (string || '').replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"').replace(/\\n/g, '\\\\n').replace(/\\t/g, '\\\\t').replace(/\\r/g, '');\n}\n\nfunction entry_to_string(msgid, data) {\n var ans = [];\n data.locations.forEach(function (loc) { ans.push('#: ' + loc); });\n if (data.format) ans.push('#, ' + data.format);\n ans.push('msgid \"' + esc(msgid) + '\"');\n if (data.plural) {\n ans.push('msgid_plural \"' + esc(data.plural) + '\"');\n ans.push('msgstr[0] \"\"');\n ans.push('msgstr[1] \"\"');\n } else ans.push('msgstr \"\"');\n return ans.join('\\n');\n}\n\nfunction write_output(catalog, options, write) {\n write = write || (function(x) { process.stdout.write(new Buffer(x, 'utf-8')); });\n function print() {\n var val = Array.prototype.slice.call(arguments).join(' ') + '\\n';\n write(val);\n }\n function header_line() {\n var val = '\"' + Array.prototype.slice.call(arguments).join(' ') + '\\\\n\"\\n';\n write(val);\n }\n if (!options.omit_header) {\n var now = (new Date()).toISOString();\n print('msgid', '\"\"');\n print('msgstr', '\"\"');\n header_line('Project-Id-Version:', esc(options.package_name), esc(options.package_version));\n header_line('POT-Creation-Date:', now);\n header_line(\"PO-Revision-Date:\", now);\n header_line(\"Report-Msgid-Bugs-To:\", esc(options.bugs_address));\n header_line(\"Last-Translator: Automatically generated\");\n header_line(\"Language-Team: LANGUAGE\");\n header_line(\"MIME-Version: 1.0\");\n header_line(\"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\");\n header_line(\"Content-Type: text/plain; charset=UTF-8\");\n header_line(\"Content-Transfer-Encoding: 8bit\");\n print();\n }\n Object.keys(catalog).forEach(function(msgid) {\n var data = catalog[msgid];\n print(entry_to_string(msgid, data));\n print();\n });\n}\n\n// CLI {{{\n\nfunction read_whole_file(filename, cb) {\n if (!filename) {\n var chunks = [];\n process.stdin.setEncoding('utf-8');\n process.stdin.on('data', function (chunk) {\n chunks.push(chunk);\n }).on('end', function () {\n cb(null, chunks.join(\"\"));\n });\n process.openStdin();\n } else {\n fs.readFile(filename, \"utf-8\", cb);\n }\n}\n\nmodule.exports.cli = function(argv, base_path, src_path, lib_path) {\n var files = [];\n var num_of_files = files.length || 1;\n var catalog = {};\n\n function read_files(src) {\n src.forEach(function(f) {\n if (fs.lstatSync(f).isDirectory()) {\n var children = [];\n fs.readdirSync(f).forEach(function(x) { children.push(path.join(f, x)); });\n read_files(children);\n }\n else files.push(f);\n });\n }\n read_files(argv.files);\n\n function process_single_file(err, code) {\n if (err) {\n console.error(\"ERROR: can't read file: \" + files[0]);\n process.exit(1);\n }\n\n gettext(catalog, code, files[0]);\n\n files = files.slice(1);\n if (files.length) {\n setImmediate(read_whole_file, files[0], process_single_file);\n return;\n } else {\n write_output(catalog, argv);\n process.exit(0);\n }\n }\n \n setImmediate(read_whole_file, files[0], process_single_file);\n\n};\n\nmodule.exports.gettext = gettext;\nmodule.exports.entry_to_string = entry_to_string;\nmodule.exports.write_output = write_output;\n// }}}\n","__stdlib__/aes.pyj":"# vim:fileencoding=utf-8\n# License: BSD Copyright: 2016, Kovid Goyal \n\n# globals: crypto\n\n# Internal API {{{\n\ndef string_to_bytes_encoder(string):\n return TextEncoder('utf-8').encode(string + '')\n\ndef string_to_bytes_slow(string):\n escstr = encodeURIComponent(string)\n binstr = escstr.replace(/%([0-9A-F]{2})/g, def(match, p1):\n return String.fromCharCode('0x' + p1)\n )\n ua = Uint8Array(binstr.length)\n for i, ch in enumerate(binstr):\n ua[i] = ch.charCodeAt(0)\n return ua\n\ndef as_hex(array, sep=''):\n num = array.BYTES_PER_ELEMENT or 1\n fmt = '{:0' + num * 2 + 'x}'\n return [str.format(fmt, x) for x in array].join(sep)\n\ndef bytes_to_string_decoder(bytes, offset):\n offset = offset or 0\n if offset:\n bytes = bytes.subarray(offset)\n return TextDecoder('utf-8').decode(bytes)\n\ndef bytes_to_string_slow(bytes, offset):\n ans = v'[]'\n i = offset or 0\n while i < bytes.length:\n c = bytes[i]\n if c < 128:\n ans.push(String.fromCharCode(c))\n i += 1\n elif 191 < c < 224:\n ans.push(String.fromCharCode(((c & 0x1f) << 6) | (bytes[i + 1] & 0x3f)))\n i += 2\n else:\n ans.push(String.fromCharCode(((c & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f)))\n i += 3\n return ans.join('')\n\nstring_to_bytes = string_to_bytes_encoder if jstype(TextEncoder) is 'function' else string_to_bytes_slow\nbytes_to_string = bytes_to_string_decoder if jstype(TextDecoder) is 'function' else bytes_to_string_slow\n\ndef increment_counter(c):\n # c must be a Uint8Array of length 16\n for v'var i = 15; i >= 12; i--':\n if c[i] is 255:\n c[i] = 0\n else:\n c[i] += 1\n break\n\ndef convert_to_int32(bytes, output, offset, length):\n offset = offset or 0\n length = length or bytes.length\n for v'var i = offset, j = 0; i < offset + length; i += 4, j++':\n output[j] = (bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]\n\ndef convert_to_int32_pad(bytes):\n extra = bytes.length % 4\n if extra:\n t = Uint8Array(bytes.length + 4 - extra)\n t.set(bytes)\n bytes = t\n ans = Uint32Array(bytes.length / 4)\n convert_to_int32(bytes, ans)\n return ans\n\nif not Uint8Array.prototype.fill:\n Uint8Array.prototype.fill = Uint32Array.prototype.fill = def(val, start, end):\n start = start or 0\n if end is undefined:\n end = this.length\n if start < 0:\n start += this.length\n if end < 0:\n end += this.length\n for v'var i = start; i < end; i++':\n this[i] = val\n\ndef from_64_to_32(num):\n # convert 64-bit number to two BE Int32s\n ans = Uint32Array(2)\n ans[0] = (num / 0x100000000) | 0\n ans[1] = num & 0xFFFFFFFF\n return ans\n\n# Lookup tables for AES {{{\n# Number of rounds by keysize\nnumber_of_rounds = {16: 10, 24: 12, 32: 14}\n# Round constant words\nrcon = v'new Uint32Array([0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91])'\n\n# S-box and Inverse S-box (S is for Substitution)\nS = v'new Uint32Array([0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16])'\nSi = v'new Uint32Array([0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d])'\n\n# Transformations for encryption\nT1 = v'new Uint32Array([0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a])'\nT2 = v'new Uint32Array([0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616])'\nT3 = v'new Uint32Array([0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16])'\nT4 = v'new Uint32Array([0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c])'\n\n# Transformations for decryption\nT5 = v'new Uint32Array([0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742])'\nT6 = v'new Uint32Array([0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857])'\nT7 = v'new Uint32Array([0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8])'\nT8 = v'new Uint32Array([0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0])'\n\n# Transformations for decryption key expansion\nU1 = v'new Uint32Array([0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3])'\nU2 = v'new Uint32Array([0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697])'\nU3 = v'new Uint32Array([0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46])'\nU4 = v'new Uint32Array([0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d])'\n\n# }}}\n\nclass AES: # {{{\n\n def __init__(self, key):\n self.working_mem = [Uint32Array(4), Uint32Array(4)]\n rounds = number_of_rounds[key.length]\n if not rounds:\n raise ValueError('invalid key size (must be length 16, 24 or 32)')\n\n # encryption round keys\n self._Ke = v'[]'\n\n # decryption round keys\n self._Kd = v'[]'\n\n for v'var i = 0; i <= rounds; i++':\n self._Ke.push(Uint32Array(4))\n self._Kd.push(Uint32Array(4))\n\n round_key_count = (rounds + 1) * 4\n KC = key.length / 4\n\n # convert the key into ints\n tk = Uint32Array(KC)\n convert_to_int32(key, tk)\n\n # copy values into round key arrays\n index = 0\n for v'var i = 0; i < KC; i++':\n index = i >> 2\n self._Ke[index][i % 4] = tk[i]\n self._Kd[rounds - index][i % 4] = tk[i]\n\n # key expansion (fips-197 section 5.2)\n rconpointer = 0\n t = KC\n while t < round_key_count:\n tt = tk[KC - 1]\n tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^\n (S[(tt >> 8) & 0xFF] << 16) ^\n (S[ tt & 0xFF] << 8) ^\n S[(tt >> 24) & 0xFF] ^\n (rcon[rconpointer] << 24))\n rconpointer += 1\n\n # key expansion (for non-256 bit)\n if KC != 8:\n for v'var i = 1; i < KC; i++':\n tk[i] ^= tk[i - 1]\n\n # key expansion for 256-bit keys is \"slightly different\" (fips-197)\n else:\n for v'var i = 1; i < (KC / 2); i++':\n tk[i] ^= tk[i - 1]\n tt = tk[(KC / 2) - 1]\n\n tk[KC / 2] ^= (S[ tt & 0xFF] ^\n (S[(tt >> 8) & 0xFF] << 8) ^\n (S[(tt >> 16) & 0xFF] << 16) ^\n (S[(tt >> 24) & 0xFF] << 24))\n\n for v'var i = (KC / 2) + 1; i < KC; i++':\n tk[i] ^= tk[i - 1]\n\n # copy values into round key arrays\n i = 0\n while i < KC and t < round_key_count:\n r = t >> 2\n c = t % 4\n self._Ke[r][c] = tk[i]\n self._Kd[rounds - r][c] = tk[v'i++']\n t += 1\n\n # inverse-cipher-ify the decryption round key (fips-197 section 5.3)\n for v'var r = 1; r < rounds; r++':\n for v'var c = 0; c < 4; c++':\n tt = self._Kd[r][c]\n self._Kd[r][c] = (U1[(tt >> 24) & 0xFF] ^\n U2[(tt >> 16) & 0xFF] ^\n U3[(tt >> 8) & 0xFF] ^\n U4[ tt & 0xFF])\n\n def _crypt(self, ciphertext, offset, encrypt):\n if encrypt:\n R1 = T1; R2 = T2; R3 = T3; R4 = T4\n o1 = 1; o3 = 3\n SB = S\n K = self._Ke\n else:\n R1 = T5; R2 = T6; R3 = T7; R4 = T8\n o1 = 3; o3 = 1\n SB = Si\n K = self._Kd\n rounds = K.length - 1\n a = self.working_mem[0]\n t = self.working_mem[1]\n\n # XOR plaintext with key\n for v'var i = 0; i < 4; i++':\n t[i] ^= K[0][i]\n\n # apply round transforms\n for v'var r = 1; r < rounds; r++':\n for v'var i = 0; i < 4; i++':\n a[i] = (R1[(t[i] >> 24) & 0xff] ^\n R2[(t[(i + o1) % 4] >> 16) & 0xff] ^\n R3[(t[(i + 2) % 4] >> 8) & 0xff] ^\n R4[ t[(i + o3) % 4] & 0xff] ^\n K[r][i])\n t.set(a)\n\n # the last round is special\n for v'var i = 0; i < 4; i++':\n tt = K[rounds][i]\n ciphertext[offset + 4 * i] = (SB[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff\n ciphertext[offset + 4 * i + 1] = (SB[(t[(i + o1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff\n ciphertext[offset + 4 * i + 2] = (SB[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff\n ciphertext[offset + 4 * i + 3] = (SB[ t[(i + o3) % 4] & 0xff] ^ tt ) & 0xff\n\n def encrypt(self, plaintext, ciphertext, offset):\n convert_to_int32(plaintext, self.working_mem[1], offset, 16)\n return self._crypt(ciphertext, offset, True)\n\n def encrypt32(self, plaintext, ciphertext, offset):\n self.working_mem[1].set(plaintext)\n return self._crypt(ciphertext, offset, True)\n\n def decrypt(self, ciphertext, plaintext, offset):\n convert_to_int32(ciphertext, self.working_mem[1], offset, 16)\n return self._crypt(plaintext, offset, False)\n\n def decrypt32(self, ciphertext, plaintext, offset):\n self.working_mem[1].set(ciphertext)\n return self._crypt(plaintext, offset, False)\n# }}}\n\ndef random_bytes_insecure(sz):\n ans = Uint8Array(sz)\n for v'var i = 0; i < sz; i++':\n ans[i] = Math.floor(Math.random() * 256)\n return ans\n\ndef random_bytes_secure(sz):\n ans = Uint8Array(sz)\n crypto.getRandomValues(ans)\n return ans\n\nrandom_bytes = random_bytes_secure if jstype(crypto) is not 'undefined' and jstype(crypto.getRandomValues) is 'function' else random_bytes_insecure\nif random_bytes is random_bytes_insecure:\n try:\n noderandom = require('crypto').randomBytes\n random_bytes = def(sz):\n return Uint8Array(noderandom(sz))\n except:\n print('WARNING: Using insecure RNG for AES')\n\nclass ModeOfOperation: # {{{\n\n def __init__(self, key):\n self.key = key or generate_key(32)\n self.aes = AES(self.key)\n\n @property\n def key_as_js(self):\n return typed_array_as_js(self.key)\n\n def tag_as_bytes(self, tag):\n if isinstance(tag, Uint8Array):\n return tag\n if not tag:\n return Uint8Array(0)\n if jstype(tag) is 'string':\n return string_to_bytes(tag)\n raise TypeError('Invalid tag, must be a string or a Uint8Array')\n# }}}\n\nclass GaloisField: # {{{\n\n def __init__(self, sub_key):\n k32 = Uint32Array(4)\n convert_to_int32(sub_key, k32, 0)\n self.m = self.generate_hash_table(k32)\n self.wmem = Uint32Array(4)\n\n def power(self, x, out):\n lsb = x[3] & 1\n for v'var i = 3; i > 0; --i':\n out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31)\n out[0] = x[0] >>> 1\n if lsb:\n out[0] ^= 0xE1000000\n\n def multiply(self, x, y):\n z_i = Uint32Array(4)\n v_i = Uint32Array(y)\n for v'var i = 0; i < 128; ++i':\n x_i = x[(i / 32) | 0] & (1 << (31 - i % 32))\n if x_i:\n z_i[0] ^= v_i[0]\n z_i[1] ^= v_i[1]\n z_i[2] ^= v_i[2]\n z_i[3] ^= v_i[3]\n self.power(v_i, v_i)\n return z_i\n\n def generate_sub_hash_table(self, mid):\n bits = mid.length\n size = 1 << bits\n half = size >>> 1\n m = Array(size)\n m[half] = Uint32Array(mid)\n i = half >>> 1\n while i > 0:\n m[i] = Uint32Array(4)\n self.power(m[2 * i], m[i])\n i >>= 1\n i = 2\n while i < half:\n for v'var j = 1; j < i; ++j':\n m_i = m[i]\n m_j = m[j]\n m[i + j] = x = Uint32Array(4)\n for v'var c = 0; c < 4; c++':\n x[c] = m_i[c] ^ m_j[c]\n i *= 2\n m[0] = Uint32Array(4)\n for v'i = half + 1; i < size; ++i':\n x = m[i ^ half]\n m[i] = y = Uint32Array(4)\n for v'var c = 0; c < 4; c++':\n y[c] = mid[c] ^ x[c]\n return m\n\n def generate_hash_table(self, key_as_int32_array):\n bits = key_as_int32_array.length\n multiplier = 8 / bits\n per_int = 4 * multiplier\n size = 16 * multiplier\n ans = Array(size)\n for v'var i =0; i < size; ++i':\n tmp = Uint32Array(4)\n idx = (i/ per_int) | 0\n shft = ((per_int - 1 - (i % per_int)) * bits)\n tmp[idx] = (1 << (bits - 1)) << shft\n ans[i] = self.generate_sub_hash_table(self.multiply(tmp, key_as_int32_array))\n return ans\n\n def table_multiply(self, x):\n z = Uint32Array(4)\n for v'var i = 0; i < 32; ++i':\n idx = (i / 8) | 0\n x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF\n ah = self.m[i][x_i]\n z[0] ^= ah[0]\n z[1] ^= ah[1]\n z[2] ^= ah[2]\n z[3] ^= ah[3]\n return z\n\n def ghash(self, x, y):\n # Corresponds to the XOR + mult_H operation from the paper\n z = self.wmem\n z[0] = y[0] ^ x[0]\n z[1] = y[1] ^ x[1]\n z[2] = y[2] ^ x[2]\n z[3] = y[3] ^ x[3]\n return self.table_multiply(z)\n\n# }}}\n\n# }}}\n\ndef generate_key(sz):\n if not number_of_rounds[sz]:\n raise ValueError('Invalid key size, must be: 16, 24 or 32')\n return random_bytes(sz)\n\ndef generate_tag(sz):\n return random_bytes(sz or 32)\n\ndef typed_array_as_js(x):\n name = x.constructor.name or 'Uint8Array'\n return '(new ' + name + '(' + JSON.stringify(Array.prototype.slice.call(x)) + '))'\n\nclass CBC(ModeOfOperation): # {{{\n\n def encrypt_bytes(self, bytes, tag_bytes, iv):\n iv = first_iv = iv or random_bytes(16)\n mlen = bytes.length + tag_bytes.length\n padsz = (16 - (mlen % 16)) % 16\n inputbytes = Uint8Array(mlen + padsz)\n if tag_bytes.length:\n inputbytes.set(tag_bytes)\n inputbytes.set(bytes, tag_bytes.length)\n\n offset = 0\n outputbytes = Uint8Array(inputbytes.length)\n for v'var block = 0; block < inputbytes.length; block += 16':\n if block > 0:\n iv, offset = outputbytes, block - 16\n for v'var i = 0; i < 16; i++':\n inputbytes[block + i] ^= iv[offset + i]\n self.aes.encrypt(inputbytes, outputbytes, block)\n return {'iv':first_iv, 'cipherbytes':outputbytes}\n\n def encrypt(self, plaintext, tag):\n return self.encrypt_bytes(string_to_bytes(plaintext), self.tag_as_bytes(tag))\n\n def decrypt_bytes(self, inputbytes, tag_bytes, iv):\n offset = 0\n outputbytes = Uint8Array(inputbytes.length)\n for v'var block = 0; block < inputbytes.length; block += 16':\n self.aes.decrypt(inputbytes, outputbytes, block)\n if block > 0:\n iv, offset = inputbytes, block - 16\n for v'var i = 0; i < 16; i++':\n outputbytes[block + i] ^= iv[offset + i]\n for v'var i = 0; i < tag_bytes.length; i++':\n if tag_bytes[i] != outputbytes[i]:\n raise ValueError('Corrupt message')\n outputbytes = outputbytes.subarray(tag_bytes.length)\n return outputbytes\n\n def decrypt(self, output_from_encrypt, tag):\n ans = self.decrypt_bytes(output_from_encrypt.cipherbytes, self.tag_as_bytes(tag), output_from_encrypt.iv)\n return str.rstrip(bytes_to_string(ans), '\\0')\n# }}}\n\nclass CTR(ModeOfOperation): # {{{\n\n # Note that this mode of operation requires the pair of (counterbytes,\n # secret key) to always be unique, for every block. Therefore, if you are\n # using it for bi-directional messaging it is best to use a different\n # secret key for each direction\n\n def __init__(self, key, iv):\n ModeOfOperation.__init__(self, key)\n self.wmem = Uint8Array(16)\n self.counter_block = Uint8Array(iv or 16)\n if self.counter_block.length != 16:\n raise ValueError('iv must be 16 bytes long')\n self.counter_index = 16\n\n def _crypt(self, bytes):\n for v'var i = 0; i < bytes.length; i++, self.counter_index++':\n if self.counter_index is 16:\n self.counter_index = 0\n self.aes.encrypt(self.counter_block, self.wmem, 0)\n increment_counter(self.counter_block)\n bytes[i] ^= self.wmem[self.counter_index]\n self.counter_index = 16\n\n def encrypt(self, plaintext, tag):\n outbytes = string_to_bytes(plaintext)\n counterbytes = Uint8Array(self.counter_block)\n if tag:\n tag_bytes = self.tag_as_bytes(tag)\n t = Uint8Array(outbytes.length + tag_bytes.length)\n t.set(tag_bytes)\n t.set(outbytes, tag_bytes.length)\n outbytes = t\n self._crypt(outbytes)\n return {'cipherbytes':outbytes, 'counterbytes':counterbytes}\n\n def __enter__(self):\n self.before_index = self.counter_index\n self.before_counter = Uint8Array(self.counter_block)\n\n def __exit__(self):\n self.counter_index = self.before_index\n self.counter_block = self.before_counter\n\n def decrypt(self, output_from_encrypt, tag):\n b = Uint8Array(output_from_encrypt.cipherbytes)\n with self:\n self.counter_block = output_from_encrypt.counterbytes\n self.counter_index = 16\n self._crypt(b)\n offset = 0\n if tag:\n tag_bytes = self.tag_as_bytes(tag)\n for v'var i = 0; i < tag_bytes.length; i++':\n if tag_bytes[i] != b[i]:\n raise ValueError('Corrupted message')\n offset = tag_bytes.length\n return bytes_to_string(b, offset)\n# }}}\n\nclass GCM(ModeOfOperation): # {{{\n\n # Note that this mode of operation requires the pair of (iv,\n # secret key) to always be unique, for every message. Therefore, if you are\n # using it for bi-directional messaging it is best to use a different\n # secret key for each direction (you could also use random_key,\n # but that has a non-zero probability of repeating keys).\n # See http://web.cs.ucdavis.edu/~rogaway/ocb/gcm.pdf\n\n def __init__(self, key, random_iv=False):\n ModeOfOperation.__init__(self, key)\n self.random_iv = random_iv\n if not random_iv:\n self.current_iv = Uint8Array(12)\n\n # Generate the hash subkey\n H = Uint8Array(16)\n self.aes.encrypt(Uint8Array(16), H, 0)\n self.galois = GaloisField(H)\n\n # Working memory\n self.J0 = Uint32Array(4)\n self.wmem = Uint32Array(4)\n self.byte_block = Uint8Array(16)\n\n def increment_iv(self):\n c = self.current_iv\n for v'var i = 11; i >=0; i--':\n if c[i] is 255:\n if i is 0:\n raise ValueError('The GCM IV space is exhausted, cannot encrypt anymore messages with this key as doing so would cause the IV to repeat')\n c[i] = 0\n else:\n c[i] += 1\n break\n\n def _create_j0(self, iv):\n J0 = self.J0\n if iv.length is 12:\n convert_to_int32(iv, J0)\n J0[3] = 1\n else:\n J0.fill(0)\n tmp = convert_to_int32_pad(iv)\n while tmp.length:\n J0 = self.galois.ghash(J0, tmp)\n tmp = tmp.subarray(4)\n tmp = Uint32Array(4)\n tmp.set(from_64_to_32(iv.length * 8), 2)\n J0 = self.galois.ghash(J0, tmp)\n return J0\n\n def _start(self, iv, additional_data):\n J0 = self._create_j0(iv)\n # Generate initial counter block\n in_block = Uint32Array(J0)\n in_block[3] = (in_block[3] + 1) & 0xFFFFFFFF # increment counter\n\n # Process additional_data\n S = Uint32Array(4)\n overflow = additional_data.length % 16\n for v'var i = 0; i < additional_data.length - overflow; i += 16':\n convert_to_int32(additional_data, self.wmem, i, 16)\n S = self.galois.ghash(S, self.wmem)\n if overflow:\n self.byte_block.fill(0)\n self.byte_block.set(additional_data.subarray(additional_data.length - overflow))\n convert_to_int32(self.byte_block, self.wmem)\n S = self.galois.ghash(S, self.wmem)\n return J0, in_block, S\n\n def _finish(self, iv, J0, adata_len, S, outbytes):\n # Mix the lengths into S\n lengths = Uint32Array(4)\n lengths.set(from_64_to_32(adata_len * 8))\n lengths.set(from_64_to_32(outbytes.length * 8), 2)\n S = self.galois.ghash(S, lengths)\n\n # Create the tag\n self.aes.encrypt32(J0, self.byte_block, 0)\n convert_to_int32(self.byte_block, self.wmem)\n tag = Uint32Array(4)\n for v'var i = 0; i < S.length; i++':\n tag[i] = S[i] ^ self.wmem[i]\n return {'iv':iv, 'cipherbytes':outbytes, 'tag':tag}\n\n def _crypt(self, iv, bytes, additional_data, decrypt):\n ghash = self.galois.ghash.bind(self.galois)\n outbytes = Uint8Array(bytes.length)\n J0, in_block, S = self._start(iv, additional_data)\n bb = self.byte_block\n enc = self.aes.encrypt32.bind(self.aes)\n hash_bytes = bytes if decrypt else outbytes\n\n # Create the ciphertext, encrypting block by block\n for v'var i = 0, counter_index = 16; i < bytes.length; i++, counter_index++':\n if counter_index is 16:\n # Encrypt counter and increment it\n enc(in_block, bb, 0)\n in_block[3] = (in_block[3] + 1) & 0xFFFFFFFF # increment counter\n counter_index = 0\n # Output is XOR of encrypted counter with input\n outbytes[i] = bytes[i] ^ bb[counter_index]\n if counter_index is 15:\n # We have completed a block, update the hash\n convert_to_int32(hash_bytes, self.wmem, i - 15, 16)\n S = ghash(S, self.wmem)\n\n # Check if we have a last partial block\n overflow = outbytes.length % 16\n if overflow:\n # partial output block\n bb.fill(0)\n bb.set(hash_bytes.subarray(hash_bytes.length - overflow))\n convert_to_int32(bb, self.wmem)\n S = ghash(S, self.wmem)\n\n return self._finish(iv, J0, additional_data.length, S, outbytes)\n\n def encrypt(self, plaintext, tag):\n if self.random_iv:\n iv = random_bytes(12)\n else:\n self.increment_iv()\n iv = self.current_iv\n return self._crypt(iv, string_to_bytes(plaintext), self.tag_as_bytes(tag), False)\n\n def decrypt(self, output_from_encrypt, tag):\n if output_from_encrypt.tag.length != 4:\n raise ValueError('Corrupted message')\n ans = self._crypt(output_from_encrypt.iv, output_from_encrypt.cipherbytes, self.tag_as_bytes(tag), True)\n if ans.tag != output_from_encrypt.tag:\n raise ValueError('Corrupted message')\n return bytes_to_string(ans.cipherbytes)\n# }}}\n","__stdlib__/elementmaker.pyj":"# vim:fileencoding=utf-8\n# License: GPL v3 Copyright: 2015, Kovid Goyal \n\nhtml_elements = {\n 'a', 'abbr', 'acronym', 'address', 'area',\n 'article', 'aside', 'audio', 'b', 'base', 'big', 'body', 'blockquote', 'br', 'button',\n 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup',\n 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn',\n 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-source', 'fieldset',\n 'figcaption', 'figure', 'footer', 'font', 'form', 'header', 'h1',\n 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'head', 'i', 'iframe', 'img', 'input', 'ins',\n 'keygen', 'kbd', 'label', 'legend', 'li', 'm', 'map', 'menu', 'meter',\n 'multicol', 'nav', 'nextid', 'ol', 'output', 'optgroup', 'option',\n 'p', 'pre', 'progress', 'q', 's', 'samp', 'script', 'section', 'select',\n 'small', 'sound', 'source', 'spacer', 'span', 'strike', 'strong', 'style',\n 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'time', 'tfoot',\n 'th', 'thead', 'tr', 'tt', 'u', 'ul', 'var', 'video'\n}\n\nmathml_elements = {\n 'maction', 'math', 'merror', 'mfrac', 'mi',\n 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom',\n 'mprescripts', 'mroot', 'mrow', 'mspace', 'msqrt', 'mstyle', 'msub',\n 'msubsup', 'msup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',\n 'munderover', 'none'\n}\n\nsvg_elements = {\n 'a', 'animate', 'animateColor', 'animateMotion',\n 'animateTransform', 'clipPath', 'circle', 'defs', 'desc', 'ellipse',\n 'font-face', 'font-face-name', 'font-face-src', 'g', 'glyph', 'hkern',\n 'linearGradient', 'line', 'marker', 'metadata', 'missing-glyph',\n 'mpath', 'path', 'polygon', 'polyline', 'radialGradient', 'rect',\n 'set', 'stop', 'svg', 'switch', 'text', 'title', 'tspan', 'use'\n}\n\nhtml5_tags = html_elements.union(mathml_elements).union(svg_elements)\n\ndef _makeelement(tag, *args, **kwargs):\n ans = this.createElement(tag)\n\n for attr in kwargs:\n vattr = str.replace(str.rstrip(attr, '_'), '_', '-')\n val = kwargs[attr]\n if callable(val):\n if str.startswith(attr, 'on'):\n attr = attr[2:]\n ans.addEventListener(attr, val)\n elif val is True:\n ans.setAttribute(vattr, vattr)\n elif jstype(val) is 'string':\n ans.setAttribute(vattr, val)\n\n for arg in args:\n if jstype(arg) is 'string':\n arg = this.createTextNode(arg)\n ans.appendChild(arg)\n return ans\n\ndef maker_for_document(document):\n # Create an elementmaker to be used with the specified document\n E = _makeelement.bind(document)\n Object.defineProperties(E, {\n tag: {\n 'value':_makeelement.bind(document, tag)\n } for tag in html5_tags\n })\n return E\n\nif jstype(document) is 'undefined':\n E = maker_for_document({\n 'createTextNode': def(value): return value;,\n 'createElement': def(name):\n return {\n 'name':name,\n 'children':[],\n 'attributes':{},\n 'setAttribute': def(name, val): this.attributes[name] = val;,\n 'appendChild': def(child): this.children.push(child);,\n }\n })\nelse:\n E = maker_for_document(document)\n","__stdlib__/encodings.pyj":"# vim:fileencoding=utf-8\n# License: BSD Copyright: 2016, Kovid Goyal \n\ndef base64encode(bytes, altchars, pad_char):\n # Convert an array of bytes into a base-64 encoded string\n l = bytes.length\n remainder = l % 3\n main_length = l - remainder\n encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + (altchars or '+/')\n pad_char = '=' if pad_char is undefined else pad_char\n ans = v'[]'\n for v'var i = 0; i < main_length; i += 3':\n chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]\n ans.push(encodings[(chunk & 16515072) >> 18], encodings[(chunk & 258048) >> 12], encodings[(chunk & 4032) >> 6], encodings[chunk & 63])\n if remainder is 1:\n chunk = bytes[main_length]\n ans.push(encodings[(chunk & 252) >> 2], encodings[(chunk & 3) << 4], pad_char, pad_char)\n elif remainder is 2:\n chunk = (bytes[main_length] << 8) | bytes[main_length + 1]\n ans.push(encodings[(chunk & 64512) >> 10], encodings[(chunk & 1008) >> 4], encodings[(chunk & 15) << 2], pad_char)\n return ans.join('')\n\ndef base64decode(string):\n # convert the output of base64encode back into an array of bytes\n # (Uint8Array) only works with the standard altchars and pad_char\n if jstype(window) is not 'undefined':\n chars = window.atob(string)\n else:\n chars = new Buffer(string, 'base64').toString('binary') # noqa: undef\n ans = Uint8Array(chars.length)\n for i in range(ans.length):\n ans[i] = chars.charCodeAt(i)\n return ans\n\ndef urlsafe_b64encode(bytes, pad_char):\n return base64encode(bytes, '-_', pad_char)\n\ndef urlsafe_b64decode(string):\n string = String.prototype.replace.call(string, /[_-]/g, def(m): return '+' if m is '-' else '/';)\n return base64decode(string)\n\ndef hexlify(bytes):\n ans = v'[]'\n for v'var i = 0; i < bytes.length; i++':\n x = bytes[i].toString(16)\n if x.length is 1:\n x = '0' + x\n ans.push(x)\n return ans.join('')\n\ndef unhexlify(string):\n num = string.length // 2\n if num * 2 is not string.length:\n raise ValueError('string length is not a multiple of two')\n ans = Uint8Array(num)\n for v'var i = 0; i < num; i++':\n x = parseInt(string[i*2:i*2+2], 16)\n if isNaN(x):\n raise ValueError('string is not hex-encoded')\n ans[i] = x\n return ans\n\nutf8_decoder_table = v'''[\n 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,0,0,0,0,0, // 00..1f\n 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,0,0,0,0,0, // 20..3f\n 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,0,0,0,0,0, // 40..5f\n 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,0,0,0,0,0, // 60..7f\n 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f\n 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf\n 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df\n 0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef\n 0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff\n 0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0\n 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2\n 1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4\n 1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6\n 1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8\n]'''\n\ndef _from_code_point(x):\n if x <= 0xFFFF:\n return String.fromCharCode(x)\n x -= 0x10000\n return String.fromCharCode((x >> 10) + 0xD800, (x % 0x400) + 0xDC00)\n\ndef utf8_decode(bytes, errors, replacement):\n # Convert an array of UTF-8 encoded bytes into a string\n state = 0\n ans = v'[]'\n\n for v'var i = 0, l = bytes.length; i < l; i++': # noqa\n byte = bytes[i]\n typ = utf8_decoder_table[byte]\n codep = (byte & 0x3f) | (codep << 6) if state is not 0 else (0xff >> typ) & (byte)\n state = utf8_decoder_table[256 + state*16 + typ]\n if state is 0:\n ans.push(_from_code_point(codep))\n elif state is 1:\n if not errors or errors is 'strict':\n raise UnicodeDecodeError(str.format('The byte 0x{:02x} at position {} is not valid UTF-8', byte, i))\n elif errors is 'replace':\n ans.push(replacement or '?')\n return ans.join('')\n\ndef utf8_encode_js(string):\n # Encode a string as an array of UTF-8 bytes\n escstr = encodeURIComponent(string)\n ans = v'[]'\n for v'var i = 0; i < escstr.length; i++':\n ch = escstr[i]\n if ch is '%':\n ans.push(parseInt(escstr[i+1:i+3], 16))\n i += 2\n else:\n ans.push(ch.charCodeAt(0))\n return Uint8Array(ans)\n\nif jstype(TextEncoder) is 'function':\n _u8enc = TextEncoder('utf-8')\n utf8_encode = _u8enc.encode.bind(_u8enc)\n _u8enc = undefined\nelse:\n utf8_encode = utf8_encode_js\n\ndef utf8_encode_native(string):\n return _u8enc.encode(string)\n","__stdlib__/gettext.pyj":"# vim:fileencoding=utf-8\n# License: BSD Copyright: 2015, Kovid Goyal \n\n# noqa: eol-semicolon\n\n# The Plural-Forms parser {{{\n# From: https://github.com/SlexAxton/Jed/blob/master/jed.js licensed under the WTFPL\n\nJed = {}\n\nvr'''\n Jed.PF = {};\n\n Jed.PF.parse = function ( p ) {\n var plural_str = Jed.PF.extractPluralExpr( p );\n return Jed.PF.parser.parse.call(Jed.PF.parser, plural_str);\n };\n\n Jed.PF.compile = function ( p ) {\n // Handle trues and falses as 0 and 1\n function imply( val ) {\n return (val === true ? 1 : val ? val : 0);\n }\n\n var ast = Jed.PF.parse( p );\n return function ( n ) {\n return imply( Jed.PF.interpreter( ast )( n ) );\n };\n };\n\n Jed.PF.interpreter = function ( ast ) {\n return function ( n ) {\n var res;\n switch ( ast.type ) {\n case 'GROUP':\n return Jed.PF.interpreter( ast.expr )( n );\n case 'TERNARY':\n if ( Jed.PF.interpreter( ast.expr )( n ) ) {\n return Jed.PF.interpreter( ast.truthy )( n );\n }\n return Jed.PF.interpreter( ast.falsey )( n );\n case 'OR':\n return Jed.PF.interpreter( ast.left )( n ) || Jed.PF.interpreter( ast.right )( n );\n case 'AND':\n return Jed.PF.interpreter( ast.left )( n ) && Jed.PF.interpreter( ast.right )( n );\n case 'LT':\n return Jed.PF.interpreter( ast.left )( n ) < Jed.PF.interpreter( ast.right )( n );\n case 'GT':\n return Jed.PF.interpreter( ast.left )( n ) > Jed.PF.interpreter( ast.right )( n );\n case 'LTE':\n return Jed.PF.interpreter( ast.left )( n ) <= Jed.PF.interpreter( ast.right )( n );\n case 'GTE':\n return Jed.PF.interpreter( ast.left )( n ) >= Jed.PF.interpreter( ast.right )( n );\n case 'EQ':\n return Jed.PF.interpreter( ast.left )( n ) == Jed.PF.interpreter( ast.right )( n );\n case 'NEQ':\n return Jed.PF.interpreter( ast.left )( n ) != Jed.PF.interpreter( ast.right )( n );\n case 'MOD':\n return Jed.PF.interpreter( ast.left )( n ) % Jed.PF.interpreter( ast.right )( n );\n case 'VAR':\n return n;\n case 'NUM':\n return ast.val;\n default:\n throw new Error(\"Invalid Token found.\");\n }\n };\n };\n\n Jed.PF.extractPluralExpr = function ( p ) {\n // trim first\n p = p.replace(/^\\s\\s*/, '').replace(/\\s\\s*$/, '');\n\n if (! /;\\s*$/.test(p)) {\n p = p.concat(';');\n }\n\n var nplurals_re = /nplurals\\=(\\d+);/,\n plural_re = /plural\\=(.*);/,\n nplurals_matches = p.match( nplurals_re ),\n res = {},\n plural_matches;\n\n // Find the nplurals number\n if ( nplurals_matches.length > 1 ) {\n res.nplurals = nplurals_matches[1];\n }\n else {\n throw new Error('nplurals not found in plural_forms string: ' + p );\n }\n\n // remove that data to get to the formula\n p = p.replace( nplurals_re, \"\" );\n plural_matches = p.match( plural_re );\n\n if (!( plural_matches && plural_matches.length > 1 ) ) {\n throw new Error('`plural` expression not found: ' + p);\n }\n return plural_matches[ 1 ];\n };\n\n /* Jison generated parser */\n Jed.PF.parser = (function(){\n\nvar parser = {trace: function trace() { },\nyy: {},\nsymbols_: {\"error\":2,\"expressions\":3,\"e\":4,\"EOF\":5,\"?\":6,\":\":7,\"||\":8,\"&&\":9,\"<\":10,\"<=\":11,\">\":12,\">=\":13,\"!=\":14,\"==\":15,\"%\":16,\"(\":17,\")\":18,\"n\":19,\"NUMBER\":20,\"$accept\":0,\"$end\":1},\nterminals_: {2:\"error\",5:\"EOF\",6:\"?\",7:\":\",8:\"||\",9:\"&&\",10:\"<\",11:\"<=\",12:\">\",13:\">=\",14:\"!=\",15:\"==\",16:\"%\",17:\"(\",18:\")\",19:\"n\",20:\"NUMBER\"},\nproductions_: [0,[3,2],[4,5],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,3],[4,1],[4,1]],\nperformAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {\n\nvar $0 = $$.length - 1;\nswitch (yystate) {\ncase 1: return { type : 'GROUP', expr: $$[$0-1] };\ncase 2:this.$ = { type: 'TERNARY', expr: $$[$0-4], truthy : $$[$0-2], falsey: $$[$0] };\nbreak;\ncase 3:this.$ = { type: \"OR\", left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 4:this.$ = { type: \"AND\", left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 5:this.$ = { type: 'LT', left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 6:this.$ = { type: 'LTE', left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 7:this.$ = { type: 'GT', left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 8:this.$ = { type: 'GTE', left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 9:this.$ = { type: 'NEQ', left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 10:this.$ = { type: 'EQ', left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 11:this.$ = { type: 'MOD', left: $$[$0-2], right: $$[$0] };\nbreak;\ncase 12:this.$ = { type: 'GROUP', expr: $$[$0-1] };\nbreak;\ncase 13:this.$ = { type: 'VAR' };\nbreak;\ncase 14:this.$ = { type: 'NUM', val: Number(yytext) };\nbreak;\n}\n},\ntable: [{3:1,4:2,17:[1,3],19:[1,4],20:[1,5]},{1:[3]},{5:[1,6],6:[1,7],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16]},{4:17,17:[1,3],19:[1,4],20:[1,5]},{5:[2,13],6:[2,13],7:[2,13],8:[2,13],9:[2,13],10:[2,13],11:[2,13],12:[2,13],13:[2,13],14:[2,13],15:[2,13],16:[2,13],18:[2,13]},{5:[2,14],6:[2,14],7:[2,14],8:[2,14],9:[2,14],10:[2,14],11:[2,14],12:[2,14],13:[2,14],14:[2,14],15:[2,14],16:[2,14],18:[2,14]},{1:[2,1]},{4:18,17:[1,3],19:[1,4],20:[1,5]},{4:19,17:[1,3],19:[1,4],20:[1,5]},{4:20,17:[1,3],19:[1,4],20:[1,5]},{4:21,17:[1,3],19:[1,4],20:[1,5]},{4:22,17:[1,3],19:[1,4],20:[1,5]},{4:23,17:[1,3],19:[1,4],20:[1,5]},{4:24,17:[1,3],19:[1,4],20:[1,5]},{4:25,17:[1,3],19:[1,4],20:[1,5]},{4:26,17:[1,3],19:[1,4],20:[1,5]},{4:27,17:[1,3],19:[1,4],20:[1,5]},{6:[1,7],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[1,28]},{6:[1,7],7:[1,29],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16]},{5:[2,3],6:[2,3],7:[2,3],8:[2,3],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,3]},{5:[2,4],6:[2,4],7:[2,4],8:[2,4],9:[2,4],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,4]},{5:[2,5],6:[2,5],7:[2,5],8:[2,5],9:[2,5],10:[2,5],11:[2,5],12:[2,5],13:[2,5],14:[2,5],15:[2,5],16:[1,16],18:[2,5]},{5:[2,6],6:[2,6],7:[2,6],8:[2,6],9:[2,6],10:[2,6],11:[2,6],12:[2,6],13:[2,6],14:[2,6],15:[2,6],16:[1,16],18:[2,6]},{5:[2,7],6:[2,7],7:[2,7],8:[2,7],9:[2,7],10:[2,7],11:[2,7],12:[2,7],13:[2,7],14:[2,7],15:[2,7],16:[1,16],18:[2,7]},{5:[2,8],6:[2,8],7:[2,8],8:[2,8],9:[2,8],10:[2,8],11:[2,8],12:[2,8],13:[2,8],14:[2,8],15:[2,8],16:[1,16],18:[2,8]},{5:[2,9],6:[2,9],7:[2,9],8:[2,9],9:[2,9],10:[2,9],11:[2,9],12:[2,9],13:[2,9],14:[2,9],15:[2,9],16:[1,16],18:[2,9]},{5:[2,10],6:[2,10],7:[2,10],8:[2,10],9:[2,10],10:[2,10],11:[2,10],12:[2,10],13:[2,10],14:[2,10],15:[2,10],16:[1,16],18:[2,10]},{5:[2,11],6:[2,11],7:[2,11],8:[2,11],9:[2,11],10:[2,11],11:[2,11],12:[2,11],13:[2,11],14:[2,11],15:[2,11],16:[2,11],18:[2,11]},{5:[2,12],6:[2,12],7:[2,12],8:[2,12],9:[2,12],10:[2,12],11:[2,12],12:[2,12],13:[2,12],14:[2,12],15:[2,12],16:[2,12],18:[2,12]},{4:30,17:[1,3],19:[1,4],20:[1,5]},{5:[2,2],6:[1,7],7:[2,2],8:[1,8],9:[1,9],10:[1,10],11:[1,11],12:[1,12],13:[1,13],14:[1,14],15:[1,15],16:[1,16],18:[2,2]}],\ndefaultActions: {6:[2,1]},\nparseError: function parseError(str, hash) {\n throw new Error(str);\n},\nparse: function parse(input) {\n var self = this,\n stack = [0],\n vstack = [null], // semantic value stack\n lstack = [], // location stack\n table = this.table,\n yytext = '',\n yylineno = 0,\n yyleng = 0,\n recovering = 0,\n TERROR = 2,\n EOF = 1;\n\n //this.reductionCount = this.shiftCount = 0;\n\n this.lexer.setInput(input);\n this.lexer.yy = this.yy;\n this.yy.lexer = this.lexer;\n if (typeof this.lexer.yylloc == 'undefined')\n this.lexer.yylloc = {};\n var yyloc = this.lexer.yylloc;\n lstack.push(yyloc);\n\n if (typeof this.yy.parseError === 'function')\n this.parseError = this.yy.parseError;\n\n function popStack (n) {\n stack.length = stack.length - 2*n;\n vstack.length = vstack.length - n;\n lstack.length = lstack.length - n;\n }\n\n function lex() {\n var token;\n token = self.lexer.lex() || 1; // $end = 1\n // if token isn't its numeric value, convert\n if (typeof token !== 'number') {\n token = self.symbols_[token] || token;\n }\n return token;\n }\n\n var symbol, preErrorSymbol, state, action, a, r, yyval={},p,len,newState, expected, errStr;\n while (true) {\n // retreive state number from top of stack\n state = stack[stack.length-1];\n\n // use default actions if available\n if (this.defaultActions[state]) {\n action = this.defaultActions[state];\n } else {\n if (symbol === null || symbol === undefined)\n symbol = lex();\n // read action for current state and first input\n action = table[state] && table[state][symbol];\n }\n\n // handle parse error\n _handle_error:\n if (typeof action === 'undefined' || !action.length || !action[0]) {\n\n if (!recovering) {\n // Report error\n expected = [];\n for (p in table[state]) if (this.terminals_[p] && p > 2) {\n expected.push(\"'\"+this.terminals_[p]+\"'\");\n }\n errStr = '';\n if (this.lexer.showPosition) {\n errStr = 'Parse error on line '+(yylineno+1)+\":\\n\"+this.lexer.showPosition()+\"\\nExpecting \"+expected.join(', ') + \", got '\" + this.terminals_[symbol]+ \"'\";\n } else {\n errStr = 'Parse error on line '+(yylineno+1)+\": Unexpected \" +\n (symbol == 1 /*EOF*/ ? \"end of input\" :\n (\"'\"+(this.terminals_[symbol] || symbol)+\"'\"));\n }\n this.parseError(errStr,\n {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});\n }\n\n // just recovered from another error\n if (recovering == 3) {\n if (symbol == EOF) {\n throw new Error(errStr || 'Parsing halted.');\n }\n\n // discard current lookahead and grab another\n yyleng = this.lexer.yyleng;\n yytext = this.lexer.yytext;\n yylineno = this.lexer.yylineno;\n yyloc = this.lexer.yylloc;\n symbol = lex();\n }\n\n // try to recover from error\n while (1) {\n // check for error recovery rule in this state\n if ((TERROR.toString()) in table[state]) {\n break;\n }\n if (state === 0) {\n throw new Error(errStr || 'Parsing halted.');\n }\n popStack(1);\n state = stack[stack.length-1];\n }\n\n preErrorSymbol = symbol; // save the lookahead token\n symbol = TERROR; // insert generic error symbol as new lookahead\n state = stack[stack.length-1];\n action = table[state] && table[state][TERROR];\n recovering = 3; // allow 3 real symbols to be shifted before reporting a new error\n }\n\n // this shouldn't happen, unless resolve defaults are off\n if (action[0] instanceof Array && action.length > 1) {\n throw new Error('Parse Error: multiple actions possible at state: '+state+', token: '+symbol);\n }\n\n switch (action[0]) {\n\n case 1: // shift\n //this.shiftCount++;\n\n stack.push(symbol);\n vstack.push(this.lexer.yytext);\n lstack.push(this.lexer.yylloc);\n stack.push(action[1]); // push state\n symbol = null;\n if (!preErrorSymbol) { // normal execution/no error\n yyleng = this.lexer.yyleng;\n yytext = this.lexer.yytext;\n yylineno = this.lexer.yylineno;\n yyloc = this.lexer.yylloc;\n if (recovering > 0)\n recovering--;\n } else { // error just occurred, resume old lookahead f/ before error\n symbol = preErrorSymbol;\n preErrorSymbol = null;\n }\n break;\n\n case 2: // reduce\n //this.reductionCount++;\n\n len = this.productions_[action[1]][1];\n\n // perform semantic action\n yyval.$ = vstack[vstack.length-len]; // default to $$ = $1\n // default location, uses first token for firsts, last for lasts\n yyval._$ = {\n first_line: lstack[lstack.length-(len||1)].first_line,\n last_line: lstack[lstack.length-1].last_line,\n first_column: lstack[lstack.length-(len||1)].first_column,\n last_column: lstack[lstack.length-1].last_column\n };\n r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);\n\n if (typeof r !== 'undefined') {\n return r;\n }\n\n // pop off stack\n if (len) {\n stack = stack.slice(0,-1*len*2);\n vstack = vstack.slice(0, -1*len);\n lstack = lstack.slice(0, -1*len);\n }\n\n stack.push(this.productions_[action[1]][0]); // push nonterminal (reduce)\n vstack.push(yyval.$);\n lstack.push(yyval._$);\n // goto new state = table[STATE][NONTERMINAL]\n newState = table[stack[stack.length-2]][stack[stack.length-1]];\n stack.push(newState);\n break;\n\n case 3: // accept\n return true;\n }\n\n }\n\n return true;\n}};/* Jison generated lexer */\nvar lexer = (function(){\n\nvar lexer = ({EOF:1,\nparseError:function parseError(str, hash) {\n if (this.yy.parseError) {\n this.yy.parseError(str, hash);\n } else {\n throw new Error(str);\n }\n },\nsetInput:function (input) {\n this._input = input;\n this._more = this._less = this.done = false;\n this.yylineno = this.yyleng = 0;\n this.yytext = this.matched = this.match = '';\n this.conditionStack = ['INITIAL'];\n this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0};\n return this;\n },\ninput:function () {\n var ch = this._input[0];\n this.yytext+=ch;\n this.yyleng++;\n this.match+=ch;\n this.matched+=ch;\n var lines = ch.match(/\\n/);\n if (lines) this.yylineno++;\n this._input = this._input.slice(1);\n return ch;\n },\nunput:function (ch) {\n this._input = ch + this._input;\n return this;\n },\nmore:function () {\n this._more = true;\n return this;\n },\npastInput:function () {\n var past = this.matched.substr(0, this.matched.length - this.match.length);\n return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\\n/g, \"\");\n },\nupcomingInput:function () {\n var next = this.match;\n if (next.length < 20) {\n next += this._input.substr(0, 20-next.length);\n }\n return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\\n/g, \"\");\n },\nshowPosition:function () {\n var pre = this.pastInput();\n var c = new Array(pre.length + 1).join(\"-\");\n return pre + this.upcomingInput() + \"\\n\" + c+\"^\";\n },\nnext:function () {\n if (this.done) {\n return this.EOF;\n }\n if (!this._input) this.done = true;\n\n var token,\n match,\n col,\n lines;\n if (!this._more) {\n this.yytext = '';\n this.match = '';\n }\n var rules = this._currentRules();\n for (var i=0;i < rules.length; i++) {\n match = this._input.match(this.rules[rules[i]]);\n if (match) {\n lines = match[0].match(/\\n.*/g);\n if (lines) this.yylineno += lines.length;\n this.yylloc = {first_line: this.yylloc.last_line,\n last_line: this.yylineno+1,\n first_column: this.yylloc.last_column,\n last_column: lines ? lines[lines.length-1].length-1 : this.yylloc.last_column + match[0].length};\n this.yytext += match[0];\n this.match += match[0];\n this.matches = match;\n this.yyleng = this.yytext.length;\n this._more = false;\n this._input = this._input.slice(match[0].length);\n this.matched += match[0];\n token = this.performAction.call(this, this.yy, this, rules[i],this.conditionStack[this.conditionStack.length-1]);\n if (token) return token;\n else return;\n }\n }\n if (this._input === \"\") {\n return this.EOF;\n } else {\n this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\\n'+this.showPosition(),\n {text: \"\", token: null, line: this.yylineno});\n }\n },\nlex:function lex() {\n var r = this.next();\n if (typeof r !== 'undefined') {\n return r;\n } else {\n return this.lex();\n }\n },\nbegin:function begin(condition) {\n this.conditionStack.push(condition);\n },\npopState:function popState() {\n return this.conditionStack.pop();\n },\n_currentRules:function _currentRules() {\n return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules;\n },\ntopState:function () {\n return this.conditionStack[this.conditionStack.length-2];\n },\npushState:function begin(condition) {\n this.begin(condition);\n }});\nlexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) {\n\nvar YYSTATE=YY_START;\nswitch($avoiding_name_collisions) {\ncase 0:/* skip whitespace */\nbreak;\ncase 1:return 20\nbreak;\ncase 2:return 19\nbreak;\ncase 3:return 8\nbreak;\ncase 4:return 9\nbreak;\ncase 5:return 6\nbreak;\ncase 6:return 7\nbreak;\ncase 7:return 11\nbreak;\ncase 8:return 13\nbreak;\ncase 9:return 10\nbreak;\ncase 10:return 12\nbreak;\ncase 11:return 14\nbreak;\ncase 12:return 15\nbreak;\ncase 13:return 16\nbreak;\ncase 14:return 17\nbreak;\ncase 15:return 18\nbreak;\ncase 16:return 5\nbreak;\ncase 17:return 'INVALID'\nbreak;\n}\n};\nlexer.rules = [/^\\s+/,/^[0-9]+(\\.[0-9]+)?\\b/,/^n\\b/,/^\\|\\|/,/^&&/,/^\\?/,/^:/,/^<=/,/^>=/,/^/,/^!=/,/^==/,/^%/,/^\\(/,/^\\)/,/^$/,/^./];\nlexer.conditions = {\"INITIAL\":{\"rules\":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17],\"inclusive\":true}};return lexer;})()\nparser.lexer = lexer;\nreturn parser;\n})();\n'''\nplural_forms_parser = Jed.PF\n# }}}\n\ndef _get_plural_forms_function(plural_forms_string):\n return plural_forms_parser.compile(plural_forms_string or \"nplurals=2; plural=(n != 1);\")\n\n_gettext = def(text): return text\n\n_ngettext = def(text, plural, n): return text if n is 1 else plural\n\ndef gettext(text):\n return _gettext(text)\n\ndef ngettext(text, plural, n):\n return _ngettext(text, plural, n)\n\ndef install(translation_data):\n t = new Translations(translation_data)\n t.install()\n for func in register_callback.install_callbacks:\n try:\n func(t)\n except:\n pass\n return t\n\nhas_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty)\n\ndef register_callback(func):\n # Register callbacks that will be called when new translation data is\n # installed\n register_callback.install_callbacks.push(func)\nregister_callback.install_callbacks = v'[]'\n\nempty_translation_data = {'entries': {}}\n\nclass Translations:\n\n def __init__(self, translation_data):\n translation_data = translation_data or empty_translation_data\n func = _get_plural_forms_function(translation_data.plural_forms)\n self.translations = [[translation_data, func]]\n self.language = translation_data['language']\n\n def add_fallback(self, fallback):\n fallback = fallback or empty_translation_data\n func = _get_plural_forms_function(fallback.plural_forms)\n self.translations.push([fallback, func])\n\n def gettext(self, text):\n for t in self.translations:\n m = t[0].entries\n if has_prop(m, text):\n return m[text][0]\n return text\n\n def ngettext(self, text, plural, n):\n for t in self.translations:\n m = t[0].entries\n if has_prop(m, text):\n idx = t[1](n)\n return m[text][idx] or (text if n is 1 else plural)\n return text if n is 1 else plural\n\n def install(self):\n nonlocal _gettext, _ngettext\n _gettext = def ():\n return self.gettext.apply(self, arguments)\n _ngettext = def ():\n return self.ngettext.apply(self, arguments)\n","__stdlib__/math.pyj":"###########################################################\n# RapydScript Standard Library\n# Author: Alexander Tsepkov\n# Copyright 2013 Pyjeon Software LLC\n# License: Apache License 2.0\n# This library is covered under Apache license, so that\n# you can distribute it with your RapydScript applications.\n###########################################################\n\n\n# basic implementation of Python's 'math' library\n\n# NOTE: this is only meant to aid those porting lots of Python code into RapydScript,\n# if you're writing a new RapydScript application, in most cases you probably want to\n# use JavaScript's Math module directly instead\n\n\npi = Math.PI\ne = Math.E\n\n########################################\n# Number-theoretic and representation functions\n########################################\ndef ceil(x):\n return Math.ceil(x)\ndef copysign(x, y):\n x = Math.abs(x)\n if y < 0:\n return -x\n else:\n return x\ndef fabs(x):\n return Math.abs(x)\ndef factorial(x):\n if Math.abs(int(x)) is not x:\n raise ValueError(\"factorial() only accepts integral values\")\n factorial.cache = []\n r = def(n):\n if n is 0 or n is 1:\n return 1\n if not factorial.cache[n]:\n factorial.cache[n] = r(n-1) * n\n return factorial.cache[n]\n return r(x)\ndef floor(x):\n return Math.floor(x)\ndef fmod(x, y):\n # javascript's % operator isn't consistent with C fmod implementation, this function is\n while y <= x:\n x -= y\n return x\ndef fsum(iterable):\n # like Python's fsum, this method is much more resilient to rounding errors than regular sum\n partials = [] # sorted, non-overlapping partial sums\n for x in iterable:\n i = 0\n for y in partials:\n if Math.abs(x) < Math.abs(y):\n x, y = y, x\n hi = x + y\n lo = y - (hi - x)\n if lo:\n partials[i] = lo\n i += 1\n x = hi\n #partials[i:] = [x]\n partials.splice(i, partials.length-i, x)\n return sum(partials)\ndef isinf(x):\n return not isFinite(x)\ndef isnan(x):\n return isNaN(x)\ndef modf(x):\n m = fmod(x, 1)\n return m, x-m\ndef trunc(x):\n return x | 0\n\n########################################\n# Power and logarithmic functions\n########################################\ndef exp(x):\n return Math.exp(x)\ndef expm1(x):\n # NOTE: Math.expm1() is currently only implemented in Firefox, this provides alternative implementation\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/expm1\n #return Math.expm1(x)\n if Math.abs(x) < 1e-5:\n return x + 0.5*x*x\n else:\n return Math.exp(x) - 1\ndef log(x, base=e):\n return Math.log(x)/Math.log(base)\ndef log1p(x):\n # NOTE: Math.log1p() is currently only implemented in Firefox, this provides alternative implementation\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log1p\n # this version has been taken from http://phpjs.org/functions/log1p/\n # admittedly it's not as accurate as MDN version, as you can see from math.log1p(1) result\n ret = 0\n n = 50\n if x <= -1:\n return Number.NEGATIVE_INFINITY\n if x < 0 or x > 1:\n return Math.log(1 + x)\n for i in range(1, n):\n if i % 2 is 0:\n ret -= Math.pow(x, i) / i\n else:\n ret += Math.pow(x, i) / i\n return ret\ndef log10(x):\n # NOTE: Math.log10() is currently only implemented in Firefox, this provides alternative implementation\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log10\n # I didn't find a more accurate algorithm so I'm using the basic implementation\n return Math.log(x)/Math.LN10\ndef pow(x, y):\n if x < 0 and int(y) is not y:\n raise ValueError('math domain error')\n if isnan(y) and x is 1:\n return 1\n return Math.pow(x, y)\ndef sqrt(x):\n return Math.sqrt(x)\n\n########################################\n# Trigonometric functions\n########################################\ndef acos(x): return Math.acos(x)\ndef asin(x): return Math.asin(x)\ndef atan(x): return Math.atan(x)\ndef atan2(y, x): return Math.atan2(y, x)\ndef cos(x): return Math.cos(x)\ndef sin(x): return Math.sin(x)\ndef hypot(x, y): return Math.sqrt(x*x + y*y)\ndef tan(x): return Math.tan(x)\n\n########################################\n# Angular conversion\n########################################\ndef degrees(x): return x*180/pi\ndef radians(x): return x*pi/180\n\n########################################\n# Hyperbolic functions\n########################################\ndef acosh(x):\n # NOTE: will be replaced with official, when it becomes mainstream\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/acosh\n return Math.log(x + Math.sqrt(x*x - 1))\ndef asinh(x):\n # NOTE: will be replaced with official, when it becomes mainstream\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/asinh\n return Math.log(x + Math.sqrt(x*x + 1))\ndef atanh(x):\n # NOTE: will be replaced with official, when it becomes mainstream\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/atanh\n return 0.5 * Math.log((1 + x) / (1 - x))\ndef cosh(x):\n # NOTE: will be replaced with official, when it becomes mainstream\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cosh\n return (Math.exp(x) + Math.exp(-x)) / 2\ndef sinh(x):\n # NOTE: will be replaced with official, when it becomes mainstream\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sinh\n return (Math.exp(x) - Math.exp(-x)) / 2\ndef tanh(x):\n # NOTE: will be replaced with official, when it becomes mainstream\n # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/tanh\n return (Math.exp(x) - Math.exp(-x)) / (Math.exp(x) + Math.exp(-x))\n\n\n\n#import stdlib\n#print(math.ceil(4.2))\n#print(math.floor(4.2))\n#print(math.fabs(-6))\n#print(math.copysign(-5, 7))\n#print(math.factorial(4))\n#print(math.fmod(-1e100, 1e100))\n#\n#d = [0.9999999, 1, 2, 3]\n#print(sum(d), math.fsum(d))\n#print(math.isinf(5), math.isinf(Infinity))\n#print(math.modf(5.5))\n#print(math.trunc(2.6), math.trunc(-2.6))\n#print(math.exp(1e-5), math.expm1(1e-5))\n#print(math.log(10), math.log(10, 1000))\n#print(math.log1p(1e-15), math.log1p(1))\n#print(math.log10(1000), math.log(1000, 10))\n#print(math.pow(1, 0), math.pow(1, NaN), math.pow(0, 0), math.pow(NaN, 0), math.pow(4,3), math.pow(100, -2))\n#print(math.hypot(3,4))\n#print(math.acosh(2), math.asinh(1), math.atanh(0.5), math.cosh(1), math.cosh(-1), math.sinh(1), math.tanh(1))\n","__stdlib__/operator.pyj":"add = __add__ = def(x, y): return x + y\nsub = __sub__ = def(x, y): return x - y\nmul = __mul__ = def(x, y): return x * y\ndiv = __div__ = def(x, y): return x / y\n\nlt = __lt__ = def(x, y): return x < y\nle = __le__ = def(x, y): return x <= y\neq = __eq__ = def(x, y): return x is y\nne = __ne__ = def(x, y): return x is not y\nge = __ge__ = def(x, y): return x >= y\ngt = __gt__ = def(x, y): return x > y\n","__stdlib__/pythonize.pyj":"# vim:fileencoding=utf-8\n# License: BSD Copyright: 2016, Kovid Goyal \n# globals: RS_str\n\ndef strings():\n string_funcs = set((\n 'capitalize strip lstrip rstrip islower isupper isspace lower upper swapcase'\n ' center count endswith startswith find rfind index rindex format join ljust rjust'\n ' partition rpartition replace split rsplit splitlines zfill').split(' '))\n\n if not arguments.length:\n exclude = {'split', 'replace'}\n elif arguments[0]:\n exclude = Array.prototype.slice.call(arguments)\n else:\n exclude = None\n if exclude:\n string_funcs = string_funcs.difference(set(exclude))\n for name in string_funcs:\n String.prototype[name] = RS_str.prototype[name]\n","__stdlib__/random.pyj":"###########################################################\n# RapydScript Standard Library\n# Author: Alexander Tsepkov\n# Copyright 2013 Pyjeon Software LLC\n# License: Apache License 2.0\n# This library is covered under Apache license, so that\n# you can distribute it with your RapydScript applications.\n###########################################################\n\n\n# basic implementation of Python's 'random' library\n\n# JavaScript's Math.random() does not allow seeding its random generator, to bypass that, this module implements its own\n# version that can be seeded. I decided on RC4 algorithm for this.\n\n# please don't mess with this from the outside\n\nRS_seed_state = {\n 'key': [],\n 'key_i': 0,\n 'key_j': 0\n}\n\nRS_get_random_byte = def():\n RS_seed_state.key_i = (RS_seed_state.key_i + 1) % 256\n RS_seed_state.key_j = (RS_seed_state.key_j + RS_seed_state.key[RS_seed_state.key_i]) % 256\n RS_seed_state.key[RS_seed_state.key_i], RS_seed_state.key[RS_seed_state.key_j] = \\\n RS_seed_state.key[RS_seed_state.key_j], RS_seed_state.key[RS_seed_state.key_i]\n return RS_seed_state.key[(RS_seed_state.key[RS_seed_state.key_i] + \\\n RS_seed_state.key[RS_seed_state.key_j]) % 256]\n\ndef seed(x=Date().getTime()):\n RS_seed_state.key_i = RS_seed_state.key_j = 0\n if jstype(x) is 'number':\n x = x.toString()\n elif jstype(x) is not 'string':\n raise TypeError(\"unhashable type: '\" + jstype(x) + \"'\")\n for i in range(256):\n RS_seed_state.key[i] = i\n j = 0\n for i in range(256):\n j = (j + RS_seed_state.key[i] + x.charCodeAt(i % x.length)) % 256\n RS_seed_state.key[i], RS_seed_state.key[j] = RS_seed_state.key[j], RS_seed_state.key[i]\nseed()\n\ndef random():\n n = 0\n m = 1\n for i in range(8):\n n += RS_get_random_byte() * m\n m *= 256\n return v'n / 0x10000000000000000'\n\n# unlike the python version, this DOES build a range object, feel free to reimplement\ndef randrange():\n return choice(range.apply(this, arguments))\n\ndef randint(a, b):\n return int(random()*(b-a+1) + a)\n\ndef uniform(a, b):\n return random()*(b-a) + a\n\ndef choice(seq):\n if seq.length > 0:\n return seq[Math.floor(random()*seq.length)]\n else:\n raise IndexError()\n\n# uses Fisher-Yates algorithm to shuffle an array\ndef shuffle(x, random_f=random):\n for i in range(x.length):\n j = Math.floor(random_f() * (i+1))\n x[i], x[j] = x[j], x[i]\n return x\n\n# similar to shuffle, but only shuffles a subset and creates a copy\ndef sample(population, k):\n x = population.slice()\n for i in range(population.length-1, population.length-k-1, -1):\n j = Math.floor(random() * (i+1))\n x[i], x[j] = x[j], x[i]\n return x.slice(population.length-k)\n\n\n#import stdlib\n#a = range(50)\n#random.seed(5)\n#print(random.choice(a))\n#print(random.shuffle(a))\n#print(random.randrange(10))\n#print(random.randint(1,5))\n#print(random.uniform(1,5))\n#print(random.sample(range(20),5))\n","__stdlib__/re.pyj":'# vim:fileencoding=utf-8\n# License: BSD\n# Copyright: 2015, Kovid Goyal \n# Copyright: 2013, Alexander Tsepkov\n\n# globals: RS_iterator_symbol, RS_list_decorate\n\n# basic implementation of Python\'s \'re\' library\n\nfrom __python__ import bound_methods\n\n# Alias DB from http://www.unicode.org/Public/8.0.0/ucd/NameAliases.txt {{{\n_ALIAS_MAP = {"null":0,"nul":0,"start of heading":1,"soh":1,"start of text":2,"stx":2,"end of text":3,"etx":3,"end of transmission":4,"eot":4,"enquiry":5,"enq":5,"acknowledge":6,"ack":6,"alert":7,"bel":7,"backspace":8,"bs":8,"character tabulation":9,"horizontal tabulation":9,"ht":9,"tab":9,"line feed":10,"new line":10,"end of line":10,"lf":10,"nl":10,"eol":10,"line tabulation":11,"vertical tabulation":11,"vt":11,"form feed":12,"ff":12,"carriage return":13,"cr":13,"shift out":14,"locking-shift one":14,"so":14,"shift in":15,"locking-shift zero":15,"si":15,"data link escape":16,"dle":16,"device control one":17,"dc1":17,"device control two":18,"dc2":18,"device control three":19,"dc3":19,"device control four":20,"dc4":20,"negative acknowledge":21,"nak":21,"synchronous idle":22,"syn":22,"end of transmission block":23,"etb":23,"cancel":24,"can":24,"end of medium":25,"eom":25,"substitute":26,"sub":26,"escape":27,"esc":27,"information separator four":28,"file separator":28,"fs":28,"information separator three":29,"group separator":29,"gs":29,"information separator two":30,"record separator":30,"rs":30,"information separator one":31,"unit separator":31,"us":31,"sp":32,"delete":127,"del":127,"padding character":128,"pad":128,"high octet preset":129,"hop":129,"break permitted here":130,"bph":130,"no break here":131,"nbh":131,"index":132,"ind":132,"next line":133,"nel":133,"start of selected area":134,"ssa":134,"end of selected area":135,"esa":135,"character tabulation set":136,"horizontal tabulation set":136,"hts":136,"character tabulation with justification":137,"horizontal tabulation with justification":137,"htj":137,"line tabulation set":138,"vertical tabulation set":138,"vts":138,"partial line forward":139,"partial line down":139,"pld":139,"partial line backward":140,"partial line up":140,"plu":140,"reverse line feed":141,"reverse index":141,"ri":141,"single shift two":142,"single-shift-2":142,"ss2":142,"single shift three":143,"single-shift-3":143,"ss3":143,"device control string":144,"dcs":144,"private use one":145,"private use-1":145,"pu1":145,"private use two":146,"private use-2":146,"pu2":146,"set transmit state":147,"sts":147,"cancel character":148,"cch":148,"message waiting":149,"mw":149,"start of guarded area":150,"start of protected area":150,"spa":150,"end of guarded area":151,"end of protected area":151,"epa":151,"start of string":152,"sos":152,"single graphic character introducer":153,"sgc":153,"single character introducer":154,"sci":154,"control sequence introducer":155,"csi":155,"string terminator":156,"st":156,"operating system command":157,"osc":157,"privacy message":158,"pm":158,"application program command":159,"apc":159,"nbsp":160,"shy":173,"latin capital letter gha":418,"latin small letter gha":419,"cgj":847,"alm":1564,"syriac sublinear colon skewed left":1801,"kannada letter llla":3294,"lao letter fo fon":3741,"lao letter fo fay":3743,"lao letter ro":3747,"lao letter lo":3749,"tibetan mark bka- shog gi mgo rgyan":4048,"fvs1":6155,"fvs2":6156,"fvs3":6157,"mvs":6158,"zwsp":8203,"zwnj":8204,"zwj":8205,"lrm":8206,"rlm":8207,"lre":8234,"rle":8235,"pdf":8236,"lro":8237,"rlo":8238,"nnbsp":8239,"mmsp":8287,"wj":8288,"lri":8294,"rli":8295,"fsi":8296,"pdi":8297,"weierstrass elliptic function":8472,"micr on us symbol":9288,"micr dash symbol":9289,"leftwards triangle-headed arrow with double vertical stroke":11130,"rightwards triangle-headed arrow with double vertical stroke":11132,"yi syllable iteration mark":40981,"presentation form for vertical right white lenticular bracket":65048,"vs1":65024,"vs2":65025,"vs3":65026,"vs4":65027,"vs5":65028,"vs6":65029,"vs7":65030,"vs8":65031,"vs9":65032,"vs10":65033,"vs11":65034,"vs12":65035,"vs13":65036,"vs14":65037,"vs15":65038,"vs16":65039,"byte order mark":65279,"bom":65279,"zwnbsp":65279,"cuneiform sign nu11 tenu":74452,"cuneiform sign nu11 over nu11 bur over bur":74453,"byzantine musical symbol fthora skliron chroma vasis":118981,"vs17":917760,"vs18":917761,"vs19":917762,"vs20":917763,"vs21":917764,"vs22":917765,"vs23":917766,"vs24":917767,"vs25":917768,"vs26":917769,"vs27":917770,"vs28":917771,"vs29":917772,"vs30":917773,"vs31":917774,"vs32":917775,"vs33":917776,"vs34":917777,"vs35":917778,"vs36":917779,"vs37":917780,"vs38":917781,"vs39":917782,"vs40":917783,"vs41":917784,"vs42":917785,"vs43":917786,"vs44":917787,"vs45":917788,"vs46":917789,"vs47":917790,"vs48":917791,"vs49":917792,"vs50":917793,"vs51":917794,"vs52":917795,"vs53":917796,"vs54":917797,"vs55":917798,"vs56":917799,"vs57":917800,"vs58":917801,"vs59":917802,"vs60":917803,"vs61":917804,"vs62":917805,"vs63":917806,"vs64":917807,"vs65":917808,"vs66":917809,"vs67":917810,"vs68":917811,"vs69":917812,"vs70":917813,"vs71":917814,"vs72":917815,"vs73":917816,"vs74":917817,"vs75":917818,"vs76":917819,"vs77":917820,"vs78":917821,"vs79":917822,"vs80":917823,"vs81":917824,"vs82":917825,"vs83":917826,"vs84":917827,"vs85":917828,"vs86":917829,"vs87":917830,"vs88":917831,"vs89":917832,"vs90":917833,"vs91":917834,"vs92":917835,"vs93":917836,"vs94":917837,"vs95":917838,"vs96":917839,"vs97":917840,"vs98":917841,"vs99":917842,"vs100":917843,"vs101":917844,"vs102":917845,"vs103":917846,"vs104":917847,"vs105":917848,"vs106":917849,"vs107":917850,"vs108":917851,"vs109":917852,"vs110":917853,"vs111":917854,"vs112":917855,"vs113":917856,"vs114":917857,"vs115":917858,"vs116":917859,"vs117":917860,"vs118":917861,"vs119":917862,"vs120":917863,"vs121":917864,"vs122":917865,"vs123":917866,"vs124":917867,"vs125":917868,"vs126":917869,"vs127":917870,"vs128":917871,"vs129":917872,"vs130":917873,"vs131":917874,"vs132":917875,"vs133":917876,"vs134":917877,"vs135":917878,"vs136":917879,"vs137":917880,"vs138":917881,"vs139":917882,"vs140":917883,"vs141":917884,"vs142":917885,"vs143":917886,"vs144":917887,"vs145":917888,"vs146":917889,"vs147":917890,"vs148":917891,"vs149":917892,"vs150":917893,"vs151":917894,"vs152":917895,"vs153":917896,"vs154":917897,"vs155":917898,"vs156":917899,"vs157":917900,"vs158":917901,"vs159":917902,"vs160":917903,"vs161":917904,"vs162":917905,"vs163":917906,"vs164":917907,"vs165":917908,"vs166":917909,"vs167":917910,"vs168":917911,"vs169":917912,"vs170":917913,"vs171":917914,"vs172":917915,"vs173":917916,"vs174":917917,"vs175":917918,"vs176":917919,"vs177":917920,"vs178":917921,"vs179":917922,"vs180":917923,"vs181":917924,"vs182":917925,"vs183":917926,"vs184":917927,"vs185":917928,"vs186":917929,"vs187":917930,"vs188":917931,"vs189":917932,"vs190":917933,"vs191":917934,"vs192":917935,"vs193":917936,"vs194":917937,"vs195":917938,"vs196":917939,"vs197":917940,"vs198":917941,"vs199":917942,"vs200":917943,"vs201":917944,"vs202":917945,"vs203":917946,"vs204":917947,"vs205":917948,"vs206":917949,"vs207":917950,"vs208":917951,"vs209":917952,"vs210":917953,"vs211":917954,"vs212":917955,"vs213":917956,"vs214":917957,"vs215":917958,"vs216":917959,"vs217":917960,"vs218":917961,"vs219":917962,"vs220":917963,"vs221":917964,"vs222":917965,"vs223":917966,"vs224":917967,"vs225":917968,"vs226":917969,"vs227":917970,"vs228":917971,"vs229":917972,"vs230":917973,"vs231":917974,"vs232":917975,"vs233":917976,"vs234":917977,"vs235":917978,"vs236":917979,"vs237":917980,"vs238":917981,"vs239":917982,"vs240":917983,"vs241":917984,"vs242":917985,"vs243":917986,"vs244":917987,"vs245":917988,"vs246":917989,"vs247":917990,"vs248":917991,"vs249":917992,"vs250":917993,"vs251":917994,"vs252":917995,"vs253":917996,"vs254":917997,"vs255":917998,"vs256":917999}\n# }}}\n\n_ASCII_CONTROL_CHARS = {\'a\':7, \'b\':8, \'f\': 12, \'n\': 10, \'r\': 13, \'t\': 9, \'v\': 11}\n_HEX_PAT = /^[a-fA-F0-9]/\n_NUM_PAT = /^[0-9]/\n_GROUP_PAT = /<([^>]+)>/\n_NAME_PAT = /^[a-zA-Z ]/\n\nI = IGNORECASE = 2\nL = LOCALE = 4\nM = MULTILINE = 8\nD = DOTALL = 16\nU = UNICODE = 32\nX = VERBOSE = 64\nDEBUG = 128\nA = ASCII = 256\n\nsupports_unicode = RegExp.prototype.unicode is not undefined\n\n_RE_ESCAPE = /[-\\/\\\\^$*+?.()|[\\]{}]/g\n\n_re_cache_map = {}\n_re_cache_items = v\'[]\'\n\nerror = SyntaxError # This is the error JS throws for invalid regexps\nhas_prop = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty)\n\ndef _expand(groups, repl, group_name_map):\n i = 0\n\n def next():\n nonlocal i\n return v\'repl[i++]\'\n\n def peek():\n return repl[i]\n\n def read_digits(count, pat, base, maxval, prefix):\n ans = prefix or \'\'\n greedy = count is Number.MAX_VALUE\n while count > 0:\n count -= 1\n if not pat.test(peek()):\n if greedy:\n break\n return ans\n ans += next()\n nval = parseInt(ans, base)\n if nval > maxval:\n return ans\n return nval\n\n def read_escape_sequence():\n nonlocal i\n q = next()\n if not q or q is \'\\\\\':\n return \'\\\\\'\n if \'"\\\'\'.indexOf(q) is not -1:\n return q\n if _ASCII_CONTROL_CHARS[q]:\n return String.fromCharCode(_ASCII_CONTROL_CHARS[q])\n if \'0\' <= q <= \'9\':\n ans = read_digits(Number.MAX_VALUE, _NUM_PAT, 10, Number.MAX_VALUE, q)\n if jstype(ans) is \'number\':\n return groups[ans] or \'\'\n return \'\\\\\' + ans\n if q is \'g\':\n m = _GROUP_PAT.exec(repl[i:])\n if m is not None:\n i += m[0].length\n gn = m[1]\n if isNaN(parseInt(gn, 10)):\n if not has_prop(group_name_map, gn):\n return \'\'\n gn = group_name_map[gn][-1]\n return groups[gn] or \'\'\n if q is \'x\':\n code = read_digits(2, _HEX_PAT, 16, 0x10FFFF)\n if jstype(code) is \'number\':\n return String.fromCharCode(code)\n return \'\\\\x\' + code\n if q is \'u\':\n code = read_digits(4, _HEX_PAT, 16, 0x10FFFF)\n if jstype(code) is \'number\':\n return String.fromCharCode(code)\n return \'\\\\u\' + code\n if q is \'U\':\n code = read_digits(8, _HEX_PAT, 16, 0x10FFFF)\n if jstype(code) is \'number\':\n if code <= 0xFFFF:\n return String.fromCharCode(code)\n code -= 0x10000\n return String.fromCharCode(0xD800+(code>>10), 0xDC00+(code&0x3FF))\n return \'\\\\U\' + code\n if q is \'N\' and peek() is \'{\':\n next()\n name = \'\'\n while _NAME_PAT.test(peek()):\n name += next()\n if peek() is not \'}\':\n return \'\\\\N{\' + name\n next()\n key = (name or \'\').toLowerCase()\n if not name or not has_prop(_ALIAS_MAP, key):\n return \'\\\\N{\' + name + \'}\'\n code = _ALIAS_MAP[key]\n if code <= 0xFFFF:\n return String.fromCharCode(code)\n code -= 0x10000\n return String.fromCharCode(0xD800+(code>>10), 0xDC00+(code&0x3FF))\n\n return \'\\\\\' + q\n\n ans = ch = \'\'\n while True:\n ch = next()\n if ch is \'\\\\\':\n ans += read_escape_sequence()\n elif not ch:\n break\n else:\n ans += ch\n return ans\n\ndef transform_regex(source, flags):\n pos = 0\n previous_backslash = in_class = False\n ans = \'\'\n group_map = {}\n flags = flags or 0\n group_count = 0\n\n while pos < source.length:\n ch = v\'source[pos++]\'\n if previous_backslash:\n ans += \'\\\\\' + ch\n previous_backslash = False\n continue\n\n if in_class:\n if ch is \']\':\n in_class = False\n ans += ch\n continue\n\n if ch is \'\\\\\':\n previous_backslash = True\n continue\n\n if ch is \'[\':\n in_class = True\n if source[pos] is \']\': # in python the empty set is not allowed, instead []] is the same as [\\]]\n pos += 1\n ch = r\'[\\]\'\n elif ch is \'(\':\n if source[pos] is \'?\':\n extension = source[pos + 1]\n if extension is \'#\':\n close = source.indexOf(\')\', pos + 1)\n if close is -1:\n raise ValueError(\'Expecting a closing )\')\n pos = close + 1\n continue\n if \'aiLmsux\'.indexOf(extension) is not -1:\n flag_map = {\'a\':ASCII, \'i\':IGNORECASE, \'L\':LOCALE, \'m\':MULTILINE, \'s\':DOTALL, \'u\':UNICODE, \'x\':VERBOSE}\n close = source.indexOf(\')\', pos + 1)\n if close is -1:\n raise SyntaxError(\'Expecting a closing )\')\n flgs = source[pos+1:close]\n for v\'var i = 0; i < flgs.length; i++\':\n q = flgs[i] # noqa:undef\n if not has_prop(flag_map, q):\n raise SyntaxError(\'Invalid flag: \' + q)\n flags |= flag_map[q]\n pos = close + 1\n continue\n if extension is \'(\':\n raise SyntaxError(\'Group existence assertions are not supported in JavaScript\')\n if extension is \'P\':\n pos += 2\n q = source[pos]\n if q is \'<\':\n close = source.indexOf(\'>\', pos)\n if close is -1:\n raise SyntaxError(\'Named group not closed, expecting >\')\n name = source[pos+1:close]\n if not has_prop(group_map, name):\n group_map[name] = v\'[]\'\n group_map[name].push(v\'++group_count\')\n pos = close + 1\n elif q is \'=\':\n close = source.indexOf(\')\', pos)\n if close is -1:\n raise SyntaxError(\'Named group back-reference not closed, expecting a )\')\n name = source[pos+1:close]\n if not isNaN(parseInt(name, 10)):\n ans += \'\\\\\' + name\n else:\n if not has_prop(group_map, name):\n raise SyntaxError(\'Invalid back-reference. The named group: \' + name + \' has not yet been defined.\')\n ans += \'\\\\\' + group_map[name][-1]\n pos = close + 1\n continue\n else:\n raise SyntaxError(\'Expecting < or = after (?P\')\n else:\n group_count += 1\n elif ch is \'.\' and (flags & DOTALL):\n ans += r\'[\\s\\S]\' # JavaScript has no DOTALL\n continue\n\n ans += ch\n\n return ans, flags, group_map\n\nclass MatchObject:\n\n def __init__(self, regex, match, pos, endpos):\n self.re = regex\n self.string = match.input\n self._start_pos = match.index\n self._groups = match\n self.pos, self.endpos = pos, endpos\n\n def _compute_extents(self):\n # compute start/end for each group\n match = self._groups\n self._start = v\'Array(match.length)\'\n self._end = v\'Array(match.length)\'\n self._start[0] = self._start_pos\n self._end[0] = self._start_pos + match[0].length\n offset = self._start_pos\n extent = match[0]\n loc = 0\n for v\'var i = 1; i < match.length; i++\':\n g = match[i]\n loc = extent.indexOf(g, loc)\n if loc is -1:\n self._start[i] = self._start[i-1]\n self._end[i] = self._end[i-1]\n else:\n self._start[i] = offset + loc\n loc += g.length\n self._end[i] = offset + loc # noqa:undef\n\n def groups(self, defval=None):\n ans = v\'[]\'\n for v\'var i = 1; i < self._groups.length; i++\':\n val = self._groups[i] # noqa:undef\n if val is undefined:\n val = defval\n ans.push(val)\n return ans\n\n def _group_number(self, g):\n if jstype(g) is \'number\':\n return g\n if has_prop(self.re.group_name_map, g):\n return self.re.group_name_map[g][-1]\n return g\n\n def _group_val(self, q, defval):\n val = undefined\n if jstype(q) is \'number\' and -1 < q < self._groups.length:\n val = self._groups[q]\n else:\n if has_prop(self.re.group_name_map, q):\n val = self._groups[self.re.group_name_map[q][-1]]\n if val is undefined:\n val = defval\n return val\n\n def group(self):\n if arguments.length is 0:\n return self._groups[0]\n ans = v\'[]\'\n for v\'var i = 0; i < arguments.length; i++\':\n q = arguments[i] # noqa:undef\n ans.push(self._group_val(q, None))\n return ans[0] if ans.length is 1 else ans\n\n def start(self, g):\n if self._start is undefined:\n self._compute_extents()\n val = self._start[self._group_number(g or 0)]\n if val is undefined:\n val = -1\n return val\n\n def end(self, g):\n if self._end is undefined:\n self._compute_extents()\n val = self._end[self._group_number(g or 0)]\n if val is undefined:\n val = -1\n return val\n\n def span(self, g):\n return [self.start(g), self.end(g)]\n\n def expand(self, repl):\n return _expand(repl, this._groups, this.re.group_name_map)\n\n def groupdict(self, defval=None):\n gnm = self.re.group_name_map\n names = Object.keys(gnm)\n ans = {}\n for v"var i = 0; i < names.length; i++":\n name = names[i] # noqa:undef\n if has_prop(gnm, name):\n val = self._groups[gnm[name][-1]]\n if val is undefined:\n val = defval\n ans[name] = val\n return ans\n\n def captures(self, group_name):\n ans = []\n if not has_prop(self.re.group_name_map, group_name):\n return ans\n groups = self.re.group_name_map[group_name]\n for v\'var i = 0; i < groups.length; i++\':\n val = self._groups[groups[i]] # noqa:undef\n if val is not undefined:\n ans.push(val)\n return ans\n\n def capturesdict(self):\n gnm = self.re.group_name_map\n names = Object.keys(gnm)\n ans = {}\n for v\'var i = 0; i < names.length; i++\':\n name = names[i] # noqa:undef\n ans[name] = self.captures(name)\n return ans\n\nclass RegexObject:\n\n def __init__(self, pattern, flags):\n self.pattern = pattern.source if isinstance(pattern, RegExp) else pattern\n self.js_pattern, self.flags, self.group_name_map = transform_regex(self.pattern, flags)\n\n modifiers = \'\'\n if self.flags & IGNORECASE: modifiers += \'i\'\n if self.flags & MULTILINE: modifiers += \'m\'\n if not (self.flags & ASCII) and supports_unicode:\n modifiers += \'u\'\n self._modifiers = modifiers + \'g\'\n self._pattern = RegExp(self.js_pattern, self._modifiers)\n\n def _do_search(self, pat, string, pos, endpos):\n pat.lastIndex = 0\n if endpos is not None:\n string = string[:endpos]\n while True:\n n = pat.exec(string)\n if n is None:\n return None\n if n.index >= pos:\n return MatchObject(self, n, pos, endpos)\n\n def search(self, string, pos=0, endpos=None):\n return self._do_search(self._pattern, string, pos, endpos)\n\n def match(self, string, pos=0, endpos=None):\n return self._do_search(RegExp(\'^\' + self.js_pattern, self._modifiers), string, pos, endpos)\n\n def split(self, string, maxsplit=0):\n self._pattern.lastIndex = 0\n return string.split(self._pattern, maxsplit or undefined)\n\n def findall(self, string):\n self._pattern.lastIndex = 0\n return RS_list_decorate(string.match(self._pattern) or v\'[]\')\n\n def finditer(self, string):\n # We have to copy pat since lastIndex is mutable\n pat = RegExp(this._pattern.source, this._modifiers) # noqa: unused-local\n ans = v"{\'_string\':string, \'_r\':pat, \'_self\':self}"\n ans[RS_iterator_symbol] = def():\n return this\n ans[\'next\'] = def():\n m = this._r.exec(this._string)\n if m is None:\n return v"{\'done\':true}"\n return v"{\'done\':false, \'value\':new MatchObject(this._self, m, 0, null)}"\n return ans\n\n def subn(self, repl, string, count=0):\n expand = _expand\n if jstype(repl) is \'function\':\n expand = def(m, repl, gnm): return \'\' + repl(MatchObject(self, m, 0, None))\n this._pattern.lastIndex = 0\n num = 0\n matches = v\'[]\'\n\n while count < 1 or num < count:\n m = this._pattern.exec(string)\n if m is None:\n break\n matches.push(m)\n num += 1\n\n for v\'var i = matches.length - 1; i > -1; i--\':\n m = matches[i] # noqa:undef\n start = m.index\n end = start + m[0].length\n string = string[:start] + expand(m, repl, self.group_name_map) + string[end:]\n return string, matches.length\n\n def sub(self, repl, string, count=0):\n return self.subn(repl, string, count)[0]\n\ndef _get_from_cache(pattern, flags):\n if isinstance(pattern, RegExp):\n pattern = pattern.source\n key = JSON.stringify(v\'[pattern, flags]\')\n if has_prop(_re_cache_map, key):\n return _re_cache_map[key]\n if _re_cache_items.length >= 100:\n v\'delete _re_cache_map[_re_cache_items.shift()]\'\n ans = RegexObject(pattern, flags)\n _re_cache_map[key] = ans\n _re_cache_items.push(key)\n return ans\n\ndef compile(pattern, flags=0):\n return _get_from_cache(pattern, flags)\n\ndef search(pattern, string, flags=0):\n return _get_from_cache(pattern, flags).search(string)\n\ndef match(pattern, string, flags=0):\n return _get_from_cache(pattern, flags).match(string)\n\ndef split(pattern, string, maxsplit=0, flags=0):\n return _get_from_cache(pattern, flags).split(string)\n\ndef findall(pattern, string, flags=0):\n return _get_from_cache(pattern, flags).findall(string)\n\ndef finditer(pattern, string, flags=0):\n return _get_from_cache(pattern, flags).finditer(string)\n\ndef sub(pattern, repl, string, count=0, flags=0):\n return _get_from_cache(pattern, flags).sub(repl, string, count)\n\ndef subn(pattern, repl, string, count=0, flags=0):\n return _get_from_cache(pattern, flags).subn(repl, string, count)\n\ndef escape(string):\n return string.replace(_RE_ESCAPE, \'\\\\$&\')\n\ndef purge():\n nonlocal _re_cache_map, _re_cache_items\n _re_cache_map = {}\n _re_cache_items = v\'[]\'\n',"__stdlib__/traceback.pyj":"# vim:fileencoding=utf-8\n# License: BSD Copyright: 2016, Kovid Goyal \n# globals: RS_str, RS_last_exception\n\n\ndef _get_internal_traceback(err):\n if isinstance(err, Exception) and err.stack:\n lines = RS_str.splitlines(err.stack)\n final_lines = v'[]'\n found_sentinel = False\n for i, line in enumerate(lines):\n sline = RS_str.strip(line)\n if i is 0:\n final_lines.push(line)\n continue\n if found_sentinel:\n final_lines.push(line)\n continue\n # These two conditions work on desktop Chrome and Firefox to identify the correct\n # line in the traceback.\n if sline.startsWith('at new ' + err.name) or sline.startsWith(err.name + '@'):\n found_sentinel = True\n return final_lines.join('\\n')\n return err and err.stack\n\ndef format_exception(exc, limit):\n if jstype(exc) is 'undefined':\n exc = RS_last_exception\n if not isinstance(exc, Error):\n if exc and exc.toString:\n return [exc.toString()]\n return []\n tb = _get_internal_traceback(exc)\n if tb:\n lines = RS_str.splitlines(tb)\n e = lines[0]\n lines = lines[1:]\n if limit:\n lines = lines[:limit+1] if limit > 0 else lines[limit:]\n lines.reverse()\n lines.push(e)\n lines.insert(0, 'Traceback (most recent call last):')\n return [l+'\\n' for l in lines]\n return [exc.toString()]\n\ndef format_exc(limit):\n return format_exception(RS_last_exception, limit).join('')\n\ndef print_exc(limit):\n print(format_exc(limit))\n\ndef format_stack(limit):\n stack = Error().stack\n if not stack:\n return []\n lines = str.splitlines(stack)[2:]\n lines.reverse()\n if limit:\n lines = lines[:limit+1] if limit > 0 else lines[limit:]\n return [l + '\\n' for l in lines]\n\ndef print_stack(limit):\n print(format_stack(limit).join(''))\n","__stdlib__/uuid.pyj":"# vim:fileencoding=utf-8\n# License: BSD Copyright: 2017, Kovid Goyal \n# globals: crypto\nfrom __python__ import hash_literals\n\nfrom encodings import hexlify, urlsafe_b64decode, urlsafe_b64encode\n\nRFC_4122 = 1\n\nif jstype(crypto) is 'object' and crypto.getRandomValues:\n random_bytes = def (num):\n ans = Uint8Array(num or 16)\n crypto.getRandomValues(ans)\n return ans\nelse:\n random_bytes = def (num):\n ans = Uint8Array(num or 16)\n for i in range(ans.length):\n ans[i] = Math.floor(Math.random() * 256)\n return ans\n\n\ndef uuid4_bytes():\n data = random_bytes()\n data[6] = 0b01000000 | (data[6] & 0b1111)\n data[8] = (((data[8] >> 4) & 0b11 | 0b1000) << 4) | (data[8] & 0b1111)\n return data\n\n\ndef as_str():\n h = this.hex\n return h[:8] + '-' + h[8:12] + '-' + h[12:16] + '-' + h[16:20] + '-' + h[20:]\n\n\ndef uuid4():\n b = uuid4_bytes()\n return {\n 'hex': hexlify(b),\n 'bytes': b,\n 'variant': RFC_4122,\n 'version': 4,\n '__str__': as_str,\n 'toString': as_str,\n }\n\n\ndef num_to_string(numbers, alphabet, pad_to_length):\n ans = v'[]'\n alphabet_len = alphabet.length\n numbers = Array.prototype.slice.call(numbers)\n for v'var i = 0; i < numbers.length - 1; i++':\n x = divmod(numbers[i], alphabet_len)\n numbers[i] = x[0]\n numbers[i+1] += x[1]\n for v'var i = 0; i < numbers.length; i++':\n number = numbers[i]\n while number:\n x = divmod(number, alphabet_len)\n number = x[0]\n ans.push(alphabet[x[1]])\n if pad_to_length and pad_to_length > ans.length:\n ans.push(alphabet[0].repeat(pad_to_length - ans.length))\n return ans.join('')\n\n\ndef short_uuid():\n # A totally random uuid encoded using only URL and filename safe characters\n return urlsafe_b64encode(random_bytes(), '')\n\n\ndef short_uuid4():\n # A uuid4 encoded using only URL and filename safe characters\n return urlsafe_b64encode(uuid4_bytes(), '')\n\n\ndef decode_short_uuid(val):\n return urlsafe_b64decode(val + '==')\n"};var namespace={},jsSHA={};var write_cache={};var builtin_modules={crypto:{createHash:function create_hash(){var ans=new jsSHA.jsSHA("SHA-1","TEXT");ans.digest=function hex_digest(){return ans.getHash("HEX")};return ans}},vm:{createContext:function create_context(ctx){var iframe=document.createElement("iframe");iframe.style.display="none";document.body.appendChild(iframe);var win=iframe.contentWindow;if(!ctx)ctx={};if(!ctx.sha1sum)ctx.sha1sum=sha1sum;if(!ctx.require)ctx.require=require;Object.keys(ctx).forEach(function(k){win[k]=ctx[k]});return win},runInContext:function run_in_context(code,ctx){return ctx.eval(code)},runInThisContext:eval},path:{join:function path_join(){return Array.prototype.slice.call(arguments).join("/")},dirname:function path_dirname(path){return path.split("/").slice(0,-1).join("/")}},inspect:function inspect(x){return x.toString()},fs:{readFileSync:function readfile(name){if(namespace.virtual_file_system&&namespace.virtual_file_system.read_file_sync){data=namespace.virtual_file_system.read_file_sync(name);if(data!==null)return data}var data=namespace.file_data[name];if(data)return data;data=write_cache[name];if(data)return data;var err=Error();err.code="ENOENT";throw err},writeFileSync:function writefile(name,data){if(namespace.virtual_file_system&&namespace.virtual_file_system.write_file_sync){namespace.virtual_file_system.write_file_sync(name,data)}else write_cache[name]=data}}};function require(name){return builtin_modules[name]||{}}(function(){(function(G){function x(b,a,d){var c=0,e=[],h=0,l=!1,f=[],g=[],q=!1;d=d||{};var r=d.encoding||"UTF8";var k=d.numRounds||1;if(k!==parseInt(k,10)||1>k)throw Error("numRounds must a integer >= 1");if("SHA-1"===b){var n=512;var y=z;var m=H;var p=160;var t=function(c){return c.slice()}}else throw Error("Chosen SHA variant is not supported");var v=A(a,r);var u=w(b);this.setHMACKey=function(e,a,d){if(!0===l)throw Error("HMAC key already set");if(!0===q)throw Error("Cannot set HMAC key after calling update");r=(d||{}).encoding||"UTF8";a=A(a,r)(e);e=a.binLen;a=a.value;var h=n>>>3;d=h/4-1;if(he/8){for(;a.length<=d;)a.push(0);a[d]&=4294967040}for(e=0;e<=d;e+=1)f[e]=a[e]^909522486,g[e]=a[e]^1549556828;u=y(f,u);c=n;l=!0};this.update=function(a){var d,b=0,l=n>>>5;var f=v(a,e,h);a=f.binLen;var g=f.value;f=a>>>5;for(d=0;d>>5);h=a%n;q=!0};this.getHash=function(a,d){if(!0===l)throw Error("Cannot call getHash after setting HMAC key");var f=B(d);switch(a){case"HEX":a=function(a){return C(a,p,f)};break;case"B64":a=function(a){return D(a,p,f)};break;case"BYTES":a=function(a){return E(a,p)};break;case"ARRAYBUFFER":try{d=new ArrayBuffer(0)}catch(I){throw Error("ARRAYBUFFER not supported by this environment")}a=function(a){return F(a,p)};break;default:throw Error("format must be HEX, B64, BYTES, or ARRAYBUFFER")}var g=m(e.slice(),h,c,t(u),p);for(d=1;d>>2]>>>8*(3+e%4*-1);c+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15)}return d.outputUpper?c.toUpperCase():c}function D(b,a,d){var c="",e=a/8,h;for(h=0;h>>2]:0;var f=h+2>>2]:0;f=(b[h>>>2]>>>8*(3+h%4*-1)&255)<<16|(l>>>8*(3+(h+1)%4*-1)&255)<<8|f>>>8*(3+(h+2)%4*-1)&255;for(l=0;4>l;l+=1)8*h+6*l<=a?c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(f>>>6*(3-l)&63):c+=d.b64Pad}return c}function E(b,a){var d="";a/=8;var c;for(c=0;c>>2]>>>8*(3+c%4*-1)&255;d+=String.fromCharCode(e)}return d}function F(b,a){a/=8;var d,c=new ArrayBuffer(a);var e=new Uint8Array(c);for(d=0;d>>2]>>>8*(3+d%4*-1)&255;return c}function B(b){var a={outputUpper:!1,b64Pad:"=",shakeLen:-1};b=b||{};a.outputUpper=b.outputUpper||!1;!0===b.hasOwnProperty("b64Pad")&&(a.b64Pad=b.b64Pad);b.hasOwnProperty("shakeLen");if("boolean"!==typeof a.outputUpper)throw Error("Invalid outputUpper formatting option");if("string"!==typeof a.b64Pad)throw Error("Invalid b64Pad formatting option");return a}function A(b,a){switch(a){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(b){case"HEX":b=function(a,c,e){var d=a.length,b,f;if(d%2)throw Error("String of HEX type must be in byte increments");c=c||[0];e=e||0;var g=e>>>3;for(b=0;b>>1)+g;for(f=r>>>2;c.length<=f;)c.push(0);c[f]|=q<<8*(3+r%4*-1)}return{value:c,binLen:4*d+e}};break;case"TEXT":b=function(d,c,e){var b=0,l,f,g;c=c||[0];e=e||0;var q=e>>>3;if("UTF8"===a){var r=3;for(l=0;lk?n.push(k):2048>k?(n.push(192|k>>>6),n.push(128|k&63)):55296>k||57344<=k?n.push(224|k>>>12,128|k>>>6&63,128|k&63):(l+=1,k=65536+((k&1023)<<10|d.charCodeAt(l)&1023),n.push(240|k>>>18,128|k>>>12&63,128|k>>>6&63,128|k&63));for(f=0;f>>2;c.length<=g;)c.push(0);c[g]|=n[f]<<8*(r+m%4*-1);b+=1}}}else if("UTF16BE"===a||"UTF16LE"===a)for(r=2,n="UTF16LE"===a&&!0||"UTF16LE"!==a&&!1,l=0;l>>8);m=b+q;for(g=m>>>2;c.length<=g;)c.push(0);c[g]|=k<<8*(r+m%4*-1);b+=2}return{value:c,binLen:8*b+e}};break;case"B64":b=function(a,c,e){var d=0,b,f;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw Error("Invalid character in base-64 string");var g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g=0){lines[lineno]="";break}else{lines[lineno]="";lineno++}}continue}}line=line.replace(/\s+$/g,"");if(lang=="vpython"&&line.slice(-1)=="\\"){cline=line.slice(0,-1);cindent=indent;continue}m=line.match(print_optionspatt);if(m)line=line.replace(/delete/,"remove");if(lang=="vpython"&&line[0]=="@"){var nextline=lines[lineno+1];m=nextline.match(getline);if(m[2].slice(0,3)=="def"||m[2].slice(0,6)=="module"){decoration=line;indent=m[1];line=m[2];lineno++}else{continue}}if(line.length===0)continue;prebraces=braces;if(lang=="vpython"){if(classindent===indent.length)classindent=-1;if(line.match(classpatt))classindent=indent.length}else{line=" "+line}var w=line.split(" ");if(lang=="vpython"&&w.indexOf("import")>-1){if(w.indexOf("random")>-1){newprogram+=" "+indent+line+"\n";continue}if(VPython_import===null)VPython_names=[];if(w[1]=="__future__")continue;if(w[1]=="visual.factorial")continue;if(w[0]=="from"&&w[2]=="import"&&w.length>=4){if(w[1]=="visual.graph"){if(w[3]=="*")continue;return'ERROR: Currently only "from visual.graph import *" is supported, line '+(lineno+2)+": "+lines[lineno]}if(!(w[1]=="vpython"||w[1]=="visual"||w[1]=="vis")){throw new Error("Line "+(lineno+1)+": cannot import from "+w[1])}if(VPython_import===null){if(w[3]=="*")continue;VPython_import=w[1];for(var j=3;j0&&w[j]!=","){if(w[j].slice(-1)==",")w[j]=w[j].slice(0,-1);if(w[j]==" "||w[j]=="("||w[j]==")"||w[j][0]=="("||w[j][-1]==")")continue;VPython_names.push(w[j])}}if(VPython_names.indexOf("canvas")==-1)VPython_names.push("canvas")}continue}else if(w[0]=="import"&&w.length==2){if(w[1]=="visual.graph")return'ERROR: Currently only "from visual.graph import *" is supported, line '+(lineno+1)+": "+lines[lineno];if(!(w[1]=="vpython"||w[1]=="visual"||w[1]=="vis"))return"ERROR: Cannot import from "+w[1]+", line "+(lineno+1)+": "+lines[lineno];if(VPython_import===null){VPython_import=w[1]}continue}else if(w[0]=="import"){if(w[1]=="vpython"||w[1]=="visual"||w[1]=="vis"){if(w.length==4&&w[2]=="as"){VPython_import=w[3];continue}else return"ERROR: improper import statement, line "+(lineno+1)+": "+lines[lineno]}else{return"ERROR: Cannot import from "+w[1]+", line "+(lineno+1)+": "+lines[lineno]}}}singlequote=false;doublequote=false;triplequote=false;backquote=false;var backslash=false;var string_bounds=[];var previouscontinuedline=continuedline;var processedtriplequote=false;var fstring=false;for(var i=0;i0&&line[i-1]=="\\")break;if(parens===0)lastleftparens=lineno;parens++;break;case")":if(i>0&&line[i-1]=="\\")break;parens--;if(indef&&parens==0)indef=false;break;case"[":if(i>0&&line[i-1]=="\\")break;if(brackets===0)lastleftbracket=lineno;brackets++;break;case"]":if(i>0&&line[i-1]=="\\")break;brackets--;break;case"{":if(i>0&&line[i-1]=="\\")break;if(braces===0)lastleftbrace=lineno;braces++;break;case"}":if(i>0&&line[i-1]=="\\")break;braces--;break}if(char=="\\"){if(i==line.length-1||line[i+1]==" "||line[i+1]=="#")line=line.slice(0,i);backslash=true;break}}continuedline=!indef&&(backslash||parens>0||brackets>0||braces>0);if(!previousquote){if(lang=="vpython"){var m=pickpatt.exec(line+" ");if(m){if(m[2]!="("&&m[2].search(/\w/)!=0){var i=m.index;line=line.slice(0,i)+".pick()"+line.slice(i+5)}}}}if(line.search("input")>=0||line.search("winput")>=0){newprogram+=" "+indent+"sleep(0.2)\n"}function instring(n){for(var sb of string_bounds){if(n>=sb[0]&&n<=sb[1]&&!sb[2])return true}return false}if(lang=="vpython"){c="";if(indent.length0){prepend=" "+c+" "+indent+decoration+"\n";prepend=" "+indent}else{prepend=" "+c+" "+indent}}start=0;while(true){var m=line.slice(start).match(awaitpatt);if(m!==null){start+=m.index;var ins=instring(start);if(ins){line=line.slice(0,start+1+m[1].length)+string_insert+line.slice(start+1+m[1].length);start+=string_insert.length}start+=m[1].length+1}else break}var start=0;var inst,cls,m1=null,m2=null,m3=null,m4=null,m5=null,m6=null,m7=null,m8=null;var declaration=false;var pre="";var newline="";const methodassignpatt=new RegExp("^(\\w+)\\s*=\\s*(\\w+)\\.(\\w+)$");const assignpatt=new RegExp("^(\\w+)\\s*=\\s*(\\w+)\\s*");m1=line.match(defpatt);if(m1===null)m2=line.match(classpatt);if(m2===null)m3=line.match(methodassignpatt);if(m3===null)m4=line.match(assignpatt);if(m1!==null){var ns=start+m1.index+m1[1].length+1;if(instring(ns)){line=line.slice(0,ns)+string_insert+line.slice(ns)}else{if(indent.length===0||classindent===-1)fcts.push(m1[1]);else if(classindent>=0&&indent.length>classindent)classmethods.push(m1[1])}declaration=true}else if(m2!==null){classes.push(m2[1]);declaration=true}else if(m3!==null){if(classinstances.indexOf(m3[2])>=0&&classmethods.indexOf(m3[3])>=0)classmethods.push(m3[1])}else if(m4!==null){var p=m4[1];var f=m4[2];if(line[m4[0].length]=="("){var end=findrightparen(line.slice(m4[0].length));if(end!==null&&m4[0].length+end+1==line.length){if(classes.indexOf(f)>=0)classinstances.push(p);else if(classmethods.indexOf(f)>=0)classmethods.push(p);else if(fcts.indexOf(f)>=0)fcts.push(p)}}}start=0;const bindmethodpatt=new RegExp("(\\w+)\\.(\\w+)\\s*");while(true){m=line.slice(start).match(bindmethodpatt);if(m===null)break;if(classinstances.indexOf(m[1])>=0&&classmethods.indexOf(m[2])>=0&&(start+m.index+m[0].length>=line.length||line[start+m.index+m[0].length]!="(")){line=line.slice(0,start+m.index)+line.slice(start+m.index).replace(m[2],m[2]+".bind("+m[1]+")");start+=m.index+m[0].length+m[1].length+7}else start+=m.index+m[0].length}if(!declaration){const leftpatt=new RegExp("^(\\w+)\\s*=\\s*");var left=null,right=line;m=line.match(leftpatt);if(m!==null){left=m[1];right=line.slice(m[0].length)}start=0;while(true){var n=0;m=line.slice(start).match(instpatt);if(m===null){if(pre.length>0)newline+=line.slice(start);break}cls=m[1];var leftparen=start+m.index+m[1].length;if(classes.indexOf(cls)>=0){var p=1;var i=leftparen+1;while(true){var char=line[i];if(char=="(")p+=1;else if(char==")"){p-=1;if(p===0)break}i+=1;if(i>line.length)break}if(i>line.length)break;n+=1;pre+="_GS_"+n+" = "+cls+"(); _GS_"+n+".__init__"+line.slice(leftparen,i+1)+"; ";newline+=line.slice(start,leftparen-m[1].length)+"_GS_"+n;start=i+1}else{newline+=line.slice(start,leftparen);start=leftparen}}}if(pre.length>0)line=pre+newline;newprogram+=prepend+line+"\n"}lastindent=indent;if(parens<0)return"ERROR: Too many right parentheses, line "+(lineno+1)+": "+lines[lineno];if(brackets<0)return"ERROR: Too many right brackets, line "+(lineno+1)+": "+lines[lineno];if(braces<0)return"ERROR: Too many right braces, line "+(lineno+1)+": "+lines[lineno]}if(parens>0)return"ERROR: Missing right parenthesis, see line "+(lastleftparens+2)+": "+lines[lastleftparens];else if(brackets>0)return"ERROR: Missing right bracket, see line "+(lastleftbracket+2)+": "+lines[lastleftbracket];else if(braces>0)return"ERROR: Missing right brace, see line "+(lastleftbrace+2)+": "+lines[lastleftbrace];return newprogram}var linenopatt=/"(\d*)"/;var RS_compiler;function compile_rapydscript(rs_input){if(rs_input.slice(0,7)=="ERROR: "){throw new Error(rs_input.slice(7))}else{if(RS_compiler===undefined)RS_compiler=RapydScript.create_embedded_compiler();rs_input+="\n";try{var output=RS_compiler.compile(rs_input,{js_version:6});return output.toString()}catch(err){if(err.line===undefined){throw new Error(err.message)}else{var lines=rs_input.split("\n");var L=lines[err.line];var m=L.match(linenopatt);if(m!==null){throw new Error(err.message+"; line "+m[1]+": "+lines[err.line+1])}else{throw new Error(err.message+": "+lines[err.line])}}}}}var vp_primitives=["box","sphere","simple_sphere","cylinder","pyramid","cone","helix","ellipsoid","ring","arrow","compound"];var vp_other=["canvas","vec","vector","rate","sleep","update","color","extrusion","paths","shapes","vertex","triangle","quad","label","distant_light","local_light","attach_trail","attach_arrow","sqrt","pi","abs","sin","cos","tan","asin","acos","atan","atan2","exp","log","pow","factorial","combin","button","radio","checkbox","slider","checkbox","text","radians","degrees","get_library","read_local_file"];function compile(program,options){options=options||{};window.__original={text:program.split("\n")};window.__GSlang=options.lang;var version='["'+options.version+'", "glowscript"]';var findtext=/[^\.\w]text[\ ]*\(/;var findstart=/^text[\ ]*\(/;var loadfonts=findtext.exec(program);if(!loadfonts)loadfonts=findstart.exec(program);program=program.replace(/\.delete/g,".remove");function pop_replace(m,p1,p2){if(p2.length===0)return m;else return".py"+m.slice(1)}var endprog;if(options.lang=="vpython"){program=preprocess(program,options.lang);var vars="";if(program.slice(0,7)=="ERROR: "){compile_rapydscript(program)}else{var prog;program=program.replace(/(\.pop\s*\(\s*)([^)]*)/g,pop_replace);program=program.replace(/\.sort\s*\(/g,".pysort(");prog="def __main__():\n version = "+version+"\n";prog+=" window.__GSlang = 'vpython'\n";if(VPython_import===null){prog+=" display=canvas\n vector=vec\n"}else if(VPython_names.length>0){vars+=" vector=vec\n";for(var i=0;i=0)vars+=" "+name+"="+name+"\n";else vars+=" "+name+"=undefined\n"}var hasvector=VPython_names.indexOf("vector")>=0;for(var i=0;i0)prog+=" scene = canvas()\n";else prog+=" scene = "+VPython_import+".canvas()\n";prog+=" from pythonize import strings\n";prog+=" strings()\n";endprog=prog.length;prog+=program;program=compile_rapydscript(prog);var start=program.indexOf("window.__GSlang");var arr="Array.prototype['+'] = function(r) {return this.concat(r)}\n";arr+=" Array.prototype['*'] = function(r) {return __array_times_number(this, r)}\n";if(VPython_names.length<=0)arr+=vars;program=program.slice(0,start)+arr+program.slice(start-4)}}else{var p="function __main__() {\n";p+="var version = "+version+";\n";p+="Array.prototype.toString = function() { return __parsearray(this) };\n";p+="var scene = canvas();\nvar vector = vec;\n";program=p+program+"\n}"}program=program.replace("function __main__() {",'async function __main__() {\n"use strict";\n');var start=program.indexOf("async function __main__()");var prog=program.slice(start);prog=papercompile(prog);prog=program.slice(0,start)+prog;prog=";\n"+prog;if(options.lang=="vpython"){const classproto=new RegExp("\\w+\\.prototype\\."+lineno_string+'"\\w+";',"g");prog=prog.replace(classproto,"");var start,m,name;var initialstart=prog.search(lineno_string);start=initialstart;while(true){if(options.lang=="vpython")m=prog.slice(start).match(asyncpatt1);m=prog.slice(start).match(asyncpatt1);if(m===null)break;name=m[1];if(classes.indexOf(name)>=0){start+=m[0].length;continue}prog=prog.slice(0,start+m.index+1)+"async function "+name+string_insert+prog.slice(start+m.index+m[0].length-1);start+=m.index+"async function ".length+m[1].length+string_insert.length+1}start=initialstart;while(true){m=prog.slice(start).match(awaitpatt);var period=false;if(m===null)break;period=prog[start+m.index]==".";name=m[1];if(options.lang=="vpython"&&!period&&classes.indexOf(name)>=0){start+=m.index+name.length+1;var lbrace=prog.slice(start).search("{");var rbrace=prog.slice(start).search("arguments");prog=prog.slice(0,start+lbrace+1)+prog.slice(start+"arguments".length+rbrace+1);continue}if(name.slice(0,3)=="RS_"){start+=m.index+name.length+1;continue}var ptr=start+m.index+1;var brackets=0;var parens=0;while(true){ptr--;if(prog[ptr]=="]"){brackets--}else if(prog[ptr]=="["){if(brackets===0)break;brackets++}else if(prog[ptr]==")"){parens--}else if(prog[ptr]=="("){if(parens===0)break;parens++}if(prog[ptr]==" "){if(brackets===0&&parens===0)break}}var pstart=ptr+1;var prefix="";if(period){prefix=prog.slice(pstart,start+m.index)}if(options.lang=="vpython"&&period&&classinstances.indexOf(prefix)<0&&name=="replace"){prog=prog.slice(0,start+m.index+1)+"__GSrep"+prog.slice(start+m.index+name.length+1);start+=m.index+name.length+1;continue}var no_await=["if","elif","return","for","while","function","else","dict","float","hex","int","iter","len","list","vec","vector","oct","ord","print","range","arange","update","print","GSprint","clock","msclock","canvas","graph","gcurve","gdots","gvbars","ghbars","rotate","box","cylinder","cone","pyramid","sphere","simple_sphere","arrow","curve","points","paths","shapes","helix","ring","compound","vertex","triangle","quad","label","distant_light","local_light","attach_trail","attach_arrow","text","extrusion","wtext","winput","radio","checkbox","button","slider","menu","input","mag","mag2","norm","hat","dot","cross","proj","diff_angle","GS_power","abs","sin","cos","tan","asin","acos","atan","atan2","exp","log","pow","sqrt","ceil","floor","sign","round","max","min","random","factorial","combin"];var no_await2=["remove","select","append_to_title","append_to_caption","bind","unbind","call","rgb_to_hsv","hsv_to_rgb","mag","mag2","norm","hat","rotate","random","pow","format","trigger","follow","defineProperties","textures","bumpmaps"];if(period&&prefix=="self"||!period&&fcts.indexOf(name)>=0||period&&classes.indexOf(prefix)>=0&&classmethods.indexOf(name)>=0||!period&&classmethods.indexOf(name)>=0||!period&&classes.indexOf(name)>=0||period&&classinstances.indexOf(prefix)<0&&vpfcts.indexOf(name)>=0||period&&prefix==VPython_import&&fcts.indexOf(name)>=0&&fcts.indexOf(name)<4||period&&no_await2.indexOf(name)<0||!period&&no_await.indexOf(name)<0||!period&&no_await.indexOf(name)<0&&no_await2.indexOf(name)<0&&fcts.indexOf(name)<0){}else{start+=m.index+name.length+1;continue}if(options.lang=="vpython"&&prog.slice(pstart,start+m.index).search("RS_")>=0){start+=m.index+name.length+1;continue}var prepend="(";while(prog[ptr]==" ")ptr--;if(prog[ptr]=="\n"){prepend=";("}var temp=start+m.index+name.length+1;var pend=findrightparen(prog.slice(temp));pend+=temp;var pst=pstart;if(prog[pstart]=="!"){if(prepend=="(")prepend="!(";else prepend=";!(";pstart++}prog=prog.slice(0,pst)+prepend+"await "+prog.slice(pstart,pend)+")"+prog.slice(pend);start+=m.index+name.length+prepend.length+6}}program=prog.replace(/\n\n\n\n/g,"");program=program.replace(new RegExp(lineno_string,"g"),"");program=program.replace(new RegExp("\\n\\s*var RS_ls;","g"),"");program=program.replace(new RegExp(string_insert,"g"),"");program=program.replace(/Math.pow/g,"GS_power");if(loadfonts){var s="scene = canvas();\n";var sc=program.indexOf(s)+s.length;s=" fontloading();\n await waitforfonts();\n";program=program.slice(0,sc)+s+program.slice(sc,program.length)}return program}window.glowscript_compile=compile})();(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global=global||self,factory(global.acorn={}))})(this,function(exports){"use strict";var reservedWords={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var keywords={5:ecma5AndLessKeywords,"5module":ecma5AndLessKeywords+" export import",6:ecma5AndLessKeywords+" const class extends export import super"};var keywordRelationalOperator=/^in(stanceof)?$/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿯ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-Ᶎꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭧꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");nonASCIIidentifierStartChars=nonASCIIidentifierChars=null;var astralIdentifierStartCodes=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,155,22,13,52,76,44,33,24,27,35,30,0,12,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,0,33,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,0,161,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,754,9486,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541];var astralIdentifierCodes=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,232,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,792487,239];function isInAstralSet(code,set){var pos=65536;for(var i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name,prec){return new TokenType(name,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name,options){if(options===void 0)options={};options.keyword=name;return keywords$1[name]=new TokenType(name,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind:kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports,node.declaration.declarations)}else{this.checkExport(exports,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value=this.value;node=this.parseLiteral(value.value);node.regex={pattern:value.pattern,flags:value.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value){var node=this.startNode();node.value=value;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref){var isTagged=ref.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref){if(ref===void 0)ref={};var isTagged=ref.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged:isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged:isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name)>-1||scope.var.indexOf(name)>-1;scope.lexical.push(name);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name)>-1}else{redeclared=scope$2.lexical.indexOf(name)>-1||scope$2.var.indexOf(name)>-1}scope$2.functions.push(name)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name)>-1){redeclared=true;break}scope$3.var.push(name);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat){return true}if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr)){return!parent.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state){var validFlags=state.validFlags;var flags=state.flags;for(var i=0;i-1){this.raise(state.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state){this.regexp_pattern(state);if(!state.switchN&&this.options.ecmaVersion>=9&&state.groupNames.length>0){state.switchN=true;this.regexp_pattern(state)}};pp$8.regexp_pattern=function(state){state.pos=0;state.lastIntValue=0;state.lastStringValue="";state.lastAssertionIsQuantifiable=false;state.numCapturingParens=0;state.maxBackReference=0;state.groupNames.length=0;state.backReferenceNames.length=0;this.regexp_disjunction(state);if(state.pos!==state.source.length){if(state.eat(41)){state.raise("Unmatched ')'")}if(state.eat(93)||state.eat(125)){state.raise("Lone quantifier brackets")}}if(state.maxBackReference>state.numCapturingParens){state.raise("Invalid escape")}for(var i=0,list=state.backReferenceNames;i=9){lookbehind=state.eat(60)}if(state.eat(61)||state.eat(33)){this.regexp_disjunction(state);if(!state.eat(41)){state.raise("Unterminated group")}state.lastAssertionIsQuantifiable=!lookbehind;return true}}state.pos=start;return false};pp$8.regexp_eatQuantifier=function(state,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state,noError)){state.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state,noError){return state.eat(42)||state.eat(43)||state.eat(63)||this.regexp_eatBracedQuantifier(state,noError)};pp$8.regexp_eatBracedQuantifier=function(state,noError){var start=state.pos;if(state.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state)){min=state.lastIntValue;if(state.eat(44)&&this.regexp_eatDecimalDigits(state)){max=state.lastIntValue}if(state.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state)}else if(state.current()===63){state.raise("Invalid group")}this.regexp_disjunction(state);if(state.eat(41)){state.numCapturingParens+=1;return true}state.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state){return state.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state)||this.regexp_eatCharacterClass(state)||this.regexp_eatUncapturingGroup(state)||this.regexp_eatCapturingGroup(state)||this.regexp_eatInvalidBracedQuantifier(state)||this.regexp_eatExtendedPatternCharacter(state)};pp$8.regexp_eatInvalidBracedQuantifier=function(state){if(this.regexp_eatBracedQuantifier(state,true)){state.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state){var ch=state.current();if(isSyntaxCharacter(ch)){state.lastIntValue=ch;state.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state){var start=state.pos;var ch=0;while((ch=state.current())!==-1&&!isSyntaxCharacter(ch)){state.advance()}return state.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state){var ch=state.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state){if(state.eat(63)){if(this.regexp_eatGroupName(state)){if(state.groupNames.indexOf(state.lastStringValue)!==-1){state.raise("Duplicate capture group name")}state.groupNames.push(state.lastStringValue);return}state.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state){state.lastStringValue="";if(state.eat(60)){if(this.regexp_eatRegExpIdentifierName(state)&&state.eat(62)){return true}state.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state){state.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state)){state.lastStringValue+=codePointToString(state.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state)){state.lastStringValue+=codePointToString(state.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state){var start=state.pos;var ch=state.current();state.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state)){ch=state.lastIntValue}if(isRegExpIdentifierStart(ch)){state.lastIntValue=ch;return true}state.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state){var start=state.pos;var ch=state.current();state.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state)){ch=state.lastIntValue}if(isRegExpIdentifierPart(ch)){state.lastIntValue=ch;return true}state.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state){if(this.regexp_eatBackReference(state)||this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)||state.switchN&&this.regexp_eatKGroupName(state)){return true}if(state.switchU){if(state.current()===99){state.raise("Invalid unicode escape")}state.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state){var start=state.pos;if(this.regexp_eatDecimalEscape(state)){var n=state.lastIntValue;if(state.switchU){if(n>state.maxBackReference){state.maxBackReference=n}return true}if(n<=state.numCapturingParens){return true}state.pos=start}return false};pp$8.regexp_eatKGroupName=function(state){if(state.eat(107)){if(this.regexp_eatGroupName(state)){state.backReferenceNames.push(state.lastStringValue);return true}state.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state){return this.regexp_eatControlEscape(state)||this.regexp_eatCControlLetter(state)||this.regexp_eatZero(state)||this.regexp_eatHexEscapeSequence(state)||this.regexp_eatRegExpUnicodeEscapeSequence(state)||!state.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state)||this.regexp_eatIdentityEscape(state)};pp$8.regexp_eatCControlLetter=function(state){var start=state.pos;if(state.eat(99)){if(this.regexp_eatControlLetter(state)){return true}state.pos=start}return false};pp$8.regexp_eatZero=function(state){if(state.current()===48&&!isDecimalDigit(state.lookahead())){state.lastIntValue=0;state.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state){var ch=state.current();if(ch===116){state.lastIntValue=9;state.advance();return true}if(ch===110){state.lastIntValue=10;state.advance();return true}if(ch===118){state.lastIntValue=11;state.advance();return true}if(ch===102){state.lastIntValue=12;state.advance();return true}if(ch===114){state.lastIntValue=13;state.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state){var ch=state.current();if(isControlLetter(ch)){state.lastIntValue=ch%32;state.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state){var start=state.pos;if(state.eat(117)){if(this.regexp_eatFixedHexDigits(state,4)){var lead=state.lastIntValue;if(state.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state.pos;if(state.eat(92)&&state.eat(117)&&this.regexp_eatFixedHexDigits(state,4)){var trail=state.lastIntValue;if(trail>=56320&&trail<=57343){state.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state.pos=leadSurrogateEnd;state.lastIntValue=lead}return true}if(state.switchU&&state.eat(123)&&this.regexp_eatHexDigits(state)&&state.eat(125)&&isValidUnicode(state.lastIntValue)){return true}if(state.switchU){state.raise("Invalid unicode escape")}state.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state){if(state.switchU){if(this.regexp_eatSyntaxCharacter(state)){return true}if(state.eat(47)){state.lastIntValue=47;return true}return false}var ch=state.current();if(ch!==99&&(!state.switchN||ch!==107)){state.lastIntValue=ch;state.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state){state.lastIntValue=0;var ch=state.current();if(ch>=49&&ch<=57){do{state.lastIntValue=10*state.lastIntValue+(ch-48);state.advance()}while((ch=state.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state){var ch=state.current();if(isCharacterClassEscape(ch)){state.lastIntValue=-1;state.advance();return true}if(state.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state.lastIntValue=-1;state.advance();if(state.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state)&&state.eat(125)){return true}state.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state){var start=state.pos;if(this.regexp_eatUnicodePropertyName(state)&&state.eat(61)){var name=state.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state)){var value=state.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state,name,value);return true}}state.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state)){var nameOrValue=state.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state,name,value){if(!has(state.unicodeProperties.nonBinary,name)){state.raise("Invalid property name")}if(!state.unicodeProperties.nonBinary[name].test(value)){state.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state,nameOrValue){if(!state.unicodeProperties.binary.test(nameOrValue)){state.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state.current())){state.lastStringValue+=codePointToString(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state.current())){state.lastStringValue+=codePointToString(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state){return this.regexp_eatUnicodePropertyValue(state)};pp$8.regexp_eatCharacterClass=function(state){if(state.eat(91)){state.eat(94);this.regexp_classRanges(state);if(state.eat(93)){return true}state.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state){while(this.regexp_eatClassAtom(state)){var left=state.lastIntValue;if(state.eat(45)&&this.regexp_eatClassAtom(state)){var right=state.lastIntValue;if(state.switchU&&(left===-1||right===-1)){state.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state){var start=state.pos;if(state.eat(92)){if(this.regexp_eatClassEscape(state)){return true}if(state.switchU){var ch$1=state.current();if(ch$1===99||isOctalDigit(ch$1)){state.raise("Invalid class escape")}state.raise("Invalid escape")}state.pos=start}var ch=state.current();if(ch!==93){state.lastIntValue=ch;state.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state){var start=state.pos;if(state.eat(98)){state.lastIntValue=8;return true}if(state.switchU&&state.eat(45)){state.lastIntValue=45;return true}if(!state.switchU&&state.eat(99)){if(this.regexp_eatClassControlLetter(state)){return true}state.pos=start}return this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)};pp$8.regexp_eatClassControlLetter=function(state){var ch=state.current();if(isDecimalDigit(ch)||ch===95){state.lastIntValue=ch%32;state.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state){var start=state.pos;if(state.eat(120)){if(this.regexp_eatFixedHexDigits(state,2)){return true}if(state.switchU){state.raise("Invalid escape")}state.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isDecimalDigit(ch=state.current())){state.lastIntValue=10*state.lastIntValue+(ch-48);state.advance()}return state.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isHexDigit(ch=state.current())){state.lastIntValue=16*state.lastIntValue+hexToInt(ch);state.advance()}return state.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state){if(this.regexp_eatOctalDigit(state)){var n1=state.lastIntValue;if(this.regexp_eatOctalDigit(state)){var n2=state.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state)){state.lastIntValue=n1*64+n2*8+state.lastIntValue}else{state.lastIntValue=n1*8+n2}}else{state.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state){var ch=state.current();if(isOctalDigit(ch)){state.lastIntValue=ch-48;state.advance();return true}state.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state,length){var start=state.pos;state.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state=this.regexpState||(this.regexpState=new RegExpValidationState(this));state.reset(start,pattern,flags);this.validateRegExpFlags(state);this.validateRegExpPattern(state);var value=null;try{value=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern:pattern,flags:flags,value:value})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos=0||num<0&&parseInt(num)===num}var binaryOperators={"+":"add","-":"sub","*":"multiply","/":"divide","%":"modulo",">":"greater",">=":"greaterorequal","<":"less","<=":"lessorequal","+=":"plusequal","-=":"minusequal","*=":"timesequal","/=":"divideequal"};var unaryOperators={"-":"negate","+":"plus"};function papercompile(code){var insertions=[];function getOffset(offset){for(var i=0,l=insertions.length;i=offset)break;offset+=insertion[1]}return offset}function getCode(node){return code.substring(getOffset(node.range[0]),getOffset(node.range[1]))}function replaceCode(node,str){var start=getOffset(node.range[0]),end=getOffset(node.range[1]);var insert=0;for(var i=insertions.length-1;i>=0;i--){if(start>insertions[i][0]){insert=i+1;break}}insertions.splice(insert,0,[start,str.length-end+start]);code=code.substring(0,start)+str+code.substring(end)}function walkAST(node,parent){if(!node)return;for(var key in node){if(key==="range")continue;var value=node[key];if(Array.isArray(value)){for(var i=0,l=value.length;i-1){return true}return false};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});return RS_anonfunc}()}if(!RS_arraylike_creator.__module__)Object.defineProperties(RS_arraylike_creator,{__module__:{value:"__main__"}});function options_object(f){return function(){var RS_anonfunc=function(){if(typeof arguments[arguments.length-1]==="object"){arguments[RS_bound_index(arguments.length-1,arguments)][RS_kwargs_symbol]=true}return f.apply(this,arguments)};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}()}if(!options_object.__argnames__)Object.defineProperties(options_object,{__argnames__:{value:["f"]},__module__:{value:"__main__"}});function RS_id(x){return x.RS_object_id}if(!RS_id.__argnames__)Object.defineProperties(RS_id,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});function RS_dir(item){var arr;arr=RS_list_decorate([]);for(var i in item){arr.push(i)}return arr}if(!RS_dir.__argnames__)Object.defineProperties(RS_dir,{__argnames__:{value:["item"]},__module__:{value:"__main__"}});function RS_ord(x){var ans,second;ans=x.charCodeAt(0);if(55296<=ans&&ans<=56319){second=x.charCodeAt(1);if(56320<=second&&second<=57343){return(ans-55296)*1024+second-56320+65536}throw new TypeError("string is missing the low surrogate char")}return ans}if(!RS_ord.__argnames__)Object.defineProperties(RS_ord,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});function RS_chr(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode(55296+(code>>10),56320+(code&1023))}if(!RS_chr.__argnames__)Object.defineProperties(RS_chr,{__argnames__:{value:["code"]},__module__:{value:"__main__"}});function RS_callable(x){return typeof x==="function"}if(!RS_callable.__argnames__)Object.defineProperties(RS_callable,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});function RS_bin(x){var ans;if(typeof x!=="number"||x%1!==0){throw new TypeError("integer required")}ans=x.toString(2);if(ans[0]==="-"){ans="-"+"0b"+ans.slice(1)}else{ans="0b"+ans}return ans}if(!RS_bin.__argnames__)Object.defineProperties(RS_bin,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});function RS_hex(x){var ans;if(typeof x!=="number"||x%1!==0){throw new TypeError("integer required")}ans=x.toString(16);if(ans[0]==="-"){ans="-"+"0x"+ans.slice(1)}else{ans="0x"+ans}return ans}if(!RS_hex.__argnames__)Object.defineProperties(RS_hex,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});function RS_enumerate(iterable){var ans,iterator;ans={_i:-1};ans[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();if(RS_arraylike(iterable)){ans["next"]=function(){var RS_anonfunc=function(){this._i+=1;if(this._i-1){return{done:false,value:iterable[this._i]}}return{done:true}};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();ans[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return ans}throw new TypeError("reversed() can only be called on arrays or strings")}if(!RS_reversed.__argnames__)Object.defineProperties(RS_reversed,{__argnames__:{value:["iterable"]},__module__:{value:"__main__"}});function RS_iter(iterable){var ans;if(typeof iterable[RS_iterator_symbol]==="function"){return typeof Map==="function"&&iterable instanceof Map?iterable.keys():iterable[RS_iterator_symbol]()}if(RS_arraylike(iterable)){ans={_i:-1};ans[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();ans["next"]=function(){var RS_anonfunc=function(){this._i+=1;if(this._i=length){RS_unpack=[this.__i,-1];this._i=RS_unpack[0];this._idx=RS_unpack[1];return{done:true}}return{done:false,value:this._i}}if(!RS_range_next.__argnames__)Object.defineProperties(RS_range_next,{__argnames__:{value:["step","length"]},__module__:{value:"__main__"}});function RS_range(start,stop,step){var length,ans;if(arguments.length<=1){stop=start||0;start=0}step=arguments[2]||1;length=Math.max(Math.ceil((stop-start)/step),0);ans={start:start,step:step,stop:stop};ans[RS_iterator_symbol]=function(){var RS_anonfunc=function(){var it;it={_i:start-step,_idx:-1};it.next=RS_range_next.bind(it,step,length);it[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return it};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();ans.count=function(){var RS_anonfunc=function(val){if(!this._cached){this._cached=list(this)}return this._cached.count(val)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["val"]},__module__:{value:"__main__"}});return RS_anonfunc}();ans.index=function(){var RS_anonfunc=function(val){if(!this._cached){this._cached=list(this)}return this._cached.index(val)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["val"]},__module__:{value:"__main__"}});return RS_anonfunc}();if(typeof Proxy==="function"){ans=new Proxy(ans,function(){var RS_d={};RS_d["get"]=function(){var RS_anonfunc=function(obj,prop){var iprop;if(typeof prop==="string"){iprop=parseInt(prop);if(!isNaN(iprop)){prop=iprop}}if(typeof prop==="number"){if(!obj._cached){obj._cached=list(obj)}return(RS_expr_temp=obj._cached)[typeof prop==="number"&&prop<0?RS_expr_temp.length+prop:prop]}return obj[typeof prop==="number"&&prop<0?obj.length+prop:prop]};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["obj","prop"]},__module__:{value:"__main__"}});return RS_anonfunc}();return RS_d}.call(this))}return ans}if(!RS_range.__argnames__)Object.defineProperties(RS_range,{__argnames__:{value:["start","stop","step"]},__module__:{value:"__main__"}});function RS_getattr(obj,name,defval){var ret;try{ret=obj[typeof name==="number"&&name<0?obj.length+name:name]}catch(RS_Exception){RS_last_exception=RS_Exception;if(RS_Exception instanceof TypeError){if(defval===undefined){throw new AttributeError("The attribute "+name+" is not present")}return defval}else{throw RS_Exception}}if(ret===undefined&&!(name in obj)){if(defval===undefined){throw new AttributeError("The attribute "+name+" is not present")}ret=defval}return ret}if(!RS_getattr.__argnames__)Object.defineProperties(RS_getattr,{__argnames__:{value:["obj","name","defval"]},__module__:{value:"__main__"}});function RS_setattr(obj,name,value){obj[typeof name==="number"&&name<0?obj.length+name:name]=value}if(!RS_setattr.__argnames__)Object.defineProperties(RS_setattr,{__argnames__:{value:["obj","name","value"]},__module__:{value:"__main__"}});function RS_hasattr(obj,name){return name in obj}if(!RS_hasattr.__argnames__)Object.defineProperties(RS_hasattr,{__argnames__:{value:["obj","name"]},__module__:{value:"__main__"}});RS_len=function(){var RS_anonfunc=function(){function len(obj){if(RS_arraylike(obj)){return obj.length}if(typeof obj.__len__==="function"){return obj.__len__()}if(obj instanceof Set||obj instanceof Map){return obj.size}return Object.keys(obj).length}if(!len.__argnames__)Object.defineProperties(len,{__argnames__:{value:["obj"]},__module__:{value:"__main__"}});function len5(obj){if(RS_arraylike(obj)){return obj.length}if(typeof obj.__len__==="function"){return obj.__len__()}return Object.keys(obj).length}if(!len5.__argnames__)Object.defineProperties(len5,{__argnames__:{value:["obj"]},__module__:{value:"__main__"}});return typeof Set==="function"&&typeof Map==="function"?len:len5};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}()();function RS_get_module(name){return RS_modules[typeof name==="number"&&name<0?RS_modules.length+name:name]}if(!RS_get_module.__argnames__)Object.defineProperties(RS_get_module,{__argnames__:{value:["name"]},__module__:{value:"__main__"}});function RS_pow(x,y,z){var ans;ans=Math.pow(x,y);if(z!==undefined){ans%=z}return ans}if(!RS_pow.__argnames__)Object.defineProperties(RS_pow,{__argnames__:{value:["x","y","z"]},__module__:{value:"__main__"}});function RS_type(x){return x.constructor}if(!RS_type.__argnames__)Object.defineProperties(RS_type,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});function RS_divmod(x,y){var d;if(y===0){throw new ZeroDivisionError("integer division or modulo by zero")}d=Math.floor(x/y);return[d,x-d*y]}if(!RS_divmod.__argnames__)Object.defineProperties(RS_divmod,{__argnames__:{value:["x","y"]},__module__:{value:"__main__"}});function RS_max(){var kwargs=arguments[arguments.length-1];if(kwargs===null||typeof kwargs!=="object"||kwargs[RS_kwargs_symbol]!==true)kwargs={};var args=Array.prototype.slice.call(arguments,0);if(kwargs!==null&&typeof kwargs==="object"&&kwargs[RS_kwargs_symbol]===true)args.pop();var args,x;if(args.length===0){if(kwargs.defval!==undefined){return kwargs.defval}throw new TypeError("expected at least one argument")}if(args.length===1){args=args[0]}if(kwargs.key){args=function(){var RS_Iter=RS_Iterable(args),RS_Result=[],x;for(var RS_Index=0;RS_Indexindex;i--){(RS_expr_temp=this)[typeof i==="number"&&i<0?RS_expr_temp.length+i:i]=(RS_expr_temp=this)[RS_bound_index(i-1,RS_expr_temp)]}(RS_expr_temp=this)[typeof index==="number"&&index<0?RS_expr_temp.length+index:index]=val}if(!RS_list_insert.__argnames__)Object.defineProperties(RS_list_insert,{__argnames__:{value:["index","val"]},__module__:{value:"__main__"}});function RS_list_copy(){return RS_list_constructor(this)}if(!RS_list_copy.__module__)Object.defineProperties(RS_list_copy,{__module__:{value:"__main__"}});function RS_list_clear(){this.length=0}if(!RS_list_clear.__module__)Object.defineProperties(RS_list_clear,{__module__:{value:"__main__"}});function RS_list_as_array(){return Array.prototype.slice.call(this)}if(!RS_list_as_array.__module__)Object.defineProperties(RS_list_as_array,{__module__:{value:"__main__"}});function RS_list_count(value){return this.reduce(function(){var RS_anonfunc=function(n,val){return n+(val===value)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["n","val"]},__module__:{value:"__main__"}});return RS_anonfunc}(),0)}if(!RS_list_count.__argnames__)Object.defineProperties(RS_list_count,{__argnames__:{value:["value"]},__module__:{value:"__main__"}});function RS_list_sort_key(value){var t;t=typeof value;if(t==="string"||t==="number"){return value}return value.toString()}if(!RS_list_sort_key.__argnames__)Object.defineProperties(RS_list_sort_key,{__argnames__:{value:["value"]},__module__:{value:"__main__"}});function RS_list_sort_cmp(a,b,ap,bp){if(ab){return 1}return ap-bp}if(!RS_list_sort_cmp.__argnames__)Object.defineProperties(RS_list_sort_cmp,{__argnames__:{value:["a","b","ap","bp"]},__module__:{value:"__main__"}});function RS_list_sort(){var key=arguments[0]===undefined||0===arguments.length-1&&arguments[arguments.length-1]!==null&&typeof arguments[arguments.length-1]==="object"&&arguments[arguments.length-1][RS_kwargs_symbol]===true?RS_list_sort.__defaults__.key:arguments[0];var reverse=arguments[1]===undefined||1===arguments.length-1&&arguments[arguments.length-1]!==null&&typeof arguments[arguments.length-1]==="object"&&arguments[arguments.length-1][RS_kwargs_symbol]===true?RS_list_sort.__defaults__.reverse:arguments[1];var RS_kwargs_obj=arguments[arguments.length-1];if(RS_kwargs_obj===null||typeof RS_kwargs_obj!=="object"||RS_kwargs_obj[RS_kwargs_symbol]!==true)RS_kwargs_obj={};if(Object.prototype.hasOwnProperty.call(RS_kwargs_obj,"key")){key=RS_kwargs_obj.key}if(Object.prototype.hasOwnProperty.call(RS_kwargs_obj,"reverse")){reverse=RS_kwargs_obj.reverse}var mult,keymap,posmap,k;key=key||RS_list_sort_key;mult=reverse?-1:1;keymap=dict();posmap=dict();for(var i=0;i=this._list.length){return function(){var RS_d={};RS_d["done"]=true;return RS_d}.call(this)}return function(){var RS_d={};RS_d["done"]=false;RS_d["value"]=(RS_expr_temp=this._list)[RS_bound_index(this._i,RS_expr_temp)];return RS_d}.call(this)};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return RS_d}.call(this)}if(!RS_list_iterator.__argnames__)Object.defineProperties(RS_list_iterator,{__argnames__:{value:["value"]},__module__:{value:"__main__"}});function RS_list_len(){return this.length}if(!RS_list_len.__module__)Object.defineProperties(RS_list_len,{__module__:{value:"__main__"}});function RS_list_contains(val){for(var i=0;i=this._keys.length){return{done:true}}return{done:false,value:this._s[this._keys[this._i]]}};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});return RS_anonfunc}();if(typeof Set!=="function"||typeof Set.prototype.delete!=="function"){RS_set_implementation=RS_set_polyfill}else{RS_set_implementation=Set}function RS_set(iterable){var ans,s,iterator,result,keys;if(this instanceof RS_set){this.jsset=new RS_set_implementation;ans=this;if(iterable===undefined){return ans}s=ans.jsset;if(RS_arraylike(iterable)){for(var i=0;i=this._keys.length){return{done:true}}return{done:false,value:this._s[this._keys[this._i]][1]}};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict_polyfill.prototype.keys=function(){var RS_anonfunc=function(x){var ans;ans={_keys:Object.keys(this._store),_i:-1,_s:this._store};ans[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();ans["next"]=function(){var RS_anonfunc=function(){this._i+=1;if(this._i>=this._keys.length){return{done:true}}return{done:false,value:this._s[this._keys[this._i]][0]}};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict_polyfill.prototype.entries=function(){var RS_anonfunc=function(x){var ans;ans={_keys:Object.keys(this._store),_i:-1,_s:this._store};ans[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();ans["next"]=function(){var RS_anonfunc=function(){this._i+=1;if(this._i>=this._keys.length){return{done:true}}return{done:false,value:this._s[this._keys[this._i]]}};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});return RS_anonfunc}();if(typeof Map!=="function"||typeof Map.prototype.delete!=="function"){RS_dict_implementation=RS_dict_polyfill}else{RS_dict_implementation=Map}function RS_dict(){var iterable=0===arguments.length-1&&arguments[arguments.length-1]!==null&&typeof arguments[arguments.length-1]==="object"&&arguments[arguments.length-1][RS_kwargs_symbol]===true?undefined:arguments[0];var kw=arguments[arguments.length-1];if(kw===null||typeof kw!=="object"||kw[RS_kwargs_symbol]!==true)kw={};if(this instanceof RS_dict){this.jsmap=new RS_dict_implementation;if(iterable!==undefined){this.update(iterable)}this.update(kw);return this}else{return RS_interpolate_kwargs_constructor.call(Object.create(RS_dict.prototype),false,RS_dict,[iterable].concat([RS_desugar_kwargs(kw)]))}}if(!RS_dict.__handles_kwarg_interpolation__)Object.defineProperties(RS_dict,{__handles_kwarg_interpolation__:{value:true},__argnames__:{value:["iterable"]},__module__:{value:"__main__"}});RS_dict.prototype.__name__="dict";Object.defineProperties(RS_dict.prototype,function(){var RS_d={};RS_d["length"]=function(){var RS_d={};RS_d["get"]=function(){var RS_anonfunc=function(){return this.jsmap.size};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return RS_d}.call(this);RS_d["size"]=function(){var RS_d={};RS_d["get"]=function(){var RS_anonfunc=function(){return this.jsmap.size};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();return RS_d}.call(this);return RS_d}.call(this));RS_dict.prototype.__len__=function(){var RS_anonfunc=function(){return this.jsmap.size};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.has=RS_dict.prototype.__contains__=function(){var RS_anonfunc=function(x){return this.jsmap.has(x)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.set=RS_dict.prototype.__setitem__=function(){var RS_anonfunc=function(key,value){this.jsmap.set(key,value)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["key","value"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.__delitem__=function(){var RS_anonfunc=function(key){this.jsmap.delete(key)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["key"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.clear=function(){var RS_anonfunc=function(){this.jsmap.clear()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.copy=function(){var RS_anonfunc=function(){return RS_dict(this)};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.keys=function(){var RS_anonfunc=function(){return this.jsmap.keys()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.values=function(){var RS_anonfunc=function(){return this.jsmap.values()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.items=RS_dict.prototype.entries=function(){var RS_anonfunc=function(){return this.jsmap.entries()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this.jsmap.keys()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.__getitem__=function(){var RS_anonfunc=function(key){var ans;ans=this.jsmap.get(key);if(ans===undefined&&!this.jsmap.has(key)){throw new KeyError(key+"")}return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["key"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.get=function(){var RS_anonfunc=function(key,defval){var ans;ans=this.jsmap.get(key);if(ans===undefined&&!this.jsmap.has(key)){return defval===undefined?null:defval}return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["key","defval"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.set_default=function(){var RS_anonfunc=function(key,defval){var j;j=this.jsmap;if(!j.has(key)){j.set(key,defval);return defval}return j.get(key)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["key","defval"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.fromkeys=RS_dict.prototype.fromkeys=function(){var RS_anonfunc=function(){var iterable=0===arguments.length-1&&arguments[arguments.length-1]!==null&&typeof arguments[arguments.length-1]==="object"&&arguments[arguments.length-1][RS_kwargs_symbol]===true?undefined:arguments[0];var value=arguments[1]===undefined||1===arguments.length-1&&arguments[arguments.length-1]!==null&&typeof arguments[arguments.length-1]==="object"&&arguments[arguments.length-1][RS_kwargs_symbol]===true?RS_anonfunc.__defaults__.value:arguments[1];var RS_kwargs_obj=arguments[arguments.length-1];if(RS_kwargs_obj===null||typeof RS_kwargs_obj!=="object"||RS_kwargs_obj[RS_kwargs_symbol]!==true)RS_kwargs_obj={};if(Object.prototype.hasOwnProperty.call(RS_kwargs_obj,"value")){value=RS_kwargs_obj.value}var ans,iterator,r;ans=RS_dict();iterator=iter(iterable);r=iterator.next();while(!r.done){ans.set(r.value,value);r=iterator.next()}return ans};if(!RS_anonfunc.__defaults__)Object.defineProperties(RS_anonfunc,{__defaults__:{value:{value:null}},__handles_kwarg_interpolation__:{value:true},__argnames__:{value:["iterable","value"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.pop=function(){var RS_anonfunc=function(key,defval){var ans;ans=this.jsmap.get(key);if(ans===undefined&&!this.jsmap.has(key)){if(defval===undefined){throw new KeyError(key)}return defval}this.jsmap.delete(key);return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["key","defval"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.popitem=function(){var RS_anonfunc=function(){var r;r=this.jsmap.entries().next();if(r.done){throw new KeyError("dict is empty")}this.jsmap.delete(r.value[0]);return r.value};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.update=function(){var RS_anonfunc=function(){var m,iterable,iterator,result,keys;if(arguments.length===0){return}m=this.jsmap;iterable=arguments[0];if(Array.isArray(iterable)){for(var i=0;i1){RS_dict.prototype.update.call(this,arguments[1])}};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.toString=RS_dict.prototype.inspect=RS_dict.prototype.__str__=RS_dict.prototype.__repr__=function(){var RS_anonfunc=function(){var entries,iterator,r;entries=[];iterator=this.jsmap.entries();r=iterator.next();while(!r.done){entries.push(RS_repr(r.value[0])+": "+RS_repr(r.value[1]));r=iterator.next()}return"{"+entries.join(", ")+"}"};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.__eq__=function(){var RS_anonfunc=function(other){var iterator,r,x;if(!(other instanceof this.constructor)){return false}if(other.size!==this.size){return false}if(other.size===0){return true}iterator=other.items();r=iterator.next();while(!r.done){x=this.jsmap.get(r.value[0]);if(x===undefined&&!this.jsmap.has(r.value[0])||x!==r.value[1]){return false}r=iterator.next()}return true};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["other"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_dict.prototype.as_object=function(){var RS_anonfunc=function(other){var ans,iterator,r;ans={};iterator=this.jsmap.entries();r=iterator.next();while(!r.done){ans[RS_bound_index(r.value[0],ans)]=r.value[1];r=iterator.next()}return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["other"]},__module__:{value:"__main__"}});return RS_anonfunc}();function RS_dict_wrap(x){var ans;ans=new RS_dict;ans.jsmap=x;return ans}if(!RS_dict_wrap.__argnames__)Object.defineProperties(RS_dict_wrap,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});var dict=RS_dict,dict_wrap=RS_dict_wrap;var NameError;NameError=ReferenceError;function Exception(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});Exception.prototype.__init__.apply(this,arguments)}RS_extends(Exception,Error);Exception.prototype.__init__=function __init__(message){var self=this;self.message=message;self.stack=(new Error).stack;self.name=self.constructor.name};if(!Exception.prototype.__init__.__argnames__)Object.defineProperties(Exception.prototype.__init__,{__argnames__:{value:["message"]},__module__:{value:"__main__"}});Exception.__argnames__=Exception.prototype.__init__.__argnames__;Exception.__handles_kwarg_interpolation__=Exception.prototype.__init__.__handles_kwarg_interpolation__;Exception.prototype.__repr__=function __repr__(){var self=this;return self.name+": "+self.message};if(!Exception.prototype.__repr__.__module__)Object.defineProperties(Exception.prototype.__repr__,{__module__:{value:"__main__"}});Exception.prototype.__str__=function __str__(){if(Error.prototype.__str__)return Error.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(Exception.prototype,"__bases__",{value:[Error]});function AttributeError(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});AttributeError.prototype.__init__.apply(this,arguments)}RS_extends(AttributeError,Exception);AttributeError.prototype.__init__=function __init__(){Exception.prototype.__init__&&Exception.prototype.__init__.apply(this,arguments)};AttributeError.prototype.__repr__=function __repr__(){if(Exception.prototype.__repr__)return Exception.prototype.__repr__.call(this);return"<"+__name__+"."+this.constructor.name+" #"+this.RS_object_id+">"};AttributeError.prototype.__str__=function __str__(){if(Exception.prototype.__str__)return Exception.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(AttributeError.prototype,"__bases__",{value:[Exception]});function IndexError(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});IndexError.prototype.__init__.apply(this,arguments)}RS_extends(IndexError,Exception);IndexError.prototype.__init__=function __init__(){Exception.prototype.__init__&&Exception.prototype.__init__.apply(this,arguments)};IndexError.prototype.__repr__=function __repr__(){if(Exception.prototype.__repr__)return Exception.prototype.__repr__.call(this);return"<"+__name__+"."+this.constructor.name+" #"+this.RS_object_id+">"};IndexError.prototype.__str__=function __str__(){if(Exception.prototype.__str__)return Exception.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(IndexError.prototype,"__bases__",{value:[Exception]});function KeyError(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});KeyError.prototype.__init__.apply(this,arguments)}RS_extends(KeyError,Exception);KeyError.prototype.__init__=function __init__(){Exception.prototype.__init__&&Exception.prototype.__init__.apply(this,arguments)};KeyError.prototype.__repr__=function __repr__(){if(Exception.prototype.__repr__)return Exception.prototype.__repr__.call(this);return"<"+__name__+"."+this.constructor.name+" #"+this.RS_object_id+">"};KeyError.prototype.__str__=function __str__(){if(Exception.prototype.__str__)return Exception.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(KeyError.prototype,"__bases__",{value:[Exception]});function ValueError(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});ValueError.prototype.__init__.apply(this,arguments)}RS_extends(ValueError,Exception);ValueError.prototype.__init__=function __init__(){Exception.prototype.__init__&&Exception.prototype.__init__.apply(this,arguments)};ValueError.prototype.__repr__=function __repr__(){if(Exception.prototype.__repr__)return Exception.prototype.__repr__.call(this);return"<"+__name__+"."+this.constructor.name+" #"+this.RS_object_id+">"};ValueError.prototype.__str__=function __str__(){if(Exception.prototype.__str__)return Exception.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(ValueError.prototype,"__bases__",{value:[Exception]});function UnicodeDecodeError(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});UnicodeDecodeError.prototype.__init__.apply(this,arguments)}RS_extends(UnicodeDecodeError,Exception);UnicodeDecodeError.prototype.__init__=function __init__(){Exception.prototype.__init__&&Exception.prototype.__init__.apply(this,arguments)};UnicodeDecodeError.prototype.__repr__=function __repr__(){if(Exception.prototype.__repr__)return Exception.prototype.__repr__.call(this);return"<"+__name__+"."+this.constructor.name+" #"+this.RS_object_id+">"};UnicodeDecodeError.prototype.__str__=function __str__(){if(Exception.prototype.__str__)return Exception.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(UnicodeDecodeError.prototype,"__bases__",{value:[Exception]});function AssertionError(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});AssertionError.prototype.__init__.apply(this,arguments)}RS_extends(AssertionError,Exception);AssertionError.prototype.__init__=function __init__(){Exception.prototype.__init__&&Exception.prototype.__init__.apply(this,arguments)};AssertionError.prototype.__repr__=function __repr__(){if(Exception.prototype.__repr__)return Exception.prototype.__repr__.call(this);return"<"+__name__+"."+this.constructor.name+" #"+this.RS_object_id+">"};AssertionError.prototype.__str__=function __str__(){if(Exception.prototype.__str__)return Exception.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(AssertionError.prototype,"__bases__",{value:[Exception]});function ZeroDivisionError(){if(this.RS_object_id===undefined)Object.defineProperty(this,"RS_object_id",{value:++RS_object_counter});ZeroDivisionError.prototype.__init__.apply(this,arguments)}RS_extends(ZeroDivisionError,Exception);ZeroDivisionError.prototype.__init__=function __init__(){Exception.prototype.__init__&&Exception.prototype.__init__.apply(this,arguments)};ZeroDivisionError.prototype.__repr__=function __repr__(){if(Exception.prototype.__repr__)return Exception.prototype.__repr__.call(this);return"<"+__name__+"."+this.constructor.name+" #"+this.RS_object_id+">"};ZeroDivisionError.prototype.__str__=function __str__(){if(Exception.prototype.__str__)return Exception.prototype.__str__.call(this);return this.__repr__()};Object.defineProperty(ZeroDivisionError.prototype,"__bases__",{value:[Exception]});var RS_in,RS_desugar_kwargs,RS_exists;function RS_eslice(arr,step,start,end){var is_string;if(typeof arr==="string"||arr instanceof String){is_string=true;arr=arr.split("")}if(step<0){step=-step;arr=arr.slice().reverse();if(typeof start!=="undefined"){start=arr.length-start-1}if(typeof end!=="undefined"){end=arr.length-end-1}}if(typeof start==="undefined"){start=0}if(typeof end==="undefined"){end=arr.length}arr=arr.slice(start,end).filter(function(){var RS_anonfunc=function(e,i){return i%step===0};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["e","i"]},__module__:{value:"__main__"}});return RS_anonfunc}());if(is_string){arr=arr.join("")}return arr}if(!RS_eslice.__argnames__)Object.defineProperties(RS_eslice,{__argnames__:{value:["arr","step","start","end"]},__module__:{value:"__main__"}});function RS_delslice(arr,step,start,end){var is_string,RS_unpack,indices;if(typeof arr==="string"||arr instanceof String){is_string=true;arr=arr.split("")}if(step<0){if(typeof start==="undefined"){start=arr.length}if(typeof end==="undefined"){end=0}RS_unpack=[end,start,-step];start=RS_unpack[0];end=RS_unpack[1];step=RS_unpack[2]}if(typeof start==="undefined"){start=0}if(typeof end==="undefined"){end=arr.length}if(step===1){arr.splice(start,end-start)}else{if(end>start){indices=[];for(var i=start;i=0;i--){arr.splice(indices[typeof i==="number"&&i<0?indices.length+i:i],1)}}}if(is_string){arr=arr.join("")}return arr}if(!RS_delslice.__argnames__)Object.defineProperties(RS_delslice,{__argnames__:{value:["arr","step","start","end"]},__module__:{value:"__main__"}});function RS_flatten(arr){var ans,value;ans=RS_list_decorate([]);for(var i=0;i1){for(var c=1;c10){val=val.slice(0,15)+"..."}val=JSON.stringify(val);attrs.push(""+RS_str.format("{}",attr.name)+"="+RS_str.format("{}",val)+"")}}attrs=attrs.length?" "+attrs.join(" "):"";ans="<"+RS_str.format("{}",elem.tagName)+""+RS_str.format("{}",attrs)+">";return ans}if(!RS_html_element_to_string.__argnames__)Object.defineProperties(RS_html_element_to_string,{__argnames__:{value:["elem"]},__module__:{value:"__main__"}});function RS_repr(x){var ans,name;if(x===null){return"None"}if(x===undefined){return"undefined"}ans=x;if(typeof x.__repr__==="function"){ans=x.__repr__()}else if(x===true||x===false){ans=x?"True":"False"}else if(Array.isArray(x)){ans=RS_repr_js_builtin(x,true)}else if(typeof x==="function"){ans=x.toString()}else if(typeof x==="object"&&!x.toString){ans=RS_repr_js_builtin(x)}else{name=Object.prototype.toString.call(x).slice(8,-1);if(RS_not_equals("Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".indexOf(name),-1)){return name+"(["+x.map(function(){var RS_anonfunc=function(i){return str.format("0x{:02x}",i)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["i"]},__module__:{value:"__main__"}});return RS_anonfunc}()).join(", ")+"])"}if(typeof HTMLElement!=="undefined"&&x instanceof HTMLElement){ans=RS_html_element_to_string(x)}else{ans=typeof x.toString==="function"?x.toString():x}if(ans==="[object Object]"){return RS_repr_js_builtin(x)}try{ans=JSON.stringify(x)}catch(RS_Exception){RS_last_exception=RS_Exception;{}}}return ans+""}if(!RS_repr.__argnames__)Object.defineProperties(RS_repr,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});function RS_str(x){var ans,name;if(x===null){return"None"}if(x===undefined){return"undefined"}ans=x;if(typeof x.__str__==="function"){ans=x.__str__()}else if(typeof x.__repr__==="function"){ans=x.__repr__()}else if(x===true||x===false){ans=x?"True":"False"}else if(Array.isArray(x)){ans=RS_repr_js_builtin(x,true)}else if(typeof x.toString==="function"){name=Object.prototype.toString.call(x).slice(8,-1);if(RS_not_equals("Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array".indexOf(name),-1)){return name+"(["+x.map(function(){var RS_anonfunc=function(i){return str.format("0x{:02x}",i)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["i"]},__module__:{value:"__main__"}});return RS_anonfunc}()).join(", ")+"])"}if(typeof HTMLElement!=="undefined"&&x instanceof HTMLElement){ans=RS_html_element_to_string(x)}else{ans=x.toString()}if(ans==="[object Object]"){ans=RS_repr_js_builtin(x)}}else if(typeof x==="object"&&!x.toString){ans=RS_repr_js_builtin(x)}return ans+""}if(!RS_str.__argnames__)Object.defineProperties(RS_str,{__argnames__:{value:["x"]},__module__:{value:"__main__"}});define_str_func=function(){var RS_anonfunc=function(name,func){var f;(RS_expr_temp=RS_str.prototype)[typeof name==="number"&&name<0?RS_expr_temp.length+name:name]=func;RS_str[typeof name==="number"&&name<0?RS_str.length+name:name]=f=func.call.bind(func);if(func.__argnames__){Object.defineProperty(f,"__argnames__",function(){var RS_d={};RS_d["value"]=["string"].concat(func.__argnames__);return RS_d}.call(this))}};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["name","func"]},__module__:{value:"__main__"}});return RS_anonfunc}();RS_unpack=[String.prototype.split.call.bind(String.prototype.split),String.prototype.replace.call.bind(String.prototype.replace)];RS_orig_split=RS_unpack[0];RS_orig_replace=RS_unpack[1];define_str_func("format",function(){var RS_anonfunc=function(){var template,args,kwargs,explicit,implicit,idx,split,ans,pos,in_brace,markup,ch;template=this;if(template===undefined){throw new TypeError("Template is required")}args=Array.prototype.slice.call(arguments);kwargs={};if(args[args.length-1]&&args[args.length-1][RS_kwargs_symbol]!==undefined){kwargs=args[args.length-1];args=args.slice(0,-1)}explicit=implicit=false;idx=0;split=RS_orig_split;if(RS_str.format._template_resolve_pat===undefined){RS_str.format._template_resolve_pat=/[.\[]/}function resolve(arg,object){var RS_unpack,first,key,rest,ans;if(!arg){return object}RS_unpack=[arg[0],arg.slice(1)];first=RS_unpack[0];arg=RS_unpack[1];key=split(arg,RS_str.format._template_resolve_pat,1)[0];rest=arg.slice(key.length);ans=first==="["?object[RS_bound_index(key.slice(0,-1),object)]:getattr(object,key);if(ans===undefined){throw new KeyError(first==="["?key.slice(0,-1):key)}return resolve(rest,ans)}if(!resolve.__argnames__)Object.defineProperties(resolve,{__argnames__:{value:["arg","object"]},__module__:{value:"__main__"}});function resolve_format_spec(format_spec){if(RS_str.format._template_resolve_fs_pat===undefined){RS_str.format._template_resolve_fs_pat=/[{]([a-zA-Z0-9_]+)[}]/g}return format_spec.replace(RS_str.format._template_resolve_fs_pat,function(){var RS_anonfunc=function(match,key){if(!Object.prototype.hasOwnProperty.call(kwargs,key)){return""}return""+kwargs[typeof key==="number"&&key<0?kwargs.length+key:key]};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["match","key"]},__module__:{value:"__main__"}});return RS_anonfunc}())}if(!resolve_format_spec.__argnames__)Object.defineProperties(resolve_format_spec,{__argnames__:{value:["format_spec"]},__module__:{value:"__main__"}});function set_comma(ans,comma){var sep;if(comma!==","){sep=1234;sep=sep.toLocaleString(undefined,{useGrouping:true})[1];ans=str.replace(ans,sep,comma)}return ans}if(!set_comma.__argnames__)Object.defineProperties(set_comma,{__argnames__:{value:["ans","comma"]},__module__:{value:"__main__"}});function safe_comma(value,comma){try{return set_comma(value.toLocaleString(undefined,{useGrouping:true}),comma)}catch(RS_Exception){RS_last_exception=RS_Exception;{return value.toString(10)}}}if(!safe_comma.__argnames__)Object.defineProperties(safe_comma,{__argnames__:{value:["value","comma"]},__module__:{value:"__main__"}});function safe_fixed(value,precision,comma){if(!comma){return value.toFixed(precision)}try{return set_comma(value.toLocaleString(undefined,{useGrouping:true,minimumFractionDigits:precision,maximumFractionDigits:precision}),comma)}catch(RS_Exception){RS_last_exception=RS_Exception;{return value.toFixed(precision)}}}if(!safe_fixed.__argnames__)Object.defineProperties(safe_fixed,{__argnames__:{value:["value","precision","comma"]},__module__:{value:"__main__"}});function apply_formatting(value,format_spec){var RS_unpack,fill,align,sign,fhash,zeropad,width,comma,precision,ftype,is_numeric,is_int,lftype,code,prec,exp,nval,is_positive,left,right;if(format_spec.indexOf("{")!==-1){format_spec=resolve_format_spec(format_spec)}if(RS_str.format._template_format_pat===undefined){RS_str.format._template_format_pat=/([^{}](?=[<>=^]))?([<>=^])?([-+\x20])?(\#)?(0)?(\d+)?([,_])?(?:\.(\d+))?([bcdeEfFgGnosxX%])?/}try{RS_unpack=format_spec.match(RS_str.format._template_format_pat).slice(1);RS_unpack=RS_unpack_asarray(9,RS_unpack);fill=RS_unpack[0];align=RS_unpack[1];sign=RS_unpack[2];fhash=RS_unpack[3];zeropad=RS_unpack[4];width=RS_unpack[5];comma=RS_unpack[6];precision=RS_unpack[7];ftype=RS_unpack[8]}catch(RS_Exception){RS_last_exception=RS_Exception;if(RS_Exception instanceof TypeError){return value}else{throw RS_Exception}}if(zeropad){fill=fill||"0";align=align||"="}else{fill=fill||" ";align=align||">"}is_numeric=Number(value)===value;is_int=is_numeric&&value%1===0;precision=parseInt(precision,10);lftype=(ftype||"").toLowerCase();if(ftype==="n"){is_numeric=true;if(is_int){if(comma){throw new ValueError("Cannot specify ',' with 'n'")}value=parseInt(value,10).toLocaleString()}else{value=parseFloat(value).toLocaleString()}}else if(["b","c","d","o","x"].indexOf(lftype)!==-1){value=parseInt(value,10);is_numeric=true;if(!isNaN(value)){if(ftype==="b"){value=(value>>>0).toString(2);if(fhash){value="0b"+value}}else if(ftype==="c"){if(value>65535){code=value-65536;value=String.fromCharCode(55296+(code>>10),56320+(code&1023))}else{value=String.fromCharCode(value)}}else if(ftype==="d"){if(comma){value=safe_comma(value,comma)}else{value=value.toString(10)}}else if(ftype==="o"){value=value.toString(8);if(fhash){value="0o"+value}}else if(lftype==="x"){value=value.toString(16);value=ftype==="x"?value.toLowerCase():value.toUpperCase();if(fhash){value="0x"+value}}}}else if(["e","f","g","%"].indexOf(lftype)!==-1){is_numeric=true;value=parseFloat(value);prec=isNaN(precision)?6:precision;if(lftype==="e"){value=value.toExponential(prec);value=ftype==="E"?value.toUpperCase():value.toLowerCase()}else if(lftype==="f"){value=safe_fixed(value,prec,comma);value=ftype==="F"?value.toUpperCase():value.toLowerCase()}else if(lftype==="%"){value*=100;value=safe_fixed(value,prec,comma)+"%"}else if(lftype==="g"){prec=max(1,prec);exp=parseInt(split(value.toExponential(prec-1).toLowerCase(),"e")[1],10);if(-4<=exp&&exp=0;if(is_positive&&(sign===" "||sign==="+")){value=sign+value}}function repeat(char,num){return new Array(num+1).join(char)}if(!repeat.__argnames__)Object.defineProperties(repeat,{__argnames__:{value:["char","num"]},__module__:{value:"__main__"}});if(is_numeric&&width&&width[0]==="0"){width=width.slice(1);RS_unpack=["0","="];fill=RS_unpack[0];align=RS_unpack[1]}width=parseInt(width||"-1",10);if(isNaN(width)){throw new ValueError("Invalid width specification: "+width)}if(fill&&value.length"){value=repeat(fill,width-value.length)+value}else if(align==="^"){left=Math.floor((width-value.length)/2);right=width-left-value.length;value=repeat(fill,left)+value+repeat(fill,right)}else if(align==="="){if(RS_in(value[0],"+- ")){value=value[0]+repeat(fill,width-value.length)+value.slice(1)}else{value=repeat(fill,width-value.length)+value}}else{throw new ValueError("Unrecognized alignment: "+align)}}return value}if(!apply_formatting.__argnames__)Object.defineProperties(apply_formatting,{__argnames__:{value:["value","format_spec"]},__module__:{value:"__main__"}});function parse_markup(markup){var key,transformer,format_spec,pos,state,ch;key=transformer=format_spec="";pos=0;state=0;while(pos=args.length){throw new IndexError("Not enough arguments to match template: "+template)}object=args[typeof idx==="number"&&idx<0?args.length+idx:idx];idx+=1}if(typeof object==="function"){object=object()}ans=""+object;if(format_spec){ans=apply_formatting(ans,format_spec)}return ans}if(!render_markup.__argnames__)Object.defineProperties(render_markup,{__argnames__:{value:["markup"]},__module__:{value:"__main__"}});ans="";pos=0;in_brace=0;markup="";while(pos0){markup+="}"}else{ans+=render_markup(markup)}}else{markup+=ch}}else{if(ch==="{"){if(template[RS_bound_index(pos+1,template)]==="{"){pos+=1;ans+="{"}else{in_brace=1;markup=""}}else{ans+=ch;if(ch==="}"&&template[RS_bound_index(pos+1,template)]==="}"){pos+=1}}}pos+=1}if(in_brace){throw new ValueError("expected '}' before end of string")}return ans};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("capitalize",function(){var RS_anonfunc=function(){var string;string=this;if(string){string=string[0].toUpperCase()+string.slice(1).toLowerCase()}return string};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("center",function(){var RS_anonfunc=function(width,fill){var left,right;left=Math.floor((width-this.length)/2);right=width-left-this.length;fill=fill||" ";return new Array(left+1).join(fill)+this+new Array(right+1).join(fill)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["width","fill"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("count",function(){var RS_anonfunc=function(needle,start,end){var string,RS_unpack,pos,step,ans;string=this;start=start||0;end=end||string.length;if(start<0||end<0){string=string.slice(start,end);RS_unpack=[0,string.length];start=RS_unpack[0];end=RS_unpack[1]}pos=start;step=needle.length;if(!step){return 0}ans=0;while(pos!==-1){pos=string.indexOf(needle,pos);if(pos!==-1){ans+=1;pos+=step}}return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["needle","start","end"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("endswith",function(){var RS_anonfunc=function(suffixes,start,end){var string,q;string=this;start=start||0;if(typeof suffixes==="string"){suffixes=[suffixes]}if(end!==undefined){string=string.slice(0,end)}for(var i=0;i=prefix.length&&prefix===this.slice(start,start+prefix.length)){return true}}return false};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["prefixes","start","end"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("find",function(){var RS_anonfunc=function(needle,start,end){var ans;while(start<0){start+=this.length}ans=this.indexOf(needle,start);if(end!==undefined&&ans!==-1){while(end<0){end+=this.length}if(ans>=end-needle.length){return-1}}return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["needle","start","end"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("rfind",function(){var RS_anonfunc=function(needle,start,end){var ans;while(end<0){end+=this.length}ans=this.lastIndexOf(needle,end-1);if(start!==undefined&&ans!==-1){while(start<0){start+=this.length}if(ans0&&this.toLowerCase()===this.toString()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("isupper",function(){var RS_anonfunc=function(){return this.length>0&&this.toUpperCase()===this.toString()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("isspace",function(){var RS_anonfunc=function(){return this.length>0&&/^\s+$/.test(this)};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("join",function(){var RS_anonfunc=function(iterable){var ans,r;if(Array.isArray(iterable)){return iterable.join(this)}ans="";r=iterable.next();while(!r.done){if(ans){ans+=this}ans+=r.value;r=iterable.next()}return ans};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["iterable"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("ljust",function(){var RS_anonfunc=function(width,fill){var string;string=this;if(width>string.length){fill=fill||" ";string+=new Array(width-string.length+1).join(fill)}return string};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["width","fill"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("rjust",function(){var RS_anonfunc=function(width,fill){var string;string=this;if(width>string.length){fill=fill||" ";string=new Array(width-string.length+1).join(fill)+string}return string};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["width","fill"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("lower",function(){var RS_anonfunc=function(){return this.toLowerCase()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("upper",function(){var RS_anonfunc=function(){return this.toUpperCase()};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("lstrip",function(){var RS_anonfunc=function(chars){var string,pos;string=this;pos=0;chars=chars||RS_str.whitespace;while(chars.indexOf(string[typeof pos==="number"&&pos<0?string.length+pos:pos])!==-1){pos+=1}if(pos){string=string.slice(pos)}return string};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["chars"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("rstrip",function(){var RS_anonfunc=function(chars){var string,pos;string=this;pos=string.length-1;chars=chars||RS_str.whitespace;while(chars.indexOf(string[typeof pos==="number"&&pos<0?string.length+pos:pos])!==-1){pos-=1}if(pos0){count-=1;idx=string.indexOf(old,pos);if(idx===-1){break}pos=idx+repl.length;string=string.slice(0,idx)+repl+string.slice(idx+old.length)}return string};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["old","repl","count"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("split",function(){var RS_anonfunc=function(sep,maxsplit){var split,ans,extra,parts;if(maxsplit===0){return RS_list_decorate([this])}split=RS_orig_split;if(sep===undefined||sep===null){if(maxsplit>0){ans=split(this,/(\s+)/);extra="";parts=[];for(var i=0;i=maxsplit+1){extra+=ans[typeof i==="number"&&i<0?ans.length+i:i]}else if(i%2===0){parts.push(ans[typeof i==="number"&&i<0?ans.length+i:i])}}parts[parts.length-1]+=extra;ans=parts}else{ans=split(this,/\s+/)}}else{if(sep===""){throw new ValueError("empty separator")}ans=split(this,sep);if(maxsplit>0&&ans.length>maxsplit){extra=ans.slice(maxsplit).join(sep);ans=ans.slice(0,maxsplit);ans.push(extra)}}return RS_list_decorate(ans)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["sep","maxsplit"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("rsplit",function(){var RS_anonfunc=function(sep,maxsplit){var split,ans,is_space,pos,current,spc,ch,end,idx;if(!maxsplit){return RS_str.prototype.split.call(this,sep)}split=RS_orig_split;if(sep===undefined||sep===null){if(maxsplit>0){ans=[];is_space=/\s/;pos=this.length-1;current="";while(pos>-1&&maxsplit>0){spc=false;ch=(RS_expr_temp=this)[typeof pos==="number"&&pos<0?RS_expr_temp.length+pos:pos];while(pos>-1&&is_space.test(ch)){spc=true;ch=this[--pos]}if(spc){if(current){ans.push(current);maxsplit-=1}current=ch}else{current+=ch}pos-=1}ans.push(this.slice(0,pos+1)+current);ans.reverse()}else{ans=split(this,/\s+/)}}else{if(sep===""){throw new ValueError("empty separator")}ans=[];pos=end=this.length;while(pos>-1&&maxsplit>0){maxsplit-=1;idx=this.lastIndexOf(sep,pos);if(idx===-1){break}ans.push(this.slice(idx+sep.length,end));pos=idx-1;end=idx}ans.push(this.slice(0,end));ans.reverse()}return RS_list_decorate(ans)};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["sep","maxsplit"]},__module__:{value:"__main__"}});return RS_anonfunc}());define_str_func("splitlines",function(){var RS_anonfunc=function(keepends){var split,parts,ans;split=RS_orig_split;if(keepends){parts=split(this,/((?:\r?\n)|\r)/);ans=[];for(var i=0;istring.length){string=new Array(width-string.length+1).join("0")+string}return string};if(!RS_anonfunc.__argnames__)Object.defineProperties(RS_anonfunc,{__argnames__:{value:["width"]},__module__:{value:"__main__"}});return RS_anonfunc}());RS_str.uchrs=function(){var RS_anonfunc=function(string,with_positions){return function(){var RS_d={};RS_d["_string"]=string;RS_d["_pos"]=0;RS_d[RS_iterator_symbol]=function(){var RS_anonfunc=function(){return this};if(!RS_anonfunc.__module__)Object.defineProperties(RS_anonfunc,{__module__:{value:"__main__"}});return RS_anonfunc}();RS_d["next"]=function(){var RS_anonfunc=function(){var length,pos,value,ans,extra;length=this._string.length;if(this._pos>=length){return function(){var RS_d={};RS_d["done"]=true;return RS_d}.call(this)}pos=this._pos;value=this._string.charCodeAt(this._pos++);ans="�";if(55296<=value&&value<=56319){if(this._pos?@[\\]^_`{|}~";RS_str.printable="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\v\f";RS_str.whitespace=" \t\n\r\v\f";define_str_func=undefined;var str=RS_str,repr=RS_repr; +/*This is a combined, compressed file. Look at https://github.com/BruceSherwood/glowscript for source code and copyright information.*/ +;(function(){})(); \ No newline at end of file diff --git a/package/compiler.3.0.min.js b/package/compiler.3.0.min.js new file mode 100644 index 00000000..817d1bf0 --- /dev/null +++ b/package/compiler.3.0.min.js @@ -0,0 +1,3 @@ +(function(){})();(function(){"use strict";var VPython_import=null;var VPython_names=[];const classpatt=new RegExp("^class\\s+(\\w+)\\s*:");const instpatt=new RegExp("(\\w+)\\s*\\(");const defpatt=new RegExp("^def\\s+(\\w+)\\s*\\(");const asyncpatt1=new RegExp("\\Wfunction\\s*(\\w+)\\s*\\(");const awaitpatt=new RegExp("\\W(\\w+)\\s*\\(");const jsasyncpatt1=new RegExp("\\Wfunction\\s*([\\w.]+)\\s*\\(");var vpfcts=["pause","waitfor","capture"];var fcts=["rate","sleep","get_library","read_local_file"];const string_insert="~!#";var classes=[];var classinstances=[];var classmethods=[];var possibleclasses={};var delim='"';var lineno_string="RS_ls = ";function findrightparen(s){var cnt=0;var i=0;while(i=0){lines[lineno]="";break}else{lines[lineno]="";lineno++}}continue}}line=line.replace(/\s+$/g,"");if(lang=="vpython"&&line.slice(-1)=="\\"){cline=line.slice(0,-1);cindent=indent;continue}m=line.match(print_optionspatt);if(m)line=line.replace(/delete/,"remove");if(lang=="vpython"&&line[0]=="@"){var nextline=lines[lineno+1];m=nextline.match(getline);if(m[2].slice(0,3)=="def"||m[2].slice(0,6)=="module"){decoration=line;indent=m[1];line=m[2];lineno++}else{continue}}if(line.length===0)continue;prebraces=braces;if(lang=="vpython"){if(classindent===indent.length)classindent=-1;if(line.match(classpatt))classindent=indent.length}else{line=" "+line}var w=line.split(" ");if(lang=="vpython"&&w.indexOf("import")>-1){if(w.indexOf("random")>-1){newprogram+=" "+indent+line+"\n";continue}if(VPython_import===null)VPython_names=[];if(w[1]=="__future__")continue;if(w[1]=="visual.factorial")continue;if(w[0]=="from"&&w[2]=="import"&&w.length>=4){if(w[1]=="visual.graph"){if(w[3]=="*")continue;return'ERROR: Currently only "from visual.graph import *" is supported, line '+(lineno+2)+": "+lines[lineno]}if(!(w[1]=="vpython"||w[1]=="visual"||w[1]=="vis")){throw new Error("Line "+(lineno+1)+": cannot import from "+w[1])}if(VPython_import===null){if(w[3]=="*")continue;VPython_import=w[1];for(var j=3;j0&&w[j]!=","){if(w[j].slice(-1)==",")w[j]=w[j].slice(0,-1);if(w[j]==" "||w[j]=="("||w[j]==")"||w[j][0]=="("||w[j][-1]==")")continue;VPython_names.push(w[j])}}if(VPython_names.indexOf("canvas")==-1)VPython_names.push("canvas")}continue}else if(w[0]=="import"&&w.length==2){if(w[1]=="visual.graph")return'ERROR: Currently only "from visual.graph import *" is supported, line '+(lineno+1)+": "+lines[lineno];if(!(w[1]=="vpython"||w[1]=="visual"||w[1]=="vis"))return"ERROR: Cannot import from "+w[1]+", line "+(lineno+1)+": "+lines[lineno];if(VPython_import===null){VPython_import=w[1]}continue}else if(w[0]=="import"){if(w[1]=="vpython"||w[1]=="visual"||w[1]=="vis"){if(w.length==4&&w[2]=="as"){VPython_import=w[3];continue}else return"ERROR: improper import statement, line "+(lineno+1)+": "+lines[lineno]}else{return"ERROR: Cannot import from "+w[1]+", line "+(lineno+1)+": "+lines[lineno]}}}singlequote=false;doublequote=false;triplequote=false;backquote=false;var backslash=false;var string_bounds=[];var previouscontinuedline=continuedline;var processedtriplequote=false;var fstring=false;for(var i=0;i0&&line[i-1]=="\\")break;if(parens===0)lastleftparens=lineno;parens++;break;case")":if(i>0&&line[i-1]=="\\")break;parens--;if(indef&&parens==0)indef=false;break;case"[":if(i>0&&line[i-1]=="\\")break;if(brackets===0)lastleftbracket=lineno;brackets++;break;case"]":if(i>0&&line[i-1]=="\\")break;brackets--;break;case"{":if(i>0&&line[i-1]=="\\")break;if(braces===0)lastleftbrace=lineno;braces++;break;case"}":if(i>0&&line[i-1]=="\\")break;braces--;break}if(char=="\\"){if(i==line.length-1||line[i+1]==" "||line[i+1]=="#")line=line.slice(0,i);backslash=true;break}}continuedline=!indef&&(backslash||parens>0||brackets>0||braces>0);if(!previousquote){if(lang=="vpython"){var m=pickpatt.exec(line+" ");if(m){if(m[2]!="("&&m[2].search(/\w/)!=0){var i=m.index;line=line.slice(0,i)+".pick()"+line.slice(i+5)}}}}if(line.search("input")>=0||line.search("winput")>=0){newprogram+=" "+indent+"sleep(0.2)\n"}function instring(n){for(var sb of string_bounds){if(n>=sb[0]&&n<=sb[1]&&!sb[2])return true}return false}if(lang=="vpython"){c="";if(indent.length0){prepend=" "+c+" "+indent+decoration+"\n";prepend=" "+indent}else{prepend=" "+c+" "+indent}}start=0;while(true){var m=line.slice(start).match(awaitpatt);if(m!==null){start+=m.index;var ins=instring(start);if(ins){line=line.slice(0,start+1+m[1].length)+string_insert+line.slice(start+1+m[1].length);start+=string_insert.length}start+=m[1].length+1}else break}var start=0;var inst,cls,m1=null,m2=null,m3=null,m4=null,m5=null,m6=null,m7=null,m8=null;var declaration=false;var pre="";var newline="";const methodassignpatt=new RegExp("^(\\w+)\\s*=\\s*(\\w+)\\.(\\w+)$");const assignpatt=new RegExp("^(\\w+)\\s*=\\s*(\\w+)\\s*");m1=line.match(defpatt);if(m1===null)m2=line.match(classpatt);if(m2===null)m3=line.match(methodassignpatt);if(m3===null)m4=line.match(assignpatt);if(m1!==null){var ns=start+m1.index+m1[1].length+1;if(instring(ns)){line=line.slice(0,ns)+string_insert+line.slice(ns)}else{if(indent.length===0||classindent===-1)fcts.push(m1[1]);else if(classindent>=0&&indent.length>classindent)classmethods.push(m1[1])}declaration=true}else if(m2!==null){classes.push(m2[1]);declaration=true}else if(m3!==null){if(classinstances.indexOf(m3[2])>=0&&classmethods.indexOf(m3[3])>=0)classmethods.push(m3[1])}else if(m4!==null){var p=m4[1];var f=m4[2];if(line[m4[0].length]=="("){var end=findrightparen(line.slice(m4[0].length));if(end!==null&&m4[0].length+end+1==line.length){if(classes.indexOf(f)>=0)classinstances.push(p);else if(classmethods.indexOf(f)>=0)classmethods.push(p);else if(fcts.indexOf(f)>=0)fcts.push(p)}}}start=0;const bindmethodpatt=new RegExp("(\\w+)\\.(\\w+)\\s*");while(true){m=line.slice(start).match(bindmethodpatt);if(m===null)break;if(classinstances.indexOf(m[1])>=0&&classmethods.indexOf(m[2])>=0&&(start+m.index+m[0].length>=line.length||line[start+m.index+m[0].length]!="(")){line=line.slice(0,start+m.index)+line.slice(start+m.index).replace(m[2],m[2]+".bind("+m[1]+")");start+=m.index+m[0].length+m[1].length+7}else start+=m.index+m[0].length}if(!declaration){const leftpatt=new RegExp("^(\\w+)\\s*=\\s*");var left=null,right=line;m=line.match(leftpatt);if(m!==null){left=m[1];right=line.slice(m[0].length)}start=0;while(true){var n=0;m=line.slice(start).match(instpatt);if(m===null){if(pre.length>0)newline+=line.slice(start);break}cls=m[1];var leftparen=start+m.index+m[1].length;if(classes.indexOf(cls)>=0){var p=1;var i=leftparen+1;while(true){var char=line[i];if(char=="(")p+=1;else if(char==")"){p-=1;if(p===0)break}i+=1;if(i>line.length)break}if(i>line.length)break;n+=1;pre+="_GS_"+n+" = "+cls+"(); _GS_"+n+".__init__"+line.slice(leftparen,i+1)+"; ";newline+=line.slice(start,leftparen-m[1].length)+"_GS_"+n;start=i+1}else{newline+=line.slice(start,leftparen);start=leftparen}}}if(pre.length>0)line=pre+newline;newprogram+=prepend+line+"\n"}lastindent=indent;if(parens<0)return"ERROR: Too many right parentheses, line "+(lineno+1)+": "+lines[lineno];if(brackets<0)return"ERROR: Too many right brackets, line "+(lineno+1)+": "+lines[lineno];if(braces<0)return"ERROR: Too many right braces, line "+(lineno+1)+": "+lines[lineno]}if(parens>0)return"ERROR: Missing right parenthesis, see line "+(lastleftparens+2)+": "+lines[lastleftparens];else if(brackets>0)return"ERROR: Missing right bracket, see line "+(lastleftbracket+2)+": "+lines[lastleftbracket];else if(braces>0)return"ERROR: Missing right brace, see line "+(lastleftbrace+2)+": "+lines[lastleftbrace];return newprogram}var linenopatt=/"(\d*)"/;var RS_compiler;function compile_rapydscript(rs_input){if(rs_input.slice(0,7)=="ERROR: "){throw new Error(rs_input.slice(7))}else{if(RS_compiler===undefined)RS_compiler=RapydScript.create_embedded_compiler();rs_input+="\n";try{var output=RS_compiler.compile(rs_input,{js_version:6});return output.toString()}catch(err){if(err.line===undefined){throw new Error(err.message)}else{var lines=rs_input.split("\n");var L=lines[err.line];var m=L.match(linenopatt);if(m!==null){throw new Error(err.message+"; line "+m[1]+": "+lines[err.line+1])}else{throw new Error(err.message+": "+lines[err.line])}}}}}var vp_primitives=["box","sphere","simple_sphere","cylinder","pyramid","cone","helix","ellipsoid","ring","arrow","compound"];var vp_other=["canvas","vec","vector","rate","sleep","update","color","extrusion","paths","shapes","vertex","triangle","quad","label","distant_light","local_light","attach_trail","attach_arrow","sqrt","pi","abs","sin","cos","tan","asin","acos","atan","atan2","exp","log","pow","factorial","combin","button","radio","checkbox","slider","checkbox","text","radians","degrees","get_library","read_local_file"];function compile(program,options){options=options||{};window.__original={text:program.split("\n")};window.__GSlang=options.lang;var version='["'+options.version+'", "glowscript"]';var findtext=/[^\.\w]text[\ ]*\(/;var findstart=/^text[\ ]*\(/;var loadfonts=findtext.exec(program);if(!loadfonts)loadfonts=findstart.exec(program);program=program.replace(/\.delete/g,".remove");function pop_replace(m,p1,p2){if(p2.length===0)return m;else return".py"+m.slice(1)}var endprog;if(options.lang=="vpython"){program=preprocess(program,options.lang);var vars="";if(program.slice(0,7)=="ERROR: "){compile_rapydscript(program)}else{var prog;program=program.replace(/(\.pop\s*\(\s*)([^)]*)/g,pop_replace);program=program.replace(/\.sort\s*\(/g,".pysort(");prog="def __main__():\n version = "+version+"\n";prog+=" window.__GSlang = 'vpython'\n";if(VPython_import===null){prog+=" display=canvas\n vector=vec\n"}else if(VPython_names.length>0){vars+=" vector=vec\n";for(var i=0;i=0)vars+=" "+name+"="+name+"\n";else vars+=" "+name+"=undefined\n"}var hasvector=VPython_names.indexOf("vector")>=0;for(var i=0;i0)prog+=" scene = canvas()\n";else prog+=" scene = "+VPython_import+".canvas()\n";prog+=" from pythonize import strings\n";prog+=" strings()\n";endprog=prog.length;prog+=program;program=compile_rapydscript(prog);var start=program.indexOf("window.__GSlang");var arr="Array.prototype['+'] = function(r) {return this.concat(r)}\n";arr+=" Array.prototype['*'] = function(r) {return __array_times_number(this, r)}\n";if(VPython_names.length<=0)arr+=vars;program=program.slice(0,start)+arr+program.slice(start-4)}}else{var p="function __main__() {\n";p+="var version = "+version+";\n";p+="Array.prototype.toString = function() { return __parsearray(this) };\n";p+="var scene = canvas();\nvar vector = vec;\n";program=p+program+"\n}"}program=program.replace("function __main__() {",'async function __main__() {\n"use strict";\n');var start=program.indexOf("async function __main__()");var prog=program.slice(start);prog=papercompile(prog);prog=program.slice(0,start)+prog;prog=";\n"+prog;if(options.lang=="vpython"){const classproto=new RegExp("\\w+\\.prototype\\."+lineno_string+'"\\w+";',"g");prog=prog.replace(classproto,"");var start,m,name;var initialstart=prog.search(lineno_string);start=initialstart;while(true){if(options.lang=="vpython")m=prog.slice(start).match(asyncpatt1);m=prog.slice(start).match(asyncpatt1);if(m===null)break;name=m[1];if(classes.indexOf(name)>=0){start+=m[0].length;continue}prog=prog.slice(0,start+m.index+1)+"async function "+name+string_insert+prog.slice(start+m.index+m[0].length-1);start+=m.index+"async function ".length+m[1].length+string_insert.length+1}start=initialstart;while(true){m=prog.slice(start).match(awaitpatt);var period=false;if(m===null)break;period=prog[start+m.index]==".";name=m[1];if(options.lang=="vpython"&&!period&&classes.indexOf(name)>=0){start+=m.index+name.length+1;var lbrace=prog.slice(start).search("{");var rbrace=prog.slice(start).search("arguments");prog=prog.slice(0,start+lbrace+1)+prog.slice(start+"arguments".length+rbrace+1);continue}if(name.slice(0,3)=="RS_"){start+=m.index+name.length+1;continue}var ptr=start+m.index+1;var brackets=0;var parens=0;while(true){ptr--;if(prog[ptr]=="]"){brackets--}else if(prog[ptr]=="["){if(brackets===0)break;brackets++}else if(prog[ptr]==")"){parens--}else if(prog[ptr]=="("){if(parens===0)break;parens++}if(prog[ptr]==" "){if(brackets===0&&parens===0)break}}var pstart=ptr+1;var prefix="";if(period){prefix=prog.slice(pstart,start+m.index)}if(options.lang=="vpython"&&period&&classinstances.indexOf(prefix)<0&&name=="replace"){prog=prog.slice(0,start+m.index+1)+"__GSrep"+prog.slice(start+m.index+name.length+1);start+=m.index+name.length+1;continue}var no_await=["if","elif","return","for","while","function","else","dict","float","hex","int","iter","len","list","vec","vector","oct","ord","print","range","arange","update","print","GSprint","clock","msclock","canvas","graph","gcurve","gdots","gvbars","ghbars","rotate","box","cylinder","cone","pyramid","sphere","simple_sphere","arrow","curve","points","paths","shapes","helix","ring","compound","vertex","triangle","quad","label","distant_light","local_light","attach_trail","attach_arrow","text","extrusion","wtext","winput","radio","checkbox","button","slider","menu","input","mag","mag2","norm","hat","dot","cross","proj","diff_angle","GS_power","abs","sin","cos","tan","asin","acos","atan","atan2","exp","log","pow","sqrt","ceil","floor","sign","round","max","min","random","factorial","combin"];var no_await2=["remove","select","append_to_title","append_to_caption","bind","unbind","call","rgb_to_hsv","hsv_to_rgb","mag","mag2","norm","hat","rotate","random","pow","format","trigger","follow","defineProperties","textures","bumpmaps"];if(period&&prefix=="self"||!period&&fcts.indexOf(name)>=0||period&&classes.indexOf(prefix)>=0&&classmethods.indexOf(name)>=0||!period&&classmethods.indexOf(name)>=0||!period&&classes.indexOf(name)>=0||period&&classinstances.indexOf(prefix)<0&&vpfcts.indexOf(name)>=0||period&&prefix==VPython_import&&fcts.indexOf(name)>=0&&fcts.indexOf(name)<4||period&&no_await2.indexOf(name)<0||!period&&no_await.indexOf(name)<0||!period&&no_await.indexOf(name)<0&&no_await2.indexOf(name)<0&&fcts.indexOf(name)<0){}else{start+=m.index+name.length+1;continue}if(options.lang=="vpython"&&prog.slice(pstart,start+m.index).search("RS_")>=0){start+=m.index+name.length+1;continue}var prepend="(";while(prog[ptr]==" ")ptr--;if(prog[ptr]=="\n"){prepend=";("}var temp=start+m.index+name.length+1;var pend=findrightparen(prog.slice(temp));pend+=temp;var pst=pstart;if(prog[pstart]=="!"){if(prepend=="(")prepend="!(";else prepend=";!(";pstart++}prog=prog.slice(0,pst)+prepend+"await "+prog.slice(pstart,pend)+")"+prog.slice(pend);start+=m.index+name.length+prepend.length+6}}program=prog.replace(/\n\n\n\n/g,"");program=program.replace(new RegExp(lineno_string,"g"),"");program=program.replace(new RegExp("\\n\\s*var RS_ls;","g"),"");program=program.replace(new RegExp(string_insert,"g"),"");program=program.replace(/Math.pow/g,"GS_power");if(loadfonts){var s="scene = canvas();\n";var sc=program.indexOf(s)+s.length;s=" fontloading();\n await waitforfonts();\n";program=program.slice(0,sc)+s+program.slice(sc,program.length)}return program}window.glowscript_compile=compile})();(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global=global||self,factory(global.acorn={}))})(this,function(exports){"use strict";var reservedWords={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var keywords={5:ecma5AndLessKeywords,"5module":ecma5AndLessKeywords+" export import",6:ecma5AndLessKeywords+" const class extends export import super"};var keywordRelationalOperator=/^in(stanceof)?$/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࢽऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿯ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-Ᶎꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭧꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");nonASCIIidentifierStartChars=nonASCIIidentifierChars=null;var astralIdentifierStartCodes=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,477,28,11,0,9,21,155,22,13,52,76,44,33,24,27,35,30,0,12,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,0,33,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,0,161,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,270,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,754,9486,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42710,42,4148,12,221,3,5761,15,7472,3104,541];var astralIdentifierCodes=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,525,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,4,9,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,232,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,19723,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,792487,239];function isInAstralSet(code,set){var pos=65536;for(var i=0;icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name,prec){return new TokenType(name,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords$1={};function kw(name,options){if(options===void 0)options={};options.keyword=name;return keywords$1[name]=new TokenType(name,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){for(var v=options.ecmaVersion;;v--){if(reserved=reservedWords[v]){break}}if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types.eof;this.value=null;this.start=this.end=this.pos;this.startLoc=this.endLoc=this.curPosition();this.lastTokEndLoc=this.lastTokStartLoc=null;this.lastTokStart=this.lastTokEnd=this.pos;this.context=this.initialContext();this.exprAllowed=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true}};Parser.prototype.parse=function parse(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};Parser.prototype.inNonArrowFunction=function inNonArrowFunction(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types._import?this.parseImport(node):this.parseExport(node,exports);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}this.toAssignable(init,false,refDestructuringErrors);this.checkLVal(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$1.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLVal(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$1.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind:kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(!this.eat(types.braceR)){var stmt=this.parseStatement(null);node.body.push(stmt)}if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}else if(init.type==="AssignmentPattern"){this.raise(init.start,"Invalid left-hand side in for-loop")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types.comma)){break}}return node};pp$1.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLVal(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLVal(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(!this.eat(types.braceR)){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}}}node.body=this.finishNode(classBody,"ClassBody");this.strict=oldStrict;return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLVal(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports){this.next();if(this.eat(types.star)){this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports,"default",this.lastTokStart);var isAsync;if(this.type===types._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports,node.declaration.declarations)}else{this.checkExport(exports,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports);if(this.eatContextual("from")){if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value=this.value;node=this.parseLiteral(value.value);node.regex={pattern:value.pattern,flags:value.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.parseExprImport=function(){var node=this.startNode();this.next();switch(this.type){case types.parenL:return this.parseDynamicImport(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.parseLiteral=function(value){var node=this.startNode();node.value=value;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1)}this.next();return this.finishNode(node,"Literal")};pp$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"||containsEsc){this.raiseRecoverable(node.property.start,"The only valid meta property for new is new.target")}if(!this.inNonArrowFunction()){this.raiseRecoverable(node.start,"new.target can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref){var isTagged=ref.isTagged;var elem=this.startNode();if(this.type===types.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.parseTemplate=function(ref){if(ref===void 0)ref={};var isTagged=ref.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged:isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged:isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types.comma&&this.type!==types.braceR)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else if(this.type===types.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,prop.key)}else{prop.value=prop.key}prop.shorthand=true}else{this.unexpected()}};pp$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$3.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));node.body=this.parseBlock(false);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope();if(this.strict&&node.id){this.checkLVal(node.id,BIND_OUTSIDE)}this.strict=oldStrict};pp$3.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name)>-1||scope.var.indexOf(name)>-1;scope.lexical.push(name);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name)>-1}else{redeclared=scope$2.lexical.indexOf(name)>-1||scope$2.var.indexOf(name)>-1}scope$2.functions.push(name)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name)>-1){redeclared=true;break}scope$3.var.push(name);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name+"' has already been declared")}};pp$5.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};var TokContext=function TokContext(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,function(p){return p.tryReadTemplateToken()}),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat){return true}if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr)){return!parent.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types.semi&&prevType!==types._else&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};var ecma9BinaryProperties="ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties};var unicodeGeneralCategoryValues="Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";var ecma9ScriptValues="Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=11?11:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i){var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!this.switchU||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i){var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!this.switchU||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(){return this.at(this.pos)};RegExpValidationState.prototype.lookahead=function lookahead(){return this.at(this.nextIndex(this.pos))};RegExpValidationState.prototype.advance=function advance(){this.pos=this.nextIndex(this.pos)};RegExpValidationState.prototype.eat=function eat(ch){if(this.current()===ch){this.advance();return true}return false};function codePointToString(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.validateRegExpFlags=function(state){var validFlags=state.validFlags;var flags=state.flags;for(var i=0;i-1){this.raise(state.start,"Duplicate regular expression flag")}}};pp$8.validateRegExpPattern=function(state){this.regexp_pattern(state);if(!state.switchN&&this.options.ecmaVersion>=9&&state.groupNames.length>0){state.switchN=true;this.regexp_pattern(state)}};pp$8.regexp_pattern=function(state){state.pos=0;state.lastIntValue=0;state.lastStringValue="";state.lastAssertionIsQuantifiable=false;state.numCapturingParens=0;state.maxBackReference=0;state.groupNames.length=0;state.backReferenceNames.length=0;this.regexp_disjunction(state);if(state.pos!==state.source.length){if(state.eat(41)){state.raise("Unmatched ')'")}if(state.eat(93)||state.eat(125)){state.raise("Lone quantifier brackets")}}if(state.maxBackReference>state.numCapturingParens){state.raise("Invalid escape")}for(var i=0,list=state.backReferenceNames;i=9){lookbehind=state.eat(60)}if(state.eat(61)||state.eat(33)){this.regexp_disjunction(state);if(!state.eat(41)){state.raise("Unterminated group")}state.lastAssertionIsQuantifiable=!lookbehind;return true}}state.pos=start;return false};pp$8.regexp_eatQuantifier=function(state,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state,noError)){state.eat(63);return true}return false};pp$8.regexp_eatQuantifierPrefix=function(state,noError){return state.eat(42)||state.eat(43)||state.eat(63)||this.regexp_eatBracedQuantifier(state,noError)};pp$8.regexp_eatBracedQuantifier=function(state,noError){var start=state.pos;if(state.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state)){min=state.lastIntValue;if(state.eat(44)&&this.regexp_eatDecimalDigits(state)){max=state.lastIntValue}if(state.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state)}else if(state.current()===63){state.raise("Invalid group")}this.regexp_disjunction(state);if(state.eat(41)){state.numCapturingParens+=1;return true}state.raise("Unterminated group")}return false};pp$8.regexp_eatExtendedAtom=function(state){return state.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state)||this.regexp_eatCharacterClass(state)||this.regexp_eatUncapturingGroup(state)||this.regexp_eatCapturingGroup(state)||this.regexp_eatInvalidBracedQuantifier(state)||this.regexp_eatExtendedPatternCharacter(state)};pp$8.regexp_eatInvalidBracedQuantifier=function(state){if(this.regexp_eatBracedQuantifier(state,true)){state.raise("Nothing to repeat")}return false};pp$8.regexp_eatSyntaxCharacter=function(state){var ch=state.current();if(isSyntaxCharacter(ch)){state.lastIntValue=ch;state.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$8.regexp_eatPatternCharacters=function(state){var start=state.pos;var ch=0;while((ch=state.current())!==-1&&!isSyntaxCharacter(ch)){state.advance()}return state.pos!==start};pp$8.regexp_eatExtendedPatternCharacter=function(state){var ch=state.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state.advance();return true}return false};pp$8.regexp_groupSpecifier=function(state){if(state.eat(63)){if(this.regexp_eatGroupName(state)){if(state.groupNames.indexOf(state.lastStringValue)!==-1){state.raise("Duplicate capture group name")}state.groupNames.push(state.lastStringValue);return}state.raise("Invalid group")}};pp$8.regexp_eatGroupName=function(state){state.lastStringValue="";if(state.eat(60)){if(this.regexp_eatRegExpIdentifierName(state)&&state.eat(62)){return true}state.raise("Invalid capture group name")}return false};pp$8.regexp_eatRegExpIdentifierName=function(state){state.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state)){state.lastStringValue+=codePointToString(state.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state)){state.lastStringValue+=codePointToString(state.lastIntValue)}return true}return false};pp$8.regexp_eatRegExpIdentifierStart=function(state){var start=state.pos;var ch=state.current();state.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state)){ch=state.lastIntValue}if(isRegExpIdentifierStart(ch)){state.lastIntValue=ch;return true}state.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$8.regexp_eatRegExpIdentifierPart=function(state){var start=state.pos;var ch=state.current();state.advance();if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state)){ch=state.lastIntValue}if(isRegExpIdentifierPart(ch)){state.lastIntValue=ch;return true}state.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$8.regexp_eatAtomEscape=function(state){if(this.regexp_eatBackReference(state)||this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)||state.switchN&&this.regexp_eatKGroupName(state)){return true}if(state.switchU){if(state.current()===99){state.raise("Invalid unicode escape")}state.raise("Invalid escape")}return false};pp$8.regexp_eatBackReference=function(state){var start=state.pos;if(this.regexp_eatDecimalEscape(state)){var n=state.lastIntValue;if(state.switchU){if(n>state.maxBackReference){state.maxBackReference=n}return true}if(n<=state.numCapturingParens){return true}state.pos=start}return false};pp$8.regexp_eatKGroupName=function(state){if(state.eat(107)){if(this.regexp_eatGroupName(state)){state.backReferenceNames.push(state.lastStringValue);return true}state.raise("Invalid named reference")}return false};pp$8.regexp_eatCharacterEscape=function(state){return this.regexp_eatControlEscape(state)||this.regexp_eatCControlLetter(state)||this.regexp_eatZero(state)||this.regexp_eatHexEscapeSequence(state)||this.regexp_eatRegExpUnicodeEscapeSequence(state)||!state.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state)||this.regexp_eatIdentityEscape(state)};pp$8.regexp_eatCControlLetter=function(state){var start=state.pos;if(state.eat(99)){if(this.regexp_eatControlLetter(state)){return true}state.pos=start}return false};pp$8.regexp_eatZero=function(state){if(state.current()===48&&!isDecimalDigit(state.lookahead())){state.lastIntValue=0;state.advance();return true}return false};pp$8.regexp_eatControlEscape=function(state){var ch=state.current();if(ch===116){state.lastIntValue=9;state.advance();return true}if(ch===110){state.lastIntValue=10;state.advance();return true}if(ch===118){state.lastIntValue=11;state.advance();return true}if(ch===102){state.lastIntValue=12;state.advance();return true}if(ch===114){state.lastIntValue=13;state.advance();return true}return false};pp$8.regexp_eatControlLetter=function(state){var ch=state.current();if(isControlLetter(ch)){state.lastIntValue=ch%32;state.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$8.regexp_eatRegExpUnicodeEscapeSequence=function(state){var start=state.pos;if(state.eat(117)){if(this.regexp_eatFixedHexDigits(state,4)){var lead=state.lastIntValue;if(state.switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state.pos;if(state.eat(92)&&state.eat(117)&&this.regexp_eatFixedHexDigits(state,4)){var trail=state.lastIntValue;if(trail>=56320&&trail<=57343){state.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state.pos=leadSurrogateEnd;state.lastIntValue=lead}return true}if(state.switchU&&state.eat(123)&&this.regexp_eatHexDigits(state)&&state.eat(125)&&isValidUnicode(state.lastIntValue)){return true}if(state.switchU){state.raise("Invalid unicode escape")}state.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$8.regexp_eatIdentityEscape=function(state){if(state.switchU){if(this.regexp_eatSyntaxCharacter(state)){return true}if(state.eat(47)){state.lastIntValue=47;return true}return false}var ch=state.current();if(ch!==99&&(!state.switchN||ch!==107)){state.lastIntValue=ch;state.advance();return true}return false};pp$8.regexp_eatDecimalEscape=function(state){state.lastIntValue=0;var ch=state.current();if(ch>=49&&ch<=57){do{state.lastIntValue=10*state.lastIntValue+(ch-48);state.advance()}while((ch=state.current())>=48&&ch<=57);return true}return false};pp$8.regexp_eatCharacterClassEscape=function(state){var ch=state.current();if(isCharacterClassEscape(ch)){state.lastIntValue=-1;state.advance();return true}if(state.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state.lastIntValue=-1;state.advance();if(state.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state)&&state.eat(125)){return true}state.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$8.regexp_eatUnicodePropertyValueExpression=function(state){var start=state.pos;if(this.regexp_eatUnicodePropertyName(state)&&state.eat(61)){var name=state.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state)){var value=state.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state,name,value);return true}}state.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state)){var nameOrValue=state.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state,nameOrValue);return true}return false};pp$8.regexp_validateUnicodePropertyNameAndValue=function(state,name,value){if(!has(state.unicodeProperties.nonBinary,name)){state.raise("Invalid property name")}if(!state.unicodeProperties.nonBinary[name].test(value)){state.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state,nameOrValue){if(!state.unicodeProperties.binary.test(nameOrValue)){state.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state.current())){state.lastStringValue+=codePointToString(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state.current())){state.lastStringValue+=codePointToString(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state){return this.regexp_eatUnicodePropertyValue(state)};pp$8.regexp_eatCharacterClass=function(state){if(state.eat(91)){state.eat(94);this.regexp_classRanges(state);if(state.eat(93)){return true}state.raise("Unterminated character class")}return false};pp$8.regexp_classRanges=function(state){while(this.regexp_eatClassAtom(state)){var left=state.lastIntValue;if(state.eat(45)&&this.regexp_eatClassAtom(state)){var right=state.lastIntValue;if(state.switchU&&(left===-1||right===-1)){state.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state.raise("Range out of order in character class")}}}};pp$8.regexp_eatClassAtom=function(state){var start=state.pos;if(state.eat(92)){if(this.regexp_eatClassEscape(state)){return true}if(state.switchU){var ch$1=state.current();if(ch$1===99||isOctalDigit(ch$1)){state.raise("Invalid class escape")}state.raise("Invalid escape")}state.pos=start}var ch=state.current();if(ch!==93){state.lastIntValue=ch;state.advance();return true}return false};pp$8.regexp_eatClassEscape=function(state){var start=state.pos;if(state.eat(98)){state.lastIntValue=8;return true}if(state.switchU&&state.eat(45)){state.lastIntValue=45;return true}if(!state.switchU&&state.eat(99)){if(this.regexp_eatClassControlLetter(state)){return true}state.pos=start}return this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)};pp$8.regexp_eatClassControlLetter=function(state){var ch=state.current();if(isDecimalDigit(ch)||ch===95){state.lastIntValue=ch%32;state.advance();return true}return false};pp$8.regexp_eatHexEscapeSequence=function(state){var start=state.pos;if(state.eat(120)){if(this.regexp_eatFixedHexDigits(state,2)){return true}if(state.switchU){state.raise("Invalid escape")}state.pos=start}return false};pp$8.regexp_eatDecimalDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isDecimalDigit(ch=state.current())){state.lastIntValue=10*state.lastIntValue+(ch-48);state.advance()}return state.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$8.regexp_eatHexDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isHexDigit(ch=state.current())){state.lastIntValue=16*state.lastIntValue+hexToInt(ch);state.advance()}return state.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$8.regexp_eatLegacyOctalEscapeSequence=function(state){if(this.regexp_eatOctalDigit(state)){var n1=state.lastIntValue;if(this.regexp_eatOctalDigit(state)){var n2=state.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state)){state.lastIntValue=n1*64+n2*8+state.lastIntValue}else{state.lastIntValue=n1*8+n2}}else{state.lastIntValue=n1}return true}return false};pp$8.regexp_eatOctalDigit=function(state){var ch=state.current();if(isOctalDigit(ch)){state.lastIntValue=ch-48;state.advance();return true}state.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$8.regexp_eatFixedHexDigits=function(state,length){var start=state.pos;state.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp$9.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types.assign,size+1)}return this.finishOp(types.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 63:++this.pos;return this.finishToken(types.question);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 126:return this.finishOp(types.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state=this.regexpState||(this.regexpState=new RegExpValidationState(this));state.reset(start,pattern,flags);this.validateRegExpFlags(state);this.validateRegExpPattern(state);var value=null;try{value=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types.regexp,{pattern:pattern,flags:flags,value:value})};pp$9.readInt=function(radix,len){var start=this.pos,total=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}++this.pos;total=total*radix+val}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};pp$9.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=typeof BigInt!=="undefined"?BigInt(this.input.slice(start,this.pos)):null;++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val)};pp$9.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var str$1=this.input.slice(start,this.pos);var val$1=typeof BigInt!=="undefined"?BigInt(str$1):null;++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var str=this.input.slice(start,this.pos);var val=octal?parseInt(str,8):parseFloat(str);return this.finishToken(types.num,val)};pp$9.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else{if(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp$9.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp$9.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos=0||num<0&&parseInt(num)===num}var binaryOperators={"+":"add","-":"sub","*":"multiply","/":"divide","%":"modulo",">":"greater",">=":"greaterorequal","<":"less","<=":"lessorequal","+=":"plusequal","-=":"minusequal","*=":"timesequal","/=":"divideequal"};var unaryOperators={"-":"negate","+":"plus"};function papercompile(code){var insertions=[];function getOffset(offset){for(var i=0,l=insertions.length;i=offset)break;offset+=insertion[1]}return offset}function getCode(node){return code.substring(getOffset(node.range[0]),getOffset(node.range[1]))}function replaceCode(node,str){var start=getOffset(node.range[0]),end=getOffset(node.range[1]);var insert=0;for(var i=insertions.length-1;i>=0;i--){if(start>insertions[i][0]){insert=i+1;break}}insertions.splice(insert,0,[start,str.length-end+start]);code=code.substring(0,start)+str+code.substring(end)}function walkAST(node,parent){if(!node)return;for(var key in node){if(key==="range")continue;var value=node[key];if(Array.isArray(value)){for(var i=0,l=value.length;i=9?["wheel"]:["mousewheel","DomMouseScroll","MozMousePixelScroll"],slice=Array.prototype.slice,nullLowestDeltaTimeout,lowestDelta;if($.event.fixHooks){for(var i=toFix.length;i;){$.event.fixHooks[toFix[--i]]=$.event.mouseHooks}}var special=$.event.special.mousewheel={version:"3.1.11",setup:function(){if(this.addEventListener){for(var i=toBind.length;i;){this.addEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=handler}$.data(this,"mousewheel-line-height",special.getLineHeight(this));$.data(this,"mousewheel-page-height",special.getPageHeight(this))},teardown:function(){if(this.removeEventListener){for(var i=toBind.length;i;){this.removeEventListener(toBind[--i],handler,false)}}else{this.onmousewheel=null}$.removeData(this,"mousewheel-line-height");$.removeData(this,"mousewheel-page-height")},getLineHeight:function(elem){var $parent=$(elem)["offsetParent"in $.fn?"offsetParent":"parent"]();if(!$parent.length){$parent=$("body")}return parseInt($parent.css("fontSize"),10)},getPageHeight:function(elem){return $(elem).height()},settings:{adjustOldDeltas:true,normalizeOffset:true}};$.fn.extend({mousewheel:function(fn){return fn?this.bind("mousewheel",fn):this.trigger("mousewheel")},unmousewheel:function(fn){return this.unbind("mousewheel",fn)}});function handler(event){var orgEvent=event||window.event,args=slice.call(arguments,1),delta=0,deltaX=0,deltaY=0,absDelta=0,offsetX=0,offsetY=0;event=$.event.fix(orgEvent);event.type="mousewheel";if("detail"in orgEvent){deltaY=orgEvent.detail*-1}if("wheelDelta"in orgEvent){deltaY=orgEvent.wheelDelta}if("wheelDeltaY"in orgEvent){deltaY=orgEvent.wheelDeltaY}if("wheelDeltaX"in orgEvent){deltaX=orgEvent.wheelDeltaX*-1}if("axis"in orgEvent&&orgEvent.axis===orgEvent.HORIZONTAL_AXIS){deltaX=deltaY*-1;deltaY=0}delta=deltaY===0?deltaX:deltaY;if("deltaY"in orgEvent){deltaY=orgEvent.deltaY*-1;delta=deltaY}if("deltaX"in orgEvent){deltaX=orgEvent.deltaX;if(deltaY===0){delta=deltaX*-1}}if(deltaY===0&&deltaX===0){return}if(orgEvent.deltaMode===1){var lineHeight=$.data(this,"mousewheel-line-height");delta*=lineHeight;deltaY*=lineHeight;deltaX*=lineHeight}else if(orgEvent.deltaMode===2){var pageHeight=$.data(this,"mousewheel-page-height");delta*=pageHeight;deltaY*=pageHeight;deltaX*=pageHeight}absDelta=Math.max(Math.abs(deltaY),Math.abs(deltaX));if(!lowestDelta||absDelta=1?"floor":"ceil"](delta/lowestDelta);deltaX=Math[deltaX>=1?"floor":"ceil"](deltaX/lowestDelta);deltaY=Math[deltaY>=1?"floor":"ceil"](deltaY/lowestDelta);if(special.settings.normalizeOffset&&this.getBoundingClientRect){var boundingRect=this.getBoundingClientRect();offsetX=event.clientX-boundingRect.left;offsetY=event.clientY-boundingRect.top}event.deltaX=deltaX;event.deltaY=deltaY;event.deltaFactor=lowestDelta;event.offsetX=offsetX;event.offsetY=offsetY;event.deltaMode=0;args.unshift(event,delta,deltaX,deltaY);if(nullLowestDeltaTimeout){clearTimeout(nullLowestDeltaTimeout)}nullLowestDeltaTimeout=setTimeout(nullLowestDelta,200);return($.event.dispatch||$.event.handle).apply(this,args)}function nullLowestDelta(){lowestDelta=null}function shouldAdjustOldDeltas(orgEvent,absDelta){return special.settings.adjustOldDeltas&&orgEvent.type==="mousewheel"&&absDelta%120===0}});(function(B){B.color={};B.color.make=function(F,E,C,D){var G={};G.r=F||0;G.g=E||0;G.b=C||0;G.a=D!=null?D:1;G.add=function(J,I){for(var H=0;H=1){return"rgb("+[G.r,G.g,G.b].join(",")+")"}else{return"rgba("+[G.r,G.g,G.b,G.a].join(",")+")"}};G.normalize=function(){function H(J,K,I){return KI?I:K}G.r=H(0,parseInt(G.r),255);G.g=H(0,parseInt(G.g),255);G.b=H(0,parseInt(G.b),255);G.a=H(0,G.a,1);return G};G.clone=function(){return B.color.make(G.r,G.b,G.g,G.a)};return G.normalize()};B.color.extract=function(D,C){var E;do{E=D.css(C).toLowerCase();if(E!=""&&E!="transparent"){break}D=D.parent()}while(!B.nodeName(D.get(0),"body"));if(E=="rgba(0, 0, 0, 0)"){E="transparent"}return B.color.parse(E)};B.color.parse=function(F){var E,C=B.color.make;if(E=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10))}if(E=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseInt(E[1],10),parseInt(E[2],10),parseInt(E[3],10),parseFloat(E[4]))}if(E=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55)}if(E=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(F)){return C(parseFloat(E[1])*2.55,parseFloat(E[2])*2.55,parseFloat(E[3])*2.55,parseFloat(E[4]))}if(E=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(F)){return C(parseInt(E[1],16),parseInt(E[2],16),parseInt(E[3],16))}if(E=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(F)){return C(parseInt(E[1]+E[1],16),parseInt(E[2]+E[2],16),parseInt(E[3]+E[3],16))}var D=B.trim(F).toLowerCase();if(D=="transparent"){return C(255,255,255,0)}else{E=A[D]||[0,0,0];return C(E[0],E[1],E[2])}};var A={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],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],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);(function($){function Plot(placeholder,data_,options_,plugins){var series=[],options={colors:["#edc240","#afd8f8","#cb4b4b","#4da74d","#9440ed"],legend:{show:true,noColumns:1,labelFormatter:null,labelBoxBorderColor:"#ccc",container:null,position:"ne",margin:5,backgroundColor:null,backgroundOpacity:.85},xaxis:{show:null,position:"bottom",mode:null,color:null,tickColor:null,transform:null,inverseTransform:null,min:null,max:null,autoscaleMargin:null,ticks:null,tickFormatter:null,labelWidth:null,labelHeight:null,reserveSpace:null,tickLength:null,alignTicksWithAxis:null,tickDecimals:null,tickSize:null,minTickSize:null,monthNames:null,timeformat:null,twelveHourClock:false},yaxis:{autoscaleMargin:.02,position:"left"},xaxes:[],yaxes:[],series:{points:{show:false,radius:3,lineWidth:2,fill:true,fillColor:"#ffffff",symbol:"circle"},lines:{lineWidth:2,fill:false,fillColor:null,steps:false},bars:{show:false,lineWidth:2,barWidth:1,fill:true,fillColor:null,align:"left",horizontal:false},shadowSize:3},grid:{show:true,aboveData:false,color:"#545454",backgroundColor:null,borderColor:null,tickColor:null,labelMargin:5,axisMargin:8,borderWidth:2,minBorderMargin:null,markings:null,markingsColor:"#f4f4f4",markingsLineWidth:2,clickable:false,hoverable:false,autoHighlight:true,mouseActiveRadius:10},hooks:{}},canvas=null,overlay=null,eventHolder=null,ctx=null,octx=null,xaxes=[],yaxes=[],plotOffset={left:0,right:0,top:0,bottom:0},canvasWidth=0,canvasHeight=0,plotWidth=0,plotHeight=0,hooks={processOptions:[],processRawData:[],processDatapoints:[],drawSeries:[],draw:[],bindEvents:[],drawOverlay:[],shutdown:[]},plot=this;plot.setData=setData;plot.setupGrid=setupGrid;plot.draw=draw;plot.getPlaceholder=function(){return placeholder};plot.getCanvas=function(){return canvas};plot.getPlotOffset=function(){return plotOffset};plot.width=function(){return plotWidth};plot.height=function(){return plotHeight};plot.offset=function(){var o=eventHolder.offset();o.left+=plotOffset.left;o.top+=plotOffset.top;return o};plot.getData=function(){return series};plot.getAxes=function(){var res={},i;$.each(xaxes.concat(yaxes),function(_,axis){if(axis)res[axis.direction+(axis.n!=1?axis.n:"")+"axis"]=axis});return res};plot.getXAxes=function(){return xaxes};plot.getYAxes=function(){return yaxes};plot.c2p=canvasToAxisCoords;plot.p2c=axisToCanvasCoords;plot.getOptions=function(){return options};plot.highlight=highlight;plot.unhighlight=unhighlight;plot.triggerRedrawOverlay=triggerRedrawOverlay;plot.pointOffset=function(point){return{left:parseInt(xaxes[axisNumber(point,"x")-1].p2c(+point.x)+plotOffset.left),top:parseInt(yaxes[axisNumber(point,"y")-1].p2c(+point.y)+plotOffset.top)}};plot.shutdown=shutdown;plot.resize=function(){getCanvasDimensions();resizeCanvas(canvas);resizeCanvas(overlay)};plot.hooks=hooks;initPlugins(plot);parseOptions(options_);setupCanvases();setData(data_);setupGrid();draw();bindEvents();function executeHooks(hook,args){args=[plot].concat(args);for(var i=0;i=options.colors.length){i=0;++variation}}var colori=0,s;for(i=0;iaxis.datamax&&max!=fakeInfinity)axis.datamax=max}$.each(allAxes(),function(_,axis){axis.datamin=topSentry;axis.datamax=bottomSentry;axis.used=false});for(i=0;i0&&points[k-ps]!=null&&points[k-ps]!=points[k]&&points[k-ps+1]!=points[k+1]){for(m=0;mxmax)xmax=val}if(f.y){if(valymax)ymax=val}}}if(s.bars.show){var delta=s.bars.align=="left"?0:-s.bars.barWidth/2;if(s.bars.horizontal){ymin+=delta;ymax+=delta+s.bars.barWidth}else{xmin+=delta;xmax+=delta+s.bars.barWidth}}updateAxis(s.xaxis,xmin,xmax);updateAxis(s.yaxis,ymin,ymax)}$.each(allAxes(),function(_,axis){if(axis.datamin==topSentry)axis.datamin=null;if(axis.datamax==bottomSentry)axis.datamax=null})}function makeCanvas(skipPositioning,cls){var c=document.createElement("canvas");c.className=cls;c.width=canvasWidth;c.height=canvasHeight;if(!skipPositioning)$(c).css({position:"absolute",left:0,top:0});$(c).appendTo(placeholder);if(!c.getContext)c=window.G_vmlCanvasManager.initElement(c);c.getContext("2d").save();return c}function getCanvasDimensions(){canvasWidth=placeholder.width();canvasHeight=placeholder.height();if(canvasWidth<=0||canvasHeight<=0)throw"Invalid dimensions for plot, width = "+canvasWidth+", height = "+canvasHeight}function resizeCanvas(c){if(c.width!=canvasWidth)c.width=canvasWidth;if(c.height!=canvasHeight)c.height=canvasHeight;var cctx=c.getContext("2d");cctx.restore();cctx.save()}function setupCanvases(){var reused,existingCanvas=placeholder.children("canvas.base"),existingOverlay=placeholder.children("canvas.overlay");if(existingCanvas.length==0||existingOverlay==0){placeholder.html("");placeholder.css({padding:0});if(placeholder.css("position")=="static")placeholder.css("position","relative");getCanvasDimensions();canvas=makeCanvas(true,"base");overlay=makeCanvas(false,"overlay");reused=false}else{canvas=existingCanvas.get(0);overlay=existingOverlay.get(0);reused=true}ctx=canvas.getContext("2d");octx=overlay.getContext("2d");eventHolder=$([overlay,canvas]);if(reused){placeholder.data("plot").shutdown();plot.resize();octx.clearRect(0,0,canvasWidth,canvasHeight);eventHolder.unbind();placeholder.children().not([canvas,overlay]).remove()}placeholder.data("plot",plot)}function bindEvents(){if(options.grid.hoverable){eventHolder.mousemove(onMouseMove);eventHolder.mouseleave(onMouseLeave)}if(options.grid.clickable)eventHolder.click(onClick);executeHooks(hooks.bindEvents,[eventHolder])}function shutdown(){if(redrawTimeout)clearTimeout(redrawTimeout);eventHolder.unbind("mousemove",onMouseMove);eventHolder.unbind("mouseleave",onMouseLeave);eventHolder.unbind("click",onClick);executeHooks(hooks.shutdown,[eventHolder])}function setTransformationHelpers(axis){function identity(x){return x}var s,m,t=axis.options.transform||identity,it=axis.options.inverseTransform;if(axis.direction=="x"){s=axis.scale=plotWidth/Math.abs(t(axis.max)-t(axis.min));m=Math.min(t(axis.max),t(axis.min))}else{s=axis.scale=plotHeight/Math.abs(t(axis.max)-t(axis.min));s=-s;m=Math.max(t(axis.max),t(axis.min))}if(t==identity)axis.p2c=function(p){return(p-m)*s};else axis.p2c=function(p){return(t(p)-m)*s};if(!it)axis.c2p=function(c){return m+c/s};else axis.c2p=function(c){return it(m+c/s)}}function measureTickLabels(axis){var opts=axis.options,i,ticks=axis.ticks||[],labels=[],l,w=opts.labelWidth,h=opts.labelHeight,dummyDiv;function makeDummyDiv(labels,width){return $('
'+'
'+labels.join("")+"
").appendTo(placeholder)}if(axis.direction=="x"){if(w==null)w=Math.floor(canvasWidth/(ticks.length>0?ticks.length:1));if(h==null){labels=[];for(i=0;i'+l+"
")}if(labels.length>0){labels.push('
');dummyDiv=makeDummyDiv(labels,"width:10000px;");h=dummyDiv.height();dummyDiv.remove()}}}else if(w==null||h==null){for(i=0;i'+l+"
")}if(labels.length>0){dummyDiv=makeDummyDiv(labels,"");if(w==null)w=dummyDiv.children().width();if(h==null)h=dummyDiv.find("div.tickLabel").height();dummyDiv.remove()}}if(w==null)w=0;if(h==null)h=0;axis.labelWidth=w;axis.labelHeight=h}function allocateAxisBoxFirstPhase(axis){var lw=axis.labelWidth,lh=axis.labelHeight,pos=axis.options.position,tickLength=axis.options.tickLength,axismargin=options.grid.axisMargin,padding=options.grid.labelMargin,all=axis.direction=="x"?xaxes:yaxes,index;var samePosition=$.grep(all,function(a){return a&&a.options.position==pos&&a.reserveSpace});if($.inArray(axis,samePosition)==samePosition.length-1)axismargin=0;if(tickLength==null)tickLength="full";var sameDirection=$.grep(all,function(a){return a&&a.reserveSpace});var innermost=$.inArray(axis,sameDirection)==0;if(!innermost&&tickLength=="full")tickLength=5;if(!isNaN(+tickLength))padding+=+tickLength;if(axis.direction=="x"){lh+=padding;if(pos=="bottom"){plotOffset.bottom+=lh+axismargin;axis.box={top:canvasHeight-plotOffset.bottom,height:lh}}else{axis.box={top:plotOffset.top+axismargin,height:lh};plotOffset.top+=lh+axismargin}}else{lw+=padding;if(pos=="left"){axis.box={left:plotOffset.left+axismargin,width:lw};plotOffset.left+=lw+axismargin}else{plotOffset.right+=lw+axismargin;axis.box={left:canvasWidth-plotOffset.right,width:lw}}}axis.position=pos;axis.tickLength=tickLength;axis.box.padding=padding;axis.innermost=innermost}function allocateAxisBoxSecondPhase(axis){if(axis.direction=="x"){axis.box.left=plotOffset.left;axis.box.width=plotWidth}else{axis.box.top=plotOffset.top;axis.box.height=plotHeight}}function setupGrid(){var i,axes=allAxes();$.each(axes,function(_,axis){axis.show=axis.options.show;if(axis.show==null)axis.show=axis.used;axis.reserveSpace=axis.show||axis.options.reserveSpace;setRange(axis)});allocatedAxes=$.grep(axes,function(axis){return axis.reserveSpace});plotOffset.left=plotOffset.right=plotOffset.top=plotOffset.bottom=0;if(options.grid.offsets!==undefined){var o=options.grid.offsets;plotOffset.left=o.left;plotOffset.right=o.right;plotOffset.top=o.top;plotOffset.bottom=o.bottom}if(options.grid.show){$.each(allocatedAxes,function(_,axis){setupTickGeneration(axis);setTicks(axis);snapRangeToTicks(axis,axis.ticks);measureTickLabels(axis)});for(i=allocatedAxes.length-1;i>=0;--i)allocateAxisBoxFirstPhase(allocatedAxes[i]);var minMargin=options.grid.minBorderMargin;if(minMargin==null){minMargin=0;for(i=0;i=0)min=0}if(opts.max==null){max+=delta*margin;if(max>0&&axis.datamax!=null&&axis.datamax<=0)max=0}}}axis.min=min;axis.max=max}function setupTickGeneration(axis){var opts=axis.options;var noTicks;if(typeof opts.ticks=="number"&&opts.ticks>0)noTicks=opts.ticks;else noTicks=.3*Math.sqrt(axis.direction=="x"?canvasWidth:canvasHeight);var delta=(axis.max-axis.min)/noTicks,size,generator,unit,formatter,i,magn,norm;if(opts.mode=="time"){var timeUnitSize={second:1e3,minute:60*1e3,hour:60*60*1e3,day:24*60*60*1e3,month:30*24*60*60*1e3,year:365.2425*24*60*60*1e3};var spec=[[1,"second"],[2,"second"],[5,"second"],[10,"second"],[30,"second"],[1,"minute"],[2,"minute"],[5,"minute"],[10,"minute"],[30,"minute"],[1,"hour"],[2,"hour"],[4,"hour"],[8,"hour"],[12,"hour"],[1,"day"],[2,"day"],[3,"day"],[.25,"month"],[.5,"month"],[1,"month"],[2,"month"],[3,"month"],[6,"month"],[1,"year"]];var minSize=0;if(opts.minTickSize!=null){if(typeof opts.tickSize=="number")minSize=opts.tickSize;else minSize=opts.minTickSize[0]*timeUnitSize[opts.minTickSize[1]]}for(var i=0;i=minSize)break;size=spec[i][0];unit=spec[i][1];if(unit=="year"){magn=Math.pow(10,Math.floor(Math.log(delta/timeUnitSize.year)/Math.LN10));norm=delta/timeUnitSize.year/magn;if(norm<1.5)size=1;else if(norm<3)size=2;else if(norm<7.5)size=5;else size=10;size*=magn}axis.tickSize=opts.tickSize||[size,unit];generator=function(axis){var ticks=[],tickSize=axis.tickSize[0],unit=axis.tickSize[1],d=new Date(axis.min);var step=tickSize*timeUnitSize[unit];if(unit=="second")d.setUTCSeconds(floorInBase(d.getUTCSeconds(),tickSize));if(unit=="minute")d.setUTCMinutes(floorInBase(d.getUTCMinutes(),tickSize));if(unit=="hour")d.setUTCHours(floorInBase(d.getUTCHours(),tickSize));if(unit=="month")d.setUTCMonth(floorInBase(d.getUTCMonth(),tickSize));if(unit=="year")d.setUTCFullYear(floorInBase(d.getUTCFullYear(),tickSize));d.setUTCMilliseconds(0);if(step>=timeUnitSize.minute)d.setUTCSeconds(0);if(step>=timeUnitSize.hour)d.setUTCMinutes(0);if(step>=timeUnitSize.day)d.setUTCHours(0);if(step>=timeUnitSize.day*4)d.setUTCDate(1);if(step>=timeUnitSize.year)d.setUTCMonth(0);var carry=0,v=Number.NaN,prev;do{prev=v;v=d.getTime();ticks.push(v);if(unit=="month"){if(tickSize<1){d.setUTCDate(1);var start=d.getTime();d.setUTCMonth(d.getUTCMonth()+1);var end=d.getTime();d.setTime(v+carry*timeUnitSize.hour+(end-start)*tickSize);carry=d.getUTCHours();d.setUTCHours(0)}else d.setUTCMonth(d.getUTCMonth()+tickSize)}else if(unit=="year"){d.setUTCFullYear(d.getUTCFullYear()+tickSize)}else d.setTime(v+step)}while(vmaxDec)dec=maxDec;magn=Math.pow(10,-dec);norm=delta/magn;if(norm<1.5)size=1;else if(norm<3){size=2;if(norm>2.25&&(maxDec==null||dec+1<=maxDec)){size=2.5;++dec}}else if(norm<7.5)size=5;else size=10;size*=magn;if(opts.minTickSize!=null&&size0){if(opts.min==null)axis.min=Math.min(axis.min,niceTicks[0]);if(opts.max==null&&niceTicks.length>1)axis.max=Math.max(axis.max,niceTicks[niceTicks.length-1])}generator=function(axis){var ticks=[],v,i;for(i=0;i1&&/\..*0$/.test((ts[1]-ts[0]).toFixed(extraDec))))axis.tickDecimals=extraDec}}}axis.tickGenerator=generator;if($.isFunction(opts.tickFormatter))axis.tickFormatter=function(v,axis){return""+opts.tickFormatter(v,axis)};else axis.tickFormatter=formatter}function setTicks(axis){var oticks=axis.options.ticks,ticks=[];if(oticks==null||typeof oticks=="number"&&oticks>0)ticks=axis.tickGenerator(axis);else if(oticks){if($.isFunction(oticks))ticks=oticks({min:axis.min,max:axis.max});else ticks=oticks}var i,v;axis.ticks=[];for(i=0;i1)label=t[1]}else v=+t;if(label==null)label=axis.tickFormatter(v,axis);if(!isNaN(v))axis.ticks.push({v:v,label:label})}}function snapRangeToTicks(axis,ticks){if(axis.options.autoscaleMargin&&ticks.length>0){if(axis.options.min==null)axis.min=Math.min(axis.min,ticks[0].v);if(axis.options.max==null&&ticks.length>1)axis.max=Math.max(axis.max,ticks[ticks.length-1].v)}}function draw(){var o=options.grid.offsets;ctx.clearRect(o.left,o.top,canvasWidth-o.left,canvasHeight-o.bottom-o.top);var grid=options.grid;if(grid.show&&grid.backgroundColor)drawBackground();if(grid.show&&!grid.aboveData)drawGrid();for(var i=0;ito){var tmp=from;from=to;to=tmp}return{from:from,to:to,axis:axis}}function drawBackground(){ctx.save();ctx.translate(plotOffset.left,plotOffset.top);ctx.fillStyle=getColorOrGradient(options.grid.backgroundColor,plotHeight,0,"rgba(255, 255, 255, 0)");ctx.fillRect(0,0,plotWidth,plotHeight);ctx.restore()}function drawGrid(){var i;ctx.save();ctx.translate(plotOffset.left,plotOffset.top);var markings=options.grid.markings;if(markings){if($.isFunction(markings)){var axes=plot.getAxes();axes.xmin=axes.xaxis.min;axes.xmax=axes.xaxis.max;axes.ymin=axes.yaxis.min;axes.ymax=axes.yaxis.max;markings=markings(axes)}for(i=0;ixrange.axis.max||yrange.toyrange.axis.max)continue;xrange.from=Math.max(xrange.from,xrange.axis.min);xrange.to=Math.min(xrange.to,xrange.axis.max);yrange.from=Math.max(yrange.from,yrange.axis.min);yrange.to=Math.min(yrange.to,yrange.axis.max);if(xrange.from==xrange.to&&yrange.from==yrange.to)continue;xrange.from=xrange.axis.p2c(xrange.from);xrange.to=xrange.axis.p2c(xrange.to);yrange.from=yrange.axis.p2c(yrange.from);yrange.to=yrange.axis.p2c(yrange.to);if(xrange.from==xrange.to||yrange.from==yrange.to){ctx.beginPath();ctx.strokeStyle=m.color||options.grid.markingsColor;ctx.lineWidth=m.lineWidth||options.grid.markingsLineWidth;ctx.moveTo(xrange.from,yrange.from);ctx.lineTo(xrange.to,yrange.to);ctx.stroke()}else{ctx.fillStyle=m.color||options.grid.markingsColor;ctx.fillRect(xrange.from,yrange.to,xrange.to-xrange.from,yrange.from-yrange.to)}}}var axes=allAxes(),bw=options.grid.borderWidth;for(var j=0;jaxis.max||t=="full"&&bw>0&&(v==axis.min||v==axis.max))continue;if(axis.direction=="x"){x=axis.p2c(v);yoff=t=="full"?-plotHeight:t;if(axis.position=="top")yoff=-yoff}else{y=axis.p2c(v);xoff=t=="full"?-plotWidth:t;if(axis.position=="left")xoff=-xoff}if(ctx.lineWidth==1){if(axis.direction=="x")x=Math.floor(x)+.5;else y=Math.floor(y)+.5}ctx.moveTo(x,y);ctx.lineTo(x+xoff,y+yoff)}ctx.stroke()}if(bw){ctx.lineWidth=bw;ctx.strokeStyle=options.grid.borderColor;ctx.strokeRect(-bw/2,-bw/2,plotWidth+bw,plotHeight+bw)}ctx.restore()}function insertAxisLabels(){placeholder.find(".tickLabels").remove();var html=['
'];var axes=allAxes();for(var j=0;j');for(var i=0;iaxis.max)continue;var pos={},align;if(axis.direction=="x"){align="center";pos.left=Math.round(plotOffset.left+axis.p2c(tick.v)-axis.labelWidth/2);if(axis.position=="bottom")pos.top=box.top+box.padding;else pos.bottom=canvasHeight-(box.top+box.height-box.padding)}else{pos.top=Math.round(plotOffset.top+axis.p2c(tick.v)-axis.labelHeight/2);if(axis.position=="left"){pos.right=canvasWidth-(box.left+box.width-box.padding);align="right"}else{pos.left=box.left+box.padding;align="left"}}pos.width=axis.labelWidth;var style=["position:absolute","text-align:"+align];for(var a in pos)style.push(a+":"+pos[a]+"px");html.push('
'+tick.label+"
")}html.push("
")}html.push("
");placeholder.append(html.join(""))}function drawSeries(series){if(series.lines.show)drawSeriesLines(series);if(series.bars.show)drawSeriesBars(series);if(series.points.show)drawSeriesPoints(series)}function drawSeriesLines(series){function plotLine(datapoints,xoffset,yoffset,axisx,axisy){var points=datapoints.points,ps=datapoints.pointsize,prevx=null,prevy=null;ctx.beginPath();for(var i=ps;i=y2&&y1>axisy.max){if(y2>axisy.max)continue;x1=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y1=axisy.max}else if(y2>=y1&&y2>axisy.max){if(y1>axisy.max)continue;x2=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y2=axisy.max}if(x1<=x2&&x1=x2&&x1>axisx.max){if(x2>axisx.max)continue;y1=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x1=axisx.max}else if(x2>=x1&&x2>axisx.max){if(x1>axisx.max)continue;y2=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x2=axisx.max}if(x1!=prevx||y1!=prevy)ctx.moveTo(axisx.p2c(x1)+xoffset,axisy.p2c(y1)+yoffset);prevx=x2;prevy=y2;ctx.lineTo(axisx.p2c(x2)+xoffset,axisy.p2c(y2)+yoffset)}ctx.stroke()}function plotLineArea(datapoints,axisx,axisy){var points=datapoints.points,ps=datapoints.pointsize,bottom=Math.min(Math.max(0,axisy.min),axisy.max),i=0,top,areaOpen=false,ypos=1,segmentStart=0,segmentEnd=0;while(true){if(ps>0&&i>points.length+ps)break;i+=ps;var x1=points[i-ps],y1=points[i-ps+ypos],x2=points[i],y2=points[i+ypos];if(areaOpen){if(ps>0&&x1!=null&&x2==null){segmentEnd=i;ps=-ps;ypos=2;continue}if(ps<0&&i==segmentStart+ps){ctx.fill();areaOpen=false;ps=-ps;ypos=1;i=segmentStart=segmentEnd+ps;continue}}if(x1==null||x2==null)continue;if(x1<=x2&&x1=x2&&x1>axisx.max){if(x2>axisx.max)continue;y1=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x1=axisx.max}else if(x2>=x1&&x2>axisx.max){if(x1>axisx.max)continue;y2=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x2=axisx.max}if(!areaOpen){ctx.beginPath();ctx.moveTo(axisx.p2c(x1),axisy.p2c(bottom));areaOpen=true}if(y1>=axisy.max&&y2>=axisy.max){ctx.lineTo(axisx.p2c(x1),axisy.p2c(axisy.max));ctx.lineTo(axisx.p2c(x2),axisy.p2c(axisy.max));continue}else if(y1<=axisy.min&&y2<=axisy.min){ctx.lineTo(axisx.p2c(x1),axisy.p2c(axisy.min));ctx.lineTo(axisx.p2c(x2),axisy.p2c(axisy.min));continue}var x1old=x1,x2old=x2;if(y1<=y2&&y1=axisy.min){x1=(axisy.min-y1)/(y2-y1)*(x2-x1)+x1;y1=axisy.min}else if(y2<=y1&&y2=axisy.min){x2=(axisy.min-y1)/(y2-y1)*(x2-x1)+x1;y2=axisy.min}if(y1>=y2&&y1>axisy.max&&y2<=axisy.max){x1=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y1=axisy.max}else if(y2>=y1&&y2>axisy.max&&y1<=axisy.max){x2=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y2=axisy.max}if(x1!=x1old){ctx.lineTo(axisx.p2c(x1old),axisy.p2c(y1))}ctx.lineTo(axisx.p2c(x1),axisy.p2c(y1));ctx.lineTo(axisx.p2c(x2),axisy.p2c(y2));if(x2!=x2old){ctx.lineTo(axisx.p2c(x2),axisy.p2c(y2));ctx.lineTo(axisx.p2c(x2old),axisy.p2c(y2))}}}ctx.save();ctx.translate(plotOffset.left,plotOffset.top);ctx.lineJoin="round";var lw=series.lines.lineWidth,sw=series.shadowSize;if(lw>0&&sw>0){ctx.lineWidth=sw;ctx.strokeStyle="rgba(0,0,0,0.1)";var angle=Math.PI/18;plotLine(series.datapoints,Math.sin(angle)*(lw/2+sw/2),Math.cos(angle)*(lw/2+sw/2),series.xaxis,series.yaxis);ctx.lineWidth=sw/2;plotLine(series.datapoints,Math.sin(angle)*(lw/2+sw/4),Math.cos(angle)*(lw/2+sw/4),series.xaxis,series.yaxis)}ctx.lineWidth=lw;ctx.strokeStyle=series.color;var fillStyle=getFillStyle(series.lines,series.color,0,plotHeight);if(fillStyle){ctx.fillStyle=fillStyle;plotLineArea(series.datapoints,series.xaxis,series.yaxis)}if(lw>0)plotLine(series.datapoints,0,0,series.xaxis,series.yaxis);ctx.restore()}function drawSeriesPoints(series){function plotPoints(datapoints,radius,fillStyle,offset,shadow,axisx,axisy,symbol){var points=datapoints.points,ps=datapoints.pointsize;for(var i=0;iaxisx.max||yaxisy.max)continue;ctx.beginPath();x=axisx.p2c(x);y=axisy.p2c(y)+offset;if(symbol=="circle")ctx.arc(x,y,radius,0,shadow?Math.PI:Math.PI*2,false);else symbol(ctx,x,y,radius,shadow);ctx.closePath();if(fillStyle){ctx.fillStyle=fillStyle;ctx.fill()}ctx.stroke()}}ctx.save();ctx.translate(plotOffset.left,plotOffset.top);var lw=series.points.lineWidth,sw=series.shadowSize,radius=series.points.radius,symbol=series.points.symbol;if(lw>0&&sw>0){var w=sw/2;ctx.lineWidth=w;ctx.strokeStyle="rgba(0,0,0,0.1)";plotPoints(series.datapoints,radius,null,w+w/2,true,series.xaxis,series.yaxis,symbol);ctx.strokeStyle="rgba(0,0,0,0.2)";plotPoints(series.datapoints,radius,null,w/2,true,series.xaxis,series.yaxis,symbol)}ctx.lineWidth=lw;ctx.strokeStyle=series.color;plotPoints(series.datapoints,radius,getFillStyle(series.points,series.color),0,false,series.xaxis,series.yaxis,symbol);ctx.restore()}function drawBar(x,y,b,barLeft,barRight,offset,fillStyleCallback,axisx,axisy,c,horizontal,lineWidth){var left,right,bottom,top,drawLeft,drawRight,drawTop,drawBottom,tmp;if(horizontal){drawBottom=drawRight=drawTop=true;drawLeft=false;left=b;right=x;top=y+barLeft;bottom=y+barRight;if(rightaxisx.max||topaxisy.max)return;if(leftaxisx.max){right=axisx.max;drawRight=false}if(bottomaxisy.max){top=axisy.max;drawTop=false}left=axisx.p2c(left);bottom=axisy.p2c(bottom);right=axisx.p2c(right);top=axisy.p2c(top);if(fillStyleCallback){c.beginPath();c.moveTo(left,bottom);c.lineTo(left,top);c.lineTo(right,top);c.lineTo(right,bottom);c.fillStyle=fillStyleCallback(bottom,top);c.fill()}if(lineWidth>0&&(drawLeft||drawRight||drawTop||drawBottom)){c.beginPath();c.moveTo(left,bottom+offset);if(drawLeft)c.lineTo(left,top+offset);else c.moveTo(left,top+offset);if(drawTop)c.lineTo(right,top+offset);else c.moveTo(right,top+offset);if(drawRight)c.lineTo(right,bottom+offset);else c.moveTo(right,bottom+offset);if(drawBottom)c.lineTo(left,bottom+offset);else c.moveTo(left,bottom+offset);c.stroke()}}function drawSeriesBars(series){function plotBars(datapoints,barLeft,barRight,offset,fillStyleCallback,axisx,axisy){var points=datapoints.points,ps=datapoints.pointsize;for(var i=0;i");fragments.push("");rowStarted=true}if(lf)label=lf(label,s);fragments.push('
'+''+label+"")}if(rowStarted)fragments.push("");if(fragments.length==0)return;var table=''+fragments.join("")+"
";if(options.legend.container!=null)$(options.legend.container).html(table);else{var pos="",p=options.legend.position,m=options.legend.margin;if(m[0]==null)m=[m,m];if(p.charAt(0)=="n")pos+="top:"+(m[1]+plotOffset.top)+"px;";else if(p.charAt(0)=="s")pos+="bottom:"+(m[1]+plotOffset.bottom)+"px;";if(p.charAt(1)=="e")pos+="right:"+(m[0]+plotOffset.right)+"px;";else if(p.charAt(1)=="w")pos+="left:"+(m[0]+plotOffset.left)+"px;";var legend=$('
'+table.replace('style="','style="position:absolute;'+pos+";")+"
").appendTo(placeholder);if(options.legend.backgroundOpacity!=0){var c=options.legend.backgroundColor;if(c==null){c=options.grid.backgroundColor;if(c&&typeof c=="string")c=$.color.parse(c);else c=$.color.extract(legend,"background-color");c.a=1;c=c.toString()}var div=legend.children();$('
').prependTo(legend).css("opacity",options.legend.backgroundOpacity)}}}var highlights=[],redrawTimeout=null;function findNearbyItem(mouseX,mouseY,seriesFilter){var maxDistance=options.grid.mouseActiveRadius,smallestDistance=maxDistance*maxDistance+1,item=null,foundPoint=false,i,j;for(i=series.length-1;i>=0;--i){if(!seriesFilter(series[i]))continue;var s=series[i],axisx=s.xaxis,axisy=s.yaxis,points=s.datapoints.points,ps=s.datapoints.pointsize,mx=axisx.c2p(mouseX),my=axisy.c2p(mouseY),maxx=maxDistance/axisx.scale,maxy=maxDistance/axisy.scale;if(axisx.options.inverseTransform)maxx=Number.MAX_VALUE;if(axisy.options.inverseTransform)maxy=Number.MAX_VALUE;if(s.lines.show||s.points.show){for(j=0;jmaxx||x-mx<-maxx||y-my>maxy||y-my<-maxy)continue;var dx=Math.abs(axisx.p2c(x)-mouseX),dy=Math.abs(axisy.p2c(y)-mouseY),dist=dx*dx+dy*dy;if(dist=Math.min(b,x)&&my>=y+barLeft&&my<=y+barRight:mx>=x+barLeft&&mx<=x+barRight&&my>=Math.min(b,y)&&my<=Math.max(b,y))item=[i,j/ps]}}}if(item){i=item[0];j=item[1];ps=series[i].datapoints.pointsize;return{datapoint:series[i].datapoints.points.slice(j*ps,(j+1)*ps),dataIndex:j,series:series[i],seriesIndex:i}}return null}function onMouseMove(e){if(options.grid.hoverable)triggerClickHoverEvent("plothover",e,function(s){return s["hoverable"]!=false})}function onMouseLeave(e){if(options.grid.hoverable)triggerClickHoverEvent("plothover",e,function(s){return false})}function onClick(e){triggerClickHoverEvent("plotclick",e,function(s){return s["clickable"]!=false})}function triggerClickHoverEvent(eventname,event,seriesFilter){var offset=eventHolder.offset(),canvasX=event.pageX-offset.left-plotOffset.left,canvasY=event.pageY-offset.top-plotOffset.top,pos=canvasToAxisCoords({left:canvasX,top:canvasY});pos.pageX=event.pageX;pos.pageY=event.pageY;var item=findNearbyItem(canvasX,canvasY,seriesFilter);if(item){item.pageX=parseInt(item.series.xaxis.p2c(item.datapoint[0])+offset.left+plotOffset.left);item.pageY=parseInt(item.series.yaxis.p2c(item.datapoint[1])+offset.top+plotOffset.top)}if(options.grid.autoHighlight){for(var i=0;iaxisx.max||yaxisy.max)return;var pointRadius=series.points.radius+series.points.lineWidth/2;octx.lineWidth=pointRadius;octx.strokeStyle=$.color.parse(series.color).scale("a",.5).toString();var radius=1.5*pointRadius,x=axisx.p2c(x),y=axisy.p2c(y);octx.beginPath();if(series.points.symbol=="circle")octx.arc(x,y,radius,0,2*Math.PI,false);else series.points.symbol(octx,x,y,radius,false);octx.closePath();octx.stroke()}function drawBarHighlight(series,point){octx.lineWidth=series.bars.lineWidth;octx.strokeStyle=$.color.parse(series.color).scale("a",.5).toString();var fillStyle=$.color.parse(series.color).scale("a",.5).toString();var barLeft=series.bars.align=="left"?0:-series.bars.barWidth/2;drawBar(point[0],point[1],point[2]||0,barLeft,barLeft+series.bars.barWidth,0,function(){return fillStyle},series.xaxis,series.yaxis,octx,series.bars.horizontal,series.bars.lineWidth)}function getColorOrGradient(spec,bottom,top,defaultColor){if(typeof spec=="string")return spec;else{var gradient=ctx.createLinearGradient(0,top,0,bottom);for(var i=0,l=spec.colors.length;i12){hours=hours-12}else if(hours==0){hours=12}}for(var i=0;i=0?"":"-";val=Math.abs(val);var before=Math.floor(log10(val))+1;if(before>n){val=val.toPrecision(n);return sign+val.replace("+","")}else if(before<0){var mantissa=val*pow(10,abs(before)+1);before-=1;return sign+mantissa.toFixed(n-1)+"e"+before}else{return sign+val.toFixed(n-before)}}function init(plot){var crosshair={x:-1,y:-1,locked:false};plot.setCrosshair=function setCrosshair(pos){if(!pos)crosshair.x=-1;else{var o=plot.p2c(pos);crosshair.x=Math.max(0,Math.min(o.left,plot.width()));crosshair.y=Math.max(0,Math.min(o.top,plot.height()))}plot.triggerRedrawOverlay()};plot.clearCrosshair=plot.setCrosshair;plot.lockCrosshair=function lockCrosshair(pos){if(pos)plot.setCrosshair(pos);crosshair.locked=true};plot.unlockCrosshair=function unlockCrosshair(){crosshair.locked=false};function onMouseOut(e){if(crosshair.locked)return;if(crosshair.x!=-1){crosshair.x=-1;plot.triggerRedrawOverlay()}}function onMouseMove(e){if(crosshair.locked)return;if(plot.getSelection&&plot.getSelection()){crosshair.x=-1;return}var offset=plot.offset();crosshair.x=Math.max(0,Math.min(e.pageX-offset.left,plot.width()));crosshair.y=Math.max(0,Math.min(e.pageY-offset.top,plot.height()));plot.triggerRedrawOverlay()}plot.hooks.bindEvents.push(function(plot,eventHolder){if(!plot.getOptions().crosshair.mode)return;eventHolder.mouseout(onMouseOut);eventHolder.mousemove(onMouseMove)});plot.hooks.drawOverlay.push(function(plot,ctx){var c=plot.getOptions().crosshair;if(!c.mode)return;var plotOffset=plot.getPlotOffset();ctx.save();ctx.translate(plotOffset.left,plotOffset.top);if(crosshair.x!=-1){var pos=plot.c2p({left:crosshair.x,top:crosshair.y});text=format_number(pos.x,3)+","+format_number(pos.y,3);var fontheight=13;ctx.fillStyle=c.color;ctx.font=fontheight+"px Verdana";var twidth=ctx.measureText(text).width;var dx=0,dy=0;if(crosshair.yplot.width()-(twidth+5)){ctx.textAlign="right";dx+=-3}else{ctx.textAlign="left";dx+=3}ctx.fillText(text,crosshair.x+dx,crosshair.y+dy);ctx.strokeStyle=c.color;ctx.lineWidth=c.lineWidth;ctx.lineJoin="round";ctx.beginPath();if(c.mode.indexOf("x")!=-1){ctx.moveTo(crosshair.x,0);ctx.lineTo(crosshair.x,plot.height())}if(c.mode.indexOf("y")!=-1){ctx.moveTo(0,crosshair.y);ctx.lineTo(plot.width(),crosshair.y)}ctx.stroke()}ctx.restore()});plot.hooks.shutdown.push(function(plot,eventHolder){eventHolder.unbind("mouseout",onMouseOut);eventHolder.unbind("mousemove",onMouseMove)})}$.plot.plugins.push({init:init,options:options,name:"crosshair_GS",version:"1.0"})})(jQuery);(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Plotly=f()}})(function(){var define,module,exports;return function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;oMath.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;view.pan(t,0,0,distance*(Math.exp(kzoom)-1))}},true);return camera}},{"3d-view":43,"has-passive-events":379,"mouse-change":402,"mouse-event-offset":403,"mouse-wheel":405,"right-now":465}],43:[function(require,module,exports){"use strict";module.exports=createViewController;var createTurntable=require("turntable-camera-controller");var createOrbit=require("orbit-camera-controller");var createMatrix=require("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 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}"});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}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}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"}var newFont=false,newFontSize=false;if(o.font){(Array.isArray(o.font)?o.font:[o.font]).forEach(function(font,i){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}if(!this$1.font[i]||baseString!=this$1.font[i].baseString){newFont=true;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,family:family,weight:font.weight,stretch:font.stretch,style:font.style,variant:font.variant,width:{},kerning:{},metrics:metrics(family,{origin:"top",fontSize:GlText.baseFontSize,fontStyle:style.join(" ")})};GlText.fonts[baseString]=this$1.font[i]}}})}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});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,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()}}if(o.text==null){o.text=this$1.text}})}if(typeof o.text==="string"&&o.position&&o.position.length>2){var textArray=Array(o.position.length*.5);for(var i=0;i2){var flat=!o.position[0].length;var positionData=pool.mallocFloat(this.count*2);for(var i$2=0,ptr=0;i$21?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})}if(o.color!=null){if(!o.color){o.color="transparent"}if(typeof o.color==="string"||!isNaN(o.color)){this.color=rgba(o.color,"uint8")}else{var colorData;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$44||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$61?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}}}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(){};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];GlText.normalViewport=false;GlText.maxAtlasSize=1024;GlText.atlasCanvas=document.createElement("canvas");GlText.atlasContext=GlText.atlasCanvas.getContext("2d",{alpha:false});GlText.baseFontSize=64;GlText.fonts={};function isRegl(o){return typeof o==="function"&&o._gl&&o.prop&&o.texture&&o.buffer}module.exports=GlText},{"color-normalize":45,"css-font":126,"detect-kerning":150,"es6-weak-map":208,"flatten-vertex-data":48,"font-atlas":217,"font-measure":218,"gl-util/context":304,"is-plain-obj":390,"object-assign":421,"parse-rect":426,"parse-unit":428,"pick-by-alias":432,regl:463,"to-px":501,"typedarray-pool":507}],45:[function(require,module,exports){"use strict";var rgba=require("color-rgba");var clamp=require("clamp");var dtype=require("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);if(color instanceof Ctor){if(Array.isArray(color)){return color.slice()}output.set(color);return output}var normalize=type!=="uint8"&&type!=="uint8_clamped";if(color instanceof Uint8Array||color instanceof Uint8ClampedArray){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(!color.length||typeof color==="string"){color=rgba(color);color[0]/=255;color[1]/=255;color[2]/=255}if(!normalize){output[0]=clamp(Math.round(color[0]*255),0,255);output[1]=clamp(Math.round(color[1]*255),0,255);output[2]=clamp(Math.round(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}},{clamp:102,"color-rgba":47,dtype:153}],46:[function(require,module,exports){(function(global){"use strict";var names=require("color-name");var isObject=require("is-plain-obj");var defined=require("defined");module.exports=parse;var baseHues={red:0,orange:60,yellow:120,green:180,blue:240,purple:300};function parse(cstr){var m,parts=[],alpha=1,space;if(typeof cstr==="string"){if(names[cstr]){parts=names[cstr].slice();space="rgb"}else if(cstr==="transparent"){alpha=0;space="rgb";parts=[0,0,0]}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"}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){if(/%$/.test(x)){if(i===size)return parseFloat(x)/100;if(base==="rgb")return parseFloat(x)*255/100;return parseFloat(x)}else if(base[i]==="h"){if(/deg$/.test(x)){return parseFloat(x)}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)}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])/gi).join("").toLowerCase()}}else if(!isNaN(cstr)){space="rgb";parts=[cstr>>>16,(cstr&65280)>>>8,cstr&255]}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}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":106,defined:148,"is-plain-obj":390}],47:[function(require,module,exports){"use strict";var parse=require("color-parse");var hsl=require("color-space/hsl");var clamp=require("clamp");module.exports=function rgba(color){var values,i,l;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:102,"color-parse":46,"color-space/hsl":110}],48:[function(require,module,exports){var dtype=require("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;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;i0;--iterations){relaxRightToLeft(alpha*=.99);resolveCollisions();relaxLeftToRight(alpha);resolveCollisions()}function initializeNodeDepth(){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;nodes.sort(ascendingDepth);for(i=0;i0)node.y+=dy;y0=node.y+node.dy+nodePadding}dy=y0-nodePadding-size[1];if(dy>0){y0=node.y-=dy;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":139,"d3-collection":140,"d3-interpolate":144}],50:[function(require,module,exports){"use strict";var weakMap=typeof WeakMap==="undefined"?require("weak-map"):WeakMap;var createBuffer=require("gl-buffer");var createVAO=require("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":230,"gl-vao":308,"weak-map":517}],51:[function(require,module,exports){module.exports=absolutize;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();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;imax)max=arr[i];if(arr[i]=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function truncate(s,n){if(typeof s==="string"){return s.length=0;i--){if(ka[i]!==kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return false}return true}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)}}assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};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){}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}}assert.throws=function(block,error,message){_throws(true,block,error,message)};assert.doesNotThrow=function(block,error,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/":514}],60:[function(require,module,exports){module.exports=function _atob(str){return atob(str)}},{}],61:[function(require,module,exports){"use strict";module.exports=barycentric;var solve=require("robust-linear-solve");function reduce(x){var r=0;for(var i=0;i0){throw new Error("Invalid string. Length must be a multiple of 4")}return b64[len-2]==="="?2:b64[len-1]==="="?1:0}function byteLength(b64){return b64.length*3/4-placeHoldersCount(b64)}function toByteArray(b64){var i,l,tmp,placeHolders,arr;var len=b64.length;placeHolders=placeHoldersCount(b64);arr=new Arr(len*3/4-placeHolders);l=placeHolders>0?len-4:len;var L=0;for(i=0;i>16&255;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}if(placeHolders===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[L++]=tmp&255}else if(placeHolders===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[L++]=tmp>>8&255;arr[L++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];output+=lookup[tmp>>2];output+=lookup[tmp<<4&63];output+="=="}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];output+=lookup[tmp>>10];output+=lookup[tmp>>4&63];output+=lookup[tmp<<2&63];output+="="}parts.push(output);return parts.join("")}},{}],63:[function(require,module,exports){"use strict";var rationalize=require("./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(require,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(require,module,exports){"use strict";var rationalize=require("./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(require,module,exports){"use strict";var isRat=require("./is-rat");var isBN=require("./lib/is-bn");var num2bn=require("./lib/num-to-bn");var str2bn=require("./lib/str-to-bn");var rationalize=require("./lib/rationalize");var div=require("./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(require,module,exports){"use strict";var isBN=require("./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(require,module,exports){"use strict";var BN=require("bn.js");module.exports=sign;function sign(x){return x.cmp(new BN(0))}},{"bn.js":82}],69:[function(require,module,exports){"use strict";var sign=require("./bn-sign");module.exports=bn2num;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]*67108864}else{for(var i=0;i20){return 52}return h+32}},{"bit-twiddle":80,"double-bits":151}],71:[function(require,module,exports){"use strict";var BN=require("bn.js");module.exports=isBN;function isBN(x){return x&&typeof x==="object"&&Boolean(x.words)}},{"bn.js":82}],72:[function(require,module,exports){"use strict";var BN=require("bn.js");var db=require("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":151}],73:[function(require,module,exports){"use strict";var num2bn=require("./num-to-bn");var sign=require("./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(require,module,exports){"use strict";var BN=require("bn.js");module.exports=str2BN;function str2BN(x){return new BN(x)}},{"bn.js":82}],75:[function(require,module,exports){"use strict";var rationalize=require("./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(require,module,exports){"use strict";var bnsign=require("./lib/bn-sign");module.exports=sign;function sign(x){return bnsign(x[0])*bnsign(x[1])}},{"./lib/bn-sign":68}],77:[function(require,module,exports){"use strict";var rationalize=require("./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(require,module,exports){"use strict";var bn2num=require("./lib/bn-to-num");var ctz=require("./lib/ctz");module.exports=roundRat;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(require,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(require,module,exports){"use strict";"use restrict";var INT_BITS=32;exports.INT_BITS=INT_BITS;exports.INT_MAX=2147483647;exports.INT_MIN=-1<0)-(v<0)};exports.abs=function(v){var mask=v>>INT_BITS-1;return(v^mask)-mask};exports.min=function(x,y){return y^(x^y)&-(x65535)<<4;v>>>=r;shift=(v>255)<<3;v>>>=shift;r|=shift;shift=(v>15)<<2;v>>>=shift;r|=shift;shift=(v>3)<<1;v>>>=shift;r|=shift;return r|v>>1};exports.log10=function(v){return v>=1e9?9:v>=1e8?8:v>=1e7?7:v>=1e6?6:v>=1e5?5:v>=1e4?4:v>=1e3?3:v>=100?2:v>=10?1:0};exports.popCount=function(v){v=v-(v>>>1&1431655765);v=(v&858993459)+(v>>>2&858993459);return(v+(v>>>4)&252645135)*16843009>>>24};function countTrailingZeros(v){var c=32;v&=-v;if(v)c--;if(v&65535)c-=16;if(v&16711935)c-=8;if(v&252645135)c-=4;if(v&858993459)c-=2;if(v&1431655765)c-=1;return c}exports.countTrailingZeros=countTrailingZeros;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};exports.prevPow2=function(v){v|=v>>>1;v|=v>>>2;v|=v>>>4;v|=v>>>8;v|=v>>>16;return v-(v>>>1)};exports.parity=function(v){v^=v>>>16;v^=v>>>8;v^=v>>>4;v&=15;return 27030>>>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<>>8&255]<<16|REVERSE_TABLE[v>>>16&255]<<8|REVERSE_TABLE[v>>>24&255]};exports.interleave2=function(x,y){x&=65535;x=(x|x<<8)&16711935;x=(x|x<<4)&252645135;x=(x|x<<2)&858993459;x=(x|x<<1)&1431655765;y&=65535;y=(y|y<<8)&16711935;y=(y|y<<4)&252645135;y=(y|y<<2)&858993459;y=(y|y<<1)&1431655765;return x|y<<1};exports.deinterleave2=function(v,n){v=v>>>n&1431655765;v=(v|v>>>1)&858993459;v=(v|v>>>2)&252645135;v=(v|v>>>4)&16711935;v=(v|v>>>16)&65535;return v<<16>>16};exports.interleave3=function(x,y,z){x&=1023;x=(x|x<<16)&4278190335;x=(x|x<<8)&251719695;x=(x|x<<4)&3272356035;x=(x|x<<2)&1227133513;y&=1023;y=(y|y<<16)&4278190335;y=(y|y<<8)&251719695;y=(y|y<<4)&3272356035;y=(y|y<<2)&1227133513;x|=y<<1;z&=1023;z=(z|z<<16)&4278190335;z=(z|z<<8)&251719695;z=(z|z<<4)&3272356035;z=(z|z<<2)&1227133513;return x|z<<2};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)&1023;return v<<22>>22};exports.nextCombination=function(v){var t=v|v-1;return t+1|(~t&-~t)-1>>>countTrailingZeros(v)+1}},{}],81:[function(require,module,exports){"use strict";var clamp=require("clamp");module.exports=calcSDF;var INF=1e20;function calcSDF(src,options){if(!options)options={};var cutoff=options.cutoff==null?.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;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);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;i0)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<67108864){this.words=[number&67108863];this.length=1}else if(number<4503599627370496){this.words=[number&67108863,number/67108864&67108863];this.length=2}else{assert(number<9007199254740992);this.words=[number&67108863,number/67108864&67108863,1];this.length=3}if(endian!=="le")return;this._initArray(this.toArray(),base,endian)};BN.prototype._initArray=function _initArray(number,base,endian){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=0;i-=3){w=number[i]|number[i-1]<<8|number[i-2]<<16;this.words[j]|=w<>>26-off&67108863;off+=24;if(off>=26){off-=26;j++}}}else if(endian==="le"){for(i=0,j=0;i>>26-off&67108863;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=49&&c<=54){r|=c-49+10}else if(c>=17&&c<=22){r|=c-17+10}else{r|=c&15}}return r}BN.prototype._parseHex=function _parseHex(number,start){this.length=Math.ceil((number.length-start)/6);this.words=new Array(this.length);for(var i=0;i=start;i-=6){w=parseHex(number,i,i+6);this.words[j]|=w<>>26-off&4194303;off+=24;if(off>=26){off-=26;j++}}if(i+6!==start){w=parseHex(number,start,i+6);this.words[j]|=w<>>26-off&4194303}this.strip()};function parseBase(str,start,end,mul){var r=0;var len=Math.min(str.length,end);for(var i=start;i=49){r+=c-49+10}else if(c>=17){r+=c-17+10}else{r+=c}}return r}BN.prototype._parseBase=function _parseBase(number,base,start){this.words=[0];this.length=1;for(var limbLen=0,limbPow=1;limbPow<=67108863;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;i1&&this.words[this.length-1]===0){this.length--}return this._normSign()};BN.prototype._normSign=function _normSign(){if(this.length===1&&this.words[0]===0){this.negative=0}return this};BN.prototype.inspect=function inspect(){return(this.red?""};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,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];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>>24-off&16777215;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=groupSizes[base];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]*67108864}else if(this.length===3&&this.words[2]===1){ret+=4503599627370496+this.words[1]*67108864}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){for(i=0;i=4096){r+=13;t>>>=13}if(t>=64){r+=7;t>>>=7}if(t>=8){r+=4;t>>>=4}if(t>=2){r+=2;t>>>=2}return r+t}}BN.prototype._zeroBits=function _zeroBits(w){if(w===0)return 26;var t=w;var r=0;if((t&8191)===0){r+=13;t>>>=13}if((t&127)===0){r+=7;t>>>=7}if((t&15)===0){r+=4;t>>>=4}if((t&3)===0){r+=2;t>>>=2}if((t&1)===0){r++}return r};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>>wbit}return w}BN.prototype.zeroBits=function zeroBits(){if(this.isZero())return 0;var r=0;for(var i=0;inum.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)};BN.prototype.iuand=function iuand(num){var b;if(this.length>num.length){b=num}else{b=this}for(var i=0;inum.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)};BN.prototype.iuxor=function iuxor(num){var a;var b;if(this.length>num.length){a=this;b=num}else{a=num;b=this}for(var i=0;inum.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)};BN.prototype.inotn=function inotn(width){assert(typeof width==="number"&&width>=0);var bytesNeeded=Math.ceil(width/26)|0;var bitsLeft=width%26;this._expand(bytesNeeded);if(bitsLeft>0){bytesNeeded--}for(var i=0;i0){this.words[i]=~this.words[i]&67108863>>26-bitsLeft}return this.strip()};BN.prototype.notn=function notn(width){return this.clone().inotn(width)};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<num.length){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>>26}for(;carry!==0&&i>>26}this.length=a.length;if(carry!==0){this.words[this.length]=carry;this.length++}else if(a!==this){for(;inum.length)return this.clone().iadd(num);return num.clone().iadd(this)};BN.prototype.isub=function isub(num){if(num.negative!==0){num.negative=0;var r=this.iadd(num);num.negative=1;return r._normSign()}else if(this.negative!==0){this.negative=0;this.iadd(num);this.negative=1;return this._normSign()}var cmp=this.cmp(num);if(cmp===0){this.negative=0;this.length=1;this.words[0]=0;return this}var a,b;if(cmp>0){a=this;b=num}else{a=num;b=this}var carry=0;for(var i=0;i>26;this.words[i]=r&67108863}for(;carry!==0&&i>26;this.words[i]=r&67108863}if(carry===0&&i>>26;var rword=carry&67108863;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/67108864|0;rword=r&67108863}out.words[k]=rword|0;carry=ncarry|0}if(carry!==0){out.words[k]=carry|0}else{out.length--}return out.strip()}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&8191;var ah0=a0>>>13;var a1=a[1]|0;var al1=a1&8191;var ah1=a1>>>13;var a2=a[2]|0;var al2=a2&8191;var ah2=a2>>>13;var a3=a[3]|0;var al3=a3&8191;var ah3=a3>>>13;var a4=a[4]|0;var al4=a4&8191;var ah4=a4>>>13;var a5=a[5]|0;var al5=a5&8191;var ah5=a5>>>13;var a6=a[6]|0;var al6=a6&8191;var ah6=a6>>>13;var a7=a[7]|0;var al7=a7&8191;var ah7=a7>>>13;var a8=a[8]|0;var al8=a8&8191;var ah8=a8>>>13;var a9=a[9]|0;var al9=a9&8191;var ah9=a9>>>13;var b0=b[0]|0;var bl0=b0&8191;var bh0=b0>>>13;var b1=b[1]|0;var bl1=b1&8191;var bh1=b1>>>13;var b2=b[2]|0;var bl2=b2&8191;var bh2=b2>>>13;var b3=b[3]|0;var bl3=b3&8191;var bh3=b3>>>13;var b4=b[4]|0;var bl4=b4&8191;var bh4=b4>>>13;var b5=b[5]|0;var bl5=b5&8191;var bh5=b5>>>13;var b6=b[6]|0;var bl6=b6&8191;var bh6=b6>>>13;var b7=b[7]|0;var bl7=b7&8191;var bh7=b7>>>13;var b8=b[8]|0;var bl8=b8&8191;var bh8=b8>>>13;var b9=b[9]|0;var bl9=b9&8191;var bh9=b9>>>13;out.negative=self.negative^num.negative;out.length=19;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w0>>>26)|0;w0&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w1>>>26)|0;w1&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w2>>>26)|0;w2&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w3>>>26)|0;w3&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w4>>>26)|0;w4&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w5>>>26)|0;w5&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w6>>>26)|0;w6&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w7>>>26)|0;w7&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w8>>>26)|0;w8&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w9>>>26)|0;w9&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w10>>>26)|0;w10&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w11>>>26)|0;w11&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w12>>>26)|0;w12&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w13>>>26)|0;w13&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w14>>>26)|0;w14&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w15>>>26)|0;w15&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w16>>>26)|0;w16&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w17>>>26)|0;w17&=67108863;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&8191)<<13)|0;c=(hi+(mid>>>13)|0)+(w18>>>26)|0;w18&=67108863;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};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>>26)|0;hncarry+=ncarry>>>26;ncarry&=67108863}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};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>=1}return rb};FFTM.prototype.permute=function permute(rbt,rws,iws,rtws,itws,N){for(var i=0;i>>1){i++}return 1<>>13;rws[2*i+1]=carry&8191;carry=carry>>>13}for(i=2*len;i>=26;carry+=w/67108864|0;carry+=lo>>>26;this.words[i]=lo&67108863}if(carry!==0){this.words[i]=carry;this.length++}return this};BN.prototype.muln=function muln(num){return this.clone().imuln(num)};BN.prototype.sqr=function sqr(){return this.mul(this)};BN.prototype.isqr=function isqr(){return this.imul(this.clone())};BN.prototype.pow=function pow(num){var w=toBitArray(num);if(w.length===0)return new BN(1);var res=this;for(var i=0;i=0);var r=bits%26;var s=(bits-r)/26;var carryMask=67108863>>>26-r<<26-r;var i;if(r!==0){var carry=0;for(i=0;i>>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=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=67108863^67108863>>>r<s){this.length-=s;for(i=0;i=0&&(carry!==0||i>=h);i--){var word=this.words[i]|0;this.words[i]=carry<<26-r|word>>>r;carry=word&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){assert(this.negative===0);return this.iushrn(bits,hint,extended)};BN.prototype.shln=function shln(bits){return this.clone().ishln(bits)};BN.prototype.ushln=function ushln(bits){return this.clone().iushln(bits)};BN.prototype.shrn=function shrn(bits){return this.clone().ishrn(bits)};BN.prototype.ushrn=function ushrn(bits){return this.clone().iushrn(bits)};BN.prototype.testn=function testn(bit){assert(typeof bit==="number"&&bit>=0);var r=bit%26;var s=(bit-r)/26;var q=1<=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=67108863^67108863>>>r<=67108864;i++){this.words[i]-=67108864;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};BN.prototype.isubn=function isubn(num){assert(typeof num==="number");assert(num<67108864);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{for(var i=0;i>26)-(right/67108864|0);this.words[i+shift]=w&67108863}for(;i>26;this.words[i+shift]=w&67108863}if(carry===0)return this.strip();assert(carry===-1);carry=0;for(i=0;i>26;this.words[i]=w&67108863}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;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}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=0;j--){var qj=(a.words[b.length+j]|0)*67108864+(a.words[b.length+j-1]|0);qj=Math.min(qj/bhi|0,67108863);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();if(mode!=="div"&&shift!==0){a.iushrn(shift)}return{div:q||null,mod:a}};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}}if(num.length>this.length||this.cmp(num)<0){return{div:new BN(0),mod:this}}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)};BN.prototype.div=function div(num){return this.divmod(num,"div",false).div};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};BN.prototype.divRound=function divRound(num){var dm=this.divmod(num);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);if(cmp<0||r2===1&&cmp===0)return dm.div;return dm.div.negative!==0?dm.div.isubn(1):dm.div.iaddn(1)};BN.prototype.modn=function modn(num){assert(num<=67108863);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};BN.prototype.idivn=function idivn(num){assert(num<=67108863);var carry=0;for(var i=this.length-1;i>=0;i--){var w=(this.words[i]|0)+carry*67108864;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()}var A=new BN(1);var B=new BN(0);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)}};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;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){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)};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};BN.prototype.andln=function andln(num){return this.words[0]&num};BN.prototype.bincn=function bincn(bit){assert(typeof bit==="number");var r=bit%26;var s=(bit-r)/26;var q=1<>>26;w&=67108863;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<=67108863,"Number is too big");var w=this.words[0]|0;res=w===num?0:wnum.length)return 1;if(this.length=0;i--){var a=this.words[i]|0;var b=num.words[i]|0;if(a===b)continue;if(ab){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};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)};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)};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)};var primes={k256:null,p224:null,p192:null,p25519:null};function MPrime(name,p){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){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=rlen0){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){var mask=4194303;var outLen=Math.min(input.length,9);for(var i=0;i>>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){num.words[num.length]=0;num.words[num.length+1]=0;num.length+=2;var lo=0;for(var i=0;i>>=26;num.words[i]=lo;carry=hi}if(carry!==0){num.words[num.length++]=carry}return num};BN._prime=function prime(name){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};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);if(mod3===3){var pow=this.m.add(new BN(1)).iushrn(2);return this.pow(a,pow)}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();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=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&¤t===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};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){var res=this.imod(a._invmp(this.m).mul(this.r2));return res._forceRed(this)}})(typeof module==="undefined"||module,this)},{buffer:91}],83:[function(require,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>>1;if(d<=0){return}var retval;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){sweep.init(n);retval=sweep.sweepComplete(d,visit,0,n,redList,redIds,0,n,redList,redIds)}else{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){retval=sweep.sweepBipartite(d,visit,0,n,redList,redIds,0,m,blueList,blueIds)}else{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}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":507}],85:[function(require,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"+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(require,module,exports){"use strict";module.exports=boxIntersectIter;var pool=require("typedarray-pool");var bits=require("bit-twiddle");var bruteForce=require("./brute");var bruteForcePartial=bruteForce.partial;var bruteForceFull=bruteForce.full;var sweep=require("./sweep");var findMedian=require("./median");var genPartition=require("./partition");var BRUTE_FORCE_CUTOFF=128;var SCAN_CUTOFF=1<<22;var SCAN_COMPLETE_CUTOFF=1<<22;var partitionInteriorContainsInterval=genPartition("!(lo>=p0)&&!(p1>=hi)",["p0","p1"]);var partitionStartEqual=genPartition("lo===p0",["p0"]);var partitionStartLessThan=genPartition("lo0){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];var flip=state&1;var full=!!(state&16);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)start&&boxes[ptr+axis]>x;--j,ptr-=elemSize){var aPtr=ptr;var bPtr=ptr+elemSize;for(var k=0;k>>1;var elemSize=2*d;var pivot=mid;var value=boxes[elemSize*mid+axis];while(lo=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}}var aPtr=elemSize*(hi-1);var bPtr=elemSize*pivot;for(var i=0;i=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(require,module,exports){"use strict";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(xdata[j+1]}return true}function comparePivot(i,y,b,data){i*=2;var x=data[i];if(x>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>>1;isort(SWEEP_EVENTS,n);var redActive=0;var blueActive=0;for(var i=0;i=BLUE_FLAG){e=e-BLUE_FLAG|0;sqPop(BLUE_SWEEP_QUEUE,BLUE_SWEEP_INDEX,blueActive--,e)}else if(e>=0){sqPop(RED_SWEEP_QUEUE,RED_SWEEP_INDEX,redActive--,e)}else if(e<=-BLUE_FLAG){e=-e-BLUE_FLAG|0;for(var j=0;j>>1;isort(SWEEP_EVENTS,n);var redActive=0;var blueActive=0;var commonActive=0;for(var i=0;i>1===SWEEP_EVENTS[2*i+3]>>1){color=2;i+=1}if(e<0){var id=-(e>>1)-1;for(var j=0;j>1)-1;if(color===0){sqPop(RED_SWEEP_QUEUE,RED_SWEEP_INDEX,redActive--,id)}else if(color===1){sqPop(BLUE_SWEEP_QUEUE,BLUE_SWEEP_INDEX,blueActive--,id)}else if(color===2){sqPop(COMMON_SWEEP_QUEUE,COMMON_SWEEP_INDEX,commonActive--,id)}}}}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>>1;isort(SWEEP_EVENTS,n);var redActive=0;for(var i=0;i=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>>1;isort(SWEEP_EVENTS,n);var redActive=0;for(var i=0;i=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=0;--j){if(RED_SWEEP_QUEUE[j]===idx){for(var k=j+1;kK_MAX_LENGTH){throw new RangeError("Invalid typed array length")}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){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(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="number"){throw new TypeError('"value" argument must not be a number')}if(isArrayBuffer(value)||value&&isArrayBuffer(value.buffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="string"){return fromString(value,encodingOrOffset)}return fromObject(value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};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('"size" argument must not be negative')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};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){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=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){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true};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>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase)return utf8ToBytes(string).length;encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}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}}}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;i0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return""};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;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}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}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&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;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(length>strLen/2){length=strLen/2}for(var i=0;i>>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":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(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)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>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){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]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(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=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*=256)){val+=this[offset+--i]*mul}mul*=128;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]&128))return this[offset];return(255-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&32768?val|4294901760: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&32768?val|4294901760: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||valuebuf.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&255;while(++i>>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&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;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,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;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&255;while(++i>0)-sub&255}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&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;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,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;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,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;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.4028234663852886e38,-3.4028234663852886e38)}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.7976931348623157e308,-1.7976931348623157e308)}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)};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=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){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"){val=code}}}else if(typeof val==="number"){val=val&255}if(start<0||this.length>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>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=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isArrayBuffer(obj){return obj instanceof ArrayBuffer||obj!=null&&obj.constructor!=null&&obj.constructor.name==="ArrayBuffer"&&typeof obj.byteLength==="number"}function numberIsNaN(obj){return obj!==obj}},{"base64-js":62,ieee754:380}],93:[function(require,module,exports){"use strict";var monotoneTriangulate=require("./lib/monotone");var makeIndex=require("./lib/triangulation");var delaunayFlip=require("./lib/delaunay");var filterTriangulation=require("./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||[]}var delaunay=!!getDefault(options,"delaunay",true);var interior=!!getDefault(options,"interior",true);var exterior=!!getDefault(options,"exterior",true);var infinity=!!getDefault(options,"infinity",false);if(!interior&&!exterior||points.length===0){return[]}var cells=monotoneTriangulate(points,edges);if(delaunay||interior!==exterior||infinity){var triangulation=makeIndex(points.length,canonicalizeEdges(edges));for(var i=0;i0){var b=stack.pop();var a=stack.pop();var x=-1,y=-1;var star=stars[a];for(var i=1;i=0){continue}triangulation.flip(a,b);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":98,"robust-in-sphere":469}],95:[function(require,module,exports){"use strict";var bsearch=require("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(b0||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}}}}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":98}],96:[function(require,module,exports){"use strict";var bsearch=require("binary-search-bounds");var orient=require("robust-orientation")[3];var EVENT_POINT=0;var EVENT_END=1;var EVENT_START=2;module.exports=monotoneTriangulate;function PartialHull(a,b,idx,lowerIds,upperIds){this.a=a;this.b=b;this.idx=idx;this.lowerIds=lowerIds;this.upperIds=upperIds}function Event(a,b,type,idx){this.a=a;this.b=b;this.type=type;this.idx=idx}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;i1&&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);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]b[0]){events.push(new Event(b,a,EVENT_START,i),new Event(a,b,EVENT_END,i))}}events.sort(compareEvent);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,[],[],[],[])];var cells=[];for(var i=0,numEvents=events.length;i=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>>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)}},{}],99:[function(require,module,exports){"use strict";module.exports=orientation;function orientation(s){var p=1;for(var i=1;imax?max:value:valuemin?min:value}},{}],103:[function(require,module,exports){"use strict";module.exports=cleanPSLG;var UnionFind=require("union-find");var boxIntersect=require("box-intersect");var segseg=require("robust-segment-intersect");var rat=require("big-rat");var ratCmp=require("big-rat/cmp");var ratToFloat=require("big-rat/to-float");var ratVec=require("rat-vec");var nextafter=require("nextafter");var solveIntersection=require("./lib/rat-seg-intersect");function boundRat(r){var f=ratToFloat(r);return[nextafter(f,-Infinity),nextafter(f,Infinity)]}function boundEdges(points,edges){var bounds=new Array(edges.length);for(var i=0;i=0;--i){var junction=junctions[i];e=junction[0];var edge=edges[e];var s=edge[0];var t=edge[1];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}edge[0]=s;var last=edge[1]=junction[1];var color;if(useColor){color=edge[2]}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}if(useColor){edges.push([last,t,color])}else{edges.push([last,t])}}return ratPoints}function dedupPoints(floatPoints,ratPoints,floatBounds){var numPoints=ratPoints.length;var uf=new UnionFind(numPoints);var bounds=[];for(var i=0;ib[2]){return 1}return 0}function dedupEdges(edges,labels,useColor){if(edges.length===0){return}if(labels){for(var i=0;i0||tjunctions.length>0}return true}function cleanPSLG(points,edges,colors){var prevEdges;if(colors){prevEdges=edges;var augEdges=new Array(edges.length);for(var i=0;i>>24;var g=(n&16711680)>>>16;var b=(n&65280)>>>8;var a=n&255;if(normalized===false)return[r,g,b,a];return[r/255,g/255,b/255,a/255]}},{clamp:102}],106:[function(require,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]}},{}],107:[function(require,module,exports){"use strict";var rgba=require("color-rgba");var clamp=require("clamp");var dtype=require("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);if(color instanceof Ctor){if(Array.isArray(color)){return color.slice()}output.set(color);return output}var normalize=type!=="uint8"&&type!=="uint8_clamped";if(color instanceof Uint8Array||color instanceof Uint8ClampedArray){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(!color.length||typeof color==="string"){color=rgba(color);color[0]/=255;color[1]/=255;color[2]/=255}if(!normalize){output[0]=clamp(Math.round(color[0]*255),0,255);output[1]=clamp(Math.round(color[1]*255),0,255);output[2]=clamp(Math.round(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}},{clamp:102,"color-rgba":109,dtype:153}],108:[function(require,module,exports){(function(global){"use strict";var names=require("color-name");var isObject=require("is-plain-obj");var defined=require("defined");module.exports=parse;var baseHues={red:0,orange:60,yellow:120,green:180,blue:240,purple:300};function parse(cstr){var m,parts=[],alpha=1,space;if(typeof cstr==="string"){if(names[cstr]){parts=names[cstr].slice();space="rgb"}else if(cstr==="transparent"){alpha=0;space="rgb";parts=[0,0,0]}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"}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){if(/%$/.test(x)){if(i===size)return parseFloat(x)/100;if(base==="rgb")return parseFloat(x)*255/100;return parseFloat(x)}else if(base[i]==="h"){if(/deg$/.test(x)){return parseFloat(x)}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)}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])/gi).join("").toLowerCase()}}else if(typeof cstr==="number"){space="rgb";parts=[cstr>>>16,(cstr&65280)>>>8,cstr&255]}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}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":106,defined:148,"is-plain-obj":390}],109:[function(require,module,exports){"use strict";var parse=require("color-parse");var hsl=require("color-space/hsl");var clamp=require("clamp");module.exports=function rgba(color){var values,i,l;if(typeof color!=="string")throw Error("Argument should be a string");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:102,"color-parse":108,"color-space/hsl":110}],110:[function(require,module,exports){"use strict";var rgb=require("./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<.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}};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<=.5){s=delta/(max+min)}else{s=delta/(2-max-min)}return[h,s*100,l*100]}},{"./rgb":111}],111:[function(require,module,exports){"use strict";module.exports={name:"rgb",min:[0,0,0],max:[255,255,255],channel:["red","green","blue"],alias:["RGB"]}},{}],112:[function(require,module,exports){module.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]}]}},{}],113:[function(require,module,exports){"use strict";var colorScale=require("./colorScale");var lerp=require("lerp");module.exports=createColormap;function createColormap(spec){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()}indicies=cmap.map(function(c){return Math.round(c.index*nshades)});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(rgba.length===4&&rgba[3]>=0&&rgba[3]<=1){return rgba}rgba[3]=alpha[0]+(alpha[1]-alpha[0])*index;return rgba});var colors=[];for(i=0;i=0}function compareAngle(a,b,c,d){var bcd=orient(b,c,d);if(bcd===0){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":471,"robust-product":472,"robust-sum":476,signum:477,"two-sum":506}],115:[function(require,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;ipoints[hi][0]){hi=i}}if(lohi){return[[hi],[lo]]}else{return[[lo]]}}},{}],119:[function(require,module,exports){"use strict";module.exports=convexHull2D;var monotoneHull=require("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=front[k]){x+=1}}c[j]=x}}}return cells}function convexHullnD(points,d){try{return ich(points,true)}catch(e){var ah=aff(points);if(ah.length<=d){return[]}var npoints=permute(points,ah);var nhull=ich(npoints,true);return invPermute(nhull,ah)}}},{"affine-hull":53,"incremental-convex-hull":381}],121:[function(require,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"}},{}],122:[function(require,module,exports){module.exports=["xx-small","x-small","small","medium","large","x-large","xx-large","larger","smaller"]},{}],123:[function(require,module,exports){module.exports=["normal","condensed","semi-condensed","extra-condensed","ultra-condensed","expanded","semi-expanded","extra-expanded","ultra-expanded"]},{}],124:[function(require,module,exports){module.exports=["normal","italic","oblique"]},{}],125:[function(require,module,exports){module.exports=["normal","bold","bolder","lighter","100","200","300","400","500","600","700","800","900"]},{}],126:[function(require,module,exports){"use strict";module.exports={parse:require("./parse"),stringify:require("./stringify")}},{"./parse":128,"./stringify":129}],127:[function(require,module,exports){"use strict";var sizes=require("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":122}],128:[function(require,module,exports){"use strict";var unquote=require("unquote");var globalKeywords=require("css-global-keywords");var systemFontKeywords=require("css-system-font-keywords");var fontWeightKeywords=require("css-font-weight-keywords");var fontStyleKeywords=require("css-font-style-keywords");var fontStretchKeywords=require("css-font-stretch-keywords");var splitBy=require("string-split-by");var isSize=require("./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":127,"css-font-stretch-keywords":123,"css-font-style-keywords":124,"css-font-weight-keywords":125,"css-global-keywords":130,"css-system-font-keywords":131,"string-split-by":490,unquote:510}],129:[function(require,module,exports){"use strict";var pick=require("pick-by-alias");var isSize=require("./lib/util").isSize;var globals=a2o(require("css-global-keywords"));var systems=a2o(require("css-system-font-keywords"));var weights=a2o(require("css-font-weight-keywords"));var styles=a2o(require("css-font-style-keywords"));var stretches=a2o(require("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);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+"`");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(", ")}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}function a2o(a){var o={};for(var i=0;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},{}],133:[function(require,module,exports){"use strict";var createThunk=require("./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){var proc=new Procedure;proc.pre=user_args.pre;proc.body=user_args.body;proc.post=user_args.post;var proc_args=user_args.args.slice(0);proc.argTypes=proc_args;for(var i=0;i0){throw new Error("cwise: pre() block may not reference array args")}if(i0){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(i0){throw new Error("cwise: pre() block may not reference array index")}if(i0){throw new Error("cwise: post() block may not reference array index")}}else if(arg_type==="shape"){proc.shapeArgs.push(i);if(iproc_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")}proc.debug=!!user_args.printCode||!!user_args.debug;proc.funcName=user_args.funcName||"cwise";proc.blockSize=user_args.blockSize||64;return createThunk(proc)}module.exports=compileCwise},{"./lib/thunk.js":135}],134:[function(require,module,exports){"use strict";var uniq=require("uniq");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;i0){code.push("var "+vars.join(","))}for(i=dimension-1;i>=0;--i){idx=order[i];code.push(["for(i",i,"=0;i",i,"0){code.push(["index[",pidx,"]-=s",pidx].join(""))}code.push(["++index[",idx,"]"].join(""))}code.push("}")}return code.join("\n")}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;i0;){"].join(""));code.push(["if(j",i,"<",blockSize,"){"].join(""));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;i0){allEqual=allEqual&&summary[i]===summary[i-1]}}if(allEqual){return summary[0]}return summary.join("")}function generateCWiseOp(proc,typesig){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;i0){vars.push("shape=SS.slice(0)")}if(proc.indexArgs.length>0){var zeros=new Array(dimension);for(var i=0;i0){code.push("var "+vars.join(","))}for(var i=0;i3){code.push(processBlock(proc.pre,proc,dtypes))}var body=processBlock(proc.body,proc,dtypes);var matched=countMatches(loopOrders);if(matched3){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:509}],135:[function(require,module,exports){"use strict";var compile=require("./compile.js");function createThunk(proc){var code=["'use strict'","var CACHED={}"];var vars=[];var thunkName=proc.funcName+"_cwise_thunk";code.push(["return function ",thunkName,"(",proc.shimArgs.join(","),"){"].join(""));var typesig=[];var string_typesig=[];var proc_args=[["array",proc.arrayArgs[0],".shape.slice(",Math.max(0,proc.arrayBlockIndices[0]),proc.arrayBlockIndices[0]<0?","+proc.arrayBlockIndices[0]+")":")"].join("")];var shapeLengthConditions=[],shapeConditions=[];for(var i=0;i0){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])+"]")}}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--\x3e0;) {");code.push("if (!("+shapeConditions.join(" && ")+")) throw new Error('cwise: Arrays do not all have the same shape!')");code.push("}")}for(var i=0;ib?1:a>=b?0:NaN};var bisector=function(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>>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>>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;var pairs=function(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(ia?1:b>=a?0:NaN};var number=function(x){return x===null?NaN:+x};var variance=function(values,valueof){var n=values.length,m=0,i=-1,mean=0,value,delta,sum=0;if(valueof==null){while(++i1)return sum/(m-1)};var deviation=function(array,f){var v=variance(array,f);return v?Math.sqrt(v):v};var extent=function(values,valueof){var n=values.length,i=-1,value,min,max;if(valueof==null){while(++i=value){min=max=value;while(++ivalue)min=value;if(max=value){min=max=value;while(++ivalue)min=value;if(max0)return[start];if(reverse=stop0){start=Math.ceil(start/step);stop=Math.floor(stop/step);ticks=new Array(n=Math.ceil(stop-start+1));while(++i=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 stopx1)tz.pop(),--m;var bins=new Array(m+1),bin;for(i=0;i<=m;++i){bin=bins[i]=[];bin.x0=i>0?tz[i-1]:x0;bin.x1=i=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)};var freedmanDiaconis=function(values,min,max){values=map.call(values,number).sort(ascending);return Math.ceil((max-min)/(2*(quantile(values,.75)-quantile(values,.25))*Math.pow(values.length,-1/3)))};var scott=function(values,min,max){return Math.ceil((max-min)/(3.5*deviation(values)*Math.pow(values.length,-1/3)))};var max=function(values,valueof){var n=values.length,i=-1,value,max;if(valueof==null){while(++i=value){max=value;while(++imax){max=value}}}}}else{while(++i=value){max=value;while(++imax){max=value}}}}}return max};var mean=function(values,valueof){var n=values.length,m=n,i=-1,value,sum=0;if(valueof==null){while(++i=0){array=arrays[n];m=array.length;while(--m>=0){merged[--j]=array[m]}}return merged};var min=function(values,valueof){var n=values.length,i=-1,value,min;if(valueof==null){while(++i=value){min=value;while(++ivalue){min=value}}}}}else{while(++i=value){min=value;while(++ivalue){min=value}}}}}return min};var permute=function(array,indexes){var i=indexes.length,permutes=new Array(i);while(i--)permutes[i]=array[indexes[i]];return permutes};var scan=function(values,compare){if(!(n=values.length))return;var n,i=0,j=0,xi,xj=values[j];if(compare==null)compare=ascending;while(++i=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(++ikeys.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;if(object instanceof Set)object.each(function(value){set.add(value)});else if(object){var i=-1,n=object.length;if(f==null)while(++i>8&15|m>>4&240,m>>4&15|m&240,(m&15)<<4|m&15,1)):(m=reHex6.exec(format))?rgbn(parseInt(m[1],16)):(m=reRgbInteger.exec(format))?new Rgb(m[1],m[2],m[3],1):(m=reRgbPercent.exec(format))?new Rgb(m[1]*255/100,m[2]*255/100,m[3]*255/100,1):(m=reRgbaInteger.exec(format))?rgba(m[1],m[2],m[3],m[4]):(m=reRgbaPercent.exec(format))?rgba(m[1]*255/100,m[2]*255/100,m[3]*255/100,m[4]):(m=reHslPercent.exec(format))?hsla(m[1],m[2]/100,m[3]/100,1):(m=reHslaPercent.exec(format))?hsla(m[1],m[2]/100,m[3]/100,m[4]):named.hasOwnProperty(format)?rgbn(named[format]):format==="transparent"?new Rgb(NaN,NaN,NaN,0):null}function rgbn(n){return new Rgb(n>>16&255,n>>8&255,n&255,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)},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 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+(g0&&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<.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)}}));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;var Kn=18;var Xn=.95047;var Yn=1;var Zn=1.08883;var t0=4/29;var t1=6/29;var t2=3*t1*t1;var 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){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 b=rgb2xyz(o.r),a=rgb2xyz(o.g),l=rgb2xyz(o.b),x=xyz2lab((.4124564*b+.3575761*a+.1804375*l)/Xn),y=xyz2lab((.2126729*b+.7151522*a+.072175*l)/Yn),z=xyz2lab((.0193339*b+.119192*a+.9503041*l)/Zn);return new Lab(116*y-16,500*(x-y),200*(y-z),o.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+Kn*(k==null?1:k),this.a,this.b,this.opacity)},darker:function(k){return new Lab(this.l-Kn*(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;y=Yn*lab2xyz(y);x=Xn*lab2xyz(x);z=Zn*lab2xyz(z);return new Rgb(xyz2rgb(3.2404542*x-1.5371385*y-.4985314*z),xyz2rgb(-.969266*x+1.8760108*y+.041556*z),xyz2rgb(.0556434*x-.2040259*y+1.0572252*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 xyz2rgb(x){return 255*(x<=.0031308?12.92*x:1.055*Math.pow(x,1/2.4)-.055)}function rgb2xyz(x){return(x/=255)<=.04045?x/12.92:Math.pow((x+.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);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 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+Kn*(k==null?1:k),this.opacity)},darker:function(k){return new Hcl(this.h,this.c,this.l-Kn*(k==null?1:k),this.opacity)},rgb:function(){return labConvert(this).rgb()}}));var A=-.14861;var B=+1.78277;var C=-.29227;var D=-.90649;var E=+1.97294;var ED=E*D;var EB=E*B;var 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)),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.cubehelix=cubehelix;Object.defineProperty(exports,"__esModule",{value:true})})},{}],142:[function(require,module,exports){(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=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(arguments.length<2){while(++i0)for(var args=new Array(n),i=0,n,t;inode.index){var x=xi-data.x-data.vx,y=yi-data.y-data.vy,l=x*x+y*y;if(lxi+r||x1yi+r||y1quad.r){quad.r=quad[i].r}}}function initialize(){if(!nodes)return;var i,n=nodes.length,node;radii=new Array(n);for(i=0;i1?(_==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;i1?(event.on(name,_),simulation):event.on(name)}}};var manyBody=function(){var nodes,node,alpha,strength=constant(-30),strengths,distanceMin2=1,distanceMax2=Infinity,theta2=.81;function force(_){var i,n=nodes.length,tree=d3Quadtree.quadtree(nodes,x$1,y$1).visitAfter(accumulate);for(alpha=_,i=0;i=distanceMax2)return;if(quad.data!==node||quad.next){if(x===0)x=jiggle(),l+=x*x;if(y===0)y=jiggle(),l+=y*y;if(l=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=i180||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$1=function rgbGamma(y){var color$$1=gamma(y);function rgb$$1(start,end){var r=color$$1((start=d3Color.rgb(start)).r,(end=d3Color.rgb(end)).r),g=color$$1(start.g,end.g),b=color$$1(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$$1.gamma=rgbGamma;return rgb$$1}(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$$1;for(i=0;ibi){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:number(am,bm)})}bi=reB.lastIndex}if(bi180)b+=360;else if(b-a>180)a+=360;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=[],q=[];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;return function(t){var i=-1,n=q.length,o;while(++i=(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}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;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;for(i=0;ix1)x1=x;if(yy1)y1=y}if(x1x||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}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()){if(!(node=q.node)||(x1=q.x0)>x3||(y1=q.y0)>y3||(x2=q.x1)=ym)<<1|x>=xm){q=quads[quads.length-1];quads[quads.length-1]=quads[quads.length-1-i];quads[quads.length-1-i]=q}}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=(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}while(node.data!==d)if(!(previous=node,node=node.next))return this;if(next=node.next)delete node.next;if(previous)return next?previous.next=next:delete previous.next,this;if(!parent)return this._root=next,this;next?parent[i]=next:delete parent[i];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=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;if(timeout)timeout=clearTimeout(timeout);var delay=time-clockNow;if(delay>24){if(timeb?1:a>=b?0:NaN}d3.descending=function(a,b){return ba?1:b>=a?0:NaN};d3.min=function(array,f){var i=-1,n=array.length,a,b;if(arguments.length===1){while(++i=b){a=b;break}while(++ib)a=b}else{while(++i=b){a=b;break}while(++ib)a=b}return a};d3.max=function(array,f){var i=-1,n=array.length,a,b;if(arguments.length===1){while(++i=b){a=b;break}while(++ia)a=b}else{while(++i=b){a=b;break}while(++ia)a=b}return a};d3.extent=function(array,f){var i=-1,n=array.length,a,b,c;if(arguments.length===1){while(++i=b){a=c=b;break}while(++ib)a=b;if(c=b){a=c=b;break}while(++ib)a=b;if(c1)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>>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>>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=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)=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=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=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=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(){if(typeof value=="string"){value=value.replace(/\[/g,"");value=value.replace(/\]/g,"");if(value.slice(0,6)=="rotate"){value=value.replace(/\'/g,"")}}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=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=i0)i0=i+1;while(!(node=group[i0])&&++i00)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;i0?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;i1){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;i1?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>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+(g0&&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++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.t8?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&,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"?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-d01){while(time=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+(length68?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=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φ1)φ1=φi}else if(λi=(λi+360)%360-180,antimeridian^(s*λ_<λi&&λiφ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]:xangle(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=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(++i0){if(!polygonStarted)listener.polygonStart(),polygonStarted=true;listener.lineStart();while(++i1&&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]=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(r0){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(r0)return;r/=dy;if(dy<0){if(r0){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(r0)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;iy&&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(xd3_geo_pathBoundsX1)d3_geo_pathBoundsX1=x;if(yd3_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*c10&&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?fromto)from+=direction*τ}else{from=radius+direction*τ;to=radius-.5*step}for(var point,t=from;direction>0?t>to:tε}).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=0;--i)polygon.push(data[points[upper[i]][2]]);for(i=+skipLeft;i1&&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ε)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ε||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=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.y1){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=x1)return;vb={x:x1,y:fm*x1+fb}}else{if(!va)va={x:x1,y:fm*x1+fb};else if(va.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(++jx2_)x2_=d.x;if(d.y>y2_)y2_=d.y;xs.push(d.x);ys.push(d.y)}else for(i=0;ix2_)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(++ix3||y1>y3||x2=xm,below=y>=ym;for(var i=below<<1|right,j=i+4;ibi){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=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=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]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(++i0){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=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(++imax)max=o;sums.push(o)}for(j=0;jv){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(++i0){i=-1;while(++i=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;iright.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;i0){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(++i0){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(++irmax)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(++irect.dx)v=rect.dx;while(++i1);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;j2?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(;i0;k--)ticks.push(pow(i)*k)}for(i=0;ticks[i]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*base0?thresholds[y-1]:domain[0],ya1?0:1;if(r1=τε)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=r00?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(++i1?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(++i1)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(++i1){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;i9){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π)+",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;++j0){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]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}()},{}],148:[function(require,module,exports){module.exports=function(){for(var i=0;i=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;ifs*threshold){var emWidth=(kerningWidth-width)/fs;table[pair]=emWidth*1e3}}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>>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&2146435072){b+=1<<20}return[lo,b]};module.exports.denormalized=function(n){var hi=module.exports.hi(n);return!(hi&2146435072)}}).call(this,require("buffer").Buffer)},{buffer:92}],152:[function(require,module,exports){var abs=require("abs-svg-path");var normalize=require("normalize-svg-path");var methods={M:"moveTo",C:"bezierCurveTo"};module.exports=function(context,segments){context.beginPath();normalize(abs(segments)).forEach(function(segment){var command=segment[0];var args=segment.slice(1);context[methods[command]].apply(context,args)});context.closePath()}},{"abs-svg-path":51,"normalize-svg-path":419}],153:[function(require,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}}},{}],154:[function(require,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;j0){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},{}],155:[function(require,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(data.length>80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var i=dim;imaxX)maxX=x;if(y>maxY)maxY=y}invSize=Math.max(maxX-minX,maxY-minY);invSize=invSize!==0?1/invSize:0}earcutLinked(outerNode,triangles,dim,minX,minY,invSize);return triangles}function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;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}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}function earcutLinked(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;if(!pass&&invSize)indexCurve(ear,minX,minY,invSize);var stop=ear,prev,next;while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)){triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);ear=next.next;stop=next.next;continue}ear=next;if(ear===stop){if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1)}else if(pass===1){ear=cureLocalIntersections(ear,triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,invSize,2)}else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,invSize)}break}}}function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;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;var minTX=a.xb.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;var minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);var p=ear.prevZ,n=ear.nextZ;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}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}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}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);removeNode(p);removeNode(p.next);p=start=b}p=p.next}while(p!==start);return p}function splitEarcut(start,triangles,dim,minX,minY,invSize){var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){var c=splitPolygon(a,b);a=filterPoints(a,a.next);c=filterPoints(c,c.next);earcutLinked(a,triangles,dim,minX,minY,invSize);earcutLinked(c,triangles,dim,minX,minY,invSize);return}b=b.next}a=a.next}while(a!==start)}function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[],i,len,start,end,list;for(i=0,len=holeIndices.length;i=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.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hym.x)&&locallyInside(p,hole)){m=p;tanMin=tan}}p=p.next}return m}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)}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;i0||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}function zOrder(x,y,minX,minY,invSize){x=32767*(x-minX)*invSize;y=32767*(y-minY)*invSize;x=(x|x<<8)&16711935;x=(x|x<<4)&252645135;x=(x|x<<2)&858993459;x=(x|x<<1)&1431655765;y=(y|y<<8)&16711935;y=(y|y<<4)&252645135;y=(y|y<<2)&858993459;y=(y|y<<1)&1431655765;return x|y<<1}function getLeftmost(start){var p=start,leftmost=start;do{if(p.x=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0}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)}function area(p,q,r){return(q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y)}function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y}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}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}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}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}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}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){this.i=i;this.x=x;this.y=y;this.prev=null;this.next=null;this.z=null;this.prevZ=null;this.nextZ=null;this.steiner=false}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;i0){holeIndex+=data[i-1].length;result.holes.push(holeIndex)}}return result}},{}],156:[function(require,module,exports){"use strict";module.exports=edgeToAdjacency;var uniq=require("uniq");function edgeToAdjacency(edges,numVertices){var numEdges=edges.length;if(typeof numVertices!=="number"){numVertices=0;for(var i=0;i=55296&&code<=56319)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){length=toPosInt(arrayLike.length);if(Context)arr=new Context(length);for(i=0;i0?1:-1}},{}],167:[function(require,module,exports){"use strict";var sign=require("../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":164}],168:[function(require,module,exports){"use strict";var toInteger=require("./to-integer"),max=Math.max;module.exports=function(value){return max(0,toInteger(value))}},{"./to-integer":167}],169:[function(require,module,exports){"use strict";var callable=require("./valid-callable"),value=require("./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){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":187,"./valid-value":189}],170:[function(require,module,exports){"use strict";module.exports=require("./is-implemented")()?Object.assign:require("./shim")},{"./is-implemented":171,"./shim":172}],171:[function(require,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"}},{}],172:[function(require,module,exports){"use strict";var keys=require("../keys"),value=require("../valid-value"),max=Math.max;module.exports=function(dest,src){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-1}},{}],193:[function(require,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}},{}],194:[function(require,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}},{}],195:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),contains=require("es5-ext/string/#/contains"),d=require("d"),Symbol=require("es6-symbol"),Iterator=require("./");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);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"))},{"./":198,d:138,"es5-ext/object/set-prototype-of":184,"es5-ext/string/#/contains":190,"es6-symbol":203}],196:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),callable=require("es5-ext/object/valid-callable"),isString=require("es5-ext/string/is-string"),get=require("./get");var isArray=Array.isArray,call=Function.prototype.call,some=Array.prototype.some;module.exports=function(iterable,cb){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=55296&&code<=56319)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":197,"es5-ext/function/is-arguments":161,"es5-ext/object/valid-callable":187,"es5-ext/string/is-string":193}],197:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),isString=require("es5-ext/string/is-string"),ArrayIterator=require("./array"),StringIterator=require("./string"),iterable=require("./valid-iterable"),iteratorSymbol=require("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":195,"./string":200,"./valid-iterable":201,"es5-ext/function/is-arguments":161,"es5-ext/string/is-string":193,"es6-symbol":203}],198:[function(require,module,exports){"use strict";var clear=require("es5-ext/array/#/clear"),assign=require("es5-ext/object/assign"),callable=require("es5-ext/object/valid-callable"),value=require("es5-ext/object/valid-value"),d=require("d"),autoBind=require("d/auto-bind"),Symbol=require("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)};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.__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:138,"d/auto-bind":137,"es5-ext/array/#/clear":157,"es5-ext/object/assign":170,"es5-ext/object/valid-callable":187,"es5-ext/object/valid-value":189,"es6-symbol":203}],199:[function(require,module,exports){"use strict";var isArguments=require("es5-ext/function/is-arguments"),isValue=require("es5-ext/object/is-value"),isString=require("es5-ext/string/is-string");var iteratorSymbol=require("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":161,"es5-ext/object/is-value":178,"es5-ext/string/is-string":193,"es6-symbol":203}],200:[function(require,module,exports){"use strict";var setPrototypeOf=require("es5-ext/object/set-prototype-of"),d=require("d"),Symbol=require("es6-symbol"),Iterator=require("./");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);delete StringIterator.prototype.constructor;StringIterator.prototype=Object.create(Iterator.prototype,{_next:d(function(){if(!this.__list__)return undefined;if(this.__nextIndex__=55296&&code<=56319)return char+this.__list__[this.__nextIndex__++];return char})});defineProperty(StringIterator.prototype,Symbol.toStringTag,d("c","String Iterator"))},{"./":198,d:138,"es5-ext/object/set-prototype-of":184,"es6-symbol":203}],201:[function(require,module,exports){"use strict";var isIterable=require("./is-iterable");module.exports=function(value){if(!isIterable(value))throw new TypeError(value+" is not iterable");return value}},{"./is-iterable":199}],202:[function(require,module,exports){(function(process,global){(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(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]";var isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function useNextTick(){return function(){return process.nextTick(flush)}}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}}function useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=flush;return function(){return channel.port2.postMessage(0)}}function useSetTimeout(){var globalSetTimeout=setTimeout;return function(){return globalSetTimeout(flush,1)}}var queue=new Array(1e3);function flush(){for(var i=0;i0&&this._events[type].length>m){this._events[type].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[type].length);if(typeof console.trace==="function"){console.trace()}}}return this};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.once=function(type,listener){if(!isFunction(listener))throw TypeError("listener must be a function");var fired=false;function g(){this.removeListener(type,g);if(!fired){fired=true;listener.apply(this,arguments)}}g.listener=listener;this.on(type,g);return this};EventEmitter.prototype.removeListener=function(type,listener){var list,position,length,i;if(!isFunction(listener))throw TypeError("listener must be a function");if(!this._events||!this._events[type])return this;list=this._events[type];length=list.length;position=-1;if(list===listener||isFunction(list.listener)&&list.listener===listener){delete this._events[type];if(this._events.removeListener)this.emit("removeListener",type,listener)}else if(isObject(list)){for(i=length;i-- >0;){if(list[i]===listener||list[i].listener&&list[i].listener===listener){position=i;break}}if(position<0)return this;if(list.length===1){list.length=0;delete this._events[type]}else{list.splice(position,1)}if(this._events.removeListener)this.emit("removeListener",type,listener)}return this};EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener){if(arguments.length===0)this._events={};else if(this._events[type])delete this._events[type];return this}if(arguments.length===0){for(key in this._events){if(key==="removeListener")continue;this.removeAllListeners(key)}this.removeAllListeners("removeListener");this._events={};return this}listeners=this._events[type];if(isFunction(listeners)){this.removeListener(type,listeners)}else if(listeners){while(listeners.length)this.removeListener(type,listeners[listeners.length-1])}delete this._events[type];return this};EventEmitter.prototype.listeners=function(type){var ret;if(!this._events||!this._events[type])ret=[];else if(isFunction(this._events[type]))ret=[this._events[type]];else ret=this._events[type].slice();return ret};EventEmitter.prototype.listenerCount=function(type){if(this._events){var evlistener=this._events[type];if(isFunction(evlistener))return 1;else if(evlistener)return evlistener.length}return 0};EventEmitter.listenerCount=function(emitter,type){return emitter.listenerCount(type)};function isFunction(arg){return typeof arg==="function"}function isNumber(arg){return typeof arg==="number"}function isObject(arg){return typeof arg==="object"&&arg!==null}function isUndefined(arg){return arg===void 0}},{}],213:[function(require,module,exports){"use strict";module.exports=extractPlanes;function extractPlanes(M,zNear,zFar){var z=zNear||0;var zf=zFar||1;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]]]}},{}],214:[function(require,module,exports){"use strict";function allBlankCharCodes(str){var l=str.length,a;for(var i=0;i13)&&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}module.exports=function(n){var type=typeof n;if(type==="string"){var original=n;n=+n;if(n===0&&allBlankCharCodes(original))return false}else if(type!=="number")return false;return n-n<1}},{}],215:[function(require,module,exports){"use strict";module.exports=createFilteredVector;var cubicHermite=require("cubic-hermite");var bsearch=require("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=n-1){var ptr=state.length-1;var tf=t-time[n-1];for(var i=0;i=n-1){var ptr=state.length-1;var tf=t-time[n-1];for(var i=0;i=0;--i){if(velocity[--ptr]){return false}}return true};proto.jump=function(t){var t0=this.lastT();var d=this.dimension;if(t0;--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(t1e-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(t0;--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;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=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;ishape[0]-step[0]/2)x=step[0]/2,y+=step[1]}return canvas}},{"css-font/stringify":129}],218:[function(require,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]){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};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;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;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;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;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;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}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}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))}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))}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))}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}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;i0;i-=4){if(data[i]!==0){return Math.floor((i-3)*.25/l)}}}},{}],219:[function(require,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}});Object.defineProperty(proto,"length",{get:function(){if(this.root){return this.root._count}return 0}});proto.insert=function(key,value){var cmp=this._compare;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}}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)}}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){p._color=BLACK;pp.right=repaint(BLACK,y);pp._color=RED;s-=1}else{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){p._color=BLACK;pp.right=repaint(BLACK,y);pp._color=RED;s-=1}else{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){p._color=BLACK;pp.left=repaint(BLACK,y);pp._color=RED;s-=1}else{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){p._color=BLACK;pp.left=repaint(BLACK,y);pp._color=RED;s-=1}else{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}}}}n_stack[0]._color=BLACK;return new RedBlackTree(cmp,n_stack[0])};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)}}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)}}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}};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)}});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)}});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.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)};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,[])};proto.remove=function(key){var iter=this.find(key);if(iter){return iter.remove()}return this};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};function RedBlackTreeIterator(tree,stack){this.tree=tree;this._stack=stack}var iproto=RedBlackTreeIterator.prototype;Object.defineProperty(iproto,"valid",{get:function(){return this._stack.length>0}});Object.defineProperty(iproto,"node",{get:function(){if(this._stack.length>0){return this._stack[this._stack.length-1]}return null},enumerable:true});iproto.clone=function(){return new RedBlackTreeIterator(this.tree,this._stack.slice())};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}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}p=stack[i-1];if(p.left===n){s=p.right;if(s.right&&s.right._color===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){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){p._color=BLACK;p.right=repaint(RED,s);return}else{p.right=repaint(RED,s);continue}}else{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+11){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){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){p._color=BLACK;p.left=repaint(RED,s);return}else{p.left=repaint(RED,s);continue}}else{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=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)}}n=cstack[cstack.length-1];if(n.left&&n.right){var split=cstack.length;n=n.left;while(n.right){cstack.push(n);n=n.right}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;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]}n=cstack[cstack.length-1];if(n._color===RED){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;i0){return this._stack[this._stack.length-1].key}return},enumerable:true});Object.defineProperty(iproto,"value",{get:function(){if(this._stack.length>0){return this._stack[this._stack.length-1].value}return},enumerable:true});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});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()}}};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}});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])};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()}}};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}});function defaultCompare(a,b){if(ab){return 1}return 0}function createRBTree(compare){return new RedBlackTree(compare||defaultCompare,null)}},{}],220:[function(require,module,exports){var g=7;var p=[.9999999999998099,676.5203681218851,-1259.1392167224028,771.3234287776531,-176.6150291621406,12.507343278686905,-.13857109526572012,9984369578019572e-21,1.5056327351493116e-7];var g_ln=607/128;var p_ln=[.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 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+.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<.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;i0){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 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;var model=params.model||identity;var view=params.view||identity;var projection=params.projection||identity;var bounds=this.bounds;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]}var lineOffset=LINE_OFFSET;for(var i=0;i<3;++i){computeLineOffset(LINE_OFFSET[i],i,this.bounds,cubeEdges,cubeAxis)}var gl=this.gl;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);this._lines.bind(model,view,projection,this);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]}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)}}for(var j=0;j<2;++j){var u=(i+1+j)%3;var v=(i+1+(j^1))%3;if(this.zeroEnable[v]){if(bounds[0][v]<=0&&bounds[1][v]>=0){this._lines.drawZero(u,v,this.bounds,x,this.zeroLineColor[v],this.zeroLineWidth[v]*this.pixelRatio)}}}}for(var i=0;i<3;++i){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)}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}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();this._text.bind(model,view,projection,this.pixelRatio);for(var i=0;i<3;++i){var minor=lineOffset[i].primalMinor;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]}}if(this.tickEnable[i]){for(var j=0;j<3;++j){offset[j]+=pixelScaleF*minor[j]*this.tickPad[j]/model[5*j]}this._text.drawTicks(i,this.tickSize[i],this.tickAngle[i],offset,this.tickColor[i])}if(this.labelEnable[i]){for(var j=0;j<3;++j){offset[j]+=pixelScaleF*minor[j]*this.labelPad[j]/model[5*j]}offset[i]+=.5*(bounds[0][i]+bounds[1][i]);this._text.drawLabel(i,this.labelSize[i],this.labelAngle[i],offset,this.labelColor[i])}}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":223,"./lib/cube.js":224,"./lib/lines.js":225,"./lib/text.js":227,"./lib/ticks.js":228}],223:[function(require,module,exports){"use strict";module.exports=createBackgroundCube;var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var createShader=require("./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){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}}var tt=u;u=v;v=tt}}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);var shader=createShader(gl);shader.attributes.position.location=0;shader.attributes.normal.location=1;return new BackgroundCube(gl,buffer,vao,shader)}},{"./shaders":226,"gl-buffer":230,"gl-vao":308}],224:[function(require,module,exports){"use strict";module.exports=getCubeEdges;var bits=require("bit-twiddle");var multiply=require("gl-mat4/multiply");var invert=require("gl-mat4/invert");var splitPoly=require("split-polygon");var orient=require("robust-orientation");var mvp=new Array(16);var imvp=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;io0){closest|=1<o0){closest|=1<cubeVerts[i][1]){bottom=i}}var left=-1;for(var i=0;i<3;++i){var idx=bottom^1<cubeVerts[right][0]){right=idx}}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}var axis=CUBE_AXIS;var cutCorner=closest;for(var d=0;d<3;++d){if(cutCorner&1< 0.0) {\n vec3 nPosition = mix(bounds[0], bounds[1], 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 colorChannel = abs(normal);\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":287,glslify:377}],227:[function(require,module,exports){(function(process){"use strict";module.exports=createTextSprites;var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var vectorizeText=require("vectorize-text");var createShader=require("./shaders").text;var globals=window||process.global||{};var __TEXT_CACHE=globals.__TEXT_CACHE||{};globals.__TEXT_CACHE={};var VERTEX_SIZE=3;var VERTEX_STRIDE=VERTEX_SIZE*4;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;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 gl=this.gl;var data=[];function addItem(t,text,font,size){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"})}var scale=(size||12)/12;var positions=mesh.positions;var cells=mesh.cells;var lo=[Infinity,Infinity];var hi=[-Infinity,-Infinity];for(var i=0,nc=cells.length;i=0;--j){var p=positions[c[j]];data.push(scale*p[0],-scale*p[1],t)}}}var tickOffset=[0,0,0];var tickCount=[0,0,0];var labelOffset=[0,0,0];var labelCount=[0,0,0];for(var d=0;d<3;++d){labelOffset[d]=data.length/VERTEX_SIZE|0;addItem(.5*(bounds[0][d]+bounds[1][d]),labels[d],labelFont);labelCount[d]=(data.length/VERTEX_SIZE|0)-labelOffset[d];tickOffset[d]=data.length/VERTEX_SIZE|0;for(var i=0;i=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=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;jlen){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=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"){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)){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"){this.length=updateTypeArray(this.gl,this.type,this.length,this.usage,array,offset)}else if(typeof array==="number"||array===undefined){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{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:417,"ndarray-ops":411,"typedarray-pool":507}],231:[function(require,module,exports){"use strict";var V=require("gl-vec3");var V4=require("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=v){return i-1}}return i};var tmp=V.create();var tmp2=V.create();var clamp=function(v,min,max){return vmax?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;var x0=findLastSmallerIndex(meshgrid[0],x);var y0=findLastSmallerIndex(meshgrid[1],y);var z0=findLastSmallerIndex(meshgrid[2],z);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)}if(x0<0||y0<0||z0<0||x1>=w||y1>=h||z1>=d){return V.create()}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;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();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){if(v[0]===0&&v[1]===0){V.set(dst,0,1,0)}else{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}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;imaxNorm){maxNorm=V.length(u)}if(i){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}var invertedMaxNorm=1/maxNorm;if(!isFinite(vectorScale)||isNaN(vectorScale)){vectorScale=1}geo.vectorScale=vectorScale;var nml=vec3(0,1,0);var coneScale=vectorfield.coneSize||.5;if(vectorfield.absoluteConeSize){coneScale=vectorfield.absoluteConeSize*invertedMaxNorm}geo.coneScale=coneScale;for(var i=0,j=0;i1.0001){return null}s+=weights[i]}if(Math.abs(s-1)>.001){return null}return[closestIndex,interpolate(simplex,weights),weights]}},{barycentric:61,"polytope-closest-point/lib/closest_point_2d.js":448}],233:[function(require,module,exports){"use strict";var DEFAULT_VERTEX_NORMALS_EPSILON=1e-6;var DEFAULT_FACE_NORMALS_EPSILON=1e-6;var createShader=require("gl-shader");var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var createTexture=require("gl-texture2d");var normals=require("normals");var multiply=require("gl-mat4/multiply");var invert=require("gl-mat4/invert");var ndarray=require("ndarray");var colormap=require("colormap");var getContour=require("simplicial-complex-contour");var pool=require("typedarray-pool");var shaders=require("./shaders");var closestPoint=require("./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=.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=1/4;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;i0){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])}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};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{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){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;var pointShader=null;var pickShader=createPickShader(gl);var pointPickShader=null;var contourShader=null;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":232,"./shaders":234,colormap:113,"gl-buffer":230,"gl-mat4/invert":254,"gl-mat4/multiply":256,"gl-shader":287,"gl-texture2d":303,"gl-vao":308,ndarray:417,normals:420,"simplicial-complex-contour":479,"typedarray-pool":507}],234:[function(require,module,exports){var glslify=require("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;\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 vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal), 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_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\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(any(lessThan(f_data, clipBounds[0])) || \n // any(greaterThan(f_data, clipBounds[1]))) {\n // discard;\n //}\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 vec4 conePosition = model * vec4(position.xyz, 1.0) + vec4(getConePosition(mat3(model) * ((vectorScale * coneScale) * vector), position.w, coneOffset, normal), 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\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n 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:377}],235:[function(require,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",34e3:"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"}},{}],236:[function(require,module,exports){var gl10=require("./1.0/numbers");module.exports=function lookupConstant(number){return gl10[number]}},{"./1.0/numbers":235}],237:[function(require,module,exports){"use strict";module.exports=createErrorBars;var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var createShader=require("./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}var proto=ErrorBars.prototype;proto.isOpaque=function(){return this.opacity>=1};proto.isTransparent=function(){return this.opacity<1};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;i0){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":238,"gl-buffer":230,"gl-vao":308}],238:[function(require,module,exports){"use strict";var glslify=require("glslify");var createShader=require("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\nuniform vec3 clipBounds[2];\nuniform float opacity;\nvarying vec3 fragPosition;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(fragPosition, clipBounds[0])) || any(greaterThan(fragPosition, clipBounds[1]))) {\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":287,glslify:377}],239:[function(require,module,exports){"use strict";var createTexture=require("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;j1){ext.drawBuffersWEBGL(colorAttachmentArrays[numColors])}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)}}var status=gl.checkFramebufferStatus(gl.FRAMEBUFFER);if(status!==gl.FRAMEBUFFER_COMPLETE){fbo._destroyed=true;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;imaxFBOSize||h<0||h>maxFBOSize){throw new Error("gl-fbo: Can't resize FBO, invalid dimensions")}fbo._shape[0]=w;fbo._shape[1]=h;var state=saveFBOState(gl);for(var i=0;imaxFBOSize||height<0||height>maxFBOSize){throw new Error("gl-fbo: Parameters are too large for FBO")}options=options||{};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){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")}}}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}}var useDepth=true;if("depth"in options){useDepth=!!options.depth}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":303}],240:[function(require,module,exports){var sprintf=require("sprintf-js").sprintf;var glConstants=require("gl-constants/lookup");var shaderName=require("glsl-shader-name");var addLineNumbers=require("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>i*8&255}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+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/(hix-lox);var ys=1/(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 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\nuniform float pickId;\nuniform vec3 clipBounds[2];\n\nvarying vec3 worldPosition;\nvarying float pixelArcLength;\nvarying vec4 fragColor;\n\nvoid main() {\n if(any(lessThan(worldPosition, clipBounds[0])) || any(greaterThan(worldPosition, clipBounds[1]))) {\n 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":287,glslify:377}],245:[function(require,module,exports){"use strict";module.exports=createLinePlot;var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var createTexture=require("gl-texture2d");var unpackFloat=require("glsl-read-float");var bsearch=require("binary-search-bounds");var ndarray=require("ndarray");var shaders=require("./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;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.dirty=true;this.pixelRatio=1}var proto=LinePlot.prototype;proto.isTransparent=function(){return this.opacity<1};proto.isOpaque=function(){return this.opacity>=1};proto.pickSlots=1;proto.setPickBase=function(id){this.pickId=id};proto.drawTransparent=proto.draw=function(camera){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){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}if("opacity"in options){this.opacity=+options.opacity}var positions=options.position||options.positions;if(!positions){return}var colors=options.color||options.colors||[0,0,0,1];var lineWidth=options.lineWidth||1;var buffer=[];var arcLengthArray=[];var pointArray=[];var arcLength=0;var vertexCount=0;var bounds=[[Infinity,Infinity,Infinity],[-Infinity,-Infinity,-Infinity]];var hadGap=false;fill_loop:for(i=1;i0){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[i-1];bcolor=colors[i]}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]}var w0;if(Array.isArray(lineWidth)){w0=lineWidth[i-1]}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;var prefixSum=dashArray.slice();prefixSum.unshift(0);for(i=1;i1.0001){return null}s+=weights[i]}if(Math.abs(s-1)>.001){return null}return[closestIndex,interpolate(simplex,weights),weights]}},{barycentric:61,"polytope-closest-point/lib/closest_point_2d.js":448}],267:[function(require,module,exports){var glslify=require("glslify");var triVertSrc=glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute vec3 position, normal;\nattribute vec4 color;\nattribute vec2 uv;\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;\nvarying vec4 f_color;\nvarying vec2 f_uv;\n\nvoid main() {\n vec4 m_position = model * vec4(position, 1.0);\n vec4 t_position = view * m_position;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = position;\n f_eyeDirection = eyePosition - position;\n f_lightDirection = lightPosition - position;\n f_uv = uv;\n}\n"]);var triFragSrc=glslify(["#extension GL_OES_standard_derivatives : enable\n\nprecision highp 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\nvec3 normals(vec3 pos) {\n vec3 fdx = dFdx(pos);\n vec3 fdy = dFdy(pos);\n return normalize(cross(fdx, fdy));\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(any(lessThan(f_data, clipBounds[0])) ||\n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n vec3 N = normalize(f_normal);\n vec3 L = normalize(f_lightDirection);\n vec3 V = normalize(f_eyeDirection);\n\n vec3 normal = normals(f_data);\n\n if (\n dot(N, normal) < 0.0\n ) {\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 = 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\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(any(lessThan(f_data, clipBounds[0])) || \n any(greaterThan(f_data, clipBounds[1]))) {\n discard;\n }\n\n gl_FragColor = f_color * texture2D(texture, f_uv) * opacity;\n}"]);var pointVertSrc=glslify(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\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\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\n if(any(lessThan(f_position, clipBounds[0])) || \n any(greaterThan(f_position, clipBounds[1]))) {\n discard;\n }\n gl_FragColor = vec4(pickId, f_id.xyz);\n}"]);var pickPointVertSrc=glslify(["precision mediump float;\n#define GLSLIFY 1\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(any(lessThan(position, clipBounds[0])) || \n any(greaterThan(position, clipBounds[1]))) {\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:377}],268:[function(require,module,exports){"use strict";var DEFAULT_VERTEX_NORMALS_EPSILON=1e-6;var DEFAULT_FACE_NORMALS_EPSILON=1e-6;var createShader=require("gl-shader");var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var createTexture=require("gl-texture2d");var normals=require("normals");var multiply=require("gl-mat4/multiply");var invert=require("gl-mat4/invert");var ndarray=require("ndarray");var colormap=require("colormap");var getContour=require("simplicial-complex-contour");var pool=require("typedarray-pool");var shaders=require("./lib/shaders");var closestPoint=require("./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 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,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=.8;this.diffuseLight=.8;this.specularLight=2;this.roughness=.5;this.fresnel=1.5;this.opacity=1;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;i0){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])}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};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;itickOffset[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;if(tickEnable[axis+2]){SCREEN_OFFSET[axis^1]+=screenScale*pixelRatio*tickPad[axis+2];if(starttickOffset[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*(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();for(var i=0;i<2;++i){var lo=bounds[i];var hi=bounds[i+2];var boundScale=hi-lo;var dataCenter=.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*boundScale/dataWidth*viewScale/screenScale;DATA_SHIFT[i]=2*(lo-dataCenter)/dataWidth*viewScale/screenScale}TEXT_SCALE[1]=2*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;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];var ticks=axesTicks[dimension];for(i=0;i=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])}}}for(var i=0;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;i0){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})}if(!gl){throw new Error("webgl not supported")}var bounds=options.bounds||[[-10,-10,-10],[10,10,10]];var selection=new MouseSelect;var accumBuffer=createFBO(gl,[gl.drawingBufferWidth,gl.drawingBufferHeight],{preferFloat:!isMobile});var accumShader=createShader(gl);var cameraOptions=options.camera||{eye:[2,0,0],center:[0,0,0],up:[0,1,0],zoomMin:.1,zoomMax:100,mode:"turntable"};var axesOptions=options.axes||{};var axes=createAxes(gl,axesOptions);axes.enable=!axesOptions.disable;var spikeOptions=options.spikes||{};var spikes=createSpikes(gl,spikeOptions);var objects=[];var pickBufferIds=[];var pickBufferCount=[];var pickBuffers=[];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];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||.01,zFar:options.zFar||1e3,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;i0&&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}axes.dispose();spikes.dispose();for(var i=0;iselection.distance){continue}for(var j=0;j 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:377}],279:[function(require,module,exports){"use strict";var createShader=require("gl-shader");var createBuffer=require("gl-buffer");var pool=require("typedarray-pool");var SHADERS=require("./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=.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=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",.5);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);var pointCount=options.positions.length>>>1;var dataStraightThrough=options.positions instanceof Float32Array;var idStraightThrough=options.idToIndex instanceof Int32Array&&options.idToIndex.length>=pointCount;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>>1;var i;for(i=0;i=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,.33333)));MATRIX[0]=2/dataX;MATRIX[4]=2/dataY;MATRIX[6]=-2*dataBox[0]/dataX-1;MATRIX[7]=-2*dataBox[1]/dataY-1;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&255;PICK_VEC4[1]=pickOffset>>8&255;PICK_VEC4[2]=pickOffset>>16&255;PICK_VEC4[3]=pickOffset>>24&255;this.pickBuffer.bind();shader.attributes.pickId.pointer(gl.UNSIGNED_BYTE);shader.uniforms.pickOffset=PICK_VEC4;this.pickOffset=pickOffset}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+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);plot.addObject(result);return result}},{"./lib/shader":278,"gl-buffer":230,"gl-shader":287,"typedarray-pool":507}],280:[function(require,module,exports){module.exports=slerp;function slerp(out,a,b,t){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;cosom=ax*bx+ay*by+az*bz+aw*bw;if(cosom<0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw}if(1-cosom>1e-6){omega=Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom}else{scale0=1-t;scale1=t}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}},{}],281:[function(require,module,exports){"use strict";var vectorizeText=require("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 lineSymbol=vectorizeText(symbol,{textAlign:"center",textBaseline:"middle",lineHeight:1,font:font});var triSymbol=vectorizeText(symbol,{triangles:true,textAlign:"center",textBaseline:"middle",lineHeight:1,font:font});var bounds=[[Infinity,Infinity],[-Infinity,-Infinity]];for(var i=0;i=1){return true}for(var i=0;i<3;++i){if(this.axesProject[i]&&this.projectOpacity[i]>=1){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,transparent,forceDraw){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/gl.drawingBufferWidth;VIEW_SHAPE[1]=2/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;uniforms.pixelRatio=points.pixelRatio;for(var i=0;i<3;++i){if(!axesProject[i]){continue}if(points.projectOpacity[i]<1!==transparent){continue}uniforms.scale=points.projectScale[i];uniforms.opacity=points.projectOpacity[i];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;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;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;var sv=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;uniforms.fragClipBounds[0]=setComponent(SCRATCH_VEC,clipBounds[0],i,-1e8);uniforms.fragClipBounds[1]=setComponent(SCRATCH_VEC,clipBounds[1],i,1e8);points.vao.draw(gl.TRIANGLES,points.vertexCount);if(points.lineWidth>0){gl.lineWidth(points.lineWidth);points.vao.draw(gl.LINES,points.lineVertexCount,points.vertexCount)}}}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;points.vao.bind();if(transparent===points.opacity<1||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/gl.drawingBufferWidth;VIEW_SHAPE[1]=2/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;uniforms.pixelRatio=points.pixelRatio;points.vao.draw(gl.TRIANGLES,points.vertexCount);if(points.lineWidth>0){gl.lineWidth(points.lineWidth);points.vao.draw(gl.LINES,points.lineVertexCount,points.vertexCount)}}drawProject(pshader,points,camera,transparent,forceDraw);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,false,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}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&255;var a1=pointId>>8&255;var a2=pointId>>16&255;this.highlightId=[a0/255,a1/255,a2/255,0]}};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]}}if("projectOpacity"in options){if(Array.isArray(options.projectOpacity)){this.projectOpacity=options.projectOpacity.slice()}else{var s=+options.projectOpacity;this.projectOpacity=[s,s,s]}}if("opacity"in options){this.opacity=options.opacity}this.dirty=true;var points=options.position;if(!points){return}var font=options.font||"normal";var alignment=options.alignment||[0,0];var lowerBound=[Infinity,Infinity,Infinity];var upperBound=[-Infinity,-Infinity,-Infinity];var glyphs=options.glyph;var colors=options.color;var sizes=options.size;var angles=options.angle;var lineColors=options.lineColor;var pickCounter=0;var triVertexCount=0;var lineVertexCount=0;var numPoints=points.length;count_loop:for(var i=0;i0){textOffset[0]=-alignment[0]*(1+glyphBounds[0][0])}var cells=glyphMesh.cells;var verts=glyphMesh.positions;for(var j=0;j0){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,.5]).slice();this.outerColor=(options.outerColor||[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":284,"gl-buffer":230,"gl-shader":287}],286:[function(require,module,exports){"use strict";module.exports=createSelectBuffer;var createFBO=require("gl-fbo");var pool=require("typedarray-pool");var ndarray=require("ndarray");var nextPow2=require("bit-twiddle").nextPow2;var selectRange=require("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_fthis.buffer.length){pool.free(this.buffer);var buffer=this.buffer=pool.mallocUint8(nextPow2(r*c*4));for(var i=0;ioldAttribCount){for(i=oldAttribCount;inewAttribCount){for(i=newAttribCount;i=0){var size=attr.type.charAt(attr.type.length-1)|0;var locVector=new Array(size);for(var j=0;j=0){curLocation+=1}attributeLocations[i]=curLocation}}var uniformLocations=new Array(uniforms.length);function relink(){wrapper.program=shaderCache.program(gl,wrapper._vref,wrapper._fref,attributeNames,attributeLocations);for(var i=0;i=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":288}],290:[function(require,module,exports){"use strict";var coallesceUniforms=require("./reflect");var GLError=require("./GLError");module.exports=createUniformWrapper;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;i4){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;i4){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;i1){if(!(x[0]in o)){o[x[0]]=[]}o=o[x[0]];for(var k=1;k1){for(var j=0;j 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;\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 vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal), 0.0);\n normal = normalize(normal * inverse(mat3(model)));\n\n vec4 t_position = view * tubePosition;\n gl_Position = projection * t_position;\n f_color = color;\n f_normal = normal;\n f_data = tubePosition.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\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 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 vec4 tubePosition = model * vec4(position.xyz, 1.0) + vec4(getTubePosition(mat3(model) * (tubeScale * vector.w * normalize(vector.xyz)), position.w, normal), 0.0);\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\nuniform vec3 clipBounds[2];\nuniform float pickId;\n\nvarying vec3 f_position;\nvarying vec4 f_id;\n\nvoid main() {\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:377}],299:[function(require,module,exports){"use strict";var DEFAULT_VERTEX_NORMALS_EPSILON=1e-6;var DEFAULT_FACE_NORMALS_EPSILON=1e-6;var createShader=require("gl-shader");var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var createTexture=require("gl-texture2d");var normals=require("normals");var multiply=require("gl-mat4/multiply");var invert=require("gl-mat4/invert");var ndarray=require("ndarray");var colormap=require("colormap");var getContour=require("simplicial-complex-contour");var pool=require("typedarray-pool");var shaders=require("./shaders");var closestPoint=require("./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=.8;this.diffuseLight=.8;this.specularLight=2;this.roughness=.5;this.fresnel=1.5;this.opacity=1;this.tubeScale=1;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;i0){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])}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};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.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 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;var pointShader=null;var pickShader=createPickShader(gl);var pointPickShader=null;var contourShader=null;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":297,"./shaders":298,colormap:113,"gl-buffer":230,"gl-mat4/invert":254,"gl-mat4/multiply":256,"gl-shader":287,"gl-texture2d":303,"gl-vao":308,ndarray:417,normals:420,"simplicial-complex-contour":479,"typedarray-pool":507}],300:[function(require,module,exports){"use strict";var vec3=require("gl-vec3");var vec4=require("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;i0){for(var a=0;amaxNorm){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;iv)return i-1}return i};var tmp=vec3.create();var tmp2=vec3.create();var clamp=function(v,min,max){return vmax?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;var x0=findLastSmallerIndex(meshgrid[0],x);var y0=findLastSmallerIndex(meshgrid[1],y);var z0=findLastSmallerIndex(meshgrid[2],z);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)}if(x0<0||y0<0||z0<0||x1>=w||y1>=h||z1>=d){return vec3.create()}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;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();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=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;var tmp=vec3.create();if(positions.length>=2){minDistance=calculateMinPositionDistance(positions)}for(var i=0;imaxDivergence&&!isNaN(dvLength)&&isFinite(dvLength)){maxDivergence=dvLength}divergences.push(dvLength);streams.push({points:stream,velocities:velocities,divergences:divergences});var j=0;while(jmaxStepSizeSq){vec3.scale(np,np,maxStepSize/Math.sqrt(sqLen))}vec3.add(np,np,p);v=vectorField.getVelocity(np);if(vec3.squaredDistance(op,np)-maxStepSizeSq>-1e-4*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}divergences.push(dvLength)}p=np}}for(var i=0;i 0.0 ||\n any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n discard;\n }\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 = step(vertexColor, .5) * texture2D(colormap, vec2(value, value)) + 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 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 vec4 worldPosition = model * vec4(dataCoordinate, 1.0);\n\n vec4 clipPosition = projection * view * worldPosition;\n clipPosition.z = clipPosition.z + zOffset;\n\n gl_Position = clipPosition;\n value = f;\n kill = -1.0;\n worldCoordinate = dataCoordinate;\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\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 any(lessThan(worldCoordinate, clipBounds[0])) || any(greaterThan(worldCoordinate, clipBounds[1]))) {\n 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":287,glslify:377}],302:[function(require,module,exports){"use strict";module.exports=createSurfacePlot;var bits=require("bit-twiddle");var createBuffer=require("gl-buffer");var createVAO=require("gl-vao");var createTexture=require("gl-texture2d");var pool=require("typedarray-pool");var colormap=require("colormap");var ops=require("ndarray-ops");var pack=require("ndarray-pack");var ndarray=require("ndarray");var surfaceNets=require("surface-nets");var multiply=require("gl-mat4/multiply");var invert=require("gl-mat4/invert");var bsearch=require("binary-search-bounds");var gradient=require("ndarray-gradient");var shaders=require("./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);return x}function SurfacePlot(gl,shape,bounds,shader,pickShader,coordinates,vao,colorMap,contourShader,contourPickShader,contourBuffer,contourVAO,dynamicBuffer,dynamicVAO){this.gl=gl;this.shape=shape;this.bounds=bounds;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=[[.5,.5,.5,1],[.5,.5,.5,1],[.5,.5,.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];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];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;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=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;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){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,contourTint:0,contourColor:[0,0,0,1],permutation:[1,0,0,0,1,0,0,0,1],zOffset:-1e-4,kambient:1,kdiffuse:1,kspecular:1,lightPosition:[1e3,1e3,1e3],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.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;uniforms.permutation=DEFAULT_PERM;uniforms.vertexColor=this.vertexColor;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){this._shader.bind();this._shader.uniforms=uniforms;this._vao.bind();if(this.showSurface&&this._vertexCount){this._vao.draw(gl.TRIANGLES,this._vertexCount)}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;uniforms.kambient=1;uniforms.kdiffuse=0;uniforms.kspecular=0;uniforms.opacity=1;shader.bind();shader.uniforms=uniforms;var vao=this._contourVAO;vao.bind();for(i=0;i<3;++i){shader.uniforms.permutation=PERMUTATIONS[i];gl.lineWidth(this.contourWidth[i]);for(j=0;j>4)/16)/255;var ix=Math.floor(x);var fx=x-ix;var y=shape[1]*(selection.value[1]+(selection.value[2]&15)/16)/255;var iy=Math.floor(y);var fy=y-iy;ix+=1;iy+=1;var pos=result.position;pos[0]=pos[1]=pos[2]=0;for(var dx=0;dx<2;++dx){var s=dx?fx:1-fx;for(var dy=0;dy<2;++dy){var t=dy?fy:1-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}}}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]Math.abs(b-pos[j])){levelIndex[j]+=1}}}result.index[0]=fx<.5?ix:ix+1;result.index[1]=fy<.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};function padField(nfield,field){var shape=field.shape.slice();var nshape=nfield.shape.slice();ops.assign(nfield.lo(1,1).hi(shape[0],shape[1]),field);ops.assign(nfield.lo(1).hi(shape[0],1),field.hi(shape[0],1));ops.assign(nfield.lo(1,nshape[1]-1).hi(shape[0],1),field.lo(0,shape[1]-1).hi(shape[0],1));ops.assign(nfield.lo(0,1).hi(1,shape[1]),field.hi(1));ops.assign(nfield.lo(nshape[0]-1,1).hi(1,shape[1]),field.lo(shape[0]-1));nfield.set(0,0,field.get(0,0));nfield.set(0,nshape[1]-1,field.get(0,shape[1]-1));nfield.set(nshape[0]-1,0,field.get(shape[0]-1,0));nfield.set(nshape[0]-1,nshape[1]-1,field.get(shape[0]-1,shape[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.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&¶ms.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)}}if("field"in params||"coords"in params){var fsize=(field.shape[0]+2)*(field.shape[1]+2);if(fsize>this._field[2].data.length){pool.freeFloat(this._field[2].data);this._field[2].data=pool.mallocFloat(bits.nextPow2(fsize))}this._field[2]=ndarray(this._field[2].data,[field.shape[0]+2,field.shape[1]+2]);padField(this._field[2],field);this.shape=field.shape.slice();var shape=this.shape;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])}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")}}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")}var tick2=ndarray(tick.data,shape);tick2.stride[i]=tick.stride[0];tick2.stride[i^1]=0;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;j0){for(var l=0;l<5;++l){contourVerts.pop()}vertexCount-=1}continue edge_loop}}}levelCounts.push(vertexCount)}this._contourOffsets[dim]=levelOffsets;this._contourCounts[dim]=levelCounts}var floatBuffer=pool.mallocFloat(contourVerts.length);for(i=0;imaxSize||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);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")}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){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{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)}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:417,"ndarray-ops":411,"typedarray-pool":507}],304:[function(require,module,exports){"use strict";var pick=require("pick-by-alias");module.exports=function setContext(o){if(!o)o={};else if(typeof o==="string")o={container:o};if(isCanvas(o)){o={container:o}}else if(isElement(o)){o={container:o}}else if(isContext(o)){o={gl:o}}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;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)}}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)}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":432}],305:[function(require,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;i1){return 0}else{return Math.acos(cosine)}}},{"./dot":317,"./fromValues":319,"./normalize":328}],311:[function(require,module,exports){module.exports=clone;function clone(a){var out=new Float32Array(3);out[0]=a[0];out[1]=a[1];out[2]=a[2];return out}},{}],312:[function(require,module,exports){module.exports=copy;function copy(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];return out}},{}],313:[function(require,module,exports){module.exports=create;function create(){var out=new Float32Array(3);out[0]=0;out[1]=0;out[2]=0;return out}},{}],314:[function(require,module,exports){module.exports=cross;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}},{}],315:[function(require,module,exports){module.exports=distance;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)}},{}],316:[function(require,module,exports){module.exports=divide;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}},{}],317:[function(require,module,exports){module.exports=dot;function dot(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]}},{}],318:[function(require,module,exports){module.exports=forEach;var vec=require("./create")();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;i0){len=1/Math.sqrt(len);out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len}return out}},{}],329:[function(require,module,exports){module.exports=random;function random(out,scale){scale=scale||1;var r=Math.random()*2*Math.PI;var z=Math.random()*2-1;var zScale=Math.sqrt(1-z*z)*scale;out[0]=Math.cos(r)*zScale;out[1]=Math.sin(r)*zScale;out[2]=z*scale;return out}},{}],330:[function(require,module,exports){module.exports=rotateX;function rotateX(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0];r[1]=p[1]*Math.cos(c)-p[2]*Math.sin(c);r[2]=p[1]*Math.sin(c)+p[2]*Math.cos(c);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}},{}],331:[function(require,module,exports){module.exports=rotateY;function rotateY(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[2]*Math.sin(c)+p[0]*Math.cos(c);r[1]=p[1];r[2]=p[2]*Math.cos(c)-p[0]*Math.sin(c);out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}},{}],332:[function(require,module,exports){module.exports=rotateZ;function rotateZ(out,a,b,c){var p=[],r=[];p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];r[0]=p[0]*Math.cos(c)-p[1]*Math.sin(c);r[1]=p[0]*Math.sin(c)+p[1]*Math.cos(c);r[2]=p[2];out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out}},{}],333:[function(require,module,exports){module.exports=scale;function scale(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;return out}},{}],334:[function(require,module,exports){module.exports=scaleAndAdd;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}},{}],335:[function(require,module,exports){module.exports=set;function set(out,x,y,z){out[0]=x;out[1]=y;out[2]=z;return out}},{}],336:[function(require,module,exports){module.exports=squaredDistance;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}},{}],337:[function(require,module,exports){module.exports=squaredLength;function squaredLength(a){var x=a[0],y=a[1],z=a[2];return x*x+y*y+z*z}},{}],338:[function(require,module,exports){module.exports=subtract;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}},{}],339:[function(require,module,exports){module.exports=transformMat3;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}},{}],340:[function(require,module,exports){module.exports=transformMat4;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;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}},{}],341:[function(require,module,exports){module.exports=transformQuat;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],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;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}},{}],342:[function(require,module,exports){module.exports=add;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}},{}],343:[function(require,module,exports){module.exports=clone;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}},{}],344:[function(require,module,exports){module.exports=copy;function copy(out,a){out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];return out}},{}],345:[function(require,module,exports){module.exports=create;function create(){var out=new Float32Array(4);out[0]=0;out[1]=0;out[2]=0;out[3]=0;return out}},{}],346:[function(require,module,exports){module.exports=distance;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)}},{}],347:[function(require,module,exports){module.exports=divide;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}},{}],348:[function(require,module,exports){module.exports=dot;function dot(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}},{}],349:[function(require,module,exports){module.exports=fromValues;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}},{}],350:[function(require,module,exports){module.exports={create:require("./create"),clone:require("./clone"),fromValues:require("./fromValues"),copy:require("./copy"),set:require("./set"),add:require("./add"),subtract:require("./subtract"),multiply:require("./multiply"),divide:require("./divide"),min:require("./min"),max:require("./max"),scale:require("./scale"),scaleAndAdd:require("./scaleAndAdd"),distance:require("./distance"),squaredDistance:require("./squaredDistance"),length:require("./length"),squaredLength:require("./squaredLength"),negate:require("./negate"),inverse:require("./inverse"),normalize:require("./normalize"),dot:require("./dot"),lerp:require("./lerp"),random:require("./random"),transformMat4:require("./transformMat4"),transformQuat:require("./transformQuat")}},{"./add":342,"./clone":343,"./copy":344,"./create":345,"./distance":346,"./divide":347,"./dot":348,"./fromValues":349,"./inverse":351,"./length":352,"./lerp":353,"./max":354,"./min":355,"./multiply":356,"./negate":357,"./normalize":358,"./random":359,"./scale":360,"./scaleAndAdd":361,"./set":362,"./squaredDistance":363,"./squaredLength":364,"./subtract":365,"./transformMat4":366,"./transformQuat":367}],351:[function(require,module,exports){module.exports=inverse;function inverse(out,a){out[0]=1/a[0];out[1]=1/a[1];out[2]=1/a[2];out[3]=1/a[3];return out}},{}],352:[function(require,module,exports){module.exports=length;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)}},{}],353:[function(require,module,exports){module.exports=lerp;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}},{}],354:[function(require,module,exports){module.exports=max;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}},{}],355:[function(require,module,exports){module.exports=min;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}},{}],356:[function(require,module,exports){module.exports=multiply;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}},{}],357:[function(require,module,exports){module.exports=negate;function negate(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=-a[3];return out}},{}],358:[function(require,module,exports){module.exports=normalize;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}},{}],359:[function(require,module,exports){var vecNormalize=require("./normalize");var vecScale=require("./scale");module.exports=random;function random(out,scale){scale=scale||1;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":358,"./scale":360}],360:[function(require,module,exports){module.exports=scale;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}},{}],361:[function(require,module,exports){module.exports=scaleAndAdd;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}},{}],362:[function(require,module,exports){module.exports=set;function set(out,x,y,z,w){out[0]=x;out[1]=y;out[2]=z;out[3]=w;return out}},{}],363:[function(require,module,exports){module.exports=squaredDistance;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}},{}],364:[function(require,module,exports){module.exports=squaredLength;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}},{}],365:[function(require,module,exports){module.exports=subtract;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}},{}],366:[function(require,module,exports){module.exports=transformMat4;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}},{}],367:[function(require,module,exports){module.exports=transformQuat;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],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;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}},{}],368:[function(require,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]}},{}],369:[function(require,module,exports){var tokenize=require("glsl-tokenizer");var atob=require("atob-lite");module.exports=getName;function getName(src){var tokens=Array.isArray(src)?src:tokenize(src);for(var i=0;i0)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":372,"./lib/builtins-300es":371,"./lib/literals":374,"./lib/literals-300es":373,"./lib/operators":375}],371:[function(require,module,exports){var v100=require("./builtins");v100=v100.slice().filter(function(b){return!/^(gl\_|texture)/.test(b)});module.exports=v100.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":372}],372:[function(require,module,exports){module.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"]},{}],373:[function(require,module,exports){var v100=require("./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":374}],374:[function(require,module,exports){module.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"]},{}],375:[function(require,module,exports){module.exports=["<<=",">>=","++","--","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^^","^=","|=","(",")","[","]",".","!","~","*","/","%","+","-","<",">","&","^","|","?",":","=",",",";","{","}"]},{}],376:[function(require,module,exports){var tokenize=require("./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":370}],377:[function(require,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>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<>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&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],381:[function(require,module,exports){"use strict";module.exports=incrementalConvexHull;var orient=require("robust-orientation");var compareCell=require("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;proto.handleBoundaryDegeneracy=function(cell,point){var d=this.dimension;var n=this.vertices.length-1;var tuple=this.tuple;var verts=this.vertices;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){var n=this.vertices.length-1;var d=this.dimension;var verts=this.vertices;var tuple=this.tuple;var initIndex=random?this.interior.length*Math.random()|0:this.interior.length-1;var cell=this.interior[initIndex];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;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;var tovisit=[cell];cell.lastVisited=n;cell.vertices[cell.vertices.indexOf(-1)]=n;cell.boundary=false;interior.push(cell);var glueFacets=[];while(tovisit.length>0){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}var neighbor=cellAdj[i];if(!neighbor.boundary||neighbor.lastVisited>=n){continue}var nv=neighbor.vertices;if(neighbor.lastVisited!==-n){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();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;var vverts=cellVerts.slice();var vadj=cellAdj.slice();var ncell=new Simplex(vverts,vadj,true);simplices.push(ncell);var opposite=na.indexOf(cell);if(opposite<0){continue}na[opposite]=ncell;vadj[indexOfN]=neighbor;vverts[i]=-1;vadj[i]=cell;cellAdj[i]=ncell;ncell.flip();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))}}}glueFacets.sort(compareGlue);for(var i=0;i+1=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")}var initialSimplex=points.slice(0,d+1);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}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]}}}}var triangles=new Triangulation(d,initialSimplex,list);var useRandom=!!randomSearch;for(var i=d+1;i3*(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]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=0&&arr[i][1]>=lo;--i){var r=cb(arr[i]);if(r){return r}}}function reportRange(arr,cb){for(var i=0;ithis.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(lothis.mid&&this.right){var r=this.right.queryInterval(lo,hi,cb);if(r){return r}}if(hithis.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>1];var leftIntervals=[];var rightIntervals=[];var centerIntervals=[];for(var i=0;i4)return true;return false}},{}],392:[function(require,module,exports){function lerp(v0,v1,t){return v0*(1-t)+v1*t}module.exports=lerp},{}],393:[function(require,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";var shared,worker,mapboxgl;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)(n=1))return n;for(;ro?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(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=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():[];r0||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":"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;r255?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;n4)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;o4?"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=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;ur&&ee))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=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;e0&&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;i1}))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=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)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;aNumber.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();in.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":[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;rWt?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&&ee&&(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;nn.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=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);ee?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=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=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=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=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=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;rthis.end)return this.prior=null,r;if(this.value.isDataDriven())return this.prior=null,r;if(e=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);rn.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.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;tOn.max||a.yOn.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=3)for(var s=0;s1){if(Zn(t,e))return!0;for(var n=0;n1?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;ae.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;ne.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=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;ht.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;u80*r){n=o=t[0],i=a=t[1];for(var y=r;yo&&(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=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;e0||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.xo.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.x&&n.x>=p&&i!==n.x&&Ii(or.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=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;o0&&(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);y0;)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 te?1:0}function $i(t,e){var r=t.length;if(r<=1)return[t];for(var n,i,o=[],a=0;a1)for(var u=0;uPn)||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=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;_>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>3}if(n--,1===r||2===r)(i+=t.readSVarint())s&&(s=i),(o+=t.readSVarint())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>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=2&&t[u-1].equals(t[u-2]);)u--;for(var l=0;ll){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&&(Si&&(I="bevel"),"bevel"===I&&(S>2&&(I="flipbevel"),S100)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=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&&A2*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;i0?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;i0)&&("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=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;u0;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;a0},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;ni.maxh||t>i.maxw||r<=i.maxh&&t<=i.maxw&&(a=i.maxw*i.maxh-t*r)o.free)){if(r===o.h)return this.allocShelf(s,t,r,n);r>o.h||rp)&&(c=2*Math.max(t,p)),(uu)&&(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;rthis.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<>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<>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<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>>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>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(;i239?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.pos127;);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;e268435455||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;o55295&&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=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:"",id:String(i),error:t?yr(t):null,data:yr(e,n)},n)};if(""===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<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>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.wrapt.wrap)&&(this.overscaledZt.overscaledZ)&&(this.canonical.xt.canonical.x)&&this.canonical.y=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=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=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=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@\,;\:\\"\/\[\]\?\=\{\}\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-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;sr;)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=0&&_=0&&I=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;o0&&(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;Sn&&(b+=M-n),!(b=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)0)for(var i=(this.length>>1)-1;i>=0;i--)this._down(i)}function c(e,t){return et?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;ha)&&(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;xS.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;ot.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=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=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);$=0;a--)if(r.dist(o[a])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=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=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;i2){for(a=0;a=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>31}function Q(e,t){for(var i=e.loadGeometry(),r=e.type,n=0,o=0,a=i.length,s=0;sn;){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);gd;)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=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;r0&&(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;ca&&(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;n1?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&&d<=r)l.push(h);else if(!(p>r||d=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=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&&(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;aa.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;s0&&t.size<(n?a:r))i.numPoints+=t.length/3;else{for(var s=[],l=0;la)&&(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;r0===t)for(r=0,n=e.length;r24)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=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;o1&&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<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<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=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=0?1.2:1))}function O(t,e,i,n,o,r,a){for(var s=0;s65535)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;nthis.height)return t.warnOnce("LineAtlas out of space"),null;for(var r=0,a=0;a90||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: , lat: }, or an array of [, ]")};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=i&&t.y0&&(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+10&&(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>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.expirationTimethis.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;i1||(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=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;ythis._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=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=0&&g[1].y+_>=0){for(var v=[],y=0;y=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;ithis.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;a0: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=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;_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;gMath.abs(n.x-i.x)*o)return{useVertical:!0};return(e===t.WritingMode.vertical?i.yn.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;C0?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;P0?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)=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;iC)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-I&&B=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;f0,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;n0||s.numVerticalGlyphVertices>0,h=s.numIconVertices>0;if(u){for(var p=Ve(c.text),d=(s.numGlyphVertices+s.numVerticalGlyphVertices)/4,f=0;ft},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._currentTileIndex2};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;nt.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;h1?"@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;s0)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 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>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;a0){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":[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;u0?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;he.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.dx0,h=e.dx<0,p=r;pl.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=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.currentLayer0?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&&ie.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<=0&&l<=r)for(c=i;ca&&(o=a-m)}if(this.lngRange){var _=this.x,g=c.x/2;_-gl&&(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)180&&(d=180);var f=d/180;c+=h*d*(f/2),Math.abs(i._normalizeBearing(c,0))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())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=ye.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)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=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;ie.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()=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;r180;){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"}];a5280)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="×",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.ythis._map.transform.height-a?["bottom"]:[],e.xthis._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:{})},{}],394:[function(require,module,exports){"use strict";module.exports=createTable;var chull=require("convex-hull");function constructVertex(d,a,b){var x=new Array(d);for(var i=0;irow[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};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}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":396,"gl-mat4/clone":248,"gl-mat4/create":249,"gl-mat4/determinant":250,"gl-mat4/invert":254,"gl-mat4/transpose":264,"gl-vec3/cross":314,"gl-vec3/dot":317,"gl-vec3/length":322,"gl-vec3/normalize":328}],396:[function(require,module,exports){module.exports=function normalize(out,mat){var m44=mat[15];if(m44===0)return false;var scale=1/m44;for(var i=0;i<16;i++)out[i]=mat[i]*scale;return true}},{}],397:[function(require,module,exports){var lerp=require("gl-vec3/lerp");var recompose=require("mat4-recompose");var decompose=require("mat4-decompose");var determinant=require("gl-mat4/determinant");var slerp=require("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;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;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);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":250,"gl-vec3/lerp":323,"mat4-decompose":395,"mat4-recompose":398,"quat-slerp":450}],398:[function(require,module,exports){var mat4={identity:require("gl-mat4/identity"),translate:require("gl-mat4/translate"),multiply:require("gl-mat4/multiply"),create:require("gl-mat4/create"),scale:require("gl-mat4/scale"),fromRotationTranslation:require("gl-mat4/fromRotationTranslation")};var rotationMatrix=mat4.create();var temp=mat4.create();module.exports=function recomposeMat4(matrix,translation,scale,skew,perspective,quaternion){mat4.identity(matrix);mat4.fromRotationTranslation(matrix,quaternion,translation);matrix[3]=perspective[0];matrix[7]=perspective[1];matrix[11]=perspective[2];matrix[15]=perspective[3];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)}mat4.scale(matrix,matrix,scale);return matrix}},{"gl-mat4/create":249,"gl-mat4/fromRotationTranslation":252,"gl-mat4/identity":253,"gl-mat4/multiply":256,"gl-mat4/scale":262,"gl-mat4/translate":263}],399:[function(require,module,exports){"use strict";module.exports=Math.log2||function(x){return Math.log(x)*Math.LOG2E}},{}],400:[function(require,module,exports){"use strict";var bsearch=require("binary-search-bounds");var m4interp=require("mat4-interpolate");var invert44=require("gl-mat4/invert");var rotateX=require("gl-mat4/rotateX");var rotateY=require("gl-mat4/rotateY");var rotateZ=require("gl-mat4/rotateZ");var lookAt=require("gl-mat4/lookAt");var translate=require("gl-mat4/translate");var scale=require("gl-mat4/scale");var normalize=require("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(t1&&orient(points[lower[m-2]],points[lower[m-1]],p)<=0){m-=1;lower.pop()}lower.push(idx);m=upper.length;while(m>1&&orient(points[upper[m-2]],points[upper[m-1]],p)>=0){m-=1;upper.pop()}upper.push(idx)}var result=new Array(upper.length+lower.length-2);var ptr=0;for(var i=0,nl=lower.length;i0;--j){result[ptr++]=upper[j]}return result}},{"robust-orientation":471}],402:[function(require,module,exports){"use strict";module.exports=mouseListen;var mouse=require("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)}}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":404}],403:[function(require,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()}}},{}],404:[function(require,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<=0){return 1<0){stepVal.push(stride(i,order[j-1])+"*"+shape(order[j-1]))}vars.push(step(i,order[j])+"=("+stepVal.join("-")+")|0")}}for(var i=0;i=0;--i){sizeVariable.push(shape(order[i]))}vars.push(POOL_SIZE+"=("+sizeVariable.join("*")+")|0",PHASES+"=mallocUint32("+POOL_SIZE+")",VERTEX_IDS+"=mallocUint32("+POOL_SIZE+")",POINTER+"=0");vars.push(pcube(0)+"=0");for(var j=1;j<1<=0;--i){forLoopBegin(i,0)}var phaseFuncArgs=[];for(var i=0;i0;k=k-1&subset){faceArgs.push(VERTEX_IDS+"["+POINTER+"+"+pdelta(k)+"]")}faceArgs.push(vert(0));for(var k=0;k0){",index(order[i]),"=1;");createLoop(i-1,mask|1< 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=0){typesig[i]=true}else{typesig[i]=false}}return compileSurfaceProcedure(args.vertex,args.cell,args.phase,scalars,order,typesig)}},{"typedarray-pool":507}],407:[function(require,module,exports){"use strict";var fill=require("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":136}],408:[function(require,module,exports){"use strict";module.exports=gradient;var dup=require("dup");var cwiseCompiler=require("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=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=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=0||facet.indexOf(-(i+1))>=0){continue}code.push(",dst.pick(",pickStr.join(),",",i,")",boundStr)}code.push(");")}for(var i=0;i1){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("};")}}for(var i=0;i<1<>",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;ithis_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_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":133}],412:[function(require,module,exports){"use strict";var ndarray=require("ndarray");var do_convert=require("./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":413,ndarray:417}],413:[function(require,module,exports){module.exports=require("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":133}],414:[function(require,module,exports){"use strict";var pool=require("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;i1){var scratch_shape=[];for(var i=1;i1){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,"b){break __l}"].join(""));for(var i=order.length-1;i>=1;--i){code.push("sptr+=e"+i,"dptr+=f"+i,"}")}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,"=0;--i){var j=order[i];if(j===0){continue}code.push(["for(i",j,"=0;i",j,"scratch)){",dataWrite("cptr",dataRead("cptr-s0")),"cptr-=s0","}",dataWrite("cptr","scratch"))}code.push("}");if(order.length>1&&allocator){code.push("free(scratch)")}code.push("} return "+funcName);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=0;--i){var j=order[i];if(j===0){continue}code.push(["for(i",j,"=0;i",j,"1){for(var i=0;i1){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;i1){for(var i=0;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){");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{");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(--great1){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);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");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(""))}}code.push("if(lessindex5){");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(--great1&&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(""));var vars=["data=array.data,offset=array.offset|0,shape=array.shape,stride=array.stride"];for(var i=0;i0){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}}code.push("var "+vars.join(","));var sortArgs=["0","n0-1","data","offset"].concat(shapeArgs(order.length));code.push(["if(n0<=",INSERTION_SORT_THRESHOLD,"){","insertionSort(",sortArgs.join(","),")}else{","quickSort(",sortArgs.join(","),")}"].join(""));code.push("}return "+funcName);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":507}],415:[function(require,module,exports){"use strict";var compile=require("./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":414}],416:[function(require,module,exports){"use strict";var interp=require("ndarray-linear-interpolate");var do_warp=require("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=require("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=require("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=require("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":136,"ndarray-linear-interpolate":410}],417:[function(require,module,exports){var iota=require("iota-array");var isBuffer=require("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;iMath.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})")}}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}")}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+"]}")}code.push("proto.index=function "+className+"_index(",args.join(),"){return "+index_str+"}");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)}");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=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)}");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=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)}");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)}");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>>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":151}],419:[function(require,module,exports){var π=Math.PI;var _120=radians(120);module.exports=normalize;function normalize(path){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;i7){result.push(seg.splice(0,7));seg.unshift("C")}break;case"S":var cx=x;var cy=y;if(prev=="C"||prev=="S"){cx+=cx-bezierX;cy+=cy-bezierY}seg=["C",cx,cy,seg[1],seg[2],seg[3],seg[4]];break;case"T":if(prev=="Q"||prev=="T"){quadX=x*2-quadX;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}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]}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;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=x1f2)f1=f1-π*2;if(!sweep_flag&&f2>f1)f2=f2-π*2}else{f1=recursive[0];f2=recursive[1];cx=recursive[2];cy=recursive[3]}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;iepsilon){var norm=normals[c];var w=1/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])}}}}for(var i=0;iepsilon){var w=1/Math.sqrt(m);for(var k=0;k<3;++k){norm[k]*=w}}else{for(var k=0;k<3;++k){norm[k]=0}}}return normals};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;iepsilon){l=1/Math.sqrt(l)}else{l=0}for(var j=0;j<3;++j){n[j]*=l}normals[i]=n}return normals}},{}],421:[function(require,module,exports){"use strict";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}var test1=new String("abc");test1[5]="de";if(Object.getOwnPropertyNames(test1)[0]==="5"){return false}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}var test3={};"abcdefghijklmnopqrst".split("").forEach(function(letter){test3[letter]=letter});if(Object.keys(Object.assign({},test3)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(err){return false}}module.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s0){var l=Math.sqrt(tr+1);out[0]=.5*(uz-fy)/l;out[1]=.5*(fx-rz)/l;out[2]=.5*(ry-uy)/l;out[3]=.5*l}else{var tf=Math.max(rx,uy,fz);var l=Math.sqrt(2*tf-tr+1);if(rx>=tf){out[0]=.5*l;out[1]=.5*(ux+ry)/l;out[2]=.5*(fx+rz)/l;out[3]=.5*(uz-fy)/l}else if(uy>=tf){out[0]=.5*(ry+ux)/l;out[1]=.5*l;out[2]=.5*(fy+uz)/l;out[3]=.5*(fx-rz)/l}else{out[0]=.5*(rz+fx)/l;out[1]=.5*(uz+fy)/l;out[2]=.5*l;out[3]=.5*(ry-ux)/l}}return out}},{}],423:[function(require,module,exports){"use strict";module.exports=createOrbitController;var filterVector=require("filtered-vector");var lookAt=require("gl-mat4/lookAt");var mat4FromQuat=require("gl-mat4/fromQuat");var invert44=require("gl-mat4/invert");var quatFromFrame=require("./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;out[3]=1}}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=[.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 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;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;dy=dy||0;dz=dz||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);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;dy=dy||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,1-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;bw=1}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;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;cw=1}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;for(var i=0;i<3;++i){fl+=Math.pow(center[i]-eye[i],2)}this.radius.set(t,.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,dy||0,dz||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;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":422,"filtered-vector":215,"gl-mat4/fromQuat":251,"gl-mat4/invert":254,"gl-mat4/lookAt":255}],424:[function(require,module,exports){"use strict";var repeat=require("repeat-string");module.exports=function padLeft(str,num,ch){ch=typeof ch!=="undefined"?ch+"":" ";return repeat(ch,num)+str}},{"repeat-string":464}],425:[function(require,module,exports){"use strict";function parse(str,opts){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){var pRE=new RegExp(["\\",bracket[0],"[^\\",bracket[0],"\\",bracket[1],"]*\\",bracket[1]].join(""));var ids=[];function replaceToken(token,idx,str){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;var a=0;while(str!=prevStr){prevStr=str;str=str.replace(pRE,replaceToken);if(a++>1e4)throw Error("References have circular dependency. Please, check them.")}res[i]=str});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]+)");function nest(str,refs,escape){var res=[],match;var a=0;while(match=re.exec(str)){if(a++>1e4)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;if(!str)return"";var re=new RegExp("\\"+escape+"([0-9]+)");var a=0;while(str!=prevStr){if(a++>1e4)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},{}],426:[function(require,module,exports){"use strict";var pick=require("pick-by-alias");module.exports=parseRect;function parseRect(arg){var rect;if(arguments.length>1){arg=arguments}if(typeof arg==="string"){arg=arg.split(/\s/).map(parseFloat)}else if(typeof arg==="number"){arg=[arg]}if(arg.length&&typeof arg[0]==="number"){if(arg.length===1){rect={width:arg[0],height:arg[0],x:0,y:0}}else if(arg.length===2){rect={width:arg[0],height:arg[1],x:0,y:0}}else{rect={x:arg[0],y:arg[1],width:arg[2]-arg[0]||0,height:arg[3]-arg[1]||0}}}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":432}],427:[function(require,module,exports){module.exports=parse;var length={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0};var segment=/([astvzqmhlc])([^astvzqmhlc]*)/gi;function parse(path){var data=[];path.replace(segment,function(_,command,args){var type=command.toLowerCase();args=parseValues(args);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.length0;--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;i0;--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":383,"typedarray-pool":507}],432:[function(require,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;i0){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;k0){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;i0){var ni=adj[0][i].length;var ncycle=extractCycle(i,j);if(shouldGlue(pcycle,ncycle)){pcycle.push.apply(pcycle,ncycle)}else{if(pcycle.length>0){cycles.push(pcycle)}pcycle=ncycle}}if(pcycle.length>0){cycles.push(pcycle)}}}return cycles}},{"compare-angle":114}],434:[function(require,module,exports){"use strict";module.exports=trimLeaves;var e2a=require("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;i0){var v=dead.pop();live[v]=false;var n=adj[v];for(var i=0;i0}faces=faces.filter(ccw);var numFaces=faces.length;var parent=new Array(numFaces);var containment=new Array(numFaces);for(var i=0;i0){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=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":434,"edges-to-adjacency-list":156,"planar-dual":433,"point-in-big-polygon":439,"robust-sum":476,"two-product":505,uniq:509}],436:[function(require,module,exports){"use strict";module.exports=require("./quad")},{"./quad":438}],437:[function(require,module,exports){arguments[4][98][0].apply(exports,arguments)},{dup:98}],438:[function(require,module,exports){"use strict";var search=require("binary-search-bounds");var clamp=require("clamp");var rect=require("parse-rect");var getBounds=require("array-bounds");var pick=require("pick-by-alias");var defined=require("defined");var flatten=require("flatten-vertex-data");var isObj=require("is-obj");var dtype=require("dtype");var log2=require("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"});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);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;imaxDepth){for(var i=0;ihix||nminY>hiy||nmaxX=maxLevel){return}if(from===to){return}var levelItems=levels[level];if(to===undefined){to=levelItems.length}for(var i=from;i=minX&&px<=maxX&&py>=minY&&py<=maxY){selection.push(id)}}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}function lod(lox,loy,hix,hiy,maxLevel){var ranges=[];for(var level=0;level0&&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]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){var numLoops=loops.length;var segments=[];var vsegments=[];var ptr=0;for(var i=0;i=-eps},pointBetween:function(p,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-eps)return false;return true},pointsSameX:function(p1,p2){return Math.abs(p1[0]-p2[0])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},{}],443:[function(require,module,exports){var GeoJSON={toPolygon:function(PolyBool,geojson){function GeoPoly(coords){if(coords.length<=0)return PolyBool.segments({inverted:false,regions:[]});function LineString(ls){var reg=ls.slice(0,ls.length-1);return PolyBool.segments({inverted:false,regions:[reg]})}var out=LineString(coords[0]);for(var i=1;i0})}function checkIntersection(ev1,ev2){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){if(!eps.pointsCollinear(a1,a2,b1))return false;if(eps.pointsSame(a1,b2)||eps.pointsSame(a2,b1))return false;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;var a1_between=!a1_equ_b1&&eps.pointBetween(a1,b1,b2);var a2_between=!a2_equ_b2&&eps.pointBetween(a2,b1,b2);if(a1_equ_b1){if(a2_between){eventDivide(ev2,a2)}else{eventDivide(ev1,b2)}return ev2}else if(a1_between){if(!a2_equ_b2){if(a2_between){eventDivide(ev2,a2)}else{eventDivide(ev1,b2)}}eventDivide(ev2,a1)}}else{if(i.alongA===0){if(i.alongB===-1)eventDivide(ev1,b1);else if(i.alongB===0)eventDivide(ev1,i.pt);else if(i.alongB===1)eventDivide(ev1,b2)}if(i.alongB===0){if(i.alongA===-1)eventDivide(ev2,a1);else if(i.alongA===0)eventDivide(ev2,i.pt);else if(i.alongA===1)eventDivide(ev2,a2)}}return false}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){if(selfIntersection){var toggle;if(ev.seg.myFill.below===null)toggle=true;else toggle=ev.seg.myFill.above!==ev.seg.myFill.below;if(toggle)eve.seg.myFill.above=!eve.seg.myFill.above}else{eve.seg.otherFill=ev.seg.myFill}if(buildLog)buildLog.segmentUpdate(eve.seg);ev.other.remove();ev.remove()}if(event_root.getHead()!==ev){if(buildLog)buildLog.rewind(ev.seg);continue}if(selfIntersection){var toggle;if(ev.seg.myFill.below===null)toggle=true;else toggle=ev.seg.myFill.above!==ev.seg.myFill.below;if(!below){ev.seg.myFill.below=primaryPolyInverted}else{ev.seg.myFill.below=below.seg.myFill.above}if(toggle)ev.seg.myFill.above=!ev.seg.myFill.below;else ev.seg.myFill.above=ev.seg.myFill.below}else{if(ev.seg.otherFill===null){var inside;if(!below){inside=ev.primary?secondaryPolyInverted:primaryPolyInverted}else{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)}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")}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);st.remove();if(!ev.primary){var s=ev.seg.myFill;ev.seg.myFill=ev.seg.otherFill;ev.seg.otherFill=s}segments.push(ev.seg)}event_root.getHead().remove()}if(buildLog)buildLog.done();return segments}if(!selfIntersection){return{calculate:function(segments1,inverted1,segments2,inverted2){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)}}}return{addRegion:function(region){var pt1;var pt2=region[region.length-1];for(var i=0;i=a00){s=1;sqrDistance=a00+2*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*b1+c}else{t=-b1/a11;sqrDistance=b1*t+c}}}else{s=0;if(b1>=0){t=0;sqrDistance=c}else if(-b1>=a11){t=1;sqrDistance=a11+2*b1+c}else{t=-b1/a11;sqrDistance=b1*t+c}}}else if(t<0){t=0;if(b0>=0){s=0;sqrDistance=c}else if(-b0>=a00){s=1;sqrDistance=a00+2*b0+c}else{s=-b0/a00;sqrDistance=b0*s+c}}else{var invDet=1/det;s*=invDet;t*=invDet;sqrDistance=s*(a00*s+a01*t+2*b0)+t*(a01*s+a11*t+2*b1)+c}}else{var tmp0,tmp1,numer,denom;if(s<0){tmp0=a01+b0;tmp1=a11+b1;if(tmp1>tmp0){numer=tmp1-tmp0;denom=a00-2*a01+a11;if(numer>=denom){s=1;t=0;sqrDistance=a00+2*b0+c}else{s=numer/denom;t=1-s;sqrDistance=s*(a00*s+a01*t+2*b0)+t*(a01*s+a11*t+2*b1)+c}}else{s=0;if(tmp1<=0){t=1;sqrDistance=a11+2*b1+c}else if(b1>=0){t=0;sqrDistance=c}else{t=-b1/a11;sqrDistance=b1*t+c}}}else if(t<0){tmp0=a01+b1;tmp1=a00+b0;if(tmp1>tmp0){numer=tmp1-tmp0;denom=a00-2*a01+a11;if(numer>=denom){t=1;s=0;sqrDistance=a11+2*b1+c}else{t=numer/denom;s=1-t;sqrDistance=s*(a00*s+a01*t+2*b0)+t*(a01*s+a11*t+2*b1)+c}}else{t=0;if(tmp1<=0){s=1;sqrDistance=a00+2*b0+c}else if(b0>=0){s=0;sqrDistance=c}else{s=-b0/a00;sqrDistance=b0*s+c}}}else{numer=a11+b1-a01-b0;if(numer<=0){s=0;t=1;sqrDistance=a11+2*b1+c}else{denom=a00-2*a01+a11;if(numer>=denom){s=1;t=0;sqrDistance=a00+2*b0+c}else{s=numer/denom;t=1-s;sqrDistance=s*(a00*s+a01*t+2*b0)+t*(a01*s+a11*t+2*b1)+c}}}}var u=1-s-t;for(var i=0;i1){for(var i=1;i0){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":99,"compare-cell":115,"compare-oriented-cell":116}],457:[function(require,module,exports){"use strict";var getBounds=require("array-bounds");var rgba=require("color-normalize");var updateDiff=require("update-diff");var pick=require("pick-by-alias");var extend=require("object-assign");var flatten=require("flatten-vertex-data");var ref=require("to-float32");var float32=ref.float32;var fract32=ref.fract32;module.exports=Error2D;var WEIGHTS=[[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]];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")}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=[];colorBuffer=regl.buffer({usage:"dynamic",type:"uint8",data:new Uint8Array(0)});positionBuffer=regl.buffer({usage:"dynamic",type:"float",data:new Uint8Array(0)});positionFractBuffer=regl.buffer({usage:"dynamic",type:"float",data:new Uint8Array(0)});errorBuffer=regl.buffer({usage:"dynamic",type:"float",data:new Uint8Array(0)});meshBuffer=regl.buffer({usage:"static",type:"float",data:WEIGHTS});update(options);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:{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},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});extend(error2d,{update:update,draw:draw,destroy:destroy,regl:regl,gl:gl,canvas:gl.canvas,groups:groups});return error2d;function error2d(opts){if(opts){update(opts)}else if(opts===null){destroy()}draw()}function draw(options){if(typeof options==="number"){return drawGroup(options)}if(options&&!Array.isArray(options)){options=[options]}regl._refresh();groups.forEach(function(s,i){if(!s){return}if(options){if(!options[i]){s.draw=false}else{s.draw=true}}if(!s.draw){s.draw=true;return}drawGroup(i)})}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}if(options.length!=null){if(typeof options[0]==="number"){options=[{positions:options}]}}else if(!Array.isArray(options)){options=[options]}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}}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"}if(!Array.isArray(colors)||typeof colors[0]==="number"){var color=colors;colors=Array(count);for(var i=0;i 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) * scale + translate;\n\tvec2 aBotPosition = (aBotCoord) * scale + translate;\n\n\tvec2 bTopPosition = (bTopCoord) * scale + translate;\n\tvec2 bBotPosition = (bBotCoord) * scale + 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:{lineEnd:{buffer:offsetBuffer,divisor:0,stride:8,offset:0},lineTop:{buffer:offsetBuffer,divisor:0,stride:8,offset:4},aColor:{buffer:regl.prop("colorBuffer"),stride:4,offset:0,divisor:1},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){drawMiterLine=drawRectLine}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}};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 args=[],len=arguments.length;while(len--)args[len]=arguments[len];if(args.length){(ref=this).update.apply(ref,args)}this.draw();var ref};Line2D.prototype.draw=function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];(args.length?args:this.passes).forEach(function(s,i){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}if(s.scale[0]*s.viewport.width>Line2D.precisionThreshold||s.scale[1]*s.viewport.height>Line2D.precisionThreshold){this$1.shaders.rect(s)}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)}var ref});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}]}}else if(!Array.isArray(options)){options=[options]}var ref=this;var regl=ref.regl;var gl=ref.gl;options.forEach(function(o,i){var state=this$1.passes[i];if(o===undefined){return}if(o===null){this$1.passes[i]=null;return}if(typeof o[0]==="number"){o={positions:o}}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"});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 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\nvec2 paletteCoord(float id) {\n return vec2(\n (mod(id, paletteSize.x) + .5) / paletteSize.x,\n (floor(id / paletteSize.x) + .5) / paletteSize.y\n );\n}\nvec2 paletteCoord(vec2 id) {\n return vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n );\n}\n\nvec4 getColor(vec4 id) {\n // zero-palette means we deal with direct buffer\n if (paletteSize.x == 0.) return id / 255.;\n return texture2D(palette, paletteCoord(id.xy));\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"]);if(ie){circleOptions.frag=circleOptions.frag.replace("smoothstep","smoothStep")}this.drawCircle=regl(circleOptions)}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};Scatter.prototype.render=function(){var args=[],len=arguments.length;while(len--)args[len]=arguments[len];if(args.length){(ref=this).update.apply(ref,args)}this.draw();return this;var ref};Scatter.prototype.draw=function(){var this$1=this;var args=[],len=arguments.length;while(len--)args[len]=arguments[len];var ref=this;var groups=ref.groups;if(args.length===1&&Array.isArray(args[0])&&(args[0][0]===null||Array.isArray(args[0][0]))){args=args[0]}this.regl._refresh();if(args.length){for(var i=0;isnap)){group.tree=cluster(positions,{bounds:bounds})}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)}}positionBuffer({data:float32(positions),usage:"dynamic"});positionFractBuffer({data:fract32(positions),usage:"dynamic"});selectionBuffer({data:new Uint8Array(count),type:"uint8",usage:"stream"});return positions}},{marker:function(markers,group,options){var activation=group.activation;activation.forEach(function(buffer){return buffer&&buffer.destroy&&buffer.destroy()});activation.length=0;if(!markers||typeof markers[0]==="number"){var id=this$1.addMarker(markers);activation[id]=true}else{var markerMasks=[];for(var i=0,l=Math.min(markers.length,group.count);i=0){return pos}var distArr;if(sdf instanceof Uint8Array||sdf instanceof Uint8ClampedArray){distArr=sdf}else{distArr=new Uint8Array(sdf.length);for(var i=0,l=sdf.length;imaxColors*maxColors*4){this.tooManyColors=true}this.updatePalette(palette);return idx.length===1?idx[0]:idx};Scatter.prototype.updatePalette=function(palette){if(this.tooManyColors){return}var ref=this;var maxColors=ref.maxColors;var paletteTexture=ref.paletteTexture;var requiredHeight=Math.ceil(palette.length*.25/maxColors);if(requiredHeight>1){palette=palette.slice();for(var i=palette.length*.25%maxColors;ij){continue}if(!trace.lower&&i$22){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":56,"array-range":58,"flatten-vertex-data":462,"parse-rect":426,"pick-by-alias":432,raf:451,"regl-scatter2d/scatter":460}],462:[function(require,module,exports){arguments[4][48][0].apply(exports,arguments)},{dtype:153,dup:48}],463:[function(require,module,exports){(function(pa,W){"object"===typeof exports&&"undefined"!==typeof module?module.exports=W():"function"===typeof define&&define.amd?define(W):pa.createREGL=W()})(this,function(){function pa(a,b){this.id=Ab++;this.type=a;this.data=b}function W(a){if(0===a.length)return[];var b=a.charAt(0),c=a.charAt(a.length-1);if(1>>=b;c=(255>>=c;b|=c;c=(15>>=c;b|=c;c=(3>>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>2].push(a)}var c=O(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 ka(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)||P(a.data))}function db(a,b,c,e,f,d){for(var n=0;ne&&(e=d.buffer.byteLength,5123===k?e>>=1:5125===k&&(e>>=2));d.vertCount=e;e=g;0>g&&(e=4,g=d.buffer.dimension,1===g&&(e=0),2===g&&(e=1),3===g&&(e=4));d.primType=e}function n(a){e.elementsCount--;delete k[a.id];a.buffer.destroy();a.buffer=null}var k={},r=0,p={uint8:5121,uint16:5123};b.oes_element_index_uint&&(p.uint32=5125);f.prototype.bind=function(){this.buffer.bind()};var u=[];return{create:function(a,b){function l(a){if(a)if("number"===typeof a)g(a),h.primType=4,h.vertCount=a|0,h.type=5121;else{var b=null,c=35044,e=-1,f=-1,m=0,k=0;if(Array.isArray(a)||P(a)||ka(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&&(f=a.count|0),"type"in a&&(k=p[a.type]),"length"in a)m=a.length|0;else if(m=f,5123===k||5122===k)m*=2;else if(5125===k||5124===k)m*=4;d(h,b,c,e,f,m,k)}else g(),h.primType=4,h.vertCount=0,h.type=5121;return l}var g=c.create(null,34963,!0),h=new f(g._buffer);e.elementsCount++;l(a);l._reglType="elements";l._elements=h;l.subdata=function(a,b){g.subdata(a,b);return l};l.destroy=function(){n(h)};return l},createStream:function(a){var b=u.pop();b||(b=new f(c.create(null,34963,!0,!1)._buffer));d(b,a,35040,-1,-1,0,0);return b},destroyStream:function(a){u.push(a)},getElements:function(a){return"function"===typeof a&&a._elements instanceof f?a._elements:null},clear:function(){R(k).forEach(n)}}}function kb(a){for(var b=z.allocType(5123,a.length),c=0;c>>31<<15,d=(e<<1>>>24)-127,e=e>>13&1023;b[c]=-24>d?f:-14>d?f+(e+1024>>-14-d):15>=d,c.height>>=d,C(c,e[d]),a.mipmask|=1<b;++b)a.images[b]=null;return a}function ib(a){for(var b=a.images,c=0;cb){for(var c=0;c=--this.refCount&&w(this)}});n.profile&&(d.getTotalTextureSize=function(){var a=0;Object.keys(Z).forEach(function(b){a+=Z[b].stats.size});return a});return{create2D:function(b,c){function e(a,b){var c=f.texInfo;v.call(c);var d=x();"number"===typeof a?"number"===typeof b?t(d,a|0,b|0):t(d,a|0,a|0):a?(N(c,a),B(d,a)):t(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);X(d,3553);Q(c,3553);Ba();ib(d);n.profile&&(f.stats.size=Ja(f.internalformat,f.type,d.width,d.height,c.genMipmaps,!1));e.format=O[f.internalformat];e.type=ba[f.type];e.mag=oa[c.magFilter];e.min=Aa[c.minFilter];e.wrapS=ia[c.wrapS];e.wrapT=ia[c.wrapT];return e}var f=new E(3553);Z[f.id]=f;d.textureCount++;e(b,c);e.subimage=function(a,b,c,d){b|=0;c|=0;d|=0;var q=g();r(q,f);q.width=0;q.height=0;C(q,a);q.width=q.width||(f.width>>d)-b;q.height=q.height||(f.height>>d)-c;T(f);l(q,3553,b,c,d);Ba();h(q);return e};e.resize=function(b,c){var d=b|0,g=c|0||d;if(d===f.width&&g===f.height)return e;e.width=f.width=d;e.height=f.height=g;T(f);for(var q,y=f.channels,G=f.type,H=0;f.mipmask>>H;++H){var ea=d>>H,fa=g>>H;if(!ea||!fa)break;q=z.zero.allocType(G,ea*fa*y);a.texImage2D(3553,H,f.format,ea,fa,0,f.format,f.type,q);q&&z.zero.freeType(q)}Ba();n.profile&&(f.stats.size=Ja(f.internalformat,f.type,d,g,!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,k,m){function A(a,b,c,d,e,J){var I,da=w.texInfo;v.call(da);for(I=0;6>I;++I)q[I]=x();if("number"===typeof a||!a)for(a=a|0||1,I=0;6>I;++I)t(q[I],a,a);else if("object"===typeof a)if(b)B(q[0],a),B(q[1],b),B(q[2],c),B(q[3],d),B(q[4],e),B(q[5],J);else if(N(da,a),p(w,a),"faces"in a)for(a=a.faces,I=0;6>I;++I)r(q[I],w),B(q[I],a[I]);else for(I=0;6>I;++I)B(q[I],a);r(w,q[0]);w.mipmask=da.genMipmaps?(q[0].width<<1)-1:q[0].mipmask;w.internalformat=q[0].internalformat;A.width=q[0].width;A.height=q[0].height;T(w);for(I=0;6>I;++I)X(q[I],34069+I);Q(da,34067);Ba();n.profile&&(w.stats.size=Ja(w.internalformat,w.type,A.width,A.height,da.genMipmaps,!0));A.format=O[w.internalformat];A.type=ba[w.type];A.mag=oa[da.magFilter];A.min=Aa[da.minFilter];A.wrapS=ia[da.wrapS];A.wrapT=ia[da.wrapT];for(I=0;6>I;++I)ib(q[I]);return A}var w=new E(34067);Z[w.id]=w;d.cubeCount++;var q=Array(6);A(b,c,e,f,k,m);A.subimage=function(a,b,c,q,d){c|=0;q|=0;d|=0;var e=g();r(e,w);e.width=0;e.height=0;C(e,b);e.width=e.width||(w.width>>d)-c;e.height=e.height||(w.height>>d)-q;T(w);l(e,34069+a,c,q,d);Ba();h(e);return A};A.resize=function(b){b|=0;if(b!==w.width){A.width=w.width=b;A.height=w.height=b;T(w);for(var c=0;6>c;++c)for(var q=0;w.mipmask>>q;++q)a.texImage2D(34069+c,q,w.format,b>>q,b>>q,0,w.format,w.type,null);Ba();n.profile&&(w.stats.size=Ja(w.internalformat,w.type,A.width,A.height,!1,!0));return A}};A._reglType="textureCube";A._texture=w;n.profile&&(A.stats=w.stats);A.destroy=function(){w.decRef()};return A},clear:function(){for(var b=0;bc;++c)if(0!==(b.mipmask&1<>c,b.height>>c,0,b.internalformat,b.type,null);else for(var e=0;6>e;++e)a.texImage2D(34069+e,c,b.internalformat,b.width>>c,b.height>>c,0,b.internalformat,b.type,null);Q(b.texInfo,b.target)})}}}function Ob(a,b,c,e,f,d){function n(a,b,c){this.target=a;this.texture=b;this.renderbuffer=c;var e=a=0;b?(a=b.width,e=b.height):c&&(a=c.width,e=c.height);this.width=a;this.height=e}function k(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 p(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 u(a){var b=3553,c=null,e=null,d=a;"object"===typeof a&&(d=a.data,"target"in a&&(b=a.target|0));a=d._reglType;"texture2d"===a?c=d:"textureCube"===a?c=d:"renderbuffer"===a&&(e=d,b=36161);return new n(b,c,e)}function m(a,b,c,d,g){if(c)return a=e.create2D({width:a,height:b,format:d,type:g}),a._texture.refCount=0,new n(3553,a,null);a=f.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 l(a,b,c){a&&(a.texture?a.texture.resize(b,c):a.renderbuffer&&a.renderbuffer.resize(b,c))}function g(){this.id=N++;Q[this.id]=this;this.framebuffer=a.createFramebuffer();this.height=this.width=0;this.colorAttachments=[];this.depthStencilAttachment=this.stencilAttachment=this.depthAttachment=null}function h(a){a.colorAttachments.forEach(k);k(a.depthAttachment);k(a.stencilAttachment);k(a.depthStencilAttachment)}function qa(b){a.deleteFramebuffer(b.framebuffer);b.framebuffer=null;d.framebufferCount--;delete Q[b.id]}function t(b){var e;a.bindFramebuffer(36160,b.framebuffer);var d=b.colorAttachments;for(e=0;ed;++d){for(k=0;ka;++a)c[a].resize(d);b.width=b.height=d;return b},_reglType:"framebufferCube",destroy:function(){c.forEach(function(a){a.destroy()})}})},clear:function(){R(Q).forEach(qa)},restore:function(){R(Q).forEach(function(b){b.framebuffer=a.createFramebuffer();t(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;ca&&(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);R(p).forEach(b);p={};R(u).forEach(b);u={};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 f=e[a];f||(f=new k(b,a),c.shaderCount++,r(f,d),e[a]=f,C.push(f));return f},restore:function(){p={};u={};for(var a=0;a"+b+"?"+e+".constant["+b+"]:0;"}).join(""),"}}else{","if(",f,"(",e,".buffer)){",h,"=",g,".createStream(",34962,",",e,".buffer);","}else{",h,"=",g,".getBuffer(",e,".buffer);","}",k,'="type" in ',e,"?",q.glTypes,"[",e,".type]:",h,".dtype;",y.normalized,"=!!",e,".normalized;");d("size");d("offset");d("stride");d("divisor");c("}}");c.exit("if(",y.isStream,"){",g,".destroyStream(",h,");","}");return y})});return g}function M(a){var b=a["static"],c=a.dynamic,d={};Object.keys(b).forEach(function(a){var c=b[a];d[a]=x(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]=K(b,function(a,c){return a.invoke(c,b)})});return d}function w(a,b,c,d,e){var f=z(a,e),g=D(a,f,e),l=N(a,e),k=Q(a,e),m=P(a,e),xa=g.viewport;xa&&(k.viewport=xa);xa=h("scissor.box");(g=g[xa])&&(k[xa]=g);g=0>1)",u],");")}function b(){c(ba,".drawArraysInstancedANGLE(",[p,r,t,u],");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}function g(){function a(){c(l+".drawElements("+[p,t,C,r+"<<(("+C+"-5121)>>1)"]+");")}function b(){c(l+".drawArrays("+[p,r,t]+");")}n?B?a():(c("if(",n,"){"),a(),c("}else{"),b(),c("}")):b()}var h=a.shared,l=h.gl,k=h.draw,m=d.draw,n=function(){var e=m.elements,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(k,".","elements");e&&f("if("+e+")"+l+".bindBuffer(34963,"+e+".buffer.buffer);");return e}(),p=e("primitive"),r=e("offset"),t=function(){var e=m.count,f=b;if(e){if(e.contextDep&&d.contextDynamic||e.propDep)f=c;e=e.append(a,f)}else e=f.def(k,".","count");return e}();if("number"===typeof t){if(0===t)return}else c("if(",t,"){"),c.exit("}");var u,ba;ga&&(u=e("instances"),ba=a.instancing);var C=n+".type",B=m.elements&&wa(m.elements);ga&&("number"!==typeof u||0<=u)?"string"===typeof u?(c("if(",u,">0){"),f(),c("}else if(",u,"<0){"),g(),c("}")):f():g()}function ca(a,b,c,d,e){b=B();e=b.proc("body",e);ga&&(b.instancing=e.def(b.shared.extensions,".angle_instanced_arrays"));a(b,e,c,d);return b.compile().body}function W(a,b,c,d){ya(a,b);U(a,b,c,d.attributes,function(){return!0});Y(a,b,c,d.uniforms,function(){return!0});S(a,b,b,c)}function ba(a,b){var c=a.proc("draw",1);ya(a,c);A(a,c,b.context);L(a,c,b.framebuffer);V(a,c,b);R(a,c,b.state);F(a,c,b,!1,!0);var d=b.shader.progVar.append(a,c);c(a.shared.gl,".useProgram(",d,".program);");if(b.shader.program)W(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(W,a,b,c,1)}),"(",d,");",g,".call(this,a0);"))}0=--this.refCount&&n(this)};f.profile&&(e.getTotalRenderbufferSize=function(){var a=0;Object.keys(u).forEach(function(b){a+=u[b].stats.size});return a});return{create:function(b,c){function l(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=k[b.format])):"number"===typeof b?(d=b|0,e="number"===typeof c?c|0:d):b||(d=e=1);if(d!==g.width||e!==g.height||m!==g.format)return l.width=g.width=d,l.height=g.height=e,g.format=m,a.bindRenderbuffer(36161,g.renderbuffer),a.renderbufferStorage(36161,m,d,e),f.profile&&(g.stats.size=M[g.format]*g.width*g.height),l.format=r[g.format],l}var g=new d(a.createRenderbuffer());u[g.id]=g;e.renderbufferCount++;l(b,c);l.resize=function(b,c){var d=b|0,e=c|0||d;if(d===g.width&&e===g.height)return l;l.width=g.width=d;l.height=g.height=e;a.bindRenderbuffer(36161,g.renderbuffer);a.renderbufferStorage(36161,g.format,d,e);f.profile&&(g.stats.size=M[g.format]*g.width*g.height);return l};l._reglType="renderbuffer";l._renderbuffer=g;f.profile&&(l.stats=g.stats);l.destroy=function(){g.decRef()};return l},clear:function(){R(u).forEach(n)},restore:function(){R(u).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 aa(!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=k.pop()||new c;e.startQueryIndex=a;e.endQueryIndex=b;e.sum=0;e.stats=d;r.push(e)}var f=b.ext_disjoint_timer_query;if(!f)return null;var d=[],n=[],k=[],r=[],p=[],u=[];return{beginQuery:function(a){var b=d.pop()||f.createQueryEXT();f.beginQueryEXT(35007,b);n.push(b);e(n.length-1,n.length,a)},endQuery:function(){f.endQueryEXT(35007)},pushScopeStats:e,update:function(){var a,b;a=n.length;if(0!==a){u.length=Math.max(u.length,a+1);p.length=Math.max(p.length,a+1);p[0]=0;var c=u[0]=0;for(b=a=0;b=F.length&&e()}var c=yb(F,a);F[c]=b}}}function p(){var a=S.viewport,b=S.scissor_box;a[0]=a[1]=b[0]=b[1]=0;N.viewportWidth=N.framebufferWidth=N.drawingBufferWidth=a[2]=b[2]=l.drawingBufferWidth;N.viewportHeight=N.framebufferHeight=N.drawingBufferHeight=a[3]=b[3]=l.drawingBufferHeight}function u(){N.tick+=1;N.time=v();p();V.procs.poll()}function m(){p();V.procs.refresh();x&&x.update()}function v(){return(zb()-O)/1e3}a=Eb(a);if(!a)return null;var l=a.gl,g=l.getContextAttributes();l.isContextLost();var h=Fb(l,a);if(!h)return null;var z=Bb(),t={bufferCount:0,elementsCount:0,framebufferCount:0,shaderCount:0,textureCount:0,cubeCount:0,renderbufferCount:0,maxTextureUnits:0},B=h.extensions,x=Xb(l,B),O=zb(),K=l.drawingBufferWidth,P=l.drawingBufferHeight,N={tick:0,time:0,viewportWidth:K,viewportHeight:P,framebufferWidth:K,framebufferHeight:P,drawingBufferWidth:K,drawingBufferHeight:P,pixelRatio:a.pixelRatio},Q=Vb(l,B),K=Pb(l,B,Q,z),E=Gb(l,t,a,K),T=Hb(l,B,E,t),R=Qb(l,z,t,a),w=Kb(l,B,Q,function(){V.procs.poll()},N,t,a),A=Wb(l,B,Q,t,a),L=Ob(l,B,Q,w,A,t),V=Tb(l,z,B,Q,E,T,w,L,{},K,R,{elements:null,primitive:4,count:-1,offset:0,instances:-1},N,x,a),z=Rb(l,L,V.procs.poll,N,g,B,Q),S=V.next,M=l.canvas,F=[],U=[],Y=[],W=[a.onDestroy],ca=null;M&&(M.addEventListener("webglcontextlost",f,!1),M.addEventListener("webglcontextrestored",d,!1));var aa=L.setFBO=n({framebuffer:ja.define.call(null,1,"framebuffer")});m();g=D(n,{clear:function(a){if("framebuffer"in a)if(a.framebuffer&&"framebufferCube"===a.framebuffer_reglType)for(var b=0;6>b;++b)aa(D({framebuffer:a.framebuffer.faces[b]},a),k);else aa(a,k);else k(null,a)},prop:ja.define.bind(null,1),context:ja.define.bind(null,2),this:ja.define.bind(null,3),draw:n({}),buffer:function(a){return E.create(a,34962,!1,!1)},elements:function(a){return T.create(a,!1)},texture:w.create2D,cube:w.createCube,renderbuffer:A.create,framebuffer:L.create,framebufferCube:L.createCube,attributes:g,frame:r,on:function(a,b){var c;switch(a){case"frame":return r(b);case"lost":c=U;break;case"restore":c=Y;break;case"destroy":c=W}c.push(b);return{cancel:function(){for(var a=0;a=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}},{}],465:[function(require,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:{})},{}],466:[function(require,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>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>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;i0){code.push(",")}code.push("[");for(var k=0;k0){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>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;i0){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;i0&&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}if(x0===0&&y0===0&&x1===0&&y1===0){return checkCollinear(a0,a1,b0,b1)}return true}},{"robust-orientation":471}],475:[function(require,module,exports){"use strict";module.exports=robustSubtract;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=nf){a=ei;eptr+=1;if(eptr=nf){a=ei;eptr+=1;if(eptr0){return 1}return 0}},{}],478:[function(require,module,exports){"use strict";module.exports=boundary;var bnd=require("boundary-cells");var reduce=require("reduce-simplicial-complex");function boundary(cells){return reduce(bnd(cells))}},{"boundary-cells":83,"reduce-simplicial-complex":456}],479:[function(require,module,exports){"use strict";module.exports=extractContour;var ndarray=require("ndarray");var pool=require("typedarray-pool");var ndsort=require("ndarray-sort");var contourAlgorithm=require("./lib/codegen");function getDimension(cells){var numCells=cells.length;var d=0;for(var i=0;i>1,v=E[2*m+1];","if(v===b){return m}","if(b0){code.push(",")}code.push("[");for(var j=0;j0){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>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;function incidence(from_cells,to_cells){var index=new Array(from_cells.length);for(var i=0,il=index.length;i=from_cells.length||compareCells(from_cells[idx],b)!==0){break}}}}return index}exports.incidence=incidence;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>>k&1){b.push(c[k])}}result.push(b)}}return normalize(result)}exports.explode=explode;function skeleton(cells,n){if(n<0){return[]}var result=[],k0=(1<>1}return(i>>1)-1}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(left0){var parent=heapParent(i);if(parent>=0){var pw=heapWeight(parent);if(w0){var head=heap[0];heapSwap(0,heapCount-1);heapCount-=1;heapDown(0);return head}return-1}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)}function kill(i){if(dead[i]){return}dead[i]=true;var s=inv[i];var t=outv[i];if(inv[t]>=0){inv[t]=s}if(outv[s]>=0){outv[s]=t}if(index[s]>=0){heapUpdate(index[s],computeWeight(s))}if(index[t]>=0){heapUpdate(index[t],computeWeight(t))}}var heap=[];var index=new Array(n);for(var i=0;i>1;i>=0;--i){heapDown(i)}while(true){var hmin=heapPop();if(hmin<0||weights[hmin]>minArea){break}kill(hmin)}var npositions=[];for(var i=0;i=0&&tout>=0&&tin!==tout){var cin=index[tin];var cout=index[tout];if(cin!==cout){ncells.push([cin,cout])}}});sc.unique(sc.normalize(ncells));return{positions:npositions,edges:ncells}}},{"robust-orientation":471,"simplicial-complex":483}],486:[function(require,module,exports){"use strict";module.exports=orderSegments;var orient=require("robust-orientation");function horizontalOrder(a,b){var bl,br;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(ahibhi){return alo-bhi}return ahi-bhi}var al,ar;if(a[0][1]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[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":471}],487:[function(require,module,exports){"use strict";module.exports=createSlabDecomposition;var bounds=require("binary-search-bounds");var createRBTree=require("functional-red-black-tree");var orient=require("robust-orientation");var orderSegments=require("./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]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}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){return lastHit}e=horiz[hbucket]}}}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;i1){t=1}var ti=1-t;var n=a.length;var r=new Array(n);for(var i=0;i0||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;i0||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;i0||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":468,"robust-sum":476}],489:[function(require,module,exports){!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){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,match,pad,pad_character,pad_length,is_positive,sign;for(i=0;i=0}switch(match[8]){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,match[6]?parseInt(match[6]):0);break;case"e":arg=match[7]?parseFloat(arg).toExponential(match[7]):parseFloat(arg).toExponential();break;case"f":arg=match[7]?parseFloat(arg).toFixed(match[7]):parseFloat(arg);break;case"g":arg=match[7]?String(Number(arg.toPrecision(match[7]))):parseFloat(arg);break;case"o":arg=(parseInt(arg,10)>>>0).toString(8);break;case"s":arg=String(arg);arg=match[7]?arg.substring(0,match[7]):arg;break;case"t":arg=String(!!arg);arg=match[7]?arg.substring(0,match[7]):arg;break;case"T":arg=Object.prototype.toString.call(arg).slice(8,-1).toLowerCase();arg=match[7]?arg.substring(0,match[7]):arg;break;case"u":arg=parseInt(arg,10)>>>0;break;case"v":arg=arg.valueOf();arg=match[7]?arg.substring(0,match[7]):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(match[8])){output+=arg}else{if(re.number.test(match[8])&&(!is_positive||match[3])){sign=is_positive?"+":"-";arg=arg.toString().replace(re.sign,"")}else{sign=""}pad_character=match[4]?match[4]==="0"?"0":match[4].charAt(1):" ";pad_length=match[6]-(sign+arg).length;pad=match[6]?pad_length>0?pad_character.repeat(pad_length):"":"";output+=match[5]?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(match)}else{throw new SyntaxError("[sprintf] unexpected placeholder")}_fmt=_fmt.substring(match[0].length)}return sprintf_cache[fmt]=parse_tree}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}})}}}()},{}],490:[function(require,module,exports){"use strict";var paren=require("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);if(o.escape){var cleanParts=[];for(var i=0;i0){v=T[T.length-1];var e=adjList[v];if(child[v]=0){sccLinks[v].push(scc[u])}}child[v]=i}else{if(lowValue[v]===index[v]){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 c)|0 },");if(dtype==="generic"){code.push("getters:[0],")}var cubeArgs=[];var extraArgs=[];for(var i=0;i>>7){")}for(var i=0;i<1<<(1<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&127,":");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;jj){continue}if(!(i&1<0){cStr="+"+crossingCount[k]+"*c"}var weight=.5*(crossings[k].length/totalCrossings);var shift=.5+.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("}}")}var faceArgs=[];for(var i=0;i<1<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];var segments=Math.max(Math.ceil(Math.abs(ang2)/(TAU/4)),1);ang2/=segments;for(var i=0;ibounds[2])bounds[2]=points[j+0];if(points[j+1]>bounds[3])bounds[3]=points[j+1]}}return bounds}},{"abs-svg-path":51,assert:59,"is-svg-path":391,"normalize-svg-path":496,"parse-svg-path":427}],496:[function(require,module,exports){"use strict";module.exports=normalize;var arcToCurve=require("svg-arc-to-cubic-bezier");function normalize(path){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;i4){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":494}],497:[function(require,module,exports){(function(global){"use strict";var pathBounds=require("svg-path-bounds");var parsePath=require("parse-svg-path");var drawPath=require("draw-svg-path");var isSvgPath=require("is-svg-path");var bitmapSdf=require("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;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(global.Path2D){var path2d=new Path2D(path);ctx.fill(path2d);stroke&&ctx.stroke(path2d)}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}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"bitmap-sdf":81,"draw-svg-path":152,"is-svg-path":391,"parse-svg-path":427,"svg-path-bounds":495}],498:[function(require,module,exports){(function(process){"use strict";module.exports=textGet;var vectorizeText=require("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;i0){shapeX+=.02}}var data=new Float32Array(bufferSize);var ptr=0;var xOffset=-.5*shapeX;for(var i=0;i=0;var needsAlphaFormat=!formatSet&&hasAlpha&&(format==="hex"||format==="hex6"||format==="hex3"||format==="hex4"||format==="hex8"||format==="name");if(needsAlphaFormat){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)}};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)};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}}function rgbToRgb(r,g,b){return{r:bound01(r,255)*255,g:bound01(g,255)*255,b:bound01(b,255)*255}}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}else{var d=max-min;s=l>.5?d/(2-max-min):d/(max+min);switch(max){case r:h=(g-b)/d+(g1)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}else{var q=l<.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}}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}else{switch(max){case r:h=(g-b)/d+(g>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}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)};tinycolor.readability=function(color1,color2){var c1=tinycolor(color1);var c2=tinycolor(color2);return(Math.max(c1.getLuminance(),c2.getLuminance())+.05)/(Math.min(c1.getLuminance(),c2.getLuminance())+.05)};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};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;ibestScore){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)}};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"};var hexNames=tinycolor.hexNames=flip(names);function flip(o){var flipped={};for(var i in o){if(o.hasOwnProperty(i)){flipped[o[i]]=i}}return flipped}function boundAlpha(a){a=parseFloat(a);if(isNaN(a)||a<0||a>1){a=1}return a}function bound01(n,max){if(isOnePointZero(n)){n="100%"}var processPercent=isPercentage(n);n=mathMin(max,mathMax(0,parseFloat(n)));if(processPercent){n=parseInt(n*max,10)/100}if(Math.abs(n-max)<1e-6){return 1}return n%max/parseFloat(max)}function clamp01(val){return mathMin(1,mathMax(0,val))}function parseIntFromHex(val){return parseInt(val,16)}function isOnePointZero(n){return typeof n=="string"&&n.indexOf(".")!=-1&&parseFloat(n)===1}function isPercentage(n){return typeof n==="string"&&n.indexOf("%")!=-1}function pad2(c){return c.length==1?"0"+c:""+c}function convertToPercentage(n){if(n<=1){n=n*100+"%"}return n}function convertDecimalToHex(d){return Math.round(parseFloat(d)*255).toString(16)}function convertHexToDecimal(h){return parseIntFromHex(h)/255}var matchers=function(){var CSS_INTEGER="[-\\+]?\\d+%?";var CSS_NUMBER="[-\\+]?\\d*\\.\\d+%?";var CSS_UNIT="(?:"+CSS_NUMBER+")|(?:"+CSS_INTEGER+")";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})$/}}();function isValidCSSUnit(color){return!!matchers.CSS_UNIT.exec(color)}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"}}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){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}}if(typeof module!=="undefined"&&module.exports){module.exports=tinycolor}else if(typeof define==="function"&&define.amd){define(function(){return tinycolor})}else{window.tinycolor=tinycolor}})(Math)},{}],500:[function(require,module,exports){"use strict";module.exports=float32;module.exports.float32=module.exports.float=float32;module.exports.fract32=module.exports.fract=fract32;function fract32(arr){if(typeof arr==="number"){return float32(arr-float32(arr))}var fract=float32(arr);for(var i=0,l=fract.length;ix1)x1=p1[0];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(++ix1)x1=p1[0];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;k1)arcs=extractArcs(topology,object$$1,filter);else for(i=0,arcs=new Array(n=topology.arcs.length);i1){for(var i=1,k=area(arcs[0]),ki,t;ik){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>>1;if(a[mid]=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(;iMath.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]=.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){this.center.curve(t);this.up.curve(t);this.right.curve(t);this.radius.curve(t);this.angle.curve(t);var up=this.computedUp;var right=this.computedRight;var uu=0;var ur=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;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}var toward=this.computedToward;cross(toward,up,right);normalize3(toward,toward);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}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;for(var j=0;j<3;++j){rr+=mat[i+4*j]*eye[j]}mat[12+i]=-rr}mat[15]=1};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;dy=dy||0;dz=dz||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);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,dy||0,dz||0)};proto.setMatrix=function(t,mat,axes,noSnap){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;if(!mat){this.recalcMatrix(t);mat=this.computedMatrix}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<.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*Math.PI);var dp=Math.abs(lastTheta+2*Math.PI-theta);var d0=Math.abs(lastTheta-theta);var dn=Math.abs(lastTheta-2*Math.PI-theta);if(dp0){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:{},require("buffer").Buffer)},{"bit-twiddle":80,buffer:92,dup:154}],508:[function(require,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=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=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}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;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]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+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){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}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=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}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");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-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]}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"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./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"];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(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){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,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":513,_process:449,inherits:512}],515:[function(require,module,exports){"use strict";module.exports=createText;var vectorizeText=require("./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":516}],516:[function(require,module,exports){"use strict";module.exports=vectorizeText;module.exports.processPixels=processPixels;var surfaceNets=require("surface-nets");var ndarray=require("ndarray");var simplify=require("simplify-planar-graph");var cleanPSLG=require("clean-pslg");var cdt2d=require("cdt2d");var toPolygonCrappy=require("planar-graph-to-polyline");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;i8192){throw new Error("vectorize-text: String too long (sorry, this will get fixed later)")}var height=3*size;if(canvas.height=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{index=keys.length;values[index]=value;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}lastIndex=keys.length-1;keys[index]=void 0;values[index]=values[lastIndex];keys[index]=keys[lastIndex];keys.length=lastIndex;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:{value:function get(key,opt_default){return this.get___(key,opt_default)},writable:true,configurable:true},has:{value:function has(key){return this.has___(key)},writable:true,configurable:true},set:{value:function set(key,value){return this.set___(key,value)},writable:true,configurable:true},delete:{value:function remove(key){return this.delete___(key)},writable:true,configurable:true}});if(typeof HostWeakMap==="function"){(function(){if(doubleWeakMapCheckSilentFailure&&typeof Proxy!=="undefined"){Proxy=undefined}function DoubleWeakMap(){if(!(this instanceof OurWeakMap)){calledAsFunctionWarning()}var hmap=new HostWeakMap;var omap=undefined;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;Object.defineProperty(WeakMap.prototype,"constructor",{value:WeakMap,enumerable:false,configurable:true,writable:true})})()}else{if(typeof Proxy!=="undefined"){Proxy=undefined}module.exports=OurWeakMap}})()},{}],518:[function(require,module,exports){var hiddenStore=require("./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":519}],519:[function(require,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}},{}],520:[function(require,module,exports){var createStore=require("./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":518}],521:[function(require,module,exports){var getContext=require("get-canvas-context");module.exports=function getWebGLContext(opt){return getContext("webgl",opt)}},{"get-canvas-context":221}],522:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");var gregorianCalendar=main.instance();function ChineseCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}ChineseCalendar.prototype=new main.baseCalendar;assign(ChineseCalendar.prototype,{name:"Chinese",jdEpoch:1721425.5,hasYearZero:false,minMonth:0,firstMonth:0,minDay:1,regionalOptions:{"":{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}},_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},toMonthIndex:function(year,month,isIntercalary){var intercalaryMonth=this.intercalaryMonth(year);var invalidIntercalaryMonth=isIntercalary&&month!==intercalaryMonth;if(invalidIntercalaryMonth||month<1||month>12){throw main.local.invalidMonth.replace(/\{0\}/,this.local.name)}var monthIndex;if(!intercalaryMonth){monthIndex=month-1}else if(!isIntercalary&&month<=intercalaryMonth){monthIndex=month-1}else{monthIndex=month}return monthIndex},toChineseMonth:function(year,monthIndex){if(year.year){year=year.year();monthIndex=year.month()}var intercalaryMonth=this.intercalaryMonth(year);var maxMonthIndex=intercalaryMonth?12:11;if(monthIndex<0||monthIndex>maxMonthIndex){throw main.local.invalidMonth.replace(/\{0\}/,this.local.name)}var month;if(!intercalaryMonth){month=monthIndex+1}else if(monthIndex>13;return intercalaryMonth},isIntercalaryMonth:function(year,monthIndex){if(year.year){year=year.year();monthIndex=year.month()}var intercalaryMonth=this.intercalaryMonth(year);return!!intercalaryMonth&&intercalaryMonth===monthIndex},leapYear:function(year){return this.intercalaryMonth(year)!==0},weekOfYear:function(year,monthIndex,day){var validatedYear=this._validateYear(year,main.local.invalidyear);var packedDate=CHINESE_NEW_YEAR[validatedYear-CHINESE_NEW_YEAR[0]];var y=packedDate>>9&4095;var m=packedDate>>5&15;var d=packedDate&31;var firstThursday;firstThursday=gregorianCalendar.newDate(y,m,d);firstThursday.add(4-(firstThursday.dayOfWeek()||7),"d");var offset=this.toJD(year,monthIndex,day)-firstThursday.toJD();return 1+Math.floor(offset/7)},monthsInYear:function(year){return this.leapYear(year)?13:12},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},weekDay:function(year,monthIndex,day){return(this.dayOfWeek(year,monthIndex,day)||7)<6},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)},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)},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: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"){var resultYear=cdate.year();var resultMonthIndex=cdate.month();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}});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;main.calendars.chinese=ChineseCalendar;var LUNAR_MONTH_DAYS=[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];var CHINESE_NEW_YEAR=[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];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||{}}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&4095;var m=chineseNewYearPackedDate>>5&15;var d=chineseNewYearPackedDate&31;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*1e3));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>13;if(!intercalaryMonth||i=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}}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>9&4095;var m=packedDate>>5&15;var d=packedDate&31;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":536,"object-assign":421}],523:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function CopticCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}CopticCalendar.prototype=new main.baseCalendar;assign(CopticCalendar.prototype,{name:"Coptic",jdEpoch:1825029.5,daysPerMonth:[30,30,30,30,30,30,30,30,30,30,30,30,5],hasYearZero:false,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:false}},leapYear:function(year){var date=this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);var year=date.year()+(date.year()<0?1:0);return year%4===3||year%4===-1},monthsInYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear||main.regionalOptions[""].invalidYear);return 13},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-checkDate.dayOfWeek(),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},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)},weekDay:function(year,month,day){return(this.dayOfWeek(year,month,day)||7)<6},toJD:function(year,month,day){var date=this._validate(year,month,day,main.local.invalidDate);year=date.year();if(year<0){year++}return date.day()+(date.month()-1)*30+(year-1)*365+Math.floor(year/4)+this.jdEpoch-1},fromJD:function(jd){var c=Math.floor(jd)+.5-this.jdEpoch;var year=Math.floor((c-Math.floor((c+366)/1461))/365)+1;if(year<=0){year--}c=Math.floor(jd)+.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)}});main.calendars.coptic=CopticCalendar},{"../main":536,"object-assign":421}],524:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function DiscworldCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}DiscworldCalendar.prototype=new main.baseCalendar;assign(DiscworldCalendar.prototype,{name:"Discworld",jdEpoch:1721425.5,daysPerMonth:[16,32,32,32,32,32,32,32,32,32,32,32,32],hasYearZero:false,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:false}},leapYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return false},monthsInYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return 13},daysInYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return 400},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-checkDate.dayOfWeek(),"d");return Math.floor((checkDate.dayOfYear()-1)/8)+1},daysInMonth:function(year,month){var date=this._validate(year,month,this.minDay,main.local.invalidMonth);return this.daysPerMonth[date.month()-1]},daysInWeek:function(){return 8},dayOfWeek:function(year,month,day){var date=this._validate(year,month,day,main.local.invalidDate);return(date.day()+1)%8},weekDay:function(year,month,day){var dow=this.dayOfWeek(year,month,day);return dow>=2&&dow<=6},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]||""}},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},fromJD:function(jd){jd=Math.floor(jd+.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)}});var centuries={20:"Fruitbat",21:"Anchovy"};main.calendars.discworld=DiscworldCalendar},{"../main":536,"object-assign":421}],525:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function EthiopianCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}EthiopianCalendar.prototype=new main.baseCalendar;assign(EthiopianCalendar.prototype,{name:"Ethiopian",jdEpoch:1724220.5,daysPerMonth:[30,30,30,30,30,30,30,30,30,30,30,30,5],hasYearZero:false,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:false}},leapYear:function(year){var date=this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);var year=date.year()+(date.year()<0?1:0);return year%4===3||year%4===-1},monthsInYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear||main.regionalOptions[""].invalidYear);return 13},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-checkDate.dayOfWeek(),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},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)},weekDay:function(year,month,day){return(this.dayOfWeek(year,month,day)||7)<6},toJD:function(year,month,day){var date=this._validate(year,month,day,main.local.invalidDate);year=date.year();if(year<0){year++}return date.day()+(date.month()-1)*30+(year-1)*365+Math.floor(year/4)+this.jdEpoch-1},fromJD:function(jd){var c=Math.floor(jd)+.5-this.jdEpoch;var year=Math.floor((c-Math.floor((c+366)/1461))/365)+1;if(year<=0){year--}c=Math.floor(jd)+.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)}});main.calendars.ethiopian=EthiopianCalendar},{"../main":536,"object-assign":421}],526:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function HebrewCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}HebrewCalendar.prototype=new main.baseCalendar;assign(HebrewCalendar.prototype,{name:"Hebrew",jdEpoch:347995.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29,29],hasYearZero:false,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:false}},leapYear:function(year){var date=this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return this._leapYear(date.year())},_leapYear:function(year){year=year<0?year+1:year;return mod(year*7+1,19)<7},monthsInYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return this._leapYear(year.year?year.year():year)?13:12},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-checkDate.dayOfWeek(),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},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)},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:month===8&&mod(this.daysInYear(year),10)===5?30:month===9&&mod(this.daysInYear(year),10)===3?29:this.daysPerMonth[month-1]},weekDay:function(year,month,day){return this.dayOfWeek(year,month,day)!==6},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]}},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=this.toJD(year===-1?+1:year+1,7,1)){year++}var month=jdthis.toJD(year,month,this.daysInMonth(year,month))){month++}var day=jd-this.toJD(year,month,1)+1;return this.newDate(year,month,day)}});function mod(a,b){return a-b*Math.floor(a/b)}main.calendars.hebrew=HebrewCalendar},{"../main":536,"object-assign":421}],527:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function IslamicCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}IslamicCalendar.prototype=new main.baseCalendar;assign(IslamicCalendar.prototype,{name:"Islamic",jdEpoch:1948439.5,daysPerMonth:[30,29,30,29,30,29,30,29,30,29,30,29],hasYearZero:false,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ī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}},leapYear:function(year){var date=this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return(date.year()*11+14)%30<11},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-checkDate.dayOfWeek(),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},daysInYear:function(year){return this.leapYear(year)?355:354},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)},weekDay:function(year,month,day){return this.dayOfWeek(year,month,day)!==5},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},fromJD:function(jd){jd=Math.floor(jd)+.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)}});main.calendars.islamic=IslamicCalendar},{"../main":536,"object-assign":421}],528:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function JulianCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}JulianCalendar.prototype=new main.baseCalendar;assign(JulianCalendar.prototype,{name:"Julian",jdEpoch:1721423.5,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:false,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:false}},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();return year%4===0},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(4-(checkDate.dayOfWeek()||7),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},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)},weekDay:function(year,month,day){return(this.dayOfWeek(year,month,day)||7)<6},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++}if(month<=2){year--;month+=12}return Math.floor(365.25*(year+4716))+Math.floor(30.6001*(month+1))+day-1524.5},fromJD:function(jd){var a=Math.floor(jd+.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--}return this.newDate(year,month,day)}});main.calendars.julian=JulianCalendar},{"../main":536,"object-assign":421}],529:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function MayanCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}MayanCalendar.prototype=new main.baseCalendar;assign(MayanCalendar.prototype,{name:"Mayan",jdEpoch:584282.5,hasYearZero:true,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: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"]}},leapYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return false},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},forYear:function(years){years=years.split(".");if(years.length<3){throw"Invalid Mayan year"}var year=0;for(var i=0;i19||i>0&&y<0){throw"Invalid Mayan year"}year=year*20+y}return year},monthsInYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return 18},weekOfYear:function(year,month,day){this._validate(year,month,day,main.local.invalidDate);return 0},daysInYear:function(year){this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return 360},daysInMonth:function(year,month){this._validate(year,month,this.minDay,main.local.invalidMonth);return 20},daysInWeek:function(){return 5},dayOfWeek:function(year,month,day){var date=this._validate(year,month,day,main.local.invalidDate);return date.day()},weekDay:function(year,month,day){this._validate(year,month,day,main.local.invalidDate);return true},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]}},_toHaab:function(jd){jd-=this.jdEpoch;var day=mod(jd+8+(18-1)*20,365);return[Math.floor(day/20)+1,mod(day,20)]},_toTzolkin:function(jd){jd-=this.jdEpoch;return[amod(jd+20,20),amod(jd+4,13)]},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},fromJD:function(jd){jd=Math.floor(jd)+.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)}});function mod(a,b){return a-b*Math.floor(a/b)}function amod(a,b){return mod(a-1,b)+1}main.calendars.mayan=MayanCalendar},{"../main":536,"object-assign":421}],530:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function NanakshahiCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}NanakshahiCalendar.prototype=new main.baseCalendar;var gregorian=main.instance("gregorian");assign(NanakshahiCalendar.prototype,{name:"Nanakshahi",jdEpoch:2257673.5,daysPerMonth:[31,31,31,31,31,30,30,30,30,30,30,30],hasYearZero:false,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:false}},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)},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(1-(checkDate.dayOfWeek()||7),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},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)},weekDay:function(year,month,day){return(this.dayOfWeek(year,month,day)||7)<6},toJD:function(year,month,day){var date=this._validate(year,month,day,main.local.invalidMonth);var year=date.year();if(year<0){year++}var doy=date.day();for(var m=1;m=this.toJD(year+1,1,1)){year++}var day=jd-Math.floor(this.toJD(year,1,1)+.5)+1;var month=1;while(day>this.daysInMonth(year,month)){day-=this.daysInMonth(year,month);month++}return this.newDate(year,month,day)}});main.calendars.nanakshahi=NanakshahiCalendar},{"../main":536,"object-assign":421}],531:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function NepaliCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}NepaliCalendar.prototype=new main.baseCalendar;assign(NepaliCalendar.prototype,{name:"Nepali",jdEpoch:1700709.5,daysPerMonth:[31,31,32,32,31,30,30,29,30,29,30,30],hasYearZero:false,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:false}},leapYear:function(year){return this.daysInYear(year)!==this.daysPerYear},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-checkDate.dayOfWeek(),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},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},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]},weekDay:function(year,month,day){return this.dayOfWeek(year,month,day)!==6},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;var nepaliMonthToCheck=nepaliMonth;var nepaliYearToCheck=nepaliYear;this._createMissingCalendarData(nepaliYear);var gregorianYear=nepaliYear-(nepaliMonthToCheck>9||nepaliMonthToCheck===9&&nepaliDay>=this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0]?56:57);if(nepaliMonth!==9){gregorianDayOfYear=nepaliDay;nepaliMonthToCheck--}while(nepaliMonthToCheck!==9){if(nepaliMonthToCheck<=0){nepaliMonthToCheck=12;nepaliYearToCheck--}gregorianDayOfYear+=this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][nepaliMonthToCheck];nepaliMonthToCheck--}if(nepaliMonth===9){gregorianDayOfYear+=nepaliDay-this.NEPALI_CALENDAR_DATA[nepaliYearToCheck][0];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()},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._createMissingCalendarData(nepaliYear);var nepaliMonth=9;var dayOfFirstJanInPaush=this.NEPALI_CALENDAR_DATA[nepaliYear][0];var daysSinceJanFirstToEndOfNepaliMonth=this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth]-dayOfFirstJanInPaush+1;while(gregorianDayOfYear>daysSinceJanFirstToEndOfNepaliMonth){nepaliMonth++;if(nepaliMonth>12){nepaliMonth=1;nepaliYear++}daysSinceJanFirstToEndOfNepaliMonth+=this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth]}var nepaliDayOfMonth=this.NEPALI_CALENDAR_DATA[nepaliYear][nepaliMonth]-(daysSinceJanFirstToEndOfNepaliMonth-gregorianDayOfYear);return this.newDate(nepaliYear,nepaliMonth,nepaliDayOfMonth)},_createMissingCalendarData:function(nepaliYear){var tmp_calendar_data=this.daysPerMonth.slice(0);tmp_calendar_data.unshift(17);for(var nepaliYearToCreate=nepaliYear-1;nepaliYearToCreate0?474:473))%2820+474+38)*682%2816<682},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-((checkDate.dayOfWeek()+1)%7),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},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)},weekDay:function(year,month,day){return this.dayOfWeek(year,month,day)!==5},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},fromJD:function(jd){jd=Math.floor(jd)+.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)}});function mod(a,b){return a-b*Math.floor(a/b)}main.calendars.persian=PersianCalendar;main.calendars.jalali=PersianCalendar},{"../main":536,"object-assign":421}],533:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");var gregorianCalendar=main.instance();function TaiwanCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}TaiwanCalendar.prototype=new main.baseCalendar;assign(TaiwanCalendar.prototype,{name:"Taiwan",jdEpoch:2419402.5,yearsOffset:1911,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:false,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:false}},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)},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())},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)},weekDay:function(year,month,day){return(this.dayOfWeek(year,month,day)||7)<6},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())},fromJD:function(jd){var date=gregorianCalendar.fromJD(jd);var year=this._g2tYear(date.year());return this.newDate(year,date.month(),date.day())},_t2gYear:function(year){return year+this.yearsOffset+(year>=-this.yearsOffset&&year<=-1?1:0)},_g2tYear:function(year){return year-this.yearsOffset-(year>=1&&year<=this.yearsOffset?1:0)}});main.calendars.taiwan=TaiwanCalendar},{"../main":536,"object-assign":421}],534:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");var gregorianCalendar=main.instance();function ThaiCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}ThaiCalendar.prototype=new main.baseCalendar;assign(ThaiCalendar.prototype,{name:"Thai",jdEpoch:1523098.5,yearsOffset:543,daysPerMonth:[31,28,31,30,31,30,31,31,30,31,30,31],hasYearZero:false,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:false}},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)},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())},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)},weekDay:function(year,month,day){return(this.dayOfWeek(year,month,day)||7)<6},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())},fromJD:function(jd){var date=gregorianCalendar.fromJD(jd);var year=this._g2tYear(date.year());return this.newDate(year,date.month(),date.day())},_t2gYear:function(year){return year-this.yearsOffset-(year>=1&&year<=this.yearsOffset?1:0)},_g2tYear:function(year){return year+this.yearsOffset+(year>=-this.yearsOffset&&year<=-1?1:0)}});main.calendars.thai=ThaiCalendar},{"../main":536,"object-assign":421}],535:[function(require,module,exports){var main=require("../main");var assign=require("object-assign");function UmmAlQuraCalendar(language){this.local=this.regionalOptions[language||""]||this.regionalOptions[""]}UmmAlQuraCalendar.prototype=new main.baseCalendar;assign(UmmAlQuraCalendar.prototype,{name:"UmmAlQura",hasYearZero:false,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ā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}},leapYear:function(year){var date=this._validate(year,this.minMonth,this.minDay,main.local.invalidYear);return this.daysInYear(date.year())===355},weekOfYear:function(year,month,day){var checkDate=this.newDate(year,month,day);checkDate.add(-checkDate.dayOfWeek(),"d");return Math.floor((checkDate.dayOfYear()-1)/7)+1},daysInYear:function(year){var daysCount=0;for(var i=1;i<=12;i++){daysCount+=this.daysInMonth(year,i)}return daysCount},daysInMonth:function(year,month){var date=this._validate(year,month,this.minDay,main.local.invalidMonth);var mcjdn=date.toJD()-24e5+.5;var index=0;for(var i=0;imcjdn){return ummalqura_dat[index]-ummalqura_dat[index-1]}index++}return 30},weekDay:function(year,month,day){return this.dayOfWeek(year,month,day)!==5},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+24e5-.5},fromJD:function(jd){var mcjdn=jd-24e5+.5;var index=0;for(var i=0;imcjdn)break;index++}var lunation=index+15292;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)},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},_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}});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,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":536,"object-assign":421}],536:[function(require,module,exports){var assign=require("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={}}assign(Calendars.prototype,{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},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)},substituteDigits:function(digits){return function(value){return(value+"").replace(/[0-9]/g,function(digit){return digits[digit]})}},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]}}});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)}}function pad(value,length){value=""+value;return"000000".substring(0,length-value.length)+value}assign(CDate.prototype,{newDate:function(year,month,day){return this._calendar.newDate(year==null?this:year,month,day)},year:function(year){return arguments.length===0?this._year:this.set(year,"y")},month:function(month){return arguments.length===0?this._month:this.set(month,"m")},day:function(day){return arguments.length===0?this._day:this.set(day,"d")},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},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(offset,period){return this._calendar.add(this,offset,period)},set:function(value,period){return this._calendar.set(this,value,period)},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},calendar:function(){return this._calendar},toJD:function(){return this._calendar.toJD(this)},fromJD:function(jd){return this._calendar.fromJD(jd)},toJSDate:function(){return this._calendar.toJSDate(this)},fromJSDate:function(jsd){return this._calendar.fromJSDate(jsd)},toString:function(){return(this.year()<0?"-":"")+pad(Math.abs(this.year()),4)+"-"+pad(this.month(),2)+"-"+pad(this.day(),2)}});function BaseCalendar(){this.shortYearCutoff="+10"}assign(BaseCalendar.prototype,{_validateLevel:0,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)},today:function(){return this.fromJSDate(new Date)},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]},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)},monthsInYear:function(year){this._validate(year,this.minMonth,this.minDay,_exports.local.invalidYear||_exports.regionalOptions[""].invalidYear);return 12},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},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},daysInYear:function(year){var date=this._validate(year,this.minMonth,this.minDay,_exports.local.invalidYear||_exports.regionalOptions[""].invalidYear);return this.leapYear(date)?366:365},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},daysInWeek:function(){return 7},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()},extraInfo:function(year,month,day){this._validate(year,month,day,_exports.local.invalidDate||_exports.regionalOptions[""].invalidDate);return{}},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: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();var resyncYearMonth=function(calendar){while(myearMonths-1+calendar.minMonth){y++;m-=yearMonths;yearMonths=calendar.monthsInYear(y)}};if(period==="y"){if(date.month()!==this.fromMonthOfYear(y,m)){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}},_correctAdd:function(date,ymd,offset,period){if(!this.hasYearZero&&(period==="y"||period==="m")){if(ymd[0]===0||date.year()>0!==ymd[0]>0){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: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)},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.minDay&&day-this.minDay13.5?13:1);var year=c-(month>2.5?4716:4715);if(year<=0){year--}return this.newDate(year,month,day)},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);jsd.setHours(jsd.getHours()>12?jsd.getHours()+2:0);return jsd},fromJSDate:function(jsd){return this.newDate(jsd.getFullYear(),jsd.getMonth()+1,jsd.getDate())}});var _exports=module.exports=new Calendars;_exports.cdate=CDate;_exports.baseCalendar=BaseCalendar;_exports.calendars.gregorian=GregorianCalendar},{"object-assign":421}],537:[function(require,module,exports){var assign=require("object-assign");var main=require("./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,{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,TICKS_PER_DAY:24*60*60*1e7,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(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;var doubled=function(match,step){var matches=1;while(iFormat+matches1};var formatNumber=function(match,value,len,step){var num=""+value;if(doubled(match,step)){while(num.length1};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)};var calendar=this;var getMonthNumber=function(){if(typeof monthNumbers==="function"){doubled("m");var month=monthNumbers.call(calendar,value.substring(iValue));iValue+=month.length;return month}return getNumber("m")};var getName=function(match,shortNames,longNames,step){var names=doubled(match,step)?longNames:shortNames;for(var i=0;i-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)},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){}offset=offset.toLowerCase();var date=(offset.match(/^c/)&¤tDate?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":536,"object-assign":421}],538:[function(require,module,exports){module.exports=require("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":133}],539:[function(require,module,exports){"use strict";module.exports=findZeroCrossings;var core=require("./lib/zc-core");function findZeroCrossings(array,level){var cross=[];level=+level||0;core(array.hi(array.shape[0]-1),cross,level);return cross}},{"./lib/zc-core":538}],540:[function(require,module,exports){"use strict";module.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:true},{path:"M2,2V-2H-2V2Z",backoff:0,noRotate:true}]},{}],541:[function(require,module,exports){"use strict";var ARROWPATHS=require("./arrow_paths");var fontAttrs=require("../../plots/font_attributes");var cartesianConstants=require("../../plots/cartesian/constants");var templatedArray=require("../../plot_api/plot_template").templatedArray;module.exports=templatedArray("annotation",{visible:{valType:"boolean",dflt:true,editType:"calcIfAutorange+arraydraw"},text:{valType:"string",editType:"calcIfAutorange+arraydraw"},textangle:{valType:"angle",dflt:0,editType:"calcIfAutorange+arraydraw"},font:fontAttrs({editType:"calcIfAutorange+arraydraw",colorEditType:"arraydraw"}),width:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+arraydraw"},height:{valType:"number",min:1,dflt:null,editType:"calcIfAutorange+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:"calcIfAutorange+arraydraw"},borderwidth:{valType:"number",min:0,dflt:1,editType:"calcIfAutorange+arraydraw"},showarrow:{valType:"boolean",dflt:true,editType:"calcIfAutorange+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:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},startarrowsize:{valType:"number",min:.3,dflt:1,editType:"calcIfAutorange+arraydraw"},arrowwidth:{valType:"number",min:.1,editType:"calcIfAutorange+arraydraw"},standoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},startstandoff:{valType:"number",min:0,dflt:0,editType:"calcIfAutorange+arraydraw"},ax:{valType:"any",editType:"calcIfAutorange+arraydraw"},ay:{valType:"any",editType:"calcIfAutorange+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"},xref:{valType:"enumerated",values:["paper",cartesianConstants.idRegex.x.toString()],editType:"calc"},x:{valType:"any",editType:"calcIfAutorange+arraydraw"},xanchor:{valType:"enumerated",values:["auto","left","center","right"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},xshift:{valType:"number",dflt:0,editType:"calcIfAutorange+arraydraw"},yref:{valType:"enumerated",values:["paper",cartesianConstants.idRegex.y.toString()],editType:"calc"},y:{valType:"any",editType:"calcIfAutorange+arraydraw"},yanchor:{valType:"enumerated",values:["auto","top","middle","bottom"],dflt:"auto",editType:"calcIfAutorange+arraydraw"},yshift:{valType:"number",dflt:0,editType:"calcIfAutorange+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":722,"../../plots/cartesian/constants":737,"../../plots/font_attributes":758,"./arrow_paths":540}],542:[function(require,module,exports){"use strict";var Lib=require("../../lib");var Axes=require("../../plots/cartesian/axes");var draw=require("./draw").draw;module.exports=function calcAutorange(gd){var fullLayout=gd._fullLayout,annotationList=Lib.filterVisible(fullLayout.annotations);if(!annotationList.length||!gd._fullData.length)return;var annotationAxes={};annotationList.forEach(function(ann){annotationAxes[ann.xref]=1;annotationAxes[ann.yref]=1});for(var axId in annotationAxes){var ax=Axes.getFromId(gd,axId);if(ax&&ax.autorange){return Lib.syncOrAsync([draw,annAutorange],gd)}}};function annAutorange(gd){var fullLayout=gd._fullLayout;Lib.filterVisible(fullLayout.annotations).forEach(function(ann){var xa=Axes.getFromId(gd,ann.xref),ya=Axes.getFromId(gd,ann.yref),headSize=3*ann.arrowsize*ann.arrowwidth||0,startHeadSize=3*ann.startarrowsize*ann.arrowwidth||0;var headPlus,headMinus,startHeadPlus,startHeadMinus;if(xa&&xa.autorange){headPlus=headSize+ann.xshift;headMinus=headSize-ann.xshift;startHeadPlus=startHeadSize+ann.xshift;startHeadMinus=startHeadSize-ann.xshift;if(ann.axref===ann.xref){Axes.expand(xa,[xa.r2c(ann.x)],{ppadplus:headPlus,ppadminus:headMinus});Axes.expand(xa,[xa.r2c(ann.ax)],{ppadplus:Math.max(ann._xpadplus,startHeadPlus),ppadminus:Math.max(ann._xpadminus,startHeadMinus)})}else{startHeadPlus=ann.ax?startHeadPlus+ann.ax:startHeadPlus;startHeadMinus=ann.ax?startHeadMinus-ann.ax:startHeadMinus;Axes.expand(xa,[xa.r2c(ann.x)],{ppadplus:Math.max(ann._xpadplus,headPlus,startHeadPlus),ppadminus:Math.max(ann._xpadminus,headMinus,startHeadMinus)})}}if(ya&&ya.autorange){headPlus=headSize-ann.yshift;headMinus=headSize+ann.yshift;startHeadPlus=startHeadSize-ann.yshift;startHeadMinus=startHeadSize+ann.yshift;if(ann.ayref===ann.yref){Axes.expand(ya,[ya.r2c(ann.y)],{ppadplus:headPlus,ppadminus:headMinus});Axes.expand(ya,[ya.r2c(ann.ay)],{ppadplus:Math.max(ann._ypadplus,startHeadPlus),ppadminus:Math.max(ann._ypadminus,startHeadMinus)})}else{startHeadPlus=ann.ay?startHeadPlus+ann.ay:startHeadPlus;startHeadMinus=ann.ay?startHeadMinus-ann.ay:startHeadMinus;Axes.expand(ya,[ya.r2c(ann.y)],{ppadplus:Math.max(ann._ypadplus,headPlus,startHeadPlus),ppadminus:Math.max(ann._ypadminus,headMinus,startHeadMinus)})}}})}},{"../../lib":684,"../../plots/cartesian/axes":732,"./draw":547}],543:[function(require,module,exports){"use strict";var Lib=require("../../lib");var Registry=require("../../registry");var arrayEditor=require("../../plot_api/plot_template").arrayEditor;module.exports={hasClickToShow:hasClickToShow,onClick:onClick};function hasClickToShow(gd,hoverData){var sets=getToggleSets(gd,hoverData);return sets.on.length>0||sets.explicitOff.length>0}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;i2/3)anchor="right";else anchor="center"}return{center:0,middle:0,left:.5,bottom:-.5,right:-.5,top:.5}[anchor]}var annotationIsOffscreen=false;var letters=["x","y"];for(var i=0;i1)){if(tailRef===axRef){posFraction=ax.r2fraction(options["a"+axLetter]);if(posFraction<0||posFraction>1){annotationIsOffscreen=true}}else{annotationIsOffscreen=true}if(annotationIsOffscreen)continue}basePx=ax._offset+ax.r2p(options[axLetter]);autoAlignFraction=.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?.5:alignPosition}if(options.showarrow){posPx.head=basePx;var arrowLength=options["a"+axLetter];textShift=annSizeFromWidth*shiftFraction(.5,options.xanchor)-annSizeFromHeight*shiftFraction(.5,options.yanchor);if(tailRef===axRef){posPx.tail=ax._offset+ax.r2p(arrowLength);textPadShift=textShift}else{posPx.tail=basePx+arrowLength;textPadShift=textShift+arrowLength}posPx.text=posPx.tail+textShift;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),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{textShift=annSize*shiftFraction(autoAlignFraction,anchor);textPadShift=textShift;posPx.text=basePx+textShift}posPx.text+=overallShift;textShift+=overallShift;textPadShift+=overallShift;options["_"+axLetter+"padplus"]=annSize/2+textPadShift;options["_"+axLetter+"padminus"]=annSize/2-textPadShift;options["_"+axLetter+"size"]=annSize;options["_"+axLetter+"shift"]=textShift}if(annotationIsOffscreen){annTextGroupInner.remove();return}var xShift=0;var yShift=0;if(options.align!=="left"){xShift=(annWidth-textWidth)*(options.align==="center"?.5:1)}if(options.valign!=="top"){yShift=(annHeight-textHeight)*(options.valign==="middle"?.5:1)}if(hasMathjax){mathjaxGroup.select("svg").attr({x:borderfull+xShift-1,y:borderfull+yShift}).call(Drawing.setClipUrl,isSizeConstrained?annClipID:null)}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)}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));annTextGroup.attr({transform:"rotate("+textangle+","+annPosPx.x.text+","+annPosPx.y.text+")"});var drawArrow=function(dx,dy){annGroup.selectAll(".annotation-arrow-g").remove();var headX=annPosPx.x.head,headY=annPosPx.y.head,tailX=annPosPx.x.tail+dx,tailY=annPosPx.y.tail+dy,textX=annPosPx.x.text+dx,textY=annPosPx.y.text+dy,transform=Lib.rotationXYMatrix(textangle,textX,textY),applyTransform=Lib.apply2DTransform(transform),applyTransform2=Lib.apply2DTransform2(transform),width=+annTextBG.attr("width"),height=+annTextBG.attr("height"),xLeft=textX-.5*width,xRight=xLeft+width,yTop=textY-.5*height,yBottom=yTop+height,edges=[[xLeft,yTop,xLeft,yBottom],[xLeft,yBottom,xRight,yBottom],[xRight,yBottom,xRight,yTop],[xRight,yTop,xLeft,yTop]].map(applyTransform2);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)){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,arrowColor=options.arrowcolor,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);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;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),xcenter=annxy0[0]+dx,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("relayout",gd,getUpdateObj());var notesBox=document.querySelector(".js-notes-box-panel");if(notesBox)notesBox.redraw(notesBox.selectedObj)}})}};if(options.showarrow)drawArrow(0,0);if(editTextPosition){var baseTextTransform;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,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,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?.5:xUpdate,ya?.5:yUpdate,options.xanchor,options.yanchor)}}else return;annTextGroup.attr({transform:"translate("+dx+","+dy+")"+baseTextTransform});setCursor(annTextGroupInner,csr)},doneFn:function(){setCursor(annTextGroupInner);Registry.call("relayout",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("relayout",gd,getUpdateObj())})}else annText.call(textLayout)}},{"../../lib":684,"../../lib/setcursor":704,"../../lib/svg_text_utils":708,"../../plot_api/plot_template":722,"../../plots/cartesian/axes":732,"../../plots/plots":795,"../../registry":817,"../color":558,"../dragelement":580,"../drawing":583,"../fx":600,"./draw_arrow_head":548,d3:147}],548:[function(require,module,exports){"use strict";var d3=require("d3");var Color=require("../color");var ARROWPATHS=require("./arrow_paths");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),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),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(),dashArray="";if(pathlen1){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":783,"../annotations/draw":547}],554:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Lib=require("../../lib");module.exports={moduleType:"component",name:"annotations3d",schema:{subplots:{scene:{annotations:require("./attributes")}}},layoutAttributes:require("./attributes"),handleDefaults:require("./defaults"),includeBasePlot:includeGL3D,convert:require("./convert"),draw:require("./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=0))return val;if(i===3){if(parts[i]>1)parts[i]=1}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":557,"fast-isnumeric":214,tinycolor2:499}],559:[function(require,module,exports){"use strict";var axesAttrs=require("../../plots/cartesian/layout_attributes");var fontAttrs=require("../../plots/font_attributes");var extendFlat=require("../../lib/extend").extendFlat;var overrideAll=require("../../plot_api/edit_types").overrideAll;module.exports=overrideAll({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:axesAttrs.linecolor,outlinewidth:axesAttrs.linewidth,bordercolor:axesAttrs.linecolor,borderwidth:{valType:"number",min:0,dflt:0},bgcolor:{valType:"color",dflt:"rgba(0,0,0,0)"},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:{valType:"string"},titlefont:fontAttrs({}),titleside:{valType:"enumerated",values:["right","top","bottom"],dflt:"top"}},"colorbars","from-root")},{"../../lib/extend":673,"../../plot_api/edit_types":715,"../../plots/cartesian/layout_attributes":744,"../../plots/font_attributes":758}],560:[function(require,module,exports){"use strict";var Colorscale=require("../colorscale");var drawColorbar=require("./draw");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;var containerName=moduleOpts.container;var container=containerName?trace[containerName]:trace;gd._fullLayout._infolayer.selectAll("."+cbId).remove();if(!container||!container.showscale)return;var zmin=container[moduleOpts.min];var zmax=container[moduleOpts.max];var cb=cd[0].t.cb=drawColorbar(gd,cbId);var sclFunc=Colorscale.makeColorScaleFunc(Colorscale.extractScale(container.colorscale,zmin,zmax),{noNumericCheck:true});cb.fillcolor(sclFunc).filllevels({start:zmin,end:zmax,size:(zmax-zmin)/254}).options(container.colorbar)()}},{"../colorscale":573,"./draw":563}],561:[function(require,module,exports){"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"}}},{}],562:[function(require,module,exports){"use strict";var Lib=require("../../lib");var Template=require("../../plot_api/plot_template");var handleTickValueDefaults=require("../../plots/cartesian/tick_value_defaults");var handleTickMarkDefaults=require("../../plots/cartesian/tick_mark_defaults");var handleTickLabelDefaults=require("../../plots/cartesian/tick_label_defaults");var attributes=require("./attributes");module.exports=function colorbarDefaults(containerIn,containerOut,layout){var colorbarOut=Template.newContainer(containerOut,"colorbar"),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",layout._dfltTitle.colorbar);Lib.coerceFont(coerce,"titlefont",layout.font);coerce("titleside")}},{"../../lib":684,"../../plot_api/plot_template":722,"../../plots/cartesian/tick_label_defaults":751,"../../plots/cartesian/tick_mark_defaults":752,"../../plots/cartesian/tick_value_defaults":753,"./attributes":559}],563:[function(require,module,exports){"use strict";var d3=require("d3");var tinycolor=require("tinycolor2");var Plots=require("../../plots/plots");var Registry=require("../../registry");var Axes=require("../../plots/cartesian/axes");var dragElement=require("../dragelement");var Lib=require("../../lib");var extendFlat=require("../../lib/extend").extendFlat;var setCursor=require("../../lib/setcursor");var Drawing=require("../drawing");var Color=require("../color");var Titles=require("../titles");var svgTextUtils=require("../../lib/svg_text_utils");var alignmentConstants=require("../../constants/alignment");var LINE_SPACING=alignmentConstants.LINE_SPACING;var FROM_TL=alignmentConstants.FROM_TL;var FROM_BR=alignmentConstants.FROM_BR;var handleAxisDefaults=require("../../plots/cartesian/axis_defaults");var handleAxisPositionDefaults=require("../../plots/cartesian/position_defaults");var axisLayoutAttrs=require("../../plots/cartesian/layout_attributes");var attributes=require("./attributes");var cn=require("./constants").cn;module.exports=function draw(gd,id){var opts={};Object.keys(attributes).forEach(function(k){opts[k]=null});opts.fillcolor=null;opts.line={color:null,width:null,dash:null};opts.levels={start:null,end:null,size:null};opts.filllevels=null;function component(){var fullLayout=gd._fullLayout,gs=fullLayout._size;if(typeof opts.fillcolor!=="function"&&typeof opts.line.color!=="function"){fullLayout._infolayer.selectAll("g."+id).remove();return}var 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,ls=opts.levels.size,zr0=1.001*zrange[0]-.001*zrange[1],zr1=1.001*zrange[1]-.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&&l0?l>=l0:l<=l0)break;if(l>zrange[0]&&l1){var dtexp=Math.pow(10,Math.floor(Math.log(dtFactor)/Math.LN10));dtick*=dtexp*Lib.roundUp(dtFactor/dtexp,[2,5,10]);if((Math.abs(opts.levels.start)/opts.levels.size+1e-6)%1<2e-6){cbAxisOut.tick0=0}}cbAxisOut.dtick=dtick}cbAxisOut.domain=[yBottomFrac+ypadFrac,yBottomFrac+lenFrac-ypadFrac];cbAxisOut.setScale();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)+")");var titleCont=container.select(".cbtitleunshift").attr("transform","translate(-"+Math.round(gs.l)+",-"+Math.round(gs.t)+")");cbAxisOut._axislayer=container.select(".cbaxis");var titleHeight=0;if(["top","bottom"].indexOf(opts.titleside)!==-1){var x=gs.l+(opts.x+xpadFrac)*gs.w,fontSize=cbAxisOut.titlefont.size,y;if(opts.titleside==="top"){y=(1-(yBottomFrac+lenFrac-ypadFrac))*gs.h+gs.t+3+fontSize*.75}else{y=(1-(yBottomFrac+ypadFrac))*gs.h+gs.t-3-fontSize*.25}drawTitle(cbAxisOut._id+"title",{attributes:{x:x,y:y,"text-anchor":"start"}})}function drawAxis(){if(["top","bottom"].indexOf(opts.titleside)!==-1){var titleGroup=container.select(".cbtitle"),titleText=titleGroup.select("text"),titleTrans=[-opts.outlinewidth/2,opts.outlinewidth/2],mathJaxNode=titleGroup.select(".h"+cbAxisOut._id+"title-math-group").node(),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){titleTrans[1]-=(titleHeight-lineSize)/2}}else if(titleText.node()&&!titleText.classed(cn.jsPlaceholder)){titleHeight=Drawing.bBox(titleText.node()).height}if(titleHeight){titleHeight+=5;if(opts.titleside==="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]))+")");cbAxisOut._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();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);if(i!==filllevels.length-1){z[1]+=z[1]>z[0]?1:-1}var colorString=fillcolormap(d).replace("e-",""),opaqueColor=tinycolor(colorString).toHexString();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),fill:opaqueColor})});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)});cbAxisOut._axislayer.selectAll("g."+cbAxisOut._id+"tick,path").remove();cbAxisOut._pos=xLeft+thickPx+(opts.outlinewidth||0)/2-(opts.ticks==="outside"?1:0);cbAxisOut.side="right";return Lib.syncOrAsync([function(){return Axes.doTicksSingle(gd,cbAxisOut,true)},function(){if(["top","bottom"].indexOf(opts.titleside)===-1){var fontSize=cbAxisOut.titlefont.size,y=cbAxisOut._offset+cbAxisOut._length/2,x=gs.l+(cbAxisOut.position||0)*gs.w+(cbAxisOut.side==="right"?10+fontSize*(cbAxisOut.showticklabels?1:.5):-10-fontSize*(cbAxisOut.showticklabels?.5:0));drawTitle("h"+cbAxisOut._id+"title",{avoid:{selection:d3.select(gd).selectAll("g."+cbAxisOut._id+"tick"),side:opts.titleside,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 trace=getTrace();var propName="colorbar.title";var containerName=trace._module.colorbar.container;if(containerName)propName=containerName+"."+propName;var dfltTitleOpts={propContainer:cbAxisOut,propName:propName,traceIndex:trace.index,placeholder:fullLayout._dfltTitle.colorbar,containerGroup:container.select(".cbtitle")};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(){var innerWidth=thickPx+opts.outlinewidth/2+Drawing.bBox(cbAxisOut._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(),titleWidth;if(mathJaxNode&&["top","bottom"].indexOf(opts.titleside)!==-1){titleWidth=Drawing.bBox(mathJaxNode).width}else{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,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.titleside==="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});var xoffset=({center:.5,right:1}[opts.xanchor]||0)*outerwidth;container.attr("transform","translate("+(gs.l-xoffset)+","+gs.t+")");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);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){Registry.call("restyle",gd,{"colorbar.x":xf,"colorbar.y":yf},getTrace().index)}}})}return cbDone}function getTrace(){var idNum=id.substr(2),i,trace;for(i=0;i=0)scl=scales.Reds;else scl=scales.Blues;doUpdate("colorscale",scl,container.reversescale?flipScale(scl):scl);if(!inputContainer.autocolorscale){doUpdate("autocolorscale",false)}}}},{"../../lib":684,"./flip_scale":570,"./scales":577}],567:[function(require,module,exports){"use strict";var scales=require("./scales");module.exports=scales.RdBu},{"./scales":577}],568:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var Lib=require("../../lib");var hasColorbar=require("../colorbar/has_colorbar");var colorbarDefaults=require("../colorbar/defaults");var isValidScale=require("./is_valid_scale");var flipScale=require("./flip_scale");module.exports=function colorScaleDefaults(traceIn,traceOut,layout,coerce,opts){var prefix=opts.prefix,cLetter=opts.cLetter,containerStr=prefix.slice(0,prefix.length-1),containerIn=prefix?Lib.nestedProperty(traceIn,containerStr).get()||{}:traceIn,containerOut=prefix?Lib.nestedProperty(traceOut,containerStr).get()||{}:traceOut,minIn=containerIn[cLetter+"min"],maxIn=containerIn[cLetter+"max"],sclIn=containerIn.colorscale;var validMinMax=isNumeric(minIn)&&isNumeric(maxIn)&&minIn=0;i--,j++){si=scl[i];sclNew[j]=[1-si[0],si[1]]}return sclNew}},{}],571:[function(require,module,exports){"use strict";var scales=require("./scales");var defaultScale=require("./default_scale");var isValidScaleArray=require("./is_valid_scale_array");module.exports=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();if(typeof scl==="string")parseScale()}if(!isValidScaleArray(scl))return dflt;return scl}},{"./default_scale":567,"./is_valid_scale_array":575,"./scales":577}],572:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var Lib=require("../../lib");var isValidScale=require("./is_valid_scale");module.exports=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;i4/3-vc)return vmax;return vc}},{}],579:[function(require,module,exports){"use strict";var Lib=require("../../lib");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":684}],580:[function(require,module,exports){"use strict";var mouseOffset=require("mouse-event-offset");var hasHover=require("has-hover");var supportsPassive=require("has-passive-events");var Registry=require("../../registry");var Lib=require("../../lib");var constants=require("../../plots/cartesian/constants");var interactConstants=require("../../constants/interactions");var dragElement=module.exports={};dragElement.align=require("./align");dragElement.getCursor=require("./cursor");var unhover=require("./unhover");dragElement.unhover=unhover.wrapped;dragElement.unhoverRaw=unhover.raw;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)DBLCLICKDELAY){numClicks=Math.max(numClicks-1,1)}if(gd._dragged){if(options.doneFn)options.doneFn()}else{if(options.clickFn)options.clickFn(numClicks,initialEvent);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":660,"../../lib":684,"../../plots/cartesian/constants":737,"../../registry":817,"./align":578,"./cursor":579,"./unhover":581,"has-hover":378,"has-passive-events":379,"mouse-event-offset":403}],581:[function(require,module,exports){"use strict";var Events=require("../../lib/events");var throttle=require("../../lib/throttle");var getGraphDiv=require("../../lib/get_graph_div");var hoverConstants=require("../fx/constants");var unhover=module.exports={};unhover.wrapped=function(gd,evt,subplot){gd=getGraphDiv(gd);if(gd._fullLayout){throttle.clear(gd._fullLayout._uid+hoverConstants.HOVERID)}unhover.raw(gd,evt,subplot)};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":672,"../../lib/get_graph_div":679,"../../lib/throttle":709,"../fx/constants":595}],582:[function(require,module,exports){"use strict";exports.dash={valType:"string",values:["solid","dot","dash","longdash","dashdot","longdashdot"],dflt:"solid",editType:"style"}},{}],583:[function(require,module,exports){"use strict";var d3=require("d3");var isNumeric=require("fast-isnumeric");var tinycolor=require("tinycolor2");var Registry=require("../../registry");var Color=require("../color");var Colorscale=require("../colorscale");var Lib=require("../../lib");var svgTextUtils=require("../../lib/svg_text_utils");var xmlnsNamespaces=require("../../constants/xmlns_namespaces");var alignment=require("../../constants/alignment");var LINE_SPACING=alignment.LINE_SPACING;var DESELECTDIM=require("../../constants/interactions").DESELECTDIM;var subTypes=require("../../traces/scatter/subtypes");var makeBubbleSizeFn=require("../../traces/scatter/make_bubble_size_func");var drawing=module.exports={};drawing.font=function(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)};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)};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()){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){if(!lineWidth||!isNumeric(lineWidth))return dflt||0;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||{},lw1=lw||line.width||0,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||{},lw1=lw||line.width||0,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"}return dash};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);try{shape.call(Color.fill,d[0].trace.fillcolor)}catch(e){Lib.error(e,s);shape.remove()}})};var SYMBOLDEFS=require("./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,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};drawing.gradient=function(sel,gd,gradientID,type,color1,color2){var gradient=gd._fullLayout._defs.select(".gradients").selectAll("#"+gradientID).data([type+color1+color2],Lib.identity);gradient.exit().remove();gradient.enter().append(type==="radial"?"radialGradient":"linearGradient").each(function(){var el=d3.select(this);if(type==="horizontal")el.attr(HORZGRADIENT);else if(type==="vertical")el.attr(VERTGRADIENT);el.attr("id",gradientID);var tc1=tinycolor(color1);var tc2=tinycolor(color2);el.append("stop").attr({offset:"0%","stop-color":Color.tinyRGB(tc2),"stop-opacity":tc2.getAlpha()});el.append("stop").attr({offset:"100%","stop-color":Color.tinyRGB(tc1),"stop-opacity":tc1.getAlpha()})});sel.style({fill:"url(#"+gradientID+")","fill-opacity":null})};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;if(d.ms==="various"||marker.size==="various"){r=3}else{r=fns.ms2mrc(d.ms)}d.mrc=r;if(fns.selectedSizeFn){r=d.mrc=fns.selectedSizeFn(d)}var x=drawing.symbolNumber(d.mx||marker.symbol)||0;d.om=x%200>=100;sel.attr("d",makePointPath(x,r))}var perPointGradient=false;var fillColor,lineColor,lineWidth;if(d.so){lineWidth=markerLine.outlierwidth;lineColor=markerLine.outliercolor;fillColor=marker.outliercolor}else{var markerLineWidth=(markerLine||{}).width;lineWidth=(d.mlw+1||markerLineWidth+1||(d.trace?(d.trace.marker.line||{}).width:0)+1)-1||0;if("mlc"in d)lineColor=d.mlcc=fns.lineScale(d.mlc);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){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;if(gradientType&&gradientType!=="none"){var gradientColor=d.mgc;if(gradientColor)perPointGradient=true;else gradientColor=markerGradient.color;var gradientID="g"+gd._fullLayout._uid+"-"+trace.uid;if(perPointGradient)gradientID+="-"+d.i;sel.call(drawing.gradient,gd,gradientID,gradientType,fillColor,gradientColor)}else{sel.call(Color.fill,fillColor)}if(lineWidth){sel.call(Color.stroke,lineColor)}}};drawing.makePointStyleFns=function(trace){var out={};var marker=trace.marker;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));d.mrc2=mrc2})}if(seq.length){s.each(function(d){var pt=d3.select(this);for(var i=0;i0?fontSize:0}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)})};var CatmullRomExp=.5;drawing.smoothopen=function(pts,smoothness){if(pts.length<3){return"M"+pts.join("L")}var path="M"+pts[0],tangents=[],i;for(i=1;i=maxSavedBBoxes){drawing.savedBBoxes={};savedBBoxesCount=0}if(hash)drawing.savedBBoxes[hash]=bb;savedBBoxesCount++;return Lib.extendFlat({},bb)};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")}drawing.setClipUrl=function(s,localId){if(!localId){s.attr("clip-path",null);return}if(drawing.baseUrl===undefined){var base=d3.select("base");if(base.size()&&base.attr("href")){drawing.baseUrl=window.location.href.split("#")[0]}else{drawing.baseUrl=""}}s.attr("clip-path","url("+drawing.baseUrl+"#"+localId+")")};drawing.getTranslate=function(element){var re=/.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/,getter=element.attr?"attr":"getAttribute",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\(.*?\);?)/,getter=element.attr?"attr":"getAttribute",setter=element.attr?"attr":"setAttribute",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].*/,getter=element.attr?"attr":"getAttribute",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\(.*?\);?)/,getter=element.attr?"attr":"getAttribute",setter=element.attr?"attr":"setAttribute",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;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":656,"../../constants/interactions":660,"../../constants/xmlns_namespaces":663,"../../lib":684,"../../lib/svg_text_utils":708,"../../registry":817,"../../traces/scatter/make_bubble_size_func":1031,"../../traces/scatter/subtypes":1037,"../color":558,"../colorscale":573,"./symbol_defs":584,d3:147,"fast-isnumeric":214,tinycolor2:499}],584:[function(require,module,exports){"use strict";var d3=require("d3");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*.4,2),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*.8/Math.sqrt(2),2),ne="l"+rx+","+rx,se="l"+rx+",-"+rx,sw="l-"+rx+",-"+rx,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),r2=d3.round(r/2,2),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),r2=d3.round(r/2,2),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),r2=d3.round(r/2,2),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),r2=d3.round(r/2,2),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*.6,2),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*.6,2),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*.6,2),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*.6,2),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*.951,2),x2=d3.round(r*.588,2),y0=d3.round(-r,2),y1=d3.round(r*-.309,2),y2=d3.round(r*.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),y1=d3.round(r/2,2),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),x1=d3.round(r/2,2),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*.924,2),b=d3.round(r*.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,x1=d3.round(rs*.225,2),x2=d3.round(rs*.951,2),x3=d3.round(rs*.363,2),x4=d3.round(rs*.588,2),y0=d3.round(-rs,2),y1=d3.round(rs*-.309,2),y3=d3.round(rs*.118,2),y4=d3.round(rs*.809,2),y5=d3.round(rs*.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*.66,2),x1=d3.round(r*.38,2),x2=d3.round(r*.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)*.8,2),y1=d3.round(r*.8,2),y2=d3.round(r*1.6,2),rc=d3.round(r*4,2),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)*.8,2),y1=d3.round(r*.8,2),y2=d3.round(r*1.6,2),rc=d3.round(r*4,2),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),rc=d3.round(r*2,2),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),rc=d3.round(r*1.9,2),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*.7,2),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),y=d3.round(r*.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),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),r2=d3.round(r*.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*.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),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),y0=d3.round(r*1.6,2),y1=d3.round(r*.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),y0=d3.round(r*1.6,2),y1=d3.round(r*.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),x0=d3.round(r*1.6,2),x1=d3.round(r*.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),x0=d3.round(r*1.6,2),x1=d3.round(r*.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:147}],585:[function(require,module,exports){"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"}}}},{}],586:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var Registry=require("../../registry");var Axes=require("../../plots/cartesian/axes");var makeComputeError=require("./compute_error");module.exports=function calc(gd){var calcdata=gd.calcdata;for(var i=0;i0;traces.each(function(d){var trace=d[0].trace,xObj=trace.error_x||{},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);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+"m-"+yw+",0V"+coords.ys;if(!coords.noYS)path+="m-"+yw+",0h"+2*yw;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+"m0,-"+xw+"H"+coords.xs;if(!coords.noXS)path+="m0,-"+xw+"v"+2*xw;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()})})};function errorCoords(d,xa,ya){var out={x:xa.c2p(d.x),y:ya.c2p(d.y)};if(d.yh!==undefined){out.yh=ya.c2p(d.yh);out.ys=ya.c2p(d.ys);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":1037,"../drawing":583,d3:147,"fast-isnumeric":214}],591:[function(require,module,exports){"use strict";var d3=require("d3");var Color=require("../color");module.exports=function style(traces){traces.each(function(d){var trace=d[0].trace,yObj=trace.error_y||{},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":558,d3:147}],592:[function(require,module,exports){"use strict";var fontAttrs=require("../../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":758}],593:[function(require,module,exports){"use strict";var Lib=require("../../lib");var Registry=require("../../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=0&&pointData.indexxaArray[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)}}var distance=Infinity;for(curvenum=0;curvenumclosedataPreviousLength){hoverData.splice(0,closedataPreviousLength);distance=hoverData[0].distance}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){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;i1;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);if(evt.target&&evt.target.tagName){var hasClickToShow=Registry.getComponentMethod("annotations","hasClickToShow")(gd,newhoverdata);overrideCursor(d3.select(evt.target),hasClickToShow?"pointer":"")}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})}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||{};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;var showCommonLabel=t0!==undefined&&c0.distance<=opts.hoverdistance&&(hovermode==="x"||hovermode==="y");if(showCommonLabel){var i,traceHoverinfo;var allHaveZ=true;for(i=0;i-1&&name.length>nameLength){if(nameLength>3)name=name.substr(0,nameLength-3)+"...";else name=name.substr(0,nameLength)}}if(d.zLabel!==undefined){if(d.xLabel!==undefined)text+="x: "+d.xLabel+"
";if(d.yLabel!==undefined)text+="y: "+d.yLabel+"
";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?"
":"")+d.text}if(d.extraText!==undefined)text+=(text?"
":"")+d.extraText;if(text===""){if(name==="")g.remove();text=name}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"),tx2width=0;if(name&&name!==text){tx2.call(Drawing.font,d.fontFamily||fontFamily,d.fontSize||fontSize,traceColor).text(name).attr("data-notex",1).call(svgTextUtils.positionText,0,0).call(svgTextUtils.convertToTspans,gd);tx2width=tx2.node().getBoundingClientRect().width+2*HOVERTEXTPAD}else{tx2.remove();g.select("rect").remove()}g.select("path").style({fill:traceColor,stroke:contrastColor});var tbb=tx.node().getBoundingClientRect(),htx=d.xa._offset+(d.x0+d.x1)/2,hty=d.ya._offset+(d.y0+d.y1)/2,dx=Math.abs(d.x1-d.x0),dy=Math.abs(d.y1-d.y0),txTotalWidth=tbb.width+HOVERARROWSIZE+HOVERTEXTPAD+tx2width,anchorStartOK,anchorEndOK;d.ty0=outerTop-tbb.top;d.bx=tbb.width+2*HOVERTEXTPAD;d.by=tbb.height+2*HOVERTEXTPAD;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}function hoverAvoidOverlaps(hoverData,ax,fullLayout){var nummoves=0,pointgroups=hoverData.map(function(d,i){var axis=d[ax];return[{i:i,dp:0,pos:d.pos,posref:d.posref,size:d.by*(axis._id.charAt(0)==="x"?YFACTOR:1)/2,pmin:0,pmax:axis._id.charAt(0)==="x"?fullLayout.width:fullLayout.height}]}).sort(function(a,b){return a[0].posref-b[0].posref}),donepositioning,topOverlap,bottomOverlap,i,j,pti,sumdp;function constrainGroup(grp){var minPt=grp[0],maxPt=grp[grp.length-1];topOverlap=minPt.pmin-minPt.pos-minPt.dp+minPt.size;bottomOverlap=maxPt.pos+maxPt.dp+maxPt.size-minPt.pmax;if(topOverlap>.01){for(j=grp.length-1;j>=0;j--)grp[j].dp+=topOverlap;donepositioning=false}if(bottomOverlap<.01)return;if(topOverlap<-.01){for(j=grp.length-1;j>=0;j--)grp[j].dp-=bottomOverlap;donepositioning=false}if(!donepositioning)return;var deleteCount=0;for(i=0;iminPt.pmax)deleteCount++}for(i=grp.length-1;i>=0;i--){if(deleteCount<=0)break;pti=grp[i];if(pti.pos>minPt.pmax-1){pti.del=true;deleteCount--}}for(i=0;i=0;j--)grp[j].dp-=bottomOverlap}}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--}}}while(!donepositioning&&nummoves<=hoverData.length){nummoves++;donepositioning=true;i=0;while(i.01&&p0.pmin===p1.pmin&&p0.pmax===p1.pmax){for(j=g1.length-1;j>=0;j--)g1[j].dp+=topOverlap;g0.push.apply(g0,g1);pointgroups.splice(i+1,1);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++}pointgroups.forEach(constrainGroup)}for(i=pointgroups.length-1;i>=0;i--){var grp=pointgroups[i];for(j=grp.length-1;j>=0;j--){var pt=grp[j],hoverPt=hoverData[pt.i];hoverPt.offset=pt.dp;hoverPt.del=pt.del}}}function alignHoverText(hoverLabels,rotateLabels){hoverLabels.each(function(d){var g=d3.select(this);if(d.del){g.remove();return}var horzSign=d.anchor==="end"?-1:1,tx=g.select("text.nums"),alignShift={start:1,end:-1,middle:0}[d.anchor],txx=alignShift*(HOVERARROWSIZE+HOVERTEXTPAD),tx2x=txx+alignShift*(d.txwidth+HOVERTEXTPAD),offsetX=0,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"?"M-"+(d.bx/2+d.tx2width/2)+","+(offsetY-d.by/2)+"h"+d.bx+"v"+d.by+"h-"+d.bx+"Z":"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("color","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"?d.xa._offset+(d.x0+d.x1)/2:d.ya._offset+(d.y0+d.y1)/2;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);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)}if(d.zLabelVal!==undefined&&d.zLabel===undefined){d.zLabel=String(d.zLabelVal)}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;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!=="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 xa,ya;var showY=!!closestPoints.hLinePoint;var showX=!!closestPoints.vLinePoint;container.selectAll(".spikeline").remove();if(!(showX||showY))return;var contrastColor=Color.combine(fullLayout.plot_bgcolor,fullLayout.paper_bgcolor);if(showY){var hLinePoint=closestPoints.hLinePoint,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,yThickness=ya.spikethickness,yColor=ya.spikecolor||dfltHLineColor,yBB=ya._boundingBox,xEdge=(yBB.left+yBB.right)/2=0;i--){var oldPt=oldhoverdata[i],newPt=gd._hoverdata[i];if(oldPt.curveNumber!==newPt.curveNumber||String(oldPt.pointNumber)!==String(newPt.pointNumber)){return true}}return false}function spikesChanged(gd,oldspikepoints){if(!oldspikepoints)return true;if(oldspikepoints.vLinePoint!==gd._spikepoints.vLinePoint||oldspikepoints.hLinePoint!==gd._spikepoints.hLinePoint)return true;return false}},{"../../lib":684,"../../lib/events":672,"../../lib/override_cursor":695,"../../lib/svg_text_utils":708,"../../plots/cartesian/axes":732,"../../registry":817,"../color":558,"../dragelement":580,"../drawing":583,"./constants":595,"./helpers":597,d3:147,"fast-isnumeric":214,tinycolor2:499}],599:[function(require,module,exports){"use strict";var Lib=require("../../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":684}],600:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");var dragElement=require("../dragelement");var helpers=require("./helpers");var layoutAttributes=require("./layout_attributes");module.exports={moduleType:"component",name:"fx",constants:require("./constants"),schema:{layout:layoutAttributes},attributes:require("./attributes"),layoutAttributes:layoutAttributes,supplyLayoutGlobalDefaults:require("./layout_global_defaults"),supplyDefaults:require("./defaults"),supplyLayoutDefaults:require("./layout_defaults"),calc:require("./calc"),getDistanceFunction:helpers.getDistanceFunction,getClosest:helpers.getClosest,inbox:helpers.inbox,quadrature:helpers.quadrature,appendArrayPointValue:helpers.appendArrayPointValue,castHoverOption:castHoverOption,castHoverinfo:castHoverinfo,hover:require("./hover").hover,unhover:dragElement.unhover,loneHover:require("./hover").loneHover,loneUnhover:loneUnhover,click:require("./click")};function loneUnhover(containerOrSelection){var selection=Lib.isD3Selection(containerOrSelection)?containerOrSelection:d3.select(containerOrSelection);selection.selectAll("g.hovertext").remove();selection.selectAll(".spikeline").remove()}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":684,"../dragelement":580,"./attributes":592,"./calc":593,"./click":594,"./constants":595,"./defaults":596,"./helpers":597,"./hover":598,"./layout_attributes":601,"./layout_defaults":602,"./layout_global_defaults":603,d3:147}],601:[function(require,module,exports){"use strict";var constants=require("./constants");var fontAttrs=require("../../plots/font_attributes")({editType:"none"});fontAttrs.family.dflt=constants.HOVERFONT;fontAttrs.size.dflt=constants.HOVERFONTSIZE;module.exports={dragmode:{valType:"enumerated",values:["zoom","pan","select","lasso","orbit","turntable"],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":758,"./constants":595}],602:[function(require,module,exports){"use strict";var Lib=require("../../lib");var layoutAttributes=require("./layout_attributes");module.exports=function supplyLayoutDefaults(layoutIn,layoutOut,fullData){function coerce(attr,dflt){return Lib.coerce(layoutIn,layoutOut,layoutAttributes,attr,dflt)}var dragMode=coerce("dragmode");if(dragMode==="select")coerce("selectdirection");var hovermodeDflt;if(layoutOut._has("cartesian")){layoutOut._isHoriz=isHoriz(fullData);hovermodeDflt=layoutOut._isHoriz?"y":"x"}else hovermodeDflt="closest";var hoverMode=coerce("hovermode",hovermodeDflt);if(hoverMode){coerce("hoverdistance");coerce("spikedistance")}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;i1)){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?.2:.1;var dfltGapY=hasSubplotGrid?.3:.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)}}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=2/3};exports.isCenterAnchor=function isCenterAnchor(opts){return opts.xanchor==="center"||opts.xanchor==="auto"&&opts.x>1/3&&opts.x<2/3};exports.isBottomAnchor=function isBottomAnchor(opts){return opts.yanchor==="bottom"||opts.yanchor==="auto"&&opts.y<=1/3};exports.isMiddleAnchor=function isMiddleAnchor(opts){return opts.yanchor==="middle"||opts.yanchor==="auto"&&opts.y>1/3&&opts.y<2/3}},{}],611:[function(require,module,exports){"use strict";var fontAttrs=require("../../plots/font_attributes");var colorAttrs=require("../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"},editType:"legend"}},{"../../plots/font_attributes":758,"../color/attributes":557}],612:[function(require,module,exports){"use strict";module.exports={scrollBarWidth:6,scrollBarMinHeight:20,scrollBarColor:"#808BA4",scrollBarMargin:4}},{}],613:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Lib=require("../../lib");var Template=require("../../plot_api/plot_template");var attributes=require("./attributes");var basePlotLayoutAttributes=require("../../plots/layout_attributes");var helpers=require("./helpers");module.exports=function legendDefaults(layoutIn,layoutOut,fullData){var containerIn=layoutIn.legend||{};var visibleTraces=0;var defaultOrder="normal";var defaultX,defaultY,defaultXAnchor,defaultYAnchor;for(var i=0;i1);if(showLegend===false)return;var containerOut=Template.newContainer(layoutOut,"legend");function coerce(attr,dflt){return Lib.coerce(containerIn,containerOut,attributes,attr,dflt)}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(xaxis&&xaxis.rangeslider&&xaxis.rangeslider.visible){defaultX=0;defaultXAnchor="left";defaultY=1.1;defaultYAnchor="bottom"}else{defaultX=0;defaultXAnchor="left";defaultY=-.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);Lib.noneOrAll(containerIn,containerOut,["x","y"])}},{"../../lib":684,"../../plot_api/plot_template":722,"../../plots/layout_attributes":786,"../../registry":817,"./attributes":611,"./helpers":617}],614:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");var Plots=require("../../plots/plots");var Registry=require("../../registry");var Events=require("../../lib/events");var dragElement=require("../dragelement");var Drawing=require("../drawing");var Color=require("../color");var svgTextUtils=require("../../lib/svg_text_utils");var handleClick=require("./handle_click");var constants=require("./constants");var interactConstants=require("../../constants/interactions");var alignmentConstants=require("../../constants/alignment");var LINE_SPACING=alignmentConstants.LINE_SPACING;var FROM_TL=alignmentConstants.FROM_TL;var FROM_BR=alignmentConstants.FROM_BR;var getLegendData=require("./get_legend_data");var style=require("./style");var helpers=require("./helpers");var anchorUtils=require("./anchor_utils");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;ilyMax){expandHorizontalMargin(gd)}else{expandMargin(gd)}var gs=fullLayout._size,lx=gs.l+gs.w*opts.x,ly=gs.t+gs.h*(1-opts.y);if(anchorUtils.isRightAnchor(opts)){lx-=opts._width}else if(anchorUtils.isCenterAnchor(opts)){lx-=opts._width/2}if(anchorUtils.isBottomAnchor(opts)){ly-=opts._height}else if(anchorUtils.isMiddleAnchor(opts)){ly-=opts._height/2}var legendWidth=opts._width,legendWidthMax=gs.w;if(legendWidth>legendWidthMax){lx=gs.l;legendWidth=legendWidthMax}else{if(lx+legendWidth>lxMax)lx=lxMax-legendWidth;if(lxlegendHeightMax){ly=gs.t;legendHeight=legendHeightMax}else{if(ly+legendHeight>lyMax)ly=lyMax-legendHeight;if(ly=bbox.left&&e.clientX<=bbox.right&&e.clientY>=bbox.top&&e.clientY<=bbox.bottom});if(clickedTrace.size()>0){clickOrDoubleClick(gd,legend,clickedTrace,numClicks,e)}}})}};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);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("restyle",gd,update,traceIndex)})}else{textLayout(textEl)}}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,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._legendMouseDownTimeDBLCLICKDELAY){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;var textY=lineHeight*(.3+(1-textLines)/2);svgTextUtils.positionText(text,40,textY)}height=Math.max(height,16)+3;legendItem.height=height;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],textHeight=legendItem.height,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],groupData=groups.data();for(var i=0,n=groupData.length;iborderwidth+fullTracesWidth-traceGap;traces.each(function(d){var legendItem=d[0],traceWidth=oneRowLegend?40+d[0].width:maxTraceWidth;if(borderwidth+offsetX+traceGap+traceWidth>fullLayout.width-(fullLayout.margin.r+fullLayout.margin.l)){offsetX=0;rowHeight=rowHeight+maxTraceHeight;opts._height=opts._height+maxTraceHeight;maxTraceHeight=0}Drawing.setTranslate(this,borderwidth+offsetX,5+borderwidth+legendItem.height/2+rowHeight);opts._width+=traceGap+traceWidth;opts._height=Math.max(opts._height,legendItem.height);offsetX+=traceGap+traceWidth;maxTraceHeight=Math.max(legendItem.height,maxTraceHeight)});opts._width+=borderwidth*2;opts._height+=10+borderwidth*2}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,opts=fullLayout.legend;var xanchor="left";if(anchorUtils.isRightAnchor(opts)){xanchor="right"}else if(anchorUtils.isCenterAnchor(opts)){xanchor="center"}var yanchor="top";if(anchorUtils.isBottomAnchor(opts)){yanchor="bottom"}else if(anchorUtils.isMiddleAnchor(opts)){yanchor="middle"}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,opts=fullLayout.legend;var xanchor="left";if(anchorUtils.isRightAnchor(opts)){xanchor="right"}else if(anchorUtils.isCenterAnchor(opts)){xanchor="center"}Plots.autoMargin(gd,"legend",{x:opts.x,y:.5,l:opts._width*FROM_TL[xanchor],r:opts._width*FROM_BR[xanchor],b:0,t:0})}},{"../../constants/alignment":656,"../../constants/interactions":660,"../../lib":684,"../../lib/events":672,"../../lib/svg_text_utils":708,"../../plots/plots":795,"../../registry":817,"../color":558,"../dragelement":580,"../drawing":583,"./anchor_utils":610,"./constants":612,"./get_legend_data":615,"./handle_click":616,"./helpers":617,"./style":619,d3:147}],615:[function(require,module,exports){"use strict";var Registry=require("../../registry");var helpers=require("./helpers");module.exports=function getLegendData(calcdata,opts){var lgroupToTraces={},lgroups=[],hasOneNonBlankGroup=false,slicesShown={},lgroupi=0;var i,j;function addOneItem(legendGroup,legendItem){if(legendGroup===""||!helpers.isGrouped(opts)){var uniqueGroup="~~i"+lgroupi;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])}for(i=0;ibounds[1])return bounds[1]}return valToBound}function pickFirst(array){return array[0]}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,[.2,1]);dEdit.ms=boundVal("marker.size",Lib.mean,[2,16]);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"}}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);tMod.selectedpoints=null}var ptgroup=d3.select(this).select("g.legendpoints");var pts=ptgroup.selectAll("path.scatterpts").data(showMarkers?dMod:[]);pts.enter().append("path").classed("scatterpts",true).attr("transform","translate(20,0)");pts.exit().remove();pts.call(Drawing.pointStyle,tMod,gd);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,marker=trace.marker||{},markerLine=marker.line||{},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),d0=d[0],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,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).attr("d","M6,6H-6V-6H6Z").attr("transform","translate(20,0)");pts.exit().remove();pts.each(function(){var w=trace.line.width,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,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";return"M15,0H8M8,-6V6H-8Z"}).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,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,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";return"M15,0H0M8,6V0"}).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,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,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":684,"../../registry":817,"../../traces/pie/style_one":1001,"../../traces/scatter/subtypes":1037,"../color":558,"../drawing":583,d3:147}],620:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Plots=require("../../plots/plots");var axisIds=require("../../plots/cartesian/axis_ids");var Lib=require("../../lib");var Icons=require("../../../build/ploticon");var _=Lib._;var modeBarButtons=module.exports={};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"):_(gd,"Download plot")},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"?.5:2,r0=(1+mag)/2,r1=(1-mag)/2;var axName;for(i=0;i1){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{hoverGroup=["toggleHover"]}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;i0);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;i0?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.r2c:ax.d2c;if(v0!==undefined)return[convertVal(v0),convertVal(v1)];if(!path)return;var min=Infinity,max=-Infinity,segments=path.match(constants.segmentRE),i,segment,drawnParam,params,val;if(ax.type==="date")convertVal=helpers.decodeDate(convertVal);for(i=0;imax)max=val}if(max>=min)return[min,max]}},{"../../lib":684,"../../plots/cartesian/axes":732,"./constants":639,"./helpers":642}],639:[function(require,module,exports){"use strict";module.exports={segmentRE:/[MLHVQCTSZ][^MLHVQCTSZ]*/g,paramRE:/[^\s,]+/g,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},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},Z:{}},numParams:{M:2,L:2,H:1,V:1,Q:4,C:6,T:2,S:4,Z:0}}},{}],640:[function(require,module,exports){"use strict";var Lib=require("../../lib");var Axes=require("../../plots/cartesian/axes");var handleArrayContainerDefaults=require("../../plots/array_container_defaults");var attributes=require("./attributes");var helpers=require("./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",shapeType=coerce("type",dfltType),xSizeMode=coerce("xsizemode"),ySizeMode=coerce("ysizemode");var axLetters=["x","y"];for(var i=0;i<2;i++){var axLetter=axLetters[i],attrAnchor=axLetter+"anchor",sizeMode=axLetter==="x"?xSizeMode:ySizeMode,gdMock={_fullLayout:fullLayout},ax,pos2r,r2pos;var axRef=Axes.coerceRef(shapeIn,shapeOut,gdMock,axLetter,"","paper");if(axRef!=="paper"){ax=Axes.getFromId(gdMock,axRef);r2pos=helpers.rangeToShapePosition(ax);pos2r=helpers.shapePositionToRange(ax)}else{pos2r=r2pos=Lib.identity}if(shapeType!=="path"){var dflt0=.25,dflt1=.75;var attr0=axLetter+"0",attr1=axLetter+"1",in0=shapeIn[attr0],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)}shapeOut[attr0]=r2pos(shapeOut[attr0]);shapeOut[attr1]=r2pos(shapeOut[attr1]);shapeIn[attr0]=in0;shapeIn[attr1]=in1}if(sizeMode==="pixel"){var inAnchor=shapeIn[attrAnchor];shapeIn[attrAnchor]=pos2r(shapeIn[attrAnchor],true);Axes.coercePosition(shapeOut,gdMock,coerce,axRef,attrAnchor,.25);shapeOut[attrAnchor]=r2pos(shapeOut[attrAnchor]);shapeIn[attrAnchor]=inAnchor}}if(shapeType==="path"){coerce("path")}else{Lib.noneOrAll(shapeIn,shapeOut,["x0","x1","y0","y1"])}}},{"../../lib":684,"../../plots/array_container_defaults":728,"../../plots/cartesian/axes":732,"./attributes":637,"./helpers":642}],641:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Lib=require("../../lib");var Axes=require("../../plots/cartesian/axes");var Color=require("../color");var Drawing=require("../drawing");var arrayEditor=require("../../plot_api/plot_template").arrayEditor;var dragElement=require("../dragelement");var setCursor=require("../../lib/setcursor");var constants=require("./constants");var helpers=require("./helpers");module.exports={draw:draw,drawOne:drawOne};function draw(gd){var fullLayout=gd._fullLayout;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;iminSensoryWidth?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{var dragBBox=dragOptions.element.getBoundingClientRect();var w=dragBBox.right-dragBBox.left,h=dragBBox.bottom-dragBBox.top,x=evt.clientX-dragBBox.left,y=evt.clientY-dragBBox.top,cursor=!isPath&&w>MINWIDTH&&h>MINHEIGHT&&!evt.shiftKey?dragElement.getCursor(x/w,1-y/h):"move";setCursor(shapePath,cursor);dragMode=cursor.split("-")[0]}}function startDrag(evt){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(x0y1){n0=y0;optN="y0";s0=y1;optS="y1"}else{n0=y1;optN="y1";s0=y0;optS="y0"}updateDragMode(evt);renderVisualCues(shapeLayer,shapeOptions);deactivateClipPathTemporarily(shapePath,shapeOptions,gd);dragOptions.moveFn=dragMode==="move"?moveShape:resizeShape}function endDrag(){setCursor(shapePath);removeVisualCues(shapeLayer);setClipPath(shapePath,gd,shapeOptions);Registry.call("relayout",gd,editHelpers.getUpdateObj())}function abortDrag(){removeVisualCues(shapeLayer)}function moveShape(dx,dy){if(shapeOptions.type==="path"){var noOp=function(coord){return coord},moveX=noOp,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){var noOp=function(coord){return coord},moveX=noOp,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,newS=~dragMode.indexOf("s")?s0+dy:s0,newW=~dragMode.indexOf("w")?w0+dx:w0,newE=~dragMode.indexOf("e")?e0+dx:e0;if(~dragMode.indexOf("n")&&yPixelSized)newN=n0-dy;if(~dragMode.indexOf("s")&&yPixelSized)newS=s0-dy;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";var visualCues=shapeLayer.selectAll(".visual-cue").data([0]);var strokeWidth=1;visualCues.enter().append("path").attr({fill:"#fff","fill-rule":"evenodd",stroke:"#000","stroke-width":strokeWidth}).classed("visual-cue",true);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,yref=shapeOptions.yref,xa=Axes.getFromId(gd,xref),ya=Axes.getFromId(gd,yref);var clipAxes="";if(xref!=="paper"&&!xa.autorange)clipAxes+=xref;if(yref!=="paper"&&!ya.autorange)clipAxes+=yref;shapePath.call(Drawing.setClipUrl,clipAxes?"clip"+gd._fullLayout._uid+clipAxes:null)}}function getPathString(gd,options){var type=options.type,xa=Axes.getFromId(gd,options.xref),ya=Axes.getFromId(gd,options.yref),gs=gd._fullLayout._size,x2r,x2p,y2r,y2p,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";var cx=(x0+x1)/2,cy=(y0+y1)/2,rx=Math.abs(cx-x0),ry=Math.abs(cy-y0),rArc="A"+rx+","+ry,rightPt=cx+rx+","+cy,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,xSizemode=options.xsizemode,ySizemode=options.ysizemode,xAnchor=options.xanchor,yAnchor=options.yanchor;return pathIn.replace(constants.segmentRE,function(segment){var paramNumber=0,segmentType=segment.charAt(0),xParams=constants.paramIsX[segmentType],yParams=constants.paramIsY[segmentType],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,segmentType=segment.charAt(0),xParams=constants.paramIsX[segmentType],yParams=constants.paramIsY[segmentType],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":684,"../../lib/setcursor":704,"../../plot_api/plot_template":722,"../../plots/cartesian/axes":732,"../../registry":817,"../color":558,"../dragelement":580,"../drawing":583,"./constants":639,"./helpers":642}],642:[function(require,module,exports){"use strict";var constants=require("./constants");var Lib=require("../../lib");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.length0?[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}Plots.autoMargin(gd,autoMarginId(sliderOpts))}sliders.exit().each(function(){d3.select(this).selectAll("g."+constants.groupClassName).each(clearSlider)}).remove();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();for(var i=0;i0){el=el.transition().duration(sliderOpts.transition.duration).ease(sliderOpts.transition.easing)}el.attr("transform","translate("+(x-constants.gripWidth*.5)+","+sliderOpts._dims.currentValueTotalHeight+")")}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))}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)*.5+dims.currentValueTotalHeight)}},{"../../constants/alignment":656,"../../lib":684,"../../lib/svg_text_utils":708,"../../plot_api/plot_template":722,"../../plots/plots":795,"../color":558,"../drawing":583,"../legend/anchor_utils":610,"./constants":645,d3:147}],648:[function(require,module,exports){"use strict";var constants=require("./constants");module.exports={moduleType:"component",name:constants.name,layoutAttributes:require("./attributes"),supplyLayoutDefaults:require("./defaults"),draw:require("./draw")}},{"./attributes":644,"./constants":645,"./defaults":646,"./draw":647}],649:[function(require,module,exports){"use strict";var d3=require("d3");var isNumeric=require("fast-isnumeric");var Plots=require("../../plots/plots");var Registry=require("../../registry");var Lib=require("../../lib");var Drawing=require("../drawing");var Color=require("../color");var svgTextUtils=require("../../lib/svg_text_utils");var interactConstants=require("../../constants/interactions");module.exports={draw:draw};var numStripRE=/ [XY][0-9]* /;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 titlefont=cont.titlefont||{};var font=titlefont.family;var fontSize=titlefont.size;var fontColor=titlefont.color;var opacity=1;var isplaceholder=false;var txt=(cont.title||"").trim();var editAttr;if(prop==="title")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;else if(txt.replace(numStripRE," % ")===placeholder.replace(numStripRE," % ")){opacity=.2;isplaceholder=true;if(!editable)txt=""}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).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":font,"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);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);if(maxshift<0)shift=maxshift;else{var offsetLeft=avoid.offsetLeft||0;var offsetTop=avoid.offsetTop||0;titlebb.left-=offsetLeft;titlebb.right-=offsetLeft;titlebb.top-=offsetTop;titlebb.bottom-=offsetTop;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("restyle",gd,prop,text,traceIndex)}else{Registry.call("relayout",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":660,"../../lib":684,"../../lib/svg_text_utils":708,"../../plots/plots":795,"../../registry":817,"../color":558,"../drawing":583,d3:147,"fast-isnumeric":214}],650:[function(require,module,exports){"use strict";var fontAttrs=require("../../plots/font_attributes");var colorAttrs=require("../color/attributes");var extendFlat=require("../../lib/extend").extendFlat;var overrideAll=require("../../plot_api/edit_types").overrideAll;var padAttrs=require("../../plots/pad_attributes");var templatedArray=require("../../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:-.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,{}),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":673,"../../plot_api/edit_types":715,"../../plot_api/plot_template":722,"../../plots/font_attributes":758,"../../plots/pad_attributes":794,"../color/attributes":557}],651:[function(require,module,exports){"use strict";module.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:"◄",right:"►",up:"▲",down:"▼"}}},{}],652:[function(require,module,exports){"use strict";var Lib=require("../../lib");var handleArrayContainerDefaults=require("../../plots/array_container_defaults");var attributes=require("./attributes");var constants=require("./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":684,"../../plots/array_container_defaults":728,"./attributes":650,"./constants":651}],653:[function(require,module,exports){"use strict";var d3=require("d3");var Plots=require("../../plots/plots");var Color=require("../color");var Drawing=require("../drawing");var Lib=require("../../lib");var svgTextUtils=require("../../lib/svg_text_utils");var anchorUtils=require("../legend/anchor_utils");var arrayEditor=require("../../plot_api/plot_template").arrayEditor;var LINE_SPACING=require("../../constants/alignment").LINE_SPACING;var constants=require("./constants");var ScrollBox=require("./scrollbox");module.exports=function draw(gd){var fullLayout=gd._fullLayout,menuData=Lib.filterVisible(fullLayout[constants.name]);function clearAutoMargin(menuOpts){Plots.autoMargin(gd,autoMarginId(menuOpts))}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(){d3.select(this).selectAll("g."+constants.headerGroupClassName).each(clearAutoMargin)}).remove();if(menuData.length===0)return;var headerGroups=menus.selectAll("g."+constants.headerGroupClassName).data(menuData,keyFunction);headerGroups.enter().append("g").classed(constants.headerGroupClassName,true);var gButton=Lib.ensureSingle(menus,"g",constants.dropdownButtonGroupClassName,function(s){s.style("pointer-events","all")});for(var i=0;iboxW,hbarW=ScrollBox.barLength+2*ScrollBox.barPad,hbarH=ScrollBox.barWidth+2*ScrollBox.barPad,hbarL=l,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});this._hbarXMin=hbarL+hbarW/2;this._hbarTranslateMax=boxW-hbarW}else{delete this.hbar;delete this._hbarXMin;delete this._hbarTranslateMax}var needsVerticalScrollBar=h>boxH,vbarW=ScrollBox.barWidth+2*ScrollBox.barPad,vbarH=ScrollBox.barLength+2*ScrollBox.barPad,vbarL=l+w,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});this._vbarYMin=vbarT+vbarH/2;this._vbarTranslateMax=boxH-vbarH}else{delete this.vbar;delete this._vbarYMin;delete this._vbarTranslateMax}var clipId=this.id,clipL=boxL-.5,clipR=needsVerticalScrollBar?boxR+vbarW+.5:boxR+.5,clipT=boxT-.5,clipB=needsHorizontalScrollBar?boxB+hbarH+.5:boxB+.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.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}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)}}this.setTranslate(translateX,translateY)};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}};ScrollBox.prototype._onBoxDrag=function onBarDrag(){var translateX=this.translateX,translateY=this.translateY;if(this.hbar){translateX-=d3.event.dx}if(this.vbar){translateY-=d3.event.dy}this.setTranslate(translateX,translateY)};ScrollBox.prototype._onBoxWheel=function onBarWheel(){var translateX=this.translateX,translateY=this.translateY;if(this.hbar){translateX+=d3.event.deltaY}if(this.vbar){translateY+=d3.event.deltaY}this.setTranslate(translateX,translateY)};ScrollBox.prototype._onBarDrag=function onBarDrag(){var translateX=this.translateX,translateY=this.translateY;if(this.hbar){var xMin=translateX+this._hbarXMin,xMax=xMin+this._hbarTranslateMax,x=Lib.constrain(d3.event.x,xMin,xMax),xf=(x-xMin)/(xMax-xMin);var translateXMax=this.position.w-this._box.w;translateX=xf*translateXMax}if(this.vbar){var yMin=translateY+this._vbarYMin,yMax=yMin+this._vbarTranslateMax,y=Lib.constrain(d3.event.y,yMin,yMax),yf=(y-yMin)/(yMax-yMin);var translateYMax=this.position.h-this._box.h;translateY=yf*translateYMax}this.setTranslate(translateX,translateY)};ScrollBox.prototype.setTranslate=function setTranslate(translateX,translateY){var translateXMax=this.position.w-this._box.w,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-.5),y:Math.floor(this.position.t+translateY-.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":684,"../color":558,"../drawing":583,d3:147}],656:[function(require,module,exports){"use strict";module.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,MID_SHIFT:.35,OPPOSITE_SIDE:{left:"right",right:"left",top:"bottom",bottom:"top"}}},{}],657:[function(require,module,exports){"use strict";module.exports={COMPARISON_OPS:["=","!=","<",">=",">","<="],COMPARISON_OPS2:["=","<",">=",">","<="],INTERVAL_OPS:["[]","()","[)","(]","][",")(","](",")["],SET_OPS:["{}","}{"],CONSTRAINT_REDUCTION:{"=":"=","<":"<","<=":"<",">":">",">=":">","[]":"[]","()":"[]","[)":"[]","(]":"[]","][":"][",")(":"][","](":"][",")[":"]["}}},{}],658:[function(require,module,exports){"use strict";module.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]}},{}],659:[function(require,module,exports){"use strict";module.exports={circle:"●","circle-open":"○",square:"■","square-open":"□",diamond:"◆","diamond-open":"◇",cross:"+",x:"❌"}},{}],660:[function(require,module,exports){"use strict";module.exports={SHOW_PLACEHOLDER:100,HIDE_PLACEHOLDER:1e3,DBLCLICKDELAY:300,DESELECTDIM:.2}},{}],661:[function(require,module,exports){"use strict";module.exports={BADNUM:undefined,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,MINUS_SIGN:"−"}},{}],662:[function(require,module,exports){"use strict";module.exports={entityToUnicode:{mu:"μ","#956":"μ",amp:"&","#28":"&",lt:"<","#60":"<",gt:">","#62":">",nbsp:" ","#160":" ",times:"×","#215":"×",plusmn:"±","#177":"±",deg:"°","#176":"°"}}},{}],663:[function(require,module,exports){"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";exports.svgAttrs={xmlns:exports.svg,"xmlns:xlink":exports.xlink}},{}],664:[function(require,module,exports){"use strict";exports.version="1.39.4";require("es6-promise").polyfill();require("../build/plotcss");require("./fonts/mathjax_config");var Registry=require("./registry");var register=exports.register=Registry.register;var plotApi=require("./plot_api");var methodNames=Object.keys(plotApi);for(var i=0;i180)deg-=Math.round(deg/360)*360;return deg}},{}],667:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var BADNUM=require("../constants/numerical").BADNUM;var JUNK=/^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;module.exports=function cleanNumber(v){if(typeof v==="string"){v=v.replace(JUNK,"")}if(isNumeric(v))return Number(v);return BADNUM}},{"../constants/numerical":661,"fast-isnumeric":214}],668:[function(require,module,exports){"use strict";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})})}}},{}],669:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var tinycolor=require("tinycolor2");var baseTraceAttrs=require("../plots/attributes");var getColorscale=require("../components/colorscale/get_scale");var colorscaleNames=Object.keys(require("../components/colorscale/scales"));var nestedProperty=require("./nested_property");var counterRegex=require("./regex").counter;var DESELECTDIM=require("../constants/interactions").DESELECTDIM;var wrap180=require("./angles").wrap180;var isArrayOrTypedArray=require("./is_array").isArrayOrTypedArray;exports.valObjectMeta={data_array:{coerceFunction:function(v,propOut,dflt){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;iopts.max){propOut.set(dflt)}else propOut.set(+v)}},integer:{coerceFunction:function(v,propOut,dflt,opts){if(v%1||!isNumeric(v)||opts.min!==undefined&&vopts.max){propOut.set(dflt)}else propOut.set(+v)}},string:{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(getColorscale(v,dflt))}},angle:{coerceFunction:function(v,propOut,dflt){if(v==="auto")propOut.set("auto");else if(!isNumeric(v))propOut.set(dflt);else propOut.set(wrap180(+v))}},subplotid:{coerceFunction:function(v,propOut,dflt,opts){var regex=opts.regex||counterRegex(dflt);if(typeof v==="string"&®ex.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("+"),i=0;while(i=MIN_MS&&s<=MAX_MS)return s;return BADNUM}if(typeof s!=="string"&&typeof s!=="number")return BADNUM;s=String(s);var isWorld=isWorldCalendar(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],m=match[3]||"1",d=Number(match[5]||1),H=Number(match[7]||0),M=Number(match[9]||0),S=Number(match[11]||0);if(isWorld){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}if(!cDate)return BADNUM;return(cDate.toJD()-EPOCHJD)*ONEDAY+H*ONEHOUR+M*ONEMIN+S*ONESEC}if(y.length===2){y=(Number(y)+2e3-YFIRST)%100+YFIRST}else y=Number(y);m-=1;var date=new Date(Date.UTC(2e3,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");exports.isDateTime=function(s,calendar){return exports.dateTime2ms(s,calendar)!==BADNUM};function lpad(val,digits){return String(val+Math.pow(10,digits)).substr(1)}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+.05,1)*10),msRounded=Math.round(ms-msecTenths/10),dateStr,h,m,s,msec10,d;if(isWorldCalendar(calendar)){var dateJD=Math.floor(msRounded/ONEDAY)+EPOCHJD,timeMs=Math.floor(mod(ms,ONEDAY));try{dateStr=Registry.getComponentMethod("calendars","getCal")(calendar).fromJD(dateJD).formatDate("yyyy-mm-dd")}catch(e){dateStr=utcFormat("G%Y-%m-%d")(new Date(msRounded))}if(dateStr.charAt(0)==="-"){while(dateStr.length<11)dateStr="-0"+dateStr.substr(1)}else{while(dateStr.length<10)dateStr="0"+dateStr}h=r=MIN_MS+ONEDAY&&ms<=MAX_MS-ONEDAY))return BADNUM;var msecTenths=Math.floor(mod(ms+.05,1)*10),d=new Date(Math.round(ms-msecTenths/10)),dateStr=d3.time.format("%Y-%m-%d")(d),h=d.getHours(),m=d.getMinutes(),s=d.getSeconds(),msec10=d.getUTCMilliseconds()*10+msecTenths;return includeTime(dateStr,h,m,s,msec10)};function includeTime(dateStr,h,m,s,msec10){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}exports.cleanDate=function(v,dflt,calendar){if(exports.isJSDate(v)||typeof v==="number"){if(isWorldCalendar(calendar)){Loggers.error("JS Dates and milliseconds are incompatible with world calendars",v);return dflt}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};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),fracSecs=(x/1e3%1+2).toFixed(digits).substr(2).replace(/0+$/,"")||"0";return fracSecs});var d=new Date(Math.floor(x+.05));if(isWorldCalendar(calendar)){try{fmt=Registry.getComponentMethod("calendars","worldCalFmt")(fmt,x,calendar)}catch(e){return"Invalid"}}return formatter(fmt)(d)}var MAXSECONDS=[59,59.9,59.99,59.999,59.9999];function formatTime(x,tr){var timePart=mod(x+.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;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}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)};var THREEDAYS=3*ONEDAY;exports.incrementMonth=function(ms,dMonth,calendar){calendar=isWorldCalendar(calendar)&&calendar;var timeMs=mod(ms,ONEDAY);ms=Math.round(ms-timeMs);if(calendar){try{var dateJD=Math.round(ms/ONEDAY)+EPOCHJD,calInstance=Registry.getComponentMethod("calendars","getCal")(calendar),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)}}var y=new Date(ms+THREEDAYS);return y.setUTCMonth(y.getUTCMonth()+dMonth)+timeMs-THREEDAYS};exports.findExactDates=function(data,calendar){var exactYears=0,exactMonths=0,exactDays=0,blankCount=0,d,di;var calInstance=isWorldCalendar(calendar)&&Registry.getComponentMethod("calendars","getCal")(calendar);for(var i=0;i0){coords.push(lineString);lineString=[]}}if(lineString.length>0){coords.push(lineString)}return coords};exports.makeLine=function(coords){if(coords.length===1){return{type:"LineString",coordinates:coords[0]}}else{return{type:"MultiLineString",coordinates:coords}}};exports.makePolygon=function(coords){if(coords.length===1){return{type:"Polygon",coordinates:coords}}else{var _coords=new Array(coords.length);for(var i=0;i1||t<0||t>1)return null;return{x:x1+a*t,y:y1+d*t}}exports.segmentDistance=function segmentDistance(x1,y1,x2,y2,x3,y3,x4,y4){if(segmentsIntersect(x1,y1,x2,y2,x3,y3,x4,y4))return 0;var x12=x2-x1;var y12=y2-y1;var x34=x4-x3;var y34=y4-y3;var l2_12=x12*x12+y12*y12;var l2_34=x34*x34+y34*y34;var dist2=Math.min(perpDistance2(x12,y12,l2_12,x3-x1,y3-y1),perpDistance2(x12,y12,l2_12,x4-x1,y4-y1),perpDistance2(x34,y34,l2_34,x1-x3,y1-y3),perpDistance2(x34,y34,l2_34,x2-x3,y2-y3));return Math.sqrt(dist2)};function perpDistance2(xab,yab,l2_ab,xac,yac){var fc_ab=xac*xab+yac*yab;if(fc_ab<0){return xac*xac+yac*yac}else if(fc_ab>l2_ab){var xbc=xac-xab;var ybc=yac-yab;return xbc*xbc+ybc*ybc}else{var crossProduct=xac*yab-yac*xab;return crossProduct*crossProduct/l2_ab}}var locationCache,workingPath,workingTextWidth;exports.getTextLocation=function getTextLocation(path,totalPathLen,positionOnPath,textWidth){if(path!==workingPath||textWidth!==workingTextWidth){locationCache={};workingPath=path;workingTextWidth=textWidth}if(locationCache[positionOnPath]){return locationCache[positionOnPath]}var p0=path.getPointAtLength(mod(positionOnPath-textWidth/2,totalPathLen));var p1=path.getPointAtLength(mod(positionOnPath+textWidth/2,totalPathLen));var theta=Math.atan((p1.y-p0.y)/(p1.x-p0.x));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};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);if(len===0)pt0=pt;else if(len===pTotal)ptTotal=pt;var dx=pt.xright?pt.x-right:0;var dy=pt.ybottom?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)<.1&&Math.abs(pt0.y-ptTotal.y)<.1}};exports.findPointOnPath=function findPointOnPath(path,val,coord,opts){opts=opts||{};var pathLength=opts.pathLength||path.getTotalLength();var tolerance=opts.tolerance||.001;var iterationLimit=opts.iterationLimit||30;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(i0){b1=mid}else{b0=mid}i++}}return pt}},{"./mod":691}],679:[function(require,module,exports){"use strict";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}},{}],680:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var tinycolor=require("tinycolor2");var rgba=require("color-normalize");var Colorscale=require("../components/colorscale");var colorDflt=require("../components/color/attributes").defaultLine;var isArrayOrTypedArray=require("./is_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.colorscale,containerIn.cmin,containerIn.cmax))}else{sclFunc=validateColor}if(isArrayColorIn){getColor=function(c,i){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",idx))>=0){var nidx=x.indexOf("",idx);if(nidx/g,"\n")}function stripTags(x){return x.replace(/\<.*\>/g,"")}function fixEntities(x){var entityToUnicode=stringMappings.entityToUnicode;var idx=0;while((idx=x.indexOf("&",idx))>=0){var nidx=x.indexOf(";",idx);if(nidxFP_SAFE)return BADNUM;return isNumeric(v)?Number(v):BADNUM};lib.isIndex=function(v,len){if(len!==undefined&&v>=len)return false;return isNumeric(v)&&v>=0&&v%1===0};lib.noop=require("./noop");lib.identity=require("./identity");lib.swapAttrs=function(cont,attrList,part1,part2){if(!part1)part1="x";if(!part2)part2="y";for(var i=0;iv1)return Math.max(v1,Math.min(v0,v));return Math.max(v0,Math.min(v1,v))};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};lib.simpleMap=function(array,func,x1,x2){var len=array.length,out=new Array(len);for(var i=0;i=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){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=function(arrayIn,FWHM){FWHM=Math.round(FWHM)||0;if(FWHM<2)return arrayIn;var alen=arrayIn.length,alen2=2*alen,wlen=2*FWHM-1,w=new Array(wlen),arrayOut=new Array(alen),i,j,k,v;for(i=0;i=alen2)k-=alen2*Math.floor(k/alen2);if(k<0)k=-1-k;else if(k>=alen)k=alen2-1-k;v+=arrayIn[k]*w[j]}arrayOut[i]=v}return arrayOut};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)};lib.stripTrailingSlash=function(str){if(str.substr(-1)==="/")return str.substr(0,str.length-1);return str};lib.noneOrAll=function(containerIn,containerOut,attrList){if(!containerIn)return;var hasAny=false,hasAll=true,i,val;for(i=0;i1?decimalSep+x[1]:"";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*$/;lib.templateString=function(string,obj){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 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=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};var randSeed=2e9;lib.seedPseudoRandom=function(){randSeed=2e9};lib.pseudoRandom=function(){var lastVal=randSeed;randSeed=(69069*randSeed+1)%4294967296;if(Math.abs(randSeed-lastVal)<429496729)return lib.pseudoRandom();return randSeed/4294967296}},{"../constants/numerical":661,"./angles":666,"./clean_number":667,"./coerce":669,"./dates":670,"./ensure_array":671,"./extend":673,"./filter_unique":674,"./filter_visible":675,"./geometry2d":678,"./get_graph_div":679,"./identity":683,"./is_array":685,"./is_plain_object":686,"./keyed_container":687,"./localize":688,"./loggers":689,"./matrix":690,"./mod":691,"./nested_property":692,"./noop":693,"./notifier":694,"./push_unique":698,"./regex":700,"./relative_attr":701,"./relink_private":702,"./search":703,"./stats":706,"./throttle":709,"./to_log_range":710,d3:147,"fast-isnumeric":214}],685:[function(require,module,exports){"use strict";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)}function isArrayOrTypedArray(a){return Array.isArray(a)||isTypedArray(a)}function isArray1D(a){return!isArrayOrTypedArray(a[0])}module.exports={isTypedArray:isTypedArray,isArrayOrTypedArray:isArrayOrTypedArray,isArray1D:isArray1D}},{}],686:[function(require,module,exports){"use strict";module.exports=function isPlainObject(obj){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}},{}],687:[function(require,module,exports){"use strict";var nestedProperty=require("./nested_property");var SIMPLE_PROPERTY_REGEX=/^\w*$/;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||"";var indexLookup={};if(arr){for(i=0;i2){changeTypes[idx]=changeTypes[idx]|VALUE;return obj.set(name,null)}if(isSimpleValueProp){for(i=idx;i1){var messages=["LOG:"];for(var i=0;i0){var messages=["WARN:"];for(var i=0;i0){var messages=["ERROR:"];for(var i=0;i/g);for(var i=0;ixmax||y===BADNUM||yymax){return false}if(omitFirstEdge&&rectFirstEdgeTest(pt))return false;return true}function contains(pt,omitFirstEdge){var x=pt[0],y=pt[1];if(x===BADNUM||xxmax||y===BADNUM||yymax){return false}var imax=pts.length,x1=pts[0][0],y1=pts[0][1],crossings=0,i,x0,y0,xmini,ycross;for(i=1;iMath.max(x0,x1)||y>Math.max(y0,y1)){continue}else if(ysegmentSquared||Math.abs(dot(part,unitPerp))>tolerance)return true}return false};polygon.filter=function filter(pts,tolerance){var ptsFiltered=[pts[0]],doneRawIndex=0,doneFilteredIndex=0;function addPt(pt){pts.push(pt);var prevFilterLen=ptsFiltered.length,iLast=doneRawIndex;ptsFiltered.splice(doneFilteredIndex+1);for(var i=iLast+1;i1){var lastPt=pts.pop();addPt(lastPt)}return{addPt:addPt,raw:pts,filtered:ptsFiltered}}},{"../constants/numerical":661,"./matrix":690}],697:[function(require,module,exports){(function(global){"use strict";var showNoWebGlMsg=require("./show_no_webgl_msg");var createRegl=require("regl");module.exports=function prepareRegl(gd,extensions){var fullLayout=gd._fullLayout;var success=true;fullLayout._glcanvas.each(function(d){if(d.regl)return;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){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":705,regl:463}],698:[function(require,module,exports){"use strict";module.exports=function pushUnique(array,item){if(item instanceof RegExp){var itemStr=item.toString(),i;for(i=0;iconfig.queueLength){gd.undoQueue.queue.shift();gd.undoQueue.index--}};queue.startSequence=function(gd){gd.undoQueue=gd.undoQueue||{index:0,queue:[],sequence:false};gd.undoQueue.sequence=true;gd.undoQueue.beginSequence=true};queue.stopSequence=function(gd){gd.undoQueue=gd.undoQueue||{index:0,queue:[],sequence:false};gd.undoQueue.sequence=false;gd.undoQueue.beginSequence=false};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}gd.undoQueue.index--;queueObj=gd.undoQueue.queue[gd.undoQueue.index];gd.undoQueue.inSequence=true;for(i=0;i=gd.undoQueue.queue.length){return}queueObj=gd.undoQueue.queue[gd.undoQueue.index];gd.undoQueue.inSequence=true;for(i=0;i1?(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);while(n190)loggers.log("Long binary search...");return n1-1}};function lessThan(a,b){return ab}function greaterOrEqual(a,b){return a>=b}exports.sorterAsc=function(a,b){return a-b};exports.sorterDes=function(a,b){return b-a};exports.distinctVals=function(valsIn){var vals=valsIn.slice();vals.sort(exports.sorterAsc);var l=vals.length-1,minDiff=vals[l]-vals[0]||1,errDiff=minDiff/(l||1)/1e4,v2=[vals[0]];for(var i=0;ivals[i]+errDiff){minDiff=Math.min(minDiff,vals[i+1]-vals[i]);v2.push(vals[i+1])}}return{vals:v2,minDiff:minDiff}};exports.roundUp=function(val,arrayIn,reverse){var low=0,high=arrayIn.length-1,mid,c=0,dlow=reverse?0:1,dhigh=reverse?1:0,rounded=reverse?Math.ceil:Math.floor;while(lowa.length)len=a.length;if(!isNumeric(v))v=false;if(isArrayOrTypedArray(a[0])){b=new Array(len);for(i=0;iarr.length-1)return arr[arr.length-1];var frac=n%1;return frac*arr[Math.ceil(n)]+(1-frac)*arr[Math.floor(n)]}},{"./is_array":685,"fast-isnumeric":214}],707:[function(require,module,exports){"use strict";var rgba=require("color-normalize");function str2RgbaArray(color){if(!color)return[0,0,0,1];return rgba(color)}module.exports=str2RgbaArray},{"color-normalize":107}],708:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../lib");var xmlnsNamespaces=require("../constants/xmlns_namespaces");var stringMappings=require("../constants/string_mappings");var LINE_SPACING=require("../constants/alignment").LINE_SPACING;function getSize(_selection,_dimension){return _selection.node().getBoundingClientRect()[_dimension]}var FIND_TEX=/([^$]*)([$]+[^$]*[$]+)([^$]*)/;exports.convertToTspans=function(_context,gd,_callback){var str=_context.text();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({"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){_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());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"),newSvgH=getSize(newSvg,"height"),newX=+_context.attr("x")-newSvgW*{start:0,middle:.5,end:1}[_context.attr("text-anchor")||"start"],textHeight=fontSize||getSize(_context,"height"),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"){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};var LT_MATCH=/(<|<|<)/g;var GT_MATCH=/(>|>|>)/g;function cleanEscapesForTex(s){return s.replace(LT_MATCH,"\\lt ").replace(GT_MATCH,"\\gt ")}function texToSVG(_texString,_config,_callback){var randomID="math-output-"+Lib.randstr({},64);var tmpDiv=d3.select("body").append("div").attr({id:randomID}).style({visibility:"hidden",position:"absolute"}).style({"font-size":_config.fontSize+"px"}).text(cleanEscapesForTex(_texString));MathJax.Hub.Queue(["Typeset",MathJax.Hub,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()})}var TAG_STYLES={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"};var SHIFT_DY={sub:"0.3em",sup:"-0.6em"};var RESET_DY={sub:"-0.21em",sup:"0.42em"};var ZERO_WIDTH_SPACE="​";var PROTOCOLS=["http:","https:","mailto:","",undefined,":"];var STRIP_TAGS=new RegExp("]*)?/?>","g");var ENTITY_TO_UNICODE=Object.keys(stringMappings.entityToUnicode).map(function(k){return{regExp:new RegExp("&"+k+";","g"),sub:stringMappings.entityToUnicode[k]}});var NEWLINES=/(\r\n?|\n)/g;var SPLIT_TAGS=/(<[^<>]*>)/;var ONE_TAG=/<(\/?)([^ >]*)(\s+(.*))?>/i;var BR_TAG=//i;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;function getQuotedMatch(_str,re){if(!_str)return null;var match=_str.match(re);return match&&(match[3]||match[4])}var COLORMATCH=/(^|;)\s*color:/;exports.plainText=function(_str){return(_str||"").replace(STRIP_TAGS," ")};function replaceFromMapObject(_str,list){if(!_str)return"";for(var i=0;i1){for(var i=1;i.",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;icache.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}})};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}}},{}],710:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");module.exports=function toLogRange(val,range){if(val>0)return Math.log(val)/Math.LN10;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":214}],711:[function(require,module,exports){"use strict";var topojsonUtils=module.exports={};var locationmodeToLayer=require("../plots/geo/constants").locationmodeToLayer;var topojsonFeature=require("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],obj=topojson.objects[layer];return topojsonFeature(topojson,obj).features}},{"../plots/geo/constants":760,"topojson-client":502}],712:[function(require,module,exports){"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"}}},{}],713:[function(require,module,exports){"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"}}},{}],714:[function(require,module,exports){"use strict";var Registry=require("../registry");module.exports=function containerArrayMatch(astr){var rootContainers=Registry.layoutArrayContainers,regexpContainers=Registry.layoutArrayRegexes,rootPart=astr.split("[")[0],arrayStr,match;for(var i=0;i0){Lib.log("Clearing previous rejected promises from queue.")}gd._promises=[]};exports.cleanLayout=function(layout){var i,j;if(!layout)layout={};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 sceneAttrRegex=(Plots.subplotsRegistry.gl3d||{}).attrRegex;var keys=Object.keys(layout);for(i=0;i3){legend.x=1.02;legend.xanchor="left"}else if(legend.x<-2){legend.x=-.02;legend.xanchor="right"}if(legend.y>3){legend.y=1.02;legend.yanchor="bottom"}else if(legend.y<-2){legend.y=-.02;legend.yanchor="top"}}if(layout.dragmode==="rotate")layout.dragmode="orbit";Color.clean(layout);return layout};function cleanAxRef(container,attr){var valIn=container[attr],axLetter=attr.charAt(0);if(valIn&&valIn!=="paper"){container[attr]=cleanId(valIn,axLetter)}}exports.cleanData=function(data){for(var tracei=0;tracei0)return attr.substr(0,tail)}exports.hasParent=function(aobj,attr){var attrParent=getParent(attr);while(attrParent){if(attrParent in aobj)return true;attrParent=getParent(attrParent)}return false};var axLetters=["x","y","z"];exports.clearAxisTypes=function(gd,traces,layoutUpdate){for(var i=0;i1){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),componentArrayIn=np.get(),componentArray=componentArrayIn||[],componentArrayFull=nestedProperty(fullLayout,componentType).get();var deletes=[],firstIndexChange=-1,maxIndex=componentArray.length,i,j,componentNum,objEdits,objKeys,objVal,adding;for(i=0;icomponentArray.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=0;i--){componentArray.splice(deletes[i],1);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);if(drawOne!==noop){var indicesToDraw;if(firstIndexChange===-1){indicesToDraw=componentNums}else{maxIndex=Math.max(componentArray.length,maxIndex);indicesToDraw=[];for(i=0;i=firstIndexChange)break;indicesToDraw.push(componentNum)}for(i=firstIndexChange;i=gd.data.length||index<-gd.data.length){throw new Error(arrayName+" must be valid indices for gd.data.")}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.")}}}function checkMoveTracesArgs(gd,currentIndices,newIndices){if(!Array.isArray(gd.data)){throw new Error("gd.data must be an array.")}if(typeof currentIndices==="undefined"){throw new Error("currentIndices is a required argument.")}else if(!Array.isArray(currentIndices)){currentIndices=[currentIndices]}assertIndexArray(gd,currentIndices,"currentIndices");if(typeof newIndices!=="undefined"&&!Array.isArray(newIndices)){newIndices=[newIndices]}if(typeof newIndices!=="undefined"){assertIndexArray(gd,newIndices,"newIndices")}if(typeof newIndices!=="undefined"&¤tIndices.length!==newIndices.length){throw new Error("current and new indices must be of equal length.")}}function checkAddTracesArgs(gd,traces,newIndices){var i,value;if(!Array.isArray(gd.data)){throw new Error("gd.data must be an array.")}if(typeof traces==="undefined"){throw new Error("traces must be defined.")}if(!Array.isArray(traces)){traces=[traces]}for(i=0;i=0&&maxp=0&&maxp0&&typeof p.parts[pend]!=="string")pend--;var pleaf=p.parts[pend];var pleafPlus=p.parts[pend-1]+"."+pleaf;var ptrunk=p.parts.slice(0,pend).join(".");var parentIn=Lib.nestedProperty(gd.layout,ptrunk).get();var parentFull=Lib.nestedProperty(fullLayout,ptrunk).get();var vOld=p.get();if(vi===undefined)continue;redoit[ai]=vi;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])}}if(["width","height"].indexOf(ai)!==-1&&vi===null){fullLayout[ai]=gd._initialAutoSize[ai]}else if(pleafPlus.match(AX_RANGE_RE)){recordAlteredAxis(pleafPlus);Lib.nestedProperty(fullLayout,ptrunk+"._inputRange").set(null)}else if(pleafPlus.match(AX_AUTORANGE_RE)){recordAlteredAxis(pleafPlus);Lib.nestedProperty(fullLayout,ptrunk+"._inputRange").set(null);var axFull=Lib.nestedProperty(fullLayout,ptrunk).get();if(axFull._inputDomain){axFull._input.domain=axFull._inputDomain.slice()}}else if(pleafPlus.match(AX_DOMAIN_RE)){Lib.nestedProperty(fullLayout,ptrunk+"._inputDomain").set(null)}if(pleaf==="type"){var ax=parentIn,toLog=parentFull.type==="linear"&&vi==="log",fromLog=parentFull.type==="log"&&vi==="linear";if(toLog||fromLog){if(!ax||!ax.range){doextra(ptrunk+".autorange",true)}else if(!parentFull.autorange){var r0=ax.range[0],r1=ax.range[1];if(toLog){if(r0<=0&&r1<=0){doextra(ptrunk+".autorange",true)}if(r0<=0)r0=r1/1e6;else if(r1<=0)r1=r0/1e6;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){ax.range=ax.range[1]>ax.range[0]?[1,2]:[2,1]}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"]}Registry.getComponentMethod("annotations","convertCoords")(gd,parentFull,vi,doextra);Registry.getComponentMethod("images","convertCoords")(gd,parentFull,vi,doextra)}else{doextra(ptrunk+".autorange",true);doextra(ptrunk+".range",null)}Lib.nestedProperty(fullLayout,ptrunk+"._inputRange").set(null)}else if(pleaf.match(AX_NAME_PATTERN)){var fullProp=Lib.nestedProperty(fullLayout,ai).get(),newType=(vi||{}).type;if(!newType||newType==="-")newType="linear";Registry.getComponentMethod("annotations","convertCoords")(gd,fullProp,newType,doextra);Registry.getComponentMethod("images","convertCoords")(gd,fullProp,newType,doextra)}var containerArrayMatch=manageArrays.containerArrayMatch(ai);if(containerArrayMatch){arrayStr=containerArrayMatch.array;i=containerArrayMatch.index;var propStr=containerArrayMatch.property;var componentArray=Lib.nestedProperty(layout,arrayStr);var obji=(componentArray||[])[i]||{};var objToAutorange=obji;var updateValObject=valObject||{editType:"calc"};var checkForAutorange=updateValObject.editType.indexOf("calcIfAutorange")!==-1;if(i===""){if(checkForAutorange)flags.calc=true;else editTypes.update(flags,updateValObject);checkForAutorange=false}else if(propStr===""){objToAutorange=vi;if(manageArrays.isAddVal(vi)){undoit[ai]=null}else if(manageArrays.isRemoveVal(vi)){undoit[ai]=obji;objToAutorange=obji}else Lib.warn("unrecognized full object value",aobj)}if(checkForAutorange&&(refAutorange(gd,objToAutorange,"x")||refAutorange(gd,objToAutorange,"y"))){flags.calc=true}else{editTypes.update(flags,updateValObject)}if(!arrayEdits[arrayStr])arrayEdits[arrayStr]={};var objEdits=arrayEdits[arrayStr][i];if(!objEdits)objEdits=arrayEdits[arrayStr][i]={};objEdits[propStr]=vi;delete aobj[ai]}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)}}for(arrayStr in arrayEdits){var finished=manageArrays.applyContainerArrayChanges(gd,Lib.nestedProperty(layout,arrayStr),arrayEdits[arrayStr],flags);if(!finished)flags.plot=true}var constraints=fullLayout._axisConstraintGroups||[];for(axId in rangesAltered){for(i=0;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}}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;itrans._timeToNext){nextFrame()}};doFrame()}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}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){frameList.push({type:"object",data:setTransitionConfig(Lib.extendFlat({},frameOrGroupNameOrFrameList))})}else if(allFrames||["string","number"].indexOf(typeof frameOrGroupNameOrFrameList)!==-1){for(i=0;i0&&idxidx){filteredFrameList.push(frame)}}frameList=filteredFrameList}}if(frameList.length>0){queueFrames(frameList)}else{gd.emit("plotly_animated");resolve()}})};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)}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;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&&numericNameWarningCountb.index)return-1;if(a.index=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){while(_frameHash[frame.name="frame "+gd._transitionData._counter++]);}if(_frameHash[frame.name]){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{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,redoFunc=Plots.modifyFrames,undoArgs=[gd,revops],redoArgs=[gd,ops];if(Queue)Queue.add(gd,undoFunc,undoArgs,redoFunc,redoArgs);return Plots.modifyFrames(gd,ops)};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,redoFunc=Plots.modifyFrames,undoArgs=[gd,revops],redoArgs=[gd,ops];if(Queue)Queue.add(gd,undoFunc,undoArgs,redoFunc,redoArgs);return Plots.modifyFrames(gd,ops)};exports.purge=function purge(gd){gd=Lib.getGraphDiv(gd);var fullLayout=gd._fullLayout||{};var fullData=gd._fullData||[];var calcdata=gd.calcdata||[];Plots.cleanPlot([],{},fullData,fullLayout,calcdata);Plots.purge(gd);Events.purge(gd);if(fullLayout._container)fullLayout._container.remove();delete gd._context;return gd};function makePlotFramework(gd){var gd3=d3.select(gd);var fullLayout=gd._fullLayout;fullLayout._container=gd3.selectAll(".plot-container").data([0]);fullLayout._container.enter().insert("div",":first-child").classed("plot-container",true).classed("plotly",true);fullLayout._paperdiv=fullLayout._container.selectAll(".svg-container").data([0]);fullLayout._paperdiv.enter().append("div").classed("svg-container",true).style("position","relative");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);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);fullLayout._cartesianlayer=fullLayout._paper.append("g").classed("cartesianlayer",true);fullLayout._polarlayer=fullLayout._paper.append("g").classed("polarlayer",true);fullLayout._ternarylayer=fullLayout._paper.append("g").classed("ternarylayer",true);fullLayout._geolayer=fullLayout._paper.append("g").classed("geolayer",true);fullLayout._pielayer=fullLayout._paper.append("g").classed("pielayer",true);fullLayout._glimages=fullLayout._paper.append("g").classed("glimages",true);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":558,"../components/colorbar/connect":560,"../components/drawing":583,"../constants/xmlns_namespaces":663,"../lib":684,"../lib/events":672,"../lib/queue":699,"../lib/svg_text_utils":708,"../plots/cartesian/axes":732,"../plots/cartesian/constants":737,"../plots/cartesian/graph_interact":741,"../plots/plots":795,"../plots/polar/legacy":803,"../registry":817,"./edit_types":715,"./helpers":716,"./manage_arrays":718,"./plot_config":720,"./plot_schema":721,"./subroutines":723,d3:147,"fast-isnumeric":214,"has-hover":378}],720:[function(require,module,exports){"use strict";module.exports={staticPlot:false,plotlyServerURL:"https://plot.ly",editable:false,edits:{annotationPosition:false,annotationTail:false,annotationText:false,axisTitleText:false,colorbarPosition:false,colorbarTitleText:false,legendPosition:false,legendText:false,shapePosition:false,titleText:false},autosizable:false,queueLength:0,fillFrame:false,frameMargins:0,scrollZoom:false,doubleClick:"reset+autosize",showTips:true,showAxisDragHandles:true,showAxisRangeEntryBoxes:true,showLink:false,sendData:true,linkText:"Edit chart",showSources:false,displayModeBar:"hover",modeBarButtonsToRemove:[],modeBarButtonsToAdd:[],modeBarButtons:false,toImageButtonOptions:{},displaylogo:true,plotGlPixelRatio:2,setBackground:"transparent",topojsonURL:"https://cdn.plot.ly/",mapboxAccessToken:null,logging:1,globalTransforms:[],locale:"en-US",locales:{}}},{}],721:[function(require,module,exports){"use strict";var Registry=require("../registry");var Lib=require("../lib");var baseAttributes=require("../plots/attributes");var baseLayoutAttributes=require("../plots/layout_attributes");var frameAttributes=require("../plots/frame_attributes");var animationAttributes=require("../plots/animation_attributes");var polarAreaAttrs=require("../plots/polar/legacy/area_attributes");var polarAxisAttrs=require("../plots/polar/legacy/axis_attributes");var editTypes=require("./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;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)}};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)}})};exports.isValObject=function(obj){return obj&&obj.valType!==undefined};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"));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=transforms.length){return false}moduleAttrs=(Registry.transformsRegistry[transforms[tNum].type]||{}).attributes;valObject=moduleAttrs&&moduleAttrs[parts[2]];i=3}else if(trace.type==="area"){valObject=polarAreaAttrs[head]}else{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];if(!valObject){var subplotModule=_module.basePlotModule;if(subplotModule&&subplotModule.attributes){valObject=subplotModule.attributes[head]}}if(!valObject)valObject=baseAttributes[head]}return recurseIntoValObject(valObject,parts,i)};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;var basePlotModules=fullLayout._basePlotModules;if(basePlotModules){var out;for(i=0;i=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}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={};attributes.type=null;extendDeepAll(attributes,baseAttributes);extendDeepAll(attributes,_module.attributes);if(basePlotModule.attributes){extendDeepAll(attributes,basePlotModule.attributes)}attributes.type=type;var out={meta:_module.meta||{},attributes:formatAttributes(attributes)};if(_module.layoutAttributes){var layoutAttributes={};extendDeepAll(layoutAttributes,_module.layoutAttributes);out.layoutAttributes=formatAttributes(layoutAttributes)}return out}function getLayoutAttributes(){var layoutAttributes={};var key,_module;extendDeepAll(layoutAttributes,baseLayoutAttributes);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)}}layoutAttributes=assignPolarLayoutAttrs(layoutAttributes);for(key in Registry.componentsRegistry){_module=Registry.componentsRegistry[key];var schema=_module.schema;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]}}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);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"){attr.role="data";attrs[attrName+"src"]=makeSrcAttr(attrName)}else if(attr.arrayOk===true){attrs[attrName+"src"]=makeSrcAttr(attrName)}}else if(isPlainObject(attr)){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)}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=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){Lib.nestedProperty(update[itemStr],attr).set(value)}else{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":684,"../plots/attributes":729}],723:[function(require,module,exports){"use strict";var d3=require("d3");var Registry=require("../registry");var Plots=require("../plots/plots");var Lib=require("../lib");var clearGlCanvases=require("../lib/clear_gl_canvases");var Color=require("../components/color");var Drawing=require("../components/drawing");var Titles=require("../components/titles");var ModeBar=require("../components/modebar");var Axes=require("../plots/cartesian/axes");var alignmentConstants=require("../constants/alignment");var axisConstraints=require("../plots/cartesian/constraints");var enforceAxisConstraints=axisConstraints.enforce;var cleanAxisConstraints=axisConstraints.clean;var doAutoRange=require("../plots/cartesian/autorange").doAutoRange;exports.layoutStyles=function(gd){return Lib.syncOrAsync([Plots.doAutoMargin,lsInner],gd)};function overlappingDomain(xDomain,yDomain,domains){for(var i=0;i=xDomain[1]||existingX[1]<=xDomain[0]){continue}if(existingY[0]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 hasSVGCartesian=fullLayout._has("cartesian");var i;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}for(i=0;idataCount){errorList.push({code:"unused",traceType:traceType,templateCount:templateCount,dataCount:dataCount})}else if(dataCount>templateCount){errorList.push({code:"reused",traceType:traceType,templateCount:templateCount,dataCount:dataCount})}}}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;i1){errorList.push(format("object","layout"))}}Plots.supplyDefaults(gd);var dataOut=gd._fullData,len=dataIn.length;for(var i=0;ivalOut.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;nvalOut[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;n0&&dp>0&&dv/dp>mbest){minbest=minpt;maxbest=maxpt;mbest=dv/dp}}}if(minmin===maxmax){var lower=minmin-1;var upper=minmin+1;if(ax.rangemode==="tozero"){newRange=minmin<0?[lower,0]:[0,upper]}else if(ax.rangemode==="nonnegative"){newRange=[Math.max(0,lower),Math.max(0,upper)]}else{newRange=[lower,upper]}}else if(mbest){if(ax.type==="linear"||ax.type==="-"){if(ax.rangemode==="tozero"){if(minbest.val>=0){minbest={val:0,pad:0}}if(maxbest.val<=0){maxbest={val:0,pad:0}}}else if(ax.rangemode==="nonnegative"){if(minbest.val-mbest*getPad(minbest)<0){minbest={val:0,pad:0}}if(maxbest.val<0){maxbest={val:1,pad:0}}}mbest=(maxbest.val-minbest.val)/(ax._length-getPad(minbest)-getPad(maxbest))}newRange=[minbest.val-mbest*getPad(minbest),maxbest.val+mbest*getPad(maxbest)]}if(newRange[0]===newRange[1]){if(ax.rangemode==="tozero"){if(newRange[0]<0){newRange=[newRange[0],0]}else if(newRange[0]>0){newRange=[0,newRange[0]]}else{newRange=[0,1]}}else{newRange=[newRange[0]-1,newRange[0]+1];if(ax.rangemode==="nonnegative"){newRange[0]=Math.max(0,newRange[0])}}}if(axReverse)newRange.reverse();return Lib.simpleMap(newRange,ax.l2r||Number)}function makePadFn(ax){var extrappad=ax._length/20;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 doAutoRange(ax){if(!ax._length)ax.setScale();var hasDeps=ax._min&&ax._max&&ax._min.length&&ax._max.length;var axIn;if(ax.autorange&&hasDeps){ax.range=getAutoRange(ax);ax._r=ax.range.slice();ax._rl=Lib.simpleMap(ax._r,ax.r2l);axIn=ax._input;axIn.range=ax.range.slice();axIn.autorange=ax.autorange}if(ax._anchorAxis&&ax._anchorAxis.rangeslider){var axeRangeOpts=ax._anchorAxis.rangeslider[ax._name];if(axeRangeOpts){if(axeRangeOpts.rangemode==="auto"){if(hasDeps){axeRangeOpts.range=getAutoRange(ax)}else{axeRangeOpts.range=ax._rangeInitial?ax._rangeInitial.slice():ax.range.slice()}}}axIn=ax._anchorAxis._input;axIn.rangeslider[ax._name]=Lib.extendFlat({},axeRangeOpts)}}function needsAutorange(ax){return ax.autorange||ax._rangesliderAutorange}function expand(ax,data,options){if(!needsAutorange(ax)||!data)return;if(!ax._min)ax._min=[];if(!ax._max)ax._max=[];if(!options)options={};if(!ax._m)ax.setScale();var len=data.length;var extrapad=options.padded||false;var tozero=options.tozero&&(ax.type==="linear"||ax.type==="-");var isLog=ax.type==="log";var i,j,k,v,di,dmin,dmax,ppadiplus,ppadiminus,includeThis,vmin,vmax;var hasArrayOption=false;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?options.ppadplus:options.ppadminus)||options.ppad||0);var ppadminus=makePadAccessor((ax._m>0?options.ppadminus:options.ppadplus)||options.ppad||0);var vpadplus=makePadAccessor(options.vpadplus||options.vpad);var vpadminus=makePadAccessor(options.vpadminus||options.vpad);if(!hasArrayOption){vmin=Infinity;vmax=-Infinity;if(isLog){for(i=0;i0)vmin=v;if(v>vmax&&v-FP_SAFE)vmin=v;if(v>vmax&&v=newPad&&(v.extrapad||!extrapad)){includeThis=false;break}else if(atLeastAsExtreme(newVal,v.val)&&v.pad<=newPad&&(extrapad||!v.extrapad)){extremes.splice(j,1);j--}}if(includeThis){var clipAtZero=tozero&&newVal===0;extremes.push({val:newVal,pad:clipAtZero?0:newPad,extrapad:clipAtZero?false:extrapad})}}}}var iMax=Math.min(6,len);for(i=0;i=iMax;i--)addItem(i)}function goodNumber(v){return isNumeric(v)&&Math.abs(v)=v1}},{"../../constants/numerical":661,"../../lib":684,"fast-isnumeric":214}],732:[function(require,module,exports){"use strict";var d3=require("d3");var isNumeric=require("fast-isnumeric");var Plots=require("../../plots/plots");var Registry=require("../../registry");var Lib=require("../../lib");var svgTextUtils=require("../../lib/svg_text_utils");var Titles=require("../../components/titles");var Color=require("../../components/color");var Drawing=require("../../components/drawing");var constants=require("../../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=require("../../constants/alignment").MID_SHIFT;var LINE_SPACING=require("../../constants/alignment").LINE_SPACING;var axes=module.exports={};axes.setConvert=require("./set_convert");var autoType=require("./axis_autotype");var axisIds=require("./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=require("./autorange");axes.expand=autorange.expand;axes.getAutoRange=autorange.getAutoRange;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;attrDef[refAttr]={valType:"enumerated",values:axlist.concat(extraOption?[extraOption]:[]),dflt:dflt};return Lib.coerce(containerIn,containerOut,attrDef,refAttr)};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)};var getDataConversions=axes.getDataConversions=function(gd,trace,target,targetArray){var ax;var d2cTarget=target==="x"||target==="y"||target==="z"?target:targetArray;if(Array.isArray(d2cTarget)){ax={type:autoType(targetArray),_categories:[]};axes.setConvert(ax);if(ax.type==="category"){for(var i=0;i2e-6||((newFirst-ax._forceTick0)/ax._minDtick%1+1.000001)%1>2e-6){ax._minDtick=0}}};axes.saveRangeInitial=function(gd,overwrite){var axList=axes.list(gd,"",true),hasOneAxisChanged=false;for(var i=0;idataCount*.3||nearEdge(dataMin)||nearEdge(dataMax)){var binshift=ax.dtick/2;binStart+=binStart+binshiftthreshold){var numMonths=Number(dtick.substr(1));if(stats.exactYears>threshold&&numMonths%12===0){binStart=axes.tickIncrement(binStart,"M6","reverse")+ONEDAY*1.5}else if(stats.exactMonths>threshold){binStart=axes.tickIncrement(binStart,"M1","reverse")+ONEDAY*15.5}else{binStart-=ONEDAY/2}var nextBinStart=axes.tickIncrement(binStart,dtick);if(nextBinStart<=dataMin)return nextBinStart}return binStart}axes.prepTicks=function(ax){var rng=Lib.simpleMap(ax.range,ax.r2l);if(ax.tickmode==="auto"||!ax.dtick){var nt=ax.nticks,minPx;if(!nt){if(ax.type==="category"){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}if(ax._name==="radialaxis")nt*=2}if(ax.tickmode==="array")nt*=100;axes.autoTicks(ax,Math.abs(rng[1]-rng[0])/nt);if(ax._minDtick>0&&ax.dtick=endTick:x<=endTick;x=axes.tickIncrement(x,ax.dtick,axrev,ax.calendar)){if(vals.length>maxTicks||x===xPrevious)break;xPrevious=x;vals.push(x)}if(ax._id==="angular"&&Math.abs(rng[1]-rng[0])===360){vals.pop()}ax._tmax=vals[vals.length-1];ax._prevDateHead="";ax._inCalcTicks=true;var ticksOut=new Array(vals.length);for(var i=0;itickMin&&valiONEAVGYEAR){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);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{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>.7){ax.dtick=Math.ceil(roughDTick)}else if(Math.abs(rng[1]-rng[0])<1){var nt=1.5*Math.abs((rng[1]-rng[0])/roughDTick);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{ax.dtick=roughDTick>.3?"D2":"D1"}}else if(ax.type==="category"){ax.tick0=0;ax.dtick=Math.ceil(Math.max(roughDTick,1))}else if(ax._id==="angular"){ax.tick0=0;base=1;ax.dtick=roundDTick(roughDTick,base,roundAngles)}else{ax.tick0=0;base=getBase(10);ax.dtick=roundDTick(roughDTick,base,roundBase10)}if(ax.dtick===0)ax.dtick=1;if(!isNumeric(ax.dtick)&&typeof ax.dtick!=="string"){var olddtick=ax.dtick;ax.dtick=1;throw"ax.dtick error: "+String(olddtick)}};function autoTickRound(ax){var dtick=ax.dtick;ax._tickexponent=0;if(!isNumeric(dtick)&&typeof dtick!=="string"){dtick=1}if(ax.type==="category"){ax._tickround=null}if(ax.type==="date"){var tick0ms=ax.r2l(ax.tick0),tick0str=ax.l2r(tick0ms).replace(/(^-|i)/g,""),tick0len=tick0str.length;if(String(dtick).charAt(0)==="M"){if(tick0len>10||tick0str.substr(5)!=="01-01")ax._tickround="d";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{var tick1len=ax.l2r(tick0ms+dtick).replace(/^-/,"").length;ax._tickround=Math.max(tick0len,tick1len)-20}}else if(isNumeric(dtick)||dtick.charAt(0)==="L"){var rng=ax.range.map(ax.r2d||Number);if(!isNumeric(dtick))dtick=Number(dtick.substr(1));ax._tickround=2-Math.floor(Math.log(dtick)/Math.LN10+.01);var maxend=Math.max(Math.abs(rng[0]),Math.abs(rng[1]));var rangeexp=Math.floor(Math.log(maxend)/Math.LN10+.01);if(Math.abs(rangeexp)>3){if(isSIFormat(ax.exponentformat)&&!beyondSI(rangeexp)){ax._tickexponent=3*Math.round((rangeexp-1)/3)}else ax._tickexponent=rangeexp}}else ax._tickround=null}axes.tickIncrement=function(x,dtick,axrev,calendar){var axSign=axrev?-1:1;if(isNumeric(dtick))return x+axSign*dtick;var tType=dtick.charAt(0),dtSigned=axSign*Number(dtick.substr(1));if(tType==="M")return Lib.incrementMonth(x,dtSigned,calendar);else if(tType==="L")return Math.log(Math.pow(10,x)+dtSigned)/Math.LN10;else if(tType==="D"){var tickset=dtick==="D2"?roundLog2:roundLog1,x2=x+axSign*.01,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)};axes.tickFirst=function(ax){var r2l=ax.r2l||Number,rng=Lib.simpleMap(ax.range,r2l),axrev=rng[1]"+headStr;ax._prevDateHead=headStr}}out.text=dateStr}function formatLog(ax,out,hover,extraPrecision,hideexp){var dtick=ax.dtick,x=out.x,tickformat=ax.tickformat;if(hideexp==="never"){hideexp=""}if(extraPrecision&&(typeof dtick!=="string"||dtick.charAt(0)!=="L"))dtick="L3";if(tickformat||typeof dtick==="string"&&dtick.charAt(0)==="L"){out.text=numFormat(Math.pow(10,x),ax,hideexp,extraPrecision)}else if(isNumeric(dtick)||dtick.charAt(0)==="D"&&Lib.mod(x+.01,1)<.1){var p=Math.round(x);if(["e","E","power"].indexOf(ax.exponentformat)!==-1||isSIFormat(ax.exponentformat)&&beyondSI(p)){if(p===0)out.text=1;else if(p===1)out.text="10";else if(p>1)out.text="10"+p+"";else out.text="10"+MINUS_SIGN+-p+"";out.fontSize*=1.25}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(dtick.charAt(0)==="D"){out.text=String(Math.round(Math.pow(10,Lib.mod(x,1))));out.fontSize*=.75}else throw"unrecognized dtick "+String(dtick);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?.5:.25)}}}}function formatCategory(ax,out){var tt=ax._categories[Math.round(out.x)];if(tt===undefined)tt="";out.text=String(tt)}function formatLinear(ax,out,hover,extraPrecision,hideexp){if(hideexp==="never"){hideexp=""}else if(ax.showexponent==="all"&&Math.abs(out.x/ax.dtick)<1e-6){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=["",frac[0],"","⁄","",frac[1],"","π"].join("")}if(isNeg)out.text=MINUS_SIGN+out.text}}}else{out.text=numFormat(out.x,ax,hideexp,extraPrecision)}}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[Math.round(number/gcd),Math.round(precision/gcd)]}var SIPREFIXES=["f","p","n","μ","m","","k","M","G","T"];function isSIFormat(exponentFormat){return exponentFormat==="SI"||exponentFormat==="B"}function beyondSI(exponent){return exponent>14||exponent<-15}function numFormat(v,ax,fmtoverride,hover){var isNeg=v<0,tickRound=ax._tickround,exponentFormat=fmtoverride||ax.exponentformat||"B",exponent=ax._tickexponent,tickformat=axes.getTickFormat(ax),separatethousands=ax.separatethousands;if(hover){var ah={exponentformat:exponentFormat,dtick:ax.showexponent==="none"?ax.dtick:isNumeric(v)?Math.abs(v)||1:1,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);var e=Math.pow(10,-tickRound)/2;if(exponentFormat==="none")exponent=0;v=Math.abs(v);if(v"+signedExponent+""}else if(exponentFormat==="B"&&exponent===9){v+="B"}else if(isSIFormat(exponentFormat)){v+=SIPREFIXES[exponent/3+5]}}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;i1&&p1){for(j=1;jncnt*2}function category(a){var inc=Math.max(1,(a.length-1)/1e3),curvenums=0,curvecats=0,ai;for(var i=0;icurvenums*2}},{"../../constants/numerical":661,"../../lib":684,"fast-isnumeric":214}],734:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Lib=require("../../lib");var layoutAttributes=require("./layout_attributes");var handleTickValueDefaults=require("./tick_value_defaults");var handleTickMarkDefaults=require("./tick_mark_defaults");var handleTickLabelDefaults=require("./tick_label_defaults");var handleCategoryOrderDefaults=require("./category_order_defaults");var handleLineGridDefaults=require("./line_grid_defaults");var setConvert=require("./set_convert");module.exports=function handleAxisDefaults(containerIn,containerOut,coerce,options,layoutOut){var letter=options.letter;var id=containerOut._id;var font=options.font||{};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));containerOut._rangesliderAutorange=false;if(autoRange)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");var dfltFontColor=dfltColor!==layoutAttributes.color.dflt?dfltColor:font.color;var dfltTitle=((layoutOut._splomAxes||{})[letter]||{})[id]||layoutOut._dfltTitle[letter];coerce("title",dfltTitle);Lib.coerceFont(coerce,"titlefont",{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");return containerOut}},{"../../lib":684,"../../registry":817,"./category_order_defaults":736,"./layout_attributes":744,"./line_grid_defaults":746,"./set_convert":750,"./tick_label_defaults":751,"./tick_mark_defaults":752,"./tick_value_defaults":753}],735:[function(require,module,exports){"use strict";var Registry=require("../../registry");var constants=require("./constants");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};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;iletter2?1:-1;return+(id1.substr(1)||1)-+(id2.substr(1)||1)}},{"../../registry":817,"./constants":737}],736:[function(require,module,exports){"use strict";function findCategories(ax,opts){var dataAttr=opts.dataAttr||ax._id.charAt(0);var lookup={};var axData;var i,j;if(opts.axData){axData=opts.axData}else{axData=[];for(i=0;i0;var orderDefault;if(isValidArray)orderDefault="array";var order=coerce("categoryorder",orderDefault);var array;if(order==="array"){array=coerce("categoryarray")}if(!isValidArray&&order==="array"){order=containerOut.categoryorder="trace"}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()}}}},{}],737:[function(require,module,exports){"use strict";var counterRegex=require("../../lib/regex").counter;module.exports={idRegex:{x:counterRegex("x"),y:counterRegex("y")},attrRegex:counterRegex("[xy]axis"),xAxisMatch:counterRegex("xaxis"),yAxisMatch:counterRegex("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":700}],738:[function(require,module,exports){"use strict";var Lib=require("../../lib");var id2name=require("./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("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");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){var thisType=layoutOut[id2name(thisID)].type;var i,j,idj,axj;var linkableAxes=[];for(j=0;jALMOST_EQUAL*maxScale&&!hasAnyDomainConstraint)continue;for(j=0;jouterMin&&newValrangeMax){rangeMax=newVal}}var domainExpand=(rangeMax-rangeMin)/(2*halfRange);factor/=domainExpand;rangeMin=ax.l2r(rangeMin);rangeMax=ax.l2r(rangeMax);ax.range=ax._input.range=rl0MINZOOM||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(!yActive||dy10||pc.scrollWidth-pc.clientWidth>10){return}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),gbb=mainplot.draglayer.select(".nsewdrag").node().getBoundingClientRect(),xfrac=(e.clientX-gbb.left)/gbb.width,yfrac=(gbb.bottom-e.clientY)/gbb.height,i;function zoomWheelOneAxis(ax,centerFraction,zoom){if(ax.fixedrange)return;var axRange=Lib.simpleMap(ax.range,ax.r2l),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(!ew)xfrac=.5;for(i=0;i=0?Math.min(d,.9):1/(1/Math.max(d,-.3)+3.222))}function getDragCursor(nsew,dragmode,isMainDrag){if(!nsew)return"pointer";if(nsew==="nsew"){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>.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>.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-.5)+","+(y0-MINZOOM-.5)+"h-3v"+(2*MINZOOM+1)+"h3ZM"+(box.r+.5)+","+(y0-MINZOOM-.5)+"h3v"+(2*MINZOOM+1)+"h-3Z"}function yCorners(box,x0){return"M"+(x0-MINZOOM-.5)+","+(box.t-.5)+"v-3h"+(2*MINZOOM+1)+"v3ZM"+(x0-MINZOOM-.5)+","+(box.b+.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-.5+clen)+"h3v"+-clen+"h"+clen+"v-3h-"+(clen+3)+"ZM"+(box.r+3.5)+","+(box.t-.5+clen)+"h-3v"+-clen+"h"+-clen+"v-3h"+(clen+3)+"ZM"+(box.r+3.5)+","+(box.b+.5-clen)+"h-3v"+clen+"h"+-clen+"v3h"+(clen+3)+"ZM"+(box.l-3.5)+","+(box.b+.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;idomain[1]-.01)containerOut.domain=dfltDomain;Lib.noneOrAll(containerIn.domain,containerOut.domain,dfltDomain)}coerce("layer");return containerOut}},{"../../lib":684,"fast-isnumeric":214}],748:[function(require,module,exports){"use strict";var FROM_BL=require("../../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":656}],749:[function(require,module,exports){"use strict";var polybool=require("polybooljs");var Registry=require("../../registry");var Color=require("../../components/color");var Fx=require("../../components/fx");var polygon=require("../../lib/polygon");var throttle=require("../../lib/throttle");var makeEventData=require("../../components/fx/helpers").makeEventData;var getFromId=require("./axis_ids").getFromId;var sortModules=require("../sort_modules").sortModules;var constants=require("./constants");var MINSELECT=constants.MINSELECT;var filteredPolygon=polygon.filter;var polygonTester=polygon.tester;var multipolygonTester=polygon.multitester;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 xAxisIds=dragOptions.xaxes.map(getAxId);var yAxisIds=dragOptions.yaxes.map(getAxId);var allAxes=dragOptions.xaxes.concat(dragOptions.yaxes);var subtract=e.altKey;var filterPoly,testPoly,mergedPolygons,currentPolygon;var i,cd,trace,searchInfo,eventData;var selectingOnSameSubplot=fullLayout._lastSelectedSubplot&&fullLayout._lastSelectedSubplot===plotinfo.id;if(selectingOnSameSubplot&&(e.shiftKey||e.altKey)&&(plotinfo.selection&&plotinfo.selection.polygons)&&!dragOptions.polygons){dragOptions.polygons=plotinfo.selection.polygons;dragOptions.mergedPolygons=plotinfo.selection.mergedPolygons}else if(!e.shiftKey&&!e.altKey||(e.shiftKey||e.altKey)&&!plotinfo.selection){plotinfo.selection={};plotinfo.selection.polygons=dragOptions.polygons=[];plotinfo.selection.mergedPolygons=dragOptions.mergedPolygons=[]}if(!selectingOnSameSubplot){clearSelect(zoomLayer);fullLayout._lastSelectedSubplot=plotinfo.id}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 searchTraces=[];var throttleID=fullLayout._uid+constants.SELECTID;var selection=[];for(i=0;i0)return Math.log(v)/Math.LN10;else if(v<=0&&clip&&ax.range&&ax.range.length===2){var r0=ax.range[0],r1=ax.range[1];return.5*(r0+r1-3*clipMult*Math.abs(r0-r1))}else return BADNUM}function dt2ms(v,_,calendar){var ms=dateTime2ms(v,calendar||ax.calendar);if(ms===BADNUM){if(isNumeric(v)){v=+v;var msecTenths=Math.floor(Lib.mod(v+.05,1)*10);var msRounded=Math.round(v-msecTenths/10);ms=dateTime2ms(new Date(msRounded))+msecTenths/10}else return BADNUM}return ms}function ms2dt(v,r,calendar){return ms2DateTime(v,r,calendar||ax.calendar)}function getCategoryName(v){return ax._categories[Math.round(v)]}function setCategoryIndex(v){if(v!==null&&v!==undefined){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 getCategoryIndex(v){if(ax._categoriesMap){var index=ax._categoriesMap[v];if(index!==undefined)return index}if(isNumeric(v))return+v}function l2p(v){if(!isNumeric(v))return BADNUM;return d3.round(ax._b+ax._m*v,2)}function p2l(px){return(px-ax._b)/ax._m}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;if(["linear","-"].indexOf(ax.type)!==-1){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"){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"){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"){ax.d2c=ax.d2l=setCategoryIndex;ax.r2d=ax.c2d=ax.l2d=getCategoryName;ax.d2r=ax.d2l_noadd=getCategoryIndex;ax.r2c=function(v){var index=getCategoryIndex(v);return index!==undefined?index:ax.fraction2r(.5)};ax.l2r=ax.c2r=ensureNumber;ax.r2l=getCategoryIndex;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)}}ax.fraction2r=function(v){var rl0=ax.r2l(ax.range[0]),rl1=ax.r2l(ax.range[1]);return ax.l2r(rl0+v*(rl1-rl0))};ax.r2fraction=function(v){var rl0=ax.r2l(ax.range[0]),rl1=ax.r2l(ax.range[1]);return(ax.r2l(v)-rl0)/(rl1-rl0)};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;dflt=dflt.slice();if(!range||range.length!==2){Lib.nestedProperty(ax,rangeAttr).set(dflt);return}if(ax.type==="date"){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])){var linCenter=Lib.constrain(ax.r2l(range[0]),Lib.MIN_MS+1e3,Lib.MAX_MS-1e3);range[0]=ax.l2r(linCenter-1e3);range[1]=ax.l2r(linCenter+1e3);break}}else{if(!isNumeric(range[i])){if(isNumeric(range[1-i])){range[i]=range[1-i]*(i?10:.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]){var inc=Math.max(1,Math.abs(range[0]*1e-6));range[0]-=inc;range[1]+=inc}}}};ax.setScale=function(usePrivateRange){var gs=fullLayout._size;if(!ax._categories)ax._categories=[];if(!ax._categoriesMap)ax._categoriesMap={};if(ax.overlaying){var ax2=axisIds.getFromId({_fullLayout:fullLayout},ax.overlaying);ax.domain=ax2.domain}var rangeAttr=usePrivateRange&&ax._r?"_r":"range",calendar=ax.calendar;ax.cleanRange(rangeAttr);var rl0=ax.r2l(ax[rangeAttr][0],calendar),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")}};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||arrayIn.length;if(Lib.isTypedArray(arrayIn)&&(axType==="linear"||axType==="log")){if(len===arrayIn.length){return arrayIn}else if(arrayIn.subarray){return arrayIn.subarray(0,len)}}arrayOut=new Array(len);for(i=0;i0?Number(dtick):dtickDflt}else if(typeof dtick!=="string"){containerOut.dtick=dtickDflt}else{var prefix=dtick.charAt(0),dtickNum=dtick.substr(1);dtickNum=isNumeric(dtickNum)?Number(dtickNum):0;if(dtickNum<=0||!(axType==="date"&&prefix==="M"&&dtickNum===Math.round(dtickNum)||axType==="log"&&prefix==="L"||axType==="log"&&prefix==="D"&&(dtickNum===1||dtickNum===2))){containerOut.dtick=dtickDflt}}var tick0Dflt=axType==="date"?Lib.dateTick0(containerOut.calendar):0;var tick0=coerce("tick0",tick0Dflt);if(axType==="date"){containerOut.tick0=Lib.cleanDate(tick0,tick0Dflt)}else if(isNumeric(tick0)&&dtick!=="D1"&&dtick!=="D2"){containerOut.tick0=Number(tick0)}else{containerOut.tick0=tick0Dflt}}else{var tickvals=coerce("tickvals");if(tickvals===undefined)containerOut.tickmode="auto";else coerce("ticktext")}}},{"../../constants/numerical":661,"../../lib":684,"fast-isnumeric":214}],754:[function(require,module,exports){"use strict";var d3=require("d3");var Registry=require("../../registry");var Drawing=require("../../components/drawing");var Axes=require("./axes");var axisRegex=require("./constants").attrRegex;module.exports=function transitionAxes(gd,newLayout,transitionOpts,makeOnCompleteCallback){var fullLayout=gd._fullLayout;var axes=[];function computeUpdates(layout){var ai,attrList,match,axis,update;var updates={};for(ai in layout){attrList=ai.split(".");match=attrList[0].match(axisRegex);if(match){var axisLetter=ai.charAt(0);var axisName=attrList[0];axis=fullLayout[axisName];update={};if(Array.isArray(layout[ai])){update.to=layout[ai].slice(0)}else{if(Array.isArray(layout[ai].range)){update.to=layout[ai].range.slice(0)}}if(!update.to)continue;update.axisName=axisName;update.length=axis._length;axes.push(axisLetter);updates[axisLetter]=update}}return updates}function computeAffectedSubplots(fullLayout,updatedAxisIds,updates){var plotName;var plotinfos=fullLayout._plots;var affectedSubplots=[];var toX,toY;for(plotName in plotinfos){var plotinfo=plotinfos[plotName];if(affectedSubplots.indexOf(plotinfo)!==-1)continue;var x=plotinfo.xaxis._id;var y=plotinfo.yaxis._id;var fromX=plotinfo.xaxis.range;var fromY=plotinfo.yaxis.range;plotinfo.xaxis._r=plotinfo.xaxis.range.slice();plotinfo.yaxis._r=plotinfo.yaxis.range.slice();if(updates[x]){toX=updates[x].to}else{toX=fromX}if(updates[y]){toY=updates[y].to}else{toY=fromY}if(fromX[0]===toX[0]&&fromX[1]===toX[1]&&fromY[0]===toY[0]&&fromY[1]===toY[1])continue;if(updatedAxisIds.indexOf(x)!==-1||updatedAxisIds.indexOf(y)!==-1){affectedSubplots.push(plotinfo)}}return affectedSubplots}var updates=computeUpdates(newLayout);var updatedAxisIds=Object.keys(updates);var affectedSubplots=computeAffectedSubplots(fullLayout,updatedAxisIds,updates);function updateLayoutObjs(){function redrawObjs(objArray,method,shortCircuit){for(var i=0;i rect").call(Drawing.setTranslate,0,0).call(Drawing.setScale,1,1);subplot.plot.call(Drawing.setTranslate,xa2._offset,ya2._offset).call(Drawing.setScale,1,1);var traceGroups=subplot.plot.selectAll(".scatterlayer .trace");traceGroups.selectAll(".point").call(Drawing.setPointGroupScale,1,1);traceGroups.selectAll(".textpoint").call(Drawing.setTextPointsScale,1,1);traceGroups.call(Drawing.hideOutsideRangePoints,subplot)}function updateSubplot(subplot,progress){var axis,r0,r1;var xUpdate=updates[subplot.xaxis._id];var yUpdate=updates[subplot.yaxis._id];var viewBox=[];if(xUpdate){axis=gd._fullLayout[xUpdate.axisName];r0=axis._r;r1=xUpdate.to;viewBox[0]=(r0[0]*(1-progress)+progress*r1[0]-r0[0])/(r0[1]-r0[0])*subplot.xaxis._length;var dx1=r0[1]-r0[0];var dx2=r1[1]-r1[0];axis.range[0]=r0[0]*(1-progress)+progress*r1[0];axis.range[1]=r0[1]*(1-progress)+progress*r1[1];viewBox[2]=subplot.xaxis._length*(1-progress+progress*dx2/dx1)}else{viewBox[0]=0;viewBox[2]=subplot.xaxis._length}if(yUpdate){axis=gd._fullLayout[yUpdate.axisName];r0=axis._r;r1=yUpdate.to;viewBox[1]=(r0[1]*(1-progress)+progress*r1[1]-r0[1])/(r0[0]-r0[1])*subplot.yaxis._length;var dy1=r0[1]-r0[0];var dy2=r1[1]-r1[0];axis.range[0]=r0[0]*(1-progress)+progress*r1[0];axis.range[1]=r0[1]*(1-progress)+progress*r1[1];viewBox[3]=subplot.yaxis._length*(1-progress+progress*dy2/dy1)}else{viewBox[1]=0;viewBox[3]=subplot.yaxis._length}ticksAndAnnotations(subplot.xaxis,subplot.yaxis);var xa2=subplot.xaxis;var ya2=subplot.yaxis;var editX=!!xUpdate;var editY=!!yUpdate;var xScaleFactor=editX?xa2._length/viewBox[2]:1,yScaleFactor=editY?ya2._length/viewBox[3]:1;var clipDx=editX?viewBox[0]:0,clipDy=editY?viewBox[1]:0;var fracDx=editX?viewBox[0]/viewBox[2]*xa2._length:0,fracDy=editY?viewBox[1]/viewBox[3]*ya2._length:0;var plotDx=xa2._offset-fracDx,plotDy=ya2._offset-fracDy;subplot.clipRect.call(Drawing.setTranslate,clipDx,clipDy).call(Drawing.setScale,1/xScaleFactor,1/yScaleFactor);subplot.plot.call(Drawing.setTranslate,plotDx,plotDy).call(Drawing.setScale,xScaleFactor,yScaleFactor);Drawing.setPointGroupScale(subplot.zoomScalePts,1/xScaleFactor,1/yScaleFactor);Drawing.setTextPointsScale(subplot.zoomScaleTxt,1/xScaleFactor,1/yScaleFactor)}var onComplete;if(makeOnCompleteCallback){onComplete=makeOnCompleteCallback()}function transitionComplete(){var aobj={};for(var i=0;itransitionOpts.duration){transitionComplete();raf=window.cancelAnimationFrame(doFrame)}else{raf=window.requestAnimationFrame(doFrame)}}t1=Date.now();raf=window.requestAnimationFrame(doFrame);return Promise.resolve()}},{"../../components/drawing":583,"../../registry":817,"./axes":732,"./constants":737,d3:147}],755:[function(require,module,exports){"use strict";var Registry=require("../../registry");var autoType=require("./axis_autotype");var name2id=require("./axis_ids").name2id;module.exports=function handleTypeDefaults(containerIn,containerOut,coerce,data,name){if(name){containerOut._name=name;containerOut._id=name2id(name)}var axType=coerce("type");if(axType==="-"){setAutoType(containerOut,data);if(containerOut.type==="-"){containerOut.type="linear"}else{containerIn.type=containerOut.type}}};function setAutoType(ax,data){if(ax.type!=="-")return;var id=ax._id;var axLetter=id.charAt(0);if(id.indexOf("scene")!==-1)id=axLetter;var d0=getFirstNonEmptyTrace(data,id,axLetter);if(!d0)return;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 i;if(isBoxWithoutPositionCoords(d0,axLetter)){var posLetter=getBoxPosLetter(d0);var boxPositions=[];for(i=0;i0&&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),isBox=Registry.traceIs(trace,"box-violin"),isCandlestick=Registry.traceIs(trace._fullInput||{},"candlestick");return isBox&&!isCandlestick&&axLetter===posLetter&&trace[posLetter]===undefined&&trace[posLetter+"0"]===undefined}},{"../../registry":817,"./axis_autotype":733,"./axis_ids":735}],756:[function(require,module,exports){"use strict";var Registry=require("../registry");var Lib=require("../lib");exports.manageCommandObserver=function(gd,container,commandList,onchange){var ret={};var enabled=true;if(container&&container._commandObserver){ret=container._commandObserver}if(!ret.cache){ret.cache={}}ret.lookupTable={};var binding=exports.hasSimpleAPICommandBindings(gd,commandList,ret.lookupTable);if(container&&container._commandObserver){if(!binding){if(container._commandObserver.remove){container._commandObserver.remove();container._commandObserver=null;return ret}}else{return ret}}if(binding){bindingValueHasChanged(gd,binding,ret.cache);ret.check=function check(){if(!enabled)return;var update=bindingValueHasChanged(gd,binding,ret.cache);if(update.changed&&onchange){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;i0?".":"")+attrName;if(Lib.isPlainObject(attr)){crawl(attr,callback,thisPath,depth+1)}else{callback(thisPath,attrName,attr)}})}},{"../lib":684,"../registry":817}],757:[function(require,module,exports){"use strict";var extendFlat=require("../lib/extend").extendFlat;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(columnmaxAngle}else{return false}};projection.getPath=function(){return d3.geo.path().projection(projection)};projection.getBounds=function(object){return projection.getPath().bounds(object)};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)}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;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":558,"../../components/dragelement":580,"../../components/drawing":583,"../../components/fx":600,"../../lib":684,"../../lib/topojson_utils":711,"../../registry":817,"../cartesian/axes":732,"../cartesian/select":749,"../plots":795,"./constants":760,"./projections":766,"./zoom":767,d3:147,"topojson-client":502}],762:[function(require,module,exports){"use strict";var createGeo=require("./geo");var getSubplotCalcData=require("../../plots/get_data").getSubplotCalcData;var counterRegex=require("../../lib").counterRegex;var GEO="geo";exports.name=GEO;exports.attr=GEO;exports.idRoot=GEO;exports.idRegex=exports.attrRegex=counterRegex(GEO);exports.attributes=require("./layout/attributes");exports.layoutAttributes=require("./layout/layout_attributes");exports.supplyLayoutDefaults=require("./layout/defaults");exports.plot=function plotGeo(gd){var fullLayout=gd._fullLayout;var calcData=gd.calcdata;var geoIds=fullLayout._subplots[GEO];if(window.PlotlyGeoAssets===undefined){window.PlotlyGeoAssets={topojson:{}}}for(var i=0;i0&&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){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){coerce("showsubunits",true);coerce("subunitcolor");coerce("subunitwidth")}if(!isScoped){show=coerce("showframe",true);if(show){coerce("framecolor");coerce("framewidth")}}coerce("bgcolor")}},{"../../subplot_defaults":809,"../constants":760,"./layout_attributes":765}],765:[function(require,module,exports){"use strict";var colorAttrs=require("../../../components/color/attributes");var domainAttrs=require("../../domain").attributes;var constants=require("../constants");var overrideAll=require("../../../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}};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")},{"../../../components/color/attributes":557,"../../../plot_api/edit_types":715,"../../domain":757,"../constants":760}],766:[function(require,module,exports){"use strict";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(++iy^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;ihemilobes[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=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ε;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},{}],767:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");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}return zoomConstructor(geo,projection)}module.exports=createGeoZoom;function initZoom(geo,projection){return d3.behavior.zoom().translate(projection.translate()).scale(projection.scale())}function sync(geo,projection,cb){var id=geo.id;var gd=geo.graphDiv;var userOpts=gd.layout[id];var fullOpts=gd._fullLayout[id];var eventData={};function set(propStr,val){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)}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}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}function zoomClipped(geo,projection){var view={r:projection.rotate(),k:projection.scale()},zoom=initZoom(geo,projection),event=d3_eventDispatch(zoom,"zoomstart","zoom","zoomend"),zooming=0,zoomOn=zoom.on;var zoomPoint;zoom.on("zoomstart",function(){d3.select(this).style(zoomstartStyle);var mouse0=d3.mouse(this),rotate0=projection.rotate(),lastRotate=rotate0,translate0=projection.translate(),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){mouse0=mouse1;zoomPoint=position(projection,mouse0)}else if(position(projection,mouse1)){projection.rotate(rotate0).translate(translate0);var point1=position(projection,mouse1),between=rotateBetween(zoomPoint,point1),newEuler=eulerFromQuaternion(multiply(q,between)),rotateAngles=view.r=unRoll(newEuler,zoomPoint,lastRotate);if(!isFinite(rotateAngles[0])||!isFinite(rotateAngles[1])||!isFinite(rotateAngles[2])){rotateAngles=lastRotate}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")}function position(projection,point){var spherical=projection.invert(point);return spherical&&isFinite(spherical[0])&&isFinite(spherical[1])&&cartesian(spherical)}function quaternionFromEuler(euler){var lambda=.5*euler[0]*radians,phi=.5*euler[1]*radians,gamma=.5*euler[2]*radians,sinLambda=Math.sin(lambda),cosLambda=Math.cos(lambda),sinPhi=Math.sin(phi),cosPhi=Math.cos(phi),sinGamma=Math.sin(gamma),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],a1=a[1],a2=a[2],a3=a[3],b0=b[0],b1=b[1],b2=b[2],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),norm=Math.sqrt(dot(axis,axis)),halfgamma=.5*Math.acos(Math.max(-1,Math.min(1,dot(a,b)))),k=Math.sin(halfgamma)/norm;return norm&&[Math.cos(halfgamma),axis[2]*k,-axis[1]*k,axis[0]*k]}function unRoll(rotateAngles,pt,lastRotate){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],y=pt[1],z=pt[2],f=ptRotated[0],g=ptRotated[1],h=ptRotated[2],theta=Math.atan2(y,x)*degrees,a=Math.sqrt(x*x+y*y),b,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,newPitch1=(Math.atan2(h,f)-Math.atan2(z,b))*degrees,newPitch2=(Math.atan2(h,f)-Math.atan2(z,-b))*degrees;var dist1=angleDistance(lastRotate[0],lastRotate[1],newYaw1,newPitch1),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),dPitch=angleMod(pitch1-pitch0);return Math.sqrt(dYaw*dYaw+dPitch*dPitch)}function angleMod(angle){return(angle%360+540)%360-180}function rotateCartesian(vector,axis,angle){var angleRads=angle*radians,vectorOut=vector.slice(),ax1=axis===0?1:0,ax2=axis===2?1:2,cosa=Math.cos(angleRads),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,phi=spherical[1]*radians,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;iMath.abs(dy)){result.boxEnd[1]=result.boxStart[1]+Math.abs(dx)*dydx*(dy>=0?1:-1);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[2]){result.boxEnd[0]=dataBox[2];result.boxEnd[1]=result.boxStart[1]+(dataBox[2]-result.boxStart[0])*Math.abs(dydx)}}}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}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)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;view.pan(t,0,0,distance*(Math.exp(kzoom)-1))}},true);return camera}},{"3d-view":43,"has-passive-events":379,"mouse-change":402,"mouse-event-offset":403,"mouse-wheel":405,"right-now":465}],774:[function(require,module,exports){"use strict";var overrideAll=require("../../plot_api/edit_types").overrideAll;var fxAttrs=require("../../components/fx/layout_attributes");var Scene=require("./scene");var getSubplotData=require("../get_data").getSubplotData;var Lib=require("../../lib");var xmlnsNamespaces=require("../../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=require("./layout/attributes");exports.layoutAttributes=require("./layout/layout_attributes");exports.baseLayoutAttrOverrides=overrideAll({hoverlabel:fxAttrs.hoverlabel},"plot","nested");exports.supplyLayoutDefaults=require("./layout/defaults");exports.plot=function plotGl3d(gd){var fullLayout=gd._fullLayout;var fullData=gd._fullData;var sceneIds=fullLayout._subplots[GL3D];for(var i=0;i1;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){var bgcolor=coerce("bgcolor"),bgColorCombined=Color.combine(bgcolor,opts.paper_bgcolor);var cameraKeys=["up","center","eye"];for(var j=0;j")}else{tx=selection.textLabel}if(scene.fullSceneLayout.hovermode){Fx.loneHover({x:(.5+.5*pdata[0]/pdata[3])*width,y:(.5-.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})}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,fullLayout,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};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 showNoWebGlMsg(scene)}var relayoutCallback=function(scene){if(scene.fullSceneLayout.dragmode===false)return;var update={};update[scene.id+".camera"]=getLayoutCamera(scene.camera);scene.saveCamera(scene.graphDiv.layout);scene.graphDiv.emit("plotly_relayout",update)};scene.glplot.canvas.addEventListener("mouseup",relayoutCallback.bind(null,scene));scene.glplot.canvas.addEventListener("wheel",relayoutCallback.bind(null,scene),passiveSupported?{passive:false}:false);if(!scene.staticMode){scene.glplot.canvas.addEventListener("webglcontextlost",function(ev){Lib.warn("Lost WebGL context.");ev.preventDefault()})}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:.1,zoomMax:100,mode:"orbit"})}scene.glplot.camera=scene.camera;scene.glplot.oncontextloss=function(){scene.recoverContext()};scene.glplot.onrender=render.bind(null,scene);scene.traces={};return true}function Scene(options,fullLayout){var sceneContainer=document.createElement("div");var plotContainer=options.container;this.graphDiv=options.graphDiv;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;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];this.plotArgs=[[],{},{}];this.axesOptions=createAxesOptions(fullLayout[this.id]);this.spikeOptions=createSpikeOptions(fullLayout[this.id]);this.container=sceneContainer;this.staticMode=!!options.staticPlot;this.pixelRatio=options.plotGlPixelRatio||2;this.dataScale=[1,1,1];this.contourLevels=[[],[],[]];this.convertAnnotations=Registry.getComponentMethod("annotations3d","convert");this.drawAnnotations=Registry.getComponentMethod("annotations3d","draw");if(!initializeGLPlot(this,fullLayout))return}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,scene.fullLayout,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;jdataBounds[1][j]){dataScale[j]=1}else{if(dataBounds[1][j]===dataBounds[0][j]){dataScale[j]=1}else{dataScale[j]=1/(dataBounds[1][j]-dataBounds[0][j])}}}this.dataScale=dataScale;this.convertAnnotations(this);for(i=0;isceneBounds[1][i]){sceneBounds[0][i]=-1;sceneBounds[1][i]=1}else{var d=sceneBounds[1][i]-sceneBounds[0][i];sceneBounds[0][i]-=d/32;sceneBounds[1][i]+=d/32}}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];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];for(i=0;i<3;++i){axis=fullSceneLayout[axisProperties[i]];axisType=axis.type;var axisRatio=axisTypeRatios[axisType];axesScaleRatio[i]=Math.pow(axisRatio.acc,1/axisRatio.count)/dataScale[i]}var axisAutoScaleFactor=4;var aspectRatio;if(fullSceneLayout.aspectmode==="auto"){if(Math.max.apply(null,axesScaleRatio)/Math.min.apply(null,axesScaleRatio)<=axisAutoScaleFactor){aspectRatio=axesScaleRatio}else{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")}fullSceneLayout.aspectratio.x=sceneLayout.aspectratio.x=aspectRatio[0];fullSceneLayout.aspectratio.y=sceneLayout.aspectratio.y=aspectRatio[1];fullSceneLayout.aspectratio.z=sceneLayout.aspectratio.z=aspectRatio[2];this.glplot.aspect=aspectRatio;var domain=fullSceneLayout.domain||null,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"}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};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]]}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]}}}proto.getCamera=function getCamera(){this.glplot.camera.view.recalcMatrix(this.camera.view.lastT());return getLayoutCamera(this.glplot.camera)};proto.setCamera=function setCamera(cameraData){this.glplot.camera.lookAt.apply(this,getOrbitCamera(cameraData))};proto.saveCamera=function saveCamera(layout){var cameraData=this.getCamera(),cameraNestedProp=Lib.nestedProperty(layout,this.id+".camera"),cameraDataLastSave=cameraNestedProp.get(),hasChanged=false;function same(x,y,i,j){var vectors=["up","center","eye"],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)cameraNestedProp.set(cameraData);return hasChanged};proto.updateFx=function(dragmode,hovermode){var camera=this.camera;if(camera){if(dragmode==="orbit"){camera.mode="orbit";camera.keyBindingMode="rotate"}else if(dragmode==="turntable"){camera.up=[0,0,1];camera.mode="turntable";camera.keyBindingMode="rotate"}else{camera.keyBindingMode=dragmode}}this.fullSceneLayout.hovermode=hovermode};proto.toImage=function(format){if(!format)format="png";if(this.staticMode)this.container.appendChild(STATIC_CANVAS);this.glplot.redraw();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);for(var j=0,k=h-1;j0)}function convertOpts(opts){var layout={},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});break;case"symbol":var symbol=opts.symbol,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});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":684,"./convert_text_opts":788}],791:[function(require,module,exports){"use strict";var Lib=require("../../lib");var defaultLine=require("../../components/color").defaultLine;var domainAttrs=require("../domain").attributes;var fontAttrs=require("../font_attributes");var textposition=require("../../traces/scatter/attributes").textposition;var overrideAll=require("../../plot_api/edit_types").overrideAll;var templatedArray=require("../../plot_api/plot_template").templatedArray;var fontAttr=fontAttrs({});fontAttr.family.dflt="Open Sans Regular, Arial Unicode MS Regular";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"},below:{valType:"string",dflt:""},color:{valType:"color",dflt:defaultLine},opacity:{valType:"number",min:0,max:1,dflt:1},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")},{"../../components/color":558,"../../lib":684,"../../plot_api/edit_types":715,"../../plot_api/plot_template":722,"../../traces/scatter/attributes":1015,"../domain":757,"../font_attributes":758}],792:[function(require,module,exports){"use strict";var Lib=require("../../lib");var handleSubplotDefaults=require("../subplot_defaults");var handleArrayContainerDefaults=require("../array_container_defaults");var layoutAttributes=require("./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});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");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":684,"../array_container_defaults":728,"../subplot_defaults":809,"./layout_attributes":791}],793:[function(require,module,exports){"use strict";var mapboxgl=require("mapbox-gl");var Fx=require("../../components/fx");var Lib=require("../../lib");var dragElement=require("../../components/dragelement");var prepSelect=require("../cartesian/select").prepSelect;var constants=require("./constants");var layoutAttributes=require("./layout_attributes");var createMapboxLayer=require("./layers");function Mapbox(opts){this.id=opts.id;this.gd=opts.gd;this.container=opts.container;this.isStatic=opts.staticPlot;var fullLayout=opts.fullLayout;this.uid=fullLayout._uid+"-"+this.id;this.opts=fullLayout[this.id];this.div=null;this.xaxis=null;this.yaxis=null;this.createFramework(fullLayout);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=self.opts=fullLayout[this.id];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=self.opts;var styleObj=self.styleObj=getStyleObj(opts.style);self.accessToken=opts.accesstoken;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});var className=constants.controlContainerClassName;var controlContainer=self.div.getElementsByClassName(className)[0];self.div.removeChild(controlContainer);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;map.on("moveend",function(eventData){if(!self.map)return;var view=self.getView();opts._input.center=opts.center=view.center;opts._input.zoom=opts.zoom=view.zoom;opts._input.bearing=opts.bearing=view.bearing;opts._input.pitch=opts.pitch=view.pitch;if(eventData.originalEvent||wheeling){emitRelayoutFromView(view)}wheeling=false});map.on("wheel",function(){wheeling=true});map.on("mousemove",function(evt){var bb=self.div.getBoundingClientRect();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)});map.on("click",function(evt){Fx.click(gd,evt.originalEvent)});function unhover(){Fx.loneUnhover(fullLayout._toppaper)}map.on("dragstart",unhover);map.on("zoomstart",unhover);map.on("dblclick",function(){gd.emit("plotly_doubleclick",null);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();opts._input.center=opts.center=viewNow.center;opts._input.zoom=opts.zoom=viewNow.zoom;opts._input.bearing=opts.bearing=viewNow.bearing;opts._input.pitch=opts.pitch=viewNow.pitch;emitRelayoutFromView(viewNow)});function emitRelayoutFromView(view){var id=self.id;var evtData={};for(var k in view){evtData[id+"."+k]=view[k]}gd.emit("plotly_relayout",evtData)}self.clearSelect=function(){gd._fullLayout._zoomlayer.selectAll(".select-outline").remove()}};proto.updateMap=function(calcData,fullLayout,resolve,reject){var self=this;var map=self.map;self.rejectOnError(reject);var styleObj=getStyleObj(self.opts.style);if(self.styleObj.id!==styleObj.id){self.styleObj=styleObj;map.setStyle(styleObj.style);map.once("styledata",function(){self.traceHash={};self.updateData(calcData);self.updateLayout(fullLayout);self.resolveOnRender(resolve)})}else{self.updateData(calcData);self.updateLayout(fullLayout);self.resolveOnRender(resolve)}};proto.updateData=function(calcData){var traceHash=this.traceHash;var traceObj,trace,i,j;for(i=0;i=fullLayout.width-20){attrs["text-anchor"]="start";attrs.x=5}else{attrs["text-anchor"]="end";attrs.x=fullLayout._paper.attr("width")-7}linkContainer.attr(attrs);var toolspan=linkContainer.select(".js-link-to-tool"),spacespan=linkContainer.select(".js-link-spacer"),sourcespan=linkContainer.select(".js-sourcelinks");if(gd._context.showSources)gd._context.showSources(gd);if(gd._context.showLink)positionPlayWithData(gd,toolspan);spacespan.text(toolspan.text()&&sourcespan.text()?" - ":"")};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"];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;if(!gd._transitionData)plots.createTransitionData(gd);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);newFullLayout._mapboxAccessToken=context.mapboxAccessToken;if(oldFullLayout._initialAutoSizeIsDone){var oldWidth=oldFullLayout.width,oldHeight=oldFullLayout.height;plots.supplyLayoutGlobalDefaults(newLayout,newFullLayout,formatObj);if(!newLayout.width)newFullLayout.width=oldWidth;if(!newLayout.height)newFullLayout.height=oldHeight;plots.sanitizeMargins(newFullLayout)}else{plots.supplyLayoutGlobalDefaults(newLayout,newFullLayout,formatObj);var missingWidthOrHeight=!newLayout.width||!newLayout.height,autosize=newFullLayout.autosize,autosizable=context.autosizable,initialAutoSize=missingWidthOrHeight&&(autosize||autosizable);if(initialAutoSize)plots.plotAutoSize(gd,newLayout,newFullLayout);else if(missingWidthOrHeight)plots.sanitizeMargins(newFullLayout);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;newFullLayout._dataLength=newData.length;newFullLayout._modules=[];newFullLayout._basePlotModules=[];var subplots=newFullLayout._subplots=emptySubplotLists();var splomAxes=newFullLayout._splomAxes={x:{},y:{}};var splomSubplots=newFullLayout._splomSubplots={};newFullLayout._splomGridDflt={};newFullLayout._requestRangeslider={};newFullLayout._traceUids=getTraceUids(oldFullData,newData);newFullLayout._globalTransforms=(gd._context||{}).globalTransforms;plots.supplyDataDefaults(newData,newFullData,newLayout,newFullLayout);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;i15&&splomYa.length>15&&newFullLayout.shapes.length===0&&newFullLayout.images.length===0;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");plots.linkSubplots(newFullData,newFullLayout,oldFullData,oldFullLayout);plots.cleanPlot(newFullData,newFullLayout,oldFullData,oldFullLayout,oldCalcdata);relinkPrivateKeys(newFullLayout,oldFullLayout);plots.doAutoMargin(gd);var axList=axisIDs.list(gd);for(i=0;i0){var reservedMargins=calculateReservedMargins(gd._boundingBoxMargins),reservedWidth=reservedMargins.left+reservedMargins.right,reservedHeight=reservedMargins.bottom+reservedMargins.top,factor=1-2*frameMargins;var gdBB=fullLayout._container&&fullLayout._container.node?fullLayout._container.node().getBoundingClientRect():{width:fullLayout.width,height:fullLayout.height};newWidth=Math.round(factor*(gdBB.width-reservedWidth));newHeight=Math.round(factor*(gdBB.height-reservedHeight))}else{var computedStyle=isPlotDiv?window.getComputedStyle(gd):{};newWidth=parseFloat(computedStyle.width)||fullLayout.width;newHeight=parseFloat(computedStyle.height)||fullLayout.height}var minWidth=plots.layoutAttributes.width.min,minHeight=plots.layoutAttributes.height.min;if(newWidth1,heightHasChanged=!layout.height&&Math.abs(fullLayout.height-newHeight)>1;if(heightHasChanged||widthHasChanged){if(widthHasChanged)fullLayout.width=newWidth;if(heightHasChanged)fullLayout.height=newHeight}if(!gd._initialAutoSize){gd._initialAutoSize={width:newWidth,height:newHeight}}plots.sanitizeMargins(fullLayout)};function calculateReservedMargins(margins){var resultingMargin={left:0,right:0,bottom:0,top:0},marginName;if(margins){for(marginName in margins){if(margins.hasOwnProperty(marginName)){resultingMargin.left+=margins[marginName].left||0;resultingMargin.right+=margins[marginName].right||0;resultingMargin.bottom+=margins[marginName].bottom||0;resultingMargin.top+=margins[marginName].top||0}}}return resultingMargin}plots.supplyLayoutModuleDefaults=function(layoutIn,layoutOut,fullData,transitionData){var componentsRegistry=Registry.componentsRegistry;var basePlotModules=layoutOut._basePlotModules;var component,i,_module;var Cartesian=Registry.subplotsRegistry.cartesian;for(component in componentsRegistry){_module=componentsRegistry[component];if(_module.includeBasePlot){_module.includeBasePlot(layoutIn,layoutOut)}}if(!basePlotModules.length){basePlotModules.push(Cartesian)}if(layoutOut._has("cartesian")){Registry.getComponentMethod("grid","contentDefaults")(layoutIn,layoutOut);Cartesian.finalizeSubplots(layoutIn,layoutOut)}for(var subplotType in layoutOut._subplots){layoutOut._subplots[subplotType].sort(Lib.subplotSort)}for(i=0;ifullLayout.width*.5)o.l=o.r=0;if(o.b+o.t>fullLayout.height*.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={};setupAutoMargin(fullLayout);var gs=fullLayout._size,oldmargins=JSON.stringify(gs);var ml=Math.max(fullLayout.margin.l||0,0);var mr=Math.max(fullLayout.margin.r||0,0);var mt=Math.max(fullLayout.margin.t||0,0);var mb=Math.max(fullLayout.margin.b||0,0);var pushMargin=fullLayout._pushmargin;var pushMarginIds=fullLayout._pushmarginIds;if(fullLayout.margin.autoexpand!==false){for(var k in pushMargin){if(!pushMarginIds[k])delete pushMargin[k]}pushMargin.base={l:{val:0,size:ml},r:{val:1,size:mr},t:{val:1,size:mt},b:{val:0,size:mb}};for(var k1 in pushMargin){var pushleft=pushMargin[k1].l||{},pushbottom=pushMargin[k1].b||{},fl=pushleft.val,pl=pushleft.size,fb=pushbottom.val,pb=pushbottom.size;for(var k2 in pushMargin){if(isNumeric(pl)&&pushMargin[k2].r){var fr=pushMargin[k2].r.val,pr=pushMargin[k2].r.size;if(fr>fl){var newl=(pl*fr+(pr-fullLayout.width)*fl)/(fr-fl),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,pt=pushMargin[k2].t.size;if(ft>fb){var newb=(pb*ft+(pt-fullLayout.height)*fb)/(ft-fb),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(fullLayout.margin.pad);gs.w=Math.round(fullLayout.width)-gs.l-gs.r;gs.h=Math.round(fullLayout.height)-gs.t-gs.b;if(!fullLayout._replotting&&oldmargins!=="{}"&&oldmargins!==JSON.stringify(fullLayout._size)){if("_redrawFromAutoMarginCount"in fullLayout){fullLayout._redrawFromAutoMarginCount++}else{fullLayout._redrawFromAutoMarginCount=1}return Registry.call("plot",gd)}};plots.graphJson=function(gd,dataonly,mode,output,useDefaults){if(useDefaults&&dataonly&&!gd._fullData||useDefaults&&!dataonly&&!gd._fullLayout){plots.supplyDefaults(gd)}var data=useDefaults?gd._fullData:gd.data,layout=useDefaults?gd._fullLayout:gd.layout,frames=(gd._transitionData||{})._frames;function stripObj(d){if(typeof d==="function"){return null}if(Lib.isPlainObject(d)){var o={},v,src;for(v in d){if(typeof d[v]==="function"||["_","["].indexOf(v.charAt(0))!==-1){continue}if(mode==="keepdata"){if(v.substr(v.length-3)==="src"){continue}}else if(mode==="keepstream"){src=d[v+"src"];if(typeof src==="string"&&src.indexOf(":")>0){if(!Lib.isPlainObject(d.stream)){continue}}}else if(mode!=="keepall"){src=d[v+"src"];if(typeof src==="string"&&src.indexOf(":")>0){continue}}o[v]=stripObj(d[v])}return o}if(Array.isArray(d)){return d.map(stripObj)}if(Lib.isJSDate(d))return Lib.ms2DateTimeLocal(+d);return d}var obj={data:(data||[]).map(function(v){var d=stripObj(v);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)};plots.modifyFrames=function(gd,operations){var i,op,frame;var _frames=gd._transitionData._frames;var _frameHash=gd._transitionData._frameHash;for(i=0;i0){gd._transitioningWithDuration=true}gd._transitionData._interruptCallbacks.push(function(){aborted=true});if(frameOpts.redraw){gd._transitionData._interruptCallbacks.push(function(){return Registry.call("redraw",gd)})}gd._transitionData._interruptCallbacks.push(function(){gd.emit("plotly_transitioninterrupted",[])});var numCallbacks=0;var numCompleted=0;function makeCallback(){numCallbacks++;return function(){numCompleted++;if(!aborted&&numCompleted===numCallbacks){completeTransition(resolve)}}}var traceTransitionOpts;var j;var basePlotModules=gd._fullLayout._basePlotModules;var hasAxisTransition=false;if(layout){for(j=0;j=0;j--){if(transforms[j].enabled){trace._indexToPoints=transforms[j]._indexToPoints;break}}if(_module&&_module.calc){cd=_module.calc(gd,trace)}}if(!Array.isArray(cd)||!cd[0]){cd=[{x:BADNUM,y:BADNUM}]}if(!cd[0].t)cd[0].t={};cd[0].trace=trace;calcdata[i]=cd}for(i=0;i=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="' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '";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){var title=svg.select("g.title-group text").style(fontStyle).text(axisConfig.title);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;i0)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":656,"../../../lib":684,d3:147}],805:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../../lib");var Color=require("../../../components/color");var micropolar=require("./micropolar");var UndoManager=require("./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"),paperDiv=container.selectAll(".svg-container"),paper=_gd.framework&&_gd.framework.svg&&_gd.framework.svg(),dflts={width:800,height:600,paper_bgcolor:Color.background,_container:container,_paperdiv:paperDiv,_paper:paper};_gd._fullLayout=extendDeepAll(dflts,_gd.layout)}},{"../../../components/color":558,"../../../lib":684,"./micropolar":804,"./undo_manager":806,d3:147}],806:[function(require,module,exports){"use strict";module.exports=function UndoManager(){var undoCommands=[],index=-1,isExecuting=false,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 indexarSector){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;var xOffset2=_this.xOffset2=gs.l+gs.w*xDomain2[0];var yOffset2=_this.yOffset2=gs.t+gs.h*(1-yDomain2[1]);var radius=_this.radius=xLength2/dxSectorBBox;var cx=_this.cx=xOffset2-radius*sectorBBox[0];var cy=_this.cy=yOffset2+radius*sectorBBox[3];var cxx=_this.cxx=cx-xOffset2;var cyy=_this.cyy=cy-yOffset2;var mockOpts={anchor:"free",position:0,_counteraxis:true,automargin:false};_this.radialAxis=Lib.extendFlat({},polarLayout.radialaxis,mockOpts,{_axislayer:layers["radial-axis"],_gridlayer:layers["radial-grid"],_id:"x",_pos:0,side:{counterclockwise:"top",clockwise:"bottom"}[polarLayout.radialaxis.side],domain:[0,radius/gs.w]});_this.angularAxis=Lib.extendFlat({},polarLayout.angularaxis,mockOpts,{_axislayer:layers["angular-axis"],_gridlayer:layers["angular-grid"],_id:"angular",_pos:0,side:"right",domain:[0,Math.PI],autorange:false});_this.doAutoRange(fullLayout,polarLayout);_this.updateAngularAxis(fullLayout,polarLayout);_this.updateRadialAxis(fullLayout,polarLayout);_this.updateRadialAxisTitle(fullLayout,polarLayout);var radialRange=_this.radialAxis.range;var rSpan=radialRange[1]-radialRange[0];var xaxis=_this.xaxis={type:"linear",_id:"x",range:[sectorBBox[0]*rSpan,sectorBBox[2]*rSpan],domain:xDomain2};Axes.setConvert(xaxis,fullLayout);xaxis.setScale();var yaxis=_this.yaxis={type:"linear",_id:"y",range:[sectorBBox[1]*rSpan,sectorBBox[3]*rSpan],domain:yDomain2};Axes.setConvert(yaxis,fullLayout);yaxis.setScale();xaxis.isPtWithinRange=function(d){return _this.isPtWithinSector(d)};yaxis.isPtWithinRange=function(){return true};_this.clipPaths.forTraces.select("path").attr("d",pathSectorClosed(radius,sector,_this.vangles)).attr("transform",strTranslate(cxx,cyy));layers.frontplot.attr("transform",strTranslate(xOffset2,yOffset2)).call(Drawing.setClipUrl,_this._hasClipOnAxisFalse?null:_this.clipIds.forTraces);layers.bg.attr("d",pathSectorClosed(radius,sector,_this.vangles)).attr("transform",strTranslate(cx,cy)).call(Color.fill,polarLayout.bgcolor);_this.framework.selectAll(".crisp").classed("crisp",0)};proto.doAutoRange=function(fullLayout,polarLayout){var radialLayout=polarLayout.radialaxis;var ax=this.radialAxis;setScale(ax,radialLayout,fullLayout);doAutoRange(ax);radialLayout.range=ax.range.slice();radialLayout._input.range=ax.range.slice()};proto.updateRadialAxis=function(fullLayout,polarLayout){var _this=this;var gd=_this.gd;var layers=_this.layers;var radius=_this.radius;var cx=_this.cx;var cy=_this.cy;var radialLayout=polarLayout.radialaxis;var sector=polarLayout.sector;var a0=wrap360(sector[0]);var ax=_this.radialAxis;_this.fillViewInitialKey("radialaxis.angle",radialLayout.angle);_this.fillViewInitialKey("radialaxis.range",ax.range.slice());if(ax.tickangle==="auto"&&(a0>90&&a0<=270)){ax.tickangle=180}ax._transfn=function(d){return"translate("+ax.l2p(d.x)+",0)"};ax._gridpath=function(d){var r=ax.r2p(d.x);return pathSector(r,sector,_this.vangles)};var newTickLayout=strTickLayout(radialLayout);if(_this.radialTickLayout!==newTickLayout){layers["radial-axis"].selectAll(".xtick").remove();_this.radialTickLayout=newTickLayout}Axes.doTicksSingle(gd,ax,true);var angle=_this.radialAxisAngle=_this.vangles?rad2deg(snapToVertexAngle(deg2rad(radialLayout.angle),_this.vangles)):radialLayout.angle;var trans=strTranslate(cx,cy)+strRotate(-angle);updateElement(layers["radial-axis"],radialLayout.showticklabels||radialLayout.ticks,{transform:trans});updateElement(layers["radial-grid"],radialLayout.showgrid,{transform:strTranslate(cx,cy)}).selectAll("path").attr("transform",null);updateElement(layers["radial-line"].select("line"),radialLayout.showline,{x1:0,y1:0,x2:radius,y2:0,transform:trans}).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;if(radialLayout.title){var h=Drawing.bBox(_this.layers["radial-axis"].node()).height;var ts=radialLayout.titlefont.size;pad=radialLayout.side==="counterclockwise"?-h-ts*.4:h+ts*.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 cx=_this.cx;var cy=_this.cy;var angularLayout=polarLayout.angularaxis;var sector=polarLayout.sector;var sectorInRad=sector.map(deg2rad);var ax=_this.angularAxis;_this.fillViewInitialKey("angularaxis.rotation",angularLayout.rotation);function c2rad(d){return ax.c2rad(d.x,"degrees")}function rad2xy(rad){return[radius*Math.cos(rad),radius*Math.sin(rad)]}if(ax.type==="linear"){if(isFullCircle(sector)){ax.range=sector.slice()}else{ax.range=sectorInRad.map(ax.unTransformRad).map(rad2deg)}if(ax.thetaunit==="radians"){ax.tick0=rad2deg(ax.tick0);ax.dtick=rad2deg(ax.dtick)}}else if(ax.type==="category"){var period=angularLayout.period?Math.max(angularLayout.period,angularLayout._categories.length):angularLayout._categories.length;ax.range=[0,period];ax._tickFilter=function(d){return isAngleInSector(c2rad(d),sector)}}setScale(ax,angularLayout,fullLayout);ax._transfn=function(d){var rad=c2rad(d);var xy=rad2xy(rad);var out=strTranslate(cx+xy[0],cy-xy[1]);var sel=d3.select(this);if(sel&&sel.node()&&sel.classed("ticks")){out+=strRotate(-rad2deg(rad))}return out};ax._gridpath=function(d){var rad=c2rad(d);var xy=rad2xy(rad);return"M0,0L"+-xy[0]+","+xy[1]};var offset4fontsize=angularLayout.ticks!=="outside"?.7:.5;ax._labelx=function(d){var rad=c2rad(d);var labelStandoff=ax._labelStandoff;var pad=ax._pad;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};ax._labely=function(d){var rad=c2rad(d);var labelStandoff=ax._labelStandoff;var labelShift=ax._labelShift;var pad=ax._pad;var offset4tx=d.dy+d.fontSize*MID_SHIFT-labelShift;var offset4tick=-Math.sin(rad)*(labelStandoff+pad+offset4fontsize*d.fontSize);return offset4tx+offset4tick};ax._labelanchor=function(angle,d){var rad=c2rad(d);return signSin(rad)===0?signCos(rad)>0?"start":"end":"middle"};var newTickLayout=strTickLayout(angularLayout);if(_this.angularTickLayout!==newTickLayout){layers["angular-axis"].selectAll(".angulartick").remove();_this.angularTickLayout=newTickLayout}Axes.doTicksSingle(gd,ax,true);var vangles;if(polarLayout.gridshape==="linear"){vangles=ax._vals.map(c2rad);if(angleDelta(vangles[0],vangles[1])<0){vangles=vangles.slice().reverse()}}else{vangles=null}_this.vangles=vangles;updateElement(layers["angular-line"].select("path"),angularLayout.showline,{d:pathSectorClosed(radius,sector,vangles),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,polarLayout);this.updateRadialDrag(fullLayout,polarLayout);this.updateMainDrag(fullLayout,polarLayout)}};proto.updateMainDrag=function(fullLayout,polarLayout){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 cx=_this.cx;var cy=_this.cy;var cxx=_this.cxx;var cyy=_this.cyy;var sector=polarLayout.sector;var vangles=_this.vangles;var chw=constants.cornerHalfWidth;var chl=constants.cornerLen/2;var mainDrag=dragBox.makeDragger(layers,"path","maindrag","crosshair");d3.select(mainDrag).attr("d",pathSectorClosed(radius,sector,vangles)).attr("transform",strTranslate(cx,cy));var dragOpts={element:mainDrag,gd:gd,subplot:_this.id,plotinfo:{xaxis:_this.xaxis,yaxis:_this.yaxis},xaxes:[_this.xaxis],yaxes:[_this.yaxis]};var x0,y0;var r0,r1;var path0,dimmed,lum;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 _pathSectorClosed(r){return pathSectorClosed(r,sector,vangles)}function pathCorner(r,a){if(r===0)return _pathSectorClosed(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"}function pathCornerForPolygons(r,va0,va1){if(r===0)return _pathSectorClosed(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){dx=chl;dy=chw}else{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=_pathSectorClosed(radius);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)}function clampAndSetR0R1(rr0,rr1){rr1=Math.min(rr1,radius);if(rr0MINZOOM){if(rr00?adelta:Infinity});var i1=Lib.mod(i0+1,vangles.length);return[vangles[i0],vangles[i1]]}function findPolygonRadius(x,y,va0,va1){var xy=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);var vangles1=findEnclosingVertexAngles(a1);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+_pathSectorClosed(r1)+_pathSectorClosed(r0);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 radialAxis=_this.radialAxis;var radialRange=radialAxis.range;var drange=radialRange[1]-radialRange[0];var updateObj={};updateObj[_this.id+".radialaxis.range"]=[radialRange[0]+r0*drange/radius,radialRange[0]+r1*drange/radius];Registry.call("relayout",gd,updateObj)}dragOpts.prepFn=function(evt,startX,startY){var dragModeNow=gd._fullLayout.dragmode;var bbox=mainDrag.getBoundingClientRect();x0=startX-bbox.left;y0=startY-bbox.top;if(vangles){var offset=findPolygonOffset(radius,sector,vangles);x0+=cxx+offset[0];y0+=cyy+offset[1]}switch(dragModeNow){case"zoom":if(vangles){dragOpts.moveFn=zoomMoveForPolygons}else{dragOpts.moveFn=zoomMove}dragOpts.doneFn=zoomDone;zoomPrep(evt,startX,startY);break;case"select":case"lasso":prepSelect(evt,startX,startY,dragOpts,dragModeNow);break}};dragOpts.clickFn=function(numClicks,evt){dragBox.removeZoombox(gd);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("relayout",gd,updateObj)}Fx.click(gd,evt,_this.id)};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){var _this=this;var gd=_this.gd;var layers=_this.layers;var radius=_this.radius;var cx=_this.cx;var cy=_this.cy;var radialAxis=_this.radialAxis;var radialLayout=polarLayout.radialaxis;var angle0=deg2rad(_this.radialAxisAngle);var range0=radialAxis.range.slice();var drange=range0[1]-range0[0];var bl=constants.radialDragBoxSize;var bl2=bl/2;if(!radialLayout.visible)return;var radialDrag=dragBox.makeRectDragger(layers,"radialdrag","crosshair",-bl2,-bl2,bl,bl);var dragOpts={element:radialDrag,gd:gd};var tx=cx+(radius+bl2)*Math.cos(angle0);var ty=cy-(radius+bl2)*Math.sin(angle0);d3.select(radialDrag).attr("transform",strTranslate(tx,ty));var moveFn2;var angle1;var rng1;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)));if(!isNaN(comp)){moveFn2=comp<.5?rotateMove:rerangeMove}}}function doneFn(){if(angle1!==null){Registry.call("relayout",gd,_this.id+".radialaxis.angle",angle1)}else if(rng1!==null){Registry.call("relayout",gd,_this.id+".radialaxis.range[1]",rng1)}}function rotateMove(dx,dy){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){var dr=Lib.dot([dx,-dy],[Math.cos(angle0),Math.sin(angle0)]);var rprime=range0[1]-drange*dr/radius*.75;if(drange>0!==rprime>range0[0])return;rng1=radialAxis.range[1]=rprime;Axes.doTicksSingle(gd,_this.radialAxis,true);layers["radial-grid"].attr("transform",strTranslate(cx,cy)).selectAll("path").attr("transform",null);var rSpan=rng1-range0[0];var sectorBBox=_this.sectorBBox;_this.xaxis.range=[sectorBBox[0]*rSpan,sectorBBox[2]*rSpan];_this.yaxis.range=[sectorBBox[1]*rSpan,sectorBBox[3]*rSpan];_this.xaxis.setScale();_this.yaxis.setScale();for(var k in _this.traceHash){var moduleCalcData=_this.traceHash[k];var moduleCalcDataVisible=Lib.filterVisible(moduleCalcData);var _module=moduleCalcData[0][0].trace._module;var polarLayoutNow=gd._fullLayout[_this.id];_module.plot(gd,_this,moduleCalcDataVisible,polarLayoutNow);if(!Registry.traceIs(k,"gl")){for(var i=0;i=radialRange[0]){r0=radialRange[0];r1=radialRange[1]}else{r0=radialRange[1];r1=radialRange[0]}if(vangles){var polygonIn=polygonTester(makePolygon(r0,sector,vangles));var polygonOut=polygonTester(makePolygon(r1,sector,vangles));var xy=[r*Math.cos(d.rad),r*Math.sin(d.rad)];return polygonOut.contains(xy)&&!polygonIn.contains(xy)}return r>=r0&&r<=r1};proto.fillViewInitialKey=function(key,val){if(!(key in this.viewInitial)){this.viewInitial[key]=val}};function setScale(ax,axLayout,fullLayout){Axes.setConvert(ax,fullLayout);ax._min=axLayout._min;ax._max=axLayout._max;ax.setScale()}function strTickLayout(axLayout){var out=axLayout.ticks+String(axLayout.ticklen)+String(axLayout.showticklabels);if("side"in axLayout)out+=axLayout.side;return out}function computeSectorBBox(sector){var s0=sector[0];var s1=sector[1];var arc=s1-s0;var a0=wrap360(s0);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 isAngleInSector(rad,sector){if(isFullCircle(sector))return true;var s0=wrap360(sector[0]);var s1=wrap360(sector[1]);if(s0>s1)s1+=360;var deg=wrap360(rad2deg(rad));var nextTurnDeg=deg+360;return deg>=s0&°<=s1||nextTurnDeg>=s0&&nextTurnDeg<=s1}function snapToVertexAngle(a,vangles){function angleDeltaAbs(va){return Math.abs(angleDelta(a,va))}var ind=findIndexOfMin(vangles,angleDeltaAbs);return vangles[ind]}function angleDelta(a,b){var d=b-a;return Math.atan2(Math.sin(d),Math.cos(d))}function findIndexOfMin(arr,fn){fn=fn||Lib.identity;var min=Infinity;var ind;for(var i=0;i1e-10?v:0}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":558,"../../components/dragelement":580,"../../components/drawing":583,"../../components/fx":600,"../../components/titles":649,"../../constants/alignment":656,"../../lib":684,"../../lib/polygon":696,"../../lib/setcursor":704,"../../registry":817,"../cartesian/autorange":731,"../cartesian/axes":732,"../cartesian/dragbox":740,"../cartesian/select":749,"../plots":795,"./constants":796,"./helpers":797,d3:147,tinycolor2:499}],808:[function(require,module,exports){"use strict";function sortModules(a,b){if(a==="splom")return-1;if(b==="splom")return 1;return 0}function sortBasePlotModules(a,b){return sortModules(a.name,b.name)}module.exports={sortBasePlotModules:sortBasePlotModules,sortModules:sortModules}},{}],809:[function(require,module,exports){"use strict";var Lib=require("../lib");var Template=require("../plot_api/plot_template");var handleDomainDefaults=require("./domain").defaults;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=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}}},{"../../../components/color":558,"../../../plot_api/plot_template":722,"../../subplot_defaults":809,"./axis_defaults":813,"./layout_attributes":815}],815:[function(require,module,exports){"use strict";var colorAttrs=require("../../../components/color/attributes");var domainAttrs=require("../../domain").attributes;var ternaryAxesAttrs=require("./axis_attributes");var overrideAll=require("../../../plot_api/edit_types").overrideAll;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")},{"../../../components/color/attributes":557,"../../../plot_api/edit_types":715,"../../domain":757,"./axis_attributes":812}],816:[function(require,module,exports){"use strict";var d3=require("d3");var tinycolor=require("tinycolor2");var Registry=require("../../registry");var Lib=require("../../lib");var _=Lib._;var Color=require("../../components/color");var Drawing=require("../../components/drawing");var setConvert=require("../cartesian/set_convert");var extendFlat=require("../../lib/extend").extendFlat;var Plots=require("../plots");var Axes=require("../cartesian/axes");var dragElement=require("../../components/dragelement");var Fx=require("../../components/fx");var Titles=require("../../components/titles");var prepSelect=require("../cartesian/select").prepSelect;var clearSelect=require("../cartesian/select").clearSelect;var constants=require("../cartesian/constants");function Ternary(options,fullLayout){this.id=options.id;this.graphDiv=options.graphDiv;this.init(fullLayout);this.makeFramework(fullLayout)}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;iw_over_h*hmax){h=hmax;w=h*w_over_h}else{w=wmax;h=w/w_over_h}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;_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};var yDomain0=_this.yaxis.domain[0];var aaxis=_this.aaxis=extendFlat({},ternaryLayout.aaxis,{visible:true,range:[amin,sum-bmin-cmin],side:"left",_counterangle:30,tickangle:(+ternaryLayout.aaxis.tickangle||0)-30,domain:[yDomain0,yDomain0+yDomainFinal*w_over_h],_axislayer:_this.layers.aaxis,_gridlayer:_this.layers.agrid,_pos:0,_id:"y",_length:w,_gridpath:"M0,0l"+h+",-"+w/2,automargin:false});setConvert(aaxis,_this.graphDiv._fullLayout);aaxis.setScale();var baxis=_this.baxis=extendFlat({},ternaryLayout.baxis,{visible:true,range:[sum-amin-cmin,bmin],side:"bottom",_counterangle:30,domain:_this.xaxis.domain,_axislayer:_this.layers.baxis,_gridlayer:_this.layers.bgrid,_counteraxis:_this.aaxis,_pos:0,_id:"x",_length:w,_gridpath:"M0,0l-"+w/2+",-"+h,automargin:false});setConvert(baxis,_this.graphDiv._fullLayout);baxis.setScale();aaxis._counteraxis=baxis;var caxis=_this.caxis=extendFlat({},ternaryLayout.caxis,{visible:true,range:[sum-amin-bmin,cmin],side:"right",_counterangle:30,tickangle:(+ternaryLayout.caxis.tickangle||0)+30,domain:[yDomain0,yDomain0+yDomainFinal*w_over_h],_axislayer:_this.layers.caxis,_gridlayer:_this.layers.cgrid,_counteraxis:_this.baxis,_pos:0,_id:"y",_length:w,_gridpath:"M0,0l-"+h+","+w/2,automargin:false});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);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.plotContainer.selectAll(".crisp").classed("crisp",false);_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)};proto.drawAxes=function(doTitles){var _this=this,gd=_this.graphDiv,titlesuffix=_this.id.substr(7)+"title",aaxis=_this.aaxis,baxis=_this.baxis,caxis=_this.caxis;Axes.doTicksSingle(gd,aaxis,true);Axes.doTicksSingle(gd,baxis,true);Axes.doTicksSingle(gd,caxis,true);if(doTitles){var apad=Math.max(aaxis.showticklabels?aaxis.tickfont.size/2:0,(caxis.showticklabels?caxis.tickfont.size*.75:0)+(caxis.ticks==="outside"?caxis.ticklen*.87:0));_this.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.titlefont.size/3-apad,"text-anchor":"middle"}});var bpad=(baxis.showticklabels?baxis.tickfont.size:0)+(baxis.ticks==="outside"?baxis.ticklen:0)+3;_this.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.titlefont.size*.83+bpad,"text-anchor":"middle"}});_this.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.titlefont.size*.83+bpad,"text-anchor":"middle"}})}};var CLEN=constants.MINZOOM/2+.87;var BLPATH="m-0.87,.5h"+CLEN+"v3h-"+(CLEN+5.2)+"l"+(CLEN/2+2.6)+",-"+(CLEN*.87+4.5)+"l2.6,1.5l-"+CLEN/2+","+CLEN*.87+"Z";var BRPATH="m0.87,.5h-"+CLEN+"v3h"+(CLEN+5.2)+"l-"+(CLEN/2+2.6)+",-"+(CLEN*.87+4.5)+"l-2.6,1.5l"+CLEN/2+","+CLEN*.87+"Z";var TOPPATH="m0,1l"+CLEN/2+","+CLEN*.87+"l2.6,-1.5l-"+(CLEN/2+2.6)+",-"+(CLEN*.87+4.5)+"l-"+(CLEN/2+2.6)+","+(CLEN*.87+4.5)+"l2.6,1.5l"+CLEN/2+",-"+CLEN*.87+"Z";var STARTMARKER="m0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z";var SHOWZOOMOUTTIP=true;proto.initInteractions=function(){var _this=this,dragger=_this.layers.plotbg.select("path").node(),gd=_this.graphDiv,zoomContainer=gd._fullLayout._zoomlayer;var dragOptions={element:dragger,gd:gd,plotinfo:{xaxis:_this.xaxis,yaxis:_this.yaxis},subplot:_this.id,prepFn:function(e,startX,startY){dragOptions.xaxes=[_this.xaxis];dragOptions.yaxes=[_this.yaxis];var dragModeNow=gd._fullLayout.dragmode;if(e.shiftKey){if(dragModeNow==="pan")dragModeNow="zoom";else dragModeNow="pan"}if(dragModeNow==="lasso")dragOptions.minDrag=1;else dragOptions.minDrag=undefined;if(dragModeNow==="zoom"){dragOptions.moveFn=zoomMove;dragOptions.doneFn=zoomDone;zoomPrep(e,startX,startY)}else if(dragModeNow==="pan"){dragOptions.moveFn=plotDrag;dragOptions.doneFn=dragDone;panPrep();clearSelect(zoomContainer)}else if(dragModeNow==="select"||dragModeNow==="lasso"){prepSelect(e,startX,startY,dragOptions,dragModeNow)}},clickFn:function(numClicks,evt){removeZoombox(gd);if(numClicks===2){var attrs={};attrs[_this.id+".aaxis.min"]=0;attrs[_this.id+".baxis.min"]=0;attrs[_this.id+".caxis.min"]=0;gd.emit("plotly_doubleclick",null);Registry.call("relayout",gd,attrs)}Fx.click(gd,evt,_this.id)}};var x0,y0,mins0,span0,mins,lum,path0,dimmed,zb,corners;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>.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,y1=y0+dy0,afrac=Math.max(0,Math.min(1,getAFrac(x0,y0),getAFrac(x1,y1))),bfrac=Math.max(0,Math.min(1,getBFrac(x0,y0),getBFrac(x1,y1))),cfrac=Math.max(0,Math.min(1,getCFrac(x0,y0),getCFrac(x1,y1))),xLeft=(afrac/2+cfrac)*_this.w,xRight=(1-afrac/2-bfrac)*_this.w,xCenter=(xLeft+xRight)/2,xSpan=xRight-xLeft,yBottom=(1-afrac)*_this.h,yTop=yBottom-xSpan/w_over_h;if(xSpan.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;var attrs={};attrs[_this.id+".aaxis.min"]=mins.a;attrs[_this.id+".baxis.min"]=mins.b;attrs[_this.id+".caxis.min"]=mins.c;Registry.call("relayout",gd,attrs);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,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(),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}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);_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);_this.plotContainer.selectAll(".crisp").classed("crisp",false);if(_this._hasClipOnAxisFalse){_this.plotContainer.select(".scatterlayer").selectAll(".trace").call(Drawing.hideOutsideRangePoints,_this)}}function dragDone(){var attrs={};attrs[_this.id+".aaxis.min"]=mins.a;attrs[_this.id+".baxis.min"]=mins.b;attrs[_this.id+".caxis.min"]=mins.c;Registry.call("relayout",gd,attrs)}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":558,"../../components/dragelement":580,"../../components/drawing":583,"../../components/fx":600,"../../components/titles":649,"../../lib":684,"../../lib/extend":673,"../../registry":817,"../cartesian/axes":732,"../cartesian/constants":737,"../cartesian/select":749,"../cartesian/set_convert":750,"../plots":795,d3:147,tinycolor2:499}],817:[function(require,module,exports){"use strict";var Loggers=require("./lib/loggers");var noop=require("./lib/noop");var pushUnique=require("./lib/push_unique");var isPlainObject=require("./lib/is_plain_object");var ExtendModule=require("./lib/extend");var basePlotAttributes=require("./plots/attributes");var baseLayoutAttributes=require("./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.register=function register(_modules){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!")}}};exports.getModule=function(trace){var _module=exports.modules[getTraceType(trace)];if(!_module)return false;return _module._module};exports.traceIs=function(traceType,category){traceType=getTraceType(traceType);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]};exports.getTransformIndices=function(data,type){var indices=[];var transforms=data.transforms||[];for(var i=0;i-1}module.exports=function clonePlot(graphObj,options){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"){newLayout.annotations=[];var keys=Object.keys(newLayout);for(i=0;i")!==-1){return""}return hiddenDiv.html(d).text()});hiddenDiv.remove();return replaced}function xmlEntityEncode(str){return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g,"&")}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;svg.insert("rect",":first-child").call(Drawing.setRect,0,0,width,height).call(Color.fill,fullLayout.paper_bgcolor);var basePlotModules=fullLayout._basePlotModules||[];for(i=0;i=2?roundWithLine(v):v>vc?Math.ceil(v):Math.floor(v)}if(!gd._context.staticPlot){var op=Color.opacity(di.mc||trace.marker.color),fixpx=op<1||lw>.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);appendBarText(gd,bar,d,i,x0,x1,y0,y1);if(plotinfo.layerClipId){Drawing.hideOutsideRangePoint(d[i],bar.select("text"),xa,ya,trace.xcalendar,trace.ycalendar)}});var hasClipOnAxisFalse=d[0].trace.cliponaxis===false;Drawing.setClipUrl(sel,hasClipOnAxisFalse?null:plotinfo.layerClipId)});Registry.getComponentMethod("errorbars","plot")(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","data-notex":1}).call(Drawing.font,textFont).call(svgTextUtils.convertToTspans,gd);return textSelection}var trace=calcTrace[0].trace,orientation=trace.orientation;var text=getText(trace,i);textPosition=getTextPosition(trace,i);if(!text||textPosition==="none"){bar.select("text").remove();return}var textFont=getTextFont(trace,i,gd._fullLayout.font),insideTextFont=getInsideTextFont(trace,i,textFont),outsideTextFont=getOutsideTextFont(trace,i,textFont);var barmode=gd._fullLayout.barmode,inStackMode=barmode==="stack",inRelativeMode=barmode==="relative",inStackOrRelativeMode=inStackMode||inRelativeMode,calcBar=calcTrace[i],isOutmostBar=!inStackOrRelativeMode||calcBar._outmost,barWidth=Math.abs(x1-x0)-2*TEXTPAD,barHeight=Math.abs(y1-y0)-2*TEXTPAD,textSelection,textBB,textWidth,textHeight;if(textPosition==="outside"){if(!isOutmostBar)textPosition="inside"}if(textPosition==="auto"){if(isOutmostBar){textPosition="inside";textSelection=appendTextNode(bar,text,insideTextFont);textBB=Drawing.bBox(textSelection.node()),textWidth=textBB.width,textHeight=textBB.height;var textHasSize=textWidth>0&&textHeight>0,fitsInside=textWidth<=barWidth&&textHeight<=barHeight,fitsInsideIfRotated=textWidth<=barHeight&&textHeight<=barWidth,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}}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){var textWidth=textBB.width,textHeight=textBB.height,textX=(textBB.left+textBB.right)/2,textY=(textBB.top+textBB.bottom)/2,barWidth=Math.abs(x1-x0),barHeight=Math.abs(y1-y0),targetWidth,targetHeight,targetX,targetY;var textpad;if(barWidth>2*TEXTPAD&&barHeight>2*TEXTPAD){textpad=TEXTPAD;barWidth-=2*textpad;barHeight-=2*textpad}else textpad=0;var rotate,scale;if(textWidth<=barWidth&&textHeight<=barHeight){rotate=false;scale=1}else if(textWidth<=barHeight&&textHeight<=barWidth){rotate=true;scale=1}else if(textWidthy0){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),textpad;if(barWidth>2*TEXTPAD){textpad=TEXTPAD}var scale=1;if(constrained){scale=orientation==="h"?Math.min(1,barWidth/textBB.height):Math.min(1,barWidth/textBB.width)}var textX=(textBB.left+textBB.right)/2,textY=(textBB.top+textBB.bottom)/2,targetWidth,targetHeight,targetX,targetY;targetWidth=scale*textBB.width;targetHeight=scale*textBB.height;if(orientation==="h"){if(x1y0){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,transformRotate,transformTranslate;if(scale<1)transformScale="scale("+scale+") ";else{scale=1;transformScale=""}transformRotate=rotate?"rotate("+rotate+" "+textX+" "+textY+") ":"";var translateX=targetX-scale*textX,translateY=targetY-scale*textY;transformTranslate="translate("+translateX+" "+translateY+")";return transformTranslate+transformScale+transformRotate}function getText(trace,index){var value=getValue(trace.text,index);return coerceString(attributeText,value)}function getTextPosition(trace,index){var value=getValue(trace.textposition,index);return coerceEnumerated(attributeTextPosition,value)}function getTextFont(trace,index,defaultValue){return getFontValue(attributeTextFont,trace.textfont,index,defaultValue)}function getInsideTextFont(trace,index,defaultValue){return getFontValue(attributeInsideTextFont,trace.insidetextfont,index,defaultValue)}function getOutsideTextFont(trace,index,defaultValue){return getFontValue(attributeOutsideTextFont,trace.outsidetextfont,index,defaultValue)}function getFontValue(attributeDefinition,attributeValue,index,defaultValue){attributeValue=attributeValue||{};var familyValue=getValue(attributeValue.family,index),sizeValue=getValue(attributeValue.size,index),colorValue=getValue(attributeValue.color,index);return{family:coerceString(attributeDefinition.family,familyValue,defaultValue.family),size:coerceNumber(attributeDefinition.size,sizeValue,defaultValue.size),color:coerceColor(attributeDefinition.color,colorValue,defaultValue.color)}}function getValue(arrayOrScalar,index){var value;if(!Array.isArray(arrayOrScalar))value=arrayOrScalar;else if(indexmax;if(!isOutOfBounds)return value}return defaultValue!==undefined?defaultValue:attributeDefinition.dflt}function coerceColor(attributeDefinition,value,defaultValue){if(tinycolor(value).isValid())return value;return defaultValue!==undefined?defaultValue:attributeDefinition.dflt}},{"../../components/color":558,"../../components/drawing":583,"../../lib":684,"../../lib/svg_text_utils":708,"../../registry":817,"./attributes":827,d3:147,"fast-isnumeric":214,tinycolor2:499}],835:[function(require,module,exports){"use strict";module.exports=function selectPoints(searchInfo,polygon){var cd=searchInfo.cd;var xa=searchInfo.xaxis;var ya=searchInfo.yaxis;var selection=[];var i;if(polygon===false){for(i=0;isMax+sTiny||!isNumeric(sMin))){padded=true;expandRange(sRange,newValue)}}for(var i=0;i1||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 textFont;if(tx.classed("bartext-inside")){textFont=trace.insidetextfont}else if(tx.classed("bartext-outside")){textFont=trace.outsidetextfont}if(!textFont)textFont=trace.textfont;function cast(k){var cont=textFont[k];return Array.isArray(cont)?cont[d.i]:cont}Drawing.font(tx,cast("family"),cast("size"),cast("color"))})}function styleOnSelect(gd,cd){var s=cd[0].node3;var trace=cd[0].trace;if(trace.selectedpoints){Drawing.selectedPointStyle(s.selectAll("path"),trace);Drawing.selectedTextStyle(s.selectAll("text"),trace)}else{stylePoints(s,trace,gd)}}module.exports={style:style,styleOnSelect:styleOnSelect}},{"../../components/drawing":583,"../../registry":817,d3:147}],839:[function(require,module,exports){"use strict";var Color=require("../../components/color");var hasColorscale=require("../../components/colorscale/has_colorscale");var colorscaleDefaults=require("../../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":558,"../../components/colorscale/defaults":568,"../../components/colorscale/has_colorscale":572}],840:[function(require,module,exports){"use strict";var scatterAttrs=require("../scatter/attributes");var colorAttrs=require("../../components/color/attributes");var extendFlat=require("../../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:.5,editType:"calcIfAutorange"},notched:{valType:"boolean",editType:"calcIfAutorange"},notchwidth:{valType:"number",min:0,max:.5,dflt:.25,editType:"calcIfAutorange"},boxpoints:{valType:"enumerated",values:["all","outliers","suspectedoutliers",false],dflt:"outliers",editType:"calcIfAutorange"},boxmean:{valType:"enumerated",values:[true,"sd",false],dflt:false,editType:"calcIfAutorange"},jitter:{valType:"number",min:0,max:1,editType:"calcIfAutorange"},pointpos:{valType:"number",min:-2,max:2,editType:"calcIfAutorange"},orientation:{valType:"enumerated",values:["v","h"],editType:"calc+clearAxisTypes"},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:"calcIfAutorange"}),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":557,"../../lib/extend":673,"../scatter/attributes":1015}],841:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var Lib=require("../../lib");var _=Lib._;var Axes=require("../../plots/cartesian/axes");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=[];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);for(i=0;i=0&&n0){var pts=ptsPerBin[i].sort(sortByVal);var boxVals=pts.map(extractVal);var bvLen=boxVals.length;var cdi={pos:posDistinct[i],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);cdi.q1=Lib.interp(boxVals,.25);cdi.med=Lib.interp(boxVals,.5);cdi.q3=Lib.interp(boxVals,.75);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)]);cdi.lo=4*cdi.q1-3*cdi.q3;cdi.uo=4*cdi.q3-3*cdi.q1;var iqr=cdi.q3-cdi.q1;var mci=1.57*iqr/Math.sqrt(bvLen);cdi.ln=cdi.med-mci;cdi.un=cdi.med+mci;cd.push(cdi)}}calcSelection(cd,trace);Axes.expand(valAxis,val,{padded:true});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}}]}};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.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;i1;var bdPos=t.dPos*groupFraction*(1-fullLayout.boxgroupgap)/(group?numBoxes:1);var bPos=group?2*t.dPos*(-.5+(t.num+.5)/numBoxes)*groupFraction:0;var wdPos=bdPos*trace.whiskerwidth;if(trace.visible!==true||t.empty){sel.remove();return}var posAxis,valAxis;if(trace.orientation==="h"){posAxis=ya;valAxis=xa}else{posAxis=xa;valAxis=ya}t.bPos=bPos;t.bdPos=bdPos;t.wdPos=wdPos;t.wHover=t.dPos*(group?groupFraction/numBoxes:1);plotBoxAndWhiskers(sel,{pos:posAxis,val:valAxis},trace,t);plotPoints(sel,{x:xa,y:ya},trace,t);plotBoxMean(sel,{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;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?Lib.identity:[]);paths.enter().append("path").style("vector-effect","non-scaling-stroke").attr("class","box");paths.exit().remove();paths.each(function(d){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);var m=Lib.constrain(valAxis.c2p(d.med,true),Math.min(q1,q3)+1,Math.max(q1,q3)-1);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+"M"+q1+","+pos0+"V"+pos1+(notched?"H"+ln+"L"+m+","+posm1+"L"+un+","+pos1:"")+"H"+q3+"V"+pos0+(notched?"H"+un+"L"+m+","+posm0+"L"+ln+","+pos0:"")+"Z"+"M"+q1+","+posc+"H"+lf+"M"+q3+","+posc+"H"+uf+(whiskerWidth===0?"":"M"+lf+","+posw0+"V"+posw1+"M"+uf+","+posw0+"V"+posw1))}else{d3.select(this).attr("d","M"+posm0+","+m+"H"+posm1+"M"+pos0+","+q1+"H"+pos1+(notched?"V"+ln+"L"+posm1+","+m+"L"+pos1+","+un:"")+"V"+q3+"H"+pos0+(notched?"V"+un+"L"+posm0+","+m+"L"+pos0+","+ln:"")+"Z"+"M"+posc+","+q1+"V"+lf+"M"+posc+","+q3+"V"+uf+(whiskerWidth===0?"":"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;var mode=trace.boxpoints||trace.points;Lib.seedPseudoRandom();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=mode==="all"?d.pts:d.pts.filter(function(pt){return pt.vd.uf});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;if(trace.jitter){if(typicalSpread===0){maxJitterFactor=1;jitterFactors=new Array(pts.length);for(i=0;id.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;var mode=trace.boxmean||(trace.meanline||{}).visible;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&&trace.meanline?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":583,"../../lib":684,d3:147}],848:[function(require,module,exports){"use strict";module.exports=function selectPoints(searchInfo,polygon){var cd=searchInfo.cd;var xa=searchInfo.xaxis;var ya=searchInfo.yaxis;var selection=[];var i,j;if(polygon===false){for(i=0;i=10){return null}var min=Infinity;var max=-Infinity;var n=a.length;for(var i=0;i0?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=0;i--){x[nea1-i]=xctrl[neb1][i];y[nea1-i]=yctrl[neb1][i]}segments.push({x:x,y:y,bicubic:asmoothing});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}},{}],863:[function(require,module,exports){"use strict";var Axes=require("../../plots/cartesian/axes");var extendFlat=require("../../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);if(axis.tickmode==="array")delete axis.tickvals;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={};if(axisLetter==="b"){j=trace.b2j(value);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;i0){dxydi0=trace.dxydi([],i-1,j0,0,tj);xpoints.push(pxy[0]+dxydi0[0]/3);ypoints.push(pxy[1]+dxydi0[1]/3);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;j0){dxydj0=trace.dxydj([],i0,j-1,ti,0);xpoints.push(pxy[0]+dxydj0[0]/3);ypoints.push(pxy[1]+dxydj0[1]/3);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)};for(j=0;jdata.length-1)continue;gridlines.push(extendFlat(constructArrayGridline(j),{color:axis.gridcolor,width:axis.gridwidth}))}for(n=n1;ndata.length-1)continue;if(j1<0||j1>data.length-1)continue;v0=data[j0];v1=data[j1];for(i=0;idata[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{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});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;ndata[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":673,"../../plots/cartesian/axes":732}],864:[function(require,module,exports){"use strict";var Axes=require("../../plots/cartesian/axes");var extendFlat=require("../../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;idata.length){out=out.slice(0,data.length)}for(i=0;i90){angle-=180;flip=-flip}return{angle:angle,flip:flip,p:trace.c2p(xy,xaxis,yaxis),offsetMultplier:offsetMultiplier}}},{}],878:[function(require,module,exports){"use strict";var d3=require("d3");var Drawing=require("../../components/drawing");var map1dArray=require("./map_1d_array");var makepath=require("./makepath");var orientText=require("./orient_text");var svgTextUtils=require("../../lib/svg_text_utils");var Lib=require("../../lib");var alignmentConstants=require("../../constants/alignment");var getUidsFromCalcData=require("../../plots/get_data").getUidsFromCalcData;module.exports=function plot(gd,plotinfo,cdcarpet,carpetLayer){var uidLookup=getUidsFromCalcData(cdcarpet);carpetLayer.selectAll("g.trace").each(function(){var classString=d3.select(this).attr("class");var oldUid=classString.split("carpet")[1].split(/\s/)[0];if(!uidLookup[oldUid]){d3.select(this).remove()}});for(var i=0;i0?"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("+orientation.p[0]+","+orientation.p[1]+") "+"rotate("+orientation.angle+")"+"translate("+label.axis.labelpadding*direction+","+bbox.height*.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=.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=.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)data.push(axis.title);var titleJoin=layer.selectAll("text."+labelClass).data(data);var offset=labelOrientation.maxExtent;titleJoin.enter().append("text").classed(labelClass,true);titleJoin.each(function(){var orientation=orientText(trace,xa,ya,xy,dxy);if(["start","both"].indexOf(axis.showticklabels)===-1){offset=0}var titleSize=axis.titlefont.size;offset+=titleSize+axis.titleoffset;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||"").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.titlefont)});titleJoin.exit().remove()}},{"../../components/drawing":583,"../../constants/alignment":656,"../../lib":684,"../../lib/svg_text_utils":708,"../../plots/get_data":768,"./makepath":875,"./map_1d_array":876,"./orient_text":877,d3:147}],879:[function(require,module,exports){"use strict";var constants=require("./constants");var search=require("../../lib/search").findBin;var computeControlPoints=require("./compute_control_points");var createSplineEvaluator=require("./create_spline_evaluator");var createIDerivativeEvaluator=require("./create_i_derivative_evaluator");var createJDerivativeEvaluator=require("./create_j_derivative_evaluator");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;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];var atol=arange*constants.RELATIVE_CULL_TOLERANCE;var btol=brange*constants.RELATIVE_CULL_TOLERANCE;amin-=atol;amax+=atol;bmin-=btol;bmax+=btol;trace.isVisible=function(a,b){return a>amin&&abmin&&bamax||bbmax};trace.setScale=function(){var x=trace._x;var y=trace._y;var result=computeControlPoints(trace._xctrl,trace._yctrl,x,y,aax.smoothing,bax.smoothing);trace._xctrl=result[0];trace._yctrl=result[1];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)};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])]};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])]};trace.i2c=function(i,j){return trace.evalxy([],i,j)};trace.ab2xy=function(aval,bval,extrapolate){if(!extrapolate&&(avala[na-1]|bvalb[nb-1])){return[false,false]}var i=trace.a2i(aval);var j=trace.b2j(bval);var pt=trace.evalxy([],i,j);if(extrapolate){var iex=0;var jex=0;var der=[];var i0,ti,j0,tj;if(avala[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(bvalb[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){var i0=Math.max(0,Math.min(a.length-2,i));return a[i0+1]-a[i0]};trace.dbdj=function(j){var j0=Math.max(0,Math.min(b.length-2,j));return b[j0+1]-b[j0]};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]};trace.dxyda_rough=function(a,b,reldiff){var h=arange*(reldiff||.1);var plus=trace.ab2xy(a+h,b,true);var minus=trace.ab2xy(a-h,b,true);return[(plus[0]-minus[0])*.5/h,(plus[1]-minus[1])*.5/h]};trace.dxydb_rough=function(a,b,reldiff){var h=brange*(reldiff||.1);var plus=trace.ab2xy(a,b+h,true);var minus=trace.ab2xy(a,b-h,true);return[(plus[0]-minus[0])*.5/h,(plus[1]-minus[1])*.5/h]};trace.dpdx=function(xa){return xa._m};trace.dpdy=function(ya){return ya._m}}},{"../../lib/search":703,"./compute_control_points":867,"./constants":868,"./create_i_derivative_evaluator":869,"./create_j_derivative_evaluator":870,"./create_spline_evaluator":871}],880:[function(require,module,exports){"use strict";var Lib=require("../../lib");module.exports=function smoothFill2dArray(data,a,b){var i,j,k;var ip=[];var jp=[];var ni=data[0].length;var nj=data.length;function avgSurrounding(i,j){var sum=0;var val;var cnt=0;if(i>0&&(val=data[j][i-1])!==undefined){cnt++;sum+=val}if(i0&&(val=data[j-1][i])!==undefined){cnt++;sum+=val}if(j0&&j0&&itol);Lib.log("Smoother converged to",resid,"after",iter,"iterations");return data}},{"../../lib":684}],881:[function(require,module,exports){"use strict";var isArray1D=require("../../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":684}],882:[function(require,module,exports){"use strict";var scatterGeoAttrs=require("../scattergeo/attributes");var colorscaleAttrs=require("../../components/colorscale/attributes");var colorbarAttrs=require("../../components/colorbar/attributes");var plotAttrs=require("../../plots/attributes");var extendFlat=require("../../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"]})},colorscaleAttrs("",{cLetter:"z",editTypeOverride:"calc"}),{colorbar:colorbarAttrs})},{"../../components/colorbar/attributes":559,"../../components/colorscale/attributes":565,"../../lib/extend":673,"../../plots/attributes":729,"../scattergeo/attributes":1053}],883:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var BADNUM=require("../../constants/numerical").BADNUM;var colorscaleCalc=require("../../components/colorscale/calc");var arraysToCalcdata=require("../scatter/arrays_to_calcdata");var calcSelection=require("../scatter/calc_selection");module.exports=function calc(gd,trace){var len=trace._length;var calcTrace=new Array(len);for(var i=0;i")}},{"../../plots/cartesian/axes":732,"../scatter/fill_hover_text":1022,"./attributes":882}],887:[function(require,module,exports){"use strict";var Choropleth={};Choropleth.attributes=require("./attributes");Choropleth.supplyDefaults=require("./defaults");Choropleth.colorbar=require("../heatmap/colorbar");Choropleth.calc=require("./calc");Choropleth.plot=require("./plot");Choropleth.style=require("./style").style;Choropleth.styleOnSelect=require("./style").styleOnSelect;Choropleth.hoverPoints=require("./hover");Choropleth.eventData=require("./event_data");Choropleth.selectPoints=require("./select");Choropleth.moduleType="trace";Choropleth.name="choropleth";Choropleth.basePlotModule=require("../../plots/geo");Choropleth.categories=["geo","noOpacity"];Choropleth.meta={};module.exports=Choropleth},{"../../plots/geo":762,"../heatmap/colorbar":928,"./attributes":882,"./calc":883,"./defaults":884,"./event_data":885,"./hover":886,"./plot":888,"./select":889,"./style":890}],888:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");var polygon=require("../../lib/polygon");var getTopojsonFeatures=require("../../lib/topojson_utils").getTopojsonFeatures;var locationToFeature=require("../../lib/geo_location_utils").locationToFeature;var style=require("./style").style;module.exports=function plot(gd,geo,calcData){for(var i=0;i0&&pts[l+1][0]<0)return l}return null}if(loc==="RUS"||loc==="FJI"){appendPolygon=function(_pts){var pts;if(doesCrossAntiMerdian(_pts)===null){pts=_pts}else{pts=new Array(_pts.length);for(m=0;m<_pts.length;m++){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"){appendPolygon=function(pts){var crossAntiMeridianIndex=doesCrossAntiMerdian(pts);if(crossAntiMeridianIndex===null){return polygons.push(polygon.tester(pts))}var stitch=new Array(pts.length+1);var si=0;for(m=0;mcrossAntiMeridianIndex){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]}}var tester=polygon.tester(stitch);tester.pts.pop();polygons.push(tester)}}else{appendPolygon=function(pts){polygons.push(polygon.tester(pts))}}switch(geometry.type){case"MultiPolygon":for(j=0;j":if(contours.value>boundaryMax){pi0.prefixBoundary=true}break;case"<":if(contours.valueboundaryMax){pi0.prefixBoundary=true}break;case"][":v1=Math.min.apply(null,contours.value);v2=Math.max.apply(null,contours.value);if(v1boundaryMax){pi0.prefixBoundary=true}break}}},{}],899:[function(require,module,exports){"use strict";var drawColorbar=require("../../components/colorbar/draw");var makeColorMap=require("./make_color_map");var endPlus=require("./end_plus");module.exports=function colorbar(gd,cd){var trace=cd[0].trace,cbId="cb"+trace.uid;gd._fullLayout._infolayer.selectAll("."+cbId).remove();if(!trace.showscale)return;var cb=drawColorbar(gd,cbId);cd[0].t.cb=cb;var contours=trace.contours,line=trace.line,cs=contours.size||1,coloring=contours.coloring;var colorMap=makeColorMap(trace,{isColorbar:true});if(coloring==="heatmap"){cb.filllevels({start:trace.zmin,end:trace.zmax,size:(trace.zmax-trace.zmin)/254})}cb.fillcolor(coloring==="fill"||coloring==="heatmap"?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":563,"./end_plus":907,"./make_color_map":912}],900:[function(require,module,exports){"use strict";module.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}}},{}],901:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var handleLabelDefaults=require("./label_defaults");var Color=require("../../components/color");var addOpacity=Color.addOpacity;var opacity=Color.opacity;var filterOps=require("../../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,.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){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{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":558,"../../constants/filter_ops":657,"./label_defaults":911,"fast-isnumeric":214}],902:[function(require,module,exports){"use strict";var filterOps=require("../../constants/filter_ops");var isNumeric=require("fast-isnumeric");module.exports={"[]":makeRangeSettings("[]"),"][":makeRangeSettings("]["),">":makeInequalitySettings(">"),"<":makeInequalitySettings("<"),"=":makeInequalitySettings("=")};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}function makeRangeSettings(operation){return function(value){value=coerceValue(operation,value);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":657,"fast-isnumeric":214}],903:[function(require,module,exports){"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;var contourSize=coerce("contours.size");var autoContour;if(missingEnd)autoContour=traceOut.autocontour=true;else autoContour=coerce("autocontour",false);if(autoContour||!contourSize)coerce("ncontours")}},{}],904:[function(require,module,exports){"use strict";var Lib=require("../../lib");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.")}pi0=pathinfo[0];for(i=0;i1e3){Lib.warn("Too many contours, clipping at 1000",contours);break}}return pathinfo}},{"../../lib":684,"./constraint_mapping":902,"./end_plus":907}],907:[function(require,module,exports){"use strict";module.exports=function endPlus(contours){return contours.end+contours.size/1e6}},{}],908:[function(require,module,exports){"use strict";var Lib=require("../../lib");var constants=require("./constants");module.exports=function findAllPaths(pathinfo,xtol,ytol){var cnt,startLoc,i,pi,j;xtol=xtol||.01;ytol=ytol||.01;for(i=0;i20){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}pts.push(getInterpPx(pi,loc,marchStep));loc[0]+=marchStep[0];loc[1]+=marchStep[1];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),closedLoop=locStr===startLocStr&&marchStep.join(",")===startStepStr;if(closedLoop||edgeflag&&atEdge)break;mi=pi.crossings[locStr]}if(cnt===1e4){Lib.log("Infinite loop in contour?")}var closedpath=equalPts(pts[0],pts[pts.length-1],xtol,ytol);var totaldist=0;var distThresholdFactor=.2*pi.smoothing;var alldists=[];var cropstart=0;var distgroup,cnt2,cnt3,newpt,ptcnt,ptavg,thisdist,i,j,edgepathi,edgepathj;for(cnt=1;cnt=cropstart;cnt--){distgroup=alldists[cnt];if(distgroup=cropstart;cnt2--){if(distgroup+alldists[cnt2]i)j--;pi.edgepaths[j]=edgepathj.concat(pts,edgepathi)}break}}if(!doublemerged){pi.edgepaths[i]=pts.concat(edgepathi)}}}for(i=0;i20&&edgeflag){if(mi===208||mi===1114){dx=loc[0]===0?1:-1}else{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]}function getInterpPx(pi,loc,step){var locx=loc[0]+Math.max(step[0],0),locy=loc[1]+Math.max(step[1],0),zxy=pi.z[locy][locx],xa=pi.xaxis,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":684,"./constants":900}],909:[function(require,module,exports){"use strict";var Color=require("../../components/color");var heatmapHoverPoints=require("../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":558,"../heatmap/hover":932}],910:[function(require,module,exports){"use strict";var Contour={};Contour.attributes=require("./attributes");Contour.supplyDefaults=require("./defaults");Contour.calc=require("./calc");Contour.plot=require("./plot").plot;Contour.style=require("./style");Contour.colorbar=require("./colorbar");Contour.hoverPoints=require("./hover");Contour.moduleType="trace";Contour.name="contour";Contour.basePlotModule=require("../../plots/cartesian");Contour.categories=["cartesian","svg","2dMap","contour","showLegend"];Contour.meta={};module.exports=Contour},{"../../plots/cartesian":743,"./attributes":896,"./calc":897,"./colorbar":899,"./defaults":905,"./hover":909,"./plot":914,"./style":916}],911:[function(require,module,exports){"use strict";var Lib=require("../../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":684}],912:[function(require,module,exports){"use strict";var d3=require("d3");var Colorscale=require("../../components/colorscale");var endPlus=require("./end_plus");module.exports=function makeColorMap(trace){var contours=trace.contours,start=contours.start,end=endPlus(contours),cs=contours.size||1,nc=Math.floor((end-start)/cs)+1,extra=contours.coloring==="lines"?0:1;if(!isFinite(cs)){cs=1;nc=1}var scl=trace.colorscale,len=scl.length;var domain=new Array(len),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;ival?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;if(val>avg)return mi===5?713:1114;return mi===5?104:208}return mi===15?0:mi}},{"./constants":900}],914:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");var Drawing=require("../../components/drawing");var svgTextUtils=require("../../lib/svg_text_utils");var Axes=require("../../plots/cartesian/axes");var setConvert=require("../../plots/cartesian/set_convert");var getUidsFromCalcData=require("../../plots/get_data").getUidsFromCalcData;var heatmapPlot=require("../heatmap/plot");var makeCrossings=require("./make_crossings");var findAllPaths=require("./find_all_paths");var emptyPathinfo=require("./empty_pathinfo");var convertToConstraints=require("./convert_to_constraints");var closeBoundaries=require("./close_boundaries");var constants=require("./constants");var costConstants=constants.LABELOPTIMIZER;exports.plot=function plot(gd,plotinfo,cdcontours,contourLayer){var uidLookup=getUidsFromCalcData(cdcontours);contourLayer.selectAll("g.contour").each(function(d){if(!uidLookup[d.trace.uid]){d3.select(this).remove()}});for(var i=0;ipi.level}if(prefixBoundary){return"M"+perimeter.join("L")+"Z"}return""}function joinAllPaths(pi,perimeter){var fullpath=initFullPath(pi,perimeter),i=0,startsleft=pi.edgepaths.map(function(v,i){return i}),newloop=true,endpt,newendpt,cnt,nexti,possiblei,addpath;function istop(pt){return Math.abs(pt[1]-perimeter[0][1])<.01}function isbottom(pt){return Math.abs(pt[1]-perimeter[2][1])<.01}function isleft(pt){return Math.abs(pt[0]-perimeter[0][0])<.01}function isright(pt){return Math.abs(pt[0]-perimeter[2][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;for(cnt=0;cnt<4;cnt++){if(!endpt){Lib.log("Missing end?",i,pi);break}if(istop(endpt)&&!isright(endpt))newendpt=perimeter[1];else if(isleft(endpt))newendpt=perimeter[0];else if(isbottom(endpt))newendpt=perimeter[3];else if(isright(endpt))newendpt=perimeter[2];for(possiblei=0;possiblei=0){newendpt=ptNew;nexti=possiblei}}else if(Math.abs(endpt[1]-newendpt[1])<.01){if(Math.abs(endpt[1]-ptNew[1])<.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;newloop=startsleft.indexOf(i)===-1;if(newloop){i=startsleft[0];fullpath+="Z"}}for(i=0;icostConstants.MAXCOST*2)break;if(j)dp/=2;p0=pMin-dp/2;pMax=p0+dp*1.5}if(cost<=costConstants.MAXCOST)return loc};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;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+=costConstants.ANGLECOST*theta*theta;var x1=x-dx;var y1=y-dy;var x2=x+dx;var y2=y+dy;for(var i=0;icontours.end){contours.start=contours.end=(contours.start+contours.end)/2}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"){var start=contours.start,end=contours.end,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}}};function autoContours(start,end,ncontours){var dummyAx={type:"linear",range:[start,end]};Axes.autoTicks(dummyAx,(end-start)/(ncontours||15));return dummyAx}},{"../../lib":684,"../../plots/cartesian/axes":732}],916:[function(require,module,exports){"use strict";var d3=require("d3");var Drawing=require("../../components/drawing");var heatmapStyle=require("../heatmap/style");var makeColorMap=require("./make_color_map");module.exports=function style(gd){var contours=d3.select(gd).selectAll("g.contour");contours.style("opacity",function(d){return d.trace.opacity});contours.each(function(d){var c=d3.select(this);var trace=d.trace;var contours=trace.contours;var line=trace.line;var cs=contours.size||1;var start=contours.start;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+.5*cs)});if(firstFill===undefined)firstFill=start;c.selectAll("g.contourbg path").style("fill",colorMap(firstFill-.5*cs))}});heatmapStyle(gd)}},{"../../components/drawing":583,"../heatmap/style":938,"./make_color_map":912,d3:147}],917:[function(require,module,exports){"use strict";var colorscaleDefaults=require("../../components/colorscale/defaults");var handleLabelDefaults=require("./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",.5);coerce("line.dash")}if(coloring!=="none"){colorscaleDefaults(traceIn,traceOut,layout,coerce,{prefix:"",cLetter:"z"})}coerce("line.smoothing");handleLabelDefaults(coerce,layout,lineColor,opts)}},{"../../components/colorscale/defaults":568,"./label_defaults":911}],918:[function(require,module,exports){"use strict";var heatmapAttrs=require("../heatmap/attributes");var contourAttrs=require("../contour/attributes");var contourContourAttrs=contourAttrs.contours;var scatterAttrs=require("../scatter/attributes");var colorscaleAttrs=require("../../components/colorscale/attributes");var colorbarAttrs=require("../../components/colorbar/attributes");var extendFlat=require("../../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:{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"}},colorscaleAttrs("",{cLetter:"z",autoColorDflt:false}),{colorbar:colorbarAttrs})},{"../../components/colorbar/attributes":559,"../../components/colorscale/attributes":565,"../../lib/extend":673,"../contour/attributes":896,"../heatmap/attributes":925,"../scatter/attributes":1015}],919:[function(require,module,exports){"use strict";var colorscaleCalc=require("../../components/colorscale/calc");var isArray1D=require("../../lib").isArray1D;var convertColumnData=require("../heatmap/convert_column_xyz");var clean2dArray=require("../heatmap/clean_2d_array");var maxRowLength=require("../heatmap/max_row_length");var interp2d=require("../heatmap/interp2d");var findEmpties=require("../heatmap/find_empties");var makeBoundArray=require("../heatmap/make_bound_array");var supplyDefaults=require("./defaults");var lookupCarpet=require("../carpet/lookup_carpetid");var setContours=require("../contour/set_contours");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){var carpetdata=gd.data[carpet.index];var tracedata=gd.data[trace.index];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){var carpet=trace._carpetTrace;var aax=carpet.aaxis;var bax=carpet.baxis;var a,a0,da,b,b0,db,z;aax._minDtick=0;bax._minDtick=0;if(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);var xlen=maxRowLength(z),xIn=trace.xtype==="scaled"?"":a,xArray=makeBoundArray(trace,xIn,a0,da,xlen,aax),yIn=trace.ytype==="scaled"?"":b,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"){colorscaleCalc(trace,z,"","z")}return[cd0]}},{"../../components/colorscale/calc":566,"../../lib":684,"../carpet/lookup_carpetid":874,"../contour/set_contours":915,"../heatmap/clean_2d_array":927,"../heatmap/convert_column_xyz":929,"../heatmap/find_empties":931,"../heatmap/interp2d":934,"../heatmap/make_bound_array":935,"../heatmap/max_row_length":936,"./defaults":920}],920:[function(require,module,exports){"use strict";var Lib=require("../../lib");var handleXYZDefaults=require("../heatmap/xyz_defaults");var attributes=require("./attributes");var handleConstraintDefaults=require("../contour/constraint_defaults");var handleContoursDefaults=require("../contour/contours_defaults");var handleStyleDefaults=require("../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(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)delete traceOut.showlegend;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":684,"../contour/constraint_defaults":901,"../contour/contours_defaults":903,"../contour/style_defaults":917,"../heatmap/xyz_defaults":940,"./attributes":918}],921:[function(require,module,exports){"use strict";var ContourCarpet={};ContourCarpet.attributes=require("./attributes");ContourCarpet.supplyDefaults=require("./defaults");ContourCarpet.colorbar=require("../contour/colorbar");ContourCarpet.calc=require("./calc");ContourCarpet.plot=require("./plot");ContourCarpet.style=require("../contour/style");ContourCarpet.moduleType="trace";ContourCarpet.name="contourcarpet";ContourCarpet.basePlotModule=require("../../plots/cartesian");ContourCarpet.categories=["cartesian","svg","carpet","contour","symbols","showLegend","hasLines","carpetDependent"];ContourCarpet.meta={};module.exports=ContourCarpet},{"../../plots/cartesian":743,"../contour/colorbar":899,"../contour/style":916,"./attributes":918,"./calc":919,"./defaults":920,"./plot":924}],922:[function(require,module,exports){"use strict";var Drawing=require("../../components/drawing");var axisAlignedLine=require("../carpet/axis_aligned_line");var Lib=require("../../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])=0){newendpt=ptNew;nexti=possiblei}}else if(Math.abs(endpt[1]-newendpt[1])=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;newloop=startsleft.indexOf(i)===-1;if(newloop){i=startsleft[0];fullpath+=pathto(endpt,newendpt)+"Z";endpt=null}}for(i=0;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";makeBackground(plotGroup,carpetcd.clipsegments,xa,ya,isConstraint,coloring);makeFills(trace,plotGroup,xa,ya,fillPathinfo,perimeter,ab2p,carpet,carpetcd,coloring,boundaryPath);makeLinesAndLabels(plotGroup,pathinfo,gd,cd[0],contours,plotinfo,carpet);Drawing.setClipUrl(plotGroup,carpet._clipPathId)}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;var linegroup=contourPlot.createLines(lineContainer,showLines||showLabels,pathinfo);var lineClip=contourPlot.createLineClip(lineContainer,clipLinesForLabels,gd._fullLayout._defs,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;var labelClipPathData=[[[0,0],[xLen,0],[xLen,yLen],[0,yLen]]];var labelData=[];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);var bounds={left:0,right:xLen,center:xLen/2,top:0,bottom:yLen,middle:yLen/2};var plotDiagonal=Math.sqrt(xLen*xLen+yLen*yLen);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;imaxEnd)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;imaxErrX){noZsmooth("x scale is not linear");break}}}if(y.length&&zsmooth==="fast"){var avgdy=(y[y.length-1]-y[0])/(y.length-1),maxErrY=Math.abs(avgdy/100);for(i=0;imaxErrY){noZsmooth("y scale is not linear");break}}}}}var xlen=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);if(!isGL2D){Axes.expand(xa,xArray);Axes.expand(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}if(!isContour||trace.contours.type!=="constraint"){colorscaleCalc(trace,z,"","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":566,"../../lib":684,"../../plots/cartesian/axes":732,"../../registry":817,"../histogram2d/calc":957,"./clean_2d_array":927,"./convert_column_xyz":929,"./find_empties":931,"./interp2d":934,"./make_bound_array":935,"./max_row_length":936}],927:[function(require,module,exports){"use strict";var isNumeric=require("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=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"}for(thisPt in newNeighborHash){neighborHash[thisPt]=newNeighborHash[thisPt];empties.push(newNeighborHash[thisPt])}}return empties.sort(function(a,b){return b[2]-a[2]})}},{"./max_row_length":936}],932:[function(require,module,exports){"use strict";var Fx=require("../../components/fx");var Lib=require("../../lib");var Axes=require("../../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;i2INTERPTHRESHOLD;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,thisPt,i,j,p,q,neighborShift,neighborRow,neighborVal,neighborCount,neighborSum,initialVal,minNeighbor,maxNeighbor;for(p=0;pminNeighbor){maxFractionalChange=Math.max(maxFractionalChange,Math.abs(z[i][j]-initialVal)/(maxNeighbor-minNeighbor))}}}return maxFractionalChange}},{"../../lib":684}],935:[function(require,module,exports){"use strict";var Registry=require("../../registry");var isArrayOrTypedArray=require("../../lib").isArrayOrTypedArray;module.exports=function makeBoundArray(trace,arrayIn,v0In,dvIn,numbricks,ax){var arrayOut=[],isContour=Registry.traceIs(trace,"contour"),isHist=Registry.traceIs(trace,"histogram"),isGL2D=Registry.traceIs(trace,"gl2d"),v0,dv,i;var isArrayOfTwoItemsOrMore=isArrayOrTypedArray(arrayIn)&&arrayIn.length>1;if(isArrayOfTwoItemsOrMore&&!isHist&&ax.type!=="category"){var len=arrayIn.length;if(len<=numbricks){if(isContour||isGL2D)arrayOut=arrayIn.slice(0,numbricks);else if(numbricks===1){arrayOut=[arrayIn[0]-.5,arrayIn[0]+.5]}else{arrayOut=[1.5*arrayIn[0]-.5*arrayIn[1]];for(i=1;i image").each(function(d){var oldTrace=d.trace||{};if(!uidLookup[oldTrace.uid]){d3.select(this.parentNode).remove()}});for(var i=0;i0){right=xa.c2p(x[i]);i--}if(right0){bottom=ya.c2p(y[i]);i--}if(bottom0)oneRowIsFilled=true;for(var j=0;jv){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]rightDigit&&rightDigitoneDay){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(roundedVoneSec){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)>.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":661,"../../plots/cartesian/axes":732}],949:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var Lib=require("../../lib");var Axes=require("../../plots/cartesian/axes");var arraysToCalcdata=require("../bar/arrays_to_calcdata");var binFunctions=require("./bin_functions");var normFunctions=require("./norm_functions");var doAvg=require("./average");var cleanBins=require("./clean_bins");var oneMonth=require("../../constants/numerical").ONEAVGMONTH;var getBinSpanLabelRound=require("./bin_label_vals");module.exports=function calc(gd,trace){if(trace.visible!==true)return;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;cleanBins(trace,pa,mainData);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;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){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]}i=pr2c(binSpec.start);binEnd=pr2c(binSpec.end)+(i-Axes.tickIncrement(i,binSpec.size,false,calendar))/1e6;while(i=0&&n=firstNonzero;i--){if(size[i]){lastNonzero=i;break}}for(i=firstNonzero;i<=lastNonzero;i++){if(isNumeric(pos[i])&&isNumeric(size[i])){var cdi={p:pos[i],s:size[i],b:0};if(!cumulativeSpec.enabled){cdi.pts=inputPoints[i];if(uniqueValsPerBin){cdi.p0=cdi.p1=inputPoints[i].length?pos0[inputPoints[i][0]]:pos[i]}else{cdi.p0=roundFn(binEdges[i]);cdi.p1=roundFn(binEdges[i+1],true)}}cd.push(cdi)}}if(cd.length===1){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};function calcAllAutoBins(gd,trace,pa,mainData,_overlayEdgeCase){var binAttr=mainData+"bins";var isOverlay=gd._fullLayout.barmode==="overlay";var i,tracei,calendar,firstManual,pos0;if(trace._autoBinFinished){delete trace._autoBinFinished}else{var traceGroup=isOverlay?[trace]:getConnectedHistograms(gd,trace);var autoBinnedTraces=[];var minSize=Infinity;var minStart=Infinity;var maxEnd=-Infinity;var autoBinAttr="autobin"+mainData;for(i=0;ifirstManual.size/1.9)minSize=firstManual.size;else minSize=firstManual.size/Math.ceil(firstManual.size/minSize);var adjustedFirstStart=firstManual.start+(firstManual.size-minSize)/2;minStart=adjustedFirstStart-minSize*Math.ceil((adjustedFirstStart-minStart)/minSize)}for(i=0;i=0;i--){nextHalfPoint(i)}}}else if(direction==="increasing"){for(i=1;i=0;i--){size[i]+=size[i+1]}if(currentBin==="exclude"){size.push(0);size.shift()}}}},{"../../constants/numerical":661,"../../lib":684,"../../plots/cartesian/axes":732,"../bar/arrays_to_calcdata":826,"./average":945,"./bin_functions":947,"./bin_label_vals":948,"./clean_bins":950,"./norm_functions":955,"fast-isnumeric":214}],950:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var cleanDate=require("../../lib").cleanDate;var constants=require("../../constants/numerical");var ONEDAY=constants.ONEDAY;var BADNUM=constants.BADNUM;module.exports=function cleanBins(trace,ax,binDirection){var axType=ax.type,binAttr=binDirection+"bins",bins=trace[binAttr];if(!bins)bins=trace[binAttr]={};var cleanBound=axType==="date"?function(v){return v||v===0?cleanDate(v,BADNUM,bins.calendar):null}:function(v){return isNumeric(v)?Number(v):null};bins.start=cleanBound(bins.start);bins.end=cleanBound(bins.end);var sizeDflt=axType==="date"?ONEDAY:1,binSize=bins.size;if(isNumeric(binSize)){bins.size=binSize>0?Number(binSize):sizeDflt}else if(typeof binSize!=="string"){bins.size=sizeDflt}else{var prefix=binSize.charAt(0),sizeNum=binSize.substr(1);sizeNum=isNumeric(sizeNum)?Number(sizeNum):0;if(sizeNum<=0||!(axType==="date"&&prefix==="M"&&sizeNum===Math.round(sizeNum))){bins.size=sizeDflt}}var autoBinAttr="autobin"+binDirection;if(typeof trace[autoBinAttr]!=="boolean"){trace[autoBinAttr]=trace._fullInput[autoBinAttr]=trace._input[autoBinAttr]=!((bins.start||bins.start===0)&&(bins.end||bins.end===0))}if(!trace[autoBinAttr]){delete trace["nbins"+binDirection];delete trace._fullInput["nbins"+binDirection]}}},{"../../constants/numerical":661,"../../lib":684,"fast-isnumeric":214}],951:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Lib=require("../../lib");var Color=require("../../components/color");var handleBinDefaults=require("./bin_defaults");var handleStyleDefaults=require("../bar/style_defaults");var attributes=require("./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(x.length&&y.length):(traceOut[sampleLetter]||[]).length;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");handleBinDefaults(traceIn,traceOut,coerce,[sampleLetter]);handleStyleDefaults(traceIn,traceOut,coerce,defaultColor,layout);var errorBarsSupplyDefaults=Registry.getComponentMethod("errorbars","supplyDefaults");errorBarsSupplyDefaults(traceIn,traceOut,Color.defaultLine,{axis:"y"});errorBarsSupplyDefaults(traceIn,traceOut,Color.defaultLine,{axis:"x",inherit:"y"});Lib.coerceSelectionMarkerOpacity(traceOut,coerce)}},{"../../components/color":558,"../../lib":684,"../../registry":817,"../bar/style_defaults":839,"./attributes":944,"./bin_defaults":946}],952:[function(require,module,exports){"use strict";module.exports=function eventData(out,pt,trace,cd,pointNumber){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;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;iserieslen)x.splice(serieslen,x.length-serieslen);if(y.length>serieslen)y.splice(serieslen,y.length-serieslen);cleanAndAutobin(trace,"x",x,xa,xr2c,xc2r,xcalendar);cleanAndAutobin(trace,"y",y,ya,yr2c,yc2r,ycalendar);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=[];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]}var binSpec=trace.xbins,binStart=xr2c(binSpec.start),binEnd=xr2c(binSpec.end)+(binStart-Axes.tickIncrement(binStart,binSpec.size,false,xcalendar))/1e6;for(i=binStart;i=0&&n=0&&m0){cells=alphaShape(data.alphahull,positions)}else{var d=["x","y","z"].indexOf(data.delaunayaxis);cells=triangulate(positions.map(function(c){return[c[(d+1)%3],c[(d+2)%3]]}))}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.colorscale)}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)}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":680,"../../lib/str2rgbarray":707,"../../plots/gl3d/zip3":785,"alpha-shape":55,"convex-hull":117,"delaunay-triangulate":149,"gl-mesh3d":268}],968:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Lib=require("../../lib");var colorscaleDefaults=require("../../components/colorscale/defaults");var attributes=require("./attributes");module.exports=function supplyDefaults(traceIn,traceOut,defaultColor,layout){function coerce(attr,dflt){return Lib.coerce(traceIn,traceOut,attributes,attr,dflt)}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"]);var indices=readComponents(["i","j","k"]);if(!coords){traceOut.visible=false;return}if(indices){indices.forEach(function(index){for(var i=0;icPrev}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)}}Axes.expand(ya,l.concat(h),{padded:true});if(cd.length){cd[0].t={labels:{open:_(gd,"open:")+" ",high:_(gd,"high:")+" ",low:_(gd,"low:")+" ",close:_(gd,"close:")+" "}}}return cd}function convertTickWidth(gd,xa,trace){var minDiff=trace._minDiff;if(!minDiff){var fullData=gd._fullData,ohlcTracesOnThisXaxis=[];minDiff=Infinity;var i;for(i=0;i");pointData.y0=pointData.y1=ya.c2p(di.yc,true);return[pointData]}},{"../../components/color":558,"../../components/fx":600,"../../plots/cartesian/axes":732,"../scatter/fill_hover_text":1022}],974:[function(require,module,exports){"use strict";module.exports={moduleType:"trace",name:"ohlc",basePlotModule:require("../../plots/cartesian"),categories:["cartesian","svg","showLegend"],meta:{},attributes:require("./attributes"),supplyDefaults:require("./defaults"),calc:require("./calc").calc,plot:require("./plot"),style:require("./style"),hoverPoints:require("./hover"),selectPoints:require("./select")}},{"../../plots/cartesian":743,"./attributes":970,"./calc":971,"./defaults":972,"./hover":973,"./plot":976,"./select":977,"./style":978}],975:[function(require,module,exports){"use strict";var Registry=require("../../registry");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");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,x.length);traceOut._length=len;return len}},{"../../registry":817}],976:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");module.exports=function plot(gd,plotinfo,cdOHLC,ohlcLayer){var xa=plotinfo.xaxis;var ya=plotinfo.yaxis;var traces=ohlcLayer.selectAll("g.trace").data(cdOHLC,function(d){return d[0].trace.uid});traces.enter().append("g").attr("class","trace ohlc");traces.exit().remove();traces.order();traces.each(function(d){var cd0=d[0];var t=cd0.t;var trace=cd0.trace;var sel=d3.select(this);if(!plotinfo.isRangePlot)cd0.node3=sel;if(trace.visible!==true||t.empty){sel.remove();return}var tickLen=t.tickLen;var paths=sel.selectAll("path").data(Lib.identity);paths.enter().append("path");paths.exit().remove();paths.attr("d",function(d){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":684,d3:147}],977:[function(require,module,exports){"use strict";module.exports=function selectPoints(searchInfo,polygon){var cd=searchInfo.cd;var xa=searchInfo.xaxis;var ya=searchInfo.yaxis;var selection=[];var i;var posOffset=cd[0].t.bPos||0;if(polygon===false){for(i=0;i=0;i--){var aNext=a[i];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[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];var p,sectionHeight,iNext;var currentGap=pixelRanges.length?pixelRanges[0][0]:null;for(var i=0;ifPix[1]+pad||y=.9*fPix[1]+.1*fPix[0])return"n";if(y<=.9*fPix[0]+.1*fPix[1])return"s";return"ns"}function clearCursor(){d3.select(document.body).style("cursor",null)}function styleHighlight(selection){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]){hoveredInterval=i;break}else{previousInterval=i?i-1:NaN;if(p&&p[0]>y){nextInterval=i;break}}}closestInterval=hoveredInterval;if(isNaN(closestInterval)){if(isNaN(previousInterval)||isNaN(nextInterval)){closestInterval=isNaN(previousInterval)?nextInterval:previousInterval}else{closestInterval=y-pixIntervals[previousInterval][1]=rangei[0]&&unitLocation<=rangei[1]){out.clickableOrdinalRange=rangei;break}}}return out}function attachDragBehavior(selection){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;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){s.newExtent=[y-s.grabPoint,y+s.barLength-s.grabPoint].map(d.unitToPaddedPx.invert)}else{s.newExtent=[s.startExtent,d.unitToPaddedPx.invert(y)].sort(sortAsc)}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){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();if(!s.wasDragged){s.wasDragged=undefined;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}var mergeIntervals=function(){filter.set(filter.getConsolidated())};if(d.ordinal){var a=d.unitTickvals;if(a[a.length-1]s.newExtent[0];s.extent=s.stayingIntervals.concat(hasNewExtent?[s.newExtent]:[]);if(!s.extent.length){brushClear(brush)}s.brushCallback(d);if(hasNewExtent){renderHighlight(this.parentNode,mergeIntervals)}else{mergeIntervals();renderHighlight(this.parentNode)}}else{mergeIntervals()}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").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);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);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){var queue=intervals.slice();var result=[];var currentInterval;var current=queue.shift();while(current){currentInterval=current.slice();while((current=queue.shift())&¤t[0]<=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,svgBrush:{extent:[],brushStartCallback:brushStartCallback,brushCallback:axisBrushMoved(brushCallback),brushEndCallback:brushEndCallback}}}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)];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":684,"../../lib/gup":681,"./constants":983,d3:147}],981:[function(require,module,exports){"use strict";var d3=require("d3");var getModuleCalcData=require("../../plots/get_data").getModuleCalcData;var parcoordsPlot=require("./plot");var xmlnsNamespaces=require("../../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);window.setTimeout(function(){d3.selectAll("#filterBarPattern").attr("id","filterBarPattern")},60)}},{"../../constants/xmlns_namespaces":663,"../../plots/get_data":768,"./plot":989,d3:147}],982:[function(require,module,exports){"use strict";var hasColorscale=require("../../components/colorscale/has_colorscale");var calcColorscale=require("../../components/colorscale/calc");var Lib=require("../../lib");var wrap=require("../../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(trace,color,"line","c")}return wrap({lineColor:color,cscale:cscale})};function constHalf(len){var out=new Array(len);for(var i=0;imaxDimensionCount){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);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":568,"../../components/colorscale/has_colorscale":572,"../../lib":684,"../../plots/array_container_defaults":728,"../../plots/domain":757,"./attributes":979,"./axisbrush":980,"./constants":983,"./merge_length":987}],985:[function(require,module,exports){"use strict";var Parcoords={};Parcoords.attributes=require("./attributes");Parcoords.supplyDefaults=require("./defaults");Parcoords.calc=require("./calc");Parcoords.plot=require("./plot");Parcoords.colorbar={container:"line",min:"cmin",max:"cmax"};Parcoords.moduleType="trace";Parcoords.name="parcoords";Parcoords.basePlotModule=require("./base_plot");Parcoords.categories=["gl","regl","noOpacity"];Parcoords.meta={};module.exports=Parcoords},{"./attributes":979,"./base_plot":981,"./calc":982,"./defaults":984,"./plot":989}],986:[function(require,module,exports){"use strict";var glslify=require("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=require("../../lib");var depthLimitEpsilon=1e-6;var filterEpsilon=1e-7;var maskHeight=2048;var gpuDimensionCount=64;var sectionVertexCount=2;var vec4NumberCount=4;var bitsPerByte=8;var channelCount=gpuDimensionCount/bitsPerByte;var contextColor=[119,119,119];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})}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){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>>8*rgbIndex)%256/255}function makePoints(sampleCount,dimensions,color){var dimensionCount=dimensions.length;var points=[];for(var j=0;j=gpuDimensionCount-4?calcPickColor(j,gpuDimensionCount-2-i):.5)}}return points}function makeVecAttr(sampleCount,points,vecIndex){var i,j,k;var pointPairs=[];for(j=0;jhighestX){highestX=panels[I].dim2.canvasX;rightmost=I}if(panels[I].dim1.canvasXdimension._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;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)}for(var j=1;j=cw||y>=ch){return}var pixel=d.lineLayer.readPixel(x,ch-1-y);var found=pixel[3]!==0;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){if(found){callbacks.hover(eventData)}else if(callbacks.unhover){callbacks.unhover(eventData)}lastHovered=curveNumber}}});parcoordsLineLayer.style("opacity",function(d){return d.pick?.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;pline").attr("fill","none").attr("stroke","black").attr("stroke-opacity",.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/drawing":583,"../../lib":684,"../../lib/gup":681,"./axisbrush":980,"./constants":983,"./lines":986,d3:147}],989:[function(require,module,exports){"use strict";var parcoords=require("./parcoords");var prepareRegl=require("../../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 size=fullLayout._size;cdparcoords.forEach(function(d,i){gdDimensions[i]=gd.data[i].dimensions;gdDimensionsOriginalOrder[i]=gd.data[i].dimensions.slice()});var filterChanged=function(i,originalDimensionIndex,newRanges){var gdDimension=gdDimensionsOriginalOrder[i][originalDimensionIndex];var newConstraints=newRanges.map(function(r){return r.slice()});if(!newConstraints.length){delete gdDimension.constraintrange;newConstraints=null}else{if(newConstraints.length===1)newConstraints=newConstraints[0];gdDimension.constraintrange=newConstraints;newConstraints=[newConstraints]}var restyleData={};var aStr="dimensions["+originalDimensionIndex+"].constraintrange";restyleData[aStr]=newConstraints;gd.emit("plotly_restyle",[restyleData,[i]])};var hover=function(eventData){gd.emit("plotly_hover",eventData)};var unhover=function(eventData){gd.emit("plotly_unhover",eventData)};var axesMoved=function(i,visibleIndices){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){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}}var orig=sorter(gdDimensionsOriginalOrder[i].filter(visible));gdDimensions[i].sort(orig);gdDimensionsOriginalOrder[i].filter(function(d){return!visible(d)}).sort(function(d){return gdDimensionsOriginalOrder[i].indexOf(d)}).forEach(function(d){gdDimensions[i].splice(gdDimensions[i].indexOf(d),1);gdDimensions[i].splice(gdDimensionsOriginalOrder[i].indexOf(d),0,d)});gd.emit("plotly_restyle")};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":697,"./parcoords":988}],990:[function(require,module,exports){"use strict";var colorAttrs=require("../../components/color/attributes");var fontAttrs=require("../../plots/font_attributes");var plotAttrs=require("../../plots/attributes");var domainAttrs=require("../../plots/domain").attributes;var extendFlat=require("../../lib/extend").extendFlat;var textFontAttrs=fontAttrs({editType:"calc",colorEditType:"style"});module.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: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"},scalegroup:{valType:"string",dflt:"",editType:"calc"},textinfo:{valType:"flaglist",flags:["label","text","value","percent"],extras:["none"],editType:"calc"},hoverinfo:extendFlat({},plotAttrs.hoverinfo,{flags:["label","text","value","percent","name"]}),textposition:{valType:"enumerated",values:["inside","outside","auto","none"],dflt:"auto",arrayOk:true,editType:"calc"},textfont:extendFlat({},textFontAttrs,{}),insidetextfont:extendFlat({},textFontAttrs,{}),outsidetextfont:extendFlat({},textFontAttrs,{}),domain:domainAttrs({name:"pie",trace:true,editType:"calc"}),hole:{valType:"number",min:0,max:1,dflt:0,editType:"calc"},sort:{valType:"boolean",dflt:true,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:true,editType:"calc"}}},{"../../components/color/attributes":557,"../../lib/extend":673,"../../plots/attributes":729,"../../plots/domain":757,"../../plots/font_attributes":758}],991:[function(require,module,exports){"use strict";var Registry=require("../../registry");var getModuleCalcData=require("../../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":768,"../../registry":817}],992:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var isArrayOrTypedArray=require("../../lib").isArrayOrTypedArray;var tinycolor=require("tinycolor2");var Color=require("../../components/color");var helpers=require("./helpers");module.exports=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 colorWay=fullLayout.colorway;var colorMap=fullLayout._piecolormap;var allThisTraceLabels={};var vTotal=0;var hiddenLabels=fullLayout.hiddenlabels||[];var i,v,label,hidden,pt;if(!fullLayout._piecolorway&&colorWay!==Color.defaults){fullLayout._piecolorway=generateDefaultColors(colorWay)}if(trace.dlabel){labels=new Array(vals.length);for(i=0;i")}}return cd};var pieDefaultColors;function nextDefaultColor(index,pieColorWay){if(!pieDefaultColors){var mainDefaults=Color.defaults;pieDefaultColors=generateDefaultColors(mainDefaults)}var pieColors=pieColorWay||pieDefaultColors;return pieColors[index%pieColors.length]}function generateDefaultColors(colorList){var i;var pieColors=colorList.slice();for(i=0;i"),name: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)},{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(){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){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")}}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){s.attr("data-notex",1)});sliceText.text(pt.text).attr({class:"slicetext",transform:"","text-anchor":"middle"}).call(Drawing.font,textPosition==="outside"?trace.outsidetextfont:trace.insidetextfont).call(svgTextUtils.convertToTspans,gd);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);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+")")})});if(hasOutsideText)scootLabels(quadrants,trace);slices.each(function(pt){if(pt.labelExtraX||pt.labelExtraY){var sliceTop=d3.select(this);var sliceText=sliceTop.select("g.slicetext text");sliceText.attr("transform","translate("+pt.labelExtraX+","+pt.labelExtraY+")"+sliceText.attr("transform"));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"})}})})});setTimeout(function(){pieGroups.selectAll("tspan").each(function(){var s=d3.select(this);if(s.attr("dy"))s.attr("dy",s.attr("dy"))})},0)};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,.5);var ring=1-cd0.trace.hole;var rInscribed=getInscribedRadiusFraction(pt,cd0),transform={scale:rInscribed*cd0.r*2/textDiameter,rCenter:1-rInscribed,rotate:0};if(transform.scale>=1)return transform;var Qr=textAspect+1/(2*Math.tan(halfAngle));var maxHalfHeightRotRadial=cd0.r*Math.min(1/(Math.sqrt(Qr*Qr+.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};var aspectInv=1/textAspect;var Qt=aspectInv+1/(2*Math.tan(halfAngle));var maxHalfWidthTangential=cd0.r*Math.min(1/(Math.sqrt(Qt*Qt+.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};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;var halfAngle=Math.PI*Math.min(pt.v/cd0.vTotal,.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 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;if(newExtraY*yDiffSign>0)thisPt.labelExtraY=newExtraY;if(!Array.isArray(trace.pull))return;for(i=0;i=(helpers.castOption(trace.pull,otherPt.pts)||0)){continue}if((thisPt.pxmid[1]-otherPt.pxmid[1])*yDiffSign>0){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){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;thisQuad=quadrants[yHalf][xHalf];thisQuad.sort(equatorFirst);oppositeQuad=quadrants[1-yHalf][xHalf];wholeSide=oppositeQuad.concat(thisQuad);thisQuadOutside=[];for(i=0;imaxPull)maxPull=trace.pull[j]}}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*(2-trace.domain.y[1]-trace.domain.y[0])/2;if(trace.scalegroup&&scaleGroups.indexOf(trace.scalegroup)===-1){scaleGroups.push(trace.scalegroup)}}for(j=0;jcd0.vTotal/2?1:0}}},{"../../components/color":558,"../../components/drawing":583,"../../components/fx":600,"../../lib":684,"../../lib/svg_text_utils":708,"./event_data":994,"./helpers":995,d3:147}],1e3:[function(require,module,exports){"use strict";var d3=require("d3");var styleOne=require("./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":1001,d3:147}],1001:[function(require,module,exports){"use strict";var Color=require("../../components/color");var castOption=require("./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":558,"./helpers":995}],1002:[function(require,module,exports){"use strict";var scatterglAttrs=require("../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:.1,max:2,dflt:.5,editType:"calc"},sizemax:{valType:"number",min:.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"}}},{"../scatter/attributes":1015}],1003:[function(require,module,exports){"use strict";var createPointCloudRenderer=require("gl-pointcloud2d");var str2RGBArray=require("../../lib/str2rgbarray");var expandAxis=require("../../plots/cartesian/autorange").expand;var getTraceColor=require("../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:.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}var proto=Pointcloud.prototype;proto.handlePick=function(pickResult){var index=this.idToIndex[pickResult.pointId];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,idToIndex,positions,bounds=this.bounds;var xx,yy,i;if(xy){positions=xy;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;ibounds[2])bounds[2]=xx;if(yybounds[3])bounds[3]=yy}}if(index){idToIndex=index}else{idToIndex=new Int32Array(len);for(i=0;ibounds[2])bounds[2]=xx;if(yybounds[3])bounds[3]=yy}}this.idToIndex=idToIndex;this.pointcloudOptions.idToIndex=idToIndex;this.pointcloudOptions.positions=positions;var markerColor=str2RGBArray(options.marker.color),borderColor=str2RGBArray(options.marker.border.color),opacity=options.opacity*options.marker.opacity;markerColor[3]*=opacity;this.pointcloudOptions.color=markerColor;var blend=options.marker.blend;if(blend===null){var maxPoints=100;blend=x.length1})}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":684,"../../lib/gup":681,"strongly-connected-components":491}],1009:[function(require,module,exports){"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"}}},{}],1010:[function(require,module,exports){"use strict";var Lib=require("../../lib");var attributes=require("./attributes");var Color=require("../../components/color");var tinycolor=require("tinycolor2");var handleDomainDefaults=require("../../plots/domain").defaults;module.exports=function supplyDefaults(traceIn,traceOut,defaultColor,layout){function coerce(attr,dflt){return Lib.coerce(traceIn,traceOut,attributes,attr,dflt)}coerce("node.label");coerce("node.pad");coerce("node.thickness");coerce("node.line.color");coerce("node.line.width");var colors=layout.colorway;var defaultNodePalette=function(i){return colors[i%colors.length]};coerce("node.color",traceOut.node.label.map(function(d,i){return Color.addOpacity(defaultNodePalette(i),.8)}));coerce("link.label");coerce("link.source");coerce("link.target");coerce("link.value");coerce("link.line.color");coerce("link.line.width");coerce("link.color",traceOut.link.value.map(function(){return tinycolor(layout.paper_bgcolor).getLuminance()<.333?"rgba(255, 255, 255, 0.6)":"rgba(0, 0, 0, 0.2)"}));handleDomainDefaults(traceOut,layout,coerce);coerce("orientation");coerce("valueformat");coerce("valuesuffix");coerce("arrangement");Lib.coerceFont(coerce,"textfont",Lib.extendFlat({},layout.font));traceOut._length=null}},{"../../components/color":558,"../../lib":684,"../../plots/domain":757,"./attributes":1006,tinycolor2:499}],1011:[function(require,module,exports){"use strict";var Plot={};Plot.attributes=require("./attributes");Plot.supplyDefaults=require("./defaults");Plot.calc=require("./calc");Plot.plot=require("./plot");Plot.moduleType="trace";Plot.name="sankey";Plot.basePlotModule=require("./base_plot");Plot.categories=["noOpacity"];Plot.meta={};module.exports=Plot},{"./attributes":1006,"./base_plot":1007,"./calc":1008,"./defaults":1010,"./plot":1012}],1012:[function(require,module,exports){"use strict";var d3=require("d3");var render=require("./render");var Fx=require("../../components/fx");var Color=require("../../components/color");var Lib=require("../../lib");var cn=require("./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",.4);if(label){ownTrace(sankey,d).selectAll("."+cn.sankeyLink).filter(function(l){return l.link.label===label}).style("fill-opacity",.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)}}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){d3.select(element).call(linkHoveredStyle.bind(0,d,sankey,true));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){var trace=d.link.trace;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 tooltip=Fx.loneHover({x:hoverCenterX-rootBBox.left,y:hoverCenterY-rootBBox.top,name:d3.format(d.valueFormat)(d.link.value)+d.valueSuffix,text:[d.link.label||"",sourceLabel+d.link.source.label,targetLabel+d.link.target.label].filter(renderableValuePresent).join("
"),color:castHoverOption(trace,"bgcolor")||Color.addOpacity(d.tinyColorHue,1),borderColor:castHoverOption(trace,"bordercolor"),fontFamily:castHoverOption(trace,"font.family"),fontSize:castHoverOption(trace,"font.size"),fontColor:castHoverOption(trace,"font.color"),idealAlign:d3.event.x"),color:castHoverOption(trace,"bgcolor")||d.tinyColorHue,borderColor:castHoverOption(trace,"bordercolor"),fontFamily:castHoverOption(trace,"font.family"),fontSize:castHoverOption(trace,"font.size"),fontColor:castHoverOption(trace,"font.color"),idealAlign:"left"},{container:fullLayout._hoverlayer.node(),outerContainer:fullLayout._paper.node(),gd:gd});makeTranslucent(tooltip,.85);makeTextContrasty(tooltip)};var nodeUnhover=function(element,d,sankey){d3.select(element).call(nodeNonHoveredStyle,d,sankey);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":558,"../../components/fx":600,"../../lib":684,"./constants":1009,"./render":1013,d3:147}],1013:[function(require,module,exports){"use strict";var c=require("./constants");var d3=require("d3");var tinycolor=require("tinycolor2");var Color=require("../../components/color");var Drawing=require("../../components/drawing");var d3sankey=require("@plotly/d3-sankey").sankey;var d3Force=require("d3-force");var Lib=require("../../lib");var isArrayOrTypedArray=Lib.isArrayOrTypedArray;var isIndex=Lib.isIndex;var gup=require("../../lib/gup");var keyFun=gup.keyFun;var repeat=gup.repeat;var unwrap=gup.unwrap;function persistOriginalPlace(nodes){var i,distinctLayerPositions=[];for(i=0;i0&&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;i1||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%"}function attachPointerEvents(selection,sankey,eventSet){selection.on(".basic",null).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{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).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;i0){window.requestAnimationFrame(faster)}})}function snappingForce(sankeyNode,forceKey,nodes,d){return function _snappingForce(){var maxVelocity=0;for(var i=0;i0){d.forceLayouts[forceKey].alpha(0)}}}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);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":558,"../../components/drawing":583,"../../lib":684,"../../lib/gup":681,"./constants":1009,"@plotly/d3-sankey":49,d3:147,"d3-force":143,tinycolor2:499}],1014:[function(require,module,exports){"use strict";var Lib=require("../../lib");module.exports=function arraysToCalcdata(cd,trace){for(var i=0;i=0;j--){var tracej=fullData[j];if(tracej.type==="scatter"&&tracej.xaxis===tracei.xaxis&&tracej.yaxis===tracei.yaxis){tracej.opacity=undefined;break}}}}}},{}],1019:[function(require,module,exports){"use strict";var hasColorscale=require("../../components/colorscale/has_colorscale");var calcColorscale=require("../../components/colorscale/calc");var subTypes=require("./subtypes");module.exports=function calcMarkerColorscale(trace){if(subTypes.hasLines(trace)&&hasColorscale(trace,"line")){calcColorscale(trace,trace.line.color,"line","c")}if(subTypes.hasMarkers(trace)){if(hasColorscale(trace,"marker")){calcColorscale(trace,trace.marker.color,"marker","c")}if(hasColorscale(trace,"marker.line")){calcColorscale(trace,trace.marker.line.color,"marker.line","c")}}}},{"../../components/colorscale/calc":566,"../../components/colorscale/has_colorscale":572,"./subtypes":1037}],1020:[function(require,module,exports){"use strict";module.exports={PTS_LINESONLY:20,minTolerance:.2,toleranceGrowth:10,maxScreensAway:20}},{}],1021:[function(require,module,exports){"use strict";var Lib=require("../../lib");var Registry=require("../../registry");var attributes=require("./attributes");var constants=require("./constants");var subTypes=require("./subtypes");var handleXYDefaults=require("./xy_defaults");var handleMarkerDefaults=require("./marker_defaults");var handleLineDefaults=require("./line_defaults");var handleLineShapeDefaults=require("./line_shape_defaults");var handleTextDefaults=require("./text_defaults");var handleFillColorDefaults=require("./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),defaultMode=lenyAvg!==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)}}}}xmin=Math.max(xmin,0);xmax=Math.min(xmax,xa._length);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,{distance:pointData.maxHoverDistance,x0:xmin,x1:xmax,y0:yAvg,y1:yAvg,color:color});delete pointData.index;if(trace.text&&!Array.isArray(trace.text)){pointData.text=String(trace.text)}else pointData.text=trace.name;return[pointData]}}}},{"../../components/color":558,"../../components/fx":600,"../../lib":684,"../../registry":817,"./fill_hover_text":1022,"./get_trace_color":1024}],1026:[function(require,module,exports){"use strict";var Scatter={};var subtypes=require("./subtypes");Scatter.hasLines=subtypes.hasLines;Scatter.hasMarkers=subtypes.hasMarkers;Scatter.hasText=subtypes.hasText;Scatter.isBubble=subtypes.isBubble;Scatter.attributes=require("./attributes");Scatter.supplyDefaults=require("./defaults");Scatter.cleanData=require("./clean_data");Scatter.calc=require("./calc").calc;Scatter.arraysToCalcdata=require("./arrays_to_calcdata");Scatter.plot=require("./plot");Scatter.colorbar=require("./marker_colorbar");Scatter.style=require("./style").style;Scatter.styleOnSelect=require("./style").styleOnSelect;Scatter.hoverPoints=require("./hover");Scatter.selectPoints=require("./select");Scatter.animatable=true;Scatter.moduleType="trace";Scatter.name="scatter";Scatter.basePlotModule=require("../../plots/cartesian");Scatter.categories=["cartesian","svg","symbols","errorBarsOK","showLegend","scatter-like","zoomScale"];Scatter.meta={};module.exports=Scatter},{"../../plots/cartesian":743,"./arrays_to_calcdata":1014,"./attributes":1015,"./calc":1016,"./clean_data":1018,"./defaults":1021,"./hover":1025,"./marker_colorbar":1032,"./plot":1034,"./select":1035,"./style":1036,"./subtypes":1037}],1027:[function(require,module,exports){"use strict";var isArrayOrTypedArray=require("../../lib").isArrayOrTypedArray;var hasColorscale=require("../../components/colorscale/has_colorscale");var colorscaleDefaults=require("../../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":568,"../../components/colorscale/has_colorscale":572,"../../lib":684}],1028:[function(require,module,exports){"use strict";var BADNUM=require("../../constants/numerical").BADNUM;var Lib=require("../../lib");var segmentsIntersect=Lib.segmentsIntersect;var constrain=Lib.constrain;var constants=require("./constants");module.exports=function linePoints(d,opts){var xa=opts.xaxis;var ya=opts.yaxis;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;var clusterStartPt,clusterEndPt,clusterHighPt,clusterLowPt;var thisPt;var clusterHighFirst;var clusterUnitVector;var thisVector;var clusterRefDist,clusterHighVal,clusterLowVal,thisVal;var clusterMinDeviation,clusterMaxDeviation,thisDeviation;function getPt(index){var di=d[index];if(!di)return false;var x=xa.c2p(di.x);var y=ya.c2p(di.y);if(x===BADNUM||y===BADNUM)return di.intoCenter||false;return[x,y]}function crossesViewport(xFrac0,yFrac0,xFrac1,yFrac1){var dx=xFrac1-xFrac0;var dy=yFrac1-yFrac0;var dx0=.5-xFrac0;var dy0=.5-yFrac0;var norm2=dx*dx+dy*dy;var dot=dx*dx0+dy*dy0;if(dot>0&&dot1||Math.abs(ptInt.y-out[0][1])>1)){ptInt=[ptInt.x,ptInt.y];if(ptCount&&ptDist(ptInt,pt1)xEdge1||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}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}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);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];if(xSame&&ySame)return;if(pti>1){var xSame2=x===pts[pti-2][0];var ySame2=y===pts[pti-2][1];if(xSame&&(x===xEdge0||x===xEdge1)&&xSame2){if(ySame2)pti--;else pts[pti-1]=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(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]/xa._length;latestYFrac=pt[1]/ya._length;xEdge=pt[0]xEdge1?xEdge1:0;yEdge=pt[1]yEdge1?yEdge1:0;if(xEdge||yEdge){if(!pti){pts[pti++]=[xEdge||pt[0],yEdge||pt[1]]}else if(lastFarPt){var intersections=getEdgeIntersections(lastFarPt,pt);if(intersections.length>1){updateEdgesForReentry(intersections[0]);pts[pti++]=intersections[1]}}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)){if(lastFarPt){if(lastXEdge!==xEdge&&lastYEdge!==yEdge){if(lastXEdge&&lastYEdge){updateEdge(getClosestCorner(lastFarPt,pt))}else{updateEdge([lastXEdge||xEdge,lastYEdge||yEdge])}}else if(lastXEdge&&lastYEdge){updateEdge([lastXEdge,lastYEdge])}}updateEdge([xEdge,yEdge])}else if(lastXEdge-xEdge&&lastYEdge-yEdge){updateEdge([xEdge||lastXEdge,yEdge||lastYEdge])}lastFarPt=pt;lastXEdge=xEdge;lastYEdge=yEdge}else{if(lastFarPt){updateEdgesForReentry(getEdgeIntersections(lastFarPt,pt)[0])}pts[pti++]=pt}}for(i=0;igetTolerance(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=d.length||!thisPt)break;addPt(thisPt);clusterStartPt=thisPt}if(lastFarPt)updateEdge([lastXEdge||lastFarPt[0],lastYEdge||lastFarPt[1]]);segments.push(pts.slice(0,pti))}return segments}},{"../../constants/numerical":661,"../../lib":684,"./constants":1020}],1029:[function(require,module,exports){"use strict";module.exports=function handleLineShapeDefaults(traceIn,traceOut,coerce){var shape=coerce("line.shape");if(shape==="spline")coerce("line.smoothing")}},{}],1030:[function(require,module,exports){"use strict";module.exports=function linkTraces(gd,plotinfo,cdscatter){var trace,i;var prevtrace=null;for(i=0;i0?Math.max(baseSize,sizeMin):0}}},{"fast-isnumeric":214}],1032:[function(require,module,exports){"use strict";module.exports={container:"marker",min:"cmin",max:"cmax"}},{}],1033:[function(require,module,exports){"use strict";var Color=require("../../components/color");var hasColorscale=require("../../components/colorscale/has_colorscale");var colorscaleDefaults=require("../../components/colorscale/defaults");var subTypes=require("./subtypes");module.exports=function markerDefaults(traceIn,traceOut,defaultColor,layout,coerce,opts){var isBubble=subTypes.isBubble(traceIn),lineColor=(traceIn.line||{}).color,defaultMLC;opts=opts||{};if(lineColor)defaultColor=lineColor;coerce("marker.symbol");coerce("marker.opacity",isBubble?.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(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":558,"../../components/colorscale/defaults":568,"../../components/colorscale/has_colorscale":572,"./subtypes":1037}],1034:[function(require,module,exports){"use strict";var d3=require("d3");var Registry=require("../../registry");var Lib=require("../../lib");var Drawing=require("../../components/drawing");var subTypes=require("./subtypes");var linePoints=require("./line_points");var linkTraces=require("./link_traces");var polygonTester=require("../../lib/polygon").tester;module.exports=function plot(gd,plotinfo,cdscatter,scatterLayer,transitionOpts,makeOnCompleteCallback){var i,uids,join,onComplete;var isFullReplot=!transitionOpts;var hasTransition=!!transitionOpts&&transitionOpts.duration>0;join=scatterLayer.selectAll("g.trace").data(cdscatter,function(d){return d[0].trace.uid});join.enter().append("g").attr("class",function(d){return"trace scatter trace"+d[0].trace.uid}).style("stroke-miterlimit",2);linkTraces(gd,plotinfo,cdscatter);createFills(gd,scatterLayer,plotinfo);for(i=0,uids={};iidx2?1:-1});if(hasTransition){if(makeOnCompleteCallback){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(){scatterLayer.selectAll("g.trace").each(function(d,i){plotOne(gd,i,plotinfo,d,cdscatter,this,transitionOpts)})})}else{scatterLayer.selectAll("g.trace").each(function(d,i){plotOne(gd,i,plotinfo,d,cdscatter,this,transitionOpts)})}if(isFullReplot){join.exit().remove()}scatterLayer.selectAll("path:not([d])").remove()};function createFills(gd,scatterLayer,plotinfo){var trace;scatterLayer.selectAll("g.trace").each(function(d){var tr=d3.select(this);trace=d[0].trace;if(trace._nexttrace){trace._nextFill=tr.select(".js-fill.js-tonext");if(!trace._nextFill.size()){var loc=":first-child";if(tr.select(".js-fill.js-tozero").size()){loc+=" + *"}trace._nextFill=tr.insert("path",loc).attr("class","js-fill js-tonext")}}else{tr.selectAll(".js-fill.js-tonext").remove();trace._nextFill=null}if(trace.fill&&(trace.fill.substr(0,6)==="tozero"||trace.fill==="toself"||trace.fill.substr(0,2)==="to"&&!trace._prevtrace)){trace._ownFill=tr.select(".js-fill.js-tozero");if(!trace._ownFill.size()){trace._ownFill=tr.insert("path",":first-child").attr("class","js-fill js-tozero")}}else{tr.selectAll(".js-fill.js-tozero").remove();trace._ownFill=null}tr.selectAll(".js-fill").call(Drawing.setClipUrl,plotinfo.layerClipId)})}function plotOne(gd,idx,plotinfo,cdscatter,cdscatterAll,element,transitionOpts){var join,i;selectMarkers(gd,idx,plotinfo,cdscatter,cdscatterAll);var hasTransition=!!transitionOpts&&transitionOpts.duration>0;function transition(selection){return hasTransition?selection.transition():selection}var xa=plotinfo.xaxis,ya=plotinfo.yaxis;var trace=cdscatter[0].trace,line=trace.line,tr=d3.select(element);Registry.getComponentMethod("errorbars","plot")(tr,plotinfo,transitionOpts);if(trace.visible!==true)return;transition(tr).style("opacity",trace.opacity);var ownFillEl3,tonext;var ownFillDir=trace.fill.charAt(trace.fill.length-1);if(ownFillDir!=="x"&&ownFillDir!=="y")ownFillDir="";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,thisrevpath,fullpath="",revpath="",pathfn,revpathbase,revpathfn,pt0,lastSegment,pt1,thisPolygons;var segments=[],makeUpdate=Lib.noop;ownFillEl3=trace._ownFill;if(subTypes.hasLines(trace)||trace.fill!=="none"){if(tonext){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]){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){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});thisPolygons=trace._polygons=new Array(segments.length);for(i=0;i1){var el=d3.select(this);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=tr.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);function clearFill(selection){transition(selection).attr("d","M0,0Z")}if(segments.length){if(ownFillEl3){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)}transition(ownFillEl3).attr("d","M"+pt1+"L"+pt0+"L"+fullpath.substr(1)).call(Drawing.singleFillStyle)}else{transition(ownFillEl3).attr("d",fullpath+"Z").call(Drawing.singleFillStyle)}}}else if(tonext){if(trace.fill.substr(0,6)==="tonext"&&fullpath&&prevRevpath){if(trace.fill==="tonext"){transition(tonext).attr("d",fullpath+"Z"+prevRevpath+"Z").call(Drawing.singleFillStyle)}else{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.vis})}function keyFunc(d){return d.id}function getKeyFunc(trace){if(trace.ids){return keyFunc}}function hideFilter(){return false}function makePoints(d){var join,selection,hasNode;var trace=d[0].trace;var s=d3.select(this);var showMarkers=subTypes.hasMarkers(trace);var showText=subTypes.hasText(trace);var keyFunc=getKeyFunc(trace);var markerFilter=hideFilter;var textFilter=hideFilter;if(showMarkers){markerFilter=trace.marker.maxdisplayed||trace._needsCull?visFilter:Lib.identity}if(showText){textFilter=trace.marker.maxdisplayed||trace._needsCull?visFilter:Lib.identity}selection=s.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()}selection=s.selectAll("g");join=selection.data(textFilter,keyFunc);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){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()}var pointSelection=tr.selectAll(".points");join=pointSelection.data([cdscatter]);pointSelection.each(makePoints);join.enter().append("g").classed("points",true).each(makePoints);join.exit().remove();join.each(function(d){var hasClipOnAxisFalse=d[0].trace.cliponaxis===false;Drawing.setClipUrl(d3.select(this),hasClipOnAxisFalse?null:plotinfo.layerClipId)})}function selectMarkers(gd,idx,plotinfo,cdscatter,cdscatterAll){var xa=plotinfo.xaxis,ya=plotinfo.yaxis,xr=d3.extent(Lib.simpleMap(xa.range,xa.r2c)),yr=d3.extent(Lib.simpleMap(ya.range,ya.r2c));var trace=cdscatter[0].trace;if(!subTypes.hasMarkers(trace))return;var mnum=trace.marker.maxdisplayed;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]}),inc=Math.ceil(cd.length/mnum),tnum=0;cdscatterAll.forEach(function(cdj,j){var tracei=cdj[0].trace;if(subTypes.hasMarkers(tracei)&&tracei.marker.maxdisplayed>0&&j=0)textOffset[1]+=1;if(tp.indexOf("top")>=0)textOffset[1]-=1;if(tp.indexOf("left")>=0)textOffset[0]-=1;if(tp.indexOf("right")>=0)textOffset[0]+=1;return textOffset}function calculateSize(sizeIn,sizeFn){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=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":658,"../../constants/gl3d_markers":659,"../../lib":684,"../../lib/gl_format_color":680,"../../lib/str2rgbarray":707,"../scatter/make_bubble_size_func":1031,"./calc_errors":1042,"delaunay-triangulate":149,"gl-error3d":237,"gl-line3d":245,"gl-mesh3d":268,"gl-scatter3d":283}],1044:[function(require,module,exports){"use strict";var Registry=require("../../registry");var Lib=require("../../lib");var subTypes=require("../scatter/subtypes");var handleMarkerDefaults=require("../scatter/marker_defaults");var handleLineDefaults=require("../scatter/line_defaults");var handleTextDefaults=require("../scatter/text_defaults");var attributes=require("./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,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,defaultColor,{axis:"z"});errorBarsSupplyDefaults(traceIn,traceOut,defaultColor,{axis:"y",inherit:"z"});errorBarsSupplyDefaults(traceIn,traceOut,defaultColor,{axis:"x",inherit:"z"})};function handleXYZDefaults(traceIn,traceOut,coerce,layout){var len=0,x=coerce("x"),y=coerce("y"),z=coerce("z");var handleCalendarDefaults=Registry.getComponentMethod("calendars","handleTraceDefaults");handleCalendarDefaults(traceIn,traceOut,["x","y","z"],layout);if(x&&y&&z){len=Math.min(x.length,y.length,z.length);traceOut._length=traceOut._xlength=traceOut._ylength=traceOut._zlength=len}return len}},{"../../lib":684,"../../registry":817,"../scatter/line_defaults":1027,"../scatter/marker_defaults":1033,"../scatter/subtypes":1037,"../scatter/text_defaults":1038,"./attributes":1040}],1045:[function(require,module,exports){"use strict";var Scatter3D={};Scatter3D.plot=require("./convert");Scatter3D.attributes=require("./attributes");Scatter3D.markerSymbols=require("../../constants/gl3d_markers");Scatter3D.supplyDefaults=require("./defaults");Scatter3D.colorbar=require("../scatter/marker_colorbar");Scatter3D.calc=require("./calc");Scatter3D.moduleType="trace";Scatter3D.name="scatter3d";Scatter3D.basePlotModule=require("../../plots/gl3d");Scatter3D.categories=["gl3d","symbols","showLegend"];Scatter3D.meta={};module.exports=Scatter3D},{"../../constants/gl3d_markers":659,"../../plots/gl3d":774,"../scatter/marker_colorbar":1032,"./attributes":1040,"./calc":1041,"./convert":1043,"./defaults":1044}],1046:[function(require,module,exports){"use strict";var scatterAttrs=require("../scatter/attributes");var plotAttrs=require("../../plots/attributes");var colorAttributes=require("../../components/colorscale/attributes");var colorbarAttrs=require("../../components/colorbar/attributes");var extendFlat=require("../../lib/extend").extendFlat;var scatterMarkerAttrs=scatterAttrs.marker,scatterLineAttrs=scatterAttrs.line,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"]}),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":559,"../../components/colorscale/attributes":565,"../../lib/extend":673,"../../plots/attributes":729,"../scatter/attributes":1015}],1047:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var calcColorscale=require("../scatter/colorscale_calc");var arraysToCalcdata=require("../scatter/arrays_to_calcdata");var calcSelection=require("../scatter/calc_selection");var calcMarkerSize=require("../scatter/calc").calcMarkerSize;var lookupCarpet=require("../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;trace.xaxis=carpet.xaxis;trace.yaxis=carpet.yaxis;var serieslen=trace._length;var cd=new Array(serieslen);var a,b;var needsCull=false;for(i=0;i0){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("
");return scatterPointData}},{"../scatter/hover":1025}],1051:[function(require,module,exports){"use strict";var ScatterCarpet={};ScatterCarpet.attributes=require("./attributes");ScatterCarpet.supplyDefaults=require("./defaults");ScatterCarpet.colorbar=require("../scatter/marker_colorbar");ScatterCarpet.calc=require("./calc");ScatterCarpet.plot=require("./plot");ScatterCarpet.style=require("../scatter/style").style;ScatterCarpet.styleOnSelect=require("../scatter/style").styleOnSelect;ScatterCarpet.hoverPoints=require("./hover");ScatterCarpet.selectPoints=require("../scatter/select");ScatterCarpet.eventData=require("./event_data");ScatterCarpet.moduleType="trace";ScatterCarpet.name="scattercarpet";ScatterCarpet.basePlotModule=require("../../plots/cartesian");ScatterCarpet.categories=["svg","carpet","symbols","showLegend","carpetDependent","zoomScale"];ScatterCarpet.meta={};module.exports=ScatterCarpet},{"../../plots/cartesian":743,"../scatter/marker_colorbar":1032,"../scatter/select":1035,"../scatter/style":1036,"./attributes":1046,"./calc":1047,"./defaults":1048,"./event_data":1049,"./hover":1050,"./plot":1052}],1052:[function(require,module,exports){"use strict";var scatterPlot=require("../scatter/plot");var Axes=require("../../plots/cartesian/axes");var Drawing=require("../../components/drawing");module.exports=function plot(gd,plotinfoproxy,data,layer){var i,trace,node;var carpet=data[0][0].carpet;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")}},{"../../components/fx":600,"../../constants/numerical":661,"../../plots/cartesian/axes":732,"../scatter/fill_hover_text":1022,"../scatter/get_trace_color":1024,"./attributes":1053}],1058:[function(require,module,exports){"use strict";var ScatterGeo={};ScatterGeo.attributes=require("./attributes");ScatterGeo.supplyDefaults=require("./defaults");ScatterGeo.colorbar=require("../scatter/marker_colorbar");ScatterGeo.calc=require("./calc");ScatterGeo.plot=require("./plot");ScatterGeo.style=require("./style");ScatterGeo.styleOnSelect=require("../scatter/style").styleOnSelect;ScatterGeo.hoverPoints=require("./hover");ScatterGeo.eventData=require("./event_data");ScatterGeo.selectPoints=require("./select");ScatterGeo.moduleType="trace";ScatterGeo.name="scattergeo";ScatterGeo.basePlotModule=require("../../plots/geo");ScatterGeo.categories=["geo","symbols","showLegend","scatter-like"];ScatterGeo.meta={};module.exports=ScatterGeo},{"../../plots/geo":762,"../scatter/marker_colorbar":1032,"../scatter/style":1036,"./attributes":1053,"./calc":1054,"./defaults":1055,"./event_data":1056,"./hover":1057,"./plot":1059,"./select":1060,"./style":1061}],1059:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");var BADNUM=require("../../constants/numerical").BADNUM;var getTopojsonFeatures=require("../../lib/topojson_utils").getTopojsonFeatures;var locationToFeature=require("../../lib/geo_location_utils").locationToFeature;var geoJsonUtils=require("../../lib/geojson_utils");var subTypes=require("../scatter/subtypes");var style=require("./style");module.exports=function plot(gd,geo,calcData){for(var i=0;iconstants.TOO_MANY_POINTS?"rect":subTypes.hasMarkers(trace)?"rect":"round";if(hasNaN&&trace.connectgaps){var lastX=linePositions[0];var lastY=linePositions[1];for(i=0;i1?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/.8+1:0;var yPad=-vSign*xPad-vSign*.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":583,"../../constants/interactions":660,"../../lib":684,"../../lib/gl_format_color":680,"../../plots/cartesian/axes":732,"../../plots/cartesian/axis_ids":735,"../../registry":817,"../scatter/make_bubble_size_func":1031,"../scatter/subtypes":1037,"./constants":1063,"color-normalize":107,"fast-isnumeric":214,"svg-path-sdf":497}],1065:[function(require,module,exports){"use strict";var Lib=require("../../lib");var Registry=require("../../registry");var attributes=require("./attributes");var constants=require("../scatter/constants");var subTypes=require("../scatter/subtypes");var handleXYDefaults=require("../scatter/xy_defaults");var handleMarkerDefaults=require("../scatter/marker_defaults");var handleLineDefaults=require("../scatter/line_defaults");var handleFillColorDefaults=require("../scatter/fillcolor_defaults");var handleTextDefaults=require("../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=TOO_MANY_POINTS){opts.marker.cluster=stash.tree}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);scene.count++;stash._scene=scene;stash.index=scene.count-1;stash.x=x;stash.y=y;stash.positions=positions;stash.count=count;gd.firstscatter=false;return[{x:false,y:false,t:stash,trace:trace}]}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}function sceneUpdate(gd,subplot){var scene=subplot._scene;var resetOpts={count:0,dirty:true,lineOptions:[],fillOptions:[],markerOptions:[],markerSelectedOptions:[],markerUnselectedOptions:[],errorXOptions:[],errorYOptions:[],textOptions:[],textSelectedOptions:[],textUnselectedOptions:[]};var initOpts={selectBatch:null,unselectBatch:null,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();scene.update=function update(opt){var i;var opts=new Array(scene.count);for(i=0;i=0?Math.floor((xval+180)/360):Math.ceil((xval-180)/360);var lonShift=winding*360;var xval2=xval-lonShift;function distFn(d){var lonlat=d.lonlat;if(lonlat[0]===BADNUM)return Infinity;var lon=Lib.wrap180(lonlat[0]);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);if(pointData.index===false)return;var di=cd[pointData.index];var lonlat=di.lonlat;var lonlatShifted=[Lib.wrap180(lonlat[0])+lonShift,lonlat[1]];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);return[pointData]};function getExtraText(trace,di,labels){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=[];function format(v){return v+"°"}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("
")}},{"../../components/fx":600,"../../constants/numerical":661,"../../lib":684,"../scatter/fill_hover_text":1022,"../scatter/get_trace_color":1024}],1072:[function(require,module,exports){"use strict";var ScatterMapbox={};ScatterMapbox.attributes=require("./attributes");ScatterMapbox.supplyDefaults=require("./defaults");ScatterMapbox.colorbar=require("../scatter/marker_colorbar");ScatterMapbox.calc=require("../scattergeo/calc");ScatterMapbox.plot=require("./plot");ScatterMapbox.hoverPoints=require("./hover");ScatterMapbox.eventData=require("./event_data");ScatterMapbox.selectPoints=require("./select");ScatterMapbox.style=function(_,cd){if(cd){var trace=cd[0].trace;trace._glTrace.update(cd)}};ScatterMapbox.moduleType="trace";ScatterMapbox.name="scattermapbox";ScatterMapbox.basePlotModule=require("../../plots/mapbox");ScatterMapbox.categories=["mapbox","gl","symbols","showLegend","scatterlike"];ScatterMapbox.meta={};module.exports=ScatterMapbox},{"../../plots/mapbox":789,"../scatter/marker_colorbar":1032,"../scattergeo/calc":1054,"./attributes":1067,"./defaults":1069,"./event_data":1070,"./hover":1071,"./plot":1073,"./select":1074}],1073:[function(require,module,exports){"use strict";var convert=require("./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"]}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")}module.exports={hoverPoints:hoverPoints,makeHoverPointText:makeHoverPointText}},{"../../lib":684,"../../plots/cartesian/axes":732,"../scatter/hover":1025}],1079:[function(require,module,exports){"use strict";module.exports={moduleType:"trace",name:"scatterpolar",basePlotModule:require("../../plots/polar"),categories:["polar","symbols","showLegend","scatter-like"],attributes:require("./attributes"),supplyDefaults:require("./defaults"),colorbar:require("../scatter/marker_colorbar"),calc:require("./calc"),plot:require("./plot"),style:require("../scatter/style").style,hoverPoints:require("./hover").hoverPoints,selectPoints:require("../scatter/select"),meta:{}}},{"../../plots/polar":798,"../scatter/marker_colorbar":1032,"../scatter/select":1035,"../scatter/style":1036,"./attributes":1075,"./calc":1076,"./defaults":1077,"./hover":1078,"./plot":1080}],1080:[function(require,module,exports){"use strict";var scatterPlot=require("../scatter/plot");var BADNUM=require("../../constants/numerical").BADNUM;module.exports=function plot(gd,subplot,moduleCalcData){var i,j;var plotinfo={xaxis:subplot.xaxis,yaxis:subplot.yaxis,plot:subplot.framework,layerClipId:subplot._hasClipOnAxisFalse?subplot.clipIds.forTraces:null};var radialAxis=subplot.radialAxis;var radialRange=radialAxis.range;var rFilter;if(radialRange[0]>radialRange[1]){rFilter=function(v){return v<=0}}else{rFilter=function(v){return v>=0}}for(i=0;i=0){rr=radialAxis.c2r(r)-rRange[0];rad=c2rad(theta);x[i]=positions[i*2]=rr*Math.cos(rad);y[i]=positions[i*2+1]=rr*Math.sin(rad)}else{x[i]=y[i]=positions[i*2]=positions[i*2+1]=NaN}}var options=ScatterGl.sceneOptions(container,subplot,trace,positions);if(options.fill&&!scene.fill2d)scene.fill2d=true;if(options.marker&&!scene.scatter2d)scene.scatter2d=true;if(options.line&&!scene.line2d)scene.line2d=true;if((options.errorX||options.errorY)&&!scene.error2d)scene.error2d=true;stash.tree=cluster(positions);if(options.marker&&count>=TOO_MANY_POINTS){options.marker.cluster=stash.tree}if(subTypes.hasMarkers(trace)){options.markerSel.positions=options.markerUnsel.positions=options.marker.positions}scene.lineOptions.push(options.line);scene.errorXOptions.push(options.errorX);scene.errorYOptions.push(options.errorY);scene.fillOptions.push(options.fill);scene.markerOptions.push(options.marker);scene.markerSelectedOptions.push(options.markerSel);scene.markerUnselectedOptions.push(options.markerUnsel);scene.count=cdata.length;stash._scene=scene;stash.index=traceIndex;stash.x=x;stash.y=y;stash.rawx=x;stash.rawy=y;stash.r=rArray;stash.theta=thetaArray;stash.positions=positions;stash.count=count});return ScatterGl.plot(container,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 angularAxis=subplot.angularAxis;var cdi=newPointData.cd[newPointData.index];var trace=newPointData.trace;cdi.r=rArray[newPointData.index];cdi.theta=thetaArray[newPointData.index];cdi.rad=angularAxis.c2rad(cdi.theta,trace.thetaunit);if(!subplot.isPtWithinSector(cdi))return;newPointData.xLabelVal=undefined;newPointData.yLabelVal=undefined;newPointData.extraText=makeHoverPointText(cdi,trace,subplot);return scatterPointData}module.exports={moduleType:"trace",name:"scatterpolargl",basePlotModule:require("../../plots/polar"),categories:["gl","regl","polar","symbols","showLegend","scatter-like"],attributes:require("./attributes"),supplyDefaults:require("./defaults"),colorbar:require("../scatter/marker_colorbar"),calc:calc,plot:plot,hoverPoints:hoverPoints,style:ScatterGl.style,selectPoints:ScatterGl.selectPoints,meta:{}}},{"../../plots/cartesian/axes":732,"../../plots/polar":798,"../scatter/colorscale_calc":1019,"../scatter/marker_colorbar":1032,"../scatter/subtypes":1037,"../scattergl":1066,"../scattergl/constants":1063,"../scatterpolar/hover":1078,"./attributes":1081,"./defaults":1082,"fast-isnumeric":214,"point-cluster":436}],1084:[function(require,module,exports){"use strict";var scatterAttrs=require("../scatter/attributes");var plotAttrs=require("../../plots/attributes");var colorAttributes=require("../../components/colorscale/attributes");var colorbarAttrs=require("../../components/colorbar/attributes");var dash=require("../../components/drawing/attributes").dash;var extendFlat=require("../../lib/extend").extendFlat;var scatterMarkerAttrs=scatterAttrs.marker,scatterLineAttrs=scatterAttrs.line,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"]}),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}},{"../../components/colorbar/attributes":559,"../../components/colorscale/attributes":565,"../../components/drawing/attributes":582,"../../lib/extend":673,"../../plots/attributes":729,"../scatter/attributes":1015}],1085:[function(require,module,exports){"use strict";var isNumeric=require("fast-isnumeric");var calcColorscale=require("../scatter/colorscale_calc");var arraysToCalcdata=require("../scatter/arrays_to_calcdata");var calcSelection=require("../scatter/calc_selection");var calcMarkerSize=require("../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;for(i=0;i");return scatterPointData}},{"../../plots/cartesian/axes":732,"../scatter/hover":1025}],1089:[function(require,module,exports){"use strict";var ScatterTernary={};ScatterTernary.attributes=require("./attributes");ScatterTernary.supplyDefaults=require("./defaults");ScatterTernary.colorbar=require("../scatter/marker_colorbar");ScatterTernary.calc=require("./calc");ScatterTernary.plot=require("./plot");ScatterTernary.style=require("../scatter/style").style;ScatterTernary.styleOnSelect=require("../scatter/style").styleOnSelect;ScatterTernary.hoverPoints=require("./hover");ScatterTernary.selectPoints=require("../scatter/select");ScatterTernary.eventData=require("./event_data");ScatterTernary.moduleType="trace";ScatterTernary.name="scatterternary";ScatterTernary.basePlotModule=require("../../plots/ternary");ScatterTernary.categories=["ternary","symbols","showLegend","scatter-like"];ScatterTernary.meta={};module.exports=ScatterTernary},{"../../plots/ternary":810,"../scatter/marker_colorbar":1032,"../scatter/select":1035,"../scatter/style":1036,"./attributes":1084,"./calc":1085,"./defaults":1086,"./event_data":1087,"./hover":1088,"./plot":1090}],1090:[function(require,module,exports){"use strict";var scatterPlot=require("../scatter/plot");module.exports=function plot(gd,ternary,moduleCalcData){var plotContainer=ternary.plotContainer;plotContainer.select(".scatterlayer").selectAll("*").remove();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":1034}],1091:[function(require,module,exports){"use strict";var scatterGlAttrs=require("../scattergl/attributes");var cartesianIdRegex=require("../../plots/cartesian/constants").idRegex;var templatedArray=require("../../plot_api/plot_template").templatedArray;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"},editType:"calc+clearAxisTypes"}),text:scatterGlAttrs.text,marker:scatterGlAttrs.marker,xaxes:makeAxesValObject("x"),yaxes:makeAxesValObject("y"),diagonal:{visible:{valType:"boolean",dflt:true,editType:"calc"},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}},{"../../plot_api/plot_template":722,"../../plots/cartesian/constants":737,"../scattergl/attributes":1062}],1092:[function(require,module,exports){"use strict";var createLine=require("regl-line2d");var Registry=require("../../registry");var Lib=require("../../lib");var prepareRegl=require("../../lib/prepare_regl");var getModuleCalcData=require("../../plots/get_data").getModuleCalcData;var Cartesian=require("../../plots/cartesian");var AxisIDs=require("../../plots/cartesian/axis_ids");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){drawGrid(gd)}_module.plot(gd,{},splomCalcData)}function drag(gd){var cd=gd.calcdata;var fullLayout=gd._fullLayout;if(fullLayout._hasOnlyLargeSploms){drawGrid(gd)}for(var i=0;i1&&p0j&&showUpper){layout._splomSubplots[id]=1}else if(iTOO_MANY_POINTS;for(i=0,k=0;i2){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[.5,.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));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{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",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"}}},{}],1109:[function(require,module,exports){"use strict";var c=require("./constants");var extendFlat=require("../../lib/extend").extendFlat;var isNumeric=require("fast-isnumeric");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);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={key:trace.index,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,groupHeight:groupHeight,rowBlocks:rowBlocks,headerRowBlocks:headerRowBlocks,scrollY:0,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,calcdata:undefined,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=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":673,"./constants":1108,"fast-isnumeric":214}],1110:[function(require,module,exports){"use strict";var extendFlat=require("../../lib/extend").extendFlat;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});return[revolverPanel1,revolverPanel2,headerPanel]};exports.splitToCells=function(d){var fromTo=rowFromTo(d);return(d.values||[]).slice(fromTo[0],fromTo[1]).map(function(v,i){var buster=typeof v==="string"&&v.match(/[<$&> ]/)?"_keybuster_"+Math.random():"";return{keyWithinBlock:i+buster,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];var rowFrom=rowBlock?rowBlock.rows[0].rowIndex:0;var rowTo=rowBlock?rowFrom+rowBlock.rows.length:0;return[rowFrom,rowTo]}},{"../../lib/extend":673}],1111:[function(require,module,exports){"use strict";var Lib=require("../../lib");var attributes=require("./attributes");var handleDomainDefaults=require("../../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/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(/pTop){pages.push(blockIndex)}pTop+=rowsHeight}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)}}if(pages[0]%2){pages.reverse()}cellsColumnBlock.each(function(d,i){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+")"});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){var d=eventD.calcdata?eventD.calcdata:eventD;var tableControlView=allTableControlView.filter(function(dd){return d.key===dd.key});var multiplier=optionalMultiplier||d.scrollbarState.dragMultiplier;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)}}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(){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){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()});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});cellTextHolder.selectAll("tspan.line").remove();populateCellText(cellTextHolder.select("."+c.cn.cellText),tableControlView,columnBlock);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){l.rows[rowIndex].rowHeight=finalHeight;columnBlock.selectAll("."+c.cn.columnCell).call(setCellHeightAndPositionY);updateBlockYPosition(null,columnBlock.filter(cellsBlock),0);renderScrollbarKit(tableControlView,gd,true)}cellTextHolder.attr("transform",function(){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;i0){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);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)}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);if(hovermode==="closest"){if(closePtData)return[closePtData];return closeData}if(closePtData){closeData.push(closePtData);return closeData}return closeData}},{"../../lib":684,"../../plots/cartesian/axes":732,"../box/hover":843,"./helpers":1117}],1119:[function(require,module,exports){"use strict";module.exports={attributes:require("./attributes"),layoutAttributes:require("./layout_attributes"),supplyDefaults:require("./defaults"),supplyLayoutDefaults:require("./layout_defaults"),calc:require("./calc"),setPositions:require("./set_positions"),plot:require("./plot"),style:require("./style"),styleOnSelect:require("../scatter/style").styleOnSelect,hoverPoints:require("./hover"),selectPoints:require("../box/select"),moduleType:"trace",name:"violin",basePlotModule:require("../../plots/cartesian"),categories:["cartesian","svg","symbols","oriented","box-violin","showLegend","violinLayout","zoomScale"],meta:{}}},{"../../plots/cartesian":743,"../box/select":848,"../scatter/style":1036,"./attributes":1114,"./calc":1115,"./defaults":1116,"./hover":1118,"./layout_attributes":1120,"./layout_defaults":1121,"./plot":1122,"./set_positions":1123,"./style":1124}],1120:[function(require,module,exports){"use strict";var boxLayoutAttrs=require("../box/layout_attributes");var extendFlat=require("../../lib").extendFlat;module.exports={violinmode:extendFlat({},boxLayoutAttrs.boxmode,{}),violingap:extendFlat({},boxLayoutAttrs.boxgap,{}),violingroupgap:extendFlat({},boxLayoutAttrs.boxgroupgap,{})}},{"../../lib":684,"../box/layout_attributes":845}],1121:[function(require,module,exports){"use strict";var Lib=require("../../lib");var layoutAttributes=require("./layout_attributes");var boxLayoutDefaults=require("../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":684,"../box/layout_defaults":846,"./layout_attributes":1120}],1122:[function(require,module,exports){"use strict";var d3=require("d3");var Lib=require("../../lib");var Drawing=require("../../components/drawing");var boxPlot=require("../box/plot");var linePoints=require("../scatter/line_points");var helpers=require("./helpers");module.exports=function plot(gd,plotinfo,cd,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:.75,shape:"spline",simplify:true});return Drawing.smoothopen(segments[0],1)}var traces=violinLayer.selectAll("g.trace.violins").data(cd,function(d){return d[0].trace.uid});traces.enter().append("g").attr("class","trace violins");traces.exit().remove();traces.order();traces.each(function(d){var cd0=d[0];var t=cd0.t;var trace=cd0.trace;var sel=d3.select(this);if(!plotinfo.isRangePlot)cd0.node3=sel;var numViolins=fullLayout._numViolins;var group=fullLayout.violinmode==="group"&&numViolins>1;var groupFraction=1-fullLayout.violingap;var bdPos=t.bdPos=t.dPos*groupFraction*(1-fullLayout.violingroupgap)/(group?numViolins:1);var bPos=t.bPos=group?2*t.dPos*(-.5+(t.num+.5)/numViolins)*groupFraction:0;t.wHover=t.dPos*(group?groupFraction/numViolins:1);if(trace.visible!==true||t.empty){d3.select(this).remove();return}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 groupStats=fullLayout._violinScaleGroupStats[trace.scalegroup];var violins=sel.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;switch(trace.scalemode){case"width":scale=groupStats.maxWidth/bdPos;break;case"count":scale=groupStats.maxWidth/bdPos*(groupStats.maxCount/d.pts.length);break}var pathPos,pathNeg,path;var i,k,pts,pt;if(hasPositiveSide){pts=new Array(len);for(i=0;imaxCnt){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":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[0]&&cvcoercedValue[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 cvcoercedValue[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[1]};case"{}":return function(v){return coercedValue.indexOf(d2cTarget(v))!==-1};case"}{":return function(v){return coercedValue.indexOf(d2cTarget(v))===-1}}}},{"../constants/filter_ops":657,"../lib":684,"../plots/cartesian/axes":732,"../registry":817,"./helpers":1128}],1127:[function(require,module,exports){"use strict";var Lib=require("../lib");var PlotSchema=require("../plot_api/plot_schema");var Plots=require("../plots/plots");var pointsAccessorFunction=require("./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"};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=node.value){this.search_node_=node;return node}}}else{while(node=node.next){if(x-EPSILON&&val0){return Orientation.CCW}else{return Orientation.CW}}function inScanArea(pa,pb,pc,pd){var oadb=(pa.x-pb.x)*(pd.y-pb.y)-(pd.x-pb.x)*(pa.y-pb.y);if(oadb>=-EPSILON){return false}var oadc=(pa.x-pc.x)*(pd.y-pc.y)-(pd.x-pc.x)*(pa.y-pc.y);if(oadc<=EPSILON){return false}return true}function isAngleObtuse(pa,pb,pc){var ax=pb.x-pa.x;var ay=pb.y-pa.y;var bx=pc.x-pa.x;var by=pc.y-pa.y;return ax*bx+ay*by<0}function triangulate(tcx){tcx.initTriangulation();tcx.createAdvancingFront();sweepPoints(tcx);finalizationPolygon(tcx)}function sweepPoints(tcx){var i,len=tcx.pointCount();for(i=1;iedge.q.x;if(isEdgeSideOfTriangle(node.triangle,edge.p,edge.q)){return}fillEdgeEvent(tcx,edge,node);edgeEventByPoints(tcx,edge.p,edge.q,node.triangle,edge.q)}function edgeEventByPoints(tcx,ep,eq,triangle,point){if(isEdgeSideOfTriangle(triangle,ep,eq)){return}var p1=triangle.pointCCW(point);var o1=orient2d(eq,p1,ep);if(o1===Orientation.COLLINEAR){throw new PointError("poly2tri EdgeEvent: Collinear not supported!",[eq,p1,ep])}var p2=triangle.pointCW(point);var o2=orient2d(eq,p2,ep);if(o2===Orientation.COLLINEAR){throw new PointError("poly2tri EdgeEvent: Collinear not supported!",[eq,p2,ep])}if(o1===o2){if(o1===Orientation.CW){triangle=triangle.neighborCCW(point)}else{triangle=triangle.neighborCW(point)}edgeEventByPoints(tcx,ep,eq,triangle,point)}else{flipEdgeEvent(tcx,ep,eq,triangle,point)}}function isEdgeSideOfTriangle(triangle,ep,eq){var index=triangle.edgeIndex(ep,eq);if(index!==-1){triangle.markConstrainedEdgeByIndex(index);var t=triangle.getNeighbor(index);if(t){t.markConstrainedEdgeByPoints(ep,eq)}return true}return false}function newFrontTriangle(tcx,point,node){var triangle=new Triangle(point,node.point,node.next.point);triangle.markNeighbor(node.triangle);tcx.addToMap(triangle);var new_node=new Node(point);new_node.next=node.next;new_node.prev=node;node.next.prev=new_node;node.next=new_node;if(!legalize(tcx,triangle)){tcx.mapTriangleToNodes(triangle)}return new_node}function fill(tcx,node){var triangle=new Triangle(node.prev.point,node.point,node.next.point);triangle.markNeighbor(node.prev.triangle);triangle.markNeighbor(node.triangle);tcx.addToMap(triangle);node.prev.next=node.next;node.next.prev=node.prev;if(!legalize(tcx,triangle)){tcx.mapTriangleToNodes(triangle)}}function fillAdvancingFront(tcx,n){var node=n.next;while(node.next){if(isAngleObtuse(node.point,node.next.point,node.prev.point)){break}fill(tcx,node);node=node.next}node=n.prev;while(node.prev){if(isAngleObtuse(node.point,node.next.point,node.prev.point)){break}fill(tcx,node);node=node.prev}if(n.next&&n.next.next){if(isBasinAngleRight(n)){fillBasin(tcx,n)}}}function isBasinAngleRight(node){var ax=node.point.x-node.next.next.point.x;var ay=node.point.y-node.next.next.point.y;assert(ay>=0,"unordered y");return ax>=0||Math.abs(ax)0}function rotateTrianglePair(t,p,ot,op){var n1,n2,n3,n4;n1=t.neighborCCW(p);n2=t.neighborCW(p);n3=ot.neighborCCW(op);n4=ot.neighborCW(op);var ce1,ce2,ce3,ce4;ce1=t.getConstrainedEdgeCCW(p);ce2=t.getConstrainedEdgeCW(p);ce3=ot.getConstrainedEdgeCCW(op);ce4=ot.getConstrainedEdgeCW(op);var de1,de2,de3,de4;de1=t.getDelaunayEdgeCCW(p);de2=t.getDelaunayEdgeCW(p);de3=ot.getDelaunayEdgeCCW(op);de4=ot.getDelaunayEdgeCW(op);t.legalize(p,op);ot.legalize(op,p);ot.setDelaunayEdgeCCW(p,de1);t.setDelaunayEdgeCW(p,de2);t.setDelaunayEdgeCCW(op,de3);ot.setDelaunayEdgeCW(op,de4);ot.setConstrainedEdgeCCW(p,ce1);t.setConstrainedEdgeCW(p,ce2);t.setConstrainedEdgeCCW(op,ce3);ot.setConstrainedEdgeCW(op,ce4);t.clearNeighbors();ot.clearNeighbors();if(n1){ot.markNeighbor(n1)}if(n2){t.markNeighbor(n2)}if(n3){t.markNeighbor(n3)}if(n4){ot.markNeighbor(n4)}t.markNeighbor(ot)}function fillBasin(tcx,node){if(orient2d(node.point,node.next.point,node.next.next.point)===Orientation.CCW){tcx.basin.left_node=node.next.next}else{tcx.basin.left_node=node.next}tcx.basin.bottom_node=tcx.basin.left_node;while(tcx.basin.bottom_node.next&&tcx.basin.bottom_node.point.y>=tcx.basin.bottom_node.next.point.y){tcx.basin.bottom_node=tcx.basin.bottom_node.next}if(tcx.basin.bottom_node===tcx.basin.left_node){return}tcx.basin.right_node=tcx.basin.bottom_node;while(tcx.basin.right_node.next&&tcx.basin.right_node.point.ytcx.basin.right_node.point.y;fillBasinReq(tcx,tcx.basin.bottom_node)}function fillBasinReq(tcx,node){if(isShallow(tcx,node)){return}fill(tcx,node);var o;if(node.prev===tcx.basin.left_node&&node.next===tcx.basin.right_node){return}else if(node.prev===tcx.basin.left_node){o=orient2d(node.point,node.next.point,node.next.next.point);if(o===Orientation.CW){return}node=node.next}else if(node.next===tcx.basin.right_node){o=orient2d(node.point,node.prev.point,node.prev.prev.point);if(o===Orientation.CCW){return}node=node.prev}else{if(node.prev.point.yheight){return true}return false}function fillEdgeEvent(tcx,edge,node){if(tcx.edge_event.right){fillRightAboveEdgeEvent(tcx,edge,node)}else{fillLeftAboveEdgeEvent(tcx,edge,node)}}function fillRightAboveEdgeEvent(tcx,edge,node){while(node.next.point.xedge.p.x){if(orient2d(edge.q,node.prev.point,edge.p)===Orientation.CW){fillLeftBelowEdgeEvent(tcx,edge,node)}else{node=node.prev}}}function fillLeftBelowEdgeEvent(tcx,edge,node){if(node.point.x>edge.p.x){if(orient2d(node.point,node.prev.point,node.prev.prev.point)===Orientation.CW){fillLeftConcaveEdgeEvent(tcx,edge,node)}else{fillLeftConvexEdgeEvent(tcx,edge,node);fillLeftBelowEdgeEvent(tcx,edge,node)}}}function fillLeftConvexEdgeEvent(tcx,edge,node){if(orient2d(node.prev.point,node.prev.prev.point,node.prev.prev.prev.point)===Orientation.CW){fillLeftConcaveEdgeEvent(tcx,edge,node.prev)}else{if(orient2d(edge.q,node.prev.prev.point,edge.p)===Orientation.CW){fillLeftConvexEdgeEvent(tcx,edge,node.prev)}else{}}}function fillLeftConcaveEdgeEvent(tcx,edge,node){fill(tcx,node.prev);if(node.prev.point!==edge.p){if(orient2d(edge.q,node.prev.point,edge.p)===Orientation.CW){if(orient2d(node.point,node.prev.point,node.prev.prev.point)===Orientation.CW){fillLeftConcaveEdgeEvent(tcx,edge,node)}else{}}}}function flipEdgeEvent(tcx,ep,eq,t,p){var ot=t.neighborAcross(p);assert(ot,"FLIP failed due to missing triangle!");var op=ot.oppositePoint(t,p);if(t.getConstrainedEdgeAcross(p)){var index=t.index(p);throw new PointError("poly2tri Intersecting Constraints",[p,op,t.getPoint((index+1)%3),t.getPoint((index+2)%3)])}if(inScanArea(p,t.pointCCW(p),t.pointCW(p),op)){rotateTrianglePair(t,p,ot,op);tcx.mapTriangleToNodes(t);tcx.mapTriangleToNodes(ot);if(p===eq&&op===ep){if(eq===tcx.edge_event.constrained_edge.q&&ep===tcx.edge_event.constrained_edge.p){t.markConstrainedEdgeByPoints(ep,eq);ot.markConstrainedEdgeByPoints(ep,eq);legalize(tcx,t);legalize(tcx,ot)}else{}}else{var o=orient2d(eq,op,ep);t=nextFlipTriangle(tcx,o,t,ot,p,op);flipEdgeEvent(tcx,ep,eq,t,p)}}else{var newP=nextFlipPoint(ep,eq,ot,op);flipScanEdgeEvent(tcx,ep,eq,t,ot,newP);edgeEventByPoints(tcx,ep,eq,t,p)}}function nextFlipTriangle(tcx,o,t,ot,p,op){var edge_index;if(o===Orientation.CCW){edge_index=ot.edgeIndex(p,op);ot.delaunay_edge[edge_index]=true;legalize(tcx,ot);ot.clearDelaunayEdges();return t}edge_index=t.edgeIndex(p,op);t.delaunay_edge[edge_index]=true;legalize(tcx,t);t.clearDelaunayEdges();return ot}function nextFlipPoint(ep,eq,ot,op){var o2d=orient2d(eq,op,ep);if(o2d===Orientation.CW){return ot.pointCCW(op)}else if(o2d===Orientation.CCW){return ot.pointCW(op)}else{throw new PointError("poly2tri [Unsupported] nextFlipPoint: opposing point on constrained edge!",[eq,op,ep])}}function flipScanEdgeEvent(tcx,ep,eq,flip_triangle,t,p){var ot=t.neighborAcross(p);assert(ot,"FLIP failed due to missing triangle");var op=ot.oppositePoint(t,p);if(inScanArea(eq,flip_triangle.pointCCW(eq),flip_triangle.pointCW(eq),op)){flipEdgeEvent(tcx,eq,op,ot,op)}else{var newP=nextFlipPoint(ep,eq,ot,op);flipScanEdgeEvent(tcx,ep,eq,flip_triangle,ot,newP)}}var kAlpha=.3;var Edge=function(p1,p2){this.p=p1;this.q=p2;if(p1.y>p2.y){this.q=p1;this.p=p2}else if(p1.y===p2.y){if(p1.x>p2.x){this.q=p1;this.p=p2}else if(p1.x===p2.x){throw new PointError("poly2tri Invalid Edge constructor: repeated points!",[p1])}}if(!this.q._p2t_edge_list){this.q._p2t_edge_list=[]}this.q._p2t_edge_list.push(this)};var Basin=function(){this.left_node=null;this.bottom_node=null;this.right_node=null;this.width=0;this.left_highest=false};Basin.prototype.clear=function(){this.left_node=null;this.bottom_node=null;this.right_node=null;this.width=0;this.left_highest=false};var EdgeEvent=function(){this.constrained_edge=null;this.right=false};var SweepContext=function(contour,options){options=options||{};this.triangles_=[];this.map_=[];this.points_=options.cloneArrays?contour.slice(0):contour;this.edge_list=[];this.pmin_=this.pmax_=null;this.front_=null;this.head_=null;this.tail_=null;this.af_head_=null;this.af_middle_=null;this.af_tail_=null;this.basin=new Basin;this.edge_event=new EdgeEvent;this.initEdges(this.points_)};SweepContext.prototype.addHole=function(polyline){this.initEdges(polyline);var i,len=polyline.length;for(i=0;ixmax&&(xmax=p.x);p.xymax&&(ymax=p.y);p.y>>=1;return bit}function tinf_read_bits(d,num,base){if(!num)return base;while(d.bitcount<24){d.tag|=d.source[d.sourceIndex++]<>>16-num;d.tag>>>=num;d.bitcount-=num;return val+base}function tinf_decode_symbol(d,t){while(d.bitcount<24){d.tag|=d.source[d.sourceIndex++]<>>=1;++len;sum+=t.table[len];cur-=t.table[len]}while(cur>=0);d.tag=tag;d.bitcount-=len;return t.trans[sum+cur]}function tinf_decode_trees(d,lt,dt){var hlit,hdist,hclen;var i,num,length;hlit=tinf_read_bits(d,5,257);hdist=tinf_read_bits(d,5,1);hclen=tinf_read_bits(d,4,4);for(i=0;i<19;++i)lengths[i]=0;for(i=0;i8){d.sourceIndex--;d.bitcount-=8}length=d.source[d.sourceIndex+1];length=256*length+d.source[d.sourceIndex];invlength=d.source[d.sourceIndex+3];invlength=256*invlength+d.source[d.sourceIndex+2];if(length!==(~invlength&65535))return TINF_DATA_ERROR;d.sourceIndex+=4;for(i=length;i;--i)d.dest[d.destLen++]=d.source[d.sourceIndex++];d.bitcount=0;return TINF_OK}function tinf_uncompress(source,dest){var d=new Data(source,dest);var bfinal,btype,res;do{bfinal=tinf_getbit(d);btype=tinf_read_bits(d,2,0);switch(btype){case 0:res=tinf_inflate_uncompressed_block(d);break;case 1:res=tinf_inflate_block_data(d,sltree,sdtree);break;case 2:tinf_decode_trees(d,d.ltree,d.dtree);res=tinf_inflate_block_data(d,d.ltree,d.dtree);break;default:res=TINF_DATA_ERROR}if(res!==TINF_OK)throw new Error("Data error")}while(!bfinal);if(d.destLen0,"No English "+name+" specified.")}assertNamePresent("fontFamily");assertNamePresent("weightName");assertNamePresent("manufacturer");assertNamePresent("copyright");assertNamePresent("version");assert(this.unitsPerEm>0,"No unitsPerEm specified.")};Font.prototype.toTables=function(){return sfnt.fontToTable(this)};Font.prototype.toBuffer=function(){console.warn("Font.toBuffer is deprecated. Use Font.toArrayBuffer instead.");return this.toArrayBuffer()};Font.prototype.toArrayBuffer=function(){var sfntTable=this.toTables();var bytes=sfntTable.encode();var buffer=new ArrayBuffer(bytes.length);var intArray=new Uint8Array(buffer);for(var i=0;i=0&&i>0){s+=" "}s+=floatToString(v)}return s}var d="";for(var i=0;i>4;var n2=b&15;if(n1===eof){break}s+=lookup[n1];if(n2===eof){break}s+=lookup[n2]}return parseFloat(s)}function parseOperand(parser,b0){var b1;var b2;var b3;var b4;if(b0===28){b1=parser.parseByte();b2=parser.parseByte();return b1<<8|b2}if(b0===29){b1=parser.parseByte();b2=parser.parseByte();b3=parser.parseByte();b4=parser.parseByte();return b1<<24|b2<<16|b3<<8|b4}if(b0===30){return parseFloatOperand(parser)}if(b0>=32&&b0<=246){return b0-139}if(b0>=247&&b0<=250){b1=parser.parseByte();return(b0-247)*256+b1+108}if(b0>=251&&b0<=254){b1=parser.parseByte();return-(b0-251)*256-b1-108}throw new Error("Invalid b0 "+b0)}function entriesToObject(entries){var o={};for(var i=0;i>1;stack.length=0;haveWidth=true}function parse(code){var b1;var b2;var b3;var b4;var codeIndex;var subrCode;var jpx;var jpy;var c3x;var c3y;var c4x;var c4y;var i=0;while(i1&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}y+=stack.pop();newContour(x,y);break;case 5:while(stack.length>0){x+=stack.shift();y+=stack.shift();p.lineTo(x,y)}break;case 6:while(stack.length>0){x+=stack.shift();p.lineTo(x,y);if(stack.length===0){break}y+=stack.shift();p.lineTo(x,y)}break;case 7:while(stack.length>0){y+=stack.shift();p.lineTo(x,y);if(stack.length===0){break}x+=stack.shift();p.lineTo(x,y)}break;case 8:while(stack.length>0){c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 10:codeIndex=stack.pop()+font.subrsBias;subrCode=font.subrs[codeIndex];if(subrCode){parse(subrCode)}break;case 11:return;case 12:v=code[i];i+=1;switch(v){case 35:c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y+stack.shift();c3x=jpx+stack.shift();c3y=jpy+stack.shift();c4x=c3x+stack.shift();c4y=c3y+stack.shift();x=c4x+stack.shift();y=c4y+stack.shift();stack.shift();p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 34:c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y;c3x=jpx+stack.shift();c3y=c2y;c4x=c3x+stack.shift();c4y=y;x=c4x+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 36:c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y;c3x=jpx+stack.shift();c3y=c2y;c4x=c3x+stack.shift();c4y=c3y+stack.shift();x=c4x+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;case 37:c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();jpx=c2x+stack.shift();jpy=c2y+stack.shift();c3x=jpx+stack.shift();c3y=jpy+stack.shift();c4x=c3x+stack.shift();c4y=c3y+stack.shift();if(Math.abs(c4x-x)>Math.abs(c4y-y)){x=c4x+stack.shift()}else{y=c4y+stack.shift()}p.curveTo(c1x,c1y,c2x,c2y,jpx,jpy);p.curveTo(c3x,c3y,c4x,c4y,x,y);break;default:console.log("Glyph "+glyph.index+": unknown operator "+1200+v);stack.length=0}break;case 14:if(stack.length>0&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}if(open){p.closePath();open=false}break;case 18:parseStems();break;case 19:case 20:parseStems();i+=nStems+7>>3;break;case 21:if(stack.length>2&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}y+=stack.pop();x+=stack.pop();newContour(x,y);break;case 22:if(stack.length>1&&!haveWidth){width=stack.shift()+font.nominalWidthX;haveWidth=true}x+=stack.pop();newContour(x,y);break;case 23:parseStems();break;case 24:while(stack.length>2){c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y)}x+=stack.shift();y+=stack.shift();p.lineTo(x,y);break;case 25:while(stack.length>6){x+=stack.shift();y+=stack.shift();p.lineTo(x,y)}c1x=x+stack.shift();c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y);break;case 26:if(stack.length%2){x+=stack.shift()}while(stack.length>0){c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x;y=c2y+stack.shift();p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 27:if(stack.length%2){y+=stack.shift()}while(stack.length>0){c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y;p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 28:b1=code[i];b2=code[i+1];stack.push((b1<<24|b2<<16)>>16);i+=2;break;case 29:codeIndex=stack.pop()+font.gsubrsBias;subrCode=font.gsubrs[codeIndex];if(subrCode){parse(subrCode)}break;case 30:while(stack.length>0){c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);if(stack.length===0){break}c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();y=c2y+stack.shift();x=c2x+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;case 31:while(stack.length>0){c1x=x+stack.shift();c1y=y;c2x=c1x+stack.shift();c2y=c1y+stack.shift();y=c2y+stack.shift();x=c2x+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y);if(stack.length===0){break}c1x=x;c1y=y+stack.shift();c2x=c1x+stack.shift();c2y=c1y+stack.shift();x=c2x+stack.shift();y=c2y+(stack.length===1?stack.shift():0);p.curveTo(c1x,c1y,c2x,c2y,x,y)}break;default:if(v<32){console.log("Glyph "+glyph.index+": unknown operator "+v)}else if(v<247){stack.push(v-139)}else if(v<251){b1=code[i];i+=1;stack.push((v-247)*256+b1+108)}else if(v<255){b1=code[i];i+=1;stack.push(-(v-251)*256-b1-108)}else{b1=code[i];b2=code[i+1];b3=code[i+2];b4=code[i+3];i+=4;stack.push((b1<<24|b2<<16|b3<<8|b4)/65536)}}}}parse(code);glyph.advanceWidth=width;return p}function calcCFFSubroutineBias(subrs){var bias;if(subrs.length<1240){bias=107}else if(subrs.length<33900){bias=1131}else{bias=32768}return bias}function parseCFFTable(data,start,font){font.tables.cff={};var header=parseCFFHeader(data,start);var nameIndex=parseCFFIndex(data,header.endOffset,bytesToString);var topDictIndex=parseCFFIndex(data,nameIndex.endOffset);var stringIndex=parseCFFIndex(data,topDictIndex.endOffset,bytesToString);var globalSubrIndex=parseCFFIndex(data,stringIndex.endOffset);font.gsubrs=globalSubrIndex.objects;font.gsubrsBias=calcCFFSubroutineBias(font.gsubrs);var topDictData=new DataView(new Uint8Array(topDictIndex.objects[0]).buffer);var topDict=parseCFFTopDict(topDictData,stringIndex.objects);font.tables.cff.topDict=topDict;var privateDictOffset=start+topDict["private"][1];var privateDict=parseCFFPrivateDict(data,privateDictOffset,topDict["private"][0],stringIndex.objects);font.defaultWidthX=privateDict.defaultWidthX;font.nominalWidthX=privateDict.nominalWidthX;if(privateDict.subrs!==0){var subrOffset=privateDictOffset+privateDict.subrs;var subrIndex=parseCFFIndex(data,subrOffset);font.subrs=subrIndex.objects;font.subrsBias=calcCFFSubroutineBias(font.subrs)}else{font.subrs=[];font.subrsBias=0}var charStringsIndex=parseCFFIndex(data,start+topDict.charStrings);font.nGlyphs=charStringsIndex.objects.length;var charset=parseCFFCharset(data,start+topDict.charset,font.nGlyphs,stringIndex.objects);if(topDict.encoding===0){font.cffEncoding=new CffEncoding(cffStandardEncoding,charset)}else if(topDict.encoding===1){font.cffEncoding=new CffEncoding(cffExpertEncoding,charset)}else{font.cffEncoding=parseCFFEncoding(data,start+topDict.encoding,charset)}font.encoding=font.encoding||font.cffEncoding;font.glyphs=new GlyphSet(font);for(var i=0;i=0){sid=i}i=strings.indexOf(s);if(i>=0){sid=i+cffStandardStrings.length}else{sid=cffStandardStrings.length+strings.length;strings.push(s)}return sid}function makeHeader(){return new table.Record("Header",[{name:"major",type:"Card8",value:1},{name:"minor",type:"Card8",value:0},{name:"hdrSize",type:"Card8",value:4},{name:"major",type:"Card8",value:1}])}function makeNameIndex(fontNames){var t=new table.Record("Name INDEX",[{name:"names",type:"INDEX",value:[]}]);t.names=[];for(var i=0;i>1;p.skip("uShort",3);cmap.glyphIndexMap={};var endCountParser=new Parser(data,start+offset+14);var startCountParser=new Parser(data,start+offset+16+segCount*2);var idDeltaParser=new Parser(data,start+offset+16+segCount*4);var idRangeOffsetParser=new Parser(data,start+offset+16+segCount*6);var glyphIndexOffset=start+offset+16+segCount*8;for(i=0;i0){v=p.parseByte();if((flag&sameBitMask)===0){v=-v}v=previousValue+v}else{if((flag&sameBitMask)>0){v=previousValue}else{v=previousValue+p.parseShort()}}return v}function parseGlyph(glyph,data,start){var p=new Parser(data,start);glyph.numberOfContours=p.parseShort();glyph.xMin=p.parseShort();glyph.yMin=p.parseShort();glyph.xMax=p.parseShort();glyph.yMax=p.parseShort();var flags;var flag;if(glyph.numberOfContours>0){var i;var endPointIndices=glyph.endPointIndices=[];for(i=0;i0){var repeatCount=p.parseByte();for(var j=0;j0){var points=[];var point;if(numberOfCoordinates>0){for(i=0;i=0;points.push(point)}var px=0;for(i=0;i0){component.dx=p.parseShort();component.dy=p.parseShort()}else{component.dx=p.parseChar();component.dy=p.parseChar()}if((flags&8)>0){component.xScale=component.yScale=p.parseF2Dot14()}else if((flags&64)>0){component.xScale=p.parseF2Dot14();component.yScale=p.parseF2Dot14()}else if((flags&128)>0){component.xScale=p.parseF2Dot14();component.scale01=p.parseF2Dot14();component.scale10=p.parseF2Dot14();component.yScale=p.parseF2Dot14()}glyph.components.push(component);moreComponents=!!(flags&32)}}}function transformPoints(points,transform){var newPoints=[];for(var i=0;i>1;if(glyphID=range.begin&&unicode=1){os2.ulCodePageRange1=p.parseULong();os2.ulCodePageRange2=p.parseULong()}if(os2.version>=2){os2.sxHeight=p.parseShort();os2.sCapHeight=p.parseShort();os2.usDefaultChar=p.parseUShort();os2.usBreakChar=p.parseUShort();os2.usMaxContent=p.parseUShort()}return os2}function makeOS2Table(options){return new table.Table("OS/2",[{name:"version",type:"USHORT",value:3},{name:"xAvgCharWidth",type:"SHORT",value:0},{name:"usWeightClass",type:"USHORT",value:0},{name:"usWidthClass",type:"USHORT",value:0},{name:"fsType",type:"USHORT",value:0},{name:"ySubscriptXSize",type:"SHORT",value:650},{name:"ySubscriptYSize",type:"SHORT",value:699},{name:"ySubscriptXOffset",type:"SHORT",value:0},{name:"ySubscriptYOffset",type:"SHORT",value:140},{name:"ySuperscriptXSize",type:"SHORT",value:650},{name:"ySuperscriptYSize",type:"SHORT",value:699},{name:"ySuperscriptXOffset",type:"SHORT",value:0},{name:"ySuperscriptYOffset",type:"SHORT",value:479},{name:"yStrikeoutSize",type:"SHORT",value:49},{name:"yStrikeoutPosition",type:"SHORT",value:258},{name:"sFamilyClass",type:"SHORT",value:0},{name:"bFamilyType",type:"BYTE",value:0},{name:"bSerifStyle",type:"BYTE",value:0},{name:"bWeight",type:"BYTE",value:0},{name:"bProportion",type:"BYTE",value:0},{name:"bContrast",type:"BYTE",value:0},{name:"bStrokeVariation",type:"BYTE",value:0},{name:"bArmStyle",type:"BYTE",value:0},{name:"bLetterform",type:"BYTE",value:0},{name:"bMidline",type:"BYTE",value:0},{name:"bXHeight",type:"BYTE",value:0},{name:"ulUnicodeRange1",type:"ULONG",value:0},{name:"ulUnicodeRange2",type:"ULONG",value:0},{name:"ulUnicodeRange3",type:"ULONG",value:0},{name:"ulUnicodeRange4",type:"ULONG",value:0},{name:"achVendID",type:"CHARARRAY",value:"XXXX"},{name:"fsSelection",type:"USHORT",value:0},{name:"usFirstCharIndex",type:"USHORT",value:0},{name:"usLastCharIndex",type:"USHORT",value:0},{name:"sTypoAscender",type:"SHORT",value:0},{name:"sTypoDescender",type:"SHORT",value:0},{name:"sTypoLineGap",type:"SHORT",value:0},{name:"usWinAscent",type:"USHORT",value:0},{name:"usWinDescent",type:"USHORT",value:0},{name:"ulCodePageRange1",type:"ULONG",value:0},{name:"ulCodePageRange2",type:"ULONG",value:0},{name:"sxHeight",type:"SHORT",value:0},{name:"sCapHeight",type:"SHORT",value:0},{name:"usDefaultChar",type:"USHORT",value:0},{name:"usBreakChar",type:"USHORT",value:0},{name:"usMaxContext",type:"USHORT",value:0}],options)}function parsePostTable(data,start){var post={};var p=new Parser(data,start);var i;post.version=p.parseVersion();post.italicAngle=p.parseFixed();post.underlinePosition=p.parseShort();post.underlineThickness=p.parseShort();post.isFixedPitch=p.parseULong();post.minMemType42=p.parseULong();post.maxMemType42=p.parseULong();post.minMemType1=p.parseULong();post.maxMemType1=p.parseULong();switch(post.version){case 1:post.names=standardNames.slice();break;case 2:post.numberOfGlyphs=p.parseUShort();post.glyphNameIndex=new Array(post.numberOfGlyphs);for(i=0;i=standardNames.length){var nameLength=p.parseChar();post.names.push(p.parseString(nameLength))}}break;case 2.5:post.numberOfGlyphs=p.parseUShort();post.offset=new Array(post.numberOfGlyphs);for(i=0;ir2.value.tag){return 1}else{return-1}});sfnt.fields=sfnt.fields.concat(recordFields);sfnt.fields=sfnt.fields.concat(tableFields);return sfnt}function metricsForChar(font,chars,notFoundMetrics){for(var i=0;i0){var glyph=font.glyphs.get(glyphIndex);return glyph.getMetrics()}}return notFoundMetrics}function average(vs){var sum=0;for(var i=0;iunicode||firstCharIndex===null){firstCharIndex=unicode}if(lastCharIndex 123 are reserved for internal usage")}if(glyph.name===".notdef")continue;var metrics=glyph.getMetrics();xMins.push(metrics.xMin);yMins.push(metrics.yMin);xMaxs.push(metrics.xMax);yMaxs.push(metrics.yMax);leftSideBearings.push(metrics.leftSideBearing);rightSideBearings.push(metrics.rightSideBearing);advanceWidths.push(glyph.advanceWidth)}var globals={xMin:Math.min.apply(null,xMins),yMin:Math.min.apply(null,yMins),xMax:Math.max.apply(null,xMaxs),yMax:Math.max.apply(null,yMaxs),advanceWidthMax:Math.max.apply(null,advanceWidths),advanceWidthAvg:average(advanceWidths),minLeftSideBearing:Math.min.apply(null,leftSideBearings),maxLeftSideBearing:Math.max.apply(null,leftSideBearings),minRightSideBearing:Math.min.apply(null,rightSideBearings)};globals.ascender=font.ascender;globals.descender=font.descender;var headTable=head.make({flags:3,unitsPerEm:font.unitsPerEm,xMin:globals.xMin,yMin:globals.yMin,xMax:globals.xMax,yMax:globals.yMax,lowestRecPPEM:3});var hheaTable=hhea.make({ascender:globals.ascender,descender:globals.descender,advanceWidthMax:globals.advanceWidthMax,minLeftSideBearing:globals.minLeftSideBearing,minRightSideBearing:globals.minRightSideBearing,xMaxExtent:globals.maxLeftSideBearing+(globals.xMax-globals.xMin),numberOfHMetrics:font.glyphs.length});var maxpTable=maxp.make(font.glyphs.length);var os2Table=os2.make({xAvgCharWidth:Math.round(globals.advanceWidthAvg),usWeightClass:500,usWidthClass:5,usFirstCharIndex:firstCharIndex,usLastCharIndex:lastCharIndex,ulUnicodeRange1:ulUnicodeRange1,ulUnicodeRange2:ulUnicodeRange2,ulUnicodeRange3:ulUnicodeRange3,ulUnicodeRange4:ulUnicodeRange4,fsSelection:64,sTypoAscender:globals.ascender,sTypoDescender:globals.descender,sTypoLineGap:0,usWinAscent:globals.yMax,usWinDescent:Math.abs(globals.yMin),ulCodePageRange1:1,sxHeight:metricsForChar(font,"xyvw",{yMax:Math.round(globals.ascender/2)}).yMax,sCapHeight:metricsForChar(font,"HIKLEFJMNTZBDPRAGOQSUVWXY",globals).yMax,usDefaultChar:font.hasChar(" ")?32:0,usBreakChar:font.hasChar(" ")?32:0});var hmtxTable=hmtx.make(font.glyphs);var cmapTable=cmap.make(font.glyphs);var englishFamilyName=font.getEnglishName("fontFamily");var englishStyleName=font.getEnglishName("fontSubfamily");var englishFullName=englishFamilyName+" "+englishStyleName;var postScriptName=font.getEnglishName("postScriptName");if(!postScriptName){postScriptName=englishFamilyName.replace(/\s/g,"")+"-"+englishStyleName}var names={};for(var n in font.names){names[n]=font.names[n]}if(!names.uniqueID){names.uniqueID={en:font.getEnglishName("manufacturer")+":"+englishFullName}}if(!names.postScriptName){names.postScriptName={en:postScriptName}}if(!names.preferredFamily){names.preferredFamily=font.names.fontFamily}if(!names.preferredSubfamily){names.preferredSubfamily=font.names.fontSubfamily}var languageTags=[];var nameTable=makeNameTable(names,languageTags);var ltagTable=languageTags.length>0?ltag.make(languageTags):undefined;var postTable=post.make();var cffTable=cff.make(font.glyphs,{version:font.getEnglishName("version"),fullName:englishFullName,familyName:englishFamilyName,weightName:englishStyleName,postScriptName:postScriptName,unitsPerEm:font.unitsPerEm,fontBBox:[0,globals.yMin,globals.ascender,globals.advanceWidthMax]});var tables=[headTable,hheaTable,maxpTable,os2Table,nameTable,cmapTable,postTable,cffTable,hmtxTable];if(ltagTable){tables.push(ltagTable)}var sfntTable=makeSfntTable(tables);var bytes=sfntTable.encode();var checkSum=computeCheckSum(bytes);var tableFields=sfntTable.fields;var checkSumAdjusted=false;for(i=0;i=0&&v<=255,"Byte value should be between 0 and 255.");return[v]};sizeOf.BYTE=constant(1);encode.CHAR=function(v){return[v.charCodeAt(0)]};sizeOf.CHAR=constant(1);encode.CHARARRAY=function(v){var b=[];for(var i=0;i>8&255,v&255]};sizeOf.USHORT=constant(2);encode.SHORT=function(v){if(v>=LIMIT16){v=-(2*LIMIT16-v)}return[v>>8&255,v&255]};sizeOf.SHORT=constant(2);encode.UINT24=function(v){return[v>>16&255,v>>8&255,v&255]};sizeOf.UINT24=constant(3);encode.ULONG=function(v){return[v>>24&255,v>>16&255,v>>8&255,v&255]};sizeOf.ULONG=constant(4);encode.LONG=function(v){if(v>=LIMIT32){v=-(2*LIMIT32-v)}return[v>>24&255,v>>16&255,v>>8&255,v&255]};sizeOf.LONG=constant(4);encode.FIXED=encode.ULONG;sizeOf.FIXED=sizeOf.ULONG;encode.FWORD=encode.SHORT;sizeOf.FWORD=sizeOf.SHORT;encode.UFWORD=encode.USHORT;sizeOf.UFWORD=sizeOf.USHORT;encode.LONGDATETIME=function(){return[0,0,0,0,0,0,0,0]};sizeOf.LONGDATETIME=constant(8);encode.TAG=function(v){assert(v.length===4,"Tag should be exactly 4 ASCII characters.");return[v.charCodeAt(0),v.charCodeAt(1),v.charCodeAt(2),v.charCodeAt(3)]};sizeOf.TAG=constant(4);encode.Card8=encode.BYTE;sizeOf.Card8=sizeOf.BYTE;encode.Card16=encode.USHORT;sizeOf.Card16=sizeOf.USHORT;encode.OffSize=encode.BYTE;sizeOf.OffSize=sizeOf.BYTE;encode.SID=encode.USHORT;sizeOf.SID=sizeOf.USHORT;encode.NUMBER=function(v){if(v>=-107&&v<=107){return[v+139]}else if(v>=108&&v<=1131){v=v-108;return[(v>>8)+247,v&255]}else if(v>=-1131&&v<=-108){v=-v-108;return[(v>>8)+251,v&255]}else if(v>=-32768&&v<=32767){return encode.NUMBER16(v)}else{return encode.NUMBER32(v)}};sizeOf.NUMBER=function(v){return encode.NUMBER(v).length};encode.NUMBER16=function(v){return[28,v>>8&255,v&255]};sizeOf.NUMBER16=constant(3);encode.NUMBER32=function(v){return[29,v>>24&255,v>>16&255,v>>8&255,v&255]};sizeOf.NUMBER32=constant(5);encode.REAL=function(v){var value=v.toString();var m=/\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value);if(m){var epsilon=parseFloat("1e"+((m[2]?+m[2]:0)+m[1].length));value=(Math.round(v*epsilon)/epsilon).toString()}var nibbles="";var i;var ii;for(i=0,ii=value.length;i>8&255);b.push(codepoint&255)}return b};sizeOf.UTF16=function(v){return v.length*2};var eightBitMacEncodings={"x-mac-croatian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø"+"¿¡¬√ƒ≈ƫȅ ÀÃÕŒœĐ—“”‘’÷◊©⁄€‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ","x-mac-cyrillic":"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњ"+"јЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю","x-mac-gaelic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØḂ±≤≥ḃĊċḊḋḞḟĠġṀæø"+"ṁṖṗɼƒſṠ«»… ÀÃÕŒœ–—“”‘’ṡẛÿŸṪ€‹›Ŷŷṫ·Ỳỳ⁊ÂÊÁËÈÍÎÏÌÓÔ♣ÒÚÛÙıÝýŴŵẄẅẀẁẂẃ","x-mac-greek":"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦€ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩ"+"άΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ­","x-mac-icelandic":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüݰ¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-inuit":"ᐃᐄᐅᐆᐊᐋᐱᐲᐳᐴᐸᐹᑉᑎᑏᑐᑑᑕᑖᑦᑭᑮᑯᑰᑲᑳᒃᒋᒌᒍᒎᒐᒑ°ᒡᒥᒦ•¶ᒧ®©™ᒨᒪᒫᒻᓂᓃᓄᓅᓇᓈᓐᓯᓰᓱᓲᓴᓵᔅᓕᓖᓗ"+"ᓘᓚᓛᓪᔨᔩᔪᔫᔭ… ᔮᔾᕕᕖᕗ–—“”‘’ᕘᕙᕚᕝᕆᕇᕈᕉᕋᕌᕐᕿᖀᖁᖂᖃᖄᖅᖏᖐᖑᖒᖓᖔᖕᙱᙲᙳᙴᙵᙶᖖᖠᖡᖢᖣᖤᖥᖦᕼŁł","x-mac-ce":"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅ"+"ņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ",macintosh:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-romanian":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂȘ∞±≤≥¥µ∂∑∏π∫ªºΩăș"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›Țț‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ","x-mac-turkish":"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø"+"¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔÒÚÛÙˆ˜¯˘˙˚¸˝˛ˇ"};opentype_decode.MACSTRING=function(dataView,offset,dataLength,encoding){var table=eightBitMacEncodings[encoding];if(table===undefined){return undefined}var result="";for(var i=0;i=128){c=table[c];if(c===undefined){return undefined}}result.push(c)}return result};sizeOf.MACSTRING=function(str,encoding){var b=encode.MACSTRING(str,encoding);if(b!==undefined){return b.length}else{return 0}};encode.INDEX=function(l){var i;var offset=1;var offsets=[offset];var data=[];var dataSize=0;for(i=0;i>8;d[o+1]=offset&255;d=d.concat(subtables[i])}return d};sizeOf.TABLE=function(table){var numBytes=0;var length=table.fields.length;for(var i=0;i=1){if(dest!=quat){dest[0]=quat[0];dest[1]=quat[1];dest[2]=quat[2];dest[3]=quat[3]}return dest}var halfTheta=Math.acos(cosHalfTheta);var sinHalfTheta=Math.sqrt(1-cosHalfTheta*cosHalfTheta);if(Math.abs(sinHalfTheta)<.001){dest[0]=quat[0]*.5+quat2[0]*.5;dest[1]=quat[1]*.5+quat2[1]*.5;dest[2]=quat[2]*.5+quat2[2]*.5;dest[3]=quat[3]*.5+quat2[3]*.5;return dest}var ratioA=Math.sin((1-slerp)*halfTheta)/sinHalfTheta;var ratioB=Math.sin(slerp*halfTheta)/sinHalfTheta;dest[0]=quat[0]*ratioA+quat2[0]*ratioB;dest[1]=quat[1]*ratioA+quat2[1]*ratioB;dest[2]=quat[2]*ratioA+quat2[2]*ratioB;dest[3]=quat[3]*ratioA+quat2[3]*ratioB;return dest};quat4.str=function(quat){return"["+quat[0]+", "+quat[1]+", "+quat[2]+", "+quat[3]+"]"};WebGLUtils=function(){var makeFailHTML=function(msg){return""+''+'
'+'
'+'
'+msg+"
"+"
"+"
"};var GET_A_WEBGL_BROWSER=""+"This page requires a browser that supports WebGL.
"+'
Click here to upgrade your browser.';var OTHER_PROBLEM=""+"It doesn't appear your computer can support WebGL.
"+'Click here for more information.';var setupWebGL=function(canvas,opt_attribs){function showLink(str){var container=canvas.parentNode;if(container){container.innerHTML=makeFailHTML(str)}}if(!window.WebGLRenderingContext){showLink(GET_A_WEBGL_BROWSER);return null}var context=create3DContext(canvas,opt_attribs);if(!context){showLink(OTHER_PROBLEM)}return context};var create3DContext=function(canvas,opt_attribs){var names=["webgl","experimental-webgl","webkit-3d","moz-webgl"];var context=null;for(var ii=0;ii1e-6){var rotaxis,newup;if(Math.abs(angle-Math.PI)<1e-6)newup=parent.__up.multiply(-1);else{rotaxis=cross(oldaxis,newaxis);newup=parent.__up.rotate({angle:angle,axis:rotaxis})}parent.__up.__x=newup.x;parent.__up.__y=newup.y;parent.__up.__z=newup.z}}function adjust_axis(parent,oldup,newup){parent.__change();if(newup.mag2===0){if(parent.__oldup===undefined)parent.__oldup=oldup}if(parent.__oldup!==undefined){oldup=parent.__oldup;parent.__oldup=undefined}if(newup.dot(parent.__axis)===0)return;var angle=oldup.diff_angle(newup);if(angle>1e-6){var rotaxis,newaxis;if(Math.abs(angle-Math.PI)<1e-6)newaxis=parent.__axis.multiply(-1);else{rotaxis=cross(oldup,newup);newaxis=parent.__axis.rotate({angle:angle,axis:rotaxis})}parent.__axis.__x=newaxis.x;parent.__axis.__y=newaxis.y;parent.__axis.__z=newaxis.z}}function vec(x,y,z){if(!(this instanceof vec)){if(y===undefined)if(z===undefined)return new vec(x.x,x.y,x.z);return new vec(x,y,z)}if(z===undefined||y===undefined)throw new Error("vector() requires 3 arguments: x, y, and z.");this.x=x;this.y=y;this.z=z}function attributeVector(parent,x,y,z){this.__parent=parent;this.__x=x;this.__y=y;this.__z=z;if(parent){parent.__change()}}attributeVector.prototype=new vec(0,0,0);attributeVector.prototype.constructor=attributeVector;function attributeVectorPos(parent,x,y,z){this.__parent=parent;this.__x=x;this.__y=y;this.__z=z;if(parent){parent.__change();parent._pos_set=true;if(parent.__make_trail)parent.__update_trail(vec(x,y,z))}}attributeVectorPos.prototype=new vec(0,0,0);attributeVectorPos.prototype.constructor=attributeVectorPos;function attributeVectorAxis(parent,x,y,z){var oldaxis;this.__parent=parent;if(parent)oldaxis=norm(parent.__axis);this.__x=x;this.__y=y;this.__z=z;if(parent){if(parent.__sizing)parent.__size.__x=Math.sqrt(x*x+y*y+z*z);if(window.__adjustupaxis)adjust_up(parent,oldaxis,this);parent.__change()}}attributeVectorAxis.prototype=new vec(1,0,0);attributeVectorAxis.prototype.constructor=attributeVectorAxis;function attributeVectorSize(parent,x,y,z){this.__parent=parent;this.__x=x;this.__y=y;this.__z=z;if(parent){if(parent.__sizing){var pa=parent.__axis;if(pa.x===0&&pa.y===0&&pa.z===0&&parent.__oldaxis!==undefined){pa=parent.__oldaxis;parent.__oldaxis=undefined}var v=pa.norm().multiply(x);parent.__axis.__x=v.x;parent.__axis.__y=v.y;parent.__axis.__z=v.z}parent.__change()}}attributeVectorSize.prototype=new vec(1,1,1);attributeVectorSize.prototype.constructor=attributeVectorSize;function attributeVectorUp(parent,x,y,z){var oldup;this.__parent=parent;if(parent)oldup=norm(parent.__up);this.__x=x;this.__y=y;this.__z=z;if(parent){if(window.__adjustupaxis)adjust_axis(parent,oldup,this);parent.__change()}}attributeVectorUp.prototype=new vec(0,1,0);attributeVectorUp.prototype.constructor=attributeVectorUp;Object.defineProperty(attributeVector.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVector.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){this.__x=value;this.__parent.__change()}});Object.defineProperty(attributeVector.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVector.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){this.__y=value;this.__parent.__change()}});Object.defineProperty(attributeVector.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVector.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){this.__z=value;this.__parent.__change()}});Object.defineProperty(attributeVectorPos.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorPos.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){this.__x=value;this.__parent.__change();this.__parent._pos_set=true;if(this.__parent.__make_trail)this.__parent.__update_trail(vec(this.__x,this.__y,this.__z))}});Object.defineProperty(attributeVectorPos.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorPos.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){this.__y=value;this.__parent.__change();this.__parent._pos_set=true;if(this.__parent.__make_trail)this.__parent.__update_trail(vec(this.__x,this.__y,this.__z))}});Object.defineProperty(attributeVectorPos.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorPos.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){this.__z=value;this.__parent.__change();this.__parent._pos_set=true;if(this.__parent.__make_trail)this.__parent.__update_trail(vec(this.__x,this.__y,this.__z))}});Object.defineProperty(attributeVectorAxis.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorAxis.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){var oldaxis=norm(this.__parent.__axis);this.__x=value;if(this.__parent.__sizing)this.__parent.__size.x=this.mag;adjust_up(this.__parent,oldaxis,this)}});Object.defineProperty(attributeVectorAxis.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorAxis.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){var oldaxis=norm(this.__parent.__axis);this.__y=value;if(this.__parent.__sizing)this.__parent.__size.x=this.mag;adjust_up(this.__parent,oldaxis,this)}});Object.defineProperty(attributeVectorAxis.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorAxis.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){var oldaxis=norm(this.__parent.__axis);this.__z=value;if(this.__parent.__sizing)this.__parent.__size.x=this.mag;adjust_up(this.__parent,oldaxis,this)}});Object.defineProperty(attributeVectorSize.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorSize.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){this.__x=value;if(this.__parent.__sizing){var pa=this.__parent.__axis;if(pa.x===0&&pa.y===0&&pa.z===0&&this.__parent.__oldaxis!==undefined){pa=this.__parent.__oldaxis;this.__parent.__oldaxis=undefined}var v=pa.norm().multiply(value);this.__parent.__axis.__x=v.x;this.__parent.__axis.__y=v.y;this.__parent.__axis.__z=v.z}this.__parent.__change()}});Object.defineProperty(attributeVectorSize.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorSize.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){this.__y=value;this.__parent.__change()}});Object.defineProperty(attributeVectorSize.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorSize.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){this.__z=value;this.__parent.__change()}});Object.defineProperty(attributeVectorUp.prototype,"__x",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorUp.prototype,"x",{enumerable:true,get:function(){return this.__x},set:function(value){var oldup=norm(this.__parent.__up);this.__x=value;adjust_axis(parent,oldup,this)}});Object.defineProperty(attributeVectorUp.prototype,"__y",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorUp.prototype,"y",{enumerable:true,get:function(){return this.__y},set:function(value){var oldup=norm(this.__parent.__up);this.__y=value;adjust_axis(parent,oldup,this)}});Object.defineProperty(attributeVectorUp.prototype,"__z",{enumerable:false,writable:true,value:0});Object.defineProperty(attributeVectorUp.prototype,"z",{enumerable:true,get:function(){return this.__z},set:function(value){var oldup=norm(this.__parent.__up);this.__z=value;adjust_axis(parent,oldup,this)}});vec.prototype.toString=function(){var input=[this.x,this.y,this.z];var output=[];for(var i=0;i<3;i++){output.push(__convert(input[i]))}return"< "+output[0]+", "+output[1]+", "+output[2]+" >"};vec.prototype.add=function(v){if(!(v instanceof vec))add_error();return new vec(this.x+v.x,this.y+v.y,this.z+v.z)};vec.prototype.sub=function(v){if(!(v instanceof vec))sub_error();return new vec(this.x-v.x,this.y-v.y,this.z-v.z)};vec.prototype.multiply=function(r){if(r instanceof vec)multiply_error();if(r===undefined||Number.isNaN(r))badnumber(r);return new vec(this.x*r,this.y*r,this.z*r)};vec.prototype.divide=function(r){if(r instanceof vec)divide_error();if(r===undefined||Number.isNaN(r))badnumber(r);return new vec(this.x/r,this.y/r,this.z/r)};property.declare(vec.prototype,{mag:{get:function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},set:function(value){var v=this.norm().multiply(value);this.x=v.x;this.y=v.y;this.z=v.z}},mag2:{get:function(){return this.x*this.x+this.y*this.y+this.z*this.z},set:function(value){var v=this.norm().multiply(Math.sqrt(value));this.x=v.x;this.y=v.y;this.z=v.z}},hat:{get:function(){return this.norm()},set:function(value){var v=value.hat.multiply(this.mag);this.x=v.x;this.y=v.y;this.z=v.z}}});vec.prototype.norm=function(){var r=this.mag;if(r==0)return new vec(0,0,0);return new vec(this.x/r,this.y/r,this.z/r)};vec.prototype.dot=function(v){return this.x*v.x+this.y*v.y+this.z*v.z};vec.prototype.equals=function(v){if(v===null)return false;return this.x===v.x&&this.y===v.y&&this.z===v.z};vec.prototype.proj=function(v){var B=norm(v);return B.multiply(this.dot(B))};vec.prototype.comp=function(v){return this.dot(norm(v))};vec.prototype.cross=function(v){return new vec(this.y*v.z-this.z*v.y,this.z*v.x-this.x*v.z,this.x*v.y-this.y*v.x)};vec.prototype.diff_angle=function(v){var a=this.norm().dot(v.norm());if(a>1)return 0;if(a<-1)return Math.PI;return Math.acos(a)};vec.prototype.rotate=function(args){var angle,axis;var L=arguments.length;if(L<1||L>2)throw new Error("vector.rotate takes 1 or 2 arguments");for(var i=0;i with vectors.")}function less_error(){throw new Error("Cannot use < with vectors.")}function greaterorequal_error(){throw new Error("Cannot use >= with vectors.")}function lessorequal_error(){throw new Error("Cannot use <= with vectors.")}function badnumber(r){if(r===undefined)throw new Error("A variable is undefined.");else throw new Error("A variable is 'NaN', not a number.")}String.prototype["+"]=function(r){return this+r};String.prototype["+="]=function(r){return this+r};String.prototype["*"]=function(r){if(typeof r=="number")return this.repeat(r);throw new Error("Cannot multiply a string by something that is not a number.")};Number.prototype["+"]=function(r){return r instanceof vec?add_error():this+r};Number.prototype["-"]=function(r){return r instanceof vec?sub_error():this-r};Number.prototype["*"]=function(r){return r instanceof vec?r.multiply(this):this*r};Number.prototype["/"]=function(r){return r instanceof vec?divide_error():this/r};Number.prototype[">"]=function(r){return r instanceof vec?greater_error():this>r};Number.prototype["<"]=function(r){return r instanceof vec?less_error():this="]=function(r){return r instanceof vec?greaterorequal_error():this>=r};Number.prototype["<="]=function(r){return r instanceof vec?lessorequal_error():this<=r};Number.prototype["%"]=function(r){return this%r};Number.prototype["-u"]=function(){return-this};vec.prototype["+"]=vec.prototype.add;vec.prototype["-"]=vec.prototype.sub;vec.prototype["*"]=vec.prototype.multiply;vec.prototype["/"]=function(r){return this.divide(r)};vec.prototype["-u"]=function(){return new vec(-this.x,-this.y,-this.z)};vec.prototype[">"]=function(r){greater_error()};vec.prototype["<"]=function(r){less_error()};vec.prototype[">="]=function(r){greaterorequal_error()};vec.prototype["<="]=function(r){lessorequal_error()};var exports={vec:vec,attributeVector:attributeVector,attributeVectorPos:attributeVectorPos,attributeVectorAxis:attributeVectorAxis,attributeVectorSize:attributeVectorSize,attributeVectorUp:attributeVectorUp};Export(exports)})();(function vectorLibraryWrappers(){"use strict";function __array_times_number(a,r){if(typeof r==="number"){var n=r;var na=a.length;var ret=[];for(var i=0;i3)throw new Error("rotate(vector, ...) takes 1 to 3 arguments");v=arguments[0];for(var i=1;i=n)return s;i++;var loc=s.search(t);if(loc<0)return s;s=s.slice(0,loc)+r+s.slice(loc+tlong)}};var exports={mag:mag,mag2:mag2,norm:norm,hat:hat,dot:dot,cross:cross,proj:proj,comp:comp,diff_angle:diff_angle,rotate:rotate,GS_power:GS_power,__array_times_number:__array_times_number};Export(exports)})();(function(){"use strict";function Mesh(){this.pos=[];this.normal=[];this.color=[];this.opacity=[];this.shininess=[];this.emissive=[];this.texpos=[];this.bumpaxis=[];this.index=[];this.model_transparent=false}$.extend(Mesh.prototype,{merge:function merge(otherMesh,object,bias){var xmin=null,xmax=null,ymin=null,ymax=null,zmin=null,zmax=null;var offset=this.pos.length/3;if(object instanceof vertex){if(offset+1>=65536)return null;if(bias<0)this.index.push(offset+bias);else{if(xmin===null||object.__pos.xxmax)xmax=object.__pos.x;if(ymin===null||object.__pos.yymax)ymax=object.__pos.y;if(zmin===null||object.__pos.zzmax)zmax=object.__pos.z;this.pos.push(object.__pos.x,object.__pos.y,object.__pos.z);this.normal.push(object.__normal.x,object.__normal.y,object.__normal.z);this.color.push(object.__color.x,object.__color.y,object.__color.z);if(object.__opacity<1)this.model_transparent=true;this.opacity.push(object.__opacity);this.shininess.push(object.__shininess);this.emissive.push(object.__emissive);this.texpos.push(object.__texpos.x,object.__texpos.y);this.bumpaxis.push(object.__bumpaxis.x,object.__bumpaxis.y,object.__bumpaxis.z);this.index.push(offset)}}else{if(offset+otherMesh.pos.length/3>=65536)return null;var c=[object.__color.x,object.__color.y,object.__color.z];for(var j=0;jxmax)xmax=otherMesh.pos[j]}else if(j%3===1){if(ymin===null||otherMesh.pos[j]ymax)ymax=otherMesh.pos[j]}else if(j%3===2){if(zmin===null||otherMesh.pos[j]zmax)zmax=otherMesh.pos[j]}this.pos.push(otherMesh.pos[j])}for(var j=0;j","?",")","!","@","#","$","%","^","&","*","(",":",":","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","{","|","}","^","_","~","","","","","","","","","","*","+","","","","","f1","f2","f3","f4","f5","f6","f7","f8","f9","f10","","{","|","}","~","delete"];_shifted[187]="+";_shifted[189]="_";_shifted[192]="~";_shifted[219]="{";_shifted[220]="|";_shifted[221]="}";_shifted[186]=":";_shifted[222]='"';_shifted[188]="<";_shifted[190]=">";_shifted[191]="?";var shiftlock=false;var __waitfor;var __waitfor_canvas;var __waitfor__expecting_key;window.print_anchor=$("
").css("white-space","pre").appendTo($("body"));window.print_anchor.css({float:"left"});var __id=0;function canvas(options){if(!(this instanceof canvas))return new canvas(options);if(!options)options={};canvas.activated=[];canvas.selected=this;canvas.hasmouse=null;this.__title_anchor=$("
");this.__caption_anchor=$("
");this.__titletext="";this.__captiontext="";if("title"in options){this.__titletext=options.title;delete options.title}if("caption"in options){this.__captiontext=options.caption;delete options.caption}this.__align="none";if("align"in options){this.__align=options.align;delete options.align}this.__lastevent=null;this.__autoscale=true;if("autoscale"in options){this.__autoscale=options.autoscale;delete options.autoscale}this.__range=10;if("width"in options){this.__width=options.width;delete options.width}if("height"in options){this.__height=options.height;delete options.height}for(var id in options)this[id]=options[id];this.hasmouse=false;this.__needs_update=false;this.events=[];this.wrapper=$("
");this.menu=$("
");this.__canvas_element=document.createElement("canvas");this.__overlay_element=document.createElement("canvas");this.elements=$([this.__canvas_element,this.__overlay_element]);this.__overlay_objects={objects:[],__changed:false};this.__visiblePrimitives={};this.lights=[];distant_light({canvas:this,direction:vec(.22,.44,.88),color:vec(.8,.8,.8)});distant_light({canvas:this,direction:vec(-.88,-.22,-.44),color:vec(.3,.3,.3)});this.trails=[];this.arrows=[];this.billboards=[];this.update_billboards=false;this.__points_objects=[];this.__opaque_objects={};this.__transparent_objects={};this.vertex_id=1;var N=100;this.__vertices={Nalloc:N,pos:new Float32Array(3*N),normal:new Float32Array(3*N),color:new Float32Array(3*N),opacity:new Float32Array(N),shininess:new Float32Array(N),emissive:new Float32Array(N),texpos:new Float32Array(2*N),bumpaxis:new Float32Array(3*N),index:new Uint16Array(N),model_transparent:false,object_info:{},available:[]};this.__vertices.normal[2]=1;this.__sort_objects={opaque:{plain:{},textures:{},bumpmaps:{},textures_and_bumpmaps:{}},transparent:{plain:{},textures:{},bumpmaps:{},textures_and_bumpmaps:{}}};this.camera=orbital_camera(this);this.mouse=new Mouse(this);this.mouse.pos=vec(0,0,0);this.mouse.ray=vec(0,0,1);this.textures={};this.textures_requested={};this.__changed={};this.__vertex_changed={};this.visible=true;this.waitfor_textures=false;__waitfor="";this.__expecting_key=false;this.center=this.center;this.axis=this.axis;this.up=this.up;this.__triggered=undefined;this.__waitfor_bound=undefined;this.__id=__id;__id++}property.declare(canvas.prototype,{__activate:function(){this.__activated=true;this.__activate=function(){};var container=canvas.container;this.__title_anchor.css("white-space","pre").appendTo(container);this.menu.css("white-space","pre").appendTo(container);this.wrapper.addClass("glowscript-canvas-wrapper").css("display","inline-block").appendTo(container);this.__caption_anchor.css("white-space","pre").appendTo(container);this.wrapper.css("position","relative");var cv=this.__canvas_element;cv.style.position="absolute";var overlay=this.__overlay_element;overlay.style.position="relative";overlay.style.backgroundColor="transparent";this.width=this.__width;this.height=this.__height;this.wrapper.append(this.__canvas_element);this.wrapper.append(this.__overlay_element);this.wrapper.resizable({alsoResize:[this.__canvas_element,this.__overlay_element],resize:function(ev,ui){this.__canvas_element.width=this.__canvas_element.style.width=this.__overlay_element.width=this.__overlay_element.style.width=this.__width=ui.size.width;this.__canvas_element.height=this.__canvas_element.style.height=this.__overlay_element.height=this.__overlay_element.style.height=this.__height=ui.size.height;this.trigger("resize",{event:"resize"})}.bind(this)});if(!this.resizable)this.wrapper.resizable("disable");this.wrapper.css("float",this.__align);if(this.camera.__activate)this.camera.__activate();this.__handleEvents();if(this.__titletext)this.title=this.__titletext;if(this.__captiontext)this.caption=this.__captiontext;this.__renderer=new WebGLRenderer(this,cv,overlay);canvas.activated.push(this)},remove:function(){for(var id in this.__visiblePrimitives)this.__visiblePrimitives[id].visible=false;for(var id in this.__overlay_objects.objects)this.__overlay_objects.objects[id].visible=false;if(this.__activated)canvas.activated[this.__id]=null;this.wrapper.remove()},__handleEvents:function(){var canvas=this;var elements=canvas.elements;elements.bind("mouseenter mouseleave",function(ev){canvas.trigger("mouse",ev)});var keys={shift:16,ctrl:17,alt:18};$(document).bind("keydown keyup",function(ev){for(var k in keys){if(keys[k]==ev.which){canvas.mouse[k]=ev.type=="keydown";break}}ev.shift=canvas.mouse.shift||shiftlock;ev.key=_unshifted[ev.which];if(shiftlock&&(65<=ev.which&&ev.which<=90))ev.key=_shifted[ev.which];else if(canvas.mouse.shift)ev.key=_shifted[ev.which];var n=keysdownlist.indexOf(ev.key);if(ev.type=="keydown"){if(n<0)keysdownlist.push(ev.key)}else if(n>=0){keysdownlist.splice(n,1)}if(!canvas.__expecting_key)return;ev.event=ev.type;if(ev.which==20&&ev.type=="keydown")shiftlock=!shiftlock;ev.alt=canvas.mouse.alt;ev.ctrl=canvas.mouse.ctrl;canvas.trigger(ev.type,ev)})},capture:async function(filename){if(filename.constructor!==String)throw new Error("A capture file name must be a string.");if(filename.slice(-4)!=".png")filename+=".png";var img=await this.__renderer.screenshot();var a=document.createElement("a");a.href=img.src;a.download=filename;a.click();a.remove()},waitfor:async function(eventTypes){var cvs=this;var __waitfor__expecting_key=this.__expecting_key;var __waitfor=eventTypes;cvs.__waitfor_bound=undefined;cvs.__expecting_key=__waitfor.search("key")>=0;if(__waitfor=="textures")cvs.waitfor_textures=true;function __waiting(ev){cvs.__waitfor_bound=ev}cvs.bind(__waitfor,__waiting);var w;while(true){await rate(60);w=cvs.__waitfor_bound;if(w!==undefined){if(__waitfor=="textures"&&w===null)break;else if(__waitfor.search(w.type)>=0)break}}cvs.__waitfor_bound=undefined;cvs.unbind(__waitfor,__waiting);__waitfor="";cvs.__expecting_key=__waitfor__expecting_key;return new Promise(resolve=>{resolve(w)})},pause:async function(args){var cvs=this;__waitfor__expecting_key=this.__expecting_key;cvs.__waitfor_bound=undefined;var w;var prompt="";if(args!==undefined)prompt=args.toString();function __waiting(ev){cvs.__waitfor_bound=ev}if(prompt.length>0){if(cvs.__prompt==undefined){cvs.__prompt=label({canvas:cvs,align:"right",pixel_pos:true,height:14,color:color.black,background:color.white,opacity:1,box:false})}cvs.__prompt.pos=vec(cvs.__width,cvs.__height-12,0);cvs.__prompt.text=prompt;cvs.__prompt.visible=true;cvs.bind("click",__waiting);while(true){await rate(60);w=cvs.__waitfor_bound;if(w!==undefined){cvs.__prompt.visible=false;break}}}else{if(cvs.__draw==undefined)cvs.__draw=draw({canvas:cvs});var x=cvs.width-5,y=cvs.height-20;cvs.__draw.points=[vec(x,y,0),vec(x-30,y-13,0),vec(x-30,y+15,0),vec(x,y,0)];cvs.__draw.opacity=1;cvs.__draw.color=color.black;cvs.__draw.fillcolor=color.white;cvs.__draw.visible=true;cvs.bind("click",__waiting);while(true){await rate(60);w=cvs.__waitfor_bound;if(w!==undefined){cvs.__draw.visible=false;break}}}cvs.__waitfor_bound=undefined;cvs.unbind(__waitfor,__waiting);cvs.__expecting_key=__waitfor__expecting_key;return new Promise(resolve=>{resolve(w)})},select:function(){window.__context.canvas_selected=this},title_anchor:{get:function(){if(!this.__activated)this.__activate();return this.__title_anchor},set:function(value){throw new Error("Cannot change title_anchor")}},caption_anchor:{get:function(){if(!this.__activated)this.__activate();return this.__caption_anchor},set:function(value){throw new Error("Cannot change caption_anchor")}},title:{get:function(){return this.__titletext},set:function(value){this.__titletext=value;this.__title_anchor.html(value)}},caption:{get:function(){return this.__captiontext},set:function(value){this.__captiontext=value;this.__caption_anchor.html(value)}},append_to_title:function(args){var s="";var L=arguments.length;for(var i=0;i=0)this.__expecting_key=true;for(var i=0;i=0)this.__expecting_key=false;var etypes=eventTypes.split(" ");for(var i=0;i=0)types=types.replace(t,"")}this.events[i][0]=types;return}}},trigger:async function(type,evarg){var ev={type:type,event:evarg};if(type=="mouse"){var ev={type:evarg.type,pageX:evarg.pageX,pageY:evarg.pageY,which:1};this.mouse.__update(ev);ev.event=ev.type;ev.pos=this.mouse.pos;if(ev.type=="mousedown"){ev.press="left";ev.release=null}else if(ev.type=="mousemove"){ev.press=null;ev.release=null}else if(ev.type=="mouseup"){ev.press=null;ev.release="left"}else if(ev.type=="mouseenter"||ev.type=="mouseleave"){ev.press=null;ev.release=null}else if(ev.type=="click"){ev.press=null;ev.release="left"}}else if(type.slice(0,3)=="key"){ev={type:type,event:type,which:evarg.which};ev.key=evarg.key;ev.alt=evarg.alt;ev.ctrl=evarg.ctrl;ev.shift=evarg.shift}if(evarg!==null){this.__triggered=ev;ev.canvas=this;if(ev.type===undefined)return}for(var i=0;i=0){(await this.events[i][1])(ev)}}},background:new vec(0,0,0),opacity:1,ambient:new vec(.2,.2,.2),__change:function(){if(this.__lastevent!==null&&this.hasmouse)this.mouse.__update(this.__lastevent);if(this.__overlay_objects)this.__overlay_objects.__changed=true},center:new attributeVector(null,0,0,0),axis:new attributeVector(null,0,0,-1),up:new attributeVector(null,0,1,0),forward:{get:function(){return this.__axis},set:function(value){this.axis=value}},__last_axis:null,__last_center:null,__activated:false,userzoom:true,userspin:true,userpan:true,fov:60*Math.PI/180,width:{value:640,onchanged:function(){this.__canvas_element.width=this.__canvas_element.style.width=this.__overlay_element.width=this.__overlay_element.style.width=this.__width}},height:{value:400,onchanged:function(){this.__canvas_element.height=this.__canvas_element.style.height=this.__overlay_element.height=this.__overlay_element.style.height=this.wrapper[0].style.height=this.__height}},align:{get:function(){return this.__align},set:function(value){if(value=="left"||value=="right"||value=="none"){this.__align=value}else throw new Error("align must be 'left', 'right', or 'none' (the default).")}},resizable:{value:true,onchanged:function(){if(this.__activated){this.wrapper.resizable((this.resizable?"en":"dis")+"able")}}},autoscale:{get:function(){return this.__autoscale},set:function(value){if(this.__autoscale&&!value)Autoscale.compute_autoscale(this);this.__autoscale=value}},range:{get:function(){if(this.__autoscale){Autoscale.compute_autoscale(this)}return this.__range},set:function(value){this.__autoscale=false;this.__range=value;if(this.__lastevent!==null)this.mouse.__update(this.__lastevent)}},pixel_to_world:{get:function(){var w=this.__width;var h=this.__height;var d=2*this.range;if(w>=h){return d/h}else{return d/w}},set:function(value){throw new Error("Cannot assign a value to pixel_to_world.")}},objects:{get:function(){var all=[];for(var id in this.__visiblePrimitives){var v=this.__visiblePrimitives[id];if(v.__obj){if(v==v.__obj.__components[0]&&v.__obj.visible)all.push(v.__obj)}else all.push(v)}for(var id in this.__overlay_objects.objects){var obj=this.__overlay_objects.objects[id];if(obj instanceof label)all.push(obj)}return all}}});property.declare(canvas,{selected:{get:function(){return window.__context.canvas_selected||null},set:function(value){window.__context.canvas_selected=value}},get_selected:function(){return window.__context.canvas_selected||null},all:{get:function(){var v=window.__context.canvas_all;if(v===undefined)v=window.__context.canvas_all=[];return v}},container:{get:function(){return window.__context.glowscript_container||null},set:function(value){window.__context.glowscript_container=$(value)}}});function Mouse(canvas){this.canvas=canvas}property.declare(Mouse.prototype,{canvas:null,pos:null,ray:null,__pickx:null,__picky:null,pick:function(){return this.canvas.__renderer.render(1)},project:function(args){if(args.normal===undefined)throw new Error("scene.mouse.project() must specify a normal");var normal=args.normal;var dist;if(args.d===undefined&&args.point===undefined)dist=normal.dot(this.canvas.__center);else if(args.d!==undefined){dist=args.d}else if(args.point!==undefined){dist=normal.dot(args.point)}var ndc=normal.dot(this.canvas.camera.pos)-dist;var ndr=normal.dot(this.ray);if(ndr==0)return null;var t=-ndc/ndr;return this.canvas.camera.pos.add(this.ray.multiply(t))},alt:false,ctrl:false,shift:false,__update:function(ev){var cv=this.canvas,factor;if(cv.__width>cv.__height)factor=2*cv.__range/cv.__height;else factor=2*cv.__range/cv.__width;var o=$(cv.__canvas_element).offset();this.__pickx=ev.pageX-o.left;this.__picky=cv.__height-(ev.pageY-o.top);var mx=(this.__pickx-cv.__width/2)*factor;var my=(this.__picky-cv.__height/2)*factor;var xaxis=cv.__axis.norm().cross(cv.__up).norm();var yaxis=xaxis.cross(cv.__axis.norm());this.pos=cv.__center.add(xaxis.multiply(mx).add(yaxis.multiply(my)));this.ray=this.pos.sub(cv.camera.pos).norm();canvas.hasmouse=cv;cv.__lastevent=ev}});var exports={canvas:canvas,keysdown:keysdown};Export(exports)})();(function(){"use strict";var toType=function(obj){return{}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()};function orbital_camera(canvas){if(!(this instanceof orbital_camera))return new orbital_camera(canvas);this.canvas=canvas;this.follower=null}property.declare(orbital_camera.prototype,{pos:{get:function(){var c=this.canvas;return c.__center.sub(c.__axis.norm().multiply(c.range/Math.tan(c.fov/2)))},set:function(val){var c=this.canvas;c.center=val.add(this.axis)}},axis:{get:function(){var c=this.canvas;return c.__axis.norm().multiply(c.range/Math.tan(c.fov/2))},set:function(val){var c=this.canvas;c.center=this.pos.add(val);c.axis=norm(val);c.range=mag(val)*Math.tan(c.fov/2)}},rotate:function(rargs){var L=arguments.length;if(L<1||L>3)throw new Error("camera.rotate takes 1 to 3 arguments");var args={};for(var i=0;i1e-6)c.axis=c.__axis.rotate({angle:angle,axis:rotaxis});c.up=c.__up.rotate({angle:angle,axis:rotaxis});c.center=origin.add(this.axis);window.__adjustupaxis=true},follow:function(objectOrFunction){this.follower=objectOrFunction},__activate:function(){var canvas=this.canvas;var camera=this;var contextMenuDisabled=false;var lastX=[null,null],lastY=[null,null];var downX=[null,null],downY=[null,null];var lastpos=null;var angleX=0,angleY=0;var afterdown=false;var rotating,zrotating,zooming,panning;var leftButton=false,rightButton=false,mouseWheel=false;var lastSep=null;var lastAngle=null;var fingers=0;var nomove=false;var tstart;var zoompos=[null,null];var saveEvent;var zoom=function(delta){var z=Math.exp(-delta*.05);canvas.range=canvas.range*z};var zrotate=function(dtheta){canvas.up=canvas.up.rotate({angle:2*dtheta,axis:canvas.__axis})};var spin=function(ev){var dx=ev.pageX-lastX[0];var dy=ev.pageY-lastY[0];angleX+=dx*.01;angleY+=dy*.01;if(angleY<-1.4)angleY=-1.4;if(angleY>1.4)angleY=1.4;canvas.__axis=canvas.__axis.rotate({angle:-.01*dx,axis:canvas.__up});var max_vertical_angle=canvas.__up.diff_angle(canvas.__axis.multiply(-1));var vertical_angle=.01*dy;if(!(vertical_angle>=max_vertical_angle||vertical_angle<=max_vertical_angle-Math.PI)){canvas.__axis=canvas.__axis.rotate({angle:-vertical_angle,axis:canvas.__axis.cross(canvas.__up)})}};var pan=function(ev){var csave=vec(canvas.__last_center);canvas.mouse.__update(ev);var c=canvas.mouse.pos;var xaxis=canvas.__axis.cross(canvas.__up).hat;var yaxis=xaxis.cross(canvas.__axis).hat;var d=c.sub(lastpos);var dx=d.dot(xaxis);var dy=d.dot(yaxis);lastpos=c.sub(d);canvas.__center=canvas.__center.sub(xaxis.multiply(dx).add(yaxis.multiply(dy)));canvas.__last_center=csave};$(document).bind("contextmenu",function(e){return!contextMenuDisabled});canvas.elements.mousewheel(function(ev,delta){if(canvas.userzoom)zoom(delta);return false});canvas.elements.mousedown(function(ev){if(ev.which==1)leftButton=true;if(ev.which==3)rightButton=true;rotating=canvas.userspin&&(ev.which==3||ev.which==1&&canvas.mouse.ctrl&&!canvas.mouse.alt);zooming=canvas.userzoom&&(ev.which==2||ev.which==1&&canvas.mouse.alt&&!canvas.mouse.ctrl||leftButton&&rightButton);panning=canvas.userpan&&ev.which==1&&canvas.mouse.shift;if(ev.which==3&&!(rotating||zooming))return;downX[0]=lastX[0]=ev.pageX;downY[0]=lastY[0]=ev.pageY;if(rotating||zooming||panning)contextMenuDisabled=true;else if(ev.which==1)canvas.trigger("mouse",ev);if(panning){canvas.autoscale=false;canvas.mouse.__update(ev);lastpos=canvas.mouse.pos}afterdown=true;ev.preventDefault();ev.stopPropagation();return false});canvas.elements.mousemove(function(ev){if(ev.pageX===lastX[0]&&ev.pageY===lastY[0])return;if(!afterdown){canvas.mouse.__update(ev);return}if(zooming){var dy=lastY[0]-ev.pageY;if(dy!==0)zoom(.1*dy)}else if(rotating){spin(ev)}else if(panning){pan(ev)}else if(ev.which==1)canvas.trigger("mouse",ev);if(!panning){lastX[0]=ev.pageX;lastY[0]=ev.pageY}});canvas.elements.mouseup(function(ev){if(ev.which==1)leftButton=false;if(ev.which==3)rightButton=false;if(!afterdown)return;if(ev.which==3&&contextMenuDisabled)setTimeout(function(){contextMenuDisabled=false},0);if(!(rotating||zooming||panning)){if(ev.which==1){canvas.trigger("mouse",ev);if(abs(ev.pageX-downX[0])<=5&&abs(ev.pageY-downY[0])<=5){ev.type="click";canvas.trigger("mouse",ev)}}else if(ev.which==3){contextMenuDisabled=true;return}}rotating=zooming=panning=afterdown=false;lastX=[null,null];lastY=[null,null]});canvas.elements.bind("touchstart",function(ev){rotating=zooming=nomove=false;lastSep=lastAngle=null;var pt;var data=ev.originalEvent.targetTouches;if(data.length>2)return;if(data.length==2&&!(canvas.userspin||canvas.userzoom))return;fingers++;for(var i=0;i2)return;var pt;var newx=[null,null],newy=[null,null];var relx=[0,0],rely=[0,0];for(var i=0;i15||dzoom[1].mag>15){saveEvent=null;zooming=true;var r=zoompos[1].sub(zoompos[0]).norm();var angmom=r.cross(dzoom[1]).sub(r.cross(dzoom[0])).mag;if(angmom>10){zrotating=canvas.userspin;if(!canvas.userspin)zooming=false}}else return}}if(saveEvent!==null){if(data.length==2){saveEvent=null}else{var near=Math.abs(relx[0])<=5&&Math.abs(rely[0])<=5;if(!rotating&&t>150&&near){canvas.trigger("mouse",saveEvent);saveEvent=null}else if(!near){rotating=canvas.userspin;saveEvent=null}}}else{if(newx[0]===lastX[0]&&newy[0]===lastY[0]&&newx[1]===lastX[1]&&newy[1]===lastY[1])return;ev.pageX=newx[0];ev.pageY=newy[0];ev.type="mousemove";if(rotating)spin(ev);else if(zooming){var xx=newx[1]-newx[0];var yy=newy[1]-newy[0];if(zrotating){var angle=Math.atan2(yy,xx);if(lastAngle!==null){var dangle;var va=vec(Math.cos(lastAngle),Math.sin(lastAngle),0);var vb=vec(Math.cos(angle),Math.sin(angle),0);var vc=va.cross(vb);var amag=Math.abs(Math.asin(vc.mag));if(vc.z>=0)dangle=-amag;else dangle=amag;zrotate(dangle)}lastAngle=angle}else if(canvas.userzoom){var sep=Math.sqrt(xx*xx+yy*yy);if(lastSep!==null&&sep!=lastSep)zoom(.2*(sep-lastSep));lastSep=sep}}else canvas.trigger("mouse",ev)}lastX[0]=newx[0];lastX[1]=newx[1];lastY[0]=newy[0];lastY[1]=newy[1]});canvas.elements.bind("touchend",function(ev){fingers--;if(saveEvent!==null&&!(rotating||zooming)){canvas.trigger("mouse",saveEvent);saveEvent=null}var data=ev.originalEvent.changedTouches;ev.pageX=data[0].clientX;ev.pageY=data[0].clientY;if(!(rotating||zooming)){ev.type="mouseup";canvas.trigger("mouse",ev);if(Math.abs(ev.pageX-downX[0])<=5&&Math.abs(ev.pageY-downY[0])<=5){ev.type="click";canvas.trigger("mouse",ev)}}if(zooming){if(fingers>0)nomove=true;else zooming=nomove=false}rotating=false;lastX=[null,null];lastY=[null,null];lastSep=lastAngle=null})}});var exports={orbital_camera:orbital_camera};Export(exports)})();(function(){"use strict";function extent(){}$.extend(extent.prototype,{xmin:null,ymin:null,zmin:null,xmax:null,ymax:null,zmax:null,zx_camera:0,zy_camera:0,last_zx_camera:-1,last_zy_camera:-1,point_extent:function(obj,p){this.xmin=Math.min(p.x,this.xmin);this.ymin=Math.min(p.y,this.ymin);this.zmin=Math.min(p.z,this.zmin);this.xmax=Math.max(p.x,this.xmax);this.ymax=Math.max(p.y,this.ymax);this.zmax=Math.max(p.z,this.zmax);obj.__xmin=Math.min(p.x,obj.__xmin);obj.__ymin=Math.min(p.y,obj.__ymin);obj.__zmin=Math.min(p.z,obj.__zmin);obj.__xmax=Math.max(p.x,obj.__xmax);obj.__ymax=Math.max(p.y,obj.__ymax);obj.__zmax=Math.max(p.z,obj.__zmax)}});var exports={Autoscale:{compute_autoscale:function compute_autoscale(canvas){var ext=canvas.__extent;if(!ext)ext=canvas.__extent=new extent;var ctrx=canvas.center.x,ctry=canvas.center.y,ctrz=canvas.center.z;var all=canvas.__visiblePrimitives;ext.zx_camera=0;ext.zy_camera=0;var cot_hfov=1/Math.tan(canvas.__fov/2);ext.__cot_hfov=cot_hfov;ext.__centerx=canvas.center.x;ext.__centery=canvas.center.y;ext.__centerz=canvas.center.z;var check=false;var obj;for(var id in all){obj=all[id];if(obj.constructor.name=="point")continue;if(obj.constructor.name=="points")continue;check=true;if(canvas.__changed[obj.__id]||obj.__zx_camera===null||obj.__zy_camera===null){obj.__get_extent(ext);if(obj.__xmin===null)continue;var xx=Math.max(Math.abs(obj.__xmin-ctrx),Math.abs(obj.__xmax-ctrx));var yy=Math.max(Math.abs(obj.__ymin-ctry),Math.abs(obj.__ymax-ctry));var zz=Math.max(Math.abs(obj.__zmin-ctrz),Math.abs(obj.__zmax-ctrz));obj.__zx_camera=xx*cot_hfov+zz;obj.__zy_camera=yy*cot_hfov+zz}ext.zx_camera=Math.max(ext.zx_camera,obj.__zx_camera);ext.zy_camera=Math.max(ext.zy_camera,obj.__zy_camera)}if(check){if(ext.zx_camera>ext.last_zx_camera||ext.zx_cameraext.last_zy_camera||ext.zy_cameraext.zy_camera){if(canvas.__width>=canvas.__height){canvas.__range=1.1*(canvas.__height/canvas.__width)*ext.zx_camera/cot_hfov}else{canvas.__range=1.1*ext.zx_camera/cot_hfov}}else{if(canvas.__width>=canvas.__height){canvas.__range=1.1*ext.zy_camera/cot_hfov}else{canvas.__range=1.1*(canvas.__width/canvas.__height)*ext.zy_camera/cot_hfov}}ext.last_zx_camera=ext.zx_camera;ext.last_zy_camera=ext.zy_camera}}},find_extent:function find_extent(obj,ext){if(obj.constructor.name=="points")return;if((obj.constructor.name=="simple_sphere"||obj.constructor.name=="vp_simple_sphere")&&obj.__pixels){for(var a=0;a<8;a++)ext.point_extent(obj,obj.__pos);return}var size=obj.__size;var sizex=size.x,sizey=size.y,sizez=size.z;var start=obj.__pos;var startx=start.x,starty=start.y,startz=start.z;var center_pos=obj.__hasPosAtCenter;var length;if(center_pos)length=Math.sqrt(sizex*sizex+sizey*sizey+sizez*sizez)/2;else length=Math.sqrt(sizex*sizex+sizey*sizey/4+sizez*sizez/4);var px=startx-ext.__centerx;var py=starty-ext.__centery;var pz=startz-ext.__centerz;var zzx=(Math.abs(px)+length)*ext.__cot_hfov+Math.abs(pz)+length;var zzy=(Math.abs(py)+length)*ext.__cot_hfov+Math.abs(pz)+length;if(zzx>i}return x+1}function handleLoadedTexture(image,obj,bump){var name,t0,ref;if(bump){name=obj.__tex.bumpmap;ref=obj.__tex.bumpmap_ref;t0=obj.__tex.bumpmap_t0}else{name=obj.__tex.file;ref=obj.__tex.texture_ref;t0=obj.__tex.texture_t0}var tf=msclock();tf=tf-t0;if(name in cvs.textures){ref.reference=cvs.textures[name]}else{cvs.textures[name]=ref.reference=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,ref.reference);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);if(!isPowerOfTwo(image.width)||!isPowerOfTwo(image.height)){var c=document.createElement("canvas");c.width=nextHighestPowerOfTwo(image.width);c.height=nextHighestPowerOfTwo(image.height);var ctx=c.getContext("2d");ctx.drawImage(image,0,0,c.width,c.height);image=c}gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,image);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR_MIPMAP_NEAREST);gl.generateMipmap(gl.TEXTURE_2D);gl.bindTexture(gl.TEXTURE_2D,null)}if(name in cvs.textures_requested){var done=cvs.textures_requested[name];while(done.length>0){var data=done.pop();if(data[1]){data[0].__tex.bumpmap_ref.reference=ref.reference}else{data[0].__tex.texture_ref.reference=ref.reference}data[0].__change()}}}this.initTexture=function(name,obj,bump){if(bump)obj.__tex.bumpmap=name;else obj.__tex.file=name;if(name in cvs.textures){if(bump)obj.__tex.bumpmap_ref.reference=cvs.textures[name];else obj.__tex.texture_ref.reference=cvs.textures[name];return}if(name in cvs.textures_requested){cvs.textures_requested[name].push([obj,bump]);return}else cvs.textures_requested[name]=[[obj,bump]];var t0=msclock();if(bump)obj.__tex.bumpmap_t0=t0;else obj.__tex.texture_t0=t0;var image=new Image;image.crossOrigin="anonymous";image.src=name;image.onload=function(){handleLoadedTexture(image,obj,bump)}};var update_vertices=0;cvs.__last_width=-1;cvs.__last_height=-1;cvs.__last_axis=cvs.__axis;cvs.__last_up=cvs.__up;cvs.__waitfor_image=false;var ktexture=1;var peels={C0:null,D0:null,C1:null,D1:null,C2:null,D2:null,C3:null,D3:null,C4:null,EXTENT_TEXTURE:null};var fullpeels=gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS)>=16;var textureN={C0:gl.TEXTURE2,D0:gl.TEXTURE3,C1:gl.TEXTURE4,D1:gl.TEXTURE5,C2:gl.TEXTURE6,D2:gl.TEXTURE7,C3:gl.TEXTURE8,D3:gl.TEXTURE9,C4:gl.TEXTURE10,EXTENT_TEXTURE:gl.TEXTURE11};function makeTexture(T){gl.activeTexture(textureN[T]);gl.bindTexture(gl.TEXTURE_2D,peels[T]);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);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);if(false&&T=="EXTENT_TEXTURE")gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,3,3,0,gl.RGBA,gl.UNSIGNED_BYTE,null);else gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,ktexture*cvs.__width,ktexture*cvs.__height,0,gl.RGBA,gl.UNSIGNED_BYTE,null);gl.bindTexture(gl.TEXTURE_2D,null)}for(var T in peels){peels[T]=gl.createTexture();makeTexture(T)}var peelFramebuffer=gl.createFramebuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,peelFramebuffer);var peelRenderbuffer=gl.createRenderbuffer();gl.bindRenderbuffer(gl.RENDERBUFFER,peelRenderbuffer);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,ktexture*cvs.__width,ktexture*cvs.__height);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,peelRenderbuffer);gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null);var data=new Uint8Array(3);var tex1=gl.createTexture();gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,tex1);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,1,1,0,gl.RGB,gl.UNSIGNED_BYTE,data);var tex0=gl.createTexture();gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tex0);gl.texImage2D(gl.TEXTURE_2D,0,gl.RGB,1,1,0,gl.RGB,gl.UNSIGNED_BYTE,data);this.render=function(mode){if(mode==RENDER){if(cvs.waitfor_textures){var check_objects=cvs.objects;for(var o in check_objects){var obj=check_objects[o];if(obj.__tex===undefined)continue;if(!obj.ready)return}cvs.waitfor_textures=false;cvs.trigger("textures",null)}}if(!cvs.visible){if(mode==RENDER)return;return null}if(cvs.__width!=cvs.__last_width||cvs.__height!=cvs.__last_height){for(var T in peels){makeTexture(T)}gl.bindFramebuffer(gl.FRAMEBUFFER,peelFramebuffer);gl.bindRenderbuffer(gl.RENDERBUFFER,peelRenderbuffer);gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,ktexture*cvs.__width,ktexture*cvs.__height);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,peelRenderbuffer);gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.bindFramebuffer(gl.FRAMEBUFFER,null)}if(mode==RENDER){for(var i in cvs.arrows){var pos;var a=cvs.arrows[i];if(!a.run)continue;if(a.obj!==undefined){if(a.obj.pos!==undefined)pos=a.obj.pos;else continue}a.arrow.pos=pos;if(a.obj[a.attr]!==undefined){if(!a.arrow.visible)a.arrow.visible=true;a.arrow.axis=a.obj[a.attr].multiply(a.scale)}}for(var i in cvs.trails){var pos;var a=cvs.trails[i];if(!a.__run)continue;var obj=a.__obj;if(obj===undefined)continue;if(typeof obj==="string"){pos=a[obj];if(pos===undefined)continue}else if(typeof obj!=="function"){if(obj!==undefined&&obj.visible){if(!obj._pos_set)continue;if(obj.__interval>0)continue;if(obj.__pos!==undefined)pos=obj.__pos;else continue}else continue}else pos=obj();if(a.__last_pos!==null&&pos.equals(a.__last_pos))continue;if(a.pps>0){var tnow=msclock();if(a.__last_time===null)a.last_time=tnow;if(tnow-a.__last_time>1e3/a.pps)a.__last_time=tnow;else if(tnow!=a.__last_time)continue}a.__trail.push({pos:pos,color:a.color,radius:a.radius,retain:a.retain});a.__last_pos=vec(pos)}if(cvs.update_billboards||!cvs.__axis.equals(cvs.__last_axis)||!cvs.__up.equals(cvs.__last_up)){cvs.update_billboards=false;for(var i=0;i=canvasElement.clientHeight)camera.distance=cvs.__range/Math.tan(cvs.__fov/2);else camera.distance=cvs.__range*(canvasElement.clientHeight/canvasElement.clientWidth)/Math.tan(cvs.__fov/2);camera.pos=mat4.multiplyVec3(mat4.rotateX(mat4.rotateY(mat4.identity(mat4.create()),-camera.angleX),-camera.angleY),vec3.create([0,0,camera.distance]));camera.pos=vec3.create([cvs.__center.x+camera.pos[0],cvs.__center.y+camera.pos[1],cvs.__center.z+camera.pos[2]]);camera.zNear=camera.distance/100;camera.zFar=camera.distance*10;var projMatrix=mat4.perspective(camera.fovy,canvasElement.clientWidth/canvasElement.clientHeight,camera.zNear,camera.zFar);var viewMatrix=mat4.lookAt(camera.pos,camera.target,camera.up);for(var i=0;i0){var scale=2*cvs.__range/cvs.__width;for(var i=0;i0&&(cvs.__overlay_objects.__changed||!(cvs.__axis.equals(cvs.__last_axis)&&cvs.__center.equals(cvs.__last_center)&&cvs.__up.equals(cvs.__last_up)&&cvs.__width==cvs.__last_width&&cvs.__height==cvs.__last_height&&cvs.__range==cvs.__last_range))){cvs.__overlay_objects.__changed=false;var ctx=cvs.overlay_context;ctx.clearRect(0,0,cvs.__width,cvs.__height);for(var i=0;iPEEL_D0)gl.uniform2fv(prog.uniforms.canvas_size,canvas_size);if(minormode!=MERGE){if(mode==RENDER||minormode==PEEL_C0||minormode==PEEL_C1||minormode==PEEL_C2||minormode==PEEL_C3||minormode==PEEL_C4){gl.uniform1i(prog.uniforms.light_count,light_count);gl.uniform4fv(prog.uniforms.light_pos,light_pos);gl.uniform3fv(prog.uniforms.light_color,light_color);gl.uniform3fv(prog.uniforms.light_ambient,light_ambient);gl.enableVertexAttribArray(prog.attributes.normal);if(prog!=curve_program){gl.enableVertexAttribArray(prog.attributes.color);gl.enableVertexAttribArray(prog.attributes.opacity);gl.enableVertexAttribArray(prog.attributes.shininess);gl.enableVertexAttribArray(prog.attributes.emissive);gl.enableVertexAttribArray(prog.attributes.texpos);gl.enableVertexAttribArray(prog.attributes.bumpaxis);gl.uniform1i(prog.uniforms.texmap,0);gl.uniform1i(prog.uniforms.bumpmap,1)}}gl.uniformMatrix4fv(prog.uniforms.viewMatrix,false,viewMatrix);gl.uniformMatrix4fv(prog.uniforms.projMatrix,false,projMatrix)}if(minormode==MERGE){gl.uniform1i(prog.uniforms.C0,2);gl.uniform1i(prog.uniforms.C1,4);if(fullpeels){gl.uniform1i(prog.uniforms.C2,6);gl.uniform1i(prog.uniforms.C3,8);gl.uniform1i(prog.uniforms.C4,10)}}else if(minormode>PEEL_D0){gl.uniform1i(prog.uniforms.D0,3);if(minormode==PEEL_C2||minormode==PEEL_D2)gl.uniform1i(prog.uniforms.D1,5);else if(minormode==PEEL_C3||minormode==PEEL_D3)gl.uniform1i(prog.uniforms.D2,7);else if(minormode==PEEL_C4)gl.uniform1i(prog.uniforms.D3,9)}}function subrender(minormode,T,Trefs){if(mode==RENDER_TEXTURE&&Trefs.length>0){for(var i=0;iPEEL_C0)gl.clearColor(0,0,0,0);else if(mode==EXTENT)gl.clearColor(0,0,0,1);else gl.clearColor(cvs.__background.x,cvs.__background.y,cvs.__background.z,cvs.__opacity);if(mode==EXTENT){gl.depthFunc(gl.GREATER);gl.clearDepth(0)}else{gl.depthFunc(gl.LEQUAL);gl.clearDepth(1)}gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);function render_curves(){var model=object_models.curve;var objs=model.id_object;var elements=model.elementType;var model_length=model.index.length;var setup=true;for(var id in objs){if(!objs[id].visible)break;if(minormode>PEEL_D0)break;if(setup){if(minormode==RENDER||minormode==PEEL_C0){if(curve_program==null)curve_program=shaderProgram(shaders.opaque_render_fragment,shaders.curve_render_vertex,gl);useProgram(curve_program,minormode)}else if(minormode==PEEL_D0){if(curve_peel_depth_programD0==null)curve_peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.curve_peel_depth_vertex,gl);useProgram(curve_peel_depth_programD0,minormode)}else if(minormode==PICK){if(curve_pick_program==null)curve_pick_program=shaderProgram(shaders.pick_fragment,shaders.curve_pick_vertex,gl);useProgram(curve_pick_program,minormode)}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.vertexAttribPointer(program.attributes.pos,4,gl.FLOAT,false,0,0);if(minormode!=PICK&&minormodePEEL_D0){if(op=="opaque")continue}else{if(op=="transparent")continue}var first=true;for(var sort_type in sort[op]){for(var sort_list in sort[op][sort_type]){if(first){first=false;switch(minormode){case RENDER:case PEEL_C0:if(triangle_program===null)triangle_program=shaderProgram(shaders.opaque_render_fragment,shaders.tri_render_vertex,gl);useProgram(triangle_program,minormode);break;case EXTENT:if(extent_program===null)extent_program=shaderProgram(shaders.pick_fragment,shaders.extent_vertex,gl);useProgram(extent_program,minormode);break;case PEEL_D0:if(tri_peel_depth_programD0===null)tri_peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD0,minormode);break;case PEEL_D1:if(tri_peel_depth_programD1===null)tri_peel_depth_programD1=shaderProgram(shaders.peel_depth_fragmentD1,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD1,minormode);break;case PEEL_D2:if(tri_peel_depth_programD2===null)tri_peel_depth_programD2=shaderProgram(shaders.peel_depth_fragmentD2,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD2,minormode);break;case PEEL_D3:if(tri_peel_depth_programD3===null)tri_peel_depth_programD3=shaderProgram(shaders.peel_depth_fragmentD3,shaders.tri_peel_depth_vertex,gl);useProgram(tri_peel_depth_programD3,minormode);break;case PEEL_C1:if(tri_peel_color_programC1===null)tri_peel_color_programC1=shaderProgram(shaders.peel_color_fragmentC1,shaders.tri_render_vertex,gl);useProgram(tri_peel_color_programC1,minormode);break;case PEEL_C2:if(tri_peel_color_programC2===null)tri_peel_color_programC2=shaderProgram(shaders.peel_color_fragmentC2,shaders.tri_render_vertex,gl);useProgram(tri_peel_color_programC2,minormode);break;case PEEL_C3:if(tri_peel_color_programC3===null)tri_peel_color_programC3=shaderProgram(shaders.peel_color_fragmentC3,shaders.tri_render_vertex,gl);useProgram(tri_peel_color_programC3,minormode);break;case PEEL_C4:if(tri_peel_color_programC4===null)tri_peel_color_programC4=shaderProgram(shaders.peel_color_fragmentC4,shaders.tri_render_vertex,gl);useProgram(tri_peel_color_programC4,minormode);break}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.pos,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.pos,3,gl.FLOAT,false,0,0);if(mode==RENDER||minormode==PEEL_C0||minormode==PEEL_C1||minormode==PEEL_C2||minormode==PEEL_C3||minormode==PEEL_C4){gl.bindBuffer(gl.ARRAY_BUFFER,model.normalBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.normal,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.normal,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.colorBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.color,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.color,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.opacityBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.opacity,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.opacity,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.shininessBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.shininess,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.shininess,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.emissiveBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.emissive,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.emissive,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.texposBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.texpos,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.texpos,2,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.bumpaxisBuffer);if(update_vertices)gl.bufferData(gl.ARRAY_BUFFER,model_arrays.bumpaxis,gl.DYNAMIC_DRAW);gl.vertexAttribPointer(program.attributes.bumpaxis,3,gl.FLOAT,false,0,0);update_vertices=0}}var indices=sort[op][sort_type][sort_list];var tbobj=indices[0];var model_index=new Uint16Array(indices.slice(1));var model_length=model_index.length;gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);gl.bufferData(gl.ELEMENT_ARRAY_BUFFER,model_index,gl.DYNAMIC_DRAW);if(mode==EXTENT)elements=gl.POINTS;var Tdata=0,Bdata=0;if(sort_type=="textures"){if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.file!==null){if(tbobj.__tex.texture_ref.reference!==null){gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.texture_ref.reference);Tdata=1}else continue}}else if(sort_type=="bumpmaps"){if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.bumpmap!==null){if(tbobj.__tex.bumpmap_ref.reference!==null){gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.bumpmap_ref.reference);Bdata=1}else continue}}else if(sort_type=="textures_and_bumpmaps"){if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.file!==null){if(tbobj.__tex.texture_ref.reference!==null){gl.activeTexture(gl.TEXTURE0);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.texture_ref.reference);Tdata=1}else continue}if((mode==RENDER||mode==RENDER_TEXTURE)&&tbobj.__tex.bumpmap!==null){if(tbobj.__tex.bumpmap_ref.reference!==null){gl.activeTexture(gl.TEXTURE1);gl.bindTexture(gl.TEXTURE_2D,tbobj.__tex.bumpmap_ref.reference);Bdata=1}else continue}}gl.uniform1f(program.uniforms.T,Tdata);gl.uniform1f(program.uniforms.B,Bdata);gl.drawElements(elements,model_length,gl.UNSIGNED_SHORT,0)}}}}function render_merge(){var model=object_models.quad;var elements=model.elementType;var model_length=model.index.length;if(fullpeels){if(merge_program==null)merge_program=shaderProgram(shaders.merge_fragment,shaders.merge_vertex,gl);useProgram(merge_program,minormode)}else{if(merge_program2==null)merge_program2=shaderProgram(shaders.merge_fragment2,shaders.merge_vertex,gl);useProgram(merge_program2,minormode)}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.vertexAttribPointer(program.attributes.pos,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);gl.drawElements(elements,model_length,gl.UNSIGNED_SHORT,0)}for(var m in object_models){if(minormode>=MERGE){render_merge();break}if(m=="quad"||m=="triangle"){if(triangles_exist)render_triangles();continue}else if(m=="curve"){render_curves();continue}var model=object_models[m];var elements=model.elementType;var model_length=model.index.length;var objs;if(minormode>PEEL_D0){if(cvs.__transparent_objects[m]===undefined)continue;objs=cvs.__transparent_objects[m]}else{if(cvs.__opaque_objects[m]===undefined)continue;objs=cvs.__opaque_objects[m]}var gotobjects=false;for(var id in objs){gotobjects=true;break}if(!gotobjects)continue;var ringobject=m=="ring"||m=="vp_ring";switch(minormode){case RENDER:case PEEL_C0:if(ringobject){if(ring_program===null)ring_program=shaderProgram(shaders.opaque_render_fragment,shaders.ring_render_vertex,gl);useProgram(ring_program,minormode)}else{if(standard_program===null)standard_program=shaderProgram(shaders.opaque_render_fragment,shaders.render_vertex,gl);useProgram(standard_program,minormode)}break;case PICK:if(ringobject){if(ring_pick_program===null)ring_pick_program=shaderProgram(shaders.pick_fragment,shaders.ring_pick_vertex,gl);useProgram(ring_pick_program,minormode)}else{if(pick_program===null)pick_program=shaderProgram(shaders.pick_fragment,shaders.pick_vertex,gl);useProgram(pick_program,minormode)}break;case EXTENT:if(extent_program===null)extent_program=shaderProgram(shaders.pick_fragment,shaders.extent_vertex,gl);useProgram(extent_program,minormode);break;case PEEL_D0:if(ringobject){if(ring_peel_depth_programD0===null)ring_peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD0,minormode)}else{if(peel_depth_programD0===null)peel_depth_programD0=shaderProgram(shaders.peel_depth_fragmentD0,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD0,minormode)}break;case PEEL_D1:if(ringobject){if(ring_peel_depth_programD1===null)ring_peel_depth_programD1=shaderProgram(shaders.peel_depth_fragmentD1,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD1,minormode)}else{if(peel_depth_programD1===null)peel_depth_programD1=shaderProgram(shaders.peel_depth_fragmentD1,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD1,minormode)}break;case PEEL_D2:if(ringobject){if(ring_peel_depth_programD2===null)ring_peel_depth_programD2=shaderProgram(shaders.peel_depth_fragmentD2,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD2,minormode)}else{if(peel_depth_programD2===null)peel_depth_programD2=shaderProgram(shaders.peel_depth_fragmentD2,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD2,minormode)}break;case PEEL_D3:if(ringobject){if(ring_peel_depth_programD3===null)ring_peel_depth_programD3=shaderProgram(shaders.peel_depth_fragmentD3,shaders.ring_peel_depth_vertex,gl);useProgram(ring_peel_depth_programD3,minormode)}else{if(peel_depth_programD3===null)peel_depth_programD3=shaderProgram(shaders.peel_depth_fragmentD3,shaders.peel_depth_vertex,gl);useProgram(peel_depth_programD3,minormode)}break;case PEEL_C1:if(ringobject){if(ring_peel_color_programC1===null)ring_peel_color_programC1=shaderProgram(shaders.peel_color_fragmentC1,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC1,minormode)}else{if(peel_color_programC1===null)peel_color_programC1=shaderProgram(shaders.peel_color_fragmentC1,shaders.render_vertex,gl);useProgram(peel_color_programC1,minormode)}break;case PEEL_C2:if(ringobject){if(ring_peel_color_programC2===null)ring_peel_color_programC2=shaderProgram(shaders.peel_color_fragmentC2,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC2,minormode)}else{if(peel_color_programC2===null)peel_color_programC2=shaderProgram(shaders.peel_color_fragmentC2,shaders.render_vertex,gl);useProgram(peel_color_programC2,minormode)}break;case PEEL_C3:if(ringobject){if(ring_peel_color_programC3===null)ring_peel_color_programC3=shaderProgram(shaders.peel_color_fragmentC3,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC3,minormode)}else{if(peel_color_programC3===null)peel_color_programC3=shaderProgram(shaders.peel_color_fragmentC3,shaders.render_vertex,gl);useProgram(peel_color_programC3,minormode)}break;case PEEL_C4:if(ringobject){if(ring_peel_color_programC4===null)ring_peel_color_programC4=shaderProgram(shaders.peel_color_fragmentC4,shaders.ring_render_vertex,gl);useProgram(ring_peel_color_programC4,minormode)}else{if(peel_color_programC4===null)peel_color_programC4=shaderProgram(shaders.peel_color_fragmentC4,shaders.render_vertex,gl);useProgram(peel_color_programC4,minormode)}break}gl.bindBuffer(gl.ARRAY_BUFFER,model.posBuffer);gl.vertexAttribPointer(program.attributes.pos,3,gl.FLOAT,false,0,0);if(mode!=PICK&&(mode==RENDER||minormode==PEEL_C0||minormode==PEEL_C1||minormode==PEEL_C2||minormode==PEEL_C3||minormode==PEEL_C4)){gl.bindBuffer(gl.ARRAY_BUFFER,model.normalBuffer);gl.vertexAttribPointer(program.attributes.normal,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.colorBuffer);gl.vertexAttribPointer(program.attributes.color,3,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.opacityBuffer);gl.vertexAttribPointer(program.attributes.opacity,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.shininessBuffer);gl.vertexAttribPointer(program.attributes.shininess,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.emissiveBuffer);gl.vertexAttribPointer(program.attributes.emissive,1,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.texposBuffer);gl.vertexAttribPointer(program.attributes.texpos,2,gl.FLOAT,false,0,0);gl.bindBuffer(gl.ARRAY_BUFFER,model.bumpaxisBuffer);gl.vertexAttribPointer(program.attributes.bumpaxis,3,gl.FLOAT,false,0,0)}else if(ringobject){gl.bindBuffer(gl.ARRAY_BUFFER,model.normalBuffer);gl.vertexAttribPointer(program.attributes.normal,3,gl.FLOAT,false,0,0)}gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,model.indexBuffer);if(mode==EXTENT)elements=gl.POINTS;for(var id in objs){var obj=objs[id];var data=obj.__data;if(minormode128){exponent=-(exponent-128);mantissa=-mantissa}var extent;if(mantissa==0&&exponent==0)extent=0;else extent=Math.exp(mantissa+exponent);return null}else if(mode==PICK){gl.readPixels(cvs.mouse.__pickx,cvs.mouse.__picky,1,1,gl.RGBA,gl.UNSIGNED_BYTE,pixels);var id=16777216*pixels[0]+65536*pixels[1]+256*pixels[2]+pixels[3];var obj=cvs.__visiblePrimitives[id];if(!obj)return null;else if(obj.__obj&&obj.__obj.pickable)return obj.__obj;else if(obj.constructor.name=="point"){if(!obj.__curve.pickable||!obj.pickable)return null;var pts=obj.__curve.__points;var L=pts.length;for(var i=0;i0;var t=msclock();var elapsed=0;if(doAverage)elapsed=t-lastStartRedraw;lastStartRedraw=t;cvs.trigger("redraw",{dt:elapsed});renderer.render(RENDER);t=msclock();elapsed=0;if(doAverage)elapsed=t-lastEndRedraw;lastEndRedraw=t;if(doAverage){renderMS=renderMS*.95+(t-lastStartRedraw)*.05;fps=fps*.95+1e3/elapsed*.05}else{renderMS=t-lastStartRedraw;fps=0}var total=fps*renderMS;$("#fps").text(fps.toFixed(1)+" renders/s * "+renderMS.toFixed(1)+" ms/render = "+total.toFixed(1)+" ms rendering/s");cvs.__last_center=cvs.__center;cvs.__last_axis=cvs.__axis;cvs.__last_range=cvs.__range;cvs.__last_up=cvs.__up;cvs.__last_width=cvs.__width;cvs.__last_height=cvs.__height;cvs.trigger("draw_complete",{dt:elapsed});if(cvs.__waitfor_image){cvs.__image=new Image;cvs.__image.src=canvasElement.toDataURL();cvs.__waitfor_image=false}}this.reset();trigger_render()}var desired_fps=60;var N=0;var enditers;async function rate(iters,callback){var dt,timer;if(N>0){N--;timer=msclock();if(timer>enditers)N=1;if(N>1){if(callback===undefined)return new Promise(resolve=>{resolve()});else callback()}else{N=0;var dt=enditers-Math.ceil(timer);if(dt<5)dt=0;if(callback===undefined)return new Promise(resolve=>{setTimeout(()=>{resolve()},dt)});else setTimeout(callback,dt)}}else{if(iters<=120){dt=Math.ceil(1e3/iters);if(callback===undefined)return new Promise(resolve=>{setTimeout(()=>{resolve()},dt)});else setTimeout(callback,dt)}else{timer=msclock();N=Math.ceil(iters/desired_fps);enditers=msclock()+Math.ceil(1e3/desired_fps);if(callback===undefined)return new Promise(resolve=>{resolve()});else callback()}}}var exports={WebGLRenderer:WebGLRenderer,rate:rate};Export(exports)})();(function(){"use strict";function log10(val){return Math.log(val)/Math.LN10}var eformat=false;var nformat=0;var nmax=0;function format_number(val,axis){if(axis.ticks.length==0){var delta=axis.tickSize;var amin=axis.min,amax=axis.max;var nticks=Math.floor((amax-amin)/delta+.5)+1;var vmax,test;for(var i=0;ivmax&&test!=0)vmax=test}nmax=Math.floor(log10(vmax))+1;var n=Math.floor(log10(delta))+1;if(n>3){eformat=true;nformat=n}else if(n>0){eformat=false;nformat=0}else if(n<0){eformat=true;nformat=n;if(nmax>=0){eformat=false;nformat=-n+1}}else{eformat=false;nformat=1}}if(val==0)return"0";if(eformat){var nf,nexp;var mantissa=val*pow(10,-nformat+1);nf=0;nexp=nformat-1;if(nmax>nformat){mantissa*=.1;nf+=1;nexp+=1}return mantissa.toFixed(nf)+"e"+nexp}else{return val.toFixed(nformat)}}var fontsize=16;var graphid=0;function graph(options){graph.activated=[];graph.__selected=null;graph.get_selected=function(){return graph.__selected};if(!(this instanceof graph))return new graph(options);options=options||{};if(options.x!==undefined)delete options.x;if(options.y!==undefined)delete options.y;this.fast=true;if(options.fast!==undefined){this.fast=options.fast;delete options.fast}this.scroll=false;if(options.scroll!==undefined){this.scroll=options.scroll;delete options.scroll}this.graph_options={};if(this.fast){this.graph_options={series:{shadowSize:0},crosshair:{mode:"xy",color:"rgba(0,0,0,1)"},xaxis:{min:null,max:null,tickFormatter:format_number},yaxis:{min:null,max:null,tickFormatter:format_number}}}this.__lock=false;this.__id="graph"+graphid;graphid++;this.container=$('
');this.__activated=false;this.__deleted=false;this.graph_series=[];this.__todo_list=[];graph.__selected=this;this.__width=640;this.__height=400;this.__plot=null;this.__xmin=this.__ymin=null;this.__xmax=this.__ymax=null;this.__xmin_actual=this.__ymin_actual=null;this.__xmax_actual=this.__ymax_actual=null;this.__title=this.__xtitle=this.__ytitle="";this.__made_title=false;this.__made_xtitle=false;this.__made_ytitle=false;if(options.width!==undefined){this.__width=options.width;delete options.width}if(options.height!==undefined){this.__height=options.height;delete options.height}this.__align="none";if(options.align!==undefined){this.__align=options.align;delete options.align}if(options.title!==undefined){this.__title=print_to_string(options.title);delete options.title}if(options.xtitle!==undefined){this.__xtitle=print_to_string(options.xtitle);delete options.xtitle}if(options.ytitle!==undefined){this.__ytitle=print_to_string(options.ytitle);delete options.ytitle}this.__foreground=color.black;this.__background=color.white;if(options.foreground!==undefined){var v=options.foreground;if(!(v instanceof vec))throw new Error("graph foreground must be a vector.");this.__foreground=v;delete options.foreground}if(options.background!==undefined){var v=options.background;if(!(v instanceof vec))throw new Error("graph background must be a vector.");var hsv=color.rgb_to_hsv(v);if(hsv.z<.5)hsv.z=.5;this.__background=color.hsv_to_rgb(hsv);delete options.background}var minmax=0;if(options.xmin!==undefined){this.__xmin=options.xmin;if(this.fast)this.graph_options.xaxis.min=options.xmin;minmax++;delete options.xmin}if(options.xmax!==undefined){this.__xmax=options.xmax;if(this.fast)this.graph_options.xaxis.max=options.xmax;minmax++;delete options.xmax}if(this.scroll){if(minmax!=2)throw new Error("For a scrolling graph, both xmin and xmax must be specified.");if(this.__xmax<=this.xmin)throw new Error("For a scrolling graph, xmax must be greater than xmin.")}if(!this.fast&&minmax==1){if(this.__xmin===null&&this.__xmax>0)this.__xmin=0;else if(this.__xmin<0&&this.__xmax===null)this.__xmax=0;else throw new Error("You must specify both xmin and xmax.")}minmax=0;if(options.ymin!==undefined){this.__ymin=options.ymin;if(this.fast)this.graph_options.yaxis.min=options.ymin;minmax++;delete options.ymin}if(options.ymax!==undefined){this.__ymax=options.ymax;if(this.fast)this.graph_options.yaxis.max=options.ymax;minmax++;delete options.ymax}if(!this.fast&&minmax==1){if(this.__ymin===null&&this.__ymax>0)this.__ymin=0;else if(this.__ymin<0&&this.__ymax===null)this.__ymax=0;else throw new Error("You must specify both ymin and ymax.")}this.__logx=this.__logy=false;if(options.logx!==undefined){this.__logx=this.graph_options.logx=options.logx;delete options.logx}if(options.logy!==undefined){this.__logy=this.graph_options.logy=options.logy;delete options.logy}if(this.fast){if(this.__logx){this.graph_options.xaxis.transform=function(v){return log10(v)};this.graph_options.xaxis.inverseTransform=function(v){return pow(10,v)}}if(this.__logy){this.graph_options.yaxis.transform=function(v){return log10(v)};this.graph_options.yaxis.inverseTransform=function(v){return pow(10,v)}}}var err="",count=0;for(var attr in options){count+=1;err+=attr+", "}if(err.length>0){if(count==1)throw new Error(err.slice(0,err.length-2)+" is not an attribute of a graph");else throw new Error("These are not attributes of a graph: "+err.slice(0,err.length-2))}function compute_offset(T){if(T==null||T=="")return 0;T=T.replace("
","\n");T=T.replace("
","\n");T=T.split("\n");if(T.length==1)return fontsize;return fontsize+1.3*fontsize*(T.length-1)}if(this.fast){var top=0,left=0,right=0,bottom=0;if(this.__align=="right")right=40;var d=10;if(this.__title!=="")top=d+compute_offset(this.__title);if(this.__ytitle!==""){left=compute_offset(this.__ytitle);if(left>fontsize)throw new Error("graph ytitle must not contain line breaks.");left+=d}if(this.__xtitle!==null&&this.__xtitle!==""){bottom=compute_offset(this.__xtitle);if(bottom>fontsize)throw new Error("graph xtitle must not contain line breaks.");bottom+=d}this.graph_options.grid={color:color.to_html(this.__foreground),backgroundColor:color.to_html(this.__background),offsets:{left:left,right:right,top:top,bottom:bottom}}}}property.declare(graph.prototype,{type:{get:function(){return this.__type},set:function(){throw new Error("Cannot change the type of a graph.")}},select:function(){graph.__selected=this},__todo:function(info,id){if(!this.__lock)Plotly.restyle(this.__id,info,id);else this.__todo_list.push([info,id])},__changed:false,remove:function(){if(this.__activated){if(!this.fast)Plotly.purge(this.__id);this.__deleted=true;this.container.remove()}},title:{get:function(){return this.__title},set:function(value){var m=value.match(/([^\n])*/);value=m[0];this.__title=value;if(this.__activated){if(this.fast){this.make_title(value)}else{Plotly.relayout(this.__id,{title:value})}}}},xtitle:{get:function(){return this.__xtitle},set:function(value){var m=value.match(/([^\n])*/);value=m[0];this.__xtitle=value;if(this.__activated){if(this.fast){this.make_xtitle(value)}else{Plotly.relayout(this.__id,{"xaxis.title":value})}}}},ytitle:{get:function(){return this.__ytitle},set:function(value){var m=value.match(/([^\n])*/);value=m[0];this.__ytitle=value;if(this.__activated){if(this.fast){this.make_ytitle(value)}else{Plotly.relayout(this.__id,{"yaxis.title":value})}}}},width:{get:function(){return this.__width},set:function(value){this.__width=value;if(this.fast){this.container.css("width",value);var plot=$.plot(this.container,[],this.graph_options);plot.resize();plot.setupGrid()}else{if(this.__activated)Plotly.relayout(this.__id,{width:value})}}},height:{get:function(){return this.__height},set:function(value){this.__height=value;if(this.fast){this.container.css("height",value);var plot=$.plot(this.container,[],this.graph_options);plot.resize();plot.setupGrid()}else{if(this.__activated)Plotly.relayout(this.__id,{height:value})}}},align:{get:function(){return this.__align},set:function(value){if(this.__activated)throw new Error("Cannot change align after the graph is activated.");if(value=="left"||value=="right"||value=="none"){this.__align=value}else throw new Error("align must be 'left', 'right', or 'none' (the default).")}},xmin:{get:function(){return this.__xmin},set:function(value){this.__xmin=value;if(this.fast)this.graph_options.xaxis.min=value;else if(this.__activated)Plotly.relayout(this.__id,{"xaxis.range":[value,this.__xmax]})}},xmax:{get:function(){return this.__xmax},set:function(value){this.__xmax=value;if(this.fast)this.graph_options.xaxis.max=value;else if(this.__activated)Plotly.relayout(this.__id,{"xaxis.range":[this.__xmin,value]})}},ymin:{get:function(){return this.__ymin},set:function(value){this.__ymin=value;if(this.fast)this.graph_options.yaxis.min=value;else if(this.__activated)Plotly.relayout(this.__id,{"yaxis.range":[value,this.__ymax]})}},ymax:{get:function(){return this.__ymax},set:function(value){this.__ymax=value;if(this.fast)this.graph_options.yaxis.max=value;else if(this.__activated)Plotly.relayout(this.__id,{"yaxis.range":[this.__ymin,value]})}},logx:{get:function(){return this.__logx},set:function(value){this.__logx=value;if(this.__logx==value)return;if(this.fast){if(value){this.graph_options.xaxis.transform=function(v){return log10(v)};this.graph_options.xaxis.inverseTransform=function(v){return pow(10,v)}}else{delete this.graph_options.xaxis.transform;delete this.graph_options.xaxis.inverseTransform}}else if(this.__activated){if(value)Plotly.relayout(this.__id,{"xaxis.type":"log"});else Plotly.relayout(this.__id,{"xaxis.type":null})}}},logy:{get:function(){return this.__logy},set:function(value){this.__logy=value;if(this.__logy==value)return;if(this.fast){if(value){this.graph_options.yaxis.transform=function(v){return log10(v)};this.graph_options.yaxis.inverseTransform=function(v){return pow(10,v)}}else{delete this.graph_options.yaxis.transform;delete this.graph_options.yaxis.inverseTransform}}else if(this.__activated){if(value)Plotly.relayout(this.__id,{"yaxis.type":"log"});else Plotly.relayout(this.__id,{"yaxis.type":null})}}},foreground:{get:function(){return this.__foreground},set:function(value){if(!(value instanceof vec))throw new Error("graph foreground color must be a vector.");this.__foreground=value;var col=color.to_html(value);if(this.fast)this.graph_options.grid.color=col;else if(this.__activated)Plotly.relayout(this.__id,{paper_bgcolor:col})}},background:{get:function(){return this.__background},set:function(value){if(!(value instanceof vec))throw new Error("graph background color must be a vector.");this.__background=value;var col=color.to_html(value);if(this.fast)this.graph_options.grid.backgroundColor=col;else if(this.__activated)Plotly.relayout(this.__id,{plot_bgcolor:col})}},make_title:function(title){var o=this.graph_options.grid.offsets;if(o.top===0)throw new Error("Cannot change a graph title if it does not already have a title.");var ctx=this.__plot.getCanvas().getContext("2d");ctx.fillStyle=color.to_html_rgba(vec(1,1,1),1);ctx.fillRect(0,0,this.__width,o.top);var font="Arial";if(title!==null&&title!==""){var y0=15;var x0=o.left+(this.__width-o.left-o.right)/2;var info=parse_html({ctx:ctx,text:title.toString(),x:x0,y:y0,align:"center",font:font,fontsize:fontsize,angle:0});display_2D(info)}},make_xtitle:function(title){var o=this.graph_options.grid.offsets;if(o.bottom===0)throw new Error("Cannot change a graph xtitle if it does not already have an xtitle.");var ctx=this.__plot.getCanvas().getContext("2d");ctx.fillStyle=color.to_html_rgba(vec(1,1,1),1);ctx.fillRect(o.left,this.__height-o.bottom,this.__width-o.right,this.__height);var font="Arial";if(title!==null&&title!==""){var x0=o.left+(this.__width-o.left-o.right)/2;var y0=this.__height+o.top-5;var info=parse_html({ctx:ctx,text:title.toString(),x:x0,y:y0,align:"center",font:font,fontsize:fontsize,angle:0});display_2D(info)}},make_ytitle:function(title){var o=this.graph_options.grid.offsets;if(o.left===0)throw new Error("Cannot change a graph ytitle if it does not already have a ytitle.");var ctx=this.__plot.getCanvas().getContext("2d");ctx.fillStyle=color.to_html_rgba(vec(1,1,1),1);ctx.fillRect(0,o.top,o.left,this.__height-o.top-o.bottom);var font="Arial";if(title!==null&&title!==""){var x0=15;var y0=o.top+(this.__height-o.bottom-15)/2;var info=parse_html({ctx:ctx,text:title.toString(),x:x0,y:y0,align:"center",font:font,fontsize:fontsize,angle:-Math.PI/2});display_2D(info)}},add_to_graph:function(obj){obj.__id=this.graph_series.length;obj.__activated=false;obj.__scrolldata=[];this.graph_series.push(obj)},__activate:function(dheight){if(this.__activated)return;if(!this.fast){this.container.addClass("glowscript-graph").css("width",this.__width).css("height",this.__height+dheight).appendTo(canvas.container);if(this.__align!="none")this.container.css("float",this.__align)}else{this.container.addClass("glowscript-graph").css("width",this.__width).css("height",this.__height+this.graph_options.grid.offsets.top).appendTo(canvas.container);this.container.css("float",this.__align)}graph.activated.push(this);this.__activated=true},__update:function(){if(!this.__changed||this.__deleted)return;if(this.__lock)return;var already_activated=this.__activated;function compute_offset(s){var m=s.match(/
/g);if(m===null)return 0;return m.length}var xmax=this.__xmax;if(!this.fast){for(var i=0;i0){layout.title=this.title;var n=compute_offset(this.title);t=65;if(n>0)t+=45*(n-1);dh+=45*(n+1);layout.height+=dh}var l=65;if(this.ytitle!==undefined&&this.ytitle.length>0){layout.yaxis.title=this.ytitle;var d=compute_offset(this.ytitle);if(d>0)throw new Error("A ytitle must not contain
.");l=80}var b=45;if(this.xtitle!==undefined&&this.xtitle.length>0){layout.xaxis.title=this.xtitle;var d=compute_offset(this.xtitle);if(d>0)throw new Error("An xtitle must not contain
.")}layout.margin={l:l,r:20,b:b,t:t,pad:4};this.__activate(dh);this.__activated=true}var indices=[];for(var i=0;iintegral of selected points = "+sum.toPrecision(6)+"",font:{color:"black",size:14},showarrow:false}]};Plotly.relayout(myPlot,layoutupdate);for(var t=0;txmax)xmax=xx}}xs.push(x);ys.push(y);s.__newdata=[]}if(this.scroll&&xmax>this.__xmax){var d=xmax-this.__xmax;this.xmin+=d;this.xmax+=d}if(!this.__lock){this.__lock=true;var self=this;Plotly.extendTraces(this.__id,{x:xs,y:ys},indices).then(function(){self.__lock=false})}}else{var info=[];for(var i=0;i0){var x=s.__data[L-1][0];if(x>xmax)xmax=x}info.push(s.options);if(s.__linemarker!==null&&s.__markers){s.__linemarker.data=s.__data;s.__linemarker.color=s.__linemarker.points.fillColor;s.__linemarker.points.radius=s.__radius;info.push(s.__linemarker)}if(s.__dot&&s.__realtype=="lines"&&s.__data.length>0){var dotdisplay={points:{show:true}};if(s.__dot_radius!==null)dotdisplay.points.radius=s.__dot_radius;else dotdisplay.points.radius=s.__width+1;if(s.__dot_color!==null)dotdisplay.color=color.to_html(s.__dot_color);else dotdisplay.color=color.to_html(s.__color);dotdisplay.points.fillColor=dotdisplay.color;dotdisplay.data=[s.options.data[s.options.data.length-1]];info.push(dotdisplay)}}if(this.scroll&&xmax>this.__xmax){var d=xmax-this.__xmax;this.xmin+=d;this.xmax+=d}if(info.length>0){this.__activate(0);this.__plot=$.plot(this.container,info,this.graph_options);this.__plot.draw()}if(!already_activated){if(this.__title!==null&&this.__title!=="")this.make_title(this.__title);if(this.__xtitle!==null&&this.__xtitle!=="")this.make_xtitle(this.__xtitle);if(this.__ytitle!==null&&this.__ytitle!=="")this.make_ytitle(this.__ytitle)}}this.__changed=false;if(!already_activated)new render_graph(this)}});var to_slow_type={lines:"lines",scatter:"markers",markers:"markers",bar:"bar"};var to_fast_type={lines:"lines",scatter:"points",markers:"points",bar:"bars"};function gobject(options){options=options||{};this.__data=[];this.__newdata=[];this.__color=vec(0,0,0);this.__marker_color=vec(0,0,0);this.__linemarker=null;this.__lineobj=null;this.__markerobj=null;this.__label=null;this.__save_label=null;this.__delta=1;this.__width=2;this.__radius=3;this.__horizontal=false;this.__dot=false;this.__xmin=null;this.__xmax=null;this.__ymin=null;this.__ymax=null;this.__label="";this.__legend=false;this.__markers=false;this.__interval=-1;this.__integrate_selected=false;var fast=true;if(options.fast!==undefined){fast=options.fast;delete options.fast}if(options.graph!==undefined){this.__graph=options.graph;delete options.graph}else if(options.gdisplay!==undefined){this.__graph=options.gdisplay;delete options.gdisplay}else{try{this.__graph=graph.get_selected()}catch(err){this.__graph=graph({fast:fast})}}this.__type="lines";if(options.type!==undefined){this.__type=options["type"];delete options["type"]}if(this.__graph.fast)this.__realtype=to_fast_type[this.__type];else this.__realtype=to_slow_type[this.__type];if(!this.__realtype)throw new Error("Unknown series type: "+this.__type);this.options={};var ftype=this.__realtype;var initialdata=[];if(options.data!==undefined){initialdata=options.data;delete options.data}if(options.color!==undefined){var c=options.color;if(!(c instanceof vec))throw new Error("graph color must be a vector.");this.__color=c;this.__marker_color=c;delete options.color}if(this.__graph.fast){if(ftype=="lines")this.options[ftype]={show:true,lineWidth:this.__width};else if(ftype=="points")this.options[ftype]={show:true,radius:this.__radius,fill:true,lineWidth:0};else if(ftype=="bars")this.options[ftype]={show:true,align:"center",horizontal:false,barWidth:1,lineWidth:1,fill:.5}}this.options.color=color.to_html(this.__color);if(this.__graph.fast){if(this.__realtype=="points")this.options[ftype].fillColor=this.options.color;else this.options.fillColor=this.options.color}if(options.marker_color!==undefined){var c=options.marker_color;if(!(c instanceof vec))throw new Error("graph color must be a vector.");this.__marker_color=c;delete options.marker_color}if(options.width!==undefined){this.__width=options.width;if(this.__graph.fast)this.options[ftype].lineWidth=options.width;delete options.width}if(options.markers!==undefined){if(this.__realtype!="lines")throw new Error("One can add markers only to graph curves.");if(options.markers===true){this.__markers=options.markers;var r=this.__width/2+2;if(options.radius!==undefined)r=options.radius;if(this.__graph.fast)this.__linemarker={points:{show:true,radius:r,lineWidth:0,fillColor:color.to_html(this.__marker_color),fill:true}};else this.__radius=r}delete options.markers}if(options.radius!==undefined){this.__radius=options.radius;if(this.__graph.fast)this.options[ftype].radius=options.radius;delete options.radius}if(options.size!==undefined){this.__radius=options.size/2;if(this.__graph.fast)this.options[ftype].radius=options.size/2;delete options.size}if(options.horizontal!==undefined){this.__horizontal=options.horizontal;if(this.__graph.fast)this.options[ftype].horizontal=options.horizontal;delete options.horizontal}if(options.delta!==undefined){this.__delta=options.delta;if(this.__graph.fast)this.options[ftype].barWidth=options.delta;delete options.delta}if(options.label!==undefined){this.__label=options.label;this.__save_label=options.label;if(this.__graph.fast)this.options.label=options.label;if(options.label.length>0)this.__legend=true;delete options.label}if(options.legend!==undefined){this.__legend=options.legend;if(this.__graph.fast&&!options.legend&&this.__label!==null)delete this.options.label;delete options.legend}if(options.__lineobj!==undefined){this.__lineobj=options.__lineobj;delete options.__lineobj}if(options.__markerobj!==undefined){this.__markerobj=options.__markerobj;delete options.__markerobj}if(options.dot!==undefined){if(this.__realtype!="lines")throw new Error('Can add a moving dot only to a gcurve or "lines" object');this.__dot=options.dot;this.__dot_radius=this.__width/2+4;this.__dot_color=this.__color;delete options.dot}if(options.dot_radius!==undefined){this.__dot_radius=options.dot_radius;delete options.dot_radius}this.__dot_color=this.__color;if(options.dot_color!==undefined){var v=options.dot_color;if(!(v instanceof vec))throw new Error("graph dot_color must be a vector.");this.__dot_color=v;delete options.dot_color}if(options.interval!==undefined){this.__interval=options.interval;this.__ninterval=options.interval;delete options.interval}if(options.integrate_selected!==undefined){this.__integrate_selected=options.integrate_selected;delete options.integrate_selected}this.__visible=true;if(options.visible!==undefined){this.__visible=options.visible;delete options.visible}var err="",count=0;for(var attr in options){count+=1;err+=attr+", "}if(err.length>0){if(count==1)throw new Error(err.slice(0,err.length-2)+" is not an attribute of a series");else throw new Error("These are not attributes of a graph object: "+err.slice(0,err.length-2))}this.__graph.add_to_graph(this);this.remove=function(){this.data=[]};var toType=function(obj){return{}.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()};var resolveargs=function(args){var v,ret;ret=[];if(toType(arguments[0][0])!="array"){for(var i=0;i0){this.__ninterval++;if(this.__ninterval>=this.__interval)this.__ninterval=0;else continue}if(this.__graph.fast)this.__data.push(data[i]);else this.__newdata.push(data[i]);if(!this.__graph.fast&&this.__realtype=="lines"&&this.__newdata.length>0){var d=this.__newdata[this.__newdata.length-1];if(this.__dot)this.__dotobject.data=[data[i]];if(this.__markers)this.__markerobject.__newdata.push(data[i])}}}else{var x,y,dx,dy,lastx,lasty,dt,xy,wx,wy;var g=this.__graph;var xmin=g.__xmin;var xmax=g.__xmax;var ymin=g.__ymin;var ymax=g.__ymax;var xmin_actual=g.__xmin_actual;var xmax_actual=g.__xmax_actual;var ymin_actual=g.__ymin_actual;var ymax_actual=g.__ymax_actual;dt=Math.floor(msclock()-this.__lasttime);this.__lasttime=msclock();lastx=lasty=null;if(this.__data.length>0){xy=this.__data[this.__data.length-1];lastx=xy[0];lasty=xy[1]}for(var i=0;i0){this.__ninterval++;if(this.__ninterval>=this.__interval)this.__ninterval=0;else continue}xy=data[i];x=xy[0];y=xy[1];checkval(x);checkval(y);if(g.scroll){g.__xmin_actual=xmin_actual=g.__xmin;g.__xmax_actual=xmax_actual=g.__xmax}else{if(xmin_actual===null||xxmax_actual)g.__xmax_actual=xmax_actual=x}if(ymin_actual===null||yymax_actual)g.__ymax_actual=ymax_actual=y;if(lastx!==null){wx=xmax_actual-xmin_actual;dx=wx===0?0:Math.abs(x-lastx)/wx;wy=ymax_actual-ymin_actual;dy=wy===0?0:Math.abs(y-lasty)/wy;if(dx<.01&&dy<.01)continue}if(this.__graph.fast)this.__data.push(xy);else this.__newdata.push(xy);lastx=x;lasty=y}if(this.__dot&&!this.__graph.fast&&this.__newdata.length>0){this.__dotobject.data=[this.__newdata[this.__newdata.length-1]]}}this.__graph.__changed=true;if(!this.__graph.__activated)this.__graph.__update()};if(initialdata.length>0)this.plot(initialdata)}property.declare(gobject.prototype,{graph:{get:function(){return this.__graph},set:function(value){throw new Error("Cannot change the choice of graph for an existing graphing object.")}},type:{get:function(){return this.__type},set:function(value){throw new Error("Cannot change the type of an existing graphing object.")}},data:{get:function(){return this.__data.concat(this.__newdata)},set:function(value){this.__data=[];this.options.data=[];this.__newdata=[];if(!this.__graph.fast){if(this.__realtype=="lines"){if(this.__dot){this.__dotobject.__data=[];this.__dotobject.__newdata=[];if(this.__graph.__activated)this.__graph.__todo({x:[[]],y:[[]]},this.__dotobject.__id)}if(this.__markers){this.__markerobject.__data=[];this.__markerobject.__newdata=[];if(this.__graph.__activated)this.__graph.__todo({x:[[]],y:[[]]},this.__markerobject.__id)}}if(this.__graph.__activated)this.__graph.__todo({x:[[]],y:[[]]},this.__id)}this.__graph.__changed=true;if(value.length>0)this.plot(value)}},markers:{get:function(){return this.__markers},set:function(value){if(this.__realtype!="lines")throw new Error("One can add markers only to graph curves.");if(this.__markers===value)return;this.__markers=value;var r=this.__radius+2;if(this.__activated){if(value){var up={};up["marker.color"]=color.to_html(this.__color);if(this.__graph.fast)this.options.points={show:true,radius:r};else this.__graph.__todo(up,this.__markerobject.__id)}else{var up={};up["marker.size"]=.1;if(this.__graph.fast)this.options.points={show:false,radius:r};else this.__graph.__todo(up,this.__markerobject.__id);this.__graph.__changed=true}}}},color:{get:function(){return this.__color},set:function(value){if(!(value instanceof vec))throw new Error("graphing color must be a vector.");if(this.__color.equals(value))return;this.__color=value;var col=color.to_html(value);if(this.__graph.fast)this.options.color=col;if(this.__activated){if(this.__graph.fast){if(this.__realtype=="points")this.options[ftype].fillColor=this.options.color;else this.options.fillColor=this.options.color;this.__graph.__changed=true}else{var up={};if(this.__realtype=="bar"){up["marker.color"]=color.to_html_rgba(value,.5);up["marker.line.color"]=color.to_html_rgba(value,1)}else if(this.__realtype=="markers"){up["marker.color"]=col}else if(this.__realtype=="lines"){up["line.color"]=col;up["marker.color"]=col}this.__graph.__todo(up,this.__id)}}}},marker_color:{get:function(){return this.__marker_color},set:function(value){if(!(value instanceof vec))throw new Error("graphing marker_color must be a vector.");if(this.__marker_color.equals(value))return;this.__marker_color=value;var col=color.to_html(value);if(this.__graph.fast)this.options.marker_color=col;if(this.__activated){if(this.__graph.fast){if(this.__realtype=="lines")this.__linemarker.points.fillColor=col;else this.options.color=col;this.__graph.__changed=true}else{if(this.__markerobject.__activated){var up={};up["marker.color"]=col;this.__graph.__todo(up,this.__markerobject.__id)}}}}},label:{get:function(){if(this.__label===undefined)return"";return this.__label},set:function(value){var m=value.match(/([^\n])*/);value=m[0];if(this.__label==value)return;this.__label=value;if(this.__graph.fast)this.options.label=value;if(value.length>0)this.__legend=true;if(this.__activated){if(this.__graph.fast){this.options.label=value;this.__graph.__changed=true}else this.__graph.__todo({name:value,showlegend:this.__legend},this.__id)}}},legend:{get:function(){return this.__legend},set:function(value){if(this.__legend==value)return;this.__legend=value;if(this.__graph.fast)this.options.legend=value;if(this.__activated){if(this.__graph.fast){if(this.options.label!==null){if(value)this.options.label=this.__save_label;else delete this.options.label}this.options.legend=value;this.__graph.__changed=true}else this.__graph.__todo({showlegend:value},this.__id)}}},delta:{get:function(){return this.__delta},set:function(value){if(this.__delta==value)return;this.__delta=value;if(this.__graph.fast)this.options[this.__realtype].barWidth=value;if(this.__activated){if(this.__graph.fast){this.__graph.__changed=true}else this.__graph.__todo({width:value},this.__id)}}},width:{get:function(){return this.__width},set:function(value){if(this.__width==value)return;this.__width=value;if(this.__graph.fast)this.options[this.__realtype].lineWidth=value;if(this.__activated){if(this.__graph.fast){this.__graph.__changed=true}else{var up={};if(this.__realtype=="bar"){return}else if(this.__realtype=="lines"){up["line.width"]=value}else if(this.__realtype=="markers"){return}this.__graph.__todo(up,this.__id)}}}},radius:{get:function(){return this.__radius},set:function(value){if(this.__radius==value)return;this.__radius=value;if(this.__graph.fast)this.options[this.__realtype].radius=value;if(this.__activated){if(this.__graph.fast){this.__graph.__changed=true}else{var up={};up["marker.size"]=2*value;if(this.__realtype=="lines"){if(!this.__markers)return;this.__graph.__todo(up,this.__markerobject.__id)}else if(this.__realtype=="markers"){this.__graph.__todo(up,this.__id)}}}}},size:{get:function(){return 2*this.__radius},set:function(value){if(2*this.__radius==value)return;this.__radius=value/2;if(this.__graph.fast)this.options[this.__realtype].radius=value/2;if(this.__activated){if(this.__graph.fast){this.__graph.__changed=true}else{var up={};if(this.__realtype=="bar"){return}else if(this.__realtype=="lines"){up["line.width"]=value;up["marker.size"]=value}else if(this.__realtype=="markers"){up["marker.size"]=value}this.__graph.__todo(up,this.__id)}}}},horizontal:{get:function(){return this.__horizontal},set:function(value){if(this.__horizontal==value)return;this.__horizontal=value;if(this.__graph.fast)this.options[this.__realtype].horizontal=value;if(this.__activated){if(this.__graph.fast){this.__graph.__changed=true}else{if(value)this.__graph.__todo({orientation:"h"},this.__id);else this.__graph.__todo({orientation:"v"},this.__id)}}}},orientation:{get:function(){var ret=this.__horizontal?"h":"v";return ret},set:function(value){var m=value.match(/([^\n])*/);value=m[0];this.__orientation=value;if(value=="v")this.__horizontal=false;else if(value=="h")this.__horizontal=true;else throw new Error("orientation must be either 'v' for vertical or 'h' for horizontal");if(this.__activated){if(this.__graph.fast)this.__graph.__changed=true;else this.__graph.__todo({orientation:value},this.__id)}}},dot:{get:function(){return this.__dot},set:function(value){if(this.__activated)throw new Error("Cannot change gcurve dot after the gcurve has been activated.");if(this.__dot==value)return;this.__dot=value}},dot_color:{get:function(){return this.__dot_color},set:function(value){if(!(value instanceof vec))throw new Error("graph dot_color must be a vector.");if(this.__dot_color.equals(value))return;this.__dot_color=value;var col=color.to_html(value);if(this.__graph.fast){this.options.dot_color=col;this.__graph.__changed=true}else if(this.__dotobject.__activated){var up={};up["marker.color"]=col;this.__graph.__todo(up,this.__dotobject.__id)}}},dot_radius:{get:function(){return this.__dot_radius},set:function(value){if(this.__dot_radius==value)return;this.__dot_radius=value;if(this.__graph.fast){this.options.dot_radius=value;this.__graph.__changed=true}else if(this.__dotobject.__activated){var up={};up["marker.size"]=2*value;this.__graph.__todo(up,this.__dotobject.__id)}}},visible:{get:function(){return this.__visible},set:function(value){if(this.__visible==value)return;this.__visible=value;if(this.__activated){if(!this.__graph.fast)this.__graph.__todo({visible:value},this.__id);this.__graph.__changed=true}}}});function render_graph(grf){function grender(){window.requestAnimationFrame(grender);grf.__update()}grender()}function series(options){var ret=new gobject(options);if(ret.dot){options={type:"scatter",color:ret.__dot_color,radius:ret.__dot_radius};ret.__dotobject=new gobject(options)}return ret}function gcurve(options){options=options||{};options.type="lines";if(options.pos!==undefined){options.data=options.pos;delete options.pos}if(options.size!==undefined){options.dot_radius=options.size/2;delete options.size}var ret=new gobject(options);if(!ret.__graph.fast){if(ret.dot)ret.__dotobject=gdots({color:ret.__dot_color,radius:ret.__dot_radius,__lineobj:ret});if(ret.markers)ret.__markerobject=gdots({color:ret.__marker_color,radius:ret.__radius,__markerobj:ret})}return ret}function gdots(options){options=options||{};options.type="scatter";if(options.pos!==undefined){options.data=options.pos;delete options.pos}return new gobject(options)}function gvbars(options){options=options||{};options.type="bar";options.horizontal=false;if(options.pos!==undefined){options.data=options.pos;delete options.pos}return new gobject(options)}function ghbars(options){options=options||{};options.type="bar";options.horizontal=true;if(options.pos!==undefined){options.data=options.pos;delete options.pos}return new gobject(options)}function ghistogram(options){throw new Error("ghistogram is not currently implemented in GlowScript.")}var exports={graph:graph,vp_graph:graph,gdisplay:graph,series:series,gcurve:gcurve,gdots:gdots,gvbars:gvbars,ghbars:ghbars,ghistogram:ghistogram};Export(exports)})();(function(){"use strict";var color={red:vec(1,0,0),green:vec(0,1,0),blue:vec(0,0,1),yellow:vec(1,1,0),orange:vec(1,.6,0),cyan:vec(0,1,1),magenta:vec(1,0,1),purple:vec(.4,.2,.6),white:vec(1,1,1),black:vec(0,0,0),gray:function(g){return vec(g,g,g)},hsv_to_rgb:function(hsv){var h=hsv.x;var s=hsv.y;var v=hsv.z;if(s==0){return vec(v,v,v)}var i=Math.floor(6*h);var f=6*h-i;var p=v*(1-s);var q=v*(1-s*f);var t=v*(1-s*(1-f));i=i%6;switch(i){case 0:return vec(v,t,p);case 1:return vec(q,v,p);case 2:return vec(p,v,t);case 3:return vec(p,q,v);case 4:return vec(t,p,v);case 5:return vec(v,p,q)}},rgb_to_hsv:function(rgb){var r=rgb.x;var g=rgb.y;var b=rgb.z;var maxc=Math.max(r,g,b);var minc=Math.min(r,g,b);var v=maxc;if(minc==maxc){return vec(0,0,v)}var s=(maxc-minc)/maxc;var rc=(maxc-r)/(maxc-minc);var gc=(maxc-g)/(maxc-minc);var bc=(maxc-b)/(maxc-minc);var h;if(r==maxc){h=bc-gc}else if(g==maxc){h=2+rc-bc}else{h=4+gc-rc}h=h/6;if(h<0)h++;return vec(h,s,v)},to_html:function(colvec){var r=Math.floor(255*colvec.x);var g=Math.floor(255*colvec.y);var b=Math.floor(255*colvec.z);return"rgb("+r+","+g+","+b+")"},to_html_rgba:function(colvec,opacity){var r=Math.floor(255*colvec.x);var g=Math.floor(255*colvec.y);var b=Math.floor(255*colvec.z);return"rgba("+r+","+g+","+b+","+opacity+")"}};var exports={color:color};Export(exports)})();(function(){"use strict";var npdefault=64;function shape_object(){}shape_object.prototype.roundc=function roundc(cps,args){var cp=[],i;for(i=0;i0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.rectangle=function rectangle(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=1;if(args.height===undefined)args.height=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var w2,h2,cp;if(args.height===null){args.height=args.width}if(args.thickness===0){cp=[];w2=args.width/2;h2=args.height/2;cp=[[w2,-h2],[w2,h2],[-w2,h2],[-w2,-h2],[w2,-h2]];cp=this.addpos(args.pos,cp);if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.rframe(args)}return cp};shape_object.prototype.cross=function cross(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=1;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=.2;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var wtp,w2,t2,cp;wtp=(args.width+args.thickness)/2;w2=args.width/2;t2=args.thickness/2;cp=[[w2,-t2],[w2,t2],[t2,t2],[t2,w2],[-t2,w2],[-t2,t2],[-w2,t2],[-w2,-t2],[-t2,-t2],[-t2,-w2],[t2,-w2],[t2,-t2],[w2,-t2]];cp=this.addpos(args.pos,cp);if(rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert});return cp};shape_object.prototype.trframe=function trframe(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=2;if(args.height===undefined)args.height=1;if(args.top===undefined)args.top=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var angle,db,outer,inner;if(args.top===null){args.top=width/2}if(args.thickness===null){args.thickness=min(args.height,args.top)*.2}else{args.thickness=min(args.height,args.top)*args.thickness*2}outer=this.trapezoid({pos:args.pos,width:args.width,height:args.height,top:args.top});angle=Math.atan((args.width-args.top)/2/args.height);db=args.thickness/Math.cos(angle);inner=this.trapezoid({pos:args.pos,width:args.width-db-args.thickness*Math.tan(angle),height:args.height-args.thickness,top:args.top-(db-args.thickness*Math.tan(angle))});outer=this.addpos(args.pos,outer);inner=this.addpos(args.pos,inner);if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}if(args.roundness>0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.trapezoid=function trapezoid(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.width===undefined)args.width=2;if(args.height===undefined)args.height=1;if(args.top===undefined)args.top=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var w2,h2,t2,cp;w2=args.width/2;h2=args.height/2;if(args.top===null){args.top=w2}t2=args.top/2;if(args.thickness===0){cp=[[w2,-h2],[t2,h2],[-t2,h2],[-w2,-h2],[w2,-h2]];cp=this.addpos(args.pos,cp);if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.trframe(args)}return cp};shape_object.prototype.circframe=function circframe(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.radius===undefined)args.radius=.5;if(args.iradius===undefined)args.iradius=null;if(args.np===undefined)args.np=npdefault;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.angle1===undefined)args.angle1=0;if(args.angle2===undefined)args.angle2=2*Math.PI;if(args.rotate===undefined)args.rotate=0;args.thickness=0;var outer,inner;if(args.iradius===null)args.iradius=args.radius*.8;outer=this.circle(args);if(args.angle1===0&&args.angle2==2*Math.PI){args.radius=args.iradius}else{var t=args.radius-args.iradius;var angle=(args.angle1+args.angle2)/2;var offset=t/Math.sin((args.angle2-args.angle1)/2);args.corner=[args.pos[0]+offset*Math.cos(angle),args.pos[1]+offset*Math.sin(angle)];var dangle=Math.asin(t/args.iradius);args.angle1=args.angle1+dangle;args.angle2=args.angle2-dangle;args.radius=args.iradius}inner=this.circle(args);if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}return[outer,inner]};shape_object.prototype.circle=function circle(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];var corner=args.pos;if(args.corner!==undefined)corner=args.corner;if(args.radius===undefined)args.radius=.5;if(args.np===undefined)args.np=npdefault;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.thickness===undefined)args.thickness=0;if(args.angle1===undefined)args.angle1=0;if(args.angle2===undefined)args.angle2=2*Math.PI;if(args.rotate===undefined)args.rotate=0;var seg,nseg,dc,ds,x0,y0,c2,s2,c,s,i,cp;cp=[];if(args.thickness>0){args.iradius=args.radius-args.radius*args.thickness;cp=this.circframe(args)}else{if(args.angle1!==0||args.angle2!==2*Math.PI){cp.push([corner[0],corner[1]])}seg=2*Math.PI/args.np;nseg=Math.floor(Math.abs((args.angle2-args.angle1)/seg+.5));seg=(args.angle2-args.angle1)/nseg;if(args.angle1!==0||args.angle2!==2*Math.PI){nseg+=1}c=args.radius*Math.cos(args.angle1);s=args.radius*Math.sin(args.angle1);dc=Math.cos(seg);ds=Math.sin(seg);x0=args.pos[0];y0=args.pos[1];cp.push([x0+c,y0+s]);for(i=0;i0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.ngon=function ngon(args){args=args||{};if(args.thickness===undefined)args.thickness=0;if(args.pos===undefined)args.pos=[0,0];if(args.length===undefined)args.length=1;if(args.rotate===undefined)args.rotate=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.np===undefined)args.np=3;var seg,x,y,angle,radius,i,cp;cp=[];if(args.np<3)throw Error("number of sides can not be less than 3");angle=2*Math.PI/args.np;radius=args.length/2/Math.sin(angle/2);if(args.thickness===0){seg=2*Math.PI/args.np;angle=0;for(i=0;i0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.nframe(args)}return cp};shape_object.prototype.triangle=function triangle(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=3;args.rotate=args.rotate-Math.PI/6;return this.ngon(args)};shape_object.prototype.pentagon=function pentagon(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=5;args.rotate=args.rotate+Math.PI/10;return this.ngon(args)};shape_object.prototype.hexagon=function hexagon(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=6;return this.ngon(args)};shape_object.prototype.octagon=function octagon(args){args=args||{};if(args.rotate===undefined)args.rotate=0;args.np=8;args.rotate=args.rotate+Math.PI/8;return this.ngon(args)};shape_object.prototype.sframe=function sframe(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.radius===undefined)args.radius=1;if(args.n===undefined)args.n=5;if(args.iradius===undefined)args.iradius=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var outer,inner,cp;if(args.iradius===null){args.iradius=.5*args.radius}if(args.thickness===null){args.thickness=.2*args.radius}else{args.thickness=args.thickness*2*args.iradius}outer=this.star({pos:args.pos,n:args.n,radius:args.radius,iradius:args.iradius});inner=this.star({pos:args.pos,n:args.n,radius:args.radius-args.thickness,iradius:(args.radius-args.thickness)*args.iradius/args.radius});if(args.rotate!==0){outer=this.rotatecp(outer,args.pos,args.rotate);inner=this.rotatecp(inner,args.pos,args.rotate)}if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1){outer=this.scale(outer,args.xscale,args.yscale);inner=this.scale(inner,args.xscale,args.yscale)}if(args.roundness>0){outer=this.roundc(outer,{roundness:args.roundness,invert:args.invert});inner=this.roundc(inner,{roundness:args.roundness,invert:args.invert})}return[outer,inner]};shape_object.prototype.star=function star(args){args=args||{};if(args.pos===undefined)args.pos=[0,0];if(args.radius===undefined)args.radius=1;if(args.n===undefined)args.n=5;if(args.iradius===undefined)args.iradius=null;if(args.rotate===undefined)args.rotate=0;if(args.thickness===undefined)args.thickness=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;var dtheta,theta,i,cp;if(args.iradius===null)args.iradius=args.radius*.5;if(args.thickness===0){cp=[];dtheta=Math.PI/args.n;theta=0;for(i=0;i<2*args.n+1;i++){if(i%2===0){cp.push([-args.radius*Math.sin(theta),args.radius*Math.cos(theta)])}else{cp.push([-args.iradius*Math.sin(theta),args.iradius*Math.cos(theta)])}theta+=dtheta}cp=this.addpos(args.pos,cp);cp[cp.length-1]=cp[0];if(args.rotate!==0)cp=this.rotatecp(cp,args.pos,args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert})}else{cp=this.sframe(args)}return cp};shape_object.prototype.points=function points(args){args=args||{};var path=false;if(args.pos===undefined)args.pos=[];if(args.rotate===undefined)args.rotate=0;if(args.roundness===undefined)args.roundness=0;if(args.invert===undefined)args.invert=false;if(args.scale===undefined)args.scale=1;if(args.xscale===undefined)args.xscale=1;if(args.yscale===undefined)args.yscale=1;if(args.path===undefined)path=args.path;var closed,cp;cp=args.pos;closed=cp[cp.length-1][0]===cp[0][0]&&cp[cp.length-1][1]===cp[0][1];if(!closed&&!path)cp.push(cp[0]);if(cp.length&&args.rotate!==0)cp=this.rotatecp(cp,cp[0],args.rotate);if(args.scale!==1)args.xscale=args.yscale=args.scale;if(args.xscale!==1||args.yscale!==1)cp=this.scale(cp,args.xscale,args.yscale);if(args.roundness>0)cp=this.roundc(cp,{roundness:args.roundness,invert:args.invert});return cp};shape_object.prototype.ToothOutline=function ToothOutline(args){args=args||{};if(args.n===undefined)args.n=30;if(args.res===undefined)args.res=1;if(args.phi===undefined)args.phi=20;if(args.radius===undefined)args.radius=50;if(args.addendum===undefined)args.addendum=.4;if(args.dedendum===undefined)args.dedendum=.5;if(args.fradius===undefined)args.fradius=.1;if(args.bevel===undefined)args.bevel=.05;var TOOTHGEO,R,DiametralPitch,ToothThickness,CircularPitch,U1,U2,ThetaA1,ThetaA2,ThetaA3;var A,pts,normals,i,Aw,r,u,xp,yp,auxth,m,rA,xc,yc,P0,Ra,th,N,P,V;TOOTHGEO={PitchRadius:args.radius,TeethN:args.n,PressureAng:args.phi,Addendum:args.addendum,Dedendum:args.dedendum,Fillet:args.fradius,Bevel:args.bevel,Resolution:args.res};R={Bottom:TOOTHGEO["PitchRadius"]-TOOTHGEO["Dedendum"]-TOOTHGEO["Fillet"],Ded:TOOTHGEO["PitchRadius"]-TOOTHGEO["Dedendum"],Base:TOOTHGEO["PitchRadius"]*cos(TOOTHGEO["PressureAng"]*Math.PI/180),Bevel:TOOTHGEO["PitchRadius"]+TOOTHGEO["Addendum"]-TOOTHGEO["Bevel"],Add:TOOTHGEO["PitchRadius"]+TOOTHGEO["Addendum"]};DiametralPitch=TOOTHGEO["TeethN"]/(2*TOOTHGEO["PitchRadius"]);ToothThickness=Math.PI/2/DiametralPitch;CircularPitch=Math.PI/DiametralPitch;U1=sqrt((1-Math.cos(TOOTHGEO["PressureAng"]*Math.PI/1800))/Math.cos(TOOTHGEO["PressureAng"]*Math.PI/180));U2=sqrt(R["Bevel"]*R["Bevel"]/(R["Ded"]*R["Ded"])-1);ThetaA1=Math.atan((sin(U1)-U1*Math.cos(U1))/(Math.cos(U1)+U1*Math.sin(U1)));ThetaA2=Math.atan((sin(U2)-U2*Math.cos(U2))/(Math.cos(U2)+U2*Math.sin(U2)));ThetaA3=ThetaA1+ToothThickness/(TOOTHGEO["PitchRadius"]*2);A={Theta0:CircularPitch/(TOOTHGEO["PitchRadius"]*2),Theta1:ThetaA3+TOOTHGEO["Fillet"]/R["Ded"],Theta2:ThetaA3,Theta3:ThetaA3-ThetaA2,Theta4:ThetaA3-ThetaA2-TOOTHGEO["Bevel"]/R["Add"]};N=TOOTHGEO["Resolution"];pts=[];normals=[];for(i=0;i<2*N;i++){th=(A["Theta1"]-A["Theta0"])*i/(2*N-1)+A["Theta0"];pts.push([R["Bottom"]*Math.cos(th),R["Bottom"]*Math.sin(th)]);normals.push([-Math.cos(th),-Math.sin(th)])}xc=R["Ded"]*Math.cos(A["Theta1"]);yc=R["Ded"]*Math.sin(A["Theta1"]);Aw=Math.PI/2+A["Theta2"]-A["Theta1"];for(i=0;iright)right=x;if(ytop)top=y}center=[(left+right)/2,(bottom+top)/2];dx=args.pos[0]-center[0];dy=args.pos[1]-center[1];gear2=[];for(i=0;i0;axis=up0.cross(args.up);p=[];for(i=0;i=16777216){R=Math.floor(N/16777216);N-=R*16777216}if(N>=65536){G=Math.floor(N/65536);N-=G*65536}if(N>=256){B=Math.floor(N/256);N-=B*256}return[R/255,G/255,B/255,N/255]}function RSdict_to_JSobjectliteral(args){return args}function makeTrail(obj,args){obj.__interval=-1;if(obj.constructor!=curve&&obj.constructor!=points&&args.make_trail!==undefined){obj.__make_trail=args.make_trail;delete args.make_trail;obj.__trail_type="curve";if(args.trail_type!==undefined){if(args.trail_type!="curve"&&args.trail_type!="points"&&args.trail_type!="spheres")throw new Error("trail_type = "+args.trail_type+" but must be 'curve' or 'points' (or 'spheres').");obj.__trail_type=args.trail_type;delete args.trail_type}if(args.interval!==undefined){obj.__interval=args.interval;delete args.interval}else if(obj.__trail_type!="curve"){obj.__interval=1}if(args.retain!==undefined){obj.__retain=args.retain;delete args.retain}else obj.__retain=-1;obj.__trail_color=color.white;if(obj.color!==undefined)obj.__trail_color=obj.color;if(args.trail_color!==undefined){obj.__trail_color=args.trail_color;delete args.trail_color}obj.__trail_radius=0;if(args.trail_radius!==undefined){obj.__trail_radius=args.trail_radius;delete args.trail_radius}else{if(obj.__trail_type=="points")obj.__trail_radius=.1*obj.__size.y}obj.__pps=0;if(args.pps!==undefined){if(obj.__interval>0){if(obj.__trail_type!="curve")throw new Error("pps cannot be used with a "+obj.__trail_type+"-type trail");else throw new Error("pps cannot be used with interval > 0")}obj.__pps=args.pps;delete args.pps}obj.__trail_object=attach_trail(obj,{type:obj.__trail_type,color:obj.__trail_color,radius:obj.__trail_radius,pps:obj.__pps,retain:obj.__retain});if(args.pos!==undefined&&obj.__make_trail)obj.__trail_object.__trail.push(args.pos);if(!obj.__make_trail)obj.__trail_object.stop();obj.__ninterval=0;obj._pos_set=args.pos!==undefined}}function init(obj,args){if(obj.constructor==text)return;if(window.__GSlang=="vpython"&&args.display!==undefined){args.canvas=args.display;delete args.display}if(args.canvas!==undefined){obj.canvas=args.canvas;delete args.canvas}else{obj.canvas=canvas.selected}if(obj.canvas){if(!(obj.constructor==distant_light||obj.constructor==local_light))obj.canvas.__activate();obj.__model=obj.__get_model()}if(args.__obj){obj.__obj=args.__obj;delete args.__obj}if(args.radius!==undefined){obj.radius=args.radius;delete args.radius}if(args.size_units!==undefined){obj.size_units=args.size_units;delete args.size_units}if(args.axis!==undefined){if(args.axis.mag2===0)obj.__oldaxis=vec(1,0,0);obj.axis=args.axis;delete args.axis}if(args.size!==undefined){obj.size=args.size;delete args.size}if(args.up!==undefined){if(args.up.mag2===0)obj.__oldup=vec(0,1,0);obj.up=args.up;delete args.up}if(args.color!==undefined){obj.color=args.color;delete args.color}if(args.make_trail!==undefined)makeTrail(obj,args);for(var id in args)obj[id]=args[id];if(args.visible===undefined&&obj.canvas!==null)obj.visible=true}function initObject(obj,constructor,args){if(!(obj instanceof constructor))return new constructor(args);args=args||{};obj.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};if(constructor==curve)obj.origin=obj.origin;if(constructor!=curve&&constructor!=points&&constructor!=text){obj.pos=obj.pos}if(constructor!=points&&constructor!=text){obj.axis=obj.axis;obj.up=obj.up;obj.size=obj.size;obj.color=obj.color}obj.__sizing=false;if(!(constructor==sphere||constructor==simple_sphere||constructor==ring||constructor==text||constructor==compound))obj.__sizing=true;if(args.opacity===undefined)obj.__opacity=1;obj.__opacity_change=true;init(obj,args)}var nextVisibleId=1;var textures={flower:":flower_texture.jpg",granite:":granite_texture.jpg",gravel:":gravel_texture.jpg",earth:":earth_texture.jpg",metal:":metal_texture.jpg",rock:":rock_texture.jpg",rough:":rough_texture.jpg",rug:":rug_texture.jpg",stones:":stones_texture.jpg",stucco:":stucco_texture.jpg",wood:":wood_texture.jpg",wood_old:":wood_old_texture.jpg"};var bumpmaps={gravel:":gravel_bumpmap.jpg",rock:":rock_bumpmap.jpg",stones:":stones_bumpmap.jpg",stucco:":stucco_bumpmap.jpg",wood_old:":wood_old_bumpmap.jpg"};function setup_texture(name,obj,isbump){if(name.slice(0,1)==":"){var jv=window.Jupyter_VPython;if(jv!==undefined){name=jv+name.slice(1)}else{if(navigator.onLine)name="https://s3.amazonaws.com/glowscript/textures/"+name.slice(1);else name="../lib/FilesInAWS/"+name.slice(1)}}obj.canvas.__renderer.initTexture(name,obj,isbump)}function Primitive(){}property.declare(Primitive.prototype,{__id:null,__hasPosAtCenter:false,__deleted:false,__zx_camera:null,__zy_camera:null,__xmin:null,__ymin:null,__zmin:null,__xmax:null,__ymax:null,__zmax:null,pos:new attributeVectorPos(null,0,0,0),size:new attributeVector(null,1,1,1),axis:new attributeVectorAxis(null,1,0,0),up:new attributeVectorUp(null,0,1,0),color:new attributeVector(null,1,1,1),opacity:{get:function(){return this.__opacity},set:function(value){if(value==this.__opacity)return;if(this.__opacity<1&&value==1||this.__opacity==1&&value<1){this.__opacity_change=true}this.__opacity=value;this.__change()}},x:{get:function(){throw new Error('"object.x" is not supported; perhaps you meant "object.pos.x"')},set:function(value){throw new Error('"object.x" is not supported; perhaps you meant "object.pos.x"')}},y:{get:function(){throw new Error('"object.y" is not supported; perhaps you meant "object.pos.y"')},set:function(value){throw new Error('"object.y" is not supported; perhaps you meant "object.pos.y"')}},z:{get:function(){throw new Error('"object.z" is not supported; perhaps you meant "object.pos.z"')},set:function(value){throw new Error('"object.z" is not supported; perhaps you meant "object.pos.z"')}},__opacity_change:false,__prev_opacity:null,shininess:{value:.6,onchanged:function(){this.__change()}},emissive:{value:false,onchanged:function(){this.__change()}},pickable:{value:true,onchanged:function(){this.__change()}},ready:{get:function(){return this.__tex.file===null||this.__tex.texture_ref.reference!==null&&this.__tex.bumpmap===null||this.__tex.bumpmap_ref.reference!==null}},make_trail:{get:function(){return this.__make_trail},set:function(value){if(this.__make_trail!==value){if(value){this.__trail_object.start();this.__trail_object.__trail.push(this.__pos)}else this.__trail_object.stop();this.__make_trail=value}}},retain:{get:function(){return this.__retain},set:function(value){this.__retain=value;if(this.__trail_object!==undefined)this.__trail_object.retain=value}},trail_type:{get:function(){if(this.__trail_type=="curve")return"curve";else if(this.__trail_type=="spheres")return"points";else return this.__trail_type},set:function(value){throw new Error('"trail_type" cannot be changed.')}},trail_color:{get:function(){return this.__color},set:function(value){this.__trail_color=value;if(this.__trail_object!==undefined)this.__trail_object.color=value}},trail_radius:{get:function(){return this.__radius},set:function(value){this.__trail_radius=value;if(this.__trail_object!==undefined)this.__trail_object.radius=value}},pps:{get:function(){return this.__pps},set:function(value){this.__pps=value;if(this.__trail_object!==undefined)this.__trail_object.pps=value}},clear_trail:function(){if(this.__trail_object!==undefined)this.__trail_object.clear()},__update_trail:function(v){if(!this.__trail_object.__run||!this.visible)return;if(this.__interval===-1)return;this.__ninterval++;var update=false;if(this.__ninterval>=this.__interval){this.__ninterval=0;update=true}else if(this.__ninterval==1&&this.__trail_object.__trail.__points.length===0)update=true;if(update){if(this.__retain==-1)this.__trail_object.__trail.push({pos:v,color:this.__trail_color,radius:this.__trail_radius});else this.__trail_object.__trail.push({pos:v,color:this.__trail_color,radius:this.__trail_radius,retain:this.__retain})}},texture:{get:function(){return{file:this.__tex.file,bumpmap:this.__tex.bumpmap,left:this.__tex.left,right:this.__tex.right,sides:this.__tex.sides,flipx:this.__tex.flipx,flipy:this.__tex.flipy,turn:this.__tex.turn}},set:function(args){this.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};if(args===null){}else if(typeof args==="string"){this.__tex.left=this.__tex.right=this.__tex.sides=true;setup_texture(args,this,false)}else{args=RSdict_to_JSobjectliteral(args);if(args.file!==undefined&&typeof args.file==="string"){setup_texture(args.file,this,false)}else throw new Error("You must specify a file name for a texture.");if(args.bumpmap!==undefined){if(args.bumpmap!==null){if(typeof args.bumpmap!=="string")throw new Error("You must specify a file name for a bumpmap.");setup_texture(args.bumpmap,this,true)}}if(args.flipx!==undefined)this.__tex.flipx=args.flipx;if(args.flipy!==undefined)this.__tex.flipy=args.flipy;if(args.turn!==undefined)this.__tex.turn=Math.round(args.turn);if(args.place!==undefined){if(typeof args.place==="string")args.place=[args.place];for(var i=0;i3)throw new Error("object.rotate takes 1 to 3 arguments");var args={};for(var i=0;i1e-6){obj.axis=obj.__axis.rotate({angle:angle,axis:rotaxis})}obj.up=obj.__up.rotate({angle:angle,axis:rotaxis});window.__adjustupaxis=true},getTransformedMesh:function(){var X=this.__axis.norm();var Y=this.__up.norm();var Z=X.cross(Y);var T=this.__pos;if(this instanceof ring){var m=Mesh.makeRing_compound(this.__size);var matrix=[X.x,X.y,X.z,0,Y.x,Y.y,Y.z,0,Z.x,Z.y,Z.z,0,T.x,T.y,T.z,1];return m.transformed(matrix)}else{X=X.multiply(this.__size.x);Y=Y.multiply(this.__size.y);Z=Z.multiply(this.__size.z);var matrix=[X.x,X.y,X.z,0,Y.x,Y.y,Y.z,0,Z.x,Z.y,Z.z,0,T.x,T.y,T.z,1];return this.__model.mesh.transformed(matrix)}}});function box(args){return initObject(this,box,args)}subclass(box,Primitive);box.prototype.__hasPosAtCenter=true;property.declare(box.prototype,{size:new attributeVectorSize(null,1,1,1),length:{get:function(){return this.__size.__x},set:function(value){if(value===0){if(this.__oldaxis===undefined)this.__oldaxis=vec(this.__axis.__x,this.__axis.__y,this.__axis.z);this.__axis.__x=0;this.__axis.__y=0;this.__axis.__z=0;this.__size.__x=0}else{if(this.__oldaxis!==undefined){this.__axis.__x=this.__oldaxis.x;this.__axis.__y=this.__oldaxis.y;this.__axis.__z=this.__oldaxis.z;this.__oldaxis=undefined}this.axis=this.__axis.norm().multiply(value)}this.__change()}},height:{get:function(){return this.__size.__y},set:function(value){this.__size.__y=value;this.__change()}},width:{get:function(){return this.__size.__z},set:function(value){this.__size.__z=value;this.__change()}},red:{get:function(){return this.__color.__x},set:function(value){this.__color.__x=value;this.__change()}},green:{get:function(){return this.__color.__y},set:function(value){this.__color.__y=value;this.__change()}},blue:{get:function(){return this.__color.__z},set:function(value){this.__color.__z=value;this.__change()}}});function pyramid(args){return initObject(this,pyramid,args)}subclass(pyramid,box);function cylinder(args){return initObject(this,cylinder,args)}subclass(cylinder,box);property.declare(cylinder.prototype,{size:new attributeVectorSize(null,1,2,2),radius:{get:function(){return this.__size.__y/2},set:function(value){this.__size.__y=this.__size.__z=2*value;this.__change()}}});function cone(args){return initObject(this,cone,args)}subclass(cone,cylinder);function sphere(args){return initObject(this,sphere,args)}subclass(sphere,Primitive);sphere.prototype.__hasPosAtCenter=true;property.declare(sphere.prototype,{axis:new attributeVectorAxis(null,1,0,0),size:new attributeVector(null,2,2,2),radius:{get:function(){return this.__size.__y/2},set:function(value){this.size=vec(2*value,2*value,2*value);this.__change()}}});function simple_sphere(args){return initObject(this,simple_sphere,args)}subclass(simple_sphere,sphere);property.declare(simple_sphere.prototype,{axis:new attributeVectorAxis(null,1,0,0),size:new attributeVector(null,2,2,2)});function ellipsoid(args){return initObject(this,ellipsoid,args)}subclass(ellipsoid,box);property.declare(ellipsoid.prototype,{radius:{get:function(){throw new Error("An ellipsoid does not have a radius attribute.")},set:function(value){throw new Error("An ellipsoid does not have a radius attribute.")}}});function arrow_update(obj){var pos=obj.__pos;var color=obj.__color;let axis=obj.__axis;var L=mag(axis);var A=axis.norm();var sw=obj.__shaftwidth||L*.1;var hw=obj.__headwidth||sw*2;var hl=obj.__headlength||sw*3;if(swL*.5){var scale=L*.5/hl;if(!obj.__shaftwidth)sw*=scale;if(!obj.__headwidth)hw*=scale;if(!obj.__headlength)hl*=scale}var components=obj.__components;if(!components){components=obj.__components=[box({canvas:obj.canvas,__obj:obj}),pyramid({canvas:obj.canvas,__obj:obj})]}var shaft=components[0];var tip=components[1];shaft.pos=pos.add(A.multiply(.5*(L-hl)));tip.pos=pos.add(A.multiply(L-hl));window.__adjustupaxis=false;shaft.axis=tip.axis=axis;shaft.up=tip.up=obj.__up;window.__adjustupaxis=true;shaft.size=vec(L-hl,sw,sw);tip.size=vec(hl,hw,hw);shaft.color=tip.color=obj.color;shaft.opacity=tip.opacity=obj.opacity;shaft.pickable=tip.pickable=obj.pickable;obj.size=vec(L,hw,hw);shaft.__update();tip.__update()}function arrow(args){if(!(this instanceof arrow))return new arrow(args);this.__shaftwidth=0;this.__headwidth=0;this.__headlength=0;return initObject(this,arrow,args)}subclass(arrow,box);property.declare(arrow.prototype,{__primitiveCount:2,axis_and_length:{get:function(){throw new Error("As of GlowScript 3.0, arrow does not have an axis_and_length attribute.")},set:function(value){throw new Error("As of GlowScript 3.0, arrow does not have an axis_and_length attribute.")}},shaftwidth:{get:function(){return this.__shaftwidth},set:function(value){this.__shaftwidth=value;this.__change()}},headwidth:{get:function(){return this.__headwidth},set:function(value){this.__headwidth=value;this.__change()}},headlength:{get:function(){return this.__headlength},set:function(value){this.__headlength=value;this.__change()}},__change:function(){if(this.__components){this.__components[0].__change();this.__components[1].__change()}},__update:function(){arrow_update(this)},__get_extent:function(ext){if(!this.__components)this.__update();Autoscale.find_extent(this.__components[0],ext);Autoscale.find_extent(this.__components[1],ext)}});function text(args){if(!(this instanceof text))return new text(args);args=args||{};if(args.canvas===null)return;if(args.text===undefined||args.text.length===0)throw new Error("A text object needs non-empty text.");if(args.length!==undefined&&args.__comp===undefined)throw new Error("The length cannot be specified when constructing 3D text.");if(args.size!==undefined)throw new Error("A text object does not have a size attribute.");this.pos=this.pos;this.axis=this.axis;this.up=this.up;this.color=this.color;this.__stage=0;if(args.__comp===undefined){args.text=print_to_string(args.text);var ret=text3D(args);this.__comp=ret[0];args=ret[1];if(args.make_trail!==undefined){this.__realtrail=args.make_trail;this.__stage=1;makeTrail(this.__comp,args);delete args.make_trail}this.__id=nextVisibleId;nextVisibleId++;for(var attr in args)this[attr]=args[attr];this.__pseudosize=vec(this.__comp.size);this.__height_fraction=this.__height/this.__comp.size.y;this.__descender_fraction=this.__descender/this.__comp.size.y;this.__offset=this.__comp.__pos;this.__offset.x/=args.__length;this.__offset.y/=args.__height;this.__offset.z/=args.__depth}else{this.__comp=args.__comp;delete args.__comp;var newargs=args.newargs;delete args.newargs;if(args.make_trail!==undefined&&newargs.make_trail===undefined){this.__realtrail=args.make_trail;delete args.make_trail;this.__stage=1;makeTrail(this.__comp,args)}else if(newargs.make_trail!==undefined){args.make_trail=this.__realtrail=newargs.make_trail;delete newargs.make_trail;this.__stage=1;makeTrail(this.__comp,args)}this.__id=nextVisibleId;nextVisibleId++;this.canvas=args.canvas;delete args.canvas;this.__offset=args.__offset;delete args.__offset;for(var attr in args)this["__"+attr]=args[attr];this.__pseudosize=vec(this.__comp.size);this.__height_fraction=this.__height/this.__comp.size.y;this.__descender_fraction=this.__descender/this.__comp.size.y}initObject(this,text,{});for(var attr in newargs)this[attr]=newargs[attr];if(this.__billboard){this.canvas.update_billboards=true;this.canvas.billboards.push(this)}this.__update()}subclass(text,Primitive);property.declare(text.prototype,{size:{get:function(){throw new Error("A text object does not have a size attribute.")},set:function(value){throw new Error("A text object does not have a size attribute.")}},visible:{get:function(){return this.__comp.visible},set:function(value){this.__comp.visible=value}},__update:function(){window.__adjustupaxis=false;this.__comp.axis=this.axis;this.__comp.up=this.up;window.__adjustupaxis=true;var yheight=this.__pseudosize.y;this.__comp.size=vec(this.length,yheight,Math.abs(this.depth));this.__comp.color=this.color;var dz=cross(this.__axis,this.__up).norm();this.__comp.pos=this.__pos.add(this.__axis.norm().multiply(this.__offset.x*this.length)).add(this.__up.norm().multiply(this.__offset.y*this.height)).add(dz.multiply(this.__offset.z*this.depth));if(this.__stage>0){if(this.__stage==1){this.__comp.make_trail=false;this.__stage=2}else if(this.__stage==2){this.__comp.make_trail=this.__realtrail;this.__stage=0}}},length:{get:function(){return this.__pseudosize.x},set:function(value){if(value===this.__pseudosize.x)return;this.__pseudosize.x=value;this.__change()}},height:{get:function(){return this.__height_fraction*this.__pseudosize.y},set:function(value){this.__pseudosize.y=value/this.__height_fraction;this.__change()}},depth:{get:function(){if(this.__depth>=0)return this.__pseudosize.z;else return-this.__pseudosize.z},set:function(value){var d=this.__depth;if(Math.abs(value)<.01*d){if(value<0)value=-.01*d;else value=.01*d}this.__depth=value;this.__size.z=Math.abs(value);this.__change()}},descender:{get:function(){return this.__descender_fraction*this.__pseudosize.y},set:function(value){throw new Error("descender is read-only")}},opacity:{get:function(){return this.__opacity},set:function(value){this.__comp.opacity=this.__opacity=value;this.__change()}},shininess:{get:function(){return this.__shininess},set:function(value){this.__shininess=this.__comp.shininess=value;this.__change()}},emissive:{get:function(){return this.__emissive},set:function(value){this.__comp.emissive=this.__emissive=value;this.__change()}},texture:{get:function(){throw new Error("Cannot currently apply a texture to a text object")},set:function(value){throw new Error("Cannot currently apply a texture to a text object")}},text:{get:function(){return this.__text},set:function(value){throw new Error("text is read-only")}},font:{get:function(){return this.__font},set:function(value){throw new Error("font is read-only")}},align:{get:function(){return this.__align},set:function(value){throw new Error("align is read-only")}},billboard:{get:function(){return this.__billboard},set:function(value){throw new Error("billboard is read-only")}},show_start_face:{get:function(){return this.__show_start_face},set:function(value){throw new Error("show_start_face is read-only")}},show_end_face:{get:function(){return this.__show_end_face},set:function(value){throw new Error("show_end_face is read-only")}},start_face_color:{get:function(){return this.__start_face_color},set:function(value){throw new Error("start_face_color is read-only")}},end_face_color:{get:function(){return this.__end_face_color},set:function(value){throw new Error("end_face_color is read-only")}},start:{get:function(){return this.upper_left.sub(this.up.norm().multiply(this.height))},set:function(value){throw new Error("start is read-only")}},end:{get:function(){return this.upper_right.sub(this.up.norm().multiply(this.height))},set:function(value){throw new Error("end is read-only")}},vertical_spacing:{get:function(){return 1.5*this.height},set:function(value){throw new Error("vertical_spacing is read-only")}},upper_left:{get:function(){var dx=0;if(this.__align=="right")dx=-this.length;else if(this.__align=="center")dx=-this.length/2;return this.pos.add(this.up.norm().multiply(this.height)).add(this.axis.norm().multiply(dx))},set:function(value){throw new Error("upper_left is read-only")}},upper_right:{get:function(){return this.upper_left.add(this.axis.norm().multiply(this.length))},set:function(value){throw new Error("upper_right is read-only")}},lower_left:{get:function(){return this.upper_left.add(this.up.norm().multiply(-this.height-this.descender-1.5*this.height*(this.__lines-1)))},set:function(value){throw new Error("lower_left is read-only")}},lower_right:{get:function(){return this.lower_left.add(this.axis.norm().multiply(this.length))},set:function(value){throw new Error("lower_right is read-only")}},lines:{get:function(){return this.__lines},set:function(value){throw new Error("lines is read-only")}}});function vertex(args){if(!(this instanceof vertex)){return new vertex(args)}args=args||{};if(args.canvas!==undefined){this.canvas=args.canvas}else if(args.display!==undefined){this.canvas=args.display}else{this.canvas=canvas.selected}for(var attr in args){if(attr=="canvas"||attr=="display")continue;this[attr]=args[attr]}if(this.opacity===undefined)this.opacity=1;if(this.__texpos.z!==0)throw new Error("In a vertex the z component of texpos must be zero.");if(this.canvas.vertex_id>=65536)throw new Error("Currently the number of vertices is limited to 65536.");var lengths={pos:3,normal:3,color:3,opacity:1,shininess:1,emissive:1,texpos:2,bumpaxis:3};this.__id=this.canvas.__vertices.available.pop();if(this.__id===undefined){this.__id=this.canvas.vertex_id;var c=this.canvas.__vertices;if(this.canvas.vertex_id%c.Nalloc===0){var temp;var L=this.canvas.vertex_id+c.Nalloc;for(var t in lengths){temp=new Float32Array(lengths[t]*L);temp.set(c[t],0);c[t]=temp}}this.canvas.vertex_id++}this.canvas.__vertices.object_info[this.__id]={};this.__change()}property.declare(vertex.prototype,{__id:null,__hasPosAtCenter:true,pos:new attributeVector(null,0,0,0),normal:new attributeVector(null,0,0,1),color:new attributeVector(null,1,1,1),opacity:{get:function(){return this.__opacity},set:function(value){if(value==this.__opacity)return;if(this.__opacity<1&&value==1||this.__opacity==1&&value<1){var users=this.canvas.__vertices.object_info[this.__id];for(var u in users){users[u].__change();users[u].__opacity_change=true}}this.__opacity=value;this.canvas.__vertex_changed[this.__id]=this}},texpos:new attributeVector(null,0,0,0),bumpaxis:new attributeVector(null,1,0,0),shininess:{value:.6,onchanged:function(){this.__change()}},emissive:{value:false,onchanged:function(){this.__change()}},__change:function(){if(this.__id){this.canvas.__vertex_changed[this.__id]=this;if(this.canvas.__autoscale){var users=this.canvas.__vertices.object_info[this.__id];for(var u in users)users[u].__change()}}},rotate:function(args){if(args.angle===undefined){throw new Error("vertex.rotate() requires angle:...")}var angle=args.angle;if(args.axis===undefined){throw new Error("vertex.rotate() requires axis:...")}var axis=args.axis.norm();var origin;if(args.origin===undefined){origin=vec(0,0,0)}else origin=args.origin;this.pos=origin.add(this.__pos.sub(origin).rotate({angle:angle,axis:axis}));this.__change()}});function tri_quad_error(object_type,attribute){throw new Error("A "+object_type+" has no "+attribute+" attribute.")}function triangle(args){if(!(this instanceof triangle))return new triangle(args);args=args||{};if(args.canvas!==undefined)throw new Error("A triangle does not have a canvas; its vertex objects do.");var vnames=["v0","v1","v2"];if(args.vs!==undefined){if(args.vs.length!=3)throw new Error("A triangle must specify three vertex objects.");for(var i=0;i<3;i++)args[vnames[i]]=args.vs[i];delete args.vs}this.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};args.canvas=args.v0.canvas;init(this,args);this.canvas=args.v0.canvas;for(var i=0;i<3;i++){if(this[vnames[i]].constructor!==vertex)throw new Error("In a triangle, "+vnames[i]+" must be a vertex object.");if(this[vnames[i]].canvas.__id!==this.canvas.__id)throw new Error("All triangle vertex objects must be in the same canvas.");this.canvas.__vertices.object_info[this[vnames[i]].__id][this.__id]=this}}subclass(triangle,box);property.declare(triangle.prototype,{v0:{get:function(){return this.__v0},set:function(value){if(!(value instanceof vertex))throw new Error("v0 must be a vertex object.");this.__v0=value;this.__change()}},v1:{get:function(){return this.__v1},set:function(value){if(!(value instanceof vertex))throw new Error("v1 must be a vertex object.");this.__v1=value;this.__change()}},v2:{get:function(){return this.__v2},set:function(value){if(!(value instanceof vertex))throw new Error("v2 must be a vertex object.");this.__v2=value;this.__change()}},vs:{get:function(){return[this.__v0,this.__v1,this.__v2]},set:function(value){if(toType(value)!="array"||value.length!=3)throw new Error("triangle.vs must be a list of 3 vertex objects.");for(var i=0;i<3;i++)if(!(value[i]instanceof vertex))throw new Error("triangle.vs must contain vertex objects.");this.__v0=value[0];this.__v1=value[1];this.__v2=value[2];this.__change()}},pos:{get:function(){tri_quad_error("triangle","pos")},set:function(value){tri_quad_error("triangle","pos")}},color:{get:function(){tri_quad_error("triangle","color")},set:function(value){tri_quad_error("triangle","color")}},size:{get:function(){tri_quad_error("triangle","size")},set:function(value){tri_quad_error("triangle","size")}},axis:{get:function(){tri_quad_error("triangle","axis")},set:function(value){tri_quad_error("triangle","axis")}},up:{get:function(){tri_quad_error("triangle","up")},set:function(value){tri_quad_error("triangle","up")}},opacity:{get:function(){tri_quad_error("triangle","opacity")},set:function(value){tri_quad_error("triangle","opacity")}},shininess:{get:function(){tri_quad_error("triangle","shininess")},set:function(value){tri_quad_error("triangle","shininess")}},emissive:{get:function(){tri_quad_error("triangle","emissive")},set:function(value){tri_quad_error("triangle","emissive")}},__prev_texture:null,__prev_bumpmap:null,__update:function(){this.__model.id_object[this.__id]=this},__get_extent:function(ext){var vnames=["__v0","__v1","__v2"];for(var i=0;i<3;i++)ext.point_extent(this,this[vnames[i]].pos)},rotate:function(args){throw new Error("A triangle has no rotate method; rotate the vertices instead.")}});function quad(args){if(!(this instanceof quad))return new quad(args);if(!(this instanceof quad))return new quad(args);args=args||{};if(args.canvas!==undefined)throw new Error("A quad does not have a canvas; its vertex objects do.");var vnames=["v0","v1","v2","v3"];if(args.vs!==undefined){if(args.vs.length!=4)throw new Error("A quad must specify four vertex objects.");for(var i=0;i<4;i++)args[vnames[i]]=args.vs[i];delete args.vs}this.__tex={file:null,bumpmap:null,texture_ref:{reference:null},bumpmap_ref:{reference:null},left:false,right:false,sides:false,flipx:false,flipy:false,turn:0,flags:0};args.canvas=args.v0.canvas;init(this,args);this.canvas=args.v0.canvas;for(var i=0;i<4;i++){if(this[vnames[i]].constructor!==vertex)throw new Error("In a quad, "+vnames[i]+" must be a vertex object.");if(this[vnames[i]].canvas.__id!==this.canvas.__id)throw new Error("All quad vertex objects must be in the same canvas.");this.canvas.__vertices.object_info[this[vnames[i]].__id][this.__id]=this}}subclass(quad,box);property.declare(quad.prototype,{v0:{get:function(){return this.__v0},set:function(value){if(!(value instanceof vertex))throw new Error("v0 must be a vertex object.");this.__v0=value;this.__change()}},v1:{get:function(){return this.__v1},set:function(value){if(!(value instanceof vertex))throw new Error("v1 must be a vertex object.");this.__v1=value;this.__change()}},v2:{get:function(){return this.__v2},set:function(value){if(!(value instanceof vertex))throw new Error("v2 must be a vertex object.");this.__v2=value;this.__change()}},v3:{get:function(){return this.__v3},set:function(value){if(!(value instanceof vertex))throw new Error("v3 must be a vertex object.");this.__v3=value;this.__change()}},vs:{get:function(){return[this.__v0,this.__v1,this.__v2,this.__v3]},set:function(value){if(toType(value)!="array"||value.length!=4)throw new Error("quad.vs must be a list of 4 vertex objects.");for(var i=0;i<4;i++)if(!(value[i]instanceof vertex))throw new Error("quad.vs must contain vertex objects.");this.__v0=value[0];this.__v1=value[1];this.__v2=value[2];this.__v3=value[3];this.__change()}},pos:{get:function(){tri_quad_error("quad","pos")},set:function(value){tri_quad_error("quad","pos")}},color:{get:function(){tri_quad_error("quad","color")},set:function(value){tri_quad_error("quad","color")}},size:{get:function(){tri_quad_error("quad","size")},set:function(value){tri_quad_error("quad","size")}},axis:{get:function(){tri_quad_error("quad","axis")},set:function(value){tri_quad_error("quad","axis")}},up:{get:function(){tri_quad_error("quad","up")},set:function(value){tri_quad_error("quad","up")}},opacity:{get:function(){tri_quad_error("quad","opacity")},set:function(value){tri_quad_error("quad","opacity")}},shininess:{get:function(){tri_quad_error("quad","shininess")},set:function(value){tri_quad_error("quad","shininess")}},__prev_texture:null,__prev_bumpmap:null,__update:function(){this.__model.id_object[this.__id]=this},__get_extent:function(ext){var vnames=["__v0","__v1","__v2","__v3"];for(var i=0;i<4;i++)ext.point_extent(this,this[vnames[i]].pos)},rotate:function(args){throw new Error("A quad has no rotate method; rotate the vertices instead.")}});var compound_id=0;function make_compound(objects,parameters){function update_extent(c,extent){if(extent.__xmin===null)return;for(var ext in extent){var value=extent[ext];if(ext.slice(-3)=="min"){if(c[ext]===null||valuec[ext])c[ext]=value}}}function compound_error(n){if(n>0)throw new Error("Compounding objects 0 through "+n+" in the list exceeds the vertex limit.");else throw new Error("The first object in the list exceeds the vertex limit")}var self=parameters.self;delete parameters.self;if(parameters.origin!==undefined){this.__origin=parameters.origin;delete parameters.origin}var mesh=new Mesh;var release=[];var temp;for(var i=0;i0)this.__push_and_append(pos,{})}}subclass(curve,Primitive);property.declare(curve.prototype,{origin:new attributeVectorPos(null,0,0,0),pos:{get:function(){throw new Error("Use methods to read curve or points pos attribute.")},set:function(value){throw new Error("Use methods to change curve or points pos attribute.")}},radius:{get:function(){return this.__radius},set:function(value){this.__radius=value;this.__change()}},retain:{get:function(){return this.__retain},set:function(value){this.__retain=value;this.__change()}},npoints:{get:function(){return this.__points.length},set:function(value){throw new Error("Cannot change curve or points npoints.")}},__no_autoscale:false,__get_extent:function(ext){if(this.__no_autoscale)return;var xmin=null,ymin=null,zmin=null,xmax=null,ymax=null,zmax=null;var length=this.__points.length;var pnt=this.__points;var org=this.__origin;var p;for(var i=0;ixmax)xmax=p.x+org.x;if(ymax===null||p.y+org.y>ymax)ymax=p.y+org.y;if(zmax===null||p.z+org.z>zmax)zmax=p.z+org.z}var center=vec((xmin+xmax)/2,(ymin+ymax)/2,(zmin+zmax)/2);var pseudosize=vec(xmax-xmin,ymax-ymin,zmax-zmin);var savepos=this.__pos,savesize=this.__size;this.__pos=center;this.__size=pseudosize;this.__hasPosAtCenter=true;ext.xmin=xmin;ext.xmax=xmax;ext.ymin=ymin;ext.ymax=ymax;ext.zmin=zmin;ext.zmax=zmax;Autoscale.find_extent(this,ext);this.__pos=savepos;this.__size=savesize},__setup:function(iargs){var pos=[];var specs={};var haspos=false;if(iargs instanceof vec){haspos=true;pos=[iargs]}else if(iargs.length>1){haspos=true;for(var i=0;i-1&&this.__points.length>=retain){var N=this.__points.length-retain;for(var d=0;d-1&&this.__points.length>=retain){var N=this.__points.length-retain;for(var d=0;d=0&&n0){this.__points[n-1].__nextsegment=p.__nextsegment;this.__points[n-1].__change()}if(n0)this.__push_and_append(pos,{});if(this.__pixels)this.canvas.__points_objects.push(this)}}subclass(points,curve);property.declare(points.prototype,{origin:{get:function(){throw new Error("The points object has no origin attribute.")},set:function(value){throw new Error("The points object has no origin attribute.")}},color:{get:function(){return this.__color},set:function(value){this.__color=value;if(!this.__pixels){for(var i=0;i=this.canvas.__height)var factor=2*this.canvas.__range/this.canvas.__height;else var factor=2*this.canvas.__range/this.canvas.__width;var viewMatrix=mat4.lookAt(camera.pos,camera.target,camera.up);var vnew=mat4.multiplyVec3(viewMatrix,vec3.create([this.pos.x,this.pos.y,this.pos.z]));if(vnew[2]>-camera.zNear||vnew[2]<-camera.zFar)return;var d=camera.distance;var k=-d/(vnew[2]*factor);posx=Math.round(k*vnew[0]+this.canvas.__width/2);posy=Math.round(-k*vnew[1]+this.canvas.__height/2)}var h=this.__height;var upperchar=.4*this.__height;var f=this.__font;if(this.__font=="sans")f="Arial";else if(this.__font=="serif")f="Georgia";ctx.textBaseline="middle";ctx.lineWidth=this.__linewidth;var default_color=vec(1,1,1);if(this.canvas.__background.equals(vec(1,1,1)))default_color=vec(0,0,0);ctx.strokeStyle=color.to_html(this.__linecolor||this.__color||default_color);var info=parse_html({ctx:ctx,text:print_to_string(this.__text),x:posx,y:posy,align:this.__align||"center",font:f,fontsize:h,color:this.__color||default_color});var nlines=info.lines.length;var width=info.maxwidth;var dh=1.3*this.__height;var height=this.__height+(nlines-1)*dh;var xbase;var ybase;var border=this.__border;if(xoffset||yoffset){if(Math.abs(yoffset)>Math.abs(xoffset)){if(yoffset>0){xbase=posx+xoffset-width/2;ybase=posy-yoffset-height-border+upperchar}else{xbase=posx+xoffset-width/2;ybase=posy-yoffset+border+upperchar}}else if(Math.abs(xoffset)>0){ybase=posy-yoffset-height/2+upperchar;if(xoffset>0){xbase=posx+xoffset+border}else if(xoffset<0){xbase=posx+xoffset-width-border}}}else{ybase=posy;switch(this.__align){case null:case"center":xbase=posx-width/2;break;case"right":xbase=posx-width;break;case"left":xbase=posx;break}}var bcolor;if(this.__background==null)bcolor=this.canvas.__background;else bcolor=this.__background;ctx.fillStyle=color.to_html_rgba(bcolor,this.__opacity);ctx.fillRect(xbase-border,ybase-upperchar-border,width+2*border,height+2*border);if((xoffset||yoffset)&&this.__line){ctx.beginPath();if(this.space>0){var v=vec(xoffset,-yoffset,0).norm().multiply(this.space);v=v.add(vec(posx,posy,0));ctx.moveTo(v.x,v.y)}else ctx.moveTo(posx,posy);ctx.lineTo(posx+xoffset,posy-yoffset);ctx.stroke()}if(this.__box){ctx.beginPath();ctx.moveTo(xbase-border,ybase-upperchar-border);ctx.lineTo(xbase+width+border,ybase-upperchar-border);ctx.lineTo(xbase+width+border,ybase-upperchar+height+border);ctx.lineTo(xbase-border,ybase-upperchar+height+border);ctx.closePath();ctx.stroke()}info.x=xbase;info.y=ybase;switch(this.__align){case null:case"center":info.x+=width/2;break;case"right":info.x+=width;break;case"left":info.x+=0;break}display_2D(info)},__change:function(){if(this.canvas!==undefined)this.canvas.__overlay_objects.__changed=true}});function attach_trail(objectOrFunction,options){if(!(this instanceof attach_trail))return new attach_trail(objectOrFunction,options);if(options===undefined)options={};this.__options={};this.__obj=objectOrFunction;if(options.canvas!==undefined)this.canvas=options.canvas;else this.canvas=canvas.selected;var radius=0;if(options.type===undefined){this.type="curve"}else{switch(options.type){case"curve":this.type=options.type;break;case"spheres":case"points":this.type="points";this.__options["size_units"]="world";break;default:throw new Error("attach_trail type must be 'curve' or 'points' (or 'spheres')")}}if(typeof objectOrFunction!=="function"&&typeof objectOrFunction!=="string"){this.canvas=objectOrFunction.canvas;this.__options["color"]=objectOrFunction.color;if(options.radius===undefined){if(this.type=="points")radius=.1*objectOrFunction.size.y}else radius=options.radius}else{if(options.radius!==undefined)radius=options.radius}this.__options["radius"]=this.__radius=radius;this.__options["canvas"]=this.canvas;if(options.color!==undefined){this.__options["color"]=options.color}else this.__options["color"]=vec(1,1,1);this.__options["retain"]=-1;if(options.retain!==undefined){this.__options["retain"]=options.retain}this.pps=0;if(options.pps!==undefined){this.pps=options.pps}this.__options["pickable"]=false;var send={};for(var a in this.__options)send[a]=this.__options[a];if(this.type=="curve")this.__trail=curve(send);else this.__trail=points(send);this.__trails=[this.__trail];this.canvas.trails.push(this);this.__last_pos=null;this.__last_time=null;this.__run=true;this.__elements=0}property.declare(attach_trail.prototype,{color:{get:function(){return this.__options.color},set:function(value){this.__options.color=value}},radius:{get:function(){return this.__options.radius},set:function(value){this.__options.radius=value}},pps:{get:function(){return this.__options.pps},set:function(value){this.__options.pps=value}},retain:{get:function(){return this.__options.retain},set:function(value){this.__options.retain=value}},start:function(){this.__run=true;var send={};for(var a in this.__options)send[a]=this.__options[a];if(this.type==="curve")this.__trail=curve(send);else this.__trail=points(send);this.__trails.push(this.__trail)},stop:function(){this.__run=false},clear:function(){this.__last_pos=null;this.__last_time=null;this.__elements=0;for(var i=0;i').css({width:"16px",height:"16px"}).appendTo(attrs.pos).click(function(){attrs.checked=!attrs.checked;$(attrs.jradio).prop("checked",attrs.checked);attrs.bind(cradio)});$(" "+attrs.text+"").appendTo(attrs.pos);var cradio={get disabled(){return attrs.disabled},set disabled(value){attrs.disabled=booleanize(value);$(attrs.jradio).attr("disabled",attrs.disabled);if(attrs.disabled)$("#"+attrs._id).css({color:rgb_to_css(vec(.7,.7,.7))});else $("#"+attrs._id).css({color:rgb_to_css(vec(0,0,0))})},get checked(){return attrs.checked},set checked(value){attrs.checked=value;$(attrs.jradio).prop("checked",value)},get text(){return attrs.text},set text(value){attrs.text=value;$("#"+attrs._id).html(" "+value)},remove:function(){$(attrs.jradio).remove();$("#"+attrs._id).remove()}};for(var a in args){cradio[a]=args[a]}cradio.checked=attrs.checked;return cradio}function checkbox(args){if(!(this instanceof checkbox))return new checkbox(args);var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,checked:false,text:"",disabled:false};if(args.bind!==undefined){attrs.bind=args.bind;delete args.bind}else throw new Error("A checkbox must have a bind attribute.");for(a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}attrs.disabled=booleanize(attrs.disabled);widgetid++;attrs._id=widgetid.toString();attrs.jcheckbox=$('').css({width:"16px",height:"16px"}).appendTo(attrs.pos).click(function(){attrs.checked=!attrs.checked;$(attrs.jcheckbox).prop("checked",attrs.checked);attrs.bind(ccheckbox)});$(" "+attrs.text+"").appendTo(attrs.pos);var ccheckbox={get disabled(){return attrs.disabled},set disabled(value){attrs.disabled=booleanize(value);$(attrs.jcheckbox).attr("disabled",attrs.disabled);if(attrs.disabled)$("#"+attrs._id).css({color:rgb_to_css(vec(.7,.7,.7))});else $("#"+attrs._id).css({color:rgb_to_css(vec(0,0,0))})},get checked(){return attrs.checked},set checked(value){attrs.checked=value;$(attrs.jcheckbox).prop("checked",value)},get text(){return attrs.text},set text(value){attrs.text=value;$("#"+attrs._id).html(" "+value)},remove:function(){$(attrs.jcheckbox).remove();$("#"+attrs._id).remove()}};for(var a in args){ccheckbox[a]=args[a]}ccheckbox.checked=attrs.checked;return ccheckbox}function wtext(args){if(!(this instanceof wtext))return new wtext(args);args=args||{};var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,text:""};for(var a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}widgetid++;attrs._id=widgetid.toString();$(""+print_to_string(attrs.text)+"").appendTo(attrs.pos);var cwtext={get text(){return attrs.text},set text(value){attrs.text=value;$("#"+attrs._id).html(print_to_string(value))},remove:function(){$("#"+attrs._id).remove()}};for(var a in args){cwtext[a]=args[a]}return cwtext}function input(arg){arg=arg||{};if(arg.prompt!==undefined&&arg.prompt!="")return prompt(arg.prompt);else if(toType(arg)=="string")return prompt(arg);else return prompt()}var mathfunctions=["e","E","abs","sqrt","sin","cos","tan","asin","acos","atan","atan2","exp","log","pow","pi","ceil","floor","round","random","factorial","combin","radians","degrees"];function winput(args){args=args||{};var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,text:undefined,prompt:"",width:100,height:20,type:"numeric",number:null,disabled:false};for(var a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}if(attrs.type!="numeric"&&attrs.type!="string")throw new Error('A winput type must be "numeric" or "string".');if(args.bind!==undefined)attrs.bind=args.bind;if(attrs.bind===undefined){while(true){if(attrs.prompt!==undefined&&attrs.prompt!=="")attrs.text=prompt(attrs.prompt,attrs.text);else attrs.text=prompt();if(attrs.text===null)return null;attrs.number=null;if(attrs.type=="numeric"){var ok=wparse();if(!ok)alert("Numeric input error");else return attrs.number}else return attrs.text}}function checksafe(s){var name="";for(var i=0;i0){if(mathfunctions.indexOf(name)<0)return false;name=""}}}if(name.length>0&&mathfunctions.indexOf(name)<0)return false;return true}function wparse(){attrs.number=null;var ok=true;if(attrs.type=="numeric"){if(checksafe(attrs.text)){try{attrs.number=Function('"use strict";return('+attrs.text+")")()}catch(err){attrs.number=null;ok=false}}}return ok}attrs.disabled=booleanize(attrs.disabled);widgetid++;attrs._id=widgetid.toString();if(attrs.prompt!="")attrs.__wprompt=wtext({text:attrs.prompt+" ",pos:attrs.pos});attrs.jwinput=$('').val(attrs.text).appendTo(attrs.pos).css({width:attrs.width.toString()+"px",height:attrs.height.toString()+"px","font-size":(attrs.height-5).toString()+"px","font-family":"sans-serif"}).keypress(function(k){if(k.keyCode==13){attrs.text=attrs.jwinput.val();var ok=wparse();if(!ok){alert("Numeric input error");return}attrs.bind(cwinput)}});var cwinput={get disabled(){return attrs.disabled},set disabled(value){attrs.disabled=booleanize(value);$(attrs.jwinput).attr("disabled",attrs.disabled);if(attrs.disabled)$("#"+attrs._id).css({color:rgb_to_css(vec(.7,.7,.7))});else $("#"+attrs._id).css({color:rgb_to_css(vec(0,0,0))})},get text(){return attrs.text},set text(value){attrs.text=value;$("#"+attrs._id).val(value)},get number(){return attrs.number},remove:function(){if(attrs.prompt!="")attrs.__wprompt.remove();$(attrs.jwinput).remove()}};for(var a in args){cwinput[a]=args[a]}return cwinput}function button(args){if(!(this instanceof button))return new button(args);var cvs=canvas.get_selected();var attrs={pos:cvs.caption_anchor,text:" ",color:vec(0,0,0),background:vec(1,1,1),disabled:false};if(args.bind!==undefined){attrs.bind=args.bind;delete args.bind}else throw new Error("A button must have a bind attribute.");for(a in attrs){if(args[a]!==undefined){attrs[a]=args[a];delete args[a]}}attrs.disabled=booleanize(attrs.disabled);attrs.jbutton=$("