gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_resource_path(filename):
    """
    Returns the absolute path of a resource, regardless of whether OnionShare is installed
    systemwide, and whether regardless of platform
    """
    p = get_platform()
    if p == "Linux" and sys.argv and sys.argv[0].startswith(sys.prefix):
        # OnionShare is installed systemwide in Linux
        resources_dir = os.path.join(sys.prefix, "share/onionshare")
    elif getattr(sys, "frozen", False):  # Check if app is "frozen" with cx_Freeze
        # http://cx-freeze.readthedocs.io/en/latest/faq.html#using-data-files
        resources_dir = os.path.join(os.path.dirname(sys.executable), "resources")
    else:  # Look for resources directory relative to python file
        resources_dir = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.abspath(inspect.getfile(inspect.currentframe()))
                )
            ),
            "resources",
        )

    return os.path.join(resources_dir, filename)


# Traceback (ImportError)
Traceback (most recent call last):
File "./install/scripts/onionshare", line 21, in <module>
import onionshare
ImportError: No module named 'onionshare'

# Fixed code
def get_resource_path(filename):
    """
    Returns the absolute path of a resource, regardless of whether OnionShare is installed
    systemwide, and whether regardless of platform
    """
    p = get_platform()

    if getattr(sys, "onionshare_dev_mode", False):
        # Look for resources directory relative to python file
        resources_dir = os.path.join(
            os.path.dirname(
                os.path.dirname(
                    os.path.abspath(inspect.getfile(inspect.currentframe()))
                )
            ),
            "resources",
        )

    elif p == "Linux" and sys.argv and sys.argv[0].startswith(sys.prefix):
        # OnionShare is installed systemwide in Linux
        resources_dir = os.path.join(sys.prefix, "share/onionshare")
    elif getattr(sys, "frozen", False):  # Check if app is "frozen" with cx_Freeze
        # http://cx-freeze.readthedocs.io/en/latest/faq.html#using-data-files
        resources_dir = os.path.join(os.path.dirname(sys.executable), "resources")

    return os.path.join(resources_dir, filename)
# Buggy code
def __init__(self, basename, webapp_port):
    global window_icon
    QWebView.__init__(self)
    self.setWindowTitle("{0} | OnionShare".format(basename))
    self.resize(580, 400)
    self.setMinimumSize(580, 400)
    self.setMaximumSize(580, 400)
    self.setWindowIcon(window_icon)
    self.load(QUrl("http://127.0.0.1:{0}".format(webapp_port)))


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "<string>", line 7, in <module>
File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 121, in main
File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 68, in select_file
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 22: ordinal not in range(128)

# Fixed code
def __init__(self, basename, webapp_port):
    global window_icon
    QWebView.__init__(self)
    self.setWindowTitle("{0} | OnionShare".format(basename.decode("utf-8")))
    self.resize(580, 400)
    self.setMinimumSize(580, 400)
    self.setMaximumSize(580, 400)
    self.setWindowIcon(window_icon)
    self.load(QUrl("http://127.0.0.1:{0}".format(webapp_port)))
# Buggy code
def select_file(strings, filename=None):
    # get filename, either from argument or file chooser dialog
    if not filename:
        args = {}
        if onionshare.get_platform() == "Tails":
            args["directory"] = "/home/amnesia"

        filename = QFileDialog.getOpenFileName(
            caption=translated("choose_file"), options=QFileDialog.ReadOnly, **args
        )
        if not filename:
            return False, False

        filename = str(filename)

    # validate filename
    if not os.path.isfile(filename):
        alert(translated("not_a_file").format(filename), QMessageBox.Warning)
        return False, False

    filename = os.path.abspath(filename)
    basename = os.path.basename(filename)
    return filename, basename


# Traceback (UnicodeEncodeError)
Traceback (most recent call last):
File "<string>", line 7, in <module>
File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 121, in main
File "/Users/micah/code/onionshare/build/onionshare-osx/out00-PYZ.pyz/onionshare_gui.onionshare_gui", line 68, in select_file
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 22: ordinal not in range(128)

# Fixed code
def select_file(strings, filename=None):
    # get filename, either from argument or file chooser dialog
    if not filename:
        args = {}
        if onionshare.get_platform() == "Tails":
            args["directory"] = "/home/amnesia"

        filename = QFileDialog.getOpenFileName(
            caption=translated("choose_file"), options=QFileDialog.ReadOnly, **args
        )
        if not filename:
            return False, False

        filename = str(unicode(filename).encode("utf-8"))

    # validate filename
    if not os.path.isfile(filename):
        alert(translated("not_a_file").format(filename), QMessageBox.Warning)
        return False, False

    filename = os.path.abspath(filename)
    basename = os.path.basename(filename)
    return filename, basename
# Buggy code
def main():
    package = sys.argv[1]
    bin_path = Path(sys.argv[2])

    apps = get_apps(package, bin_path)
    app_paths = [str(Path(bin_path) / app) for app in apps]
    app_paths_of_dependencies: Dict[str, List[str]] = {}
    app_paths_of_dependencies = _dfs_package_apps(
        bin_path, package, app_paths_of_dependencies
    )

    output = {
        "apps": apps,
        "app_paths": app_paths,
        "app_paths_of_dependencies": app_paths_of_dependencies,
        "package_version": get_package_version(package),
        "python_version": f"Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
    }

    print(json.dumps(output))


# Traceback (SyntaxError)
$ python3.7 -m pip install --user pipx
$ python3.7 -m pipx run  --python python3.4 cowsay 'Hello, world!'
_____________
< Hello, world! >
=============
\
\
^__^
(oo)\_______
(__)\       )\/\
||----w |
||     ||


