We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
On rerun, faded elements are becoming opaque one by one. Instead they become opaque all at once.
Steps to repro:
1. Run `examples/reference.py`
2. When done, rerun it.

**Expected:** on rerun, all elements fade out and then become opaque one by one even before the run is done.
**Actual:** on rerun, all elements fade out and only become opaque when the entire run is done.

I believe this bug was introduced with the Sidebar code.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `lib/streamlit/hello.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 # Copyright 2018-2019 Streamlit Inc.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #    http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 
16 """A "Hello World" app."""
17 
18 from __future__ import division, unicode_literals
19 
20 import streamlit as st
21 from streamlit.logger import get_logger
22 import inspect
23 from collections import OrderedDict
24 import urllib
25 import textwrap
26 
27 LOGGER = get_logger(__name__)
28 
29 
30 def intro():
31     st.sidebar.success("Select a demo above.")
32 
33     st.markdown("""
34         Streamlit is an open-source app framework built specifically for
35         Machine Learning and Data Science projects.
36 
37         **👈 Select a demo from the dropdown on the left** to see some examples
38         of what Streamlit can do!
39 
40         ### Want to learn more?
41 
42         - Check out [streamlit.io](https://streamlit.io)
43         - Jump into our [documentation](https://streamlit.io/docs)
44         - Ask a question in our [community
45           forums](https://discuss.streamlit.io)
46 
47         ### See more complex demos
48 
49         - Use a neural net to [analyze the Udacity Self-driving Car Image
50           Dataset] (https://github.com/streamlit/demo-self-driving)
51         - Explore a [New York City rideshare dataset]
52           (https://github.com/streamlit/demo-uber-nyc-pickups)
53     """)
54 
55 
56 # Turn off black formatting for this function to present the user with more
57 # compact code.
58 # IMPORTANT: This docstring is shown to the user as an intro to the demo.
59 # fmt: off
60 def mapping_demo():
61     """
62     This demo shows how to use
63     [`st.deck_gl_chart`](https://streamlit.io/docs/api.html#streamlit.deck_gl_chart)
64     to display geospatial data.
65     """
66     import pandas as pd
67     import os
68 
69     @st.cache
70     def from_data_file(filename):
71         GITHUB_DATA = "https://raw.githubusercontent.com/streamlit/streamlit/develop/examples/"
72         return pd.read_json(os.path.join(GITHUB_DATA, "data", filename))
73 
74     try:
75         ALL_LAYERS = {
76             "Bike Rentals": {
77                 "type": "HexagonLayer",
78                 "data": from_data_file("bike_rental_stats.json"),
79                 "radius": 200,
80                 "elevationScale": 4,
81                 "elevationRange": [0, 1000],
82                 "pickable": True,
83                 "extruded": True,
84             },
85             "Bart Stop Exits": {
86                 "type": "ScatterplotLayer",
87                 "data": from_data_file("bart_stop_stats.json"),
88                 "radiusScale": 0.05,
89                 "getRadius": "exits",
90             },
91             "Bart Stop Names": {
92                 "type": "TextLayer",
93                 "data": from_data_file("bart_stop_stats.json"),
94                 "getText": "name",
95                 "getColor": [0, 0, 0, 200],
96                 "getSize": 15,
97             },
98             "Outbound Flow": {
99                 "type": "ArcLayer",
100                 "data": from_data_file("bart_path_stats.json"),
101                 "pickable": True,
102                 "autoHighlight": True,
103                 "getStrokeWidth": 10,
104                 "widthScale": 0.0001,
105                 "getWidth": "outbound",
106                 "widthMinPixels": 3,
107                 "widthMaxPixels": 30,
108             }
109         }
110     except urllib.error.URLError:
111         st.error("Connection Error. This demo requires internet access")
112         return
113 
114     st.sidebar.markdown('### Map Layers')
115     selected_layers = [layer for layer_name, layer in ALL_LAYERS.items()
116         if st.sidebar.checkbox(layer_name, True)]
117     if selected_layers:
118         viewport={"latitude": 37.76, "longitude": -122.4, "zoom": 11, "pitch": 50}
119         st.deck_gl_chart(viewport=viewport, layers=selected_layers)
120     else:
121         st.error("Please choose at least one layer above.")
122 # fmt: on
123 
124 # Turn off black formatting for this function to present the user with more
125 # compact code.
126 # IMPORTANT: This docstring is shown to the user as an intro to the demo.
127 # fmt: off
128 def fractal_demo():
129     """
130     This app shows how you can use Streamlit to build cool animations.
131     It displays an animated fractal based on the the Julia Set. Use the slider
132     to tune different parameters.
133     """
134     import numpy as np
135 
136     # Interactive Streamlit elements, like these sliders, return their value.
137     # This gives you an extremely simple interaction model.
138     iterations = st.sidebar.slider("Level of detail", 2, 20, 10, 1)
139     separation = st.sidebar.slider("Separation", 0.7, 2.0, 0.7885)
140 
141     # Non-interactive elements return a placeholder to their location
142     # in the app. Here we're storing progress_bar to update it later.
143     progress_bar = st.sidebar.progress(0)
144 
145     # These two elements will be filled in later, so we create a placeholder
146     # for them using st.empty()
147     frame_text = st.sidebar.empty()
148     image = st.empty()
149 
150     m, n, s = 960, 640, 400
151     x = np.linspace(-m / s, m / s, num=m).reshape((1, m))
152     y = np.linspace(-n / s, n / s, num=n).reshape((n, 1))
153 
154     for frame_num, a in enumerate(np.linspace(0.0, 4 * np.pi, 100)):
155         # Here were setting value for these two elements.
156         progress_bar.progress(frame_num)
157         frame_text.text("Frame %i/100" % (frame_num + 1))
158 
159         # Performing some fractal wizardry.
160         c = separation * np.exp(1j * a)
161         Z = np.tile(x, (n, 1)) + 1j * np.tile(y, (1, m))
162         C = np.full((n, m), c)
163         M = np.full((n, m), True, dtype=bool)
164         N = np.zeros((n, m))
165 
166         for i in range(iterations):
167             Z[M] = Z[M] * Z[M] + C[M]
168             M[np.abs(Z) > 2] = False
169             N[M] = i
170 
171         # Update the image placeholder by calling the image() function on it.
172         image.image(1.0 - (N / N.max()), use_column_width=True)
173 
174     # We clear elements by calling empty on them.
175     progress_bar.empty()
176     frame_text.empty()
177 
178     # Streamlit widgets automatically run the script from top to bottom. Since
179     # this button is not connected to any other logic, it just causes a plain
180     # rerun.
181     st.button("Re-run")
182 
183 
184 # fmt: on
185 
186 # Turn off black formatting for this function to present the user with more
187 # compact code.
188 # IMPORTANT: This docstring is shown to the user as an intro to the demo.
189 # fmt: off
190 def plotting_demo():
191     """
192     This demo illustrates a combination of plotting and animation with
193     Streamlit. We're generating a bunch of random numbers in a loop for around
194     5 seconds. Enjoy!
195     """
196     import time
197     import numpy as np
198 
199     progress_bar = st.sidebar.progress(0)
200     status_text = st.sidebar.empty()
201     last_rows = np.random.randn(1, 1)
202     chart = st.line_chart(last_rows)
203 
204     for i in range(1, 101):
205         new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)
206         status_text.text("%i%% Complete" % i)
207         chart.add_rows(new_rows)
208         progress_bar.progress(i)
209         last_rows = new_rows
210         time.sleep(0.05)
211 
212     progress_bar.empty()
213 
214     # Streamlit widgets automatically run the script from top to bottom. Since
215     # this button is not connected to any other logic, it just causes a plain
216     # rerun.
217     st.button("Re-run")
218 
219 
220 # fmt: on
221 
222 # Turn off black formatting for this function to present the user with more
223 # compact code.
224 # IMPORTANT: This docstring is shown to the user as an intro to the demo.
225 # fmt: off
226 def data_frame_demo():
227     """
228     This demo shows how to use `st.write` to visualize Pandas DataFrames.
229 
230     (Data courtesy of the [UN Data Exlorer](http://data.un.org/Explorer.aspx).)
231     """
232     import sys
233     import pandas as pd
234     import altair as alt
235 
236     if sys.version_info[0] < 3:
237         reload(sys)
238         sys.setdefaultencoding("utf-8")
239 
240     @st.cache
241     def get_UN_data():
242         AWS_BUCKET_URL = "https://streamlit-demo-data.s3-us-west-2.amazonaws.com"
243         df = pd.read_csv(AWS_BUCKET_URL + "/agri.csv.gz")
244         return df.set_index("Region")
245 
246     try:
247         df = get_UN_data()
248     except urllib.error.URLError:
249         st.error("Connection Error. This demo requires internet access")
250         return
251 
252     countries = st.multiselect(
253         "Choose countries", list(df.index), ["China", "United States of America"]
254     )
255     if not countries:
256         st.error("Please select at least one country.")
257         return
258 
259     data = df.loc[countries]
260     data /= 1000000.0
261     st.write("### Gross Agricultural Production ($B)", data.sort_index())
262 
263     data = data.T.reset_index()
264     data = pd.melt(data, id_vars=["index"]).rename(
265         columns={"index": "year", "value": "Gross Agricultural Product ($B)"}
266     )
267     chart = (
268         alt.Chart(data)
269         .mark_area(opacity=0.3)
270         .encode(
271             x="year:T",
272             y=alt.Y("Gross Agricultural Product ($B):Q", stack=None),
273             color="Region:N",
274         )
275     )
276     st.write("", "", chart)
277 
278 
279 # fmt: on
280 
281 DEMOS = OrderedDict(
282     [
283         ("—", intro),
284         ("Animation Demo", fractal_demo),
285         ("Plotting Demo", plotting_demo),
286         ("Mapping Demo", mapping_demo),
287         ("DataFrame Demo", data_frame_demo),
288     ]
289 )
290 
291 
292 def run():
293     demo_name = st.sidebar.selectbox("Choose a demo", list(DEMOS.keys()), 0)
294     demo = DEMOS[demo_name]
295 
296     if demo_name == "—":
297         show_code = False
298         st.write("# Welcome to Streamlit! 👋")
299     else:
300         show_code = st.sidebar.checkbox("Show code", True)
301         st.markdown("# %s" % demo_name)
302         st.write(inspect.getdoc(demo))
303         # Clear everything from the intro page.
304         # We only have 4 elements in the page so this is intentional overkill.
305         for i in range(10):
306             st.empty()
307 
308     demo()
309 
310     if show_code:
311         st.markdown("## Code")
312         sourcelines, n_lines = inspect.getsourcelines(demo)
313         sourcelines = remove_docstring(sourcelines)
314         st.code(textwrap.dedent("".join(sourcelines)))
315 
316 
317 # This function parses the lines of a function and removes the docstring
318 # if found. If no docstring is found, it returns None.
319 def remove_docstring(lines):
320     if len(lines) < 3 and '"""' not in lines[1]:
321         return lines
322     #  lines[2] is the first line of the docstring, past the inital """
323     index = 2
324     while '"""' not in lines[index]:
325         index += 1
326         # limit to ~100 lines, if the docstring is longer, just bail
327         if index > 100:
328             return lines
329     # lined[index] is the closing """
330     return lines[index + 1 :]
331 
332 
333 if __name__ == "__main__":
334     run()
335
```
--- 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/lib/streamlit/hello.py b/lib/streamlit/hello.py
--- a/lib/streamlit/hello.py
+++ b/lib/streamlit/hello.py
@@ -68,8 +68,9 @@
 
     @st.cache
     def from_data_file(filename):
