We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bokeh cannot serve notebooks on Python 2
Using a notebook containing a single code cell (simply  `1+1`) in a Python 2 environment: 

`bokeh serve --show Test.ipynb`

Results in the following error:

```
SyntaxError: encoding declaration in Unicode string
```

Note that this is why the unit tests added in #8546 skip for Python 2.




--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `bokeh/application/handlers/notebook.py`
Content:
```
1 #-----------------------------------------------------------------------------
2 # Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.
3 # All rights reserved.
4 #
5 # The full license is in the file LICENSE.txt, distributed with this software.
6 #-----------------------------------------------------------------------------
7 ''' Provide a Bokeh Application Handler to build up documents by running
8 the code from Jupyter notebook (``.ipynb``) files.
9 
10 This handler is configured with the filename of a Jupyter notebook. When a
11 Bokeh application calls ``modify_doc``, the code from all the notebook cells
12 is collected and executed to process a new Document for a session. When the
13 notebook code is executed, the Document being modified will be available as
14 ``curdoc``, and any optionally provided ``args`` will be available as
15 ``sys.argv``.
16 
17 '''
18 
19 #-----------------------------------------------------------------------------
20 # Boilerplate
21 #-----------------------------------------------------------------------------
22 from __future__ import absolute_import, division, print_function, unicode_literals
23 
24 import re
25 import logging
26 log = logging.getLogger(__name__)
27 
28 #-----------------------------------------------------------------------------
29 # Imports
30 #-----------------------------------------------------------------------------
31 
32 # Standard library imports
33 
34 # External imports
35 
36 # Bokeh imports
37 from ...util.dependencies import import_required
38 from .code import CodeHandler
39 
40 #-----------------------------------------------------------------------------
41 # Globals and constants
42 #-----------------------------------------------------------------------------
43 
44 __all__ = (
45     'NotebookHandler',
46 )
47 
48 #-----------------------------------------------------------------------------
49 # General API
50 #-----------------------------------------------------------------------------
51 
52 #-----------------------------------------------------------------------------
53 # Dev API
54 #-----------------------------------------------------------------------------
55 
56 class NotebookHandler(CodeHandler):
57     ''' A Handler that uses code in a Jupyter notebook for modifying Bokeh
58     Documents.
59 
60     '''
61 
62     _logger_text = "%s: call to %s() ignored when running notebooks with the 'bokeh' command."
63 
64     _origin = "Notebook"
65 
66     def __init__(self, *args, **kwargs):
67         '''
68 
69         Keywords:
70             filename (str) : a path to a Jupyter notebook (".ipynb") file
71 
72         '''
73         nbformat = import_required('nbformat', 'The Bokeh notebook application handler requires Jupyter Notebook to be installed.')
74         nbconvert = import_required('nbconvert', 'The Bokeh notebook application handler requires Jupyter Notebook to be installed.')
75 
76         if 'filename' not in kwargs:
77             raise ValueError('Must pass a filename to NotebookHandler')
78 
79 
80         class StripMagicsProcessor(nbconvert.preprocessors.Preprocessor):
81             """
82             Preprocessor to convert notebooks to Python source while stripping
83             out all magics (i.e IPython specific syntax).
84             """
85 
86             _magic_pattern = re.compile('^\s*(?P<magic>%%\w\w+)($|(\s+))')
87 
88             def strip_magics(self, source):
89                 """
90                 Given the source of a cell, filter out all cell and line magics.
91                 """
92                 filtered=[]
93                 for line in source.splitlines():
94                     match = self._magic_pattern.match(line)
95                     if match is None:
96                         filtered.append(line)
97                     else:
98                         msg = 'Stripping out IPython magic {magic} in code cell {cell}'
99                         message = msg.format(cell=self._cell_counter, magic=match.group('magic'))
100                         log.warn(message)
101                 return '\n'.join(filtered)
102 
103             def preprocess_cell(self, cell, resources, index):
104                 if cell['cell_type'] == 'code':
105                     self._cell_counter += 1
106                     cell['source'] = self.strip_magics(cell['source'])
107                 return cell, resources
108 
109             def __call__(self, nb, resources):
110                 self._cell_counter = 0
111                 return self.preprocess(nb,resources)
112 
113         preprocessors=[StripMagicsProcessor()]
114         filename = kwargs['filename']
115 
116         with open(filename) as f:
117             nb = nbformat.read(f, nbformat.NO_CONVERT)
118             exporter = nbconvert.PythonExporter()
119 
120             for preprocessor in preprocessors:
121                 exporter.register_preprocessor(preprocessor)
122 
123             source, _ = exporter.from_notebook_node(nb)
124             source = source.replace('get_ipython().run_line_magic', '')
125             kwargs['source'] = source
126 
127         super(NotebookHandler, self).__init__(*args, **kwargs)
128 
129 #-----------------------------------------------------------------------------
130 # Private API
131 #-----------------------------------------------------------------------------
132 
133 #-----------------------------------------------------------------------------
134 # Code
135 #-----------------------------------------------------------------------------
136
```
--- 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/bokeh/application/handlers/notebook.py b/bokeh/application/handlers/notebook.py
--- a/bokeh/application/handlers/notebook.py
+++ b/bokeh/application/handlers/notebook.py
@@ -22,6 +22,7 @@
 from __future__ import absolute_import, division, print_function, unicode_literals
 
 import re
