gurudesh/pytracebugs huggingface dataset:
# Buggy code
def astype(self, dtype, copy=True):
    """
    Cast to a NumPy array with 'dtype'.

    Parameters
    ----------
    dtype : str or dtype
        Typecode or data-type to which the array is cast.
    copy : bool, default True
        Whether to copy the data, even if not necessary. If False,
        a copy is made only if the old dtype does not match the
        new dtype.

    Returns
    -------
    array : ndarray
        NumPy ndarray with 'dtype' for its dtype.
    """
    if isinstance(dtype, GeometryDtype):
        if copy:
            return self.copy()
        else:
            return self
    return np.array(self, dtype=dtype, copy=copy)


# Traceback (ValueError)
$ conda create -n gpd060 python=3.6 geopandas=0.6.0
<conda output>
$ conda activate gpd060
(gpd060) $ python
Python 3.6.7 | packaged by conda-forge | (default, Jul  2 2019, 02:07:37)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
from shapely.wkt import loads
import geopandas as gpd
geom_str = 'MULTIPOLYGON (((1 0, 1 1, 0 1, 0 0, 1 0)), ((3 0, 3 1, 2 1, 2 0, 3 0)))'
geom = loads(geom_str)
gdf = gpd.GeoDataFrame(geometry=[geom])
gdf.to_csv()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/john.flavin/anaconda3/envs/gpd060/lib/python3.6/site-packages/pandas/core/generic.py", line 3228, in to_csv
formatter.save()
File "/Users/john.flavin/anaconda3/envs/gpd060/lib/python3.6/site-packages/pandas/io/formats/csvs.py", line 202, in save
self._save()
File "/Users/john.flavin/anaconda3/envs/gpd060/lib/python3.6/site-packages/pandas/io/formats/csvs.py", line 324, in _save
self._save_chunk(start_i, end_i)
File "/Users/john.flavin/anaconda3/envs/gpd060/lib/python3.6/site-packages/pandas/io/formats/csvs.py", line 340, in _save_chunk
quoting=self.quoting,
File "/Users/john.flavin/anaconda3/envs/gpd060/lib/python3.6/site-packages/pandas/core/internals/blocks.py", line 760, in to_native_types
values = values.astype(str)
ValueError: setting an array element with a sequence

# Fixed code
def astype(self, dtype, copy=True):
    """
    Cast to a NumPy array with 'dtype'.

    Parameters
    ----------
    dtype : str or dtype
        Typecode or data-type to which the array is cast.
    copy : bool, default True
        Whether to copy the data, even if not necessary. If False,
        a copy is made only if the old dtype does not match the
        new dtype.

    Returns
    -------
    array : ndarray
        NumPy ndarray with 'dtype' for its dtype.
    """
    if isinstance(dtype, GeometryDtype):
        if copy:
            return self.copy()
        else:
            return self
    elif pd.api.types.is_string_dtype(dtype) and not pd.api.types.is_object_dtype(
        dtype
    ):
        return to_wkt(self).astype(dtype, copy=False)
    else:
        return np.array(self, dtype=dtype, copy=copy)
# Buggy code
def from_wkb(data):
    """
    Convert a list or array of WKB objects to a GeometryArray.
    """
    import shapely.wkb

    n = len(data)

    out = []

    for idx in range(n):
        geom = data[idx]
        if geom is not None and len(geom):
            geom = shapely.wkb.loads(geom)
        else:
            geom = None
        out.append(geom)

    out = np.array(out, dtype=object)
    return GeometryArray(out)


# Traceback (ValueError)
Traceback (most recent call last):
File "intersection_crash.py", line 17, in <module>
intersection_big_gdf = gpd.overlay(concave_polygon_gdf, big_rect_polygon_gdf, how='intersection')
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 362, in overlay
result = _overlay_intersection(df1, df2)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 217, in _overlay_intersection
intersections = left.intersection(right).buffer(0)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 530, in buffer
resolution=resolution, **kwargs)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 92, in _delegate_geo_method
data = getattr(a_this, op)(*args, **kwargs).data
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 616, in buffer
return GeometryArray(np.array(data, dtype=object))
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 407, in __init__
"'data' should be a 1-dimensional array of geometry objects.")
ValueError: 'data' should be a 1-dimensional array of geometry objects.

# Fixed code
def from_wkb(data):
    """
    Convert a list or array of WKB objects to a GeometryArray.
    """
    import shapely.wkb

    n = len(data)

    out = []

    for idx in range(n):
        geom = data[idx]
        if geom is not None and len(geom):
            geom = shapely.wkb.loads(geom)
        else:
            geom = None
        out.append(geom)

    aout = np.empty(n, dtype=object)
    aout[:] = out
    return GeometryArray(aout)
