gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _is_token_non_standard(symbol: str, address: ChecksumEthAddress) -> bool:
    """ignore some assets we do not yet support and don't want to spam warnings with"""
    if symbol in ("UNI-V2", "swUSD", "crCRV"):
        return True

    if address in ("0xCb2286d9471cc185281c4f763d34A962ED212962",):  # Sushi LP token
        return True

    return False


# Traceback (FileNotFoundError)
2020-11-23T14:53:52.590Z: Traceback (most recent call last):
File "src/gevent/greenlet.py", line 818, in gevent._greenlet.Greenlet.run
File "rotkehlchen/api/rest.py", line 235, in _do_query_async
result = getattr(self, command)(**kwargs)
File "rotkehlchen/api/rest.py", line 1576, in _eth_module_query
result = getattr(module_obj, method)(**kwargs)
File "rotkehlchen/chain/ethereum/uniswap/uniswap.py", line 944, in get_balances
protocol_balance = self.get_balances_chain(addresses)
File "rotkehlchen/chain/ethereum/uniswap/uniswap.py", line 309, in get_balances_chain
lp_addresses = get_latest_lp_addresses(self.data_directory)
File "rotkehlchen/chain/ethereum/uniswap/utils.py", line 152, in get_latest_lp_addresses
with open(local_meta_file, 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/lefteris/_MEI4E2fsg/rotkehlchen/data/uniswapv2_lp_tokens.meta'
2020-11-23T14:49:58Z <Greenlet at 0x7fef149a8a70: <bound method RestAPI._do_query_async of <rotkehlchen.api.rest.RestAPI object at 0x7fef1cd87090>>('_eth_module_query', 9, module='uniswap', method='get_balances', query_specific_balances_before=None, addresses=['0x8F1aa25822F4DE42089970c55E6Ab1111e134012', '0x)> failed with FileNotFoundError

# Fixed code
def _is_token_non_standard(symbol: str, address: ChecksumEthAddress) -> bool:
    """ignore some assets we do not query directly as token balances"""
    if symbol in ("UNI-V2",):
        return True

    if address in ("0xCb2286d9471cc185281c4f763d34A962ED212962",):  # Sushi LP token
        return True

    return False
# Buggy code
def meshgrid(self):
    """Return the a meshgrid of numpy arrays for this mesh.

    This simply returns a ``numpy.meshgrid`` of the coordinates for this
    mesh in ``ij`` indexing.

    """
    return np.meshgrid(self.x, self.y, self.z, indexing="ij")


# Traceback (TypeError)
Traceback (most recent call last):
...
...
File "/Users/Daniel/opt/anaconda3/lib/python3.7/site-packages/pyvista/core/grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)

TypeError: SetSpacing argument 1: only size-1 arrays can be converted to Python scalars

# Fixed code
def meshgrid(self):
    """Return a meshgrid of numpy arrays for this mesh.

    This simply returns a ``numpy.meshgrid`` of the coordinates for this
    mesh in ``ij`` indexing. These are a copy of the points of this mesh.

    """
    return np.meshgrid(self.x, self.y, self.z, indexing="ij")
# Buggy code
def points(self, points):
    """Set points without copying."""
    if not isinstance(points, np.ndarray):
        raise TypeError("Points must be a numpy array")
    # get the unique coordinates along each axial direction
    x = np.unique(points[:, 0])
    y = np.unique(points[:, 1])
    z = np.unique(points[:, 2])
    # Set the vtk coordinates
    self._from_arrays(x, y, z)
    # self._point_ref = points
    self.Modified()


# Traceback (TypeError)
Traceback (most recent call last):
...
...
File "/Users/Daniel/opt/anaconda3/lib/python3.7/site-packages/pyvista/core/grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)

TypeError: SetSpacing argument 1: only size-1 arrays can be converted to Python scalars

# Fixed code
def points(self, points):
    """Points must be set along each axial direction.

    Please set the point coordinates with the ``x``, ``y``, and ``z``
    setters.

    This setter overrides the base class's setter to ensure a user does not
    attempt to set them.

    """
    raise AttributeError(
        "The points cannot be set. The points of "
        "`RectilinearGrid` are defined in each axial direction. Please "
        "use the `x`, `y`, and `z` setters individually."
    )
# Buggy code
def points(self, points):
    """Set points without copying."""
    if not isinstance(points, np.ndarray):
        raise TypeError("Points must be a numpy array")
    # get the unique coordinates along each axial direction
    x = np.unique(points[:, 0])
    y = np.unique(points[:, 1])
    z = np.unique(points[:, 2])
    nx, ny, nz = len(x), len(y), len(z)
    # diff returns an empty array if the input is constant
    dx, dy, dz = [np.diff(d) if len(np.diff(d)) > 0 else d for d in (x, y, z)]
    # TODO: this needs to be tested (unique might return a tuple)
    dx, dy, dz = np.unique(dx), np.unique(dy), np.unique(dz)
    ox, oy, oz = np.min(x), np.min(y), np.min(z)
    # Build the vtk object
    self._from_specs((nx, ny, nz), (dx, dy, dz), (ox, oy, oz))
    # self._point_ref = points
    self.Modified()


# Traceback (TypeError)
Traceback (most recent call last):
...
...
File "/Users/Daniel/opt/anaconda3/lib/python3.7/site-packages/pyvista/core/grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)

TypeError: SetSpacing argument 1: only size-1 arrays can be converted to Python scalars

# Fixed code
def points(self, points):
    """Points cannot be set.

    This setter overrides the base class's setter to ensure a user does not
    attempt to set them. See https://github.com/pyvista/pyvista/issues/713.

    """
    raise AttributeError(
        "The points cannot be set. The points of "
        "`UniformGrid`/`vtkImageData` are implicitly defined by the "
        "`origin`, `spacing`, and `dimensions` of the grid."
    )
# Buggy code
def points(self, points):
    """Set points without copying."""
    if not isinstance(points, np.ndarray):
        raise TypeError("Points must be a numpy array")
    # get the unique coordinates along each axial direction
    x = np.unique(points[:, 0])
    y = np.unique(points[:, 1])
    z = np.unique(points[:, 2])
    nx, ny, nz = len(x), len(y), len(z)
    # TODO: this needs to be tested (unique might return a tuple)
    dx, dy, dz = np.unique(np.diff(x)), np.unique(np.diff(y)), np.unique(np.diff(z))
    ox, oy, oz = np.min(x), np.min(y), np.min(z)
    # Build the vtk object
    self._from_specs((nx, ny, nz), (dx, dy, dz), (ox, oy, oz))
    # self._point_ref = points
    self.Modified()


# Traceback (TypeError)
Traceback (most recent call last):

File "C:\Users\camramez\Documents\Meshing\gen_terrain.py", line 28, in <module>
grid.points=np.array([x_surf,y_surf,z_surf]).transpose()

File "C:\ProgramData\Anaconda3\envs\mesh\lib\site-packages\pyvista\core\grid.py", line 470, in points
self._from_specs((nx,ny,nz), (dx,dy,dz), (ox,oy,oz))

File "C:\ProgramData\Anaconda3\envs\mesh\lib\site-packages\pyvista\core\grid.py", line 435, in _from_specs
self.SetSpacing(xs, ys, zs)

TypeError: SetSpacing argument %Id: %V

# Fixed code
def points(self, points):
    """Set points without copying."""
    if not isinstance(points, np.ndarray):
        raise TypeError("Points must be a numpy array")
    # get the unique coordinates along each axial direction
    x = np.unique(points[:, 0])
    y = np.unique(points[:, 1])
    z = np.unique(points[:, 2])
    nx, ny, nz = len(x), len(y), len(z)
    # diff returns an empty array if the input is constant
    dx, dy, dz = [np.diff(d) if len(np.diff(d)) > 0 else d for d in (x, y, z)]
    # TODO: this needs to be tested (unique might return a tuple)
    dx, dy, dz = np.unique(dx), np.unique(dy), np.unique(dz)
    ox, oy, oz = np.min(x), np.min(y), np.min(z)
    # Build the vtk object
    self._from_specs((nx, ny, nz), (dx, dy, dz), (ox, oy, oz))
    # self._point_ref = points
    self.Modified()
# Buggy code
def field_arrays(self):
    """Returns all field arrays"""
    fdata = self.GetFieldData()
    narr = fdata.GetNumberOfArrays()

    # just return if unmodified
    if hasattr(self, "_field_arrays"):
        keys = list(self._field_arrays.keys())
        if narr == len(keys):
            return self._field_arrays

    # dictionary with callbacks
    self._field_arrays = FieldScalarsDict(self)

    for i in range(narr):
        name = fdata.GetArrayName(i)
        self._field_arrays[name] = self._field_scalar(name)

    self._field_arrays.enable_callback()
    return self._field_arrays


# Traceback (RecursionError)
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-15-403e4a0f4e87> in <module>
9
10 # Try to access the point arrays
---> 11 continents.point_arrays

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697         for i in range(narr):
698             name = pdata.GetArrayName(i)
--> 699             self._point_arrays[name] = self._point_scalar(name)
700
701         self._point_arrays.enable_callback()

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in _point_scalar(self, name)
342         if name is None:
343             # use active scalar array
--> 344             field, name = self.active_scalar_info
345             if field != POINT_DATA_FIELD:
346                 raise RuntimeError('Must specify an array to fetch.')

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in active_scalar_info(self)
53
54         # rare error where scalar name isn't a valid scalar
---> 55         if name not in self.point_arrays:
56             if name not in self.cell_arrays:
57                 if name in self.field_arrays:

... last 3 frames repeated, from the frame below ...

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697         for i in range(narr):
698             name = pdata.GetArrayName(i)
--> 699             self._point_arrays[name] = self._point_scalar(name)
700
701         self._point_arrays.enable_callback()

RecursionError: maximum recursion depth exceeded

# Fixed code
def field_arrays(self):
    """Returns all field arrays"""
    fdata = self.GetFieldData()
    narr = fdata.GetNumberOfArrays()

    # just return if unmodified
    if hasattr(self, "_field_arrays"):
        keys = list(self._field_arrays.keys())
        if narr == len(keys):
            return self._field_arrays

    # dictionary with callbacks
    self._field_arrays = FieldScalarsDict(self)

    for i in range(narr):
        name = fdata.GetArrayName(i)
        if name is None or len(name) < 1:
            name = "Field Array {}".format(i)
            fdata.GetArray(i).SetName(name)
        self._field_arrays[name] = self._field_scalar(name)

    self._field_arrays.enable_callback()
    return self._field_arrays
# Buggy code
def format_array(key, field):
    """internal helper to foramt array information for printing"""
    arr = get_scalar(self, key, preference=field)
    dl, dh = self.get_data_range(key)
    dl = pyvista.FLOAT_FORMAT.format(dl)
    dh = pyvista.FLOAT_FORMAT.format(dh)
    if key == self.active_scalar_info[1]:
        key = "<b>{}</b>".format(key)
    if arr.ndim > 1:
        ncomp = arr.shape[1]
    else:
        ncomp = 1
    return row.format(key, field, arr.dtype, ncomp, dl, dh)


# Traceback (RecursionError)
---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-15-403e4a0f4e87> in <module>
9
10 # Try to access the point arrays
---> 11 continents.point_arrays

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697         for i in range(narr):
698             name = pdata.GetArrayName(i)
--> 699             self._point_arrays[name] = self._point_scalar(name)
700
701         self._point_arrays.enable_callback()

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in _point_scalar(self, name)
342         if name is None:
343             # use active scalar array
--> 344             field, name = self.active_scalar_info
345             if field != POINT_DATA_FIELD:
346                 raise RuntimeError('Must specify an array to fetch.')

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in active_scalar_info(self)
53
54         # rare error where scalar name isn't a valid scalar
---> 55         if name not in self.point_arrays:
56             if name not in self.cell_arrays:
57                 if name in self.field_arrays:

... last 3 frames repeated, from the frame below ...

~/Documents/OpenGeoVis/Software/pyvista/pyvista/core/common.py in point_arrays(self)
697         for i in range(narr):
698             name = pdata.GetArrayName(i)
--> 699             self._point_arrays[name] = self._point_scalar(name)
700
701         self._point_arrays.enable_callback()

RecursionError: maximum recursion depth exceeded

# Fixed code
def format_array(name, arr, field):
    """internal helper to foramt array information for printing"""
    dl, dh = self.get_data_range(arr)
    dl = pyvista.FLOAT_FORMAT.format(dl)
    dh = pyvista.FLOAT_FORMAT.format(dh)
    if name == self.active_scalar_info[1]:
        name = "<b>{}</b>".format(name)
    if arr.ndim > 1:
        ncomp = arr.shape[1]
    else:
        ncomp = 1
    return row.format(name, field, arr.dtype, ncomp, dl, dh)
# Buggy code
def close(self):
    """closes render window"""
    # must close out axes marker
    if hasattr(self, "axes_widget"):
        del self.axes_widget

    # reset scalar bar stuff
    self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
    self._scalar_bar_slot_lookup = {}
    self._scalar_bar_ranges = {}
    self._scalar_bar_mappers = {}

    if hasattr(self, "ren_win"):
        self.ren_win.Finalize()
        del self.ren_win

    if hasattr(self, "_style"):
        del self._style

    if hasattr(self, "iren"):
        self.iren.RemoveAllObservers()
        del self.iren

    if hasattr(self, "textActor"):
        del self.textActor

    # end movie
    if hasattr(self, "mwriter"):
        try:
            self.mwriter.close()
        except BaseException:
            pass


# Traceback (ValueError)
Traceback (most recent call last):
File "cmap.py", line 54, in <module>
p.add_mesh(mesh, cmap="fire", lighting=True, stitle="Colorcet Fire")
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/plotting.py", line 752, in add_mesh
cmap = get_cmap_safe(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/pyvista/plotting/colors.py", line 391, in get_cmap_safe
cmap = get_cmap(cmap)
File "/home/musy/soft/anaconda3/lib/python3.6/site-packages/matplotlib/cm.py", line 182, in get_cmap
% (name, ', '.join(sorted(cmap_d))))
ValueError: Colormap fire is not recognized. Possible values are: Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r ...

# Fixed code
def close(self):
    """closes render window"""
    # must close out widgets first
    if hasattr(self, "axes_widget"):
        del self.axes_widget

    if hasattr(self, "scalar_widget"):
        del self.scalar_widget

    # reset scalar bar stuff
    self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
    self._scalar_bar_slot_lookup = {}
    self._scalar_bar_ranges = {}
    self._scalar_bar_mappers = {}
    self._scalar_bar_actors = {}
    self._scalar_bar_widgets = {}

    if hasattr(self, "ren_win"):
        self.ren_win.Finalize()
        del self.ren_win

    if hasattr(self, "_style"):
        del self._style

    if hasattr(self, "iren"):
        self.iren.RemoveAllObservers()
        del self.iren

    if hasattr(self, "textActor"):
        del self.textActor

    # end movie
    if hasattr(self, "mwriter"):
        try:
            self.mwriter.close()
        except BaseException:
            pass
# Buggy code
def __getitem__(self, index):
    """Get a block by its index or name (if the name is non-unique then
    returns the first occurence)"""
    if isinstance(index, str):
        index = self.get_index_by_name(index)
    data = self.GetBlock(index)
    if data is None:
        return data
    if data is not None and not is_vtki_obj(data):
        data = wrap(data)
    return data


# Traceback (ReferenceError)
---------------------------------------------------------------------------
ReferenceError                            Traceback (most recent call last)
<ipython-input-5-1ae88bf5bf88> in <module>()
1 # Add values to the meshes so colors are consistent with other data
2 # try:
----> 3 proj['temp_175c'].point_arrays['Temperature'] = np.full(proj['temp_175c'].n_points, 175.)
4 proj['temp_225c'].point_arrays['Temperature'] = np.full(proj['temp_225c'].n_points, 225.)
5 #     tc = vtki.MultiBlock()

~/Documents/OpenGeoVis/Software/vtki/vtki/common.py in __setitem__(self, key, val)
883         """ overridden to assure data is contigious """
884         if self.callback_enabled:
--> 885             self.adder(val, key, deep=False)
886         dict.__setitem__(self, key, val)
887         self.modifier()

~/Documents/OpenGeoVis/Software/vtki/vtki/common.py in adder(self, scalars, name, set_active, deep)
920
921     def adder(self, scalars, name, set_active=False, deep=True):
--> 922         self.data._add_point_scalar(scalars, name, set_active=False, deep=deep)
923
924

ReferenceError: weakly-referenced object no longer exists

# Fixed code
def __getitem__(self, index):
    """Get a block by its index or name (if the name is non-unique then
    returns the first occurence)"""
    if isinstance(index, str):
        index = self.get_index_by_name(index)
    data = self.GetBlock(index)
    if data is None:
        return data
    if data is not None and not is_vtki_obj(data):
        data = wrap(data)
    if data not in self.refs:
        self.refs.append(data)
    return data
# Buggy code
def left_button_down(self, obj, eventType):
    # Get 2D click location on window
    clickPos = self.iren.GetEventPosition()

    # Get corresponding click location in the 3D plot
    picker = vtk.vtkWorldPointPicker()
    picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
    self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))


# Traceback (ValueError)
Python 2.7.13 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:17:26) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://anaconda.org
import pyansys
C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\archive_reader.py:32: UserWarning: Unable to load vtk dependent modules
warnings.warn('Unable to load vtk dependent modules')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\__init__.py", line 4, in <module>
from pyansys.binary_reader import *
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\pyansys\binary_reader.py", line 7, in <module>
import vtkInterface
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\__init__.py", line 7, in <module>
from vtkInterface.polydata import PolyData
File "C:\Users\myusername\AppData\Local\Continuum\Anaconda3\envs\py27\lib\site-packages\vtkInterface\polydata.py", line 22, in <module>
class PolyData(vtkPolyData, vtkInterface.Common):
ValueError: multiple inheritance is not allowed with VTK classes