$  python3.7 -m pipx install --python python3.4 cowsay
File "<string>", line 89
app_paths_of_dependencies: Dict[str, List[str]] = {}
^
SyntaxError: invalid syntax

⢿ installing package 'cowsay'Traceback (most recent call last):
File "/home/bkboulton/.pyenv/versions/py37/bin/pipx", line 10, in <module>
sys.exit(cli())
File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 547, in c
exit(run_pipx_command(parsed_pipx_args))
File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/main.py", line 166, in r
include_dependencies=args.include_deps,
File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/commands.py", line 318,
if venv.get_venv_metadata_for_package(package).package_version is None:
File "/home/bkboulton/.pyenv/versions/py37/lib/python3.7/site-packages/pipx/Venv.py", line 161, in g
self.python_path, VENV_METADATA_INSPECTOR, package, str(self.bin_path)
File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/bkboulton/.pyenv/versions/3.7.4/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

# Fixed code
def main():
    package = sys.argv[1]
    bin_path = Path(sys.argv[2])

    apps = get_apps(package, bin_path)
    app_paths = [str(Path(bin_path) / app) for app in apps]
    app_paths_of_dependencies = {}  # type: Dict[str, List[str]]
    app_paths_of_dependencies = _dfs_package_apps(
        bin_path, package, app_paths_of_dependencies
    )

    output = {
        "apps": apps,
        "app_paths": app_paths,
        "app_paths_of_dependencies": app_paths_of_dependencies,
        "package_version": get_package_version(package),
        "python_version": "Python {}.{}.{}".format(
            sys.version_info.major, sys.version_info.minor, sys.version_info.micro
        ),
    }

    print(json.dumps(output))
# Buggy code
def guard(clusters):
    """
    Split Clusters containing conditional expressions into separate Clusters.
    """
    processed = []
    for c in clusters:
        # Group together consecutive expressions with same ConditionalDimensions
        for cds, g in groupby(c.exprs, key=lambda e: e.conditionals):
            exprs = list(g)

            if not cds:
                processed.append(c.rebuild(exprs=exprs))
                continue

            # Create a guarded Cluster
            guards = {}
            for cd in cds:
                condition = guards.setdefault(cd.parent, [])
                if cd.condition is None:
                    condition.append(CondEq(cd.parent % cd.factor, 0))
                else:
                    condition.append(lower_exprs(cd.condition))
            guards = {k: sympy.And(*v, evaluate=False) for k, v in guards.items()}
            exprs = [e.func(*e.args, conditionals=dict(guards)) for e in exprs]
            processed.append(c.rebuild(exprs=exprs, guards=guards))

    return ClusterGroup(processed)


# Traceback (AttributeError)
Traceback (most recent call last):
File "tests/mfe_args.py", line 23, in <module>
op.apply()
File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 655, in apply
args = self.arguments(**kwargs)
File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 537, in arguments
args = self._prepare_arguments(**kwargs)
File "/home/gbisbas/workspace/devito/devito/operator/operator.py", line 482, in _prepare_arguments
p._arg_check(args, self._dspace[p])
AttributeError: 'Symbol' object has no attribute '_arg_check'

# Fixed code
def guard(clusters):
    """
    Split Clusters containing conditional expressions into separate Clusters.
    """
    processed = []
    for c in clusters:
        # Group together consecutive expressions with same ConditionalDimensions
        for cds, g in groupby(c.exprs, key=lambda e: tuple(e.conditionals)):
            exprs = list(g)

            if not cds:
                processed.append(c.rebuild(exprs=exprs))
                continue

            # Chain together all conditions from all expressions in `c`
            guards = {}
            for cd in cds:
                condition = guards.setdefault(cd.parent, [])
                for e in exprs:
                    try:
                        condition.append(e.conditionals[cd])
                        break
                    except KeyError:
                        pass
            guards = {d: sympy.And(*v, evaluate=False) for d, v in guards.items()}

            # Construct a guarded Cluster
            processed.append(c.rebuild(exprs=exprs, guards=guards))

    return ClusterGroup(processed)
# Buggy code
def get_param_cached(self, key):
    resolved_key = rospy.names.resolve_name(key)
    try:
        # check for value in the parameter server cache
        return rospy.impl.paramserver.get_param_server_cache().get(resolved_key)
    except KeyError:
        # first access, make call to parameter server
        with self._lock:
            code, msg, value = self.target.subscribeParam(
                rospy.names.get_caller_id(), rospy.core.get_node_uri(), resolved_key
            )
        if code != 1:  # unwrap value with Python semantics
            raise KeyError(key)
        # set the value in the cache so that it's marked as subscribed
        rospy.impl.paramserver.get_param_server_cache().set(resolved_key, value)
        if isinstance(value, dict) and not value:
            raise KeyError(key)
        return value


# Traceback (AttributeError)
[rospy.rosout][ERROR] 2020-03-18 22:57:59,303: Unable to report rosout: __exit__
Traceback (most recent call last):
File "/home/robomaker/workspace/applications/robot-application/dependencies/opt/ros/melodic/lib/python2.7/dist-packages/rospy/impl/rosout.py", line 91, in _rosout
disable_topics_ = rospy.get_param_cached("/rosout_disable_topics_generation", False)
File "/home/robomaker/workspace/applications/robot-application/dependencies/opt/ros/melodic/lib/python2.7/dist-packages/rospy/client.py", line 490, in get_param_cached
return _param_server.get_param_cached(param_name)
File "/home/robomaker/workspace/applications/robot-application/dependencies/opt/ros/melodic/lib/python2.7/dist-packages/rospy/msproxy.py", line 162, in get_param_cached
with self._lock:
AttributeError: __exit__

