gurudesh/pytracebugs huggingface dataset:
# Buggy code
def load_ssh_public_key(data, backend):
    key_parts = data.split(b" ")

    if len(key_parts) != 2 and len(key_parts) != 3:
        raise ValueError("Key is not in the proper format or contains extra data.")

    key_type = key_parts[0]

    if key_type == b"ssh-rsa":
        loader = _load_ssh_rsa_public_key
    elif key_type == b"ssh-dss":
        loader = _load_ssh_dss_public_key
    elif key_type in [
        b"ecdsa-sha2-nistp256",
        b"ecdsa-sha2-nistp384",
        b"ecdsa-sha2-nistp521",
    ]:
        loader = _load_ssh_ecdsa_public_key
    else:
        raise UnsupportedAlgorithm("Key type is not supported.")

    key_body = key_parts[1]

    try:
        decoded_data = base64.b64decode(key_body)
    except TypeError:
        raise ValueError("Key is not in the proper format.")

    inner_key_type, rest = _read_next_string(decoded_data)

    if inner_key_type != key_type:
        raise ValueError("Key header and key body contain different key type values.")

    return loader(key_type, rest, backend)


# Traceback (ValueError)
from cryptography.hazmat import backends
from cryptography.hazmat.primitives import serialization
key=open('test_key.pub')
keyval = key.read()
serialization.load_ssh_public_key(keyval, backends.default_backend())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/mike/.venvs/openstack/lib/python2.7/site-packages/cryptography/hazmat/primitives/serialization.py", line 40, in load_ssh_public_key
'Key is not in the proper format or contains extra data.')
ValueError: Key is not in the proper format or contains extra data.


# Fixed code
def load_ssh_public_key(data, backend):
    key_parts = data.split(b" ", 2)

    if len(key_parts) < 2:
        raise ValueError("Key is not in the proper format or contains extra data.")

    key_type = key_parts[0]

    if key_type == b"ssh-rsa":
        loader = _load_ssh_rsa_public_key
    elif key_type == b"ssh-dss":
        loader = _load_ssh_dss_public_key
    elif key_type in [
        b"ecdsa-sha2-nistp256",
        b"ecdsa-sha2-nistp384",
        b"ecdsa-sha2-nistp521",
    ]:
        loader = _load_ssh_ecdsa_public_key
    else:
        raise UnsupportedAlgorithm("Key type is not supported.")

    key_body = key_parts[1]

    try:
        decoded_data = base64.b64decode(key_body)
    except TypeError:
        raise ValueError("Key is not in the proper format.")

    inner_key_type, rest = _read_next_string(decoded_data)

    if inner_key_type != key_type:
        raise ValueError("Key header and key body contain different key type values.")

    return loader(key_type, rest, backend)
# Buggy code
def open_browser():
    # Child process
    time.sleep(0.5)
    webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new="tab")


# Traceback (webbrowser.Error)
Exception in thread Thread-2:
Traceback (most recent call last):
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "docserver.py", line 43, in open_browser
webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new="tab")
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/webbrowser.py", line 78, in open
if browser.open(url, new, autoraise):
File "/home/p-himik/soft/miniconda3/envs/bokeh-dev/lib/python3.7/webbrowser.py", line 251, in open
"expected 0, 1, or 2, got %s" % new)
webbrowser.Error: Bad 'new' parameter to open(); expected 0, 1, or 2, got tab

# Fixed code
def open_browser():
    # Child process
    time.sleep(0.5)
    webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new=2)
# Buggy code
def set_select(self, selector, updates):
    """Update objects that match a given selector with the specified
    attribute/value updates.

    Args:
        selector (JSON-like query dictionary) : you can query by type or by
            name,i e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}``
            updates (dict) :

    Returns:
        None

    """
    for obj in self.select(selector):
        for key, val in updates.items():
            setattr(obj, key, val)