# Fixed code
def left_button_down(self, obj, eventType):
    # Get 2D click location on window
    clickPos = self.iren.GetEventPosition()

    # Get corresponding click location in the 3D plot
    picker = vtk.vtkWorldPointPicker()
    picker.Pick(clickPos[0], clickPos[1], 0, self.renderer)
    self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3))
    if np.any(np.isnan(self.pickpoint)):
        self.pickpoint[:] = 0
# Buggy code
def process_gcov_data(data_fname, covdata, source_fname, options):
    logger = Logger(options.verbose)

    INPUT = open(data_fname, "r")

    # Find the source file
    firstline = INPUT.readline()
    fname = guess_source_file_name(
        firstline,
        data_fname,
        source_fname,
        root_dir=options.root_dir,
        starting_dir=options.starting_dir,
        logger=logger,
    )

    logger.verbose_msg("Parsing coverage data for file {}", fname)

    # Return if the filename does not match the filter
    # Return if the filename matches the exclude pattern
    filtered, excluded = apply_filter_include_exclude(
        fname, options.filter, options.exclude, strip=options.root_filter
    )

    if filtered:
        logger.verbose_msg("  Filtering coverage data for file {}", fname)
        return

    if excluded:
        logger.verbose_msg("  Excluding coverage data for file {}", fname)
        return

    parser = GcovParser(fname, logger=logger)
    for line in INPUT:
        parser.parse_line(line, options.exclude_unreachable_branches)
    parser.update_coverage(covdata)
    parser.check_unclosed_exclusions()

    INPUT.close()


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/local/bin/gcovr", line 2412, in <module>
process_datafile(file_, covdata, options)
File "/usr/local/bin/gcovr", line 884, in process_datafile
process_gcov_data(fname, covdata, abs_filename, options)
File "/usr/local/bin/gcovr", line 616, in process_gcov_data
covered[lineno] = int(segments[0].strip())
ValueError: invalid literal for int() with base 10: '1*'