# Fixed code
def get_param_cached(self, key):
    resolved_key = rospy.names.resolve_name(key)
    try:
        # check for value in the parameter server cache
        return rospy.impl.paramserver.get_param_server_cache().get(resolved_key)
    except KeyError:
        # first access, make call to parameter server
        code, msg, value = self.target.subscribeParam(
            rospy.names.get_caller_id(), rospy.core.get_node_uri(), resolved_key
        )
        if code != 1:  # unwrap value with Python semantics
            raise KeyError(key)
        # set the value in the cache so that it's marked as subscribed
        rospy.impl.paramserver.get_param_server_cache().set(resolved_key, value)
        if isinstance(value, dict) and not value:
            raise KeyError(key)
        return value
# Buggy code
def _rostopic_list_group_by_host(master, pubs, subs):
    """
    Build up maps for hostname to topic list per hostname
    :returns: publishers host map, subscribers host map, ``{str: set(str)}, {str: set(str)}``
    """

    def build_map(master, state, uricache):
        tmap = {}
        for topic, ttype, tnodes in state:
            for p in tnodes:
                if not p in uricache:
                    uricache[p] = master.lookupNode(p)
                uri = uricache[p]
                puri = urlparse(uri)
                if not puri.hostname in tmap:
                    tmap[puri.hostname] = []
                # recreate the system state data structure, but for a single host
                matches = [l for x, l in tmap[puri.hostname] if x == topic]
                if matches:
                    matches[0].append(p)
                else:
                    tmap[puri.hostname].append((topic, [p]))
        return tmap

    uricache = {}
    host_pub_topics = build_map(master, pubs, uricache)
    host_sub_topics = build_map(master, subs, uricache)
    return host_pub_topics, host_sub_topics


# Traceback (ValueError)
Host [vboxros]:
Traceback (most recent call last):
File "/opt/ros/melodic/bin/rostopic", line 35, in <module>
rostopic.rostopicmain()
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 2119, in rostopicmain
_rostopic_cmd_list(argv)
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 2059, in _rostopic_cmd_list
exitval = _rostopic_list(topic, verbose=options.verbose, subscribers_only=options.subscribers, publishers_only=options.publishers, group_by_host=options.hostname) or 0
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 1242, in _rostopic_list
verbose, indent='  ')
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 1150, in _sub_rostopic_list
topics = list(set([t for t, _, _ in pubs] + [t for t, _, _ in subs]))
ValueError: need more than 2 values to unpack

# Fixed code
def _rostopic_list_group_by_host(master, pubs, subs):
    """
    Build up maps for hostname to topic list per hostname
    :returns: publishers host map, subscribers host map, ``{str: set(str)}, {str: set(str)}``
    """

    def build_map(master, state, uricache):
        tmap = {}
        for topic, ttype, tnodes in state:
            for p in tnodes:
                if not p in uricache:
                    uricache[p] = master.lookupNode(p)
                uri = uricache[p]
                puri = urlparse(uri)
                if not puri.hostname in tmap:
                    tmap[puri.hostname] = []
                # recreate the system state data structure, but for a single host
                matches = [l for x, _, l in tmap[puri.hostname] if x == topic]
                if matches:
                    matches[0].append(p)
                else:
                    tmap[puri.hostname].append((topic, ttype, [p]))
        return tmap

    uricache = {}
    host_pub_topics = build_map(master, pubs, uricache)
    host_sub_topics = build_map(master, subs, uricache)
    return host_pub_topics, host_sub_topics
# Buggy code
def build_map(master, state, uricache):
    tmap = {}
    for topic, ttype, tnodes in state:
        for p in tnodes:
            if not p in uricache:
                uricache[p] = master.lookupNode(p)
            uri = uricache[p]
            puri = urlparse(uri)
            if not puri.hostname in tmap:
                tmap[puri.hostname] = []
            # recreate the system state data structure, but for a single host
            matches = [l for x, l in tmap[puri.hostname] if x == topic]
            if matches:
                matches[0].append(p)
            else:
                tmap[puri.hostname].append((topic, [p]))
    return tmap


# Traceback (ValueError)
Host [vboxros]:
Traceback (most recent call last):
File "/opt/ros/melodic/bin/rostopic", line 35, in <module>
rostopic.rostopicmain()
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 2119, in rostopicmain
_rostopic_cmd_list(argv)
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 2059, in _rostopic_cmd_list
exitval = _rostopic_list(topic, verbose=options.verbose, subscribers_only=options.subscribers, publishers_only=options.publishers, group_by_host=options.hostname) or 0
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 1242, in _rostopic_list
verbose, indent='  ')
File "/opt/ros/melodic/lib/python2.7/dist-packages/rostopic/__init__.py", line 1150, in _sub_rostopic_list
topics = list(set([t for t, _, _ in pubs] + [t for t, _, _ in subs]))
ValueError: need more than 2 values to unpack

# Fixed code
def build_map(master, state, uricache):
    tmap = {}
    for topic, ttype, tnodes in state:
        for p in tnodes:
            if not p in uricache:
                uricache[p] = master.lookupNode(p)
            uri = uricache[p]
            puri = urlparse(uri)
            if not puri.hostname in tmap:
                tmap[puri.hostname] = []
            # recreate the system state data structure, but for a single host
            matches = [l for x, _, l in tmap[puri.hostname] if x == topic]
            if matches:
                matches[0].append(p)
            else:
                tmap[puri.hostname].append((topic, ttype, [p]))
    return tmap
