We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Kill all running `.show()` instances?
I'm using a slightly wacky setup (jupyter-mode in `emacs`) and I end up calling `Pane.show()` a lot. Is there an easy way to kill all previously-created `show()` servers without killing the whole process?

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `panel/io/server.py`
Content:
```
1 """
2 Utilities for creating bokeh Server instances.
3 """
4 from __future__ import absolute_import, division, unicode_literals
5 
6 import signal
7 import threading
8 
9 from functools import partial
10 
11 from bokeh.server.server import Server
12 
13 from .state import state
14 
15 
16 #---------------------------------------------------------------------
17 # Private API
18 #---------------------------------------------------------------------
19 
20 def _origin_url(url):
21     if url.startswith("http"):
22         url = url.split("//")[1]
23     return url
24 
25 
26 def _server_url(url, port):
27     if url.startswith("http"):
28         return '%s:%d%s' % (url.rsplit(':', 1)[0], port, "/")
29     else:
30         return 'http://%s:%d%s' % (url.split(':')[0], port, "/")
31 
32 #---------------------------------------------------------------------
33 # Public API
34 #---------------------------------------------------------------------
35 
36 def get_server(panel, port=0, websocket_origin=None, loop=None,
37                show=False, start=False, **kwargs):
38     """
39     Returns a Server instance with this panel attached as the root
40     app.
41 
42     Arguments
43     ---------
44     port: int (optional, default=0)
45       Allows specifying a specific port
46     websocket_origin: str or list(str) (optional)
47       A list of hosts that can connect to the websocket.
48 
49       This is typically required when embedding a server app in
50       an external web site.
51 
52       If None, "localhost" is used.
53     loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())
54       The tornado IOLoop to run the Server on
55     show : boolean (optional, default=False)
56       Whether to open the server in a new browser tab on start
57     start : boolean(optional, default=False)
58       Whether to start the Server
59     kwargs: dict
60       Additional keyword arguments to pass to Server instance
61 
62     Returns
63     -------
64     server : bokeh.server.server.Server
65       Bokeh Server instance running this panel
66     """
67     from tornado.ioloop import IOLoop
68     opts = dict(kwargs)
69     if loop:
70         loop.make_current()
71         opts['io_loop'] = loop
72     else:
73         opts['io_loop'] = IOLoop.current()
74 
75     if websocket_origin:
76         if not isinstance(websocket_origin, list):
77             websocket_origin = [websocket_origin]
78         opts['allow_websocket_origin'] = websocket_origin
79 
80     server_id = kwargs.pop('server_id', None)
81     server = Server({'/': partial(panel._modify_doc, server_id)}, port=port, **opts)
82     if server_id:
83         state._servers[server_id] = (server, panel, [])
84 
85     if show:
86         def show_callback():
87             server.show('/')
88         server.io_loop.add_callback(show_callback)
89 
90     def sig_exit(*args, **kwargs):
91         server.io_loop.add_callback_from_signal(do_stop)
92 
93     def do_stop(*args, **kwargs):
94         server.io_loop.stop()
95 
96     try:
97         signal.signal(signal.SIGINT, sig_exit)
98     except ValueError:
99         pass # Can't use signal on a thread
100 
101     if start:
102         server.start()
103         try:
104             server.io_loop.start()
105         except RuntimeError:
106             pass
107     return server
108 
109 
110 class StoppableThread(threading.Thread):
111     """Thread class with a stop() method."""
112 
113     def __init__(self, io_loop=None, timeout=1000, **kwargs):
114         from tornado import ioloop
115         super(StoppableThread, self).__init__(**kwargs)
116         self._stop_event = threading.Event()
117         self.io_loop = io_loop
118         self._cb = ioloop.PeriodicCallback(self._check_stopped, timeout)
119         self._cb.start()
120 
121     def _check_stopped(self):
122         if self.stopped:
123             self._cb.stop()
124             self.io_loop.stop()
125 
126     def run(self):
127         if hasattr(self, '_target'):
128             target, args, kwargs = self._target, self._args, self._kwargs
129         else:
130             target, args, kwargs = self._Thread__target, self._Thread__args, self._Thread__kwargs
131         if not target:
132             return
133         bokeh_server = None
134         try:
135             bokeh_server = target(*args, **kwargs)
136         finally:
137             if isinstance(bokeh_server, Server):
138                 bokeh_server.stop()
139             if hasattr(self, '_target'):
140                 del self._target, self._args, self._kwargs
141             else:
142                 del self._Thread__target, self._Thread__args, self._Thread__kwargs
143 
144     def stop(self):
145         self._stop_event.set()
146 
147     @property
148     def stopped(self):
149         return self._stop_event.is_set()
150
```