-        GITHUB_DATA = "https://raw.githubusercontent.com/streamlit/streamlit/develop/examples/"
-        return pd.read_json(os.path.join(GITHUB_DATA, "data", filename))
+        return pd.read_json(
+            "https://raw.githubusercontent.com/streamlit/streamlit/develop/"
+            "examples/data/" + filename)
 
     try:
         ALL_LAYERS = {

{"golden_diff": "diff --git a/lib/streamlit/hello.py b/lib/streamlit/hello.py\n--- a/lib/streamlit/hello.py\n+++ b/lib/streamlit/hello.py\n@@ -68,8 +68,9 @@\n \n     @st.cache\n     def from_data_file(filename):\n-        GITHUB_DATA = \"https://raw.githubusercontent.com/streamlit/streamlit/develop/examples/\"\n-        return pd.read_json(os.path.join(GITHUB_DATA, \"data\", filename))\n+        return pd.read_json(\n+            \"https://raw.githubusercontent.com/streamlit/streamlit/develop/\"\n+            \"examples/data/\" + filename)\n \n     try:\n         ALL_LAYERS = {\n", "issue": "On rerun, faded elements are becoming opaque one by one. Instead they become opaque all at once.\nSteps to repro:\r\n1. Run `examples/reference.py`\r\n2. When done, rerun it.\r\n\r\n**Expected:** on rerun, all elements fade out and then become opaque one by one even before the run is done.\r\n**Actual:** on rerun, all elements fade out and only become opaque when the entire run is done.\r\n\r\nI believe this bug was introduced with the Sidebar code.\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n# Copyright 2018-2019 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A \"Hello World\" app.\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport streamlit as st\nfrom streamlit.logger import get_logger\nimport inspect\nfrom collections import OrderedDict\nimport urllib\nimport textwrap\n\nLOGGER = get_logger(__name__)\n\n\ndef intro():\n    st.sidebar.success(\"Select a demo above.\")\n\n    st.markdown(\"\"\"\n        Streamlit is an open-source app framework built specifically for\n        Machine Learning and Data Science projects.\n\n        **\ud83d\udc48 Select a demo from the dropdown on the left** to see some examples\n        of what Streamlit can do!\n\n        ### Want to learn more?\n\n        - Check out [streamlit.io](https://streamlit.io)\n        - Jump into our [documentation](https://streamlit.io/docs)\n        - Ask a question in our [community\n          forums](https://discuss.streamlit.io)\n\n        ### See more complex demos\n\n        - Use a neural net to [analyze the Udacity Self-driving Car Image\n          Dataset] (https://github.com/streamlit/demo-self-driving)\n        - Explore a [New York City rideshare dataset]\n          (https://github.com/streamlit/demo-uber-nyc-pickups)\n    \"\"\")\n\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef mapping_demo():\n    \"\"\"\n    This demo shows how to use\n    [`st.deck_gl_chart`](https://streamlit.io/docs/api.html#streamlit.deck_gl_chart)\n    to display geospatial data.\n    \"\"\"\n    import pandas as pd\n    import os\n\n    @st.cache\n    def from_data_file(filename):\n        GITHUB_DATA = \"https://raw.githubusercontent.com/streamlit/streamlit/develop/examples/\"\n        return pd.read_json(os.path.join(GITHUB_DATA, \"data\", filename))\n\n    try:\n        ALL_LAYERS = {\n            \"Bike Rentals\": {\n                \"type\": \"HexagonLayer\",\n                \"data\": from_data_file(\"bike_rental_stats.json\"),\n                \"radius\": 200,\n                \"elevationScale\": 4,\n                \"elevationRange\": [0, 1000],\n                \"pickable\": True,\n                \"extruded\": True,\n            },\n            \"Bart Stop Exits\": {\n                \"type\": \"ScatterplotLayer\",\n                \"data\": from_data_file(\"bart_stop_stats.json\"),\n                \"radiusScale\": 0.05,\n                \"getRadius\": \"exits\",\n            },\n            \"Bart Stop Names\": {\n                \"type\": \"TextLayer\",\n                \"data\": from_data_file(\"bart_stop_stats.json\"),\n                \"getText\": \"name\",\n                \"getColor\": [0, 0, 0, 200],\n                \"getSize\": 15,\n            },\n            \"Outbound Flow\": {\n                \"type\": \"ArcLayer\",\n                \"data\": from_data_file(\"bart_path_stats.json\"),\n                \"pickable\": True,\n                \"autoHighlight\": True,\n                \"getStrokeWidth\": 10,\n                \"widthScale\": 0.0001,\n                \"getWidth\": \"outbound\",\n                \"widthMinPixels\": 3,\n                \"widthMaxPixels\": 30,\n            }\n        }\n    except urllib.error.URLError:\n        st.error(\"Connection Error. This demo requires internet access\")\n        return\n\n    st.sidebar.markdown('### Map Layers')\n    selected_layers = [layer for layer_name, layer in ALL_LAYERS.items()\n        if st.sidebar.checkbox(layer_name, True)]\n    if selected_layers:\n        viewport={\"latitude\": 37.76, \"longitude\": -122.4, \"zoom\": 11, \"pitch\": 50}\n        st.deck_gl_chart(viewport=viewport, layers=selected_layers)\n    else:\n        st.error(\"Please choose at least one layer above.\")\n# fmt: on\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef fractal_demo():\n    \"\"\"\n    This app shows how you can use Streamlit to build cool animations.\n    It displays an animated fractal based on the the Julia Set. Use the slider\n    to tune different parameters.\n    \"\"\"\n    import numpy as np\n\n    # Interactive Streamlit elements, like these sliders, return their value.\n    # This gives you an extremely simple interaction model.\n    iterations = st.sidebar.slider(\"Level of detail\", 2, 20, 10, 1)\n    separation = st.sidebar.slider(\"Separation\", 0.7, 2.0, 0.7885)\n\n    # Non-interactive elements return a placeholder to their location\n    # in the app. Here we're storing progress_bar to update it later.\n    progress_bar = st.sidebar.progress(0)\n\n    # These two elements will be filled in later, so we create a placeholder\n    # for them using st.empty()\n    frame_text = st.sidebar.empty()\n    image = st.empty()\n\n    m, n, s = 960, 640, 400\n    x = np.linspace(-m / s, m / s, num=m).reshape((1, m))\n    y = np.linspace(-n / s, n / s, num=n).reshape((n, 1))\n\n    for frame_num, a in enumerate(np.linspace(0.0, 4 * np.pi, 100)):\n        # Here were setting value for these two elements.\n        progress_bar.progress(frame_num)\n        frame_text.text(\"Frame %i/100\" % (frame_num + 1))\n\n        # Performing some fractal wizardry.\n        c = separation * np.exp(1j * a)\n        Z = np.tile(x, (n, 1)) + 1j * np.tile(y, (1, m))\n        C = np.full((n, m), c)\n        M = np.full((n, m), True, dtype=bool)\n        N = np.zeros((n, m))\n\n        for i in range(iterations):\n            Z[M] = Z[M] * Z[M] + C[M]\n            M[np.abs(Z) > 2] = False\n            N[M] = i\n\n        # Update the image placeholder by calling the image() function on it.\n        image.image(1.0 - (N / N.max()), use_column_width=True)\n\n    # We clear elements by calling empty on them.\n    progress_bar.empty()\n    frame_text.empty()\n\n    # Streamlit widgets automatically run the script from top to bottom. Since\n    # this button is not connected to any other logic, it just causes a plain\n    # rerun.\n    st.button(\"Re-run\")\n\n\n# fmt: on\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef plotting_demo():\n    \"\"\"\n    This demo illustrates a combination of plotting and animation with\n    Streamlit. We're generating a bunch of random numbers in a loop for around\n    5 seconds. Enjoy!\n    \"\"\"\n    import time\n    import numpy as np\n\n    progress_bar = st.sidebar.progress(0)\n    status_text = st.sidebar.empty()\n    last_rows = np.random.randn(1, 1)\n    chart = st.line_chart(last_rows)\n\n    for i in range(1, 101):\n        new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)\n        status_text.text(\"%i%% Complete\" % i)\n        chart.add_rows(new_rows)\n        progress_bar.progress(i)\n        last_rows = new_rows\n        time.sleep(0.05)\n\n    progress_bar.empty()\n\n    # Streamlit widgets automatically run the script from top to bottom. Since\n    # this button is not connected to any other logic, it just causes a plain\n    # rerun.\n    st.button(\"Re-run\")\n\n\n# fmt: on\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef data_frame_demo():\n    \"\"\"\n    This demo shows how to use `st.write` to visualize Pandas DataFrames.\n\n    (Data courtesy of the [UN Data Exlorer](http://data.un.org/Explorer.aspx).)\n    \"\"\"\n    import sys\n    import pandas as pd\n    import altair as alt\n\n    if sys.version_info[0] < 3:\n        reload(sys)\n        sys.setdefaultencoding(\"utf-8\")\n\n    @st.cache\n    def get_UN_data():\n        AWS_BUCKET_URL = \"https://streamlit-demo-data.s3-us-west-2.amazonaws.com\"\n        df = pd.read_csv(AWS_BUCKET_URL + \"/agri.csv.gz\")\n        return df.set_index(\"Region\")\n\n    try:\n        df = get_UN_data()\n    except urllib.error.URLError:\n        st.error(\"Connection Error. This demo requires internet access\")\n        return\n\n    countries = st.multiselect(\n        \"Choose countries\", list(df.index), [\"China\", \"United States of America\"]\n    )\n    if not countries:\n        st.error(\"Please select at least one country.\")\n        return\n\n    data = df.loc[countries]\n    data /= 1000000.0\n    st.write(\"### Gross Agricultural Production ($B)\", data.sort_index())\n\n    data = data.T.reset_index()\n    data = pd.melt(data, id_vars=[\"index\"]).rename(\n        columns={\"index\": \"year\", \"value\": \"Gross Agricultural Product ($B)\"}\n    )\n    chart = (\n        alt.Chart(data)\n        .mark_area(opacity=0.3)\n        .encode(\n            x=\"year:T\",\n            y=alt.Y(\"Gross Agricultural Product ($B):Q\", stack=None),\n            color=\"Region:N\",\n        )\n    )\n    st.write(\"\", \"\", chart)\n\n\n# fmt: on\n\nDEMOS = OrderedDict(\n    [\n        (\"\u2014\", intro),\n        (\"Animation Demo\", fractal_demo),\n        (\"Plotting Demo\", plotting_demo),\n        (\"Mapping Demo\", mapping_demo),\n        (\"DataFrame Demo\", data_frame_demo),\n    ]\n)\n\n\ndef run():\n    demo_name = st.sidebar.selectbox(\"Choose a demo\", list(DEMOS.keys()), 0)\n    demo = DEMOS[demo_name]\n\n    if demo_name == \"\u2014\":\n        show_code = False\n        st.write(\"# Welcome to Streamlit! \ud83d\udc4b\")\n    else:\n        show_code = st.sidebar.checkbox(\"Show code\", True)\n        st.markdown(\"# %s\" % demo_name)\n        st.write(inspect.getdoc(demo))\n        # Clear everything from the intro page.\n        # We only have 4 elements in the page so this is intentional overkill.\n        for i in range(10):\n            st.empty()\n\n    demo()\n\n    if show_code:\n        st.markdown(\"## Code\")\n        sourcelines, n_lines = inspect.getsourcelines(demo)\n        sourcelines = remove_docstring(sourcelines)\n        st.code(textwrap.dedent(\"\".join(sourcelines)))\n\n\n# This function parses the lines of a function and removes the docstring\n# if found. If no docstring is found, it returns None.\ndef remove_docstring(lines):\n    if len(lines) < 3 and '\"\"\"' not in lines[1]:\n        return lines\n    #  lines[2] is the first line of the docstring, past the inital \"\"\"\n    index = 2\n    while '\"\"\"' not in lines[index]:\n        index += 1\n        # limit to ~100 lines, if the docstring is longer, just bail\n        if index > 100:\n            return lines\n    # lined[index] is the closing \"\"\"\n    return lines[index + 1 :]\n\n\nif __name__ == \"__main__\":\n    run()\n", "path": "lib/streamlit/hello.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n# Copyright 2018-2019 Streamlit Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A \"Hello World\" app.\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport streamlit as st\nfrom streamlit.logger import get_logger\nimport inspect\nfrom collections import OrderedDict\nimport urllib\nimport textwrap\n\nLOGGER = get_logger(__name__)\n\n\ndef intro():\n    st.sidebar.success(\"Select a demo above.\")\n\n    st.markdown(\"\"\"\n        Streamlit is an open-source app framework built specifically for\n        Machine Learning and Data Science projects.\n\n        **\ud83d\udc48 Select a demo from the dropdown on the left** to see some examples\n        of what Streamlit can do!\n\n        ### Want to learn more?\n\n        - Check out [streamlit.io](https://streamlit.io)\n        - Jump into our [documentation](https://streamlit.io/docs)\n        - Ask a question in our [community\n          forums](https://discuss.streamlit.io)\n\n        ### See more complex demos\n\n        - Use a neural net to [analyze the Udacity Self-driving Car Image\n          Dataset] (https://github.com/streamlit/demo-self-driving)\n        - Explore a [New York City rideshare dataset]\n          (https://github.com/streamlit/demo-uber-nyc-pickups)\n    \"\"\")\n\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef mapping_demo():\n    \"\"\"\n    This demo shows how to use\n    [`st.deck_gl_chart`](https://streamlit.io/docs/api.html#streamlit.deck_gl_chart)\n    to display geospatial data.\n    \"\"\"\n    import pandas as pd\n    import os\n\n    @st.cache\n    def from_data_file(filename):\n        return pd.read_json(\n            \"https://raw.githubusercontent.com/streamlit/streamlit/develop/\"\n            \"examples/data/\" + filename)\n\n    try:\n        ALL_LAYERS = {\n            \"Bike Rentals\": {\n                \"type\": \"HexagonLayer\",\n                \"data\": from_data_file(\"bike_rental_stats.json\"),\n                \"radius\": 200,\n                \"elevationScale\": 4,\n                \"elevationRange\": [0, 1000],\n                \"pickable\": True,\n                \"extruded\": True,\n            },\n            \"Bart Stop Exits\": {\n                \"type\": \"ScatterplotLayer\",\n                \"data\": from_data_file(\"bart_stop_stats.json\"),\n                \"radiusScale\": 0.05,\n                \"getRadius\": \"exits\",\n            },\n            \"Bart Stop Names\": {\n                \"type\": \"TextLayer\",\n                \"data\": from_data_file(\"bart_stop_stats.json\"),\n                \"getText\": \"name\",\n                \"getColor\": [0, 0, 0, 200],\n                \"getSize\": 15,\n            },\n            \"Outbound Flow\": {\n                \"type\": \"ArcLayer\",\n                \"data\": from_data_file(\"bart_path_stats.json\"),\n                \"pickable\": True,\n                \"autoHighlight\": True,\n                \"getStrokeWidth\": 10,\n                \"widthScale\": 0.0001,\n                \"getWidth\": \"outbound\",\n                \"widthMinPixels\": 3,\n                \"widthMaxPixels\": 30,\n            }\n        }\n    except urllib.error.URLError:\n        st.error(\"Connection Error. This demo requires internet access\")\n        return\n\n    st.sidebar.markdown('### Map Layers')\n    selected_layers = [layer for layer_name, layer in ALL_LAYERS.items()\n        if st.sidebar.checkbox(layer_name, True)]\n    if selected_layers:\n        viewport={\"latitude\": 37.76, \"longitude\": -122.4, \"zoom\": 11, \"pitch\": 50}\n        st.deck_gl_chart(viewport=viewport, layers=selected_layers)\n    else:\n        st.error(\"Please choose at least one layer above.\")\n# fmt: on\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef fractal_demo():\n    \"\"\"\n    This app shows how you can use Streamlit to build cool animations.\n    It displays an animated fractal based on the the Julia Set. Use the slider\n    to tune different parameters.\n    \"\"\"\n    import numpy as np\n\n    # Interactive Streamlit elements, like these sliders, return their value.\n    # This gives you an extremely simple interaction model.\n    iterations = st.sidebar.slider(\"Level of detail\", 2, 20, 10, 1)\n    separation = st.sidebar.slider(\"Separation\", 0.7, 2.0, 0.7885)\n\n    # Non-interactive elements return a placeholder to their location\n    # in the app. Here we're storing progress_bar to update it later.\n    progress_bar = st.sidebar.progress(0)\n\n    # These two elements will be filled in later, so we create a placeholder\n    # for them using st.empty()\n    frame_text = st.sidebar.empty()\n    image = st.empty()\n\n    m, n, s = 960, 640, 400\n    x = np.linspace(-m / s, m / s, num=m).reshape((1, m))\n    y = np.linspace(-n / s, n / s, num=n).reshape((n, 1))\n\n    for frame_num, a in enumerate(np.linspace(0.0, 4 * np.pi, 100)):\n        # Here were setting value for these two elements.\n        progress_bar.progress(frame_num)\n        frame_text.text(\"Frame %i/100\" % (frame_num + 1))\n\n        # Performing some fractal wizardry.\n        c = separation * np.exp(1j * a)\n        Z = np.tile(x, (n, 1)) + 1j * np.tile(y, (1, m))\n        C = np.full((n, m), c)\n        M = np.full((n, m), True, dtype=bool)\n        N = np.zeros((n, m))\n\n        for i in range(iterations):\n            Z[M] = Z[M] * Z[M] + C[M]\n            M[np.abs(Z) > 2] = False\n            N[M] = i\n\n        # Update the image placeholder by calling the image() function on it.\n        image.image(1.0 - (N / N.max()), use_column_width=True)\n\n    # We clear elements by calling empty on them.\n    progress_bar.empty()\n    frame_text.empty()\n\n    # Streamlit widgets automatically run the script from top to bottom. Since\n    # this button is not connected to any other logic, it just causes a plain\n    # rerun.\n    st.button(\"Re-run\")\n\n\n# fmt: on\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef plotting_demo():\n    \"\"\"\n    This demo illustrates a combination of plotting and animation with\n    Streamlit. We're generating a bunch of random numbers in a loop for around\n    5 seconds. Enjoy!\n    \"\"\"\n    import time\n    import numpy as np\n\n    progress_bar = st.sidebar.progress(0)\n    status_text = st.sidebar.empty()\n    last_rows = np.random.randn(1, 1)\n    chart = st.line_chart(last_rows)\n\n    for i in range(1, 101):\n        new_rows = last_rows[-1, :] + np.random.randn(5, 1).cumsum(axis=0)\n        status_text.text(\"%i%% Complete\" % i)\n        chart.add_rows(new_rows)\n        progress_bar.progress(i)\n        last_rows = new_rows\n        time.sleep(0.05)\n\n    progress_bar.empty()\n\n    # Streamlit widgets automatically run the script from top to bottom. Since\n    # this button is not connected to any other logic, it just causes a plain\n    # rerun.\n    st.button(\"Re-run\")\n\n\n# fmt: on\n\n# Turn off black formatting for this function to present the user with more\n# compact code.\n# IMPORTANT: This docstring is shown to the user as an intro to the demo.\n# fmt: off\ndef data_frame_demo():\n    \"\"\"\n    This demo shows how to use `st.write` to visualize Pandas DataFrames.\n\n    (Data courtesy of the [UN Data Exlorer](http://data.un.org/Explorer.aspx).)\n    \"\"\"\n    import sys\n    import pandas as pd\n    import altair as alt\n\n    if sys.version_info[0] < 3:\n        reload(sys)\n        sys.setdefaultencoding(\"utf-8\")\n\n    @st.cache\n    def get_UN_data():\n        AWS_BUCKET_URL = \"https://streamlit-demo-data.s3-us-west-2.amazonaws.com\"\n        df = pd.read_csv(AWS_BUCKET_URL + \"/agri.csv.gz\")\n        return df.set_index(\"Region\")\n\n    try:\n        df = get_UN_data()\n    except urllib.error.URLError:\n        st.error(\"Connection Error. This demo requires internet access\")\n        return\n\n    countries = st.multiselect(\n        \"Choose countries\", list(df.index), [\"China\", \"United States of America\"]\n    )\n    if not countries:\n        st.error(\"Please select at least one country.\")\n        return\n\n    data = df.loc[countries]\n    data /= 1000000.0\n    st.write(\"### Gross Agricultural Production ($B)\", data.sort_index())\n\n    data = data.T.reset_index()\n    data = pd.melt(data, id_vars=[\"index\"]).rename(\n        columns={\"index\": \"year\", \"value\": \"Gross Agricultural Product ($B)\"}\n    )\n    chart = (\n        alt.Chart(data)\n        .mark_area(opacity=0.3)\n        .encode(\n            x=\"year:T\",\n            y=alt.Y(\"Gross Agricultural Product ($B):Q\", stack=None),\n            color=\"Region:N\",\n        )\n    )\n    st.write(\"\", \"\", chart)\n\n\n# fmt: on\n\nDEMOS = OrderedDict(\n    [\n        (\"\u2014\", intro),\n        (\"Animation Demo\", fractal_demo),\n        (\"Plotting Demo\", plotting_demo),\n        (\"Mapping Demo\", mapping_demo),\n        (\"DataFrame Demo\", data_frame_demo),\n    ]\n)\n\n\ndef run():\n    demo_name = st.sidebar.selectbox(\"Choose a demo\", list(DEMOS.keys()), 0)\n    demo = DEMOS[demo_name]\n\n    if demo_name == \"\u2014\":\n        show_code = False\n        st.write(\"# Welcome to Streamlit! \ud83d\udc4b\")\n    else:\n        show_code = st.sidebar.checkbox(\"Show code\", True)\n        st.markdown(\"# %s\" % demo_name)\n        st.write(inspect.getdoc(demo))\n        # Clear everything from the intro page.\n        # We only have 4 elements in the page so this is intentional overkill.\n        for i in range(10):\n            st.empty()\n\n    demo()\n\n    if show_code:\n        st.markdown(\"## Code\")\n        sourcelines, n_lines = inspect.getsourcelines(demo)\n        sourcelines = remove_docstring(sourcelines)\n        st.code(textwrap.dedent(\"\".join(sourcelines)))\n\n\n# This function parses the lines of a function and removes the docstring\n# if found. If no docstring is found, it returns None.\ndef remove_docstring(lines):\n    if len(lines) < 3 and '\"\"\"' not in lines[1]:\n        return lines\n    #  lines[2] is the first line of the docstring, past the inital \"\"\"\n    index = 2\n    while '\"\"\"' not in lines[index]:\n        index += 1\n        # limit to ~100 lines, if the docstring is longer, just bail\n        if index > 100:\n            return lines\n    # lined[index] is the closing \"\"\"\n    return lines[index + 1 :]\n\n\nif __name__ == \"__main__\":\n    run()\n", "path": "lib/streamlit/hello.py"}]}