gurudesh/pytracebugs huggingface dataset:
# Buggy code
def _initialize_index(self, data_file, regions):
    DLE = data_file.ds.domain_left_edge
    DRE = data_file.ds.domain_right_edge
    self._float_type = data_file.ds._validate_header(data_file.filename)[1]
    if self.index_ptype == "all":
        count = sum(data_file.total_particles.values())
        return self._get_morton_from_position(data_file, count, 0, regions, DLE, DRE)
    else:
        idpos = self._ptypes.index(self.index_ptype)
        count = data_file.total_particles.get(self.index_ptype)
        account = [0] + [data_file.total_particles.get(ptype) for ptype in self._ptypes]
        account = np.cumsum(account)
        return self._get_morton_from_position(
            data_file, account, account[idpos], regions, DLE, DRE
        )


# Traceback (TypeError)
Traceback (most recent call last):
File "./plot_solution.py", line 519, in <module>
pf.add_field(("gas", "density_squared"), function=_density_squared, units="g**2/cm**6")
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 1191, in add_field
self.index
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 504, in index
self, dataset_type=self.dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 39, in __init__
super(ParticleIndex, self).__init__(ds, dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/geometry_handler.py", line 50, in __init__
self._setup_geometry()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 50, in _setup_geometry
self._initialize_particle_handler()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 104, in _initialize_particle_handler
self._initialize_indices()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 134, in _initialize_indices
self.io._initialize_index(data_file, self.regions)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 351, in _initialize_index
data_file, count, 0, regions, DLE, DRE)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 334, in _get_morton_from_position
pp = np.fromfile(f, dtype=self._endian + self._float_type,
TypeError: cannot concatenate 'str' and 'int' objects

# Fixed code
def _initialize_index(self, data_file, regions):
    DLE = data_file.ds.domain_left_edge
    DRE = data_file.ds.domain_right_edge
    self._float_type = data_file.ds._validate_header(
        data_file.filename, data_file.ds._header_size
    )[1]
    if self.index_ptype == "all":
        count = sum(data_file.total_particles.values())
        return self._get_morton_from_position(data_file, count, 0, regions, DLE, DRE)
    else:
        idpos = self._ptypes.index(self.index_ptype)
        count = data_file.total_particles.get(self.index_ptype)
        account = [0] + [data_file.total_particles.get(ptype) for ptype in self._ptypes]
        account = np.cumsum(account)
        return self._get_morton_from_position(
            data_file, account, account[idpos], regions, DLE, DRE
        )
# Buggy code
def __init__(self, ds, io, filename, file_id):
    gformat = _get_gadget_format(filename, ds._header_size)
    with open(filename, "rb") as f:
        if gformat[0] == 2:
            f.seek(f.tell() + SNAP_FORMAT_2_OFFSET)
        self.header = read_record(f, ds._header_spec, endian=gformat[1])
        if gformat[0] == 2:
            f.seek(f.tell() + SNAP_FORMAT_2_OFFSET)
        self._position_offset = f.tell()
        f.seek(0, os.SEEK_END)
        self._file_size = f.tell()

    super(GadgetBinaryFile, self).__init__(ds, io, filename, file_id)


# Traceback (TypeError)
Traceback (most recent call last):
File "./plot_solution.py", line 519, in <module>
pf.add_field(("gas", "density_squared"), function=_density_squared, units="g**2/cm**6")
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 1191, in add_field
self.index
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 504, in index
self, dataset_type=self.dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 39, in __init__
super(ParticleIndex, self).__init__(ds, dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/geometry_handler.py", line 50, in __init__
self._setup_geometry()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 50, in _setup_geometry
self._initialize_particle_handler()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 104, in _initialize_particle_handler
self._initialize_indices()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 134, in _initialize_indices
self.io._initialize_index(data_file, self.regions)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 351, in _initialize_index
data_file, count, 0, regions, DLE, DRE)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 334, in _get_morton_from_position
pp = np.fromfile(f, dtype=self._endian + self._float_type,
TypeError: cannot concatenate 'str' and 'int' objects

# Fixed code
def __init__(self, ds, io, filename, file_id):
    header = ds._header
    self.header = header.value
    self._position_offset = header.position_offset
    with header.open() as f:
        self._file_size = f.seek(0, os.SEEK_END)

    super(GadgetBinaryFile, self).__init__(ds, io, filename, file_id)
# Buggy code
def _setup_binary_spec(cls, spec, spec_dict):
    if isinstance(spec, str):
        _hs = ()
        for hs in spec.split("+"):
            _hs += spec_dict[hs]
        spec = _hs
    return spec


# Traceback (TypeError)
Traceback (most recent call last):
File "./plot_solution.py", line 519, in <module>
pf.add_field(("gas", "density_squared"), function=_density_squared, units="g**2/cm**6")
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 1191, in add_field
self.index
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 504, in index
self, dataset_type=self.dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 39, in __init__
super(ParticleIndex, self).__init__(ds, dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/geometry_handler.py", line 50, in __init__
self._setup_geometry()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 50, in _setup_geometry
self._initialize_particle_handler()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 104, in _initialize_particle_handler
self._initialize_indices()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 134, in _initialize_indices
self.io._initialize_index(data_file, self.regions)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 351, in _initialize_index
data_file, count, 0, regions, DLE, DRE)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 334, in _get_morton_from_position
pp = np.fromfile(f, dtype=self._endian + self._float_type,
TypeError: cannot concatenate 'str' and 'int' objects

# Fixed code
def _setup_binary_spec(cls, spec, spec_dict):
    if isinstance(spec, string_types):
        _hs = ()
        for hs in spec.split("+"):
            _hs += spec_dict[hs]
        spec = _hs
    return spec
# Buggy code
def _get_hvals(self):
    # The entries in this header are capitalized and named to match Table 4
    # in the GADGET-2 user guide.
    gformat = _get_gadget_format(self.parameter_filename, self._header_size)
    f = open(self.parameter_filename, "rb")
    if gformat[0] == 2:
        f.seek(f.tell() + SNAP_FORMAT_2_OFFSET)
    hvals = read_record(f, self._header_spec, endian=gformat[1])
    for i in hvals:
        if len(hvals[i]) == 1:
            hvals[i] = hvals[i][0]
    return hvals


# Traceback (TypeError)
Traceback (most recent call last):
File "./plot_solution.py", line 519, in <module>
pf.add_field(("gas", "density_squared"), function=_density_squared, units="g**2/cm**6")
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 1191, in add_field
self.index
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 504, in index
self, dataset_type=self.dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 39, in __init__
super(ParticleIndex, self).__init__(ds, dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/geometry_handler.py", line 50, in __init__
self._setup_geometry()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 50, in _setup_geometry
self._initialize_particle_handler()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 104, in _initialize_particle_handler
self._initialize_indices()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 134, in _initialize_indices
self.io._initialize_index(data_file, self.regions)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 351, in _initialize_index
data_file, count, 0, regions, DLE, DRE)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 334, in _get_morton_from_position
pp = np.fromfile(f, dtype=self._endian + self._float_type,
TypeError: cannot concatenate 'str' and 'int' objects

# Fixed code
def _get_hvals(self):
    return self._header.value
# Buggy code
def _is_valid(cls, *args, **kwargs):
    if "header_spec" in kwargs:
        # Compute header size if header is customized
        header_spec = cls._setup_binary_spec(kwargs["header_spec"], gadget_header_specs)
        header_size = _compute_header_size(header_spec)
    else:
        header_size = 256
    # First 4 bytes used to check load
    return GadgetDataset._validate_header(args[0], header_size)[0]


# Traceback (TypeError)
Traceback (most recent call last):
File "./plot_solution.py", line 519, in <module>
pf.add_field(("gas", "density_squared"), function=_density_squared, units="g**2/cm**6")
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 1191, in add_field
self.index
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 504, in index
self, dataset_type=self.dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 39, in __init__
super(ParticleIndex, self).__init__(ds, dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/geometry_handler.py", line 50, in __init__
self._setup_geometry()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 50, in _setup_geometry
self._initialize_particle_handler()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 104, in _initialize_particle_handler
self._initialize_indices()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 134, in _initialize_indices
self.io._initialize_index(data_file, self.regions)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 351, in _initialize_index
data_file, count, 0, regions, DLE, DRE)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 334, in _get_morton_from_position
pp = np.fromfile(f, dtype=self._endian + self._float_type,
TypeError: cannot concatenate 'str' and 'int' objects

# Fixed code
def _is_valid(cls, *args, **kwargs):
    if "header_spec" in kwargs:
        header_spec = kwargs["header_spec"]
    else:
        header_spec = "default"
    header = GadgetBinaryHeader(args[0], header_spec)
    return header.validate()
# Buggy code
def __init__(self, ds, *args, **kwargs):
    self._vector_fields = dict(self._vector_fields)
    self._fields = ds._field_spec
    self._ptypes = ds._ptype_spec
    self.data_files = set([])
    gformat = _get_gadget_format(ds.parameter_filename, ds._header_size)
    # gadget format 1 original, 2 with block name
    self._format = gformat[0]
    self._endian = gformat[1]
    super(IOHandlerGadgetBinary, self).__init__(ds, *args, **kwargs)


# Traceback (TypeError)
Traceback (most recent call last):
File "./plot_solution.py", line 519, in <module>
pf.add_field(("gas", "density_squared"), function=_density_squared, units="g**2/cm**6")
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 1191, in add_field
self.index
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 504, in index
self, dataset_type=self.dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 39, in __init__
super(ParticleIndex, self).__init__(ds, dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/geometry_handler.py", line 50, in __init__
self._setup_geometry()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 50, in _setup_geometry
self._initialize_particle_handler()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 104, in _initialize_particle_handler
self._initialize_indices()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 134, in _initialize_indices
self.io._initialize_index(data_file, self.regions)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 351, in _initialize_index
data_file, count, 0, regions, DLE, DRE)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 334, in _get_morton_from_position
pp = np.fromfile(f, dtype=self._endian + self._float_type,
TypeError: cannot concatenate 'str' and 'int' objects

# Fixed code
def __init__(self, ds, *args, **kwargs):
    self._vector_fields = dict(self._vector_fields)
    self._fields = ds._field_spec
    self._ptypes = ds._ptype_spec
    self.data_files = set([])
    gformat, endianswap = ds._header.gadget_format
    # gadget format 1 original, 2 with block name
    self._format = gformat
    self._endian = endianswap
    super(IOHandlerGadgetBinary, self).__init__(ds, *args, **kwargs)
# Buggy code
def _initialize_index(self, data_file, regions):
    DLE = data_file.ds.domain_left_edge
    DRE = data_file.ds.domain_right_edge
    self._float_type = data_file.ds._validate_header(
        data_file.filename, data_file.ds._header_size
    )[1]
    if self.index_ptype == "all":
        count = sum(data_file.total_particles.values())
        return self._get_morton_from_position(data_file, count, 0, regions, DLE, DRE)
    else:
        idpos = self._ptypes.index(self.index_ptype)
        count = data_file.total_particles.get(self.index_ptype)
        account = [0] + [data_file.total_particles.get(ptype) for ptype in self._ptypes]
        account = np.cumsum(account)
        return self._get_morton_from_position(
            data_file, account, account[idpos], regions, DLE, DRE
        )


# Traceback (TypeError)
Traceback (most recent call last):
File "./plot_solution.py", line 519, in <module>
pf.add_field(("gas", "density_squared"), function=_density_squared, units="g**2/cm**6")
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 1191, in add_field
self.index
File "/usr/local/lib/python2.7/dist-packages/yt/data_objects/static_output.py", line 504, in index
self, dataset_type=self.dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 39, in __init__
super(ParticleIndex, self).__init__(ds, dataset_type)
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/geometry_handler.py", line 50, in __init__
self._setup_geometry()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 50, in _setup_geometry
self._initialize_particle_handler()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 104, in _initialize_particle_handler
self._initialize_indices()
File "/usr/local/lib/python2.7/dist-packages/yt/geometry/particle_geometry_handler.py", line 134, in _initialize_indices
self.io._initialize_index(data_file, self.regions)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 351, in _initialize_index
data_file, count, 0, regions, DLE, DRE)
File "/usr/local/lib/python2.7/dist-packages/yt/frontends/gadget/io.py", line 334, in _get_morton_from_position
pp = np.fromfile(f, dtype=self._endian + self._float_type,
TypeError: cannot concatenate 'str' and 'int' objects

# Fixed code
def _initialize_index(self, data_file, regions):
    DLE = data_file.ds.domain_left_edge
    DRE = data_file.ds.domain_right_edge
    self._float_type = data_file.ds._header.float_type
    if self.index_ptype == "all":
        count = sum(data_file.total_particles.values())
        return self._get_morton_from_position(data_file, count, 0, regions, DLE, DRE)
    else:
        idpos = self._ptypes.index(self.index_ptype)
        count = data_file.total_particles.get(self.index_ptype)
        account = [0] + [data_file.total_particles.get(ptype) for ptype in self._ptypes]
        account = np.cumsum(account)
        return self._get_morton_from_position(
            data_file, account, account[idpos], regions, DLE, DRE
        )
# Buggy code
def _switch_ds(self, new_ds, data_source=None):
    old_object = self.data_source
    name = old_object._type_name
    kwargs = dict((n, getattr(old_object, n)) for n in old_object._con_args)
    kwargs["center"] = getattr(old_object, "center", None)
    if data_source is not None:
        if name != "proj":
            raise RuntimeError(
                "The data_source keyword argument is only defined for projections."
            )
        kwargs["data_source"] = data_source
    new_object = getattr(new_ds, name)(**kwargs)
    self.ds = new_ds
    self.data_source = new_object
    self._data_valid = self._plot_valid = False
    for d in "xyz":
        lim_name = d + "lim"
        if hasattr(self, lim_name):
            lim = getattr(self, lim_name)
            lim = tuple(new_ds.quan(l.value, str(l.units)) for l in lim)
            setattr(self, lim_name, lim)
    self.plots.data_source = new_object
    self._colorbar_label.data_source = new_object
    self._setup_plots()


# Traceback (AttributeError)
Traceback (most recent call last):
File "test.py", line 13, in <module>
plot._switch_ds(ds2)
File "/Users/goldbaum/Documents/yt-git-fixes/yt/visualization/plot_container.py", line 325, in _switch_ds
new_object = getattr(new_ds, name)(**kwargs)
AttributeError: 'TipsyDataset' object has no attribute 'Particle'

# Fixed code
def _switch_ds(self, new_ds, data_source=None):
    old_object = self.data_source
    name = old_object._type_name
    kwargs = dict((n, getattr(old_object, n)) for n in old_object._con_args)
    kwargs["center"] = getattr(old_object, "center", None)
    if data_source is not None:
        if name != "proj":
            raise RuntimeError(
                "The data_source keyword argument is only defined for projections."
            )
        kwargs["data_source"] = data_source

    self.ds = new_ds

    # A _hack_ for ParticleProjectionPlots
    if name == "Particle":
        from yt.visualization.particle_plots import ParticleAxisAlignedDummyDataSource

        new_object = ParticleAxisAlignedDummyDataSource(ds=self.ds, **kwargs)
    else:
        new_object = getattr(new_ds, name)(**kwargs)

    self.data_source = new_object
    self._data_valid = self._plot_valid = False

    for d in "xyz":
        lim_name = d + "lim"
        if hasattr(self, lim_name):
            lim = getattr(self, lim_name)
            lim = tuple(new_ds.quan(l.value, str(l.units)) for l in lim)
            setattr(self, lim_name, lim)
    self.plots.data_source = new_object
    self._colorbar_label.data_source = new_object
    self._setup_plots()
# Buggy code
def _fill_fields(self, fields):
    fields = [f for f in fields if f not in self.field_data]
    if len(fields) == 0:
        return
    assert len(fields) == 1
    field = fields[0]
    dest = np.zeros(self.ActiveDimensions, dtype="float64")
    for chunk in self._data_source.chunks(fields, "io"):
        fill_region_float(
            chunk.fcoords,
            chunk.fwidth,
            chunk[field],
            self.left_edge,
            self.right_edge,
            dest,
            1,
            self.ds.domain_width,
            int(any(self.ds.periodicity)),
        )
    fi = self.ds._get_field_info(field)
    self[field] = self.ds.arr(dest, fi.units)


# Traceback (AssertionError)
Traceback (most recent call last):
File "yt_arbgridtest.py", line 16, in <module>
tracerp = galgas['tracerf']
File "/Users/goldbaum/Documents/yt-git-fixes/yt/data_objects/data_containers.py", line 281, in __getitem__
self.get_data(f)
File "/Users/goldbaum/Documents/yt-git-fixes/yt/data_objects/construction_data_containers.py", line 641, in get_data
if len(fill) > 0: self._fill_fields(fill)
File "/Users/goldbaum/Documents/yt-git-fixes/yt/data_objects/construction_data_containers.py", line 851, in _fill_fields
assert(len(fields) == 1)
AssertionError

# Fixed code
def _fill_fields(self, fields):
    fields = [f for f in fields if f not in self.field_data]
    if len(fields) == 0:
        return
    # It may be faster to adapt fill_region_float to fill multiple fields
    # instead of looping here
    for field in fields:
        dest = np.zeros(self.ActiveDimensions, dtype="float64")
        for chunk in self._data_source.chunks(fields, "io"):
            fill_region_float(
                chunk.fcoords,
                chunk.fwidth,
                chunk[field],
                self.left_edge,
                self.right_edge,
                dest,
                1,
                self.ds.domain_width,
                int(any(self.ds.periodicity)),
            )
        fi = self.ds._get_field_info(field)
        self[field] = self.ds.arr(dest, fi.units)
# Buggy code
def _setup_filtered_type(self, filter):
    if not filter.available(self.derived_field_list):
        return False
    fi = self.field_info
    fd = self.field_dependencies
    available = False
    for fn in self.derived_field_list:
        if fn[0] == filter.filtered_type:
            # Now we can add this
            available = True
            self.derived_field_list.append((filter.name, fn[1]))
            fi[filter.name, fn[1]] = filter.wrap_func(fn, fi[fn])
            # Now we append the dependencies
            fd[filter.name, fn[1]] = fd[fn]
    if available:
        self.particle_types += (filter.name,)
        self.filtered_particle_types.append(filter.name)
        new_fields = self._setup_particle_types([filter.name])
        deps, _ = self.field_info.check_derived_fields(new_fields)
        self.field_dependencies.update(deps)
    return available


# Traceback (yt.utilities.exceptions.YTFieldNotFound)
Traceback (most recent call last):
File "test.py", line 22, in <module>
width=(2000, 'kpc'))
File "/Users/goldbaum/Documents/yt-hg/yt/visualization/particle_plots.py", line 399, in ParticlePlot
x_field = ad._determine_fields(x_field)[0]
File "/Users/goldbaum/Documents/yt-hg/yt/data_objects/data_containers.py", line 1088, in _determine_fields
finfo = self.ds._get_field_info(ftype, fname)
File "/Users/goldbaum/Documents/yt-hg/yt/data_objects/static_output.py", line 666, in _get_field_info
raise YTFieldNotFound((ftype, fname), self)
yt.utilities.exceptions.YTFieldNotFound: Could not find field '('small_x', 'particle_position_x')' in snapshot_200

# Fixed code
def _setup_filtered_type(self, filter):
    if not filter.available(self.derived_field_list):
        raise YTIllDefinedParticleFilter(
            filter, filter.missing(self.derived_field_list)
        )
    fi = self.field_info
    fd = self.field_dependencies
    available = False
    for fn in self.derived_field_list:
        if fn[0] == filter.filtered_type:
            # Now we can add this
            available = True
            self.derived_field_list.append((filter.name, fn[1]))
            fi[filter.name, fn[1]] = filter.wrap_func(fn, fi[fn])
            # Now we append the dependencies
            fd[filter.name, fn[1]] = fd[fn]
    if available:
        self.particle_types += (filter.name,)
        self.filtered_particle_types.append(filter.name)
        new_fields = self._setup_particle_types([filter.name])
        deps, _ = self.field_info.check_derived_fields(new_fields)
        self.field_dependencies.update(deps)
    return available
# Buggy code
def _oblique_pixelize(self, data_source, field, bounds, size, antialias):
    indices = np.argsort(data_source["pdx"])[::-1]
    buff = np.zeros((size[1], size[0]), dtype="f8")
    pixelize_off_axis_cartesian(
        buff,
        data_source["x"],
        data_source["y"],
        data_source["z"],
        data_source["px"],
        data_source["py"],
        data_source["pdx"],
        data_source["pdy"],
        data_source["pdz"],
        data_source.center,
        data_source._inv_mat,
        indices,
        data_source[field],
        bounds,
    )
    return buff


# Traceback (ValueError)
Traceback (most recent call last):
File "C:\Miniconda-x64\envs\test\lib\site-packages\nose\loader.py", line 251, in generate
for test in g():
File "c:\projects\yt\yt\utilities\lib\tests\test_alt_ray_tracers.py", line 65, in test_cylindrical_ray_trace
t, s, rztheta, inds = cylindrical_ray_trace(p1, p2, left_grid, right_grid)
File "yt\utilities\lib\alt_ray_tracers.pyx", line 203, in yt.utilities.lib.alt_ray_tracers.cylindrical_ray_trace (yt/utilities/lib/alt_ray_tracers.c:6000)
tsect, tinds = np.unique(tsect[tmask], return_index=True)
ValueError: Item size of buffer (1 byte) does not match size of 'int64_t' (8 bytes)

# Fixed code
def _oblique_pixelize(self, data_source, field, bounds, size, antialias):
    indices = np.argsort(data_source["pdx"])[::-1].astype(np.int_)
    buff = np.zeros((size[1], size[0]), dtype="f8")
    pixelize_off_axis_cartesian(
        buff,
        data_source["x"],
        data_source["y"],
        data_source["z"],
        data_source["px"],
        data_source["py"],
        data_source["pdx"],
        data_source["pdy"],
        data_source["pdz"],
        data_source.center,
        data_source._inv_mat,
        indices,
        data_source[field],
        bounds,
    )
    return buff
# Buggy code
def _localize_check(self, fn):
    # If the file exists, use it.  If not, set it to None.
    root_dir = os.path.dirname(self.output_dir)
    full_fn = os.path.join(root_dir, fn)
    if os.path.exists(full_fn):
        return full_fn
    return None


# Traceback (TypeError)
Traceback (most recent call last):
File "get_plot.py", line 20, in <module>
ds=yt.load(file_name)
File "xxx/python2.7/site-packages/yt/convenience.py", line 86, in load
return candidates[0](*args, **kwargs)
File "xxx/python2.7/site-packages/yt/frontends/boxlib/data_structures.py", line 392, in __init__
self.cparam_filename = self._localize_check(cparam_filename)
File "xxx/python2.7/site-packages/yt/frontends/boxlib/data_structures.py", line 415, in _localize_check
if os.path.exists(full_fn):
File "xxx/python2.7/genericpath.py", line 26, in exists
os.stat(path)
TypeError: coercing to Unicode: need string or buffer, NoneType found

# Fixed code
def _localize_check(self, fn):
    if fn is None:
        return None
    # If the file exists, use it.  If not, set it to None.
    root_dir = os.path.dirname(self.output_dir)
    full_fn = os.path.join(root_dir, fn)
    if os.path.exists(full_fn):
        return full_fn
    return None
# Buggy code
def run_callback_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    queue = Queue()
    devices = read_device_map("device-mapping")
    block = CallbackDataBlock(devices, queue)
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    context = ModbusServerContext(slaves=store, single=True)

    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #
    identity = ModbusDeviceIdentification()
    identity.VendorName = "pymodbus"
    identity.ProductCode = "PM"
    identity.VendorUrl = "http://github.com/bashwork/pymodbus/"
    identity.ProductName = "pymodbus Server"
    identity.ModelName = "pymodbus Server"
    identity.MajorMinorRevision = "1.0"

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    p = Process(target=device_writer, args=(queue,))
    p.start()
    StartTcpServer(context, identity=identity, address=("localhost", 5020))


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def run_callback_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    queue = Queue()
    devices = read_device_map("device-mapping")
    block = CallbackDataBlock(devices, queue)
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    context = ModbusServerContext(slaves=store, single=True)

    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #
    identity = ModbusDeviceIdentification()
    identity.VendorName = "pymodbus"
    identity.ProductCode = "PM"
    identity.VendorUrl = "http://github.com/bashwork/pymodbus/"
    identity.ProductName = "pymodbus Server"
    identity.ModelName = "pymodbus Server"
    identity.MajorMinorRevision = "2.2.0"

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    p = Process(target=device_writer, args=(queue,))
    p.start()
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
# Buggy code
def run_custom_db_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    block = CustomDataBlock([0] * 100)
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    context = ModbusServerContext(slaves=store, single=True)

    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #

    identity = ModbusDeviceIdentification()
    identity.VendorName = "pymodbus"
    identity.ProductCode = "PM"
    identity.VendorUrl = "http://github.com/bashwork/pymodbus/"
    identity.ProductName = "pymodbus Server"
    identity.ModelName = "pymodbus Server"
    identity.MajorMinorRevision = "1.0"

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #

    # p = Process(target=device_writer, args=(queue,))
    # p.start()
    StartTcpServer(context, identity=identity, address=("localhost", 5020))


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def run_custom_db_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #
    block = CustomDataBlock([0] * 100)
    store = ModbusSlaveContext(di=block, co=block, hr=block, ir=block)
    context = ModbusServerContext(slaves=store, single=True)

    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #

    identity = ModbusDeviceIdentification()
    identity.VendorName = "pymodbus"
    identity.ProductCode = "PM"
    identity.VendorUrl = "http://github.com/bashwork/pymodbus/"
    identity.ProductName = "pymodbus Server"
    identity.ModelName = "pymodbus Server"
    identity.MajorMinorRevision = "2.2.0"

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #

    # p = Process(target=device_writer, args=(queue,))
    # p.start()
    StartTcpServer(context, identity=identity, address=("localhost", 5020))
# Buggy code
def __init__(self, address):
    ModbusRequest.__init__(self)
    self.address = address
    self.count = 16


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, address=None, **kwargs):
    ModbusRequest.__init__(self, **kwargs)
    self.address = address
    self.count = 16
# Buggy code
def __init__(self, address):
    """Initializes a new instance

    :param address: The address to start reading from
    """
    ReadCoilsRequest.__init__(self, address, 16)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, address, **kwargs):
    """Initializes a new instance

    :param address: The address to start reading from
    """
    ReadCoilsRequest.__init__(self, address, 16, **kwargs)
# Buggy code
def updating_writer(a):
    """A worker process that runs every so often and
    updates live values of the context which resides in an SQLite3 database.
    It should be noted that there is a race condition for the update.
    :param arguments: The input arguments to the call
    """
    log.debug("Updating the database context")
    context = a[0]
    readfunction = 0x03  # read holding registers
    writefunction = 0x10
    slave_id = 0x01  # slave address
    count = 50

    # import pdb; pdb.set_trace()

    rand_value = random.randint(0, 9999)
    rand_addr = random.randint(0, 65000)
    log.debug("Writing to datastore: {}, {}".format(rand_addr, rand_value))
    # import pdb; pdb.set_trace()
    context[slave_id].setValues(writefunction, rand_addr, [rand_value])
    values = context[slave_id].getValues(readfunction, rand_addr, count)
    log.debug("Values from datastore: " + str(values))


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def updating_writer(a):
    """A worker process that runs every so often and
    updates live values of the context which resides in an SQLite3 database.
    It should be noted that there is a race condition for the update.
    :param arguments: The input arguments to the call
    """
    log.debug("Updating the database context")
    context = a[0]
    readfunction = 0x03  # read holding registers
    writefunction = 0x10
    slave_id = 0x01  # slave address
    count = 50

    # import pdb; pdb.set_trace()

    rand_value = random.randint(0, 9999)
    rand_addr = random.randint(0, 65000)
    log.debug("Writing to datastore: {}, {}".format(rand_addr, rand_value))
    # import pdb; pdb.set_trace()
    context[slave_id].setValues(writefunction, rand_addr, [rand_value], update=False)
    values = context[slave_id].getValues(readfunction, rand_addr, count)
    log.debug("Values from datastore: " + str(values))
# Buggy code
def run_dbstore_update_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #

    block = ModbusSequentialDataBlock(0x00, [0] * 0xFF)
    store = SqlSlaveContext(block)

    context = ModbusServerContext(slaves={1: store}, single=False)

    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #
    identity = ModbusDeviceIdentification()
    identity.VendorName = "pymodbus"
    identity.ProductCode = "PM"
    identity.VendorUrl = "http://github.com/bashwork/pymodbus/"
    identity.ProductName = "pymodbus Server"
    identity.ModelName = "pymodbus Server"
    identity.MajorMinorRevision = "1.0"

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    time = 5  # 5 seconds delay
    loop = LoopingCall(f=updating_writer, a=(context,))
    loop.start(time, now=False)  # initially delay by time
    StartTcpServer(context, identity=identity, address=("", 5020))


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def run_dbstore_update_server():
    # ----------------------------------------------------------------------- #
    # initialize your data store
    # ----------------------------------------------------------------------- #

    block = ModbusSequentialDataBlock(0x00, [0] * 0xFF)
    store = SqlSlaveContext(block)

    context = ModbusServerContext(slaves={1: store}, single=False)

    # ----------------------------------------------------------------------- #
    # initialize the server information
    # ----------------------------------------------------------------------- #
    identity = ModbusDeviceIdentification()
    identity.VendorName = "pymodbus"
    identity.ProductCode = "PM"
    identity.VendorUrl = "http://github.com/bashwork/pymodbus/"
    identity.ProductName = "pymodbus Server"
    identity.ModelName = "pymodbus Server"
    identity.MajorMinorRevision = "2.2.0"

    # ----------------------------------------------------------------------- #
    # run the server you want
    # ----------------------------------------------------------------------- #
    time = 5  # 5 seconds delay
    loop = LoopingCall(f=updating_writer, a=(context,))
    loop.start(time, now=False)  # initially delay by time
    loop.stop()
    StartTcpServer(context, identity=identity, address=("", 5020))
# Buggy code
def execute(self, request=None):
    """
    Executes a transaction
    :param request: Request to be written on to the bus
    :return:
    """
    request.transaction_id = self.transaction.getNextTID()

    def callback(*args):
        LOGGER.debug("in callback - {}".format(request.transaction_id))
        while True:
            waiting = self.stream.connection.in_waiting
            if waiting:
                data = self.stream.connection.read(waiting)
                LOGGER.debug("recv: " + " ".join([hex(byte2int(x)) for x in data]))
                self.framer.processIncomingPacket(
                    data, self._handle_response, tid=request.transaction_id
                )
                break

    packet = self.framer.buildPacket(request)
    LOGGER.debug("send: " + " ".join([hex(byte2int(x)) for x in packet]))
    self.stream.write(packet, callback=callback)
    f = self._build_response(request.transaction_id)
    return f


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def execute(self, request=None):
    """
    Executes a transaction
    :param request: Request to be written on to the bus
    :return:
    """
    request.transaction_id = self.transaction.getNextTID()

    def callback(*args):
        LOGGER.debug("in callback - {}".format(request.transaction_id))
        while True:
            waiting = self.stream.connection.in_waiting
            if waiting:
                data = self.stream.connection.read(waiting)
                LOGGER.debug("recv: " + " ".join([hex(byte2int(x)) for x in data]))
                unit = self.framer.decode_data(data).get("uid", 0)
                self.framer.processIncomingPacket(
                    data, self._handle_response, unit, tid=request.transaction_id
                )
                break

    packet = self.framer.buildPacket(request)
    LOGGER.debug("send: " + " ".join([hex(byte2int(x)) for x in packet]))
    self.stream.write(packet, callback=callback)
    f = self._build_response(request.transaction_id)
    return f
# Buggy code
def callback(*args):
    LOGGER.debug("in callback - {}".format(request.transaction_id))
    while True:
        waiting = self.stream.connection.in_waiting
        if waiting:
            data = self.stream.connection.read(waiting)
            LOGGER.debug("recv: " + " ".join([hex(byte2int(x)) for x in data]))
            self.framer.processIncomingPacket(
                data, self._handle_response, tid=request.transaction_id
            )
            break


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def callback(*args):
    LOGGER.debug("in callback - {}".format(request.transaction_id))
    while True:
        waiting = self.stream.connection.in_waiting
        if waiting:
            data = self.stream.connection.read(waiting)
            LOGGER.debug("recv: " + " ".join([hex(byte2int(x)) for x in data]))
            unit = self.framer.decode_data(data).get("uid", 0)
            self.framer.processIncomingPacket(
                data, self._handle_response, unit, tid=request.transaction_id
            )
            break
# Buggy code
def __init__(self, framer, **kwargs):
    """Initialize a client instance

    :param framer: The modbus framer implementation to use
    """
    self.framer = framer
    if isinstance(self.framer, ModbusSocketFramer):
        self.transaction = DictTransactionManager(self, **kwargs)
    else:
        self.transaction = FifoTransactionManager(self, **kwargs)
    self._debug = False
    self._debugfd = None


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def __init__(self, framer, **kwargs):
    """Initialize a client instance

    :param framer: The modbus framer implementation to use
    """
    self.framer = framer
    self.transaction = DictTransactionManager(self, **kwargs)
    self._debug = False
    self._debugfd = None
    self.broadcast_enable = kwargs.get("broadcast_enable", Defaults.broadcast_enable)
# Buggy code
def connect(self):
    """Connect to the modbus serial server

    :returns: True if connection succeeded, False otherwise
    """
    if self.socket:
        return True
    try:
        self.socket = serial.Serial(
            port=self.port,
            timeout=self.timeout,
            bytesize=self.bytesize,
            stopbits=self.stopbits,
            baudrate=self.baudrate,
            parity=self.parity,
        )
    except serial.SerialException as msg:
        _logger.error(msg)
        self.close()
    if self.method == "rtu":
        if self._strict and self.socket:
            self.socket.interCharTimeout = self.inter_char_timeout
        self.last_frame_end = None
    return self.socket is not None


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def connect(self):
    """Connect to the modbus serial server

    :returns: True if connection succeeded, False otherwise
    """
    if self.socket:
        return True
    try:
        self.socket = serial.Serial(
            port=self.port,
            timeout=self.timeout,
            bytesize=self.bytesize,
            stopbits=self.stopbits,
            baudrate=self.baudrate,
            parity=self.parity,
        )
        if self.method == "rtu":
            if self._strict:
                self.socket.interCharTimeout = self.inter_char_timeout
            self.last_frame_end = None
    except serial.SerialException as msg:
        _logger.error(msg)
        self.close()
    return self.socket is not None
# Buggy code
def validate(self, fx, address, count=1):
    """Validates the request to make sure it is in range

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to test
    :returns: True if the request in within range, False otherwise
    """
    if not self.zero_mode:
        address = address + 1
    _logger.debug("validate[%d] %d:%d" % (fx, address, count))
    return self.store[self.decode(fx)].validate(address, count)


# Traceback (AttributeError)
client = ModbusSerialClient(port='notexist', method='rtu')
client.connect()
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "lib/python3.6/site-packages/pymodbus/client/sync.py", line 476, in connect
self.socket.interCharTimeout = self.inter_char_timeout
AttributeError: 'NoneType' object has no attribute 'interCharTimeout'

# Fixed code
def validate(self, fx, address, count=1):
    """Validates the request to make sure it is in range

    :param fx: The function we are working with
    :param address: The starting address
    :param count: The number of values to test
    :returns: True if the request in within range, False otherwise
    """
    if not self.zero_mode:
        address = address + 1
    _logger.debug("validate: fc-[%d] address-%d: count-%d" % (fx, address, count))
    return self.store[self.decode(fx)].validate(address, count)