# Buggy code
def from_wkt(data):
    """
    Convert a list or array of WKT objects to a GeometryArray.
    """
    import shapely.wkt

    n = len(data)

    out = []

    for idx in range(n):
        geom = data[idx]
        if geom is not None and len(geom):
            if isinstance(geom, bytes):
                geom = geom.decode("utf-8")
            geom = shapely.wkt.loads(geom)
        else:
            geom = None
        out.append(geom)

    out = np.array(out, dtype=object)
    return GeometryArray(out)


# Traceback (ValueError)
Traceback (most recent call last):
File "intersection_crash.py", line 17, in <module>
intersection_big_gdf = gpd.overlay(concave_polygon_gdf, big_rect_polygon_gdf, how='intersection')
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 362, in overlay
result = _overlay_intersection(df1, df2)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 217, in _overlay_intersection
intersections = left.intersection(right).buffer(0)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 530, in buffer
resolution=resolution, **kwargs)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 92, in _delegate_geo_method
data = getattr(a_this, op)(*args, **kwargs).data
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 616, in buffer
return GeometryArray(np.array(data, dtype=object))
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 407, in __init__
"'data' should be a 1-dimensional array of geometry objects.")
ValueError: 'data' should be a 1-dimensional array of geometry objects.

# Fixed code
def from_wkt(data):
    """
    Convert a list or array of WKT objects to a GeometryArray.
    """
    import shapely.wkt

    n = len(data)

    out = []

    for idx in range(n):
        geom = data[idx]
        if geom is not None and len(geom):
            if isinstance(geom, bytes):
                geom = geom.decode("utf-8")
            geom = shapely.wkt.loads(geom)
        else:
            geom = None
        out.append(geom)

    aout = np.empty(n, dtype=object)
    aout[:] = out
    return GeometryArray(aout)
# Buggy code
def points_from_xy(x, y, z=None):
    """Convert arrays of x and y values to a GeometryArray of points."""
    x = np.asarray(x, dtype="float64")
    y = np.asarray(y, dtype="float64")
    if z is not None:
        z = np.asarray(z, dtype="float64")
    out = _points_from_xy(x, y, z)
    out = np.array(out, dtype=object)
    return GeometryArray(out)


# Traceback (ValueError)
Traceback (most recent call last):
File "intersection_crash.py", line 17, in <module>
intersection_big_gdf = gpd.overlay(concave_polygon_gdf, big_rect_polygon_gdf, how='intersection')
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 362, in overlay
result = _overlay_intersection(df1, df2)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 217, in _overlay_intersection
intersections = left.intersection(right).buffer(0)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 530, in buffer
resolution=resolution, **kwargs)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 92, in _delegate_geo_method
data = getattr(a_this, op)(*args, **kwargs).data
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 616, in buffer
return GeometryArray(np.array(data, dtype=object))
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 407, in __init__
"'data' should be a 1-dimensional array of geometry objects.")
ValueError: 'data' should be a 1-dimensional array of geometry objects.

# Fixed code
def points_from_xy(x, y, z=None):
    """Convert arrays of x and y values to a GeometryArray of points."""
    x = np.asarray(x, dtype="float64")
    y = np.asarray(y, dtype="float64")
    if z is not None:
        z = np.asarray(z, dtype="float64")
    out = _points_from_xy(x, y, z)
    aout = np.empty(len(x), dtype=object)
    aout[:] = out
    return GeometryArray(aout)
# Buggy code
def _affinity_method(op, left, *args, **kwargs):
    # type: (str, GeometryArray, ...) -> GeometryArray

    # not all shapely.affinity methods can handle empty geometries:
    # affine_transform itself works (as well as translate), but rotate, scale
    # and skew fail (they try to unpack the bounds).
    # Here: consistently returning empty geom for input empty geom
    data = []
    for geom in left.data:
        if geom is None or geom.is_empty:
            res = geom
        else:
            res = getattr(shapely.affinity, op)(geom, *args, **kwargs)
        data.append(res)
    return GeometryArray(np.array(data, dtype=object))


# Traceback (ValueError)
Traceback (most recent call last):
File "intersection_crash.py", line 17, in <module>
intersection_big_gdf = gpd.overlay(concave_polygon_gdf, big_rect_polygon_gdf, how='intersection')
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 362, in overlay
result = _overlay_intersection(df1, df2)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 217, in _overlay_intersection
intersections = left.intersection(right).buffer(0)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 530, in buffer
resolution=resolution, **kwargs)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 92, in _delegate_geo_method
data = getattr(a_this, op)(*args, **kwargs).data
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 616, in buffer
return GeometryArray(np.array(data, dtype=object))
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 407, in __init__
"'data' should be a 1-dimensional array of geometry objects.")
ValueError: 'data' should be a 1-dimensional array of geometry objects.