# Fixed code
def process_gcov_data(data_fname, covdata, source_fname, options):
    logger = Logger(options.verbose)

    INPUT = open(data_fname, "r")

    # Find the source file
    firstline = INPUT.readline()
    fname = guess_source_file_name(
        firstline,
        data_fname,
        source_fname,
        root_dir=options.root_dir,
        starting_dir=options.starting_dir,
        logger=logger,
    )

    logger.verbose_msg("Parsing coverage data for file {}", fname)

    # Return if the filename does not match the filter
    # Return if the filename matches the exclude pattern
    filtered, excluded = apply_filter_include_exclude(
        fname, options.filter, options.exclude, strip=options.root_filter
    )

    if filtered:
        logger.verbose_msg("  Filtering coverage data for file {}", fname)
        return

    if excluded:
        logger.verbose_msg("  Excluding coverage data for file {}", fname)
        return

    parser = GcovParser(fname, logger=logger)
    parser.parse_all_lines(INPUT, options.exclude_unreachable_branches)
    parser.update_coverage(covdata)
    parser.check_unrecognized_lines()
    parser.check_unclosed_exclusions()

    INPUT.close()
# Buggy code
def __init__(self, fname, logger):
    self.logger = logger
    self.excluding = []
    self.noncode = set()
    self.uncovered = set()
    self.uncovered_exceptional = set()
    self.covered = dict()
    self.branches = dict()
    # self.first_record = True
    self.fname = fname
    self.lineno = 0
    self.last_code_line = ""
    self.last_code_lineno = 0
    self.last_code_line_excluded = False


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/local/bin/gcovr", line 2412, in <module>
process_datafile(file_, covdata, options)
File "/usr/local/bin/gcovr", line 884, in process_datafile
process_gcov_data(fname, covdata, abs_filename, options)
File "/usr/local/bin/gcovr", line 616, in process_gcov_data
covered[lineno] = int(segments[0].strip())
ValueError: invalid literal for int() with base 10: '1*'