# Traceback (AttributeError)
Traceback (most recent call last):
File "set_select_plot.py", line 81, in <module>
plot_width=500,
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\model.py", line 628, in set_select
for obj in self.select(selector):
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 87, in <genexpr>
return (obj for obj in objs if match(obj, selector, context))
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 159, in match
for key, val in selector.items():
AttributeError: type object 'Figure' has no attribute 'items'

# Fixed code
def set_select(self, selector, updates):
    """Update objects that match a given selector with the specified
    attribute/value updates.

    Args:
        selector (JSON-like query dictionary) : you can query by type or by
            name,i e.g. ``{"type": HoverTool}``, ``{"name": "mycircle"}``
            updates (dict) :

    Returns:
        None

    """
    if isclass(selector) and issubclass(selector, Model):
        selector = dict(type=selector)
    for obj in self.select(selector):
        for key, val in updates.items():
            setattr(obj, key, val)
# Buggy code
def set_select(self, selector, updates):
    """Update objects that match a given selector with the specified
    attribute/value updates.

    Args:
        selector (JSON-like) :
        updates (dict) :

    Returns:
        None

    """
    for obj in self.select(selector):
        for key, val in updates.items():
            setattr(obj, key, val)


# Traceback (AttributeError)
Traceback (most recent call last):
File "set_select_plot.py", line 81, in <module>
plot_width=500,
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\model.py", line 628, in set_select
for obj in self.select(selector):
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 87, in <genexpr>
return (obj for obj in objs if match(obj, selector, context))
File "env\lib\site-packages\bokeh-1.3.4-py3.7.egg\bokeh\core\query.py", line 159, in match
for key, val in selector.items():
AttributeError: type object 'Figure' has no attribute 'items'

# Fixed code
def set_select(self, selector, updates):
    """Update objects that match a given selector with the specified
    attribute/value updates.

    Args:
        selector (JSON-like) :
        updates (dict) :

    Returns:
        None

    """
    if isclass(selector) and issubclass(selector, Model):
        selector = dict(type=selector)
    for obj in self.select(selector):
        for key, val in updates.items():
            setattr(obj, key, val)
# Buggy code
def decode_base64_dict(data):
    """Decode a base64 encoded array into a NumPy array.

    Args:
        data (dict) : encoded array data to decode

    Data should have the format encoded by :func:`encode_base64_dict`.

    Returns:
        np.ndarray

    """
    b64 = base64.b64decode(data["__ndarray__"])
    array = np.frombuffer(b64, dtype=data["dtype"])
    if len(data["shape"]) > 1:
        array = array.reshape(data["shape"])
    return array


# Traceback (AttributeError)
2018-09-10 19:07:29,992 Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x1202aa6a8>, <Future finished exception=ValueError('assignment destination is read-only',)>)
Traceback (most recent call last):
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 759, in _run_callback
ret = callback()
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "/Users/bryanv/work/bokeh/bokeh/util/tornado.py", line 95, in on_done
log.error("".join(format_exception(*future.exc_info())))
AttributeError: '_asyncio.Future' object has no attribute 'exc_info'

# Fixed code
def decode_base64_dict(data):
    """Decode a base64 encoded array into a NumPy array.

    Args:
        data (dict) : encoded array data to decode

    Data should have the format encoded by :func:`encode_base64_dict`.

    Returns:
        np.ndarray

    """
    b64 = base64.b64decode(data["__ndarray__"])
    array = np.copy(np.frombuffer(b64, dtype=data["dtype"]))
    if len(data["shape"]) > 1:
        array = array.reshape(data["shape"])
    return array