# Fixed code
def _affinity_method(op, left, *args, **kwargs):
    # type: (str, GeometryArray, ...) -> GeometryArray

    # not all shapely.affinity methods can handle empty geometries:
    # affine_transform itself works (as well as translate), but rotate, scale
    # and skew fail (they try to unpack the bounds).
    # Here: consistently returning empty geom for input empty geom
    out = []
    for geom in left.data:
        if geom is None or geom.is_empty:
            res = geom
        else:
            res = getattr(shapely.affinity, op)(geom, *args, **kwargs)
        out.append(res)
    data = np.empty(len(left), dtype=object)
    data[:] = out
    return GeometryArray(data)
# Buggy code
def interiors(self):
    has_non_poly = False
    inner_rings = []
    for geom in self.data:
        interior_ring_seq = getattr(geom, "interiors", None)
        # polygon case
        if interior_ring_seq is not None:
            inner_rings.append(list(interior_ring_seq))
        # non-polygon case
        else:
            has_non_poly = True
            inner_rings.append(None)
    if has_non_poly:
        warnings.warn(
            "Only Polygon objects have interior rings. For other "
            "geometry types, None is returned."
        )

    return np.array(inner_rings, dtype=object)


# Traceback (ValueError)
Traceback (most recent call last):
File "intersection_crash.py", line 17, in <module>
intersection_big_gdf = gpd.overlay(concave_polygon_gdf, big_rect_polygon_gdf, how='intersection')
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 362, in overlay
result = _overlay_intersection(df1, df2)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 217, in _overlay_intersection
intersections = left.intersection(right).buffer(0)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 530, in buffer
resolution=resolution, **kwargs)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 92, in _delegate_geo_method
data = getattr(a_this, op)(*args, **kwargs).data
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 616, in buffer
return GeometryArray(np.array(data, dtype=object))
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 407, in __init__
"'data' should be a 1-dimensional array of geometry objects.")
ValueError: 'data' should be a 1-dimensional array of geometry objects.

# Fixed code
def interiors(self):
    has_non_poly = False
    inner_rings = []
    for geom in self.data:
        interior_ring_seq = getattr(geom, "interiors", None)
        # polygon case
        if interior_ring_seq is not None:
            inner_rings.append(list(interior_ring_seq))
        # non-polygon case
        else:
            has_non_poly = True
            inner_rings.append(None)
    if has_non_poly:
        warnings.warn(
            "Only Polygon objects have interior rings. For other "
            "geometry types, None is returned."
        )
    data = np.empty(len(self), dtype=object)
    data[:] = inner_rings
    return data
# Buggy code
def buffer(self, distance, resolution=16, **kwargs):
    if isinstance(distance, np.ndarray):
        if len(distance) != len(self):
            raise ValueError(
                "Length of distance sequence does not match length of the GeoSeries"
            )
        data = [
            geom.buffer(dist, resolution, **kwargs) if geom is not None else None
            for geom, dist in zip(self.data, distance)
        ]
        return GeometryArray(np.array(data, dtype=object))

    data = [
        geom.buffer(distance, resolution, **kwargs) if geom is not None else None
        for geom in self.data
    ]
    return GeometryArray(np.array(data, dtype=object))


# Traceback (ValueError)
Traceback (most recent call last):
File "intersection_crash.py", line 17, in <module>
intersection_big_gdf = gpd.overlay(concave_polygon_gdf, big_rect_polygon_gdf, how='intersection')
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 362, in overlay
result = _overlay_intersection(df1, df2)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 217, in _overlay_intersection
intersections = left.intersection(right).buffer(0)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 530, in buffer
resolution=resolution, **kwargs)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 92, in _delegate_geo_method
data = getattr(a_this, op)(*args, **kwargs).data
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 616, in buffer
return GeometryArray(np.array(data, dtype=object))
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 407, in __init__
"'data' should be a 1-dimensional array of geometry objects.")
ValueError: 'data' should be a 1-dimensional array of geometry objects.

# Fixed code
def buffer(self, distance, resolution=16, **kwargs):
    data = data = np.empty(len(self), dtype=object)
    if isinstance(distance, np.ndarray):
        if len(distance) != len(self):
            raise ValueError(
                "Length of distance sequence does not match length of the GeoSeries"
            )

        data[:] = [
            geom.buffer(dist, resolution, **kwargs) if geom is not None else None
            for geom, dist in zip(self.data, distance)
        ]
        return GeometryArray(data)

    data[:] = [
        geom.buffer(distance, resolution, **kwargs) if geom is not None else None
        for geom in self.data
    ]
    return GeometryArray(data)
# Buggy code
def interpolate(self, distance, normalized=False):
    if isinstance(distance, np.ndarray):
        if len(distance) != len(self):
            raise ValueError(
                "Length of distance sequence does not match length of the GeoSeries"
            )
        data = [
            geom.interpolate(dist, normalized=normalized)
            for geom, dist in zip(self.data, distance)
        ]
        return GeometryArray(np.array(data, dtype=object))

    data = [geom.interpolate(distance, normalized=normalized) for geom in self.data]
    return GeometryArray(np.array(data, dtype=object))