# Fixed code
def __init__(self, fname, logger):
    self.logger = logger
    self.excluding = []
    self.noncode = set()
    self.uncovered = set()
    self.uncovered_exceptional = set()
    self.covered = dict()
    self.branches = dict()
    # self.first_record = True
    self.fname = fname
    self.lineno = 0
    self.last_code_line = ""
    self.last_code_lineno = 0
    self.last_code_line_excluded = False
    self.unrecognized_lines = []
    self.deferred_exceptions = []
    self.last_was_specialization_section_marker = False
# Buggy code
def parse_code_line(self, status, code):
    firstchar = status[0]

    if firstchar == "-" or (self.excluding and firstchar in "#=0123456789"):
        # remember certain non-executed lines
        if self.excluding or is_non_code(code):
            self.noncode.add(self.lineno)
        return True

    if firstchar == "#":
        if is_non_code(code):
            self.noncode.add(self.lineno)
        else:
            self.uncovered.add(self.lineno)
        return True

    if firstchar == "=":
        self.uncovered_exceptional.add(self.lineno)
        return True

    if firstchar in "0123456789":
        self.covered[self.lineno] = int(status)
        return True

    return False


# Traceback (ValueError)
Traceback (most recent call last):
File "/usr/local/bin/gcovr", line 2412, in <module>
process_datafile(file_, covdata, options)
File "/usr/local/bin/gcovr", line 884, in process_datafile
process_gcov_data(fname, covdata, abs_filename, options)
File "/usr/local/bin/gcovr", line 616, in process_gcov_data
covered[lineno] = int(segments[0].strip())
ValueError: invalid literal for int() with base 10: '1*'