# Buggy code
def get_start_time(self):
    """
    Returns the start time of the bag.
    @return: a timestamp of the start of the bag
    @rtype: float, timestamp in seconds, includes fractions of a second
    """

    if self._chunks:
        start_stamp = self._chunks[0].start_time.to_sec()
    else:
        if not self._connection_indexes:
            raise ROSBagException("Bag contains no message")
        start_stamp = min(
            [index[0].time.to_sec() for index in self._connection_indexes.values()]
        )

    return start_stamp


# Traceback (IndexError)
$ unzip rosbag_reindex_issue.zip
$ rosbag info unindexed.bag
ERROR bag unindexed: unindexed.bag.  Run rosbag reindex.
$ rosbag reindex unindexed_bag
$ rosbag info unindexed.bag
Traceback (most recent call last):
File "/path/redacted/rosbag/scripts/rosbag_bin.py", line 35, in <module>
rosbag.rosbagmain()
File "/path/redacted/rosbag/src/rosbag/rosbag_main.py", line 863, in rosbagmain
cmds[cmd](argv[2:])
File "/path/redacted/rosbag/src/rosbag/rosbag_main.py", line 149, in info_cmd
print(b)
File "/path/redacted/rosbag/src/rosbag/bag.py", line 628, in __str__
start_stamp = min([index[ 0].time.to_sec() for index in self._connection_indexes.values()])
IndexError: list index out of range

# Fixed code
def get_start_time(self):
    """
    Returns the start time of the bag.
    @return: a timestamp of the start of the bag
    @rtype: float, timestamp in seconds, includes fractions of a second
    """

    if self._chunks:
        start_stamp = self._chunks[0].start_time.to_sec()
    else:
        if not self._connection_indexes:
            raise ROSBagException("Bag contains no message")
        start_stamps = [
            index[0].time.to_sec()
            for index in self._connection_indexes.values()
            if index
        ]
        start_stamp = min(start_stamps) if start_stamps else 0

    return start_stamp
# Buggy code
def get_end_time(self):
    """
    Returns the end time of the bag.
    @return: a timestamp of the end of the bag
    @rtype: float, timestamp in seconds, includes fractions of a second
    """

    if self._chunks:
        end_stamp = self._chunks[-1].end_time.to_sec()
    else:
        if not self._connection_indexes:
            raise ROSBagException("Bag contains no message")
        end_stamp = max(
            [index[-1].time.to_sec() for index in self._connection_indexes.values()]
        )

    return end_stamp


# Traceback (IndexError)
$ unzip rosbag_reindex_issue.zip
$ rosbag info unindexed.bag
ERROR bag unindexed: unindexed.bag.  Run rosbag reindex.
$ rosbag reindex unindexed_bag
$ rosbag info unindexed.bag
Traceback (most recent call last):
File "/path/redacted/rosbag/scripts/rosbag_bin.py", line 35, in <module>
rosbag.rosbagmain()
File "/path/redacted/rosbag/src/rosbag/rosbag_main.py", line 863, in rosbagmain
cmds[cmd](argv[2:])
File "/path/redacted/rosbag/src/rosbag/rosbag_main.py", line 149, in info_cmd
print(b)
File "/path/redacted/rosbag/src/rosbag/bag.py", line 628, in __str__
start_stamp = min([index[ 0].time.to_sec() for index in self._connection_indexes.values()])
IndexError: list index out of range

# Fixed code
def get_end_time(self):
    """
    Returns the end time of the bag.
    @return: a timestamp of the end of the bag
    @rtype: float, timestamp in seconds, includes fractions of a second
    """

    if self._chunks:
        end_stamp = self._chunks[-1].end_time.to_sec()
    else:
        if not self._connection_indexes:
            raise ROSBagException("Bag contains no message")
        end_stamps = [
            index[-1].time.to_sec()
            for index in self._connection_indexes.values()
            if index
        ]
        end_stamp = max(end_stamps) if end_stamps else 0

    return end_stamp
# Buggy code
def custom_strify_message(
    self,
    val,
    indent="",
    time_offset=None,
    current_time=None,
    field_filter=None,
    type_information=None,
    fixed_numeric_width=None,
    value_transform=None,
):
    # ensure to print uint8[] as array of numbers instead of string
    if type_information and type_information.startswith("uint8["):
        val = [ord(x) for x in val]
    if value_transform is not None:
        val = value_transform(val)
    return genpy.message.strify_message(
        val,
        indent=indent,
        time_offset=time_offset,
        current_time=current_time,
        field_filter=field_filter,
        fixed_numeric_width=fixed_numeric_width,
    )


# Traceback (AttributeError)
$ rostopic echo /rosout/msg -n 1
Traceback (most recent call last):
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 940, in callback
self.suffix + '\n')
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 876, in custom_strify_message
val = value_transform(val)
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 1393, in value_transform
class TransformedMessage(genpy.Message):
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 1396, in TransformedMessage
__slots__ = val.__slots__[:]
AttributeError: 'str' object has no attribute '__slots__'

$ rostopic echo /rosout/topics -n 1
Traceback (most recent call last):
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 940, in callback
self.suffix + '\n')
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 876, in custom_strify_message
val = value_transform(val)
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 1393, in value_transform
class TransformedMessage(genpy.Message):
File "<ws>/lib/python2.7/dist-packages/rostopic/__init__.py", line 1396, in TransformedMessage
__slots__ = val.__slots__[:]
AttributeError: 'list' object has no attribute '__slots__'