# Traceback (ValueError)
Traceback (most recent call last):
File "intersection_crash.py", line 17, in <module>
intersection_big_gdf = gpd.overlay(concave_polygon_gdf, big_rect_polygon_gdf, how='intersection')
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 362, in overlay
result = _overlay_intersection(df1, df2)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/tools/overlay.py", line 217, in _overlay_intersection
intersections = left.intersection(right).buffer(0)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 530, in buffer
resolution=resolution, **kwargs)
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/base.py", line 92, in _delegate_geo_method
data = getattr(a_this, op)(*args, **kwargs).data
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 616, in buffer
return GeometryArray(np.array(data, dtype=object))
File "/usr/local/lib/python3.6/site-packages/geopandas-0.6.0rc1-py3.6.egg/geopandas/array.py", line 407, in __init__
"'data' should be a 1-dimensional array of geometry objects.")
ValueError: 'data' should be a 1-dimensional array of geometry objects.

# Fixed code
def interpolate(self, distance, normalized=False):
    data = data = np.empty(len(self), dtype=object)
    if isinstance(distance, np.ndarray):
        if len(distance) != len(self):
            raise ValueError(
                "Length of distance sequence does not match length of the GeoSeries"
            )
        data[:] = [
            geom.interpolate(dist, normalized=normalized)
            for geom, dist in zip(self.data, distance)
        ]
        return GeometryArray(data)

    data[:] = [geom.interpolate(distance, normalized=normalized) for geom in self.data]
    return GeometryArray(data)
# Buggy code
def cleanup(self):
    super().cleanup()
    self._save_marker_cache()

    for proxy in self.export_proxies:
        proxy.cancel()
        self.export_proxies.remove(proxy)


# Traceback (RuntimeError)
Traceback (most recent call last):
File "/Users/papr/work/pupil/pupil_src/launchables/player.py", line 679, in player
g_pool.plugins.clean()
File "/Users/papr/work/pupil/pupil_src/shared_modules/plugin.py", line 396, in clean
p.cleanup()
File "/Users/papr/work/pupil/pupil_src/shared_modules/surface_tracker/surface_tracker_offline.py", line 560, in cleanup
for proxy in self.export_proxies:
RuntimeError: Set changed size during iteration

# Fixed code
def cleanup(self):
    super().cleanup()
    self._save_marker_cache()

    for proxy in self.export_proxies.copy():
        proxy.cancel()
        self.export_proxies.remove(proxy)
# Buggy code
def on_click(self, pos: Vec2, button: int, action: int) -> bool:
    if action == glfw.GLFW_PRESS:
        clicked_handle = self.get_handle_at(pos)
        if clicked_handle != self.active_handle:
            self.active_handle = clicked_handle
            return True
    elif action == glfw.GLFW_RELEASE:
        if self.active_handle != Handle.NONE:
            self.active_handle = Handle.NONE
            return True
    return False


# Traceback (AttributeError)
Traceback (most recent call last):
File "/Users/papr/work/pupil/pupil_src/launchables/eye.py", line 633, in eye
if plugin.on_click(pos, button, action):
File "/Users/papr/work/pupil/pupil_src/shared_modules/roi.py", line 287, in on_click
clicked_handle = self.get_handle_at(pos)
File "/Users/papr/work/pupil/pupil_src/shared_modules/roi.py", line 250, in get_handle_at
for handle in self._all_points.keys():
AttributeError: 'Roi' object has no attribute '_all_points'

# Fixed code
def on_click(self, pos: Vec2, button: int, action: int) -> bool:
    if not self.has_frame or self.model.is_invalid():
        return False

    if action == glfw.GLFW_PRESS:
        clicked_handle = self.get_handle_at(pos)
        if clicked_handle != self.active_handle:
            self.active_handle = clicked_handle
            return True
    elif action == glfw.GLFW_RELEASE:
        if self.active_handle != Handle.NONE:
            self.active_handle = Handle.NONE
            return True
    return False
# Buggy code
def __init__(self, name, generator, args=(), kwargs={}):
    super().__init__()

    self._should_terminate_flag = mp.Value(c_bool, 0)
    self._completed = False
    self._canceled = False

    pipe_recv, pipe_send = mp.Pipe(False)
    wrapper_args = [pipe_send, self._should_terminate_flag, generator]
    wrapper_args.extend(args)
    self.process = mp.Process(
        target=self._wrapper, name=name, args=wrapper_args, kwargs=kwargs
    )
    self.process.start()
    self.pipe = pipe_recv


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def __init__(self, name, generator, args=(), kwargs={}):
    super().__init__()

    self._should_terminate_flag = mp.Value(c_bool, 0)
    self._completed = False
    self._canceled = False

    pipe_recv, pipe_send = mp.Pipe(False)
    wrapper_args = [pipe_send, self._should_terminate_flag, generator]
    wrapper_args.extend(args)
    self.process = mp.Process(
        target=self._wrapper, name=name, args=wrapper_args, kwargs=kwargs
    )
    self.process.daemon = True
    self.process.start()
    self.pipe = pipe_recv