# Buggy code
def start(self):
    if self._started:
        raise RuntimeError("called start() twice on _AsyncPeriodic")
    self._started = True

    def invoke():
        # important to start the sleep before starting callback
        # so any initial time spent in callback "counts against"
        # the period.
        sleep_future = self.sleep()
        result = self._func()

        # This is needed for Tornado >= 4.5 where convert_yielded will no
        # longer raise BadYieldError on None
        if result is None:
            return sleep_future

        try:
            callback_future = gen.convert_yielded(result)
        except gen.BadYieldError:
            # result is not a yieldable thing
            return sleep_future
        else:
            return gen.multi([sleep_future, callback_future])

    def on_done(future):
        if not self._stopped:
            self._loop.add_future(invoke(), on_done)
        if future.exception() is not None:
            log.error("Error thrown from periodic callback:")
            log.error("".join(format_exception(*future.exc_info())))

    self._loop.add_future(self.sleep(), on_done)


# Traceback (AttributeError)
2018-09-10 19:07:29,992 Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x1202aa6a8>, <Future finished exception=ValueError('assignment destination is read-only',)>)
Traceback (most recent call last):
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 759, in _run_callback
ret = callback()
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "/Users/bryanv/work/bokeh/bokeh/util/tornado.py", line 95, in on_done
log.error("".join(format_exception(*future.exc_info())))
AttributeError: '_asyncio.Future' object has no attribute 'exc_info'

# Fixed code
def start(self):
    if self._started:
        raise RuntimeError("called start() twice on _AsyncPeriodic")
    self._started = True

    def invoke():
        # important to start the sleep before starting callback
        # so any initial time spent in callback "counts against"
        # the period.
        sleep_future = self.sleep()
        result = self._func()

        # This is needed for Tornado >= 4.5 where convert_yielded will no
        # longer raise BadYieldError on None
        if result is None:
            return sleep_future

        try:
            callback_future = gen.convert_yielded(result)
        except gen.BadYieldError:
            # result is not a yieldable thing
            return sleep_future
        else:
            return gen.multi([sleep_future, callback_future])

    def on_done(future):
        if not self._stopped:
            self._loop.add_future(invoke(), on_done)
        ex = future.exception()
        if ex is not None:
            log.error("Error thrown from periodic callback:")
            if six.PY2:
                lines = format_exception(*future.exc_info())
            else:
                lines = format_exception(ex.__class__, ex, ex.__traceback__)
            log.error("".join(lines))

    self._loop.add_future(self.sleep(), on_done)
# Buggy code
def on_done(future):
    if not self._stopped:
        self._loop.add_future(invoke(), on_done)
    if future.exception() is not None:
        log.error("Error thrown from periodic callback:")
        log.error("".join(format_exception(*future.exc_info())))


# Traceback (AttributeError)
2018-09-10 19:07:29,992 Exception in callback functools.partial(<function wrap.<locals>.null_wrapper at 0x1202aa6a8>, <Future finished exception=ValueError('assignment destination is read-only',)>)
Traceback (most recent call last):
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/ioloop.py", line 759, in _run_callback
ret = callback()
File "/Users/bryanv/anaconda/lib/python3.6/site-packages/tornado/stack_context.py", line 276, in null_wrapper
return fn(*args, **kwargs)
File "/Users/bryanv/work/bokeh/bokeh/util/tornado.py", line 95, in on_done
log.error("".join(format_exception(*future.exc_info())))
AttributeError: '_asyncio.Future' object has no attribute 'exc_info'

# Fixed code
def on_done(future):
    if not self._stopped:
        self._loop.add_future(invoke(), on_done)
    ex = future.exception()
    if ex is not None:
        log.error("Error thrown from periodic callback:")
        if six.PY2:
            lines = format_exception(*future.exc_info())
        else:
            lines = format_exception(ex.__class__, ex, ex.__traceback__)
        log.error("".join(lines))
# Buggy code
def error(self):
    """If code execution fails, may contain a related error message."""
    return self._error


# Traceback (Exception)
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!

2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created

# Fixed code
def error(self):
    """If code execution fails, may contain a related error message."""
    return self._error if self._permanent_error is None else self._permanent_error
# Buggy code
def error_detail(self):
    """If code execution fails, may contain a traceback or other details."""
    return self._error_detail