# Fixed code
def parse_code_line(self, status, code):
    firstchar = status[0]

    if firstchar == "-" or (self.excluding and firstchar in "#=0123456789"):
        # remember certain non-executed lines
        if self.excluding or is_non_code(code):
            self.noncode.add(self.lineno)
        return True

    if firstchar == "#":
        if is_non_code(code):
            self.noncode.add(self.lineno)
        else:
            self.uncovered.add(self.lineno)
        return True

    if firstchar == "=":
        self.uncovered_exceptional.add(self.lineno)
        return True

    if firstchar in "0123456789":
        # GCOV 8 marks partial coverage
        # with a trailing "*" after the execution count.
        self.covered[self.lineno] = int(status.rstrip("*"))
        return True

    return False
# Buggy code
def getFileInfo(self, name, pathname):
    try:
        audio = None
        size = os.stat(pathname).st_size

        if size > 0:
            try:
                audio = taglib.File(pathname)
            except IOError:
                pass

        if audio is not None and audio.length > 0:
            fileinfo = (name, size, int(audio.bitrate), int(audio.length))
        else:
            fileinfo = (name, size, None, None)

        return fileinfo

    except Exception as errtuple:
        message = _("Error while scanning file %(path)s: %(error)s") % {
            "path": pathname,
            "error": errtuple,
        }
        self.logMessage(message)
        displayTraceback(sys.exc_info()[2])