# Buggy code
def fetch(self):
    """Fetches progress and available results from background"""
    while self.pipe.poll(0):
        try:
            datum = self.pipe.recv()
        except EOFError:
            logger.debug("Process canceled be user.")
            return
        else:
            if isinstance(datum, StopIteration):
                self._completed = True
                return
            elif isinstance(datum, EarlyCancellationError):
                self._canceled = True
                return
            elif isinstance(datum, Exception):
                raise datum
            else:
                yield datum


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def fetch(self):
    """Fetches progress and available results from background"""
    while self.pipe.poll(0):
        try:
            datum = self.pipe.recv()
        except EOFError:
            logger.debug("Process canceled be user.")
            self._canceled = True
            self.process = None
            return
        else:
            if isinstance(datum, StopIteration):
                self._completed = True
                self.process = None
                return
            elif isinstance(datum, EarlyCancellationError):
                self._canceled = True
                self.process = None
                return
            elif isinstance(datum, Exception):
                raise datum
            else:
                yield datum
# Buggy code
def get_recording_dirs(data_dir):
    """
    You can supply a data folder or any folder
    - all folders within will be checked for necessary files
    - in order to make a visualization
    """
    filtered_recording_dirs = []
    if is_pupil_rec_dir(data_dir):
        filtered_recording_dirs.append(data_dir)
    for root, dirs, files in os.walk(data_dir):
        filtered_recording_dirs += [
            os.path.join(root, d)
            for d in dirs
            if not d.startswith(".") and is_pupil_rec_dir(os.path.join(root, d))
        ]
    logger.debug("Filtered Recording Dirs: {}".format(filtered_recording_dirs))
    return filtered_recording_dirs


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def get_recording_dirs(data_dir):
    """
    You can supply a data folder or any folder
    - all folders within will be checked for necessary files
    - in order to make a visualization
    """
    if is_pupil_rec_dir(data_dir):
        yield data_dir
    for root, dirs, files in os.walk(data_dir):
        for d in dirs:
            joined = os.path.join(root, d)
            if not d.startswith(".") and is_pupil_rec_dir(joined):
                yield joined
# Buggy code
def __init__(self, g_pool):
    super().__init__(g_pool)

    # initialize empty menu
    # and load menu configuration of last session
    self.menu = None

    self.exports = []
    self.new_exports = []
    self.active_exports = []
    default_path = os.path.expanduser("~/work/pupil/recordings/demo")
    self.destination_dir = default_path
    self.source_dir = default_path

    self.run = False
    self.workers = [None for x in range(mp.cpu_count())]
    logger.info(
        "Using a maximum of {} CPUs to process visualizations in parallel...".format(
            mp.cpu_count()
        )
    )


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def __init__(self, g_pool, source_dir="~/", destination_dir="~/"):
    super().__init__(g_pool)

    self.available_exports = []
    self.queued_exports = []
    self.active_exports = []
    self.destination_dir = os.path.expanduser(destination_dir)
    self.source_dir = os.path.expanduser(source_dir)

    self.search_task = None
    self.worker_count = cpu_count() - 1
    logger.info(
        "Using a maximum of {} CPUs to process visualizations in parallel...".format(
            cpu_count() - 1
        )
    )
# Buggy code
def init_ui(self):
    self.add_menu()
    # initialize the menu
    self.menu.label = "Batch Export Recordings"
    # load the configuration of last session
    # add menu to the window
    self._update_ui()


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def init_ui(self):
    self.add_menu()
    self.menu.label = "Batch Export Recordings"

    self.menu.append(
        ui.Info_Text(
            "Search will walk through the source direcotry recursively and detect available Pupil recordings."
        )
    )
    self.menu.append(
        ui.Text_Input(
            "source_dir", self, label="Source directory", setter=self.set_src_dir
        )
    )

    self.search_button = ui.Button("Search", self.detect_recordings)
    self.menu.append(self.search_button)

    self.avail_recs_menu = ui.Growing_Menu("Available Recordings")
    self._update_avail_recs_menu()
    self.menu.append(self.avail_recs_menu)

    self.menu.append(
        ui.Text_Input(
            "destination_dir",
            self,
            label="Destination directory",
            setter=self.set_dest_dir,
        )
    )
    self.menu.append(ui.Button("Export selected", self.queue_selected))
    self.menu.append(ui.Button("Clear search results", self._clear_avail))
    self.menu.append(ui.Separator())
    self.menu.append(ui.Button("Cancel all exports", self.cancel_all))
# Buggy code
def deinit_ui(self):
    self.remove_menu()


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def deinit_ui(self):
    self.menu.remove(self.avail_recs_menu)
    self.avail_recs_menu = None
    self.remove_menu()