# Fixed code
def custom_strify_message(
    self,
    val,
    indent="",
    time_offset=None,
    current_time=None,
    field_filter=None,
    type_information=None,
    fixed_numeric_width=None,
    value_transform=None,
):
    # ensure to print uint8[] as array of numbers instead of string
    if type_information and type_information.startswith("uint8["):
        val = [ord(x) for x in val]
    if value_transform is not None:
        val = value_transform(val, type_information)
    return genpy.message.strify_message(
        val,
        indent=indent,
        time_offset=time_offset,
        current_time=current_time,
        field_filter=field_filter,
        fixed_numeric_width=fixed_numeric_width,
    )
# Buggy code
def _run(self):
    while not self._connection.done:
        queue = []
        with self._lock:
            # wait for available data
            while not self._queue and not self._connection.done:
                self._waiting = True
                self._cond_data_available.wait(1.0)
                self._waiting = False
                if self._queue:
                    self._cond_queue_swapped.notify()
            # take all data from queue for processing outside of the lock
            if self._queue:
                queue = self._queue
                self._queue = []
        # relay all data
        for data in queue:
            try:
                self._connection.write_data(data)
            except Exception as e:
                with self._cond:
                    self._error = e


# Traceback (AttributeError)
Exception in thread Thread-23:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "/opt/ros/hydro/lib/python2.7/dist-packages/rospy/impl/tcpros_pubsub.py", line 431, in _run
with self._cond:
File "/opt/ros/hydro/lib/python2.7/dist-packages/rospy/impl/tcpros_pubsub.py", line 390, in __getattr__
return getattr(self._connection, name)
AttributeError: 'TCPROSTransport' object has no attribute '_cond'

# Fixed code
def _run(self):
    while not self._connection.done:
        queue = []
        with self._lock:
            # wait for available data
            while not self._queue and not self._connection.done:
                self._waiting = True
                self._cond_data_available.wait(1.0)
                self._waiting = False
                if self._queue:
                    self._cond_queue_swapped.notify()
            # take all data from queue for processing outside of the lock
            if self._queue:
                queue = self._queue
                self._queue = []
        # relay all data
        for data in queue:
            try:
                self._connection.write_data(data)
            except Exception as e:
                with self._lock:
                    self._error = e