# Traceback (Exception)
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!

2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created

# Fixed code
def error_detail(self):
    """If code execution fails, may contain a traceback or other details."""
    return (
        self._error_detail
        if self._permanent_error_detail is None
        else self._permanent_error_detail
    )
# Buggy code
def failed(self):
    """``True`` if code execution failed"""
    return self._failed


# Traceback (Exception)
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!

2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created

# Fixed code
def failed(self):
    """``True`` if code execution failed"""
    return self._failed or self._code is None
# Buggy code
def new_module(self):
    """Make a fresh module to run in.

    Returns:
        Module

    """
    if self.failed:
        return None

    module_name = "bk_script_" + make_id().replace("-", "")
    module = ModuleType(str(module_name))  # str needed for py2.7
    module.__dict__["__file__"] = os.path.abspath(self._path)

    return module


# Traceback (Exception)
(venv) $ bokeh serve myapp.py
2018-06-27 12:59:45,343 Starting Bokeh server version 0.13.0 (running on Tornado 5.0.1)
2018-06-27 12:59:45,345 Bokeh app running at: http://localhost:5006/myapp
2018-06-27 12:59:45,345 Starting Bokeh server with process id: 13979
0.5604607908584933
2018-06-27 13:00:06,274 200 GET /myapp (::1) 96.25ms
2018-06-27 13:00:06,437 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=OxhSy81ZBM8URWfk6wp7OTH7bTictF12u6pI8o7fkIUs (::1) 0.64ms
2018-06-27 13:00:06,437 WebSocket connection opened
2018-06-27 13:00:06,438 ServerConnection created
0.6452850662545722
0.2762922805351794
2018-06-27 13:00:11,120 Error running application handler <bokeh.application.handlers.script.ScriptHandler object at 0x7feae4861a58>: boom!
File "myapp.py", line 46, in <module>:
raise Exception('boom!') Traceback (most recent call last):
File "/home/matt/Clients/QEye/venv/lib/python3.5/site-packages/bokeh/application/handlers/code_runner.py", line 163, in run
exec(self._code, module.__dict__)
File "/home/matt/Clients/QEye/isolate/myapp.py", line 46, in <module>
raise Exception('boom!')
Exception: boom!

2018-06-27 13:00:11,125 200 GET /myapp (::1) 25.45ms
2018-06-27 13:00:11,132 WebSocket connection closed: code=1001, reason=None
2018-06-27 13:00:11,207 101 GET /myapp/ws?bokeh-protocol-version=1.0&amp;bokeh-session-id=Y5IlTpoIxVs42drth0tKZonyuwGnUNM3zKK6OAG5eg6n (::1) 0.60ms
2018-06-27 13:00:11,208 WebSocket connection opened
2018-06-27 13:00:11,208 ServerConnection created

# Fixed code
def new_module(self):
    """Make a fresh module to run in.

    Returns:
        Module

    """
    self.reset_run_errors()

    if self._code is None:
        return None

    module_name = "bk_script_" + make_id().replace("-", "")
    module = ModuleType(str(module_name))  # str needed for py2.7
    module.__dict__["__file__"] = os.path.abspath(self._path)

    return module
# Buggy code
def bk_worker():
    io_loop = IOLoop.current()
    server = BaseServer(io_loop, bokeh_tornado, bokeh_http)
    server.start()
    server.io_loop.start()


# Traceback (RuntimeError)
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'.

# Fixed code
def bk_worker():
    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()
# Buggy code
def check_origin(self, origin):
    from ..util import check_whitelist

    parsed_origin = urlparse(origin)
    origin_host = parsed_origin.netloc.lower()

    allowed_hosts = self.application.websocket_origins

    allowed = check_whitelist(origin_host, allowed_hosts)
    if allowed:
        return True
    else:
        log.error(
            "Refusing websocket connection from Origin '%s'; \
                      use --allow-websocket-origin=%s to permit this; currently we allow origins %r",
            origin,
            origin_host,
            allowed_hosts,
        )
        return False


