prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  flask_gunicorn_embed.py does not work with Tornado 5
  ref: https://github.com/bokeh/bokeh/blob/master/examples/howto/server_embed/flask_gunicorn_embed.py
  
  Running as is gets:
  ```
  Exception in thread Thread-1:
  Traceback (most recent call last):
    File "/Users/bryanv/anaconda/envs/01216/lib/python3.6/threading.py", line 916, in _bootstrap_inner
      self.run()
    File "/Users/bryanv/anaconda/envs/01216/lib/python3.6/threading.py", line 864, in run
      self._target(*self._args, **self._kwargs)
    File "/Users/bryanv/work/bokeh/examples/howto/server_embed/flask_gunicorn_embed.py", line 72, in bk_worker
      server.start()
    File "/Users/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/bokeh/server/server.py", line 149, in start
      self._tornado.start()
    File "/Users/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/bokeh/server/tornado.py", line 372, in start
      self._stats_job.start()
    File "/Users/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/tornado/ioloop.py", line 1185, in start
      self.io_loop = IOLoop.current()
    File "/Use
  rs/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/tornado/ioloop.py", line 282, in current
      loop = asyncio.get_event_loop()
    File "/Users/bryanv/anaconda/envs/01216/lib/python3.6/asyncio/events.py", line 694, in get_event_loop
      return get_event_loop_policy().get_event_loop()
    File "/Users/bryanv/anaconda/envs/01216/lib/python3.6/asyncio/events.py", line 602, in get_event_loop
      % threading.current_thread().name)
  RuntimeError: There is no current event loop in thread 'Thread-1'.
  ```
  
  Tried changing worker to 
  ```
  def bk_worker():
      io_loop = IOLoop())
      server = BaseServer(io_loop, bokeh_tornado, bokeh_http)
      server.start()
      server.io_loop.start()
  ```
  
  
  but then the http requests to the `HTTPServer` just hang (the workers are getting executed the right number of times though)
  
  cc @bdarnell any quick ideas?
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `examples/howto/server_embed/flask_gunicorn_embed.py`
  Content:
  ```
  1 from flask import Flask, render_template
  2 
  3 from tornado.httpserver import HTTPServer
  4 from tornado.ioloop import IOLoop
  5 
  6 from bokeh.application import Application
  7 from bokeh.application.handlers import FunctionHandler
  8 from bokeh.embed import server_document
  9 from bokeh.layouts import column
  10 from bokeh.models import ColumnDataSource, Slider
  11 from bokeh.plotting import figure
  12 from bokeh.server.server import BaseServer
  13 from bokeh.server.tornado import BokehTornado
  14 from bokeh.server.util import bind_sockets
  15 from bokeh.themes import Theme
  16 
  17 if __name__ == '__main__':
  18     print('This script is intended to be run with gunicorn. e.g.')
  19     print()
  20     print('    gunicorn -w 4 flask_gunicorn_embed:app')
  21     print()
  22     print('will start the app on four processes')
  23     import sys
  24     sys.exit()
  25 
  26 from bokeh.sampledata.sea_surface_temperature import sea_surface_temperature
  27 
  28 app = Flask(__name__)
  29 
  30 def modify_doc(doc):
  31     df = sea_surface_temperature.copy()
  32     source = ColumnDataSource(data=df)
  33 
  34     plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',
  35                   title="Sea Surface Temperature at 43.18, -70.43")
  36     plot.line('time', 'temperature', source=source)
  37 
  38     def callback(attr, old, new):
  39         if new == 0:
  40             data = df
  41         else:
  42             data = df.rolling('{0}D'.format(new)).mean()
  43         source.data = ColumnDataSource(data=data).data
  44 
  45     slider = Slider(start=0, end=30, value=0, step=1, title="Smoothing by N Days")
  46     slider.on_change('value', callback)
  47 
  48     doc.add_root(column(slider, plot))
  49 
  50     doc.theme = Theme(filename="theme.yaml")
  51 
  52 # can't use shortcuts here, since we are passing to low level BokehTornado
  53 bkapp = Application(FunctionHandler(modify_doc))
  54 
  55 bokeh_tornado = BokehTornado({'/bkapp': bkapp}, extra_websocket_origins=["localhost:8000"])
  56 bokeh_http = HTTPServer(bokeh_tornado)
  57 
  58 # This is so that if this app is run using something like "gunicorn -w 4" then
  59 # each process will listen on its own port
  60 sockets, port = bind_sockets("localhost", 0)
  61 bokeh_http.add_sockets(sockets)
  62 
  63 @app.route('/', methods=['GET'])
  64 def bkapp_page():
  65     script = server_document('http://localhost:%d/bkapp' % port)
  66     return render_template("embed.html", script=script, template="Flask")
  67 
  68 def bk_worker():
  69     io_loop = IOLoop.current()
  70     server = BaseServer(io_loop, bokeh_tornado, bokeh_http)
  71     server.start()
  72     server.io_loop.start()
  73 
  74 from threading import Thread
  75 Thread(target=bk_worker).start()
  76
  ```
  --- 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()
  
  ```
  
golden_diff: diff --git a/examples/howto/server_embed/flask_gunicorn_embed.py b/examples/howto/server_embed/flask_gunicorn_embed.py
  --- a/examples/howto/server_embed/flask_gunicorn_embed.py
  +++ b/examples/howto/server_embed/flask_gunicorn_embed.py
  @@ -1,3 +1,8 @@
  +try:
  +    import asyncio
  +except ImportError:
  +    raise RuntimeError("This example requries Python3 / asyncio")
  +
   from flask import Flask, render_template
   
   from tornado.httpserver import HTTPServer
  @@ -52,13 +57,9 @@
   # can't use shortcuts here, since we are passing to low level BokehTornado
   bkapp = Application(FunctionHandler(modify_doc))
   
  -bokeh_tornado = BokehTornado({'/bkapp': bkapp}, extra_websocket_origins=["localhost:8000"])
  -bokeh_http = HTTPServer(bokeh_tornado)
  -
   # This is so that if this app is run using something like "gunicorn -w 4" then
   # each process will listen on its own port
   sockets, port = bind_sockets("localhost", 0)
  -bokeh_http.add_sockets(sockets)
   
   @app.route('/', methods=['GET'])
   def bkapp_page():
  @@ -66,8 +67,13 @@
       return render_template("embed.html", script=script, template="Flask")
   
   def bk_worker():
  -    io_loop = IOLoop.current()
  -    server = BaseServer(io_loop, bokeh_tornado, bokeh_http)
  +    asyncio.set_event_loop(asyncio.new_event_loop())
  +
  +    bokeh_tornado = BokehTornado({'/bkapp': bkapp}, extra_websocket_origins=["localhost:8000"])
  +    bokeh_http = HTTPServer(bokeh_tornado)
  +    bokeh_http.add_sockets(sockets)
  +
  +    server = BaseServer(IOLoop.current(), bokeh_tornado, bokeh_http)
       server.start()
       server.io_loop.start()
  
verification_info: {"golden_diff": "diff --git a/examples/howto/server_embed/flask_gunicorn_embed.py b/examples/howto/server_embed/flask_gunicorn_embed.py\n--- a/examples/howto/server_embed/flask_gunicorn_embed.py\n+++ b/examples/howto/server_embed/flask_gunicorn_embed.py\n@@ -1,3 +1,8 @@\n+try:\n+    import asyncio\n+except ImportError:\n+    raise RuntimeError(\"This example requries Python3 / asyncio\")\n+\n from flask import Flask, render_template\n \n from tornado.httpserver import HTTPServer\n@@ -52,13 +57,9 @@\n # can't use shortcuts here, since we are passing to low level BokehTornado\n bkapp = Application(FunctionHandler(modify_doc))\n \n-bokeh_tornado = BokehTornado({'/bkapp': bkapp}, extra_websocket_origins=[\"localhost:8000\"])\n-bokeh_http = HTTPServer(bokeh_tornado)\n-\n # This is so that if this app is run using something like \"gunicorn -w 4\" then\n # each process will listen on its own port\n sockets, port = bind_sockets(\"localhost\", 0)\n-bokeh_http.add_sockets(sockets)\n \n @app.route('/', methods=['GET'])\n def bkapp_page():\n@@ -66,8 +67,13 @@\n     return render_template(\"embed.html\", script=script, template=\"Flask\")\n \n def bk_worker():\n-    io_loop = IOLoop.current()\n-    server = BaseServer(io_loop, bokeh_tornado, bokeh_http)\n+    asyncio.set_event_loop(asyncio.new_event_loop())\n+\n+    bokeh_tornado = BokehTornado({'/bkapp': bkapp}, extra_websocket_origins=[\"localhost:8000\"])\n+    bokeh_http = HTTPServer(bokeh_tornado)\n+    bokeh_http.add_sockets(sockets)\n+\n+    server = BaseServer(IOLoop.current(), bokeh_tornado, bokeh_http)\n     server.start()\n     server.io_loop.start()\n", "issue": "flask_gunicorn_embed.py does not work with Tornado 5\nref: https://github.com/bokeh/bokeh/blob/master/examples/howto/server_embed/flask_gunicorn_embed.py\r\n\r\nRunning as is gets:\r\n```\r\nException in thread Thread-1:\r\nTraceback (most recent call last):\r\n  File \"/Users/bryanv/anaconda/envs/01216/lib/python3.6/threading.py\", line 916, in _bootstrap_inner\r\n    self.run()\r\n  File \"/Users/bryanv/anaconda/envs/01216/lib/python3.6/threading.py\", line 864, in run\r\n    self._target(*self._args, **self._kwargs)\r\n  File \"/Users/bryanv/work/bokeh/examples/howto/server_embed/flask_gunicorn_embed.py\", line 72, in bk_worker\r\n    server.start()\r\n  File \"/Users/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/bokeh/server/server.py\", line 149, in start\r\n    self._tornado.start()\r\n  File \"/Users/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/bokeh/server/tornado.py\", line 372, in start\r\n    self._stats_job.start()\r\n  File \"/Users/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/tornado/ioloop.py\", line 1185, in start\r\n    self.io_loop = IOLoop.current()\r\n  File \"/Use\r\nrs/bryanv/anaconda/envs/01216/lib/python3.6/site-packages/tornado/ioloop.py\", line 282, in current\r\n    loop = asyncio.get_event_loop()\r\n  File \"/Users/bryanv/anaconda/envs/01216/lib/python3.6/asyncio/events.py\", line 694, in get_event_loop\r\n    return get_event_loop_policy().get_event_loop()\r\n  File \"/Users/bryanv/anaconda/envs/01216/lib/python3.6/asyncio/events.py\", line 602, in get_event_loop\r\n    % threading.current_thread().name)\r\nRuntimeError: There is no current event loop in thread 'Thread-1'.\r\n```\r\n\r\nTried changing worker to \r\n```\r\ndef bk_worker():\r\n    io_loop = IOLoop())\r\n    server = BaseServer(io_loop, bokeh_tornado, bokeh_http)\r\n    server.start()\r\n    server.io_loop.start()\r\n```\r\n\r\n\r\nbut then the http requests to the `HTTPServer` just hang (the workers are getting executed the right number of times though)\r\n\r\ncc @bdarnell any quick ideas?\n", "before_files": [{"content": "from flask import Flask, render_template\n\nfrom tornado.httpserver import HTTPServer\nfrom tornado.ioloop import IOLoop\n\nfrom bokeh.application import Application\nfrom bokeh.application.handlers import FunctionHandler\nfrom bokeh.embed import server_document\nfrom bokeh.layouts import column\nfrom bokeh.models import ColumnDataSource, Slider\nfrom bokeh.plotting import figure\nfrom bokeh.server.server import BaseServer\nfrom bokeh.server.tornado import BokehTornado\nfrom bokeh.server.util import bind_sockets\nfrom bokeh.themes import Theme\n\nif __name__ == '__main__':\n    print('This script is intended to be run with gunicorn. e.g.')\n    print()\n    print('    gunicorn -w 4 flask_gunicorn_embed:app')\n    print()\n    print('will start the app on four processes')\n    import sys\n    sys.exit()\n\nfrom bokeh.sampledata.sea_surface_temperature import sea_surface_temperature\n\napp = Flask(__name__)\n\ndef modify_doc(doc):\n    df = sea_surface_temperature.copy()\n    source = ColumnDataSource(data=df)\n\n    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',\n                  title=\"Sea Surface Temperature at 43.18, -70.43\")\n    plot.line('time', 'temperature', source=source)\n\n    def callback(attr, old, new):\n        if new == 0:\n            data = df\n        else:\n            data = df.rolling('{0}D'.format(new)).mean()\n        source.data = ColumnDataSource(data=data).data\n\n    slider = Slider(start=0, end=30, value=0, step=1, title=\"Smoothing by N Days\")\n    slider.on_change('value', callback)\n\n    doc.add_root(column(slider, plot))\n\n    doc.theme = Theme(filename=\"theme.yaml\")\n\n# can't use shortcuts here, since we are passing to low level BokehTornado\nbkapp = Application(FunctionHandler(modify_doc))\n\nbokeh_tornado = BokehTornado({'/bkapp': bkapp}, extra_websocket_origins=[\"localhost:8000\"])\nbokeh_http = HTTPServer(bokeh_tornado)\n\n# This is so that if this app is run using something like \"gunicorn -w 4\" then\n# each process will listen on its own port\nsockets, port = bind_sockets(\"localhost\", 0)\nbokeh_http.add_sockets(sockets)\n\n@app.route('/', methods=['GET'])\ndef bkapp_page():\n    script = server_document('http://localhost:%d/bkapp' % port)\n    return render_template(\"embed.html\", script=script, template=\"Flask\")\n\ndef bk_worker():\n    io_loop = IOLoop.current()\n    server = BaseServer(io_loop, bokeh_tornado, bokeh_http)\n    server.start()\n    server.io_loop.start()\n\nfrom threading import Thread\nThread(target=bk_worker).start()\n", "path": "examples/howto/server_embed/flask_gunicorn_embed.py"}], "after_files": [{"content": "try:\n    import asyncio\nexcept ImportError:\n    raise RuntimeError(\"This example requries Python3 / asyncio\")\n\nfrom flask import Flask, render_template\n\nfrom tornado.httpserver import HTTPServer\nfrom tornado.ioloop import IOLoop\n\nfrom bokeh.application import Application\nfrom bokeh.application.handlers import FunctionHandler\nfrom bokeh.embed import server_document\nfrom bokeh.layouts import column\nfrom bokeh.models import ColumnDataSource, Slider\nfrom bokeh.plotting import figure\nfrom bokeh.server.server import BaseServer\nfrom bokeh.server.tornado import BokehTornado\nfrom bokeh.server.util import bind_sockets\nfrom bokeh.themes import Theme\n\nif __name__ == '__main__':\n    print('This script is intended to be run with gunicorn. e.g.')\n    print()\n    print('    gunicorn -w 4 flask_gunicorn_embed:app')\n    print()\n    print('will start the app on four processes')\n    import sys\n    sys.exit()\n\nfrom bokeh.sampledata.sea_surface_temperature import sea_surface_temperature\n\napp = Flask(__name__)\n\ndef modify_doc(doc):\n    df = sea_surface_temperature.copy()\n    source = ColumnDataSource(data=df)\n\n    plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)',\n                  title=\"Sea Surface Temperature at 43.18, -70.43\")\n    plot.line('time', 'temperature', source=source)\n\n    def callback(attr, old, new):\n        if new == 0:\n            data = df\n        else:\n            data = df.rolling('{0}D'.format(new)).mean()\n        source.data = ColumnDataSource(data=data).data\n\n    slider = Slider(start=0, end=30, value=0, step=1, title=\"Smoothing by N Days\")\n    slider.on_change('value', callback)\n\n    doc.add_root(column(slider, plot))\n\n    doc.theme = Theme(filename=\"theme.yaml\")\n\n# can't use shortcuts here, since we are passing to low level BokehTornado\nbkapp = Application(FunctionHandler(modify_doc))\n\n# This is so that if this app is run using something like \"gunicorn -w 4\" then\n# each process will listen on its own port\nsockets, port = bind_sockets(\"localhost\", 0)\n\n@app.route('/', methods=['GET'])\ndef bkapp_page():\n    script = server_document('http://localhost:%d/bkapp' % port)\n    return render_template(\"embed.html\", script=script, template=\"Flask\")\n\ndef bk_worker():\n    asyncio.set_event_loop(asyncio.new_event_loop())\n\n    bokeh_tornado = BokehTornado({'/bkapp': bkapp}, extra_websocket_origins=[\"localhost:8000\"])\n    bokeh_http = HTTPServer(bokeh_tornado)\n    bokeh_http.add_sockets(sockets)\n\n    server = BaseServer(IOLoop.current(), bokeh_tornado, bokeh_http)\n    server.start()\n    server.io_loop.start()\n\nfrom threading import Thread\nThread(target=bk_worker).start()\n", "path": "examples/howto/server_embed/flask_gunicorn_embed.py"}]}