# Buggy code
def set_src_dir(self, new_dir):
    new_dir = new_dir
    self.new_exports = []
    self.exports = []
    new_dir = os.path.expanduser(new_dir)
    if os.path.isdir(new_dir):
        self.source_dir = new_dir
        self.new_exports = get_recording_dirs(new_dir)
    else:
        logger.warning('"{}" is not a directory'.format(new_dir))
        return
    if self.new_exports is []:
        logger.warning('"{}" does not contain recordings'.format(new_dir))
        return

    self.add_exports()
    self._update_ui()


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def set_src_dir(self, new_dir):
    new_dir = os.path.expanduser(new_dir)
    if os.path.isdir(new_dir):
        self.source_dir = new_dir
    else:
        logger.warning('"{}" is not a directory'.format(new_dir))
        return
# Buggy code
def set_dest_dir(self, new_dir):
    new_dir = new_dir

    new_dir = os.path.expanduser(new_dir)
    if os.path.isdir(new_dir):
        self.destination_dir = new_dir
    else:
        logger.warning('"{}" is not a directory'.format(new_dir))
        return

    self.exports = []
    self.add_exports()
    self._update_ui()


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def set_dest_dir(self, new_dir):
    new_dir = os.path.expanduser(new_dir)
    if os.path.isdir(new_dir):
        self.destination_dir = new_dir
    else:
        logger.warning('"{}" is not a directory'.format(new_dir))
        return
# Buggy code
def recent_events(self, events):
    frame = events.get("frame")
    if not frame:
        return
    if self.run:
        for i in range(len(self.workers)):
            if self.workers[i] and self.workers[i].is_alive():
                pass
            else:
                logger.info("starting new job")
                if self.active_exports:
                    self.workers[i] = self.active_exports.pop(0)
                    if not self.workers[i].is_alive():
                        self.workers[i].start()
                else:
                    self.run = False


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def recent_events(self, events):
    if self.search_task:
        recent = [d for d in self.search_task.fetch()]
        if recent:
            currently_avail = [rec["source"] for rec in self.available_exports]
            self.available_exports.extend(
                [
                    {"source": rec, "selected": True}
                    for rec in recent
                    if rec not in currently_avail
                ]
            )
            self._update_avail_recs_menu()
        if self.search_task.completed:
            self.search_task = None
            self.search_button.outer_label = ""
            self.search_button.label = "Search"
# Buggy code
def recent_events(self, events):
    for e in self.exports:
        recent = [d for d in e.fetch()]
        if recent:
            e.status, e.progress = recent[-1]
        if e.canceled:
            e.status = "Export has been canceled."


# Traceback (AssertionError)
Traceback (most recent call last):
File "/home/papr/work/pupil/pupil_src/launchables/player.py", line 441, in player
p.recent_events(events)
File "/home/papr/work/pupil/pupil_src/shared_modules/batch_exporter.py", line 190, in recent_events
self.workers[i].start()
File "/usr/lib/python3.5/multiprocessing/process.py", line 99, in start
assert self._popen is None, 'cannot start a process twice'
AssertionError: cannot start a process twice

# Fixed code
def recent_events(self, events):
    for e in self.exports:
        try:
            recent = [d for d in e.fetch()]
        except Exception as e:
            self.status, self.progress = "{}: {}".format(type(e).__name__, e), 0
        else:
            if recent:
                e.status, e.progress = recent[-1]
            if e.canceled:
                e.status = "Export has been canceled."
# Buggy code
def export_annotations(self, export_range, export_dir):
    if not self.annotations:
        logger.warning("No annotations in this recording nothing to export")
        return

    annotations_in_section = chain(*self.annotations_by_frame[export_range])
    annotations_in_section = {
        a["index"]: a for a in annotations_in_section
    }.values()  # remove dublicates
    annotations_in_section.sort(key=lambda a: a["index"])

    with open(
        os.path.join(export_dir, "annotations.csv"), "w", encoding="utf-8", newline=""
    ) as csvfile:
        csv_writer = csv.writer(csvfile)
        csv_writer.writerow(self.csv_representation_keys())
        for a in annotations_in_section:
            csv_writer.writerow(self.csv_representation_for_annotations(a))
        logger.info("Created 'annotations.csv' file.")


# Traceback (AttributeError)
Traceback (most recent call last):
File "main.py", line 626, in <module>
session(this_session_dir)
File "main.py", line 490, in session
p.on_notify(n)
File "/Users/pabloprietz/work/pupil/pupil_src/shared_modules/annotations.py", line 247, in on_notify
self.export_annotations(notification['range'],notification['export_dir'])
File "/Users/pabloprietz/work/pupil/pupil_src/shared_modules/annotations.py", line 217, in export_annotations
annotations_in_section.sort(key=lambda a:a['index'])
AttributeError: 'dict_values' object has no attribute 'sort'