+import sys
 import logging
 log = logging.getLogger(__name__)
 
@@ -122,6 +123,9 @@
 
             source, _ = exporter.from_notebook_node(nb)
             source = source.replace('get_ipython().run_line_magic', '')
+            source = source.replace('get_ipython().magic', '')
+            if sys.version_info.major == 2:
+                source = source.replace('# coding: utf-8','')
             kwargs['source'] = source
 
         super(NotebookHandler, self).__init__(*args, **kwargs)

{"golden_diff": "diff --git a/bokeh/application/handlers/notebook.py b/bokeh/application/handlers/notebook.py\n--- a/bokeh/application/handlers/notebook.py\n+++ b/bokeh/application/handlers/notebook.py\n@@ -22,6 +22,7 @@\n from __future__ import absolute_import, division, print_function, unicode_literals\n \n import re\n+import sys\n import logging\n log = logging.getLogger(__name__)\n \n@@ -122,6 +123,9 @@\n \n             source, _ = exporter.from_notebook_node(nb)\n             source = source.replace('get_ipython().run_line_magic', '')\n+            source = source.replace('get_ipython().magic', '')\n+            if sys.version_info.major == 2:\n+                source = source.replace('# coding: utf-8','')\n             kwargs['source'] = source\n \n         super(NotebookHandler, self).__init__(*args, **kwargs)\n", "issue": "Bokeh cannot serve notebooks on Python 2\nUsing a notebook containing a single code cell (simply  `1+1`) in a Python 2 environment: \r\n\r\n`bokeh serve --show Test.ipynb`\r\n\r\nResults in the following error:\r\n\r\n```\r\nSyntaxError: encoding declaration in Unicode string\r\n```\r\n\r\nNote that this is why the unit tests added in #8546 skip for Python 2.\r\n\r\n\r\n\n", "before_files": [{"content": "#-----------------------------------------------------------------------------\n# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.\n# All rights reserved.\n#\n# The full license is in the file LICENSE.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n''' Provide a Bokeh Application Handler to build up documents by running\nthe code from Jupyter notebook (``.ipynb``) files.\n\nThis handler is configured with the filename of a Jupyter notebook. When a\nBokeh application calls ``modify_doc``, the code from all the notebook cells\nis collected and executed to process a new Document for a session. When the\nnotebook code is executed, the Document being modified will be available as\n``curdoc``, and any optionally provided ``args`` will be available as\n``sys.argv``.\n\n'''\n\n#-----------------------------------------------------------------------------\n# Boilerplate\n#-----------------------------------------------------------------------------\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport re\nimport logging\nlog = logging.getLogger(__name__)\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Standard library imports\n\n# External imports\n\n# Bokeh imports\nfrom ...util.dependencies import import_required\nfrom .code import CodeHandler\n\n#-----------------------------------------------------------------------------\n# Globals and constants\n#-----------------------------------------------------------------------------\n\n__all__ = (\n    'NotebookHandler',\n)\n\n#-----------------------------------------------------------------------------\n# General API\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Dev API\n#-----------------------------------------------------------------------------\n\nclass NotebookHandler(CodeHandler):\n    ''' A Handler that uses code in a Jupyter notebook for modifying Bokeh\n    Documents.\n\n    '''\n\n    _logger_text = \"%s: call to %s() ignored when running notebooks with the 'bokeh' command.\"\n\n    _origin = \"Notebook\"\n\n    def __init__(self, *args, **kwargs):\n        '''\n\n        Keywords:\n            filename (str) : a path to a Jupyter notebook (\".ipynb\") file\n\n        '''\n        nbformat = import_required('nbformat', 'The Bokeh notebook application handler requires Jupyter Notebook to be installed.')\n        nbconvert = import_required('nbconvert', 'The Bokeh notebook application handler requires Jupyter Notebook to be installed.')\n\n        if 'filename' not in kwargs:\n            raise ValueError('Must pass a filename to NotebookHandler')\n\n\n        class StripMagicsProcessor(nbconvert.preprocessors.Preprocessor):\n            \"\"\"\n            Preprocessor to convert notebooks to Python source while stripping\n            out all magics (i.e IPython specific syntax).\n            \"\"\"\n\n            _magic_pattern = re.compile('^\\s*(?P<magic>%%\\w\\w+)($|(\\s+))')\n\n            def strip_magics(self, source):\n                \"\"\"\n                Given the source of a cell, filter out all cell and line magics.\n                \"\"\"\n                filtered=[]\n                for line in source.splitlines():\n                    match = self._magic_pattern.match(line)\n                    if match is None:\n                        filtered.append(line)\n                    else:\n                        msg = 'Stripping out IPython magic {magic} in code cell {cell}'\n                        message = msg.format(cell=self._cell_counter, magic=match.group('magic'))\n                        log.warn(message)\n                return '\\n'.join(filtered)\n\n            def preprocess_cell(self, cell, resources, index):\n                if cell['cell_type'] == 'code':\n                    self._cell_counter += 1\n                    cell['source'] = self.strip_magics(cell['source'])\n                return cell, resources\n\n            def __call__(self, nb, resources):\n                self._cell_counter = 0\n                return self.preprocess(nb,resources)\n\n        preprocessors=[StripMagicsProcessor()]\n        filename = kwargs['filename']\n\n        with open(filename) as f:\n            nb = nbformat.read(f, nbformat.NO_CONVERT)\n            exporter = nbconvert.PythonExporter()\n\n            for preprocessor in preprocessors:\n                exporter.register_preprocessor(preprocessor)\n\n            source, _ = exporter.from_notebook_node(nb)\n            source = source.replace('get_ipython().run_line_magic', '')\n            kwargs['source'] = source\n\n        super(NotebookHandler, self).__init__(*args, **kwargs)\n\n#-----------------------------------------------------------------------------\n# Private API\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Code\n#-----------------------------------------------------------------------------\n", "path": "bokeh/application/handlers/notebook.py"}], "after_files": [{"content": "#-----------------------------------------------------------------------------\n# Copyright (c) 2012 - 2019, Anaconda, Inc., and Bokeh Contributors.\n# All rights reserved.\n#\n# The full license is in the file LICENSE.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n''' Provide a Bokeh Application Handler to build up documents by running\nthe code from Jupyter notebook (``.ipynb``) files.\n\nThis handler is configured with the filename of a Jupyter notebook. When a\nBokeh application calls ``modify_doc``, the code from all the notebook cells\nis collected and executed to process a new Document for a session. When the\nnotebook code is executed, the Document being modified will be available as\n``curdoc``, and any optionally provided ``args`` will be available as\n``sys.argv``.\n\n'''\n\n#-----------------------------------------------------------------------------\n# Boilerplate\n#-----------------------------------------------------------------------------\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport re\nimport sys\nimport logging\nlog = logging.getLogger(__name__)\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\n\n# Standard library imports\n\n# External imports\n\n# Bokeh imports\nfrom ...util.dependencies import import_required\nfrom .code import CodeHandler\n\n#-----------------------------------------------------------------------------\n# Globals and constants\n#-----------------------------------------------------------------------------\n\n__all__ = (\n    'NotebookHandler',\n)\n\n#-----------------------------------------------------------------------------\n# General API\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Dev API\n#-----------------------------------------------------------------------------\n\nclass NotebookHandler(CodeHandler):\n    ''' A Handler that uses code in a Jupyter notebook for modifying Bokeh\n    Documents.\n\n    '''\n\n    _logger_text = \"%s: call to %s() ignored when running notebooks with the 'bokeh' command.\"\n\n    _origin = \"Notebook\"\n\n    def __init__(self, *args, **kwargs):\n        '''\n\n        Keywords:\n            filename (str) : a path to a Jupyter notebook (\".ipynb\") file\n\n        '''\n        nbformat = import_required('nbformat', 'The Bokeh notebook application handler requires Jupyter Notebook to be installed.')\n        nbconvert = import_required('nbconvert', 'The Bokeh notebook application handler requires Jupyter Notebook to be installed.')\n\n        if 'filename' not in kwargs:\n            raise ValueError('Must pass a filename to NotebookHandler')\n\n\n        class StripMagicsProcessor(nbconvert.preprocessors.Preprocessor):\n            \"\"\"\n            Preprocessor to convert notebooks to Python source while stripping\n            out all magics (i.e IPython specific syntax).\n            \"\"\"\n\n            _magic_pattern = re.compile('^\\s*(?P<magic>%%\\w\\w+)($|(\\s+))')\n\n            def strip_magics(self, source):\n                \"\"\"\n                Given the source of a cell, filter out all cell and line magics.\n                \"\"\"\n                filtered=[]\n                for line in source.splitlines():\n                    match = self._magic_pattern.match(line)\n                    if match is None:\n                        filtered.append(line)\n                    else:\n                        msg = 'Stripping out IPython magic {magic} in code cell {cell}'\n                        message = msg.format(cell=self._cell_counter, magic=match.group('magic'))\n                        log.warn(message)\n                return '\\n'.join(filtered)\n\n            def preprocess_cell(self, cell, resources, index):\n                if cell['cell_type'] == 'code':\n                    self._cell_counter += 1\n                    cell['source'] = self.strip_magics(cell['source'])\n                return cell, resources\n\n            def __call__(self, nb, resources):\n                self._cell_counter = 0\n                return self.preprocess(nb,resources)\n\n        preprocessors=[StripMagicsProcessor()]\n        filename = kwargs['filename']\n\n        with open(filename) as f:\n            nb = nbformat.read(f, nbformat.NO_CONVERT)\n            exporter = nbconvert.PythonExporter()\n\n            for preprocessor in preprocessors:\n                exporter.register_preprocessor(preprocessor)\n\n            source, _ = exporter.from_notebook_node(nb)\n            source = source.replace('get_ipython().run_line_magic', '')\n            source = source.replace('get_ipython().magic', '')\n            if sys.version_info.major == 2:\n                source = source.replace('# coding: utf-8','')\n            kwargs['source'] = source\n\n        super(NotebookHandler, self).__init__(*args, **kwargs)\n\n#-----------------------------------------------------------------------------\n# Private API\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Code\n#-----------------------------------------------------------------------------\n", "path": "bokeh/application/handlers/notebook.py"}]}