Path: `panel/io/state.py`
Content:
```
1 """
2 Various utilities for recording and embedding state in a rendered app.
3 """
4 from __future__ import absolute_import, division, unicode_literals
5 
6 import threading
7 
8 import param
9 
10 from bokeh.document import Document
11 from bokeh.io import curdoc as _curdoc
12 from pyviz_comms import CommManager as _CommManager
13 
14 
15 class _state(param.Parameterized):
16     """
17     Holds global state associated with running apps, allowing running
18     apps to indicate their state to a user.
19     """
20 
21     _curdoc = param.ClassSelector(class_=Document, doc="""
22         The bokeh Document for which a server event is currently being
23         processed.""")
24 
25     webdriver = param.Parameter(default=None, doc="""
26         Selenium webdriver used to export bokeh models to pngs.""")
27 
28     # Whether to hold comm events
29     _hold = False
30 
31     # Used to ensure that events are not scheduled from the wrong thread
32     _thread_id = None
33 
34     _comm_manager = _CommManager
35 
36     # An index of all currently active views
37     _views = {}
38 
39     # An index of all curently active servers
40     _servers = {}
41 
42     def _unblocked(self, doc):
43         thread = threading.current_thread()
44         thread_id = thread.ident if thread else None
45         return (doc is self.curdoc and self._thread_id == thread_id)
46 
47     @property
48     def curdoc(self):
49         if self._curdoc:
50             return self._curdoc
51         elif _curdoc().session_context:
52             return _curdoc()
53 
54     @curdoc.setter
55     def curdoc(self, doc):
56         self._curdoc = doc
57 
58     @property
59     def session_args(self):
60         return self.curdoc.session_context.request.arguments if self.curdoc else {}
61 
62 
63 state = _state()
64
```
--- 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/panel/io/server.py b/panel/io/server.py
--- a/panel/io/server.py
+++ b/panel/io/server.py
@@ -5,6 +5,7 @@
 
 import signal
 import threading
+import uuid
 
 from functools import partial
 
@@ -77,10 +78,9 @@
             websocket_origin = [websocket_origin]
         opts['allow_websocket_origin'] = websocket_origin
 
-    server_id = kwargs.pop('server_id', None)
+    server_id = kwargs.pop('server_id', uuid.uuid4().hex)
     server = Server({'/': partial(panel._modify_doc, server_id)}, port=port, **opts)
-    if server_id:
-        state._servers[server_id] = (server, panel, [])
+    state._servers[server_id] = (server, panel, [])
 
     if show:
         def show_callback():
diff --git a/panel/io/state.py b/panel/io/state.py
--- a/panel/io/state.py
+++ b/panel/io/state.py
@@ -36,9 +36,23 @@
     # An index of all currently active views
     _views = {}
 
-    # An index of all curently active servers
+    # An index of all currently active servers
     _servers = {}
 
+    def __repr__(self):
+        server_info = []
+        for server, panel, docs in self._servers.values():
+            server_info.append("{}:{:d} - {!r}".format(
+                server.address or "localhost", server.port, panel)
+            )
+        return "state(servers=\n  {}\n)".format(",\n  ".join(server_info))
+
+    def kill_all_servers(self):
+        """Stop all servers and clear them from the current state."""
+        for server_id in self._servers:
+            self._servers[server_id][0].stop()
+        self._servers = {}
+
     def _unblocked(self, doc):
         thread = threading.current_thread()
         thread_id = thread.ident if thread else None