# Traceback (tornado.iostream.StreamClosedError)
2018-03-12 09:05:56,504 200 GET /gapminder (::1) 134.13ms
2018-03-12 09:05:56,506 Sending pull-doc-reply from session 'c13X3Xet3szgUeNWFMzrL86pmFq77b8q04pGAUD8WUFJ'
2018-03-12 09:05:56,513 Failed sending message as connection was closed
2018-03-12 09:05:56,514 WebSocket connection closed: code=None, reason=None
2018-03-12 09:05:56,604 Future exception was never retrieved
future: <Future finished exception=WebSocketClosedError()>
Traceback (most recent call last):
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/websocket.py", line 808, in wrapper
yield fut
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/gen.py", line 1099, in run
value = future.result()
tornado.iostream.StreamClosedError: Stream is closed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/gen.py", line 1107, in run
yielded = self.gen.throw(*exc_info)
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/websocket.py", line 810, in wrapper
raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError

# Fixed code
def check_origin(self, origin):
    """Implement a check_origin policy for Tornado to call.

    The suplied origin will be compared to the Bokeh server whitelist. If the
    origin is not allow, an error will be logged and ``False`` will be returned.

    Args:
        origin (str) :
            The URL of the connection origin

    Returns:
        bool, True if the connection is allowed, False otherwise

    """
    from ..util import check_whitelist

    parsed_origin = urlparse(origin)
    origin_host = parsed_origin.netloc.lower()

    allowed_hosts = self.application.websocket_origins

    allowed = check_whitelist(origin_host, allowed_hosts)
    if allowed:
        return True
    else:
        log.error(
            "Refusing websocket connection from Origin '%s'; \
                      use --allow-websocket-origin=%s to permit this; currently we allow origins %r",
            origin,
            origin_host,
            allowed_hosts,
        )
        return False
# Buggy code
def send_message(self, message):
    """Send a Bokeh Server protocol message to the connected client.

    Args:
        message (Message) : a message to send

    """
    try:
        yield message.send(self)
    except WebSocketClosedError:
        # on_close() is / will be called anyway
        log.warn("Failed sending message as connection was closed")
    raise gen.Return(None)


# Traceback (tornado.iostream.StreamClosedError)
2018-03-12 09:05:56,504 200 GET /gapminder (::1) 134.13ms
2018-03-12 09:05:56,506 Sending pull-doc-reply from session 'c13X3Xet3szgUeNWFMzrL86pmFq77b8q04pGAUD8WUFJ'
2018-03-12 09:05:56,513 Failed sending message as connection was closed
2018-03-12 09:05:56,514 WebSocket connection closed: code=None, reason=None
2018-03-12 09:05:56,604 Future exception was never retrieved
future: <Future finished exception=WebSocketClosedError()>
Traceback (most recent call last):
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/websocket.py", line 808, in wrapper
yield fut
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/gen.py", line 1099, in run
value = future.result()
tornado.iostream.StreamClosedError: Stream is closed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/gen.py", line 1107, in run
yielded = self.gen.throw(*exc_info)
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/websocket.py", line 810, in wrapper
raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError

# Fixed code
def send_message(self, message):
    """Send a Bokeh Server protocol message to the connected client.

    Args:
        message (Message) : a message to send

    """
    try:
        yield message.send(self)
    except (
        WebSocketClosedError,
        StreamClosedError,
    ):  # Tornado 4.x may raise StreamClosedError
        # on_close() is / will be called anyway
        log.warn("Failed sending message as connection was closed")
    raise gen.Return(None)
# Buggy code
def write_message(self, message, binary=False, locked=True):
    """Override parent write_message with a version that acquires a
    write lock before writing.

    """

    def write_message_unlocked():
        future = super(WSHandler, self).write_message(message, binary)
        # don't yield this future or we're blocking on ourselves!
        raise gen.Return(future)

    if locked:
        with (yield self.write_lock.acquire()):
            write_message_unlocked()
    else:
        write_message_unlocked()