# Fixed code
def export_annotations(self, export_range, export_dir):
    if not self.annotations:
        logger.warning("No annotations in this recording nothing to export")
        return

    annotations_in_section = chain(*self.annotations_by_frame[export_range])
    annotations_in_section = list(
        {a["index"]: a for a in annotations_in_section}.values()
    )  # remove duplicates
    annotations_in_section.sort(key=lambda a: a["index"])

    with open(
        os.path.join(export_dir, "annotations.csv"), "w", encoding="utf-8", newline=""
    ) as csvfile:
        csv_writer = csv.writer(csvfile)
        csv_writer.writerow(self.csv_representation_keys())
        for a in annotations_in_section:
            csv_writer.writerow(self.csv_representation_for_annotations(a))
        logger.info("Created 'annotations.csv' file.")
# Buggy code
def load_object(file_path):
    file_path = os.path.expanduser(file_path)
    # reading to string and loads is 2.5x faster that using the file handle and load.
    try:
        with open(file_path, "rb") as fh:
            return pickle.load(fh, encoding="bytes")
    except pickle.UnpicklingError as e:
        raise ValueError(e)


# Traceback (AttributeError)
Traceback (most recent call last):
File "main.py", line 626, in <module>
session(this_session_dir)
File "main.py", line 490, in session
p.on_notify(n)
File "/Users/pabloprietz/work/pupil/pupil_src/shared_modules/annotations.py", line 247, in on_notify
self.export_annotations(notification['range'],notification['export_dir'])
File "/Users/pabloprietz/work/pupil/pupil_src/shared_modules/annotations.py", line 217, in export_annotations
annotations_in_section.sort(key=lambda a:a['index'])
AttributeError: 'dict_values' object has no attribute 'sort'

# Fixed code
def load_object(file_path):
    file_path = os.path.expanduser(file_path)
    # reading to string and loads is 2.5x faster that using the file handle and load.
    try:
        with open(file_path, "rb") as fh:
            return pickle.load(fh, encoding="bytes")
    except pickle.UnpicklingError as e:
        raise ValueError from e
# Buggy code
def set_items(self, data, new_items, indexes):
    if type(data) in [list, tuple]:
        data_out = data.copy()
        params = list_match_func[self.list_match_local]([indexes, new_items])
        for ind, i in zip(*params):
            if self.replace and len(data_out) > ind:
                data_out.pop(ind)
            data_out.insert(ind, i)
        return data_out
    elif type(data) == np.ndarray:
        out_data = np.array(data)
        ind, items = list_match_func[self.list_match_local]([indexes, new_items])
        if self.replace:
            out_data[ind] = items

        else:
            for i, item in zip(ind, items):
                out_data = np.concatenate([data[:i], [item], data[i:]])

        return out_data
    elif type(data) == str:
        ind, items = list_match_func[self.list_match_local]([indexes, new_items])

        add_one = 1 if self.replace else 0
        out_data = data
        for i, item in zip(ind, items):
            out_data = out_data[:i] + str(item) + out_data[i + add_one :]
        return out_data
    return None


# Traceback (AttributeError)
Traceback (most recent call last):
File "\sverchok\core\update_system.py", line 384, in do_update_general
node.process()
File "\sverchok\nodes\list_struct\item_insert.py", line 99, in process
out = self.set_items(data, new_item, indexes[0])
File "\sverchok\nodes\list_struct\item_insert.py", line 105, in set_items
data_out = data.copy()
AttributeError: 'tuple' object has no attribute 'copy'

# Fixed code
def set_items(self, data, new_items, indexes):
    if type(data) in [list, tuple]:
        data_out = data.copy() if isinstance(data, list) else list(data)
        params = list_match_func[self.list_match_local]([indexes, new_items])
        for ind, i in zip(*params):
            if self.replace and len(data_out) > ind:
                data_out.pop(ind)
            data_out.insert(ind, i)
        return data_out
    elif type(data) == np.ndarray:
        out_data = np.array(data)
        ind, items = list_match_func[self.list_match_local]([indexes, new_items])
        if self.replace:
            out_data[ind] = items

        else:
            for i, item in zip(ind, items):
                out_data = np.concatenate([data[:i], [item], data[i:]])

        return out_data
    elif type(data) == str:
        ind, items = list_match_func[self.list_match_local]([indexes, new_items])

        add_one = 1 if self.replace else 0
        out_data = data
        for i, item in zip(ind, items):
            out_data = out_data[:i] + str(item) + out_data[i + add_one :]
        return out_data
    return None
# Buggy code
def storage_get_data(self, node_dict):
    local_storage = {"knots": [], "knotsnames": []}

    for knot in self.SvLists["knots"].SvSubLists:
        local_storage["knots"].append([knot.SvX, knot.SvY, knot.SvZ])

    for outname in self.SvLists["knotsnames"].SvSubLists:
        local_storage["knotsnames"].append(outname.SvName)

    node_dict["profile_sublist_storage"] = json.dumps(local_storage, sort_keys=True)
    node_dict["path_file"] = bpy.data.texts[self.filename].as_string()


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/portnov/.config/blender/2.79/scripts/addons/sverchok-master/utils/sv_IO_panel_operators.py", line 58, in execute
layout_dict = create_dict_of_tree(ng)
File "/home/portnov/.config/blender/2.79/scripts/addons/sverchok-master/utils/sv_IO_panel_tools.py", line 298, in create_dict_of_tree
node.storage_get_data(node_dict)
File "/home/portnov/.config/blender/2.79/scripts/addons/sverchok-master/nodes/generators_extended/profile_mk2.py", line 952, in storage_get_data
for knot in self.SvLists['knots'].SvSubLists:
KeyError: 'bpy_prop_collection[key]: key "knots" not found'

