internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: bokeh/bokeh

Issue:
Compat: Get correct env when freezing with cx_Freeze
Anaconda Python 3.6 bokeh 0.13.0
Pip cx-Freeze 5.1.1
OS Windows

#### Expected behaviour
Freezing with cx-Freeze works for bokeh.

#### Actual behaviour
Exception is raised
```
AttributeError: module 'sys' has no attribute '_MEIPASS'
```

#### Bug description
When freezing with cx_Freeze `sys.frozen` is `True`. It does not define `sys._MEIPASS` though. `sys._MEIPASS` is only used by the PyInstaller freezer.

I prepared a patch in #8324.




Discussion:

Resolving patch:
diff --git a/bokeh/core/templates.py b/bokeh/core/templates.py
--- a/bokeh/core/templates.py
+++ b/bokeh/core/templates.py
@@ -25,12 +25,14 @@
 def get_env():
     ''' Get the correct Jinja2 Environment, also for frozen scripts.
     '''
-    if getattr(sys, 'frozen', False):
+    if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
+        # PyInstaller uses _MEIPASS and only works with jinja2.FileSystemLoader
         templates_path = join(sys._MEIPASS, 'bokeh', 'core', '_templates')
-        return Environment(loader=FileSystemLoader(templates_path))
     else:
+        # Non-frozen Python and cx_Freeze can use __file__ directly
         templates_path = join(dirname(__file__), '_templates')
-        return Environment(loader=FileSystemLoader(templates_path))
+
+    return Environment(loader=FileSystemLoader(templates_path))
 
 _env = get_env()
 _env.filters['json'] = lambda obj: Markup(json.dumps(obj))


Test patch:
Repository: bokeh/bokeh

Issue:
Garbage collection of export_png() 
I am using export_png() for producing images.  However, the phamtonjs process does not go away when program is fiished.  After running the program for few times, I need to clean the phamtonjs process before it eat up all memory.  

Therefore, I am writing to ask a possible way to do garbage collection after export_png() is done.  




Discussion:
I've noticed the same thing. In holoviews we use static export to generate thumbnails for our examples, and when building the docs I end up with about 100 phantomjs processes, which use an inordinate amount of CPU.
My solution is a little bit ugly.  I did something like this.

```
   # Garbage collection for Phantomjs.  This is because it produce one process after export_png()
    p = subprocess.Popen(['ps', '-A'], stdout=subprocess.PIPE)
    out, err = p.communicate()

    for line in out.splitlines():
        if b'phantom' in line:
            pid = int(line.split(None, 1)[0])
            os.kill(pid, signal.SIGKILL)    
```

So, I believe there is a way to fix the issue.
Issue #6525 seems related.
This seems to be a regression after PR #8329.

Resolving patch:
diff --git a/bokeh/io/webdriver.py b/bokeh/io/webdriver.py
--- a/bokeh/io/webdriver.py
+++ b/bokeh/io/webdriver.py
@@ -22,6 +22,7 @@
 #-----------------------------------------------------------------------------
 
 # Standard library imports
+import atexit
 import signal
 import warnings
 from os.path import devnull
@@ -125,3 +126,5 @@ def kind(self, value):
 
 
 webdriver_control = _WebdriverState()
+
+atexit.register(lambda: webdriver_control.reset())


Test patch:
Repository: bokeh/bokeh

Issue:
Fix failing codebase tests
For some reason `except E as e` without usage of `e`, is now failing (as it should).


Discussion:

Resolving patch:
diff --git a/bokeh/core/property/bases.py b/bokeh/core/property/bases.py
--- a/bokeh/core/property/bases.py
+++ b/bokeh/core/property/bases.py
@@ -303,7 +303,7 @@ def is_valid(self, value):
         try:
             if validation_on():
                 self.validate(value, False)
-        except ValueError as e:
+        except ValueError:
             return False
         else:
             return True
diff --git a/scripts/deploy.py b/scripts/deploy.py
--- a/scripts/deploy.py
+++ b/scripts/deploy.py
@@ -428,7 +428,7 @@ def merge_and_push():
     try:
         out = run("git checkout master")
         passed("Returned to master branch")