# Traceback (tornado.iostream.StreamClosedError)
2018-03-12 09:05:56,504 200 GET /gapminder (::1) 134.13ms
2018-03-12 09:05:56,506 Sending pull-doc-reply from session 'c13X3Xet3szgUeNWFMzrL86pmFq77b8q04pGAUD8WUFJ'
2018-03-12 09:05:56,513 Failed sending message as connection was closed
2018-03-12 09:05:56,514 WebSocket connection closed: code=None, reason=None
2018-03-12 09:05:56,604 Future exception was never retrieved
future: <Future finished exception=WebSocketClosedError()>
Traceback (most recent call last):
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/websocket.py", line 808, in wrapper
yield fut
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/gen.py", line 1099, in run
value = future.result()
tornado.iostream.StreamClosedError: Stream is closed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/gen.py", line 1107, in run
yielded = self.gen.throw(*exc_info)
File "/Users/bryanv/anaconda/envs/15dev1/lib/python3.6/site-packages/tornado/websocket.py", line 810, in wrapper
raise WebSocketClosedError()
tornado.websocket.WebSocketClosedError

# Fixed code
def write_message(self, message, binary=False, locked=True):
    """Override parent write_message with a version that acquires a
    write lock before writing.

    """
    if locked:
        with (yield self.write_lock.acquire()):
            yield super(WSHandler, self).write_message(message, binary)
    else:
        yield super(WSHandler, self).write_message(message, binary)
# Buggy code
def _build_docstring():
    global __doc__
    from . import subcommands

    for cls in subcommands.all:
        __doc__ += "%8s : %s\n" % (cls.name, cls.help)


# Traceback (TypeError)
2017-04-18 16:51:23 ERROR    Error on request:
Traceback (most recent call last):
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 193, in run_wsgi
execute(self.server.app)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 181, in execute
application_iter = app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/wsgi.py", line 599, in __call__
return self.app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/contrib/lint.py", line 337, in __call__
app_iter = self.app(environ, checking_start_response)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 40, in __call__
response, endpoint = self.dispatch_request(request)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 31, in dispatch_request
func = getattr(importlib.import_module(module[0]), module[1])
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Delivery.py", line 20, in <module>
from serverMonitoring.Handler.Dashboard.Widgets import ChartParameters, Chart
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Dashboard/Widgets.py", line 20, in <module>
from bokeh.embed import file_html
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/embed.py", line 28, in <module>
from .core.json_encoder import serialize_json
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/core/json_encoder.py", line 47, in <module>
from ..util.serialization import transform_series, transform_array
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/util/serialization.py", line 39, in <module>
__doc__ = __doc__ % ("\n".join("* ``np." + str(x) + "``" for x in BINARY_ARRAY_TYPES))
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

# Fixed code
def _build_docstring():
    global __doc__
    from . import subcommands

    for cls in subcommands.all:
        # running python with -OO will discard docstrings -> __doc__ is None
        if __doc__ is None:
            __doc__ = ""
        __doc__ += "%8s : %s\n" % (cls.name, cls.help)
# Buggy code
def abstract(cls):
    """A decorator to mark abstract base classes derived from |HasProps|."""
    if not issubclass(cls, HasProps):
        raise TypeError("%s is not a subclass of HasProps" % cls.__name__)

    cls.__doc__ += _ABSTRACT_ADMONITION

    return cls