{"golden_diff": "diff --git a/panel/io/server.py b/panel/io/server.py\n--- a/panel/io/server.py\n+++ b/panel/io/server.py\n@@ -5,6 +5,7 @@\n \n import signal\n import threading\n+import uuid\n \n from functools import partial\n \n@@ -77,10 +78,9 @@\n             websocket_origin = [websocket_origin]\n         opts['allow_websocket_origin'] = websocket_origin\n \n-    server_id = kwargs.pop('server_id', None)\n+    server_id = kwargs.pop('server_id', uuid.uuid4().hex)\n     server = Server({'/': partial(panel._modify_doc, server_id)}, port=port, **opts)\n-    if server_id:\n-        state._servers[server_id] = (server, panel, [])\n+    state._servers[server_id] = (server, panel, [])\n \n     if show:\n         def show_callback():\ndiff --git a/panel/io/state.py b/panel/io/state.py\n--- a/panel/io/state.py\n+++ b/panel/io/state.py\n@@ -36,9 +36,23 @@\n     # An index of all currently active views\n     _views = {}\n \n-    # An index of all curently active servers\n+    # An index of all currently active servers\n     _servers = {}\n \n+    def __repr__(self):\n+        server_info = []\n+        for server, panel, docs in self._servers.values():\n+            server_info.append(\"{}:{:d} - {!r}\".format(\n+                server.address or \"localhost\", server.port, panel)\n+            )\n+        return \"state(servers=\\n  {}\\n)\".format(\",\\n  \".join(server_info))\n+\n+    def kill_all_servers(self):\n+        \"\"\"Stop all servers and clear them from the current state.\"\"\"\n+        for server_id in self._servers:\n+            self._servers[server_id][0].stop()\n+        self._servers = {}\n+\n     def _unblocked(self, doc):\n         thread = threading.current_thread()\n         thread_id = thread.ident if thread else None\n", "issue": "Kill all running `.show()` instances?\nI'm using a slightly wacky setup (jupyter-mode in `emacs`) and I end up calling `Pane.show()` a lot. Is there an easy way to kill all previously-created `show()` servers without killing the whole process?\n", "before_files": [{"content": "\"\"\"\nUtilities for creating bokeh Server instances.\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport signal\nimport threading\n\nfrom functools import partial\n\nfrom bokeh.server.server import Server\n\nfrom .state import state\n\n\n#---------------------------------------------------------------------\n# Private API\n#---------------------------------------------------------------------\n\ndef _origin_url(url):\n    if url.startswith(\"http\"):\n        url = url.split(\"//\")[1]\n    return url\n\n\ndef _server_url(url, port):\n    if url.startswith(\"http\"):\n        return '%s:%d%s' % (url.rsplit(':', 1)[0], port, \"/\")\n    else:\n        return 'http://%s:%d%s' % (url.split(':')[0], port, \"/\")\n\n#---------------------------------------------------------------------\n# Public API\n#---------------------------------------------------------------------\n\ndef get_server(panel, port=0, websocket_origin=None, loop=None,\n               show=False, start=False, **kwargs):\n    \"\"\"\n    Returns a Server instance with this panel attached as the root\n    app.\n\n    Arguments\n    ---------\n    port: int (optional, default=0)\n      Allows specifying a specific port\n    websocket_origin: str or list(str) (optional)\n      A list of hosts that can connect to the websocket.\n\n      This is typically required when embedding a server app in\n      an external web site.\n\n      If None, \"localhost\" is used.\n    loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())\n      The tornado IOLoop to run the Server on\n    show : boolean (optional, default=False)\n      Whether to open the server in a new browser tab on start\n    start : boolean(optional, default=False)\n      Whether to start the Server\n    kwargs: dict\n      Additional keyword arguments to pass to Server instance\n\n    Returns\n    -------\n    server : bokeh.server.server.Server\n      Bokeh Server instance running this panel\n    \"\"\"\n    from tornado.ioloop import IOLoop\n    opts = dict(kwargs)\n    if loop:\n        loop.make_current()\n        opts['io_loop'] = loop\n    else:\n        opts['io_loop'] = IOLoop.current()\n\n    if websocket_origin:\n        if not isinstance(websocket_origin, list):\n            websocket_origin = [websocket_origin]\n        opts['allow_websocket_origin'] = websocket_origin\n\n    server_id = kwargs.pop('server_id', None)\n    server = Server({'/': partial(panel._modify_doc, server_id)}, port=port, **opts)\n    if server_id:\n        state._servers[server_id] = (server, panel, [])\n\n    if show:\n        def show_callback():\n            server.show('/')\n        server.io_loop.add_callback(show_callback)\n\n    def sig_exit(*args, **kwargs):\n        server.io_loop.add_callback_from_signal(do_stop)\n\n    def do_stop(*args, **kwargs):\n        server.io_loop.stop()\n\n    try:\n        signal.signal(signal.SIGINT, sig_exit)\n    except ValueError:\n        pass # Can't use signal on a thread\n\n    if start:\n        server.start()\n        try:\n            server.io_loop.start()\n        except RuntimeError:\n            pass\n    return server\n\n\nclass StoppableThread(threading.Thread):\n    \"\"\"Thread class with a stop() method.\"\"\"\n\n    def __init__(self, io_loop=None, timeout=1000, **kwargs):\n        from tornado import ioloop\n        super(StoppableThread, self).__init__(**kwargs)\n        self._stop_event = threading.Event()\n        self.io_loop = io_loop\n        self._cb = ioloop.PeriodicCallback(self._check_stopped, timeout)\n        self._cb.start()\n\n    def _check_stopped(self):\n        if self.stopped:\n            self._cb.stop()\n            self.io_loop.stop()\n\n    def run(self):\n        if hasattr(self, '_target'):\n            target, args, kwargs = self._target, self._args, self._kwargs\n        else:\n            target, args, kwargs = self._Thread__target, self._Thread__args, self._Thread__kwargs\n        if not target:\n            return\n        bokeh_server = None\n        try:\n            bokeh_server = target(*args, **kwargs)\n        finally:\n            if isinstance(bokeh_server, Server):\n                bokeh_server.stop()\n            if hasattr(self, '_target'):\n                del self._target, self._args, self._kwargs\n            else:\n                del self._Thread__target, self._Thread__args, self._Thread__kwargs\n\n    def stop(self):\n        self._stop_event.set()\n\n    @property\n    def stopped(self):\n        return self._stop_event.is_set()\n", "path": "panel/io/server.py"}, {"content": "\"\"\"\nVarious utilities for recording and embedding state in a rendered app.\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport threading\n\nimport param\n\nfrom bokeh.document import Document\nfrom bokeh.io import curdoc as _curdoc\nfrom pyviz_comms import CommManager as _CommManager\n\n\nclass _state(param.Parameterized):\n    \"\"\"\n    Holds global state associated with running apps, allowing running\n    apps to indicate their state to a user.\n    \"\"\"\n\n    _curdoc = param.ClassSelector(class_=Document, doc=\"\"\"\n        The bokeh Document for which a server event is currently being\n        processed.\"\"\")\n\n    webdriver = param.Parameter(default=None, doc=\"\"\"\n        Selenium webdriver used to export bokeh models to pngs.\"\"\")\n\n    # Whether to hold comm events\n    _hold = False\n\n    # Used to ensure that events are not scheduled from the wrong thread\n    _thread_id = None\n\n    _comm_manager = _CommManager\n\n    # An index of all currently active views\n    _views = {}\n\n    # An index of all curently active servers\n    _servers = {}\n\n    def _unblocked(self, doc):\n        thread = threading.current_thread()\n        thread_id = thread.ident if thread else None\n        return (doc is self.curdoc and self._thread_id == thread_id)\n\n    @property\n    def curdoc(self):\n        if self._curdoc:\n            return self._curdoc\n        elif _curdoc().session_context:\n            return _curdoc()\n\n    @curdoc.setter\n    def curdoc(self, doc):\n        self._curdoc = doc\n\n    @property\n    def session_args(self):\n        return self.curdoc.session_context.request.arguments if self.curdoc else {}\n\n\nstate = _state()\n", "path": "panel/io/state.py"}], "after_files": [{"content": "\"\"\"\nUtilities for creating bokeh Server instances.\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport signal\nimport threading\nimport uuid\n\nfrom functools import partial\n\nfrom bokeh.server.server import Server\n\nfrom .state import state\n\n\n#---------------------------------------------------------------------\n# Private API\n#---------------------------------------------------------------------\n\ndef _origin_url(url):\n    if url.startswith(\"http\"):\n        url = url.split(\"//\")[1]\n    return url\n\n\ndef _server_url(url, port):\n    if url.startswith(\"http\"):\n        return '%s:%d%s' % (url.rsplit(':', 1)[0], port, \"/\")\n    else:\n        return 'http://%s:%d%s' % (url.split(':')[0], port, \"/\")\n\n#---------------------------------------------------------------------\n# Public API\n#---------------------------------------------------------------------\n\ndef get_server(panel, port=0, websocket_origin=None, loop=None,\n               show=False, start=False, **kwargs):\n    \"\"\"\n    Returns a Server instance with this panel attached as the root\n    app.\n\n    Arguments\n    ---------\n    port: int (optional, default=0)\n      Allows specifying a specific port\n    websocket_origin: str or list(str) (optional)\n      A list of hosts that can connect to the websocket.\n\n      This is typically required when embedding a server app in\n      an external web site.\n\n      If None, \"localhost\" is used.\n    loop : tornado.ioloop.IOLoop (optional, default=IOLoop.current())\n      The tornado IOLoop to run the Server on\n    show : boolean (optional, default=False)\n      Whether to open the server in a new browser tab on start\n    start : boolean(optional, default=False)\n      Whether to start the Server\n    kwargs: dict\n      Additional keyword arguments to pass to Server instance\n\n    Returns\n    -------\n    server : bokeh.server.server.Server\n      Bokeh Server instance running this panel\n    \"\"\"\n    from tornado.ioloop import IOLoop\n    opts = dict(kwargs)\n    if loop:\n        loop.make_current()\n        opts['io_loop'] = loop\n    else:\n        opts['io_loop'] = IOLoop.current()\n\n    if websocket_origin:\n        if not isinstance(websocket_origin, list):\n            websocket_origin = [websocket_origin]\n        opts['allow_websocket_origin'] = websocket_origin\n\n    server_id = kwargs.pop('server_id', uuid.uuid4().hex)\n    server = Server({'/': partial(panel._modify_doc, server_id)}, port=port, **opts)\n    state._servers[server_id] = (server, panel, [])\n\n    if show:\n        def show_callback():\n            server.show('/')\n        server.io_loop.add_callback(show_callback)\n\n    def sig_exit(*args, **kwargs):\n        server.io_loop.add_callback_from_signal(do_stop)\n\n    def do_stop(*args, **kwargs):\n        server.io_loop.stop()\n\n    try:\n        signal.signal(signal.SIGINT, sig_exit)\n    except ValueError:\n        pass # Can't use signal on a thread\n\n    if start:\n        server.start()\n        try:\n            server.io_loop.start()\n        except RuntimeError:\n            pass\n    return server\n\n\nclass StoppableThread(threading.Thread):\n    \"\"\"Thread class with a stop() method.\"\"\"\n\n    def __init__(self, io_loop=None, timeout=1000, **kwargs):\n        from tornado import ioloop\n        super(StoppableThread, self).__init__(**kwargs)\n        self._stop_event = threading.Event()\n        self.io_loop = io_loop\n        self._cb = ioloop.PeriodicCallback(self._check_stopped, timeout)\n        self._cb.start()\n\n    def _check_stopped(self):\n        if self.stopped:\n            self._cb.stop()\n            self.io_loop.stop()\n\n    def run(self):\n        if hasattr(self, '_target'):\n            target, args, kwargs = self._target, self._args, self._kwargs\n        else:\n            target, args, kwargs = self._Thread__target, self._Thread__args, self._Thread__kwargs\n        if not target:\n            return\n        bokeh_server = None\n        try:\n            bokeh_server = target(*args, **kwargs)\n        finally:\n            if isinstance(bokeh_server, Server):\n                bokeh_server.stop()\n            if hasattr(self, '_target'):\n                del self._target, self._args, self._kwargs\n            else:\n                del self._Thread__target, self._Thread__args, self._Thread__kwargs\n\n    def stop(self):\n        self._stop_event.set()\n\n    @property\n    def stopped(self):\n        return self._stop_event.is_set()\n", "path": "panel/io/server.py"}, {"content": "\"\"\"\nVarious utilities for recording and embedding state in a rendered app.\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nimport threading\n\nimport param\n\nfrom bokeh.document import Document\nfrom bokeh.io import curdoc as _curdoc\nfrom pyviz_comms import CommManager as _CommManager\n\n\nclass _state(param.Parameterized):\n    \"\"\"\n    Holds global state associated with running apps, allowing running\n    apps to indicate their state to a user.\n    \"\"\"\n\n    _curdoc = param.ClassSelector(class_=Document, doc=\"\"\"\n        The bokeh Document for which a server event is currently being\n        processed.\"\"\")\n\n    webdriver = param.Parameter(default=None, doc=\"\"\"\n        Selenium webdriver used to export bokeh models to pngs.\"\"\")\n\n    # Whether to hold comm events\n    _hold = False\n\n    # Used to ensure that events are not scheduled from the wrong thread\n    _thread_id = None\n\n    _comm_manager = _CommManager\n\n    # An index of all currently active views\n    _views = {}\n\n    # An index of all currently active servers\n    _servers = {}\n\n    def __repr__(self):\n        server_info = []\n        for server, panel, docs in self._servers.values():\n            server_info.append(\"{}:{:d} - {!r}\".format(\n                server.address or \"localhost\", server.port, panel)\n            )\n        return \"state(servers=\\n  {}\\n)\".format(\",\\n  \".join(server_info))\n\n    def kill_all_servers(self):\n        \"\"\"Stop all servers and clear them from the current state.\"\"\"\n        for server_id in self._servers:\n            self._servers[server_id][0].stop()\n        self._servers = {}\n\n    def _unblocked(self, doc):\n        thread = threading.current_thread()\n        thread_id = thread.ident if thread else None\n        return (doc is self.curdoc and self._thread_id == thread_id)\n\n    @property\n    def curdoc(self):\n        if self._curdoc:\n            return self._curdoc\n        elif _curdoc().session_context:\n            return _curdoc()\n\n    @curdoc.setter\n    def curdoc(self, doc):\n        self._curdoc = doc\n\n    @property\n    def session_args(self):\n        return self.curdoc.session_context.request.arguments if self.curdoc else {}\n\n\nstate = _state()\n", "path": "panel/io/state.py"}]}