-    except Exception as e:
+    except Exception:
         failed("[NON-FATAL] Could not return to master branch", out.split("\n"))
 
     return True


Test patch:
Repository: bokeh/bokeh

Issue:
Typo in documentation of io.export.create_webdriver

**Version**: Bokeh 1.0.1

Documentation of `io.export.create_webdriver` has a formatting typo and a spelling error

#### Complete, minimal, self-contained example code that reproduces the issue

```python
>>> from bokeh.io.export import create_webdriver
>>> help(create_webdriver)

create_webdriver()
    Create a new webdriver.
    
    ..note ::
        Here for compatiboility. Prefer methods on the webdriver_control
        object.
```



Discussion:

Resolving patch:
diff --git a/bokeh/io/export.py b/bokeh/io/export.py
--- a/bokeh/io/export.py
+++ b/bokeh/io/export.py
@@ -164,8 +164,8 @@ def export_svgs(obj, filename=None, height=None, width=None, webdriver=None):
 def create_webdriver():
     ''' Create a new webdriver.
 
-    ..note ::
-        Here for compatiboility. Prefer methods on the webdriver_control
+    .. note ::
+        Here for compatibility. Prefer methods on the webdriver_control
         object.
 
     '''


Test patch:
Repository: bokeh/bokeh

Issue:
Feature request: add support for setting the DataTable row height
The current implementation of `DataTable` does not allow the user to override the default row height (25px).  This has been requested a few times on in the google group ([here](https://groups.google.com/a/continuum.io/forum/#!searchin/bokeh/datatable$20row$20height|sort:date/bokeh/QLCbnzX1cFY/uWZUxDAEBAAJ) and [here](https://groups.google.com/a/continuum.io/forum/#!searchin/bokeh/datatable$20row$20height|sort:date/bokeh/ItFqOH3iRac/Pr2T58K2AgAJ)).  It doesn't seem to be solvable with custom CSS.  SlickGrid does expose `rowHeight` as a [grid option](https://github.com/6pac/SlickGrid/wiki/Grid-Options).

I'll make a PR to add this option.


Discussion:
Just to provide a little more detail, I'm proposing to add an attribute `row_height` to the `DataTable` class.  The default value would be 25 (pixels) which matches the default in SlickGrid.

Resolving patch:
diff --git a/bokeh/models/widgets/tables.py b/bokeh/models/widgets/tables.py
--- a/bokeh/models/widgets/tables.py
+++ b/bokeh/models/widgets/tables.py
@@ -576,3 +576,7 @@ class DataTable(TableWidget):
     """)
 
     height = Override(default=400)
+
+    row_height = Int(25, help="""
+    The height of each row in pixels.
+    """)
diff --git a/examples/integration/widgets/data_table_customization.py b/examples/integration/widgets/data_table_customization.py
new file mode 100644
--- /dev/null
+++ b/examples/integration/widgets/data_table_customization.py
@@ -0,0 +1,26 @@
+from bokeh.io import save
+from bokeh.models import ColumnDataSource
+from bokeh.models.widgets import DataTable, TableColumn, HTMLTemplateFormatter
+
+from bokeh.sampledata.periodic_table import elements
+
+elements['name_lower'] = elements['name'].str.lower()
+source = ColumnDataSource(elements)
+
+html_font_template = '<font color="<%= CPK %>"><%= value %></font>'
+html_image_template = """
+<a href="http://images-of-elements.com/<%= value %>.php" target="_blank">
+  <img src="http://images-of-elements.com/<%= value %>.jpg" style="width:40px;height:40px;border:0">
+</a>
+"""
+columns = [
+    TableColumn(field='atomic number', title='Atomic Number'),
+    TableColumn(field='symbol', title='Symbol'),
+    TableColumn(field='name', title='Name',
+                formatter=HTMLTemplateFormatter(template=html_font_template)),
+    TableColumn(field='name_lower', title='Image',
+                formatter=HTMLTemplateFormatter(template=html_image_template))
+]
+data_table = DataTable(source=source, columns=columns, editable=False, row_height=45)
+
+save(data_table)


Test patch:
Repository: bokeh/bokeh

Issue:
Make components() preserve the type of dict
For example, if `OrderedDict` is given as an argument, the result should be the same kind of dict with order preserved. This should finally fix flaky `embed/embed_multiple` example.


Discussion:

Resolving patch:
diff --git a/bokeh/embed/standalone.py b/bokeh/embed/standalone.py
--- a/bokeh/embed/standalone.py
+++ b/bokeh/embed/standalone.py
@@ -209,8 +209,10 @@ def components(models, wrap_script=True, wrap_plot_info=True, theme=FromCurdoc):
 
     # now convert dict to list, saving keys in the same order
     model_keys = None
+    dict_type = None
     if isinstance(models, dict):
         model_keys = models.keys()
+        dict_type = models.__class__
         values = []
         # don't just use .values() to ensure we are in the same order as key list
         for k in model_keys:
@@ -238,14 +240,13 @@ def div_for_root(root):
     # 3) convert back to the input shape
 
     if was_single_object:
-        return script, results[0]
+        result = results[0]
     elif model_keys is not None:
-        result = {}
-        for (key, value) in zip(model_keys, results):
-            result[key] = value
-        return script, result
+        result = dict_type(zip(model_keys, results))
     else:
-        return script, tuple(results)
+        result = tuple(results)
+
+    return script, result
 
 def file_html(models,
               resources,


Test patch:
diff --git a/bokeh/embed/tests/test_standalone.py b/bokeh/embed/tests/test_standalone.py
--- a/bokeh/embed/tests/test_standalone.py
+++ b/bokeh/embed/tests/test_standalone.py
@@ -19,6 +19,7 @@
 
 # Standard library imports
 from mock import patch
+from collections import OrderedDict
 
 # External imports
 import bs4
@@ -95,6 +96,10 @@ def test_return_type(self):
         assert isinstance(divs, dict)
         assert all(isinstance(x, string_types) for x in divs.keys())
 
+        _, divs = bes.components(OrderedDict([("Plot 1", plot1), ("Plot 2", plot2)]))
+        assert isinstance(divs, OrderedDict)
+        assert all(isinstance(x, string_types) for x in divs.keys())
+
     @patch('bokeh.embed.util.make_globally_unique_id', new_callable=lambda: stable_id)
     def test_plot_dict_returned_when_wrap_plot_info_is_false(self, mock_make_id):
         doc = Document()
Repository: bokeh/bokeh

Issue:
Typo in range_tool example
There is a small typo "range_rool" in the range_tool.py example. I would like to use this issue to create my first pull request and see how the process works.


Discussion:

Resolving patch:
diff --git a/examples/plotting/file/range_tool.py b/examples/plotting/file/range_tool.py
--- a/examples/plotting/file/range_tool.py
+++ b/examples/plotting/file/range_tool.py
@@ -21,13 +21,13 @@
                 x_axis_type="datetime", y_axis_type=None,
                 tools="", toolbar_location=None, background_fill_color="#efefef")
 
-range_rool = RangeTool(x_range=p.x_range)
-range_rool.overlay.fill_color = "navy"
-range_rool.overlay.fill_alpha = 0.2
+range_tool = RangeTool(x_range=p.x_range)
+range_tool.overlay.fill_color = "navy"
+range_tool.overlay.fill_alpha = 0.2
 
 select.line('date', 'close', source=source)
 select.ygrid.grid_line_color = None
-select.add_tools(range_rool)
-select.toolbar.active_multi = range_rool
+select.add_tools(range_tool)
+select.toolbar.active_multi = range_tool
 
 show(column(p, select))


Test patch:
Repository: bokeh/bokeh

Issue:
Docs tweak to add note about BOKEH_DEV and apps
Make clearer need to change BOKEH_RESOURCES too.


Discussion:
Like I mentioned I don't really use it, but I'm fairly sure the intended usage of `BOKEH_DEV=True` is to have `bokeh static` running at the same time, so that BokehJS resources will be loaded from there. 

Resolving patch:
diff --git a/bokeh/resources.py b/bokeh/resources.py
--- a/bokeh/resources.py
+++ b/bokeh/resources.py
@@ -516,5 +516,8 @@ def mk_url(comp, kind):
 
 __all__ = (
     'CDN',
-    'INLINE'
+    'INLINE',
+    'Resources',
+    'JSResources',
+    'CSSResources',
 )


Test patch:
Repository: bokeh/bokeh

Issue:
pyyaml version is vulnerable to CVE-2017-18342
The pyyaml version specified [here](https://github.com/bokeh/bokeh/blob/master/setup.py#L91) is vulnerable to to [CVE-2017-18342](https://nvd.nist.gov/vuln/detail/CVE-2017-18342). 

![screen shot 2019-01-07 at 10 26 29](https://user-images.githubusercontent.com/30386655/50763100-c904a600-1266-11e9-87ad-2066d5d71931.png)

Can this be upgraded without issue?


Discussion:
It's unclear. The latest version of pyyaml on both PyPI and conda default repositories is 3.13. Evidently the project was taken over by an entirely new team, though I can't find any release of it under the same name.
Looks like 4.2 is not available yet: https://github.com/yaml/pyyaml/issues/193 We are certainly happy to move on this as soon as a release is available


Resolving patch:
diff --git a/bokeh/themes/theme.py b/bokeh/themes/theme.py
--- a/bokeh/themes/theme.py
+++ b/bokeh/themes/theme.py
@@ -128,7 +128,7 @@ def __init__(self, filename=None, json=None):
         if filename is not None:
             f = open(filename)
             try:
-                json = yaml.load(f)
+                json = yaml.safe_load(f)
                 # empty docs result in None rather than {}, fix it.
                 if json is None:
                     json = {}
diff --git a/bokeh/util/sampledata.py b/bokeh/util/sampledata.py
--- a/bokeh/util/sampledata.py
+++ b/bokeh/util/sampledata.py
@@ -106,7 +106,7 @@ def external_data_dir(create=False):
     data_dir = join(bokeh_dir, "data")
 
     try:
-        config = yaml.load(open(join(bokeh_dir, 'config')))
+        config = yaml.safe_load(open(join(bokeh_dir, 'config')))
         data_dir = expanduser(config['sampledata_dir'])
     except (IOError, TypeError):
         pass


Test patch:
diff --git a/bokeh/_testing/util/examples.py b/bokeh/_testing/util/examples.py
--- a/bokeh/_testing/util/examples.py
+++ b/bokeh/_testing/util/examples.py
@@ -263,7 +263,7 @@ def collect_examples(config_path):
     list_of_examples = []
 
     with open(config_path, "r") as f:
-        examples = yaml.load(f.read())
+        examples = yaml.safe_load(f.read())
 
     for example in examples:
         path = example["path"]
Repository: bokeh/bokeh

Issue:
Bad error message for nonexistent bokeh serve target
If you call `bokeh serve` on a something that simply does not exist, the error message is misleading:
```
(base) ❯ bokeh serve junk
ERROR: Expected a '.py' script or '.ipynb' notebook, got: '/Users/bryanv/work/bokeh/junk'
```
This came up recently on SO and was very confusing until I (later) recognized the cause. 


Discussion:

Resolving patch:
diff --git a/bokeh/command/util.py b/bokeh/command/util.py
--- a/bokeh/command/util.py
+++ b/bokeh/command/util.py
@@ -114,9 +114,13 @@ def build_single_handler_application(path, argv=None):
     '''
     argv = argv or []
     path = os.path.abspath(path)
+
+    # There are certainly race conditions here if the file/directory is deleted
+    # in between the isdir/isfile tests and subsequent code. But it would be a
+    # failure if they were not there to begin with, too (just a different error)
     if os.path.isdir(path):
         handler = DirectoryHandler(filename=path, argv=argv)
-    else:
+    elif os.path.isfile(path):
         if path.endswith(".ipynb"):
             handler = NotebookHandler(filename=path, argv=argv)
         elif path.endswith(".py"):
@@ -125,6 +129,8 @@ def build_single_handler_application(path, argv=None):
             handler = ScriptHandler(filename=path, argv=argv)
         else:
             raise ValueError("Expected a '.py' script or '.ipynb' notebook, got: '%s'" % path)
+    else:
+        raise ValueError("Path for Bokeh server application does not exist: %s" % path)
 
     if handler.failed:
         raise RuntimeError("Error loading %s:\n\n%s\n%s " % (path, handler.error, handler.error_detail))


Test patch:
diff --git a/bokeh/command/tests/test_util.py b/bokeh/command/tests/test_util.py
--- a/bokeh/command/tests/test_util.py
+++ b/bokeh/command/tests/test_util.py
@@ -53,9 +53,15 @@ def test_die(capsys):
     assert out == ""
 
 def test_build_single_handler_application_unknown_file():
-    with pytest.raises(ValueError):
+    with pytest.raises(ValueError) as e:
         f = tempfile.NamedTemporaryFile(suffix=".bad")
         util.build_single_handler_application(f.name)
+    assert "Expected a '.py' script or '.ipynb' notebook, got: " in str(e)
+
+def test_build_single_handler_application_nonexistent_file():
+    with pytest.raises(ValueError) as e:
+        util.build_single_handler_application("junkjunkjunk")
+    assert "Path for Bokeh server application does not exist: " in str(e)
 
 DIRSTYLE_MAIN_WARNING_COPY = """
 It looks like you might be running the main.py of a directory app directly.
Repository: bokeh/bokeh

Issue:
Docs tweak to add note about BOKEH_DEV and apps
Make clearer need to change BOKEH_RESOURCES too.


Discussion:
Like I mentioned I don't really use it, but I'm fairly sure the intended usage of `BOKEH_DEV=True` is to have `bokeh static` running at the same time, so that BokehJS resources will be loaded from there. 

Resolving patch:
diff --git a/bokeh/settings.py b/bokeh/settings.py
--- a/bokeh/settings.py
+++ b/bokeh/settings.py
@@ -34,10 +34,17 @@
   - ``BOKEH_PRETTY=true``
   - ``BOKEH_PY_LOG_LEVEL=debug``
   - ``BOKEH_RESOURCES=absolute-dev``
-  - ``BOKEH_SIMPLE_IDS=true``
 
   Accepted values are ``yes``/``no``, ``true``/``false`` or ``0``/``1``.
 
+  .. note::
+    When running server and notebook examples, the ``BOKEH_RESOURCES``
+    setting that ``BOKEH_DEV`` sets will cause rendering problems.
+
+    We recommend manually setting ``BOKEH_RESOURCES`` to ``server``
+    for server work, and ``inline`` for notebooks (other
+    :class:`~bokeh.resources.Resources` settings may also work)
+
 ``BOKEH_DOCS_CDN`` --- What version of BokehJS to use when building sphinx.
 
   See :ref:`bokeh.resources` module reference for full details.


Test patch:
Repository: bokeh/bokeh

Issue:
TypeError: index is not a valid DatetimeIndex or PeriodIndex
Looks like pandas 0.24.0 brought some backwards incompatible changes, e.g. https://travis-ci.org/bokeh/bokeh/jobs/484595447#L1287.


Discussion:
Fun. I am fine if you want to just skip the one test in your PR for now. We can use this update for a proper fix to the one sample data file. 
I fixed this in https://github.com/bokeh/bokeh/pull/8085/commits/8f6f99937c779b869e999bf639d6f294a15d52eb. I mean, it seems to work, but I'm not sure if this is the right thing to do.

Resolving patch:
diff --git a/bokeh/sampledata/commits.py b/bokeh/sampledata/commits.py
--- a/bokeh/sampledata/commits.py
+++ b/bokeh/sampledata/commits.py
@@ -51,9 +51,14 @@ def _read_data():
     '''
 
     '''
-    data = package_csv('commits', 'commits.txt.gz', parse_dates=True, header=None, names=['day', 'datetime'], index_col='datetime')
-    data = data.tz_localize('GMT').tz_convert('US/Central')
+    from ..util.dependencies import import_required
+    module = 'commits'
+    pd = import_required('pandas', '%s sample data requires Pandas (http://pandas.pydata.org) to be installed' % module)
+
+    data = package_csv(module, 'commits.txt.gz', parse_dates=True, header=None, names=['day', 'datetime'], index_col='datetime')
+    data.index = pd.to_datetime(data.index, utc=True,).astype('datetime64[ns]').tz_localize('utc').tz_convert('US/Central')
     data['time'] = data.index.time
+
     return data
 
 #-----------------------------------------------------------------------------


Test patch:
Repository: bokeh/bokeh

Issue:
Stocks Example is not working properly 
https://github.com/bokeh/bokeh/tree/master/examples/app/stocks

The example suppose to change the stats according to the selected points. For some reason 

        def selection_change(attrname, old, new):
            print('lol')
            t1, t2 = ticker1.value, ticker2.value
            data = get_data(t1, t2)
            selected = source.selected.indices
            if selected:
                data = data.iloc[selected, :]
            update_stats(data, t1, t2)

        source.on_change('selected', selection_change)

The code never prints 'lol'. 


Discussion:
This example is tested and run regularly. How did your run this Bokeh application? It had to be run e.g. `bokeh serve stocks.py` and not just `python stocks.py`
Thanks for very quick reply. Yes I am running with `bokeh serve stocks.py`.

Also can you check the link in the gallery. I think it doesn't work either. 
https://demo.bokehplots.com/apps/stocks

When I select points , stats text never updates.

Thanks 
I just tried it with version 0.12.6, 

Than it prints 'lol' but throws the following ERROR 

ERROR:bokeh.server.protocol.server_handler:error handling message Message 'PATCH-DOC' (revision 1): AttributeError("'PropertyValueDict' object has no attribute 'indices'",)

Version 1.0.4, never prints 'lol'
The code in the example is wrong. I'm not sure when/how it got reverted to the old/bad way. The correct way to do this from version 1.0 forward is:
```
source.selected.on_change('indices', selection_change)
```

Would you like to make a PR to fix things?
Yes,  it is working now! That was the line to change. 

Thank you so much : )
Maybe I should leave the issue open so that you can change the example line
@ahmetbaglan would you like to submit a Pull Request to update the file? It can even be done directly from the GH web UI (just make sure there is no trailing whitespace or our linter will complain)

Resolving patch:
diff --git a/examples/app/stocks/main.py b/examples/app/stocks/main.py
--- a/examples/app/stocks/main.py
+++ b/examples/app/stocks/main.py
@@ -130,7 +130,7 @@ def selection_change(attrname, old, new):
         data = data.iloc[selected, :]
     update_stats(data, t1, t2)
 
-source.on_change('selected', selection_change)
+source.selected.on_change('indices', selection_change)
 
 # set up layout
 widgets = column(ticker1, ticker2, stats)


Test patch:
Repository: bokeh/bokeh

Issue:
grid_axis_alignment_no_toolbar is broken in Windows (32-bit)
`examples/integration/layout/grid_axis_alignment_no_toolbar`:

![image](https://user-images.githubusercontent.com/27475/52644650-81191480-2edf-11e9-9905-eb5b000448f1.png)

All axes should be in 0 to 10, 10^3, 10^6, 10^9 ranges. All major browsers are affected the same way. I suspect this may be due to 32-bit system architecture. It would be good if someone with 64-bit windows could run this example for comparison.


Discussion:
Looking at those glyphs, it's pretty clear to me that this is an overflow-kind issue.
This is a problem with numpy. The code uses `10**9 * np.arange(10)` which overflows, because `dtype` defaults to platform `int` which is 32-bit in size.
The code in our example uses that? Seems like an easy fix to make the type explicit then

Resolving patch:
diff --git a/examples/integration/layout/grid_axis_alignment_no_toolbar.py b/examples/integration/layout/grid_axis_alignment_no_toolbar.py
--- a/examples/integration/layout/grid_axis_alignment_no_toolbar.py
+++ b/examples/integration/layout/grid_axis_alignment_no_toolbar.py
@@ -6,7 +6,7 @@
 from bokeh.layouts import gridplot
 
 coeffs = [10**0, 10**3, 10**6, 10**9]
-V = np.arange(10)
+V = np.arange(10, dtype="int64")
 
 figs = []
 


Test patch: