We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Advanced tutorial chart
I have been unable to get the chart showing the gini coefficient to open up in  the advanced tutorial to open up. Everything else is working, the chart just does not appear. Please advise, 

Thank you.

Tom 

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mesa/visualization/ModularVisualization.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 """
3 ModularServer
4 =============
5 
6 A visualization server which renders a model via one or more elements.
7 
8 The concept for the modular visualization server as follows:
9 A visualization is composed of VisualizationElements, each of which defines how
10 to generate some visualization from a model instance and render it on the
11 client. VisualizationElements may be anything from a simple text display to
12 a multilayered HTML5 canvas.
13 
14 The actual server is launched with one or more VisualizationElements;
15 it runs the model object through each of them, generating data to be sent to
16 the client. The client page is also generated based on the JavaScript code
17 provided by each element.
18 
19 This file consists of the following classes:
20 
21 VisualizationElement: Parent class for all other visualization elements, with
22                       the minimal necessary options.
23 PageHandler: The handler for the visualization page, generated from a template
24              and built from the various visualization elements.
25 SocketHandler: Handles the websocket connection between the client page and
26                 the server.
27 ModularServer: The overall visualization application class which stores and
28                controls the model and visualization instance.
29 
30 
31 ModularServer should *not* need to be subclassed on a model-by-model basis; it
32 should be primarily a pass-through for VisualizationElement subclasses, which
33 define the actual visualization specifics.
34 
35 For example, suppose we have created two visualization elements for our model,
36 called canvasvis and graphvis; we would launch a server with:
37 
38     server = ModularServer(MyModel, [canvasvis, graphvis], name="My Model")
39     server.launch()
40 
41 The client keeps track of what step it is showing. Clicking the Step button in
42 the browser sends a message requesting the viz_state corresponding to the next
43 step position, which is then sent back to the client via the websocket.
44 
45 The websocket protocol is as follows:
46 Each message is a JSON object, with a "type" property which defines the rest of
47 the structure.
48 
49 Server -> Client:
50     Send over the model state to visualize.
51     Model state is a list, with each element corresponding to a div; each div
52     is expected to have a render function associated with it, which knows how
53     to render that particular data. The example below includes two elements:
54     the first is data for a CanvasGrid, the second for a raw text display.
55 
56     {
57     "type": "viz_state",
58     "data": [{0:[ {"Shape": "circle", "x": 0, "y": 0, "r": 0.5,
59                 "Color": "#AAAAAA", "Filled": "true", "Layer": 0,
60                 "text": 'A', "text_color": "white" }]},
61             "Shape Count: 1"]
62     }
63 
64     Informs the client that the model is over.
65     {"type": "end"}
66 
67 Client -> Server:
68     Reset the model.
69     TODO: Allow this to come with parameters
70     {
71     "type": "reset"
72     }
73 
74     Get a given state.
75     {
76     "type": "get_step",
77     "step:" index of the step to get.
78     }
79 
80 """
81 import os
82 
83 import tornado.ioloop
84 import tornado.web
85 import tornado.websocket
86 import tornado.escape
87 import tornado.gen
88 
89 import webbrowser
90 
91 # Suppress several pylint warnings for this file.
92 # Attributes being defined outside of init is a Tornado feature.
93 # pylint: disable=attribute-defined-outside-init
94 
95 
96 class VisualizationElement:
97     """
98     Defines an element of the visualization.
99 
100     Attributes:
101         package_includes: A list of external JavaScript files to include that
102                           are part of the Mesa packages.
103         local_includes: A list of JavaScript files that are local to the
104                         directory that the server is being run in.
105         js_code: A JavaScript code string to instantiate the element.
106 
107     Methods:
108         render: Takes a model object, and produces JSON data which can be sent
109                 to the client.
110 
111     """
112 
113     package_includes = []
114     local_includes = []
115     js_code = ''
116     render_args = {}
117 
118     def __init__(self):
119         pass
120 
121     def render(self, model):
122         """ Build visualization data from a model object.
123 
124         Args:
125             model: A model object
126 
127         Returns:
128             A JSON-ready object.
129 
130         """
131         return "<b>VisualizationElement goes here</b>."
132 
133 # =============================================================================
134 # Actual Tornado code starts here:
135 
136 
137 class PageHandler(tornado.web.RequestHandler):
138     """ Handler for the HTML template which holds the visualization. """
139 
140     def get(self):
141         elements = self.application.visualization_elements
142         for i, element in enumerate(elements):
143             element.index = i
144         self.render("modular_template.html", port=self.application.port,
145                     model_name=self.application.model_name,
146                     package_includes=self.application.package_includes,
147                     local_includes=self.application.local_includes,
148                     scripts=self.application.js_code)
149 
150 
151 class SocketHandler(tornado.websocket.WebSocketHandler):
152     """ Handler for websocket. """
153     def open(self):
154         if self.application.verbose:
155             print("Socket opened!")
156 
157     def check_origin(self, origin):
158         return True
159 
160     def on_message(self, message):
161         """ Receiving a message from the websocket, parse, and act accordingly.
162 
163         """
164         if self.application.verbose:
165             print(message)
166         msg = tornado.escape.json_decode(message)
167 
168         if msg["type"] == "get_step":
169             self.application.model.step()
170             self.write_message({"type": "viz_state",
171                     "data": self.application.render_model()})
172 
173         elif msg["type"] == "reset":
174             self.application.reset_model()
175             self.write_message({"type": "viz_state",
176                     "data": self.application.render_model()})
177 
178         else:
179             if self.application.verbose:
180                 print("Unexpected message!")
181 
182 
183 class ModularServer(tornado.web.Application):
184     """ Main visualization application. """
185     verbose = True
186 
187     model_name = "Mesa Model"
188     model_cls = None  # A model class
189     portrayal_method = None
190     port = 8521  # Default port to listen on
191     canvas_width = 500
192     canvas_height = 500
193     grid_height = 0
194     grid_width = 0
195 
196     max_steps = 100000
197 
198     model_args = ()
199     model_kwargs = {}
200 
201     # Handlers and other globals:
202     page_handler = (r'/', PageHandler)
203     socket_handler = (r'/ws', SocketHandler)
204     static_handler = (r'/static/(.*)', tornado.web.StaticFileHandler,
205                       {"path": os.path.dirname(__file__) + "/templates"})
206     local_handler = (r'/local/(.*)', tornado.web.StaticFileHandler,
207                      {"path": ''})
208 
209     handlers = [page_handler, socket_handler, static_handler, local_handler]
210 
211     settings = {"debug": True,
212                 "template_path": os.path.dirname(__file__) + "/templates"}
213 
214     def __init__(self, model_cls, visualization_elements, name="Mesa Model",
215                  *args, **kwargs):
216         """ Create a new visualization server with the given elements. """
217         # Prep visualization elements:
218         self.visualization_elements = visualization_elements
219         self.package_includes = set()
220         self.local_includes = set()
221         self.js_code = []
222         for element in self.visualization_elements:
223             for include_file in element.package_includes:
224                 self.package_includes.add(include_file)
225             for include_file in element.local_includes:
226                 self.local_includes.add(include_file)
227             self.js_code.append(element.js_code)
228 
229         # Initializing the model
230         self.model_name = name
231         self.model_cls = model_cls
232 
233         self.model_args = args
234         self.model_kwargs = kwargs
235         self.reset_model()
236 
237         # Initializing the application itself:
238         super().__init__(self.handlers, **self.settings)
239 
240     def reset_model(self):
241         """ Reinstantiate the model object, using the current parameters. """
242         self.model = self.model_cls(*self.model_args, **self.model_kwargs)
243 
244     def render_model(self):
245         """ Turn the current state of the model into a dictionary of
246         visualizations
247 
248         """
249         visualization_state = []
250         for element in self.visualization_elements:
251             element_state = element.render(self.model)
252             visualization_state.append(element_state)
253         return visualization_state
254 
255     def launch(self, port=None):
256         """ Run the app. """
257         if port is not None:
258             self.port = port
259         url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)
260         print('Interface starting at {url}'.format(url=url))
261         self.listen(self.port)
262         webbrowser.open(url)
263         tornado.ioloop.IOLoop.instance().start()
264
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mesa/visualization/ModularVisualization.py b/mesa/visualization/ModularVisualization.py
--- a/mesa/visualization/ModularVisualization.py
+++ b/mesa/visualization/ModularVisualization.py
@@ -80,6 +80,7 @@
 """
 import os
 
+import tornado.autoreload
 import tornado.ioloop
 import tornado.web
 import tornado.websocket
@@ -209,6 +210,7 @@
     handlers = [page_handler, socket_handler, static_handler, local_handler]
 
     settings = {"debug": True,
+                "autoreload": False,
                 "template_path": os.path.dirname(__file__) + "/templates"}
 
     def __init__(self, model_cls, visualization_elements, name="Mesa Model",
@@ -254,10 +256,13 @@
 
     def launch(self, port=None):
         """ Run the app. """
+        startLoop = not tornado.ioloop.IOLoop.initialized()
         if port is not None:
             self.port = port
         url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)
         print('Interface starting at {url}'.format(url=url))
         self.listen(self.port)
         webbrowser.open(url)
-        tornado.ioloop.IOLoop.instance().start()
+        tornado.autoreload.start()
+        if startLoop:
+            tornado.ioloop.IOLoop.instance().start()

{"golden_diff": "diff --git a/mesa/visualization/ModularVisualization.py b/mesa/visualization/ModularVisualization.py\n--- a/mesa/visualization/ModularVisualization.py\n+++ b/mesa/visualization/ModularVisualization.py\n@@ -80,6 +80,7 @@\n \"\"\"\n import os\n \n+import tornado.autoreload\n import tornado.ioloop\n import tornado.web\n import tornado.websocket\n@@ -209,6 +210,7 @@\n     handlers = [page_handler, socket_handler, static_handler, local_handler]\n \n     settings = {\"debug\": True,\n+                \"autoreload\": False,\n                 \"template_path\": os.path.dirname(__file__) + \"/templates\"}\n \n     def __init__(self, model_cls, visualization_elements, name=\"Mesa Model\",\n@@ -254,10 +256,13 @@\n \n     def launch(self, port=None):\n         \"\"\" Run the app. \"\"\"\n+        startLoop = not tornado.ioloop.IOLoop.initialized()\n         if port is not None:\n             self.port = port\n         url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)\n         print('Interface starting at {url}'.format(url=url))\n         self.listen(self.port)\n         webbrowser.open(url)\n-        tornado.ioloop.IOLoop.instance().start()\n+        tornado.autoreload.start()\n+        if startLoop:\n+            tornado.ioloop.IOLoop.instance().start()\n", "issue": "Advanced tutorial chart\nI have been unable to get the chart showing the gini coefficient to open up in  the advanced tutorial to open up. Everything else is working, the chart just does not appear. Please advise, \r\n\r\nThank you.\r\n\r\nTom \n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\nModularServer\n=============\n\nA visualization server which renders a model via one or more elements.\n\nThe concept for the modular visualization server as follows:\nA visualization is composed of VisualizationElements, each of which defines how\nto generate some visualization from a model instance and render it on the\nclient. VisualizationElements may be anything from a simple text display to\na multilayered HTML5 canvas.\n\nThe actual server is launched with one or more VisualizationElements;\nit runs the model object through each of them, generating data to be sent to\nthe client. The client page is also generated based on the JavaScript code\nprovided by each element.\n\nThis file consists of the following classes:\n\nVisualizationElement: Parent class for all other visualization elements, with\n                      the minimal necessary options.\nPageHandler: The handler for the visualization page, generated from a template\n             and built from the various visualization elements.\nSocketHandler: Handles the websocket connection between the client page and\n                the server.\nModularServer: The overall visualization application class which stores and\n               controls the model and visualization instance.\n\n\nModularServer should *not* need to be subclassed on a model-by-model basis; it\nshould be primarily a pass-through for VisualizationElement subclasses, which\ndefine the actual visualization specifics.\n\nFor example, suppose we have created two visualization elements for our model,\ncalled canvasvis and graphvis; we would launch a server with:\n\n    server = ModularServer(MyModel, [canvasvis, graphvis], name=\"My Model\")\n    server.launch()\n\nThe client keeps track of what step it is showing. Clicking the Step button in\nthe browser sends a message requesting the viz_state corresponding to the next\nstep position, which is then sent back to the client via the websocket.\n\nThe websocket protocol is as follows:\nEach message is a JSON object, with a \"type\" property which defines the rest of\nthe structure.\n\nServer -> Client:\n    Send over the model state to visualize.\n    Model state is a list, with each element corresponding to a div; each div\n    is expected to have a render function associated with it, which knows how\n    to render that particular data. The example below includes two elements:\n    the first is data for a CanvasGrid, the second for a raw text display.\n\n    {\n    \"type\": \"viz_state\",\n    \"data\": [{0:[ {\"Shape\": \"circle\", \"x\": 0, \"y\": 0, \"r\": 0.5,\n                \"Color\": \"#AAAAAA\", \"Filled\": \"true\", \"Layer\": 0,\n                \"text\": 'A', \"text_color\": \"white\" }]},\n            \"Shape Count: 1\"]\n    }\n\n    Informs the client that the model is over.\n    {\"type\": \"end\"}\n\nClient -> Server:\n    Reset the model.\n    TODO: Allow this to come with parameters\n    {\n    \"type\": \"reset\"\n    }\n\n    Get a given state.\n    {\n    \"type\": \"get_step\",\n    \"step:\" index of the step to get.\n    }\n\n\"\"\"\nimport os\n\nimport tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nimport tornado.escape\nimport tornado.gen\n\nimport webbrowser\n\n# Suppress several pylint warnings for this file.\n# Attributes being defined outside of init is a Tornado feature.\n# pylint: disable=attribute-defined-outside-init\n\n\nclass VisualizationElement:\n    \"\"\"\n    Defines an element of the visualization.\n\n    Attributes:\n        package_includes: A list of external JavaScript files to include that\n                          are part of the Mesa packages.\n        local_includes: A list of JavaScript files that are local to the\n                        directory that the server is being run in.\n        js_code: A JavaScript code string to instantiate the element.\n\n    Methods:\n        render: Takes a model object, and produces JSON data which can be sent\n                to the client.\n\n    \"\"\"\n\n    package_includes = []\n    local_includes = []\n    js_code = ''\n    render_args = {}\n\n    def __init__(self):\n        pass\n\n    def render(self, model):\n        \"\"\" Build visualization data from a model object.\n\n        Args:\n            model: A model object\n\n        Returns:\n            A JSON-ready object.\n\n        \"\"\"\n        return \"<b>VisualizationElement goes here</b>.\"\n\n# =============================================================================\n# Actual Tornado code starts here:\n\n\nclass PageHandler(tornado.web.RequestHandler):\n    \"\"\" Handler for the HTML template which holds the visualization. \"\"\"\n\n    def get(self):\n        elements = self.application.visualization_elements\n        for i, element in enumerate(elements):\n            element.index = i\n        self.render(\"modular_template.html\", port=self.application.port,\n                    model_name=self.application.model_name,\n                    package_includes=self.application.package_includes,\n                    local_includes=self.application.local_includes,\n                    scripts=self.application.js_code)\n\n\nclass SocketHandler(tornado.websocket.WebSocketHandler):\n    \"\"\" Handler for websocket. \"\"\"\n    def open(self):\n        if self.application.verbose:\n            print(\"Socket opened!\")\n\n    def check_origin(self, origin):\n        return True\n\n    def on_message(self, message):\n        \"\"\" Receiving a message from the websocket, parse, and act accordingly.\n\n        \"\"\"\n        if self.application.verbose:\n            print(message)\n        msg = tornado.escape.json_decode(message)\n\n        if msg[\"type\"] == \"get_step\":\n            self.application.model.step()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        elif msg[\"type\"] == \"reset\":\n            self.application.reset_model()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        else:\n            if self.application.verbose:\n                print(\"Unexpected message!\")\n\n\nclass ModularServer(tornado.web.Application):\n    \"\"\" Main visualization application. \"\"\"\n    verbose = True\n\n    model_name = \"Mesa Model\"\n    model_cls = None  # A model class\n    portrayal_method = None\n    port = 8521  # Default port to listen on\n    canvas_width = 500\n    canvas_height = 500\n    grid_height = 0\n    grid_width = 0\n\n    max_steps = 100000\n\n    model_args = ()\n    model_kwargs = {}\n\n    # Handlers and other globals:\n    page_handler = (r'/', PageHandler)\n    socket_handler = (r'/ws', SocketHandler)\n    static_handler = (r'/static/(.*)', tornado.web.StaticFileHandler,\n                      {\"path\": os.path.dirname(__file__) + \"/templates\"})\n    local_handler = (r'/local/(.*)', tornado.web.StaticFileHandler,\n                     {\"path\": ''})\n\n    handlers = [page_handler, socket_handler, static_handler, local_handler]\n\n    settings = {\"debug\": True,\n                \"template_path\": os.path.dirname(__file__) + \"/templates\"}\n\n    def __init__(self, model_cls, visualization_elements, name=\"Mesa Model\",\n                 *args, **kwargs):\n        \"\"\" Create a new visualization server with the given elements. \"\"\"\n        # Prep visualization elements:\n        self.visualization_elements = visualization_elements\n        self.package_includes = set()\n        self.local_includes = set()\n        self.js_code = []\n        for element in self.visualization_elements:\n            for include_file in element.package_includes:\n                self.package_includes.add(include_file)\n            for include_file in element.local_includes:\n                self.local_includes.add(include_file)\n            self.js_code.append(element.js_code)\n\n        # Initializing the model\n        self.model_name = name\n        self.model_cls = model_cls\n\n        self.model_args = args\n        self.model_kwargs = kwargs\n        self.reset_model()\n\n        # Initializing the application itself:\n        super().__init__(self.handlers, **self.settings)\n\n    def reset_model(self):\n        \"\"\" Reinstantiate the model object, using the current parameters. \"\"\"\n        self.model = self.model_cls(*self.model_args, **self.model_kwargs)\n\n    def render_model(self):\n        \"\"\" Turn the current state of the model into a dictionary of\n        visualizations\n\n        \"\"\"\n        visualization_state = []\n        for element in self.visualization_elements:\n            element_state = element.render(self.model)\n            visualization_state.append(element_state)\n        return visualization_state\n\n    def launch(self, port=None):\n        \"\"\" Run the app. \"\"\"\n        if port is not None:\n            self.port = port\n        url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)\n        print('Interface starting at {url}'.format(url=url))\n        self.listen(self.port)\n        webbrowser.open(url)\n        tornado.ioloop.IOLoop.instance().start()\n", "path": "mesa/visualization/ModularVisualization.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\"\"\"\nModularServer\n=============\n\nA visualization server which renders a model via one or more elements.\n\nThe concept for the modular visualization server as follows:\nA visualization is composed of VisualizationElements, each of which defines how\nto generate some visualization from a model instance and render it on the\nclient. VisualizationElements may be anything from a simple text display to\na multilayered HTML5 canvas.\n\nThe actual server is launched with one or more VisualizationElements;\nit runs the model object through each of them, generating data to be sent to\nthe client. The client page is also generated based on the JavaScript code\nprovided by each element.\n\nThis file consists of the following classes:\n\nVisualizationElement: Parent class for all other visualization elements, with\n                      the minimal necessary options.\nPageHandler: The handler for the visualization page, generated from a template\n             and built from the various visualization elements.\nSocketHandler: Handles the websocket connection between the client page and\n                the server.\nModularServer: The overall visualization application class which stores and\n               controls the model and visualization instance.\n\n\nModularServer should *not* need to be subclassed on a model-by-model basis; it\nshould be primarily a pass-through for VisualizationElement subclasses, which\ndefine the actual visualization specifics.\n\nFor example, suppose we have created two visualization elements for our model,\ncalled canvasvis and graphvis; we would launch a server with:\n\n    server = ModularServer(MyModel, [canvasvis, graphvis], name=\"My Model\")\n    server.launch()\n\nThe client keeps track of what step it is showing. Clicking the Step button in\nthe browser sends a message requesting the viz_state corresponding to the next\nstep position, which is then sent back to the client via the websocket.\n\nThe websocket protocol is as follows:\nEach message is a JSON object, with a \"type\" property which defines the rest of\nthe structure.\n\nServer -> Client:\n    Send over the model state to visualize.\n    Model state is a list, with each element corresponding to a div; each div\n    is expected to have a render function associated with it, which knows how\n    to render that particular data. The example below includes two elements:\n    the first is data for a CanvasGrid, the second for a raw text display.\n\n    {\n    \"type\": \"viz_state\",\n    \"data\": [{0:[ {\"Shape\": \"circle\", \"x\": 0, \"y\": 0, \"r\": 0.5,\n                \"Color\": \"#AAAAAA\", \"Filled\": \"true\", \"Layer\": 0,\n                \"text\": 'A', \"text_color\": \"white\" }]},\n            \"Shape Count: 1\"]\n    }\n\n    Informs the client that the model is over.\n    {\"type\": \"end\"}\n\nClient -> Server:\n    Reset the model.\n    TODO: Allow this to come with parameters\n    {\n    \"type\": \"reset\"\n    }\n\n    Get a given state.\n    {\n    \"type\": \"get_step\",\n    \"step:\" index of the step to get.\n    }\n\n\"\"\"\nimport os\n\nimport tornado.autoreload\nimport tornado.ioloop\nimport tornado.web\nimport tornado.websocket\nimport tornado.escape\nimport tornado.gen\n\nimport webbrowser\n\n# Suppress several pylint warnings for this file.\n# Attributes being defined outside of init is a Tornado feature.\n# pylint: disable=attribute-defined-outside-init\n\n\nclass VisualizationElement:\n    \"\"\"\n    Defines an element of the visualization.\n\n    Attributes:\n        package_includes: A list of external JavaScript files to include that\n                          are part of the Mesa packages.\n        local_includes: A list of JavaScript files that are local to the\n                        directory that the server is being run in.\n        js_code: A JavaScript code string to instantiate the element.\n\n    Methods:\n        render: Takes a model object, and produces JSON data which can be sent\n                to the client.\n\n    \"\"\"\n\n    package_includes = []\n    local_includes = []\n    js_code = ''\n    render_args = {}\n\n    def __init__(self):\n        pass\n\n    def render(self, model):\n        \"\"\" Build visualization data from a model object.\n\n        Args:\n            model: A model object\n\n        Returns:\n            A JSON-ready object.\n\n        \"\"\"\n        return \"<b>VisualizationElement goes here</b>.\"\n\n# =============================================================================\n# Actual Tornado code starts here:\n\n\nclass PageHandler(tornado.web.RequestHandler):\n    \"\"\" Handler for the HTML template which holds the visualization. \"\"\"\n\n    def get(self):\n        elements = self.application.visualization_elements\n        for i, element in enumerate(elements):\n            element.index = i\n        self.render(\"modular_template.html\", port=self.application.port,\n                    model_name=self.application.model_name,\n                    package_includes=self.application.package_includes,\n                    local_includes=self.application.local_includes,\n                    scripts=self.application.js_code)\n\n\nclass SocketHandler(tornado.websocket.WebSocketHandler):\n    \"\"\" Handler for websocket. \"\"\"\n    def open(self):\n        if self.application.verbose:\n            print(\"Socket opened!\")\n\n    def check_origin(self, origin):\n        return True\n\n    def on_message(self, message):\n        \"\"\" Receiving a message from the websocket, parse, and act accordingly.\n\n        \"\"\"\n        if self.application.verbose:\n            print(message)\n        msg = tornado.escape.json_decode(message)\n\n        if msg[\"type\"] == \"get_step\":\n            self.application.model.step()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        elif msg[\"type\"] == \"reset\":\n            self.application.reset_model()\n            self.write_message({\"type\": \"viz_state\",\n                    \"data\": self.application.render_model()})\n\n        else:\n            if self.application.verbose:\n                print(\"Unexpected message!\")\n\n\nclass ModularServer(tornado.web.Application):\n    \"\"\" Main visualization application. \"\"\"\n    verbose = True\n\n    model_name = \"Mesa Model\"\n    model_cls = None  # A model class\n    portrayal_method = None\n    port = 8521  # Default port to listen on\n    canvas_width = 500\n    canvas_height = 500\n    grid_height = 0\n    grid_width = 0\n\n    max_steps = 100000\n\n    model_args = ()\n    model_kwargs = {}\n\n    # Handlers and other globals:\n    page_handler = (r'/', PageHandler)\n    socket_handler = (r'/ws', SocketHandler)\n    static_handler = (r'/static/(.*)', tornado.web.StaticFileHandler,\n                      {\"path\": os.path.dirname(__file__) + \"/templates\"})\n    local_handler = (r'/local/(.*)', tornado.web.StaticFileHandler,\n                     {\"path\": ''})\n\n    handlers = [page_handler, socket_handler, static_handler, local_handler]\n\n    settings = {\"debug\": True,\n                \"autoreload\": False,\n                \"template_path\": os.path.dirname(__file__) + \"/templates\"}\n\n    def __init__(self, model_cls, visualization_elements, name=\"Mesa Model\",\n                 *args, **kwargs):\n        \"\"\" Create a new visualization server with the given elements. \"\"\"\n        # Prep visualization elements:\n        self.visualization_elements = visualization_elements\n        self.package_includes = set()\n        self.local_includes = set()\n        self.js_code = []\n        for element in self.visualization_elements:\n            for include_file in element.package_includes:\n                self.package_includes.add(include_file)\n            for include_file in element.local_includes:\n                self.local_includes.add(include_file)\n            self.js_code.append(element.js_code)\n\n        # Initializing the model\n        self.model_name = name\n        self.model_cls = model_cls\n\n        self.model_args = args\n        self.model_kwargs = kwargs\n        self.reset_model()\n\n        # Initializing the application itself:\n        super().__init__(self.handlers, **self.settings)\n\n    def reset_model(self):\n        \"\"\" Reinstantiate the model object, using the current parameters. \"\"\"\n        self.model = self.model_cls(*self.model_args, **self.model_kwargs)\n\n    def render_model(self):\n        \"\"\" Turn the current state of the model into a dictionary of\n        visualizations\n\n        \"\"\"\n        visualization_state = []\n        for element in self.visualization_elements:\n            element_state = element.render(self.model)\n            visualization_state.append(element_state)\n        return visualization_state\n\n    def launch(self, port=None):\n        \"\"\" Run the app. \"\"\"\n        startLoop = not tornado.ioloop.IOLoop.initialized()\n        if port is not None:\n            self.port = port\n        url = 'http://127.0.0.1:{PORT}'.format(PORT=self.port)\n        print('Interface starting at {url}'.format(url=url))\n        self.listen(self.port)\n        webbrowser.open(url)\n        tornado.autoreload.start()\n        if startLoop:\n            tornado.ioloop.IOLoop.instance().start()\n", "path": "mesa/visualization/ModularVisualization.py"}]}