# Traceback (TypeError)
2017-04-18 16:51:23 ERROR    Error on request:
Traceback (most recent call last):
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 193, in run_wsgi
execute(self.server.app)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 181, in execute
application_iter = app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/wsgi.py", line 599, in __call__
return self.app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/contrib/lint.py", line 337, in __call__
app_iter = self.app(environ, checking_start_response)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 40, in __call__
response, endpoint = self.dispatch_request(request)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 31, in dispatch_request
func = getattr(importlib.import_module(module[0]), module[1])
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Delivery.py", line 20, in <module>
from serverMonitoring.Handler.Dashboard.Widgets import ChartParameters, Chart
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Dashboard/Widgets.py", line 20, in <module>
from bokeh.embed import file_html
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/embed.py", line 28, in <module>
from .core.json_encoder import serialize_json
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/core/json_encoder.py", line 47, in <module>
from ..util.serialization import transform_series, transform_array
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/util/serialization.py", line 39, in <module>
__doc__ = __doc__ % ("\n".join("* ``np." + str(x) + "``" for x in BINARY_ARRAY_TYPES))
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

# Fixed code
def abstract(cls):
    """A decorator to mark abstract base classes derived from |HasProps|."""
    if not issubclass(cls, HasProps):
        raise TypeError("%s is not a subclass of HasProps" % cls.__name__)

    # running python with -OO will discard docstrings -> __doc__ is None
    if cls.__doc__ is not None:
        cls.__doc__ += _ABSTRACT_ADMONITION

    return cls
# Buggy code
def _get_argspecs(glyphclass):
    argspecs = OrderedDict()
    for arg in glyphclass._args:
        spec = {}
        prop = getattr(glyphclass, arg)
        spec["desc"] = " ".join(
            x.strip() for x in prop.__doc__.strip().split("\n\n")[0].split("\n")
        )
        spec["default"] = prop.class_default(glyphclass)
        spec["type"] = prop.__class__.__name__
        argspecs[arg] = spec
    return argspecs


# Traceback (TypeError)
2017-04-18 16:51:23 ERROR    Error on request:
Traceback (most recent call last):
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 193, in run_wsgi
execute(self.server.app)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 181, in execute
application_iter = app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/wsgi.py", line 599, in __call__
return self.app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/contrib/lint.py", line 337, in __call__
app_iter = self.app(environ, checking_start_response)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 40, in __call__
response, endpoint = self.dispatch_request(request)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 31, in dispatch_request
func = getattr(importlib.import_module(module[0]), module[1])
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Delivery.py", line 20, in <module>
from serverMonitoring.Handler.Dashboard.Widgets import ChartParameters, Chart
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Dashboard/Widgets.py", line 20, in <module>
from bokeh.embed import file_html
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/embed.py", line 28, in <module>
from .core.json_encoder import serialize_json
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/core/json_encoder.py", line 47, in <module>
from ..util.serialization import transform_series, transform_array
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/util/serialization.py", line 39, in <module>
__doc__ = __doc__ % ("\n".join("* ``np." + str(x) + "``" for x in BINARY_ARRAY_TYPES))
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

# Fixed code
def _get_argspecs(glyphclass):
    argspecs = OrderedDict()
    for arg in glyphclass._args:
        spec = {}
        prop = getattr(glyphclass, arg)

        # running python with -OO will discard docstrings -> __doc__ is None
        if prop.__doc__:
            spec["desc"] = " ".join(
                x.strip() for x in prop.__doc__.strip().split("\n\n")[0].split("\n")
            )
        else:
            spec["desc"] = ""
        spec["default"] = prop.class_default(glyphclass)
        spec["type"] = prop.__class__.__name__
        argspecs[arg] = spec
    return argspecs
# Buggy code
def array_encoding_disabled(array):
    """Determine whether an array may be binary encoded.

    The NumPy array dtypes that can be encoded are:

    %s

    Args:
        array (np.ndarray) : the array to check

    Returns:
        bool

    """

    # disable binary encoding for non-supported dtypes
    return array.dtype not in BINARY_ARRAY_TYPES


# Traceback (TypeError)
2017-04-18 16:51:23 ERROR    Error on request:
Traceback (most recent call last):
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 193, in run_wsgi
execute(self.server.app)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/serving.py", line 181, in execute
application_iter = app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/wsgi.py", line 599, in __call__
return self.app(environ, start_response)
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/werkzeug/contrib/lint.py", line 337, in __call__
app_iter = self.app(environ, checking_start_response)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 40, in __call__
response, endpoint = self.dispatch_request(request)
File "/data/projects/python/server-monitoring/serverMonitoring/Main.py", line 31, in dispatch_request
func = getattr(importlib.import_module(module[0]), module[1])
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Delivery.py", line 20, in <module>
from serverMonitoring.Handler.Dashboard.Widgets import ChartParameters, Chart
File "/data/projects/python/server-monitoring/serverMonitoring/Handler/Dashboard/Widgets.py", line 20, in <module>
from bokeh.embed import file_html
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/embed.py", line 28, in <module>
from .core.json_encoder import serialize_json
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/core/json_encoder.py", line 47, in <module>
from ..util.serialization import transform_series, transform_array
File "/data/projects/python/server-monitoring/env/lib/python2.7/site-packages/bokeh/util/serialization.py", line 39, in <module>
__doc__ = __doc__ % ("\n".join("* ``np." + str(x) + "``" for x in BINARY_ARRAY_TYPES))
TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

# Fixed code
def array_encoding_disabled(array):
    """Determine whether an array may be binary encoded.

    The NumPy array dtypes that can be encoded are:

    {binary_array_types}

    Args:
        array (np.ndarray) : the array to check

    Returns:
        bool

    """

    # disable binary encoding for non-supported dtypes
    return array.dtype not in BINARY_ARRAY_TYPES
# Buggy code
def bkapp_page():
    script = autoload_server(model=None, url="http://localhost:5006/bkapp")
    return render_template("embed.html", script=script)


# Traceback (jinja2.exceptions.TemplateNotFound)
$ python flask_embed.py
Opening Flask app with embedded Bokeh application on http://localhost:8080/
[2017-01-16 21:29:37,150] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "flask_embed.py", line 43, in bkapp_page
return render_template("embed.html", script=script)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/templating.py", line 133, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/jinja2/environment.py", line 851, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/jinja2/environment.py", line 812, in get_template
return self._load_template(name, self.make_globals(globals))
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/jinja2/environment.py", line 774, in _load_template
cache_key = self.loader.get_source(self, name)[1]
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/templating.py", line 57, in get_source
return self._get_source_fast(environment, template)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/templating.py", line 85, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: embed.html

# Fixed code
def bkapp_page():
    script = autoload_server(model=None, url="http://localhost:5006/bkapp")
    return render_template("embed.html", script=script, template="Flask")
# Buggy code
def get(self):
    template = env.get_template("embed.html")
    script = autoload_server(model=None, url="http://localhost:5006/bkapp")
    self.write(template.render(script=script))


# Traceback (jinja2.exceptions.TemplateNotFound)
$ python flask_embed.py
Opening Flask app with embedded Bokeh application on http://localhost:8080/
[2017-01-16 21:29:37,150] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/_compat.py", line 33, in reraise
raise value
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "flask_embed.py", line 43, in bkapp_page
return render_template("embed.html", script=script)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/templating.py", line 133, in render_template
return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/jinja2/environment.py", line 851, in get_or_select_template
return self.get_template(template_name_or_list, parent, globals)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/jinja2/environment.py", line 812, in get_template
return self._load_template(name, self.make_globals(globals))
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/jinja2/environment.py", line 774, in _load_template
cache_key = self.loader.get_source(self, name)[1]
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/templating.py", line 57, in get_source
return self._get_source_fast(environment, template)
File "/home/juanlu/.miniconda3/envs/py35/lib/python3.5/site-packages/flask/templating.py", line 85, in _get_source_fast
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: embed.html

# Fixed code
def get(self):
    template = env.get_template("embed.html")
    script = autoload_server(model=None, url="http://localhost:5006/bkapp")
    self.write(template.render(script=script, template="Tornado"))