# Fixed code
def storage_get_data(self, node_dict):
    local_storage = {"knots": [], "knotsnames": []}

    if "knots" in self.SvLists:
        # implies "knotsnames" will be found too.. because that's how it works..
        for knot in self.SvLists["knots"].SvSubLists:
            local_storage["knots"].append([knot.SvX, knot.SvY, knot.SvZ])

        for outname in self.SvLists["knotsnames"].SvSubLists:
            local_storage["knotsnames"].append(outname.SvName)

    # store anyway
    node_dict["profile_sublist_storage"] = json.dumps(local_storage, sort_keys=True)

    if self.filename:
        node_dict["path_file"] = bpy.data.texts[self.filename].as_string()
    else:
        node_dict["path_file"] = ""
# Buggy code
def __str__(self):
    if self.role and self.device and self.name:
        return "{} for {} ({})".format(self.role, self.device, self.name)
    # Return role and device if no name is set
    if self.role and self.device:
        return "{} for {}".format(self.role, self.device)
    return "Secret"


# Traceback (KeyError)
Internal Server Error: /dcim/devices/1611/delete/
Traceback (most recent call last):
File "/home/jstretch/.virtualenvs/netbox/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 164, in __get__
rel_obj = self.field.get_cached_value(instance)
File "/home/jstretch/.virtualenvs/netbox/lib/python3.6/site-packages/django/db/models/fields/mixins.py", line 13, in get_cached_value
return instance._state.fields_cache[cache_name]
KeyError: 'device'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/jstretch/.virtualenvs/netbox/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/jstretch/netbox/netbox/extras/middleware.py", line 110, in __call__
objectchange = instance.to_objectchange(action)
File "/home/jstretch/netbox/netbox/utilities/models.py", line 33, in to_objectchange
object_repr=str(self),
File "/home/jstretch/netbox/netbox/secrets/models.py", line 362, in __str__
if self.role and self.device and self.name:
File "/home/jstretch/.virtualenvs/netbox/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 178, in __get__
rel_obj = self.get_object(instance)
File "/home/jstretch/.virtualenvs/netbox/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 145, in get_object
return qs.get(self.field.get_reverse_related_filter(instance))
File "/home/jstretch/.virtualenvs/netbox/lib/python3.6/site-packages/cacheops/query.py", line 356, in get
return qs._no_monkey.get(qs, *args, **kwargs)
File "/home/jstretch/.virtualenvs/netbox/lib/python3.6/site-packages/django/db/models/query.py", line 408, in get
self.model._meta.object_name
dcim.models.Device.DoesNotExist: Device matching query does not exist.

# Fixed code
def __str__(self):
    try:
        device = self.device
    except Device.DoesNotExist:
        device = None
    if self.role and device and self.name:
        return "{} for {} ({})".format(self.role, self.device, self.name)
    # Return role and device if no name is set
    if self.role and device:
        return "{} for {}".format(self.role, self.device)
    return "Secret"
# Buggy code
def assign_virtualchassis_master(instance, created, **kwargs):
    """
    When a VirtualChassis is created, automatically assign its master device to the VC.
    """
    if created:
        Device.objects.filter(pk=instance.master.pk).update(
            virtual_chassis=instance, vc_position=1
        )


# Traceback (psycopg2.IntegrityError)
[user@netboxserver:netbox] python manage.py dumpdata >  ~/VCtest.json
[user@netboxserver:netbox] python manage.py flush --noinput
[user@netboxserver:netbox] python manage.py loaddata ~/VCtest.json
Traceback (most recent call last):
File "/var/netbox_env/lib/python3.6/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
psycopg2.IntegrityError: duplicate key value violates unique constraint "dcim_device_virtual_chassis_id_vc_position_efea7133_uniq"
DETAIL:  Key (virtual_chassis_id, vc_position)=(1, 1) already exists.

# Fixed code
def assign_virtualchassis_master(instance, created, **kwargs):
    """
    When a VirtualChassis is created, automatically assign its master device to the VC.
    """
    # Default to 1 but don't overwrite an existing position (see #2087)
    if instance.master.vc_position is not None:
        vc_position = instance.master.vc_position
    else:
        vc_position = 1
    if created:
        Device.objects.filter(pk=instance.master.pk).update(
            virtual_chassis=instance, vc_position=vc_position
        )