# Traceback (struct.error)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskproto.py", line 552, in run
conns, connsinprogress, server_socket = self.process_queue(queue, conns, connsinprogress, server_socket)
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskproto.py", line 1134, in process_queue
msg = msgObj.makeNetworkMessage()
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 1877, in makeNetworkMessage
self.packObject(1) +
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 277, in packObject
return struct.pack("<I", object.value)
struct.error: required argument is not an integer

# Fixed code
def getFileInfo(self, name, pathname):
    try:
        audio = None
        size = os.stat(pathname).st_size

        if size > 0:
            try:
                audio = taglib.File(pathname)
            except IOError:
                pass

        if audio is not None:
            bitrateinfo = (
                int(audio.bitrate),
                False,
            )  # Second argument used to be VBR (variable bitrate)
            fileinfo = (name, size, bitrateinfo, int(audio.length))
        else:
            fileinfo = (name, size, None, None)

        return fileinfo

    except Exception as errtuple:
        message = _("Error while scanning file %(path)s: %(error)s") % {
            "path": pathname,
            "error": errtuple,
        }
        self.logMessage(message)
        displayTraceback(sys.exc_info()[2])
# Buggy code
def makeNetworkMessage(self):
    msg = (
        self.packObject(1)
        + self.packObject(self.dir)
        + self.packObject(1)
        + self.packObject(self.dir)
        + self.packObject(len(self.list))
    )
    for i in self.list:
        msg = (
            msg
            + bytes([1])
            + self.packObject(i[0])
            + self.packObject(i[1])
            + self.packObject(0)
        )
        if i[2] is None:
            msg = msg + self.packObject("") + self.packObject(0)
        else:
            msg = msg + self.packObject("mp3") + self.packObject(2)
            msg = (
                msg
                + self.packObject(0)
                + self.packObject(i[2])
                + self.packObject(1)
                + self.packObject(i[3])
            )
    return zlib.compress(msg)


# Traceback (struct.error)
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskproto.py", line 552, in run
conns, connsinprogress, server_socket = self.process_queue(queue, conns, connsinprogress, server_socket)
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskproto.py", line 1134, in process_queue
msg = msgObj.makeNetworkMessage()
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 1877, in makeNetworkMessage
self.packObject(1) +
File "/usr/local/lib/python3.7/site-packages/pynicotine/slskmessages.py", line 277, in packObject
return struct.pack("<I", object.value)
struct.error: required argument is not an integer

# Fixed code
def makeNetworkMessage(self):
    msg = (
        self.packObject(1)
        + self.packObject(self.dir)
        + self.packObject(1)
        + self.packObject(self.dir)
        + self.packObject(len(self.list))
    )
    for i in self.list:
        msg = (
            msg
            + bytes([1])
            + self.packObject(i[0])
            + self.packObject(i[1])
            + self.packObject(0)
        )
        if i[2] is None:
            msg = msg + self.packObject("") + self.packObject(0)
        else:
            msg = msg + self.packObject("mp3") + self.packObject(3)
            msg = (
                msg
                + self.packObject(0)
                + self.packObject(i[2][0])
                + self.packObject(1)
                + self.packObject(i[3])
                + self.packObject(2)
                + self.packObject(i[2][1])
            )
    return zlib.compress(msg)