# Buggy code
def print_prf_per_type(
    msg: Printer, scores: Dict[str, Dict[str, float]], name: str, type: str
) -> None:
    data = [
        (k, f"{v['p'] * 100:.2f}", f"{v['r'] * 100:.2f}", f"{v['f'] * 100:.2f}")
        for k, v in scores.items()
    ]
    msg.table(
        data,
        header=("", "P", "R", "F"),
        aligns=("l", "r", "r", "r"),
        title=f"{name} (per {type})",
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "/opt/miniconda3/envs/spacy/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/opt/miniconda3/envs/spacy/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/__main__.py", line 4, in <module>
setup_cli()
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/_util.py", line 68, in setup_cli
command(prog_name=COMMAND)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/typer/main.py", line 497, in wrapper
return callback(**use_params)  # type: ignore
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 50, in evaluate_cli
silent=False,
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 130, in evaluate
print_textcats_auc_per_cat(msg, scores["cats_auc_per_type"])
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 194, in print_textcats_auc_per_cat
[(k, f"{v:.2f}") for k, v in scores.items()],
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 194, in <listcomp>
[(k, f"{v:.2f}") for k, v in scores.items()],
TypeError: unsupported format string passed to NoneType.__format__

# Fixed code
def print_prf_per_type(
    msg: Printer, scores: Dict[str, Dict[str, float]], name: str, type: str
) -> None:
    data = []
    for key, value in scores.items():
        row = [key]
        for k in ("p", "r", "f"):
            v = value[k]
            row.append(f"{v * 100:.2f}" if isinstance(v, (int, float)) else v)
        data.append(row)
    msg.table(
        data,
        header=("", "P", "R", "F"),
        aligns=("l", "r", "r", "r"),
        title=f"{name} (per {type})",
    )
# Buggy code
def print_textcats_auc_per_cat(
    msg: Printer, scores: Dict[str, Dict[str, float]]
) -> None:
    msg.table(
        [(k, f"{v:.2f}") for k, v in scores.items()],
        header=("", "ROC AUC"),
        aligns=("l", "r"),
        title="Textcat ROC AUC (per label)",
    )


# Traceback (TypeError)
Traceback (most recent call last):
File "/opt/miniconda3/envs/spacy/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/opt/miniconda3/envs/spacy/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/__main__.py", line 4, in <module>
setup_cli()
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/_util.py", line 68, in setup_cli
command(prog_name=COMMAND)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/typer/main.py", line 497, in wrapper
return callback(**use_params)  # type: ignore
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 50, in evaluate_cli
silent=False,
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 130, in evaluate
print_textcats_auc_per_cat(msg, scores["cats_auc_per_type"])
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 194, in print_textcats_auc_per_cat
[(k, f"{v:.2f}") for k, v in scores.items()],
File "/opt/miniconda3/envs/spacy/lib/python3.6/site-packages/spacy/cli/evaluate.py", line 194, in <listcomp>
[(k, f"{v:.2f}") for k, v in scores.items()],
TypeError: unsupported format string passed to NoneType.__format__

# Fixed code
def print_textcats_auc_per_cat(
    msg: Printer, scores: Dict[str, Dict[str, float]]
) -> None:
    msg.table(
        [
            (k, f"{v:.2f}" if isinstance(v, (float, int)) else v)
            for k, v in scores.items()
        ],
        header=("", "ROC AUC"),
        aligns=("l", "r"),
        title="Textcat ROC AUC (per label)",
    )
# Buggy code
def to_bytes(self):
    """Serialize the DocBin's annotations to a bytestring.

    RETURNS (bytes): The serialized DocBin.

    DOCS: https://spacy.io/api/docbin#to_bytes
    """
    for tokens in self.tokens:
        assert len(tokens.shape) == 2, tokens.shape  # this should never happen
    lengths = [len(tokens) for tokens in self.tokens]
    msg = {
        "attrs": self.attrs,
        "tokens": numpy.vstack(self.tokens).tobytes("C"),
        "spaces": numpy.vstack(self.spaces).tobytes("C"),
        "lengths": numpy.asarray(lengths, dtype="int32").tobytes("C"),
        "strings": list(self.strings),
        "cats": self.cats,
    }
    if self.store_user_data:
        msg["user_data"] = self.user_data
    return zlib.compress(srsly.msgpack_dumps(msg))


# Traceback (ValueError)
ValueError                                Traceback (most recent call last)
<ipython-input-6-d51ca7c2f6fe> in <module>
----> 1 doc_bin_bytes = doc_bin.to_bytes()

~/anaconda3/envs/insights/lib/python3.7/site-packages/spacy/tokens/_serialize.py in to_bytes(self)
141         msg = {
142             "attrs": self.attrs,
--> 143             "tokens": numpy.vstack(self.tokens).tobytes("C"),
144             "spaces": numpy.vstack(self.spaces).tobytes("C"),
145             "lengths": numpy.asarray(lengths, dtype="int32").tobytes("C"),

<__array_function__ internals> in vstack(*args, **kwargs)

~/anaconda3/envs/insights/lib/python3.7/site-packages/numpy/core/shape_base.py in vstack(tup)
281     if not isinstance(arrs, list):
282         arrs = [arrs]
--> 283     return _nx.concatenate(arrs, 0)
284
285

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: need at least one array to concatenate

# Fixed code
def to_bytes(self):
    """Serialize the DocBin's annotations to a bytestring.

    RETURNS (bytes): The serialized DocBin.

    DOCS: https://spacy.io/api/docbin#to_bytes
    """
    for tokens in self.tokens:
        assert len(tokens.shape) == 2, tokens.shape  # this should never happen
    lengths = [len(tokens) for tokens in self.tokens]
    tokens = numpy.vstack(self.tokens) if self.tokens else numpy.asarray([])
    spaces = numpy.vstack(self.spaces) if self.spaces else numpy.asarray([])

    msg = {
        "attrs": self.attrs,
        "tokens": tokens.tobytes("C"),
        "spaces": spaces.tobytes("C"),
        "lengths": numpy.asarray(lengths, dtype="int32").tobytes("C"),
        "strings": list(self.strings),
        "cats": self.cats,
    }
    if self.store_user_data:
        msg["user_data"] = self.user_data
    return zlib.compress(srsly.msgpack_dumps(msg))
# Buggy code
def _apply_model(nlp):
    for text, annotation in TRAIN_DATA:
        doc = nlp.tokenizer(text)

        # set entities so the evaluation is independent of the NER step
        # all the examples contain 'Russ Cochran' as the first two tokens in the sentence
        rc_ent = Span(doc, 0, 2, label=PERSON)
        doc.ents = [rc_ent]

        # apply the entity linker which will now make predictions for the 'Russ Cochran' entities
        doc = nlp.get_pipe("entity_linker")(doc)

        print()
        print("Entities", [(ent.text, ent.label_, ent.kb_id_) for ent in doc.ents])
        print("Tokens", [(t.text, t.ent_type_, t.ent_kb_id_) for t in doc])


# Traceback (KeyError)
Created blank 'en' model with vocab from 'tmp/vocab'
Loaded Knowledge Base from 'tmp/kb'
('Russ Cochran his reprints include EC Comics.', 'Russ Cochran captured his first major title with his son as caddie.', 'Russ Cochran has been publishing comic art.', "Russ Cochran was a member of University of Kentucky's golf team.") ({'links': {(0, 12): {'Q7381115': 1.0, 'Q2146908': 0.0}}}, {'links': {(0, 12): {'Q7381115': 0.0, 'Q2146908': 1.0}}}, {'links': {(0, 12): {'Q7381115': 1.0, 'Q2146908': 0.0}}}, {'links': {(0, 12): {'Q7381115': 0.0, 'Q2146908': 1.0}}})
Traceback (most recent call last):
File "train_entity_linker.py", line 167, in <module>
plac.call(main)
File "/Users/johngiorgi/miniconda3/envs/el/lib/python3.7/site-packages/plac_core.py", line 367, in call
cmd, result = parser.consume(arglist)
File "/Users/johngiorgi/miniconda3/envs/el/lib/python3.7/site-packages/plac_core.py", line 232, in consume
return cmd, self.func(*(args + varargs + extraopts), **kwargs)
File "train_entity_linker.py", line 127, in main
sgd=optimizer,
File "/Users/johngiorgi/miniconda3/envs/el/lib/python3.7/site-packages/spacy/language.py", line 515, in update
proc.update(docs, golds, sgd=get_grads, losses=losses, **kwargs)
File "pipes.pyx", line 1219, in spacy.pipeline.pipes.EntityLinker.update
KeyError: (0, 12)

# Fixed code
def _apply_model(nlp):
    for text, annotation in TRAIN_DATA:
        # apply the entity linker which will now make predictions for the 'Russ Cochran' entities
        doc = nlp(text)
        print()
        print("Entities", [(ent.text, ent.label_, ent.kb_id_) for ent in doc.ents])
        print("Tokens", [(t.text, t.ent_type_, t.ent_kb_id_) for t in doc])
# Buggy code
def _collate_best_model(meta, output_path, components):
    bests = {}
    for component in components:
        bests[component] = _find_best(output_path, component)
    best_dest = output_path / "model-best"
    shutil.copytree(output_path / "model-final", best_dest)
    for component, best_component_src in bests.items():
        shutil.rmtree(best_dest / component)
        shutil.copytree(best_component_src / component, best_dest / component)
        accs = srsly.read_json(best_component_src / "accuracy.json")
        for metric in _get_metrics(component):
            meta["accuracy"][metric] = accs[metric]
    srsly.write_json(best_dest / "meta.json", meta)
    return best_dest


# Traceback (TypeError)
File "[...]/lib/python3.5/site-packages/spacy/cli/train.py", line 382, in _collate_best_model
shutil.copytree(output_path / "model-final", best_dest)
File "[...]/lib/python3.5/shutil.py", line 309, in copytree
names = os.listdir(src)
TypeError: argument should be string, bytes or integer, not PosixPath
Exception ignored in: <bound method GoldCorpus.__del__ of <spacy.gold.GoldCorpus object at 0x7f6e53d262b0>>
Traceback (most recent call last):
File "gold.pyx", line 116, in spacy.gold.GoldCorpus.__del__
File "[...]/lib/python3.5/shutil.py", line 471, in rmtree
onerror(os.lstat, path, sys.exc_info())
File "[...]/lib/python3.5/shutil.py", line 469, in rmtree
orig_st = os.lstat(path)
TypeError: lstat: illegal type for path parameter

# Fixed code
def _collate_best_model(meta, output_path, components):
    bests = {}
    for component in components:
        bests[component] = _find_best(output_path, component)
    best_dest = output_path / "model-best"
    shutil.copytree(path2str(output_path / "model-final"), path2str(best_dest))
    for component, best_component_src in bests.items():
        shutil.rmtree(path2str(best_dest / component))
        shutil.copytree(
            path2str(best_component_src / component), path2str(best_dest / component)
        )
        accs = srsly.read_json(best_component_src / "accuracy.json")
        for metric in _get_metrics(component):
            meta["accuracy"][metric] = accs[metric]
    srsly.write_json(best_dest / "meta.json", meta)
    return best_dest
# Buggy code
def build_bow_text_classifier(
    nr_class, ngram_size=1, exclusive_classes=False, no_output_layer=False, **cfg
):
    with Model.define_operators({">>": chain}):
        model = extract_ngrams(ngram_size, attr=ORTH) >> with_cpu(
            Model.ops, LinearModel(nr_class)
        )
        if not no_output_layer:
            model = model >> (cpu_softmax if exclusive_classes else logistic)
    model.nO = nr_class
    return model


# Traceback (TypeError)
Traceback (most recent call last):
...
nlp.update(texts, annotations, sgd=optimizer, drop=0.5, losses=losses)
File "venv/lib/python3.7/site-packages/spacy/language.py", line 452, in update
proc.update(docs, golds, sgd=get_grads, losses=losses, **kwargs)
File "pipes.pyx", line 931, in spacy.pipeline.pipes.TextCategorizer.update
File "venv/lib/python3.7/site-packages/thinc/neural/_classes/feed_forward.py", line 46, in begin_update
X, inc_layer_grad = layer.begin_update(X, drop=drop)
File "venv/lib/python3.7/site-packages/thinc/api.py", line 132, in begin_update
values = [fwd(X, *a, **k) for fwd in forward]
File "venv/lib/python3.7/site-packages/thinc/api.py", line 132, in <listcomp>
values = [fwd(X, *a, **k) for fwd in forward]
File "venv/lib/python3.7/site-packages/thinc/api.py", line 225, in wrap
output = func(*args, **kwargs)
File "venv/lib/python3.7/site-packages/thinc/neural/_classes/feed_forward.py", line 46, in begin_update
X, inc_layer_grad = layer.begin_update(X, drop=drop)
File "venv/lib/python3.7/site-packages/spacy/_ml.py", line 138, in begin_update
keys = self.ops.xp.concatenate(ngrams)
File "venv/lib/python3.7/site-packages/cupy/manipulation/join.py", line 49, in concatenate
return core.concatenate_method(tup, axis)
File "cupy/core/_routines_manipulation.pyx", line 561, in cupy.core._routines_manipulation.concatenate_method
File "cupy/core/_routines_manipulation.pyx", line 574, in cupy.core._routines_manipulation.concatenate_method
TypeError: Only cupy arrays can be concatenated

# Fixed code
def build_bow_text_classifier(
    nr_class, ngram_size=1, exclusive_classes=False, no_output_layer=False, **cfg
):
    with Model.define_operators({">>": chain}):
        model = with_cpu(
            Model.ops, extract_ngrams(ngram_size, attr=ORTH) >> LinearModel(nr_class)
        )
        if not no_output_layer:
            model = model >> (cpu_softmax if exclusive_classes else logistic)
    model.nO = nr_class
    return model
# Buggy code
def POS_tree(root, light=False, flat=False):
    """Helper: generate a POS tree for a root token. The doc must have
    `merge_ents(doc)` ran on it.
    """
    subtree = format_POS(root, light=light, flat=flat)
    for c in root.children:
        subtree["modifiers"].append(POS_tree(c))
    return subtree


# Traceback (KeyError)
$ python
Python 3.7.2 (default, Jan  3 2019, 02:55:40)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
import spacy
nlp = spacy.load('en_core_web_sm')
doc = nlp('Alice ate the pizza')
doc.print_tree(flat=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "doc.pyx", line 983, in spacy.tokens.doc.Doc.print_tree
File "/venv/lib/python3.7/site-packages/spacy/tokens/printers.py", line 74, in parse_tree
for sent in doc_clone.sents]
File "/venv/lib/python3.7/site-packages/spacy/tokens/printers.py", line 74, in <listcomp>
for sent in doc_clone.sents]
File "/venv/lib/python3.7/site-packages/spacy/tokens/printers.py", line 41, in POS_tree
subtree["modifiers"].append(POS_tree(c))
KeyError: 'modifiers'

# Fixed code
def POS_tree(root, light=False, flat=False):
    """Helper: generate a POS tree for a root token. The doc must have
    `merge_ents(doc)` ran on it.
    """
    subtree = format_POS(root, light=light, flat=flat)
    if not flat:
        for c in root.children:
            subtree["modifiers"].append(POS_tree(c))
    return subtree
# Buggy code
def __init__(self, cls, nlp=None):
    self.vocab = nlp.vocab if nlp is not None else cls.create_vocab(nlp)

    MeCab = try_mecab_import()
    self.tokenizer = MeCab.Tagger()


# Traceback (ValueError)
import spacy
nlp = spacy.blank('ja')
nlp('pythonが大好きです')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/spacy/language.py", line 340, in __call__
doc = self.make_doc(text)
File "/usr/local/lib/python3.6/site-packages/spacy/lang/ja/__init__.py", line 117, in make_doc
return self.tokenizer(text)
File "/usr/local/lib/python3.6/site-packages/spacy/lang/ja/__init__.py", line 81, in __call__
doc = Doc(self.vocab, words=words, spaces=[False]*len(words))
File "doc.pyx", line 176, in spacy.tokens.doc.Doc.__init__
File "doc.pyx", line 559, in spacy.tokens.doc.Doc.push_back
ValueError: [E031] Invalid token: empty string ('') at position 0.
nlp('pythonが大好きです')
pythonが大好きです


# Fixed code
def __init__(self, cls, nlp=None):
    self.vocab = nlp.vocab if nlp is not None else cls.create_vocab(nlp)

    MeCab = try_mecab_import()
    self.tokenizer = MeCab.Tagger()
    self.tokenizer.parseToNode("")  # see #2901
# Buggy code
def load_data(limit=0, split=0.8):
    """Load data from the IMDB dataset."""
    # Partition off part of the train data for evaluation
    train_data, _ = thinc.extra.datasets.imdb()
    random.shuffle(train_data)
    train_data = train_data[-limit:]
    texts, labels = zip(*train_data)
    cats = [{"POSITIVE": bool(y)} for y in labels]
    split = int(len(train_data) * split)
    return (texts[:split], cats[:split]), (texts[split:], cats[split:])


# Traceback (TypeError)
$ python scripts/train_textcat.py
Created blank 'en' model
Loading IMDB data...
Using 2000 examples (1600 training, 400 evaluation)
Training the model...
LOSS      P       R       F
Traceback (most recent call last):
File "scripts/train_textcat.py", line 133, in <module>
plac.call(main)
File "/home/motoki/aes/lib/python3.6/site-packages/plac_core.py", line 328, in call
cmd, result = parser.consume(arglist)
File "/home/motoki/aes/lib/python3.6/site-packages/plac_core.py", line 207, in consume
return cmd, self.func(*(args + varargs + extraopts), **kwargs)
File "scripts/train_textcat.py", line 68, in main
losses=losses)
File "/home/motoki/aes/lib/python3.6/site-packages/spacy/language.py", line 407, in update
proc.update(docs, golds, drop=drop, sgd=get_grads, losses=losses)
File "pipeline.pyx", line 817, in spacy.pipeline.TextCategorizer.update
File "/home/motoki/aes/lib/python3.6/site-packages/thinc/api.py", line 61, in begin_update
X, inc_layer_grad = layer.begin_update(X, drop=drop)
File "/home/motoki/aes/lib/python3.6/site-packages/thinc/api.py", line 176, in begin_update
values = [fwd(X, *a, **k) for fwd in forward]
File "/home/motoki/aes/lib/python3.6/site-packages/thinc/api.py", line 176, in <listcomp>
values = [fwd(X, *a, **k) for fwd in forward]
File "/home/motoki/aes/lib/python3.6/site-packages/thinc/api.py", line 258, in wrap
output = func(*args, **kwargs)
File "/home/motoki/aes/lib/python3.6/site-packages/thinc/api.py", line 61, in begin_update
X, inc_layer_grad = layer.begin_update(X, drop=drop)
File "/home/motoki/aes/lib/python3.6/site-packages/spacy/_ml.py", line 101, in _preprocess_doc
keys = ops.xp.concatenate(keys)
File "/home/motoki/aes/lib/python3.6/site-packages/cupy/manipulation/join.py", line 49, in concatenate
return core.concatenate_method(tup, axis)
File "cupy/core/core.pyx", line 2410, in cupy.core.core.concatenate_method
File "cupy/core/core.pyx", line 2422, in cupy.core.core.concatenate_method
TypeError: Only cupy arrays can be concatenated

# Fixed code
def load_data(limit=0, split=0.8):
    """Load data from the IMDB dataset."""
    # Partition off part of the train data for evaluation
    train_data, _ = thinc.extra.datasets.imdb()
    random.shuffle(train_data)
    train_data = train_data[-limit:]
    texts, labels = zip(*train_data)
    cats = [{"POSITIVE": bool(y), "NEGATIVE": not bool(y)} for y in labels]
    split = int(len(train_data) * split)
    return (texts[:split], cats[:split]), (texts[split:], cats[split:])