# Buggy code
def setBuddyShares(self, files, streams, wordindex, fileindex, mtimes):
    storable_objects = [
        (files, "bsharedfiles", "buddyfiles.db"),
        (streams, "bsharedfilesstreams", "buddystreams.db"),
        (mtimes, "bsharedmtimes", "buddymtimes.db"),
        (wordindex, "bwordindex", "buddywordindex.db"),
        (fileindex, "bfileindex", "buddyfileindex.db"),
    ]

    self.config_lock.acquire()
    _thread.start_new_thread(self._storeObjects, (storable_objects,))
    self.config_lock.release()


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def setBuddyShares(self, files, streams, wordindex, fileindex, mtimes):
    storable_objects = [
        (files, "bsharedfiles", "buddyfiles.db"),
        (streams, "bsharedfilesstreams", "buddystreams.db"),
        (mtimes, "bsharedmtimes", "buddymtimes.db"),
        (wordindex, "bwordindex", "buddywordindex.db"),
        (fileindex, "bfileindex", "buddyfileindex.db"),
    ]

    self.storeObjects(storable_objects)
# Buggy code
def setShares(self, files, streams, wordindex, fileindex, mtimes):
    storable_objects = [
        (files, "sharedfiles", "files.db"),
        (streams, "sharedfilesstreams", "streams.db"),
        (mtimes, "sharedmtimes", "mtimes.db"),
        (wordindex, "wordindex", "wordindex.db"),
        (fileindex, "fileindex", "fileindex.db"),
    ]

    self.config_lock.acquire()
    _thread.start_new_thread(self._storeObjects, (storable_objects,))
    self.config_lock.release()


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def setShares(self, files, streams, wordindex, fileindex, mtimes):
    storable_objects = [
        (files, "sharedfiles", "files.db"),
        (streams, "sharedfilesstreams", "streams.db"),
        (mtimes, "sharedmtimes", "mtimes.db"),
        (wordindex, "wordindex", "wordindex.db"),
        (fileindex, "fileindex", "fileindex.db"),
    ]

    self.storeObjects(storable_objects)
# Buggy code
def _BuddyRescanFinished(self, files, streams, wordindex, fileindex, mtimes):
    self.np.config.setBuddyShares(files, streams, wordindex, fileindex, mtimes)
    self.np.config.writeShares()

    if self.np.config.sections["transfers"]["enablebuddyshares"]:
        self.rescan_buddy.set_sensitive(True)
        self.browse_buddy_shares.set_sensitive(True)

    if self.np.transfers is not None:
        self.np.shares.sendNumSharedFoldersFiles()

    self.brescanning = 0
    self.logMessage(_("Rescanning Buddy Shares finished"))

    self.BuddySharesProgress.hide()
    self.np.shares.CompressShares("buddy")


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def _BuddyRescanFinished(self, files, streams, wordindex, fileindex, mtimes):
    self.np.config.setBuddyShares(files, streams, wordindex, fileindex, mtimes)

    if self.np.config.sections["transfers"]["enablebuddyshares"]:
        self.rescan_buddy.set_sensitive(True)
        self.browse_buddy_shares.set_sensitive(True)

    if self.np.transfers is not None:
        self.np.shares.sendNumSharedFoldersFiles()

    self.brescanning = 0
    self.logMessage(_("Rescanning Buddy Shares finished"))

    self.BuddySharesProgress.hide()

    self.np.shares.CompressShares("buddy")
# Buggy code
def _RescanFinished(self, files, streams, wordindex, fileindex, mtimes):
    self.np.config.setShares(files, streams, wordindex, fileindex, mtimes)
    self.np.config.writeShares()

    if self.np.config.sections["transfers"]["shared"]:
        self.rescan_public.set_sensitive(True)
        self.browse_public_shares.set_sensitive(True)

    if self.np.transfers is not None:
        self.np.shares.sendNumSharedFoldersFiles()

    self.rescanning = 0
    self.logMessage(_("Rescanning finished"))

    self.SharesProgress.hide()
    self.np.shares.CompressShares("normal")


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def _RescanFinished(self, files, streams, wordindex, fileindex, mtimes):
    self.np.config.setShares(files, streams, wordindex, fileindex, mtimes)

    if self.np.config.sections["transfers"]["shared"]:
        self.rescan_public.set_sensitive(True)
        self.browse_public_shares.set_sensitive(True)

    self.rescanning = 0
    self.logMessage(_("Rescanning finished"))

    self.SharesProgress.hide()

    self.np.shares.CompressShares("normal")

    if self.np.transfers is not None:
        self.np.shares.sendNumSharedFoldersFiles()
# Buggy code
def sendNumSharedFoldersFiles(self):
    """
    Send number of files in buddy shares if only buddies can
    download, and buddy-shares are enabled.
    """
    conf = self.config.sections

    if conf["transfers"]["enablebuddyshares"] and conf["transfers"]["friendsonly"]:
        shared_db = "bsharedfiles"
    else:
        shared_db = "sharedfiles"

    sharedfolders = len(conf["transfers"][shared_db])
    sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
    self.queue.put(slskmessages.SharedFoldersFiles(sharedfolders, sharedfiles))


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def sendNumSharedFoldersFiles(self):
    """
    Send number of files in buddy shares if only buddies can
    download, and buddy-shares are enabled.
    """

    conf = self.config.sections

    if conf["transfers"]["enablebuddyshares"] and conf["transfers"]["friendsonly"]:
        shared_db = "bsharedfiles"
        index_db = "bfileindex"
    else:
        shared_db = "sharedfiles"
        index_db = "fileindex"

    sharedfolders = len(conf["transfers"][shared_db])
    sharedfiles = len(conf["transfers"][index_db])

    self.queue.put(slskmessages.SharedFoldersFiles(sharedfolders, sharedfiles))
# Buggy code
def RebuildShares(self, msg):
    self.RescanShares(msg, rebuild=True)


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def RebuildShares(self, msg):
    self._RescanShares(msg, "normal", rebuild=True)
# Buggy code
def RescanShares(self, msg, rebuild=False):
    try:
        files, streams, wordindex, fileindex, mtimes = self.rescandirs(
            msg.shared,
            self.config.sections["transfers"]["sharedmtimes"],
            self.config.sections["transfers"]["sharedfiles"],
            self.config.sections["transfers"]["sharedfilesstreams"],
            msg.yieldfunction,
            self.np.frame.SharesProgress,
            name=_("Shares"),
            rebuild=rebuild,
        )

        time.sleep(0.5)

        self.np.frame.RescanFinished(
            files, streams, wordindex, fileindex, mtimes, "normal"
        )
    except Exception as ex:
        config_dir, data_dir = GetUserDirectories()
        log.addwarning(
            _(
                "Failed to rebuild share, serious error occurred. If this problem persists delete %s/*.db and try again. If that doesn't help please file a bug report with the stack trace included (see terminal output after this message). Technical details: %s"
            )
            % (data_dir, ex)
        )
        raise


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def RescanShares(self, msg, rebuild=False):
    self._RescanShares(msg, "normal", rebuild)
# Buggy code
def RebuildBuddyShares(self, msg):
    self.RescanBuddyShares(msg, rebuild=True)


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def RebuildBuddyShares(self, msg):
    self._RescanShares(msg, "buddy", rebuild=True)
# Buggy code
def RescanBuddyShares(self, msg, rebuild=False):
    files, streams, wordindex, fileindex, mtimes = self.rescandirs(
        msg.shared,
        self.config.sections["transfers"]["bsharedmtimes"],
        self.config.sections["transfers"]["bsharedfiles"],
        self.config.sections["transfers"]["bsharedfilesstreams"],
        msg.yieldfunction,
        self.np.frame.BuddySharesProgress,
        name=_("Buddy Shares"),
        rebuild=rebuild,
    )

    time.sleep(0.5)

    self.np.frame.RescanFinished(files, streams, wordindex, fileindex, mtimes, "buddy")


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/shelve.py", line 111, in __getitem__
value = self.cache[key]
KeyError: 'Klassiek\\Jean Sibelius\\Two Serenades for Violin and Orchestra, Op.69'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/pynicotine/gtkgui/frame.py", line 2039, in _RescanFinished
self.np.shares.sendNumSharedFoldersFiles()
File "/usr/local/lib/python3.7/site-packages/pynicotine/shares.py", line 105, in sendNumSharedFoldersFiles
sharedfiles = sum([len(x) for x in list(conf["transfers"][shared_db].values())])
File "/usr/local/lib/python3.7/_collections_abc.py", line 762, in __iter__
yield self._mapping[key]
File "/usr/local/lib/python3.7/shelve.py", line 113, in __getitem__
f = BytesIO(self.dict[key.encode(self.keyencoding)])
File "/usr/local/lib/python3.7/shelve.py", line 70, in closed
raise ValueError('invalid operation on closed shelf')
ValueError: invalid operation on closed shelf

# Fixed code
def RescanBuddyShares(self, msg, rebuild=False):
    self._RescanShares(msg, "buddy", rebuild)