gurudesh/pytracebugs huggingface dataset:
# Buggy code
def parse_json_links_details(out_dir: str) -> Iterator[Link]:
    """read through all the archive data folders and return the parsed links"""

    for entry in os.scandir(os.path.join(out_dir, ARCHIVE_DIR_NAME)):
        if entry.is_dir(follow_symlinks=True):
            if os.path.exists(os.path.join(entry.path, "index.json")):
                link = parse_json_link_details(entry.path)
                if link:
                    yield link


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/USERNAME/.local/bin/archivebox", line 8, in <module>
sys.exit(main())
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 126, in main
pwd=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 62, in run_subcommand
module.main(args=subcommand_args, stdin=stdin, pwd=pwd)    # type: ignore
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/archivebox_init.py", line 34, in main
out_dir=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/main.py", line 316, in init
for link in load_main_index(out_dir=out_dir, warn=False)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/__init__.py", line 250, in load_main_index
all_links = list(parse_json_main_index(out_dir))
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/json.py", line 52, in parse_json_main_index
yield Link.from_json(link_json)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 203, in from_json
cast_result = ArchiveResult.from_json(json_result)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 62, in from_json
info['start_ts'] = parse_date(info['start_ts'])
KeyError: 'start_ts'

# Fixed code
def parse_json_links_details(out_dir: str) -> Iterator[Link]:
    """read through all the archive data folders and return the parsed links"""

    for entry in os.scandir(os.path.join(out_dir, ARCHIVE_DIR_NAME)):
        if entry.is_dir(follow_symlinks=True):
            if os.path.exists(os.path.join(entry.path, "index.json")):
                try:
                    link = parse_json_link_details(entry.path)
                except KeyError:
                    link = None
                if link:
                    yield link
# Buggy code
def is_valid(link: Link) -> bool:
    dir_exists = os.path.exists(link.link_dir)
    index_exists = os.path.exists(os.path.join(link.link_dir, "index.json"))
    if not dir_exists:
        # unarchived links are not included in the valid list
        return False
    if dir_exists and not index_exists:
        return False
    if dir_exists and index_exists:
        try:
            parsed_link = parse_json_link_details(link.link_dir)
            return link.url == parsed_link.url
        except Exception:
            pass
    return False


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/USERNAME/.local/bin/archivebox", line 8, in <module>
sys.exit(main())
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 126, in main
pwd=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 62, in run_subcommand
module.main(args=subcommand_args, stdin=stdin, pwd=pwd)    # type: ignore
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/archivebox_init.py", line 34, in main
out_dir=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/main.py", line 316, in init
for link in load_main_index(out_dir=out_dir, warn=False)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/__init__.py", line 250, in load_main_index
all_links = list(parse_json_main_index(out_dir))
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/json.py", line 52, in parse_json_main_index
yield Link.from_json(link_json)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 203, in from_json
cast_result = ArchiveResult.from_json(json_result)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 62, in from_json
info['start_ts'] = parse_date(info['start_ts'])
KeyError: 'start_ts'

# Fixed code
def is_valid(link: Link) -> bool:
    dir_exists = os.path.exists(link.link_dir)
    index_exists = os.path.exists(os.path.join(link.link_dir, "index.json"))
    if not dir_exists:
        # unarchived links are not included in the valid list
        return False
    if dir_exists and not index_exists:
        return False
    if dir_exists and index_exists:
        try:
            parsed_link = parse_json_link_details(link.link_dir, guess=True)
            return link.url == parsed_link.url
        except Exception as e:
            pass
    return False
# Buggy code
def parse_json_link_details(out_dir: str) -> Optional[Link]:
    """load the json link index from a given directory"""
    existing_index = os.path.join(out_dir, JSON_INDEX_FILENAME)
    if os.path.exists(existing_index):
        with open(existing_index, "r", encoding="utf-8") as f:
            try:
                link_json = pyjson.load(f)
                return Link.from_json(link_json)
            except pyjson.JSONDecodeError:
                pass
    return None


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/USERNAME/.local/bin/archivebox", line 8, in <module>
sys.exit(main())
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 126, in main
pwd=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 62, in run_subcommand
module.main(args=subcommand_args, stdin=stdin, pwd=pwd)    # type: ignore
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/archivebox_init.py", line 34, in main
out_dir=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/main.py", line 316, in init
for link in load_main_index(out_dir=out_dir, warn=False)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/__init__.py", line 250, in load_main_index
all_links = list(parse_json_main_index(out_dir))
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/json.py", line 52, in parse_json_main_index
yield Link.from_json(link_json)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 203, in from_json
cast_result = ArchiveResult.from_json(json_result)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 62, in from_json
info['start_ts'] = parse_date(info['start_ts'])
KeyError: 'start_ts'

# Fixed code
def parse_json_link_details(
    out_dir: str, guess: Optional[bool] = False
) -> Optional[Link]:
    """load the json link index from a given directory"""
    existing_index = os.path.join(out_dir, JSON_INDEX_FILENAME)
    if os.path.exists(existing_index):
        with open(existing_index, "r", encoding="utf-8") as f:
            try:
                link_json = pyjson.load(f)
                return Link.from_json(link_json, guess)
            except pyjson.JSONDecodeError:
                pass
    return None
# Buggy code
def from_json(cls, json_info):
    from ..util import parse_date

    info = {key: val for key, val in json_info.items() if key in cls.field_names()}
    info["start_ts"] = parse_date(info["start_ts"])
    info["end_ts"] = parse_date(info["end_ts"])
    info["cmd_version"] = info.get("cmd_version")
    return cls(**info)


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/USERNAME/.local/bin/archivebox", line 8, in <module>
sys.exit(main())
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 126, in main
pwd=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/__init__.py", line 62, in run_subcommand
module.main(args=subcommand_args, stdin=stdin, pwd=pwd)    # type: ignore
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/cli/archivebox_init.py", line 34, in main
out_dir=pwd or OUTPUT_DIR,
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/main.py", line 316, in init
for link in load_main_index(out_dir=out_dir, warn=False)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/util.py", line 108, in typechecked_function
return func(*args, **kwargs)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/__init__.py", line 250, in load_main_index
all_links = list(parse_json_main_index(out_dir))
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/json.py", line 52, in parse_json_main_index
yield Link.from_json(link_json)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 203, in from_json
cast_result = ArchiveResult.from_json(json_result)
File "/home/USERNAME/.local/lib/python3.7/site-packages/archivebox/index/schema.py", line 62, in from_json
info['start_ts'] = parse_date(info['start_ts'])
KeyError: 'start_ts'

# Fixed code
def from_json(cls, json_info, guess=False):
    from ..util import parse_date

    info = {key: val for key, val in json_info.items() if key in cls.field_names()}
    if guess:
        keys = info.keys()
        if "start_ts" not in keys:
            info["start_ts"], info["end_ts"] = cls.guess_ts(json_info)
        else:
            info["start_ts"] = parse_date(info["start_ts"])
            info["end_ts"] = parse_date(info["end_ts"])
        if "pwd" not in keys:
            info["pwd"] = str(
                Path(OUTPUT_DIR) / ARCHIVE_DIR_NAME / json_info["timestamp"]
            )
        if "cmd_version" not in keys:
            info["cmd_version"] = "Undefined"
        if "cmd" not in keys:
            info["cmd"] = []
    else:
        info["start_ts"] = parse_date(info["start_ts"])
        info["end_ts"] = parse_date(info["end_ts"])
        info["cmd_version"] = info.get("cmd_version")
    return cls(**info)
# Buggy code
def main_group(
    ctx,
    verbose,
    quiet,
    aws_profile,
    aws_no_sign_requests,
    aws_requester_pays,
    gdal_version,
):
    """Rasterio command line interface."""
    verbosity = verbose - quiet
    configure_logging(verbosity)
    ctx.obj = {}
    ctx.obj["verbosity"] = verbosity
    ctx.obj["aws_profile"] = aws_profile
    envopts = {"CPL_DEBUG": (verbosity > 2)}
    if aws_profile or aws_no_sign_requests:
        ctx.obj["env"] = rasterio.Env(
            session=AWSSession(
                profile_name=aws_profile,
                aws_unsigned=aws_no_sign_requests,
                requester_pays=aws_requester_pays,
            ),
            **envopts,
        )
    else:
        ctx.obj["env"] = rasterio.Env(**envopts)


# Traceback (rasterio._err.CPLE_AWSAccessDeniedError)
Traceback (most recent call last):
File "rasterio/_base.pyx", line 216, in rasterio._base.DatasetBase.__init__
File "rasterio/_shim.pyx", line 78, in rasterio._shim.open_dataset
File "rasterio/_err.pyx", line 213, in rasterio._err.exc_wrap_pointer
rasterio._err.CPLE_AWSAccessDeniedError: Access Denied

# Fixed code
def main_group(
    ctx,
    verbose,
    quiet,
    aws_profile,
    aws_no_sign_requests,
    aws_requester_pays,
    gdal_version,
):
    """Rasterio command line interface."""
    verbosity = verbose - quiet
    configure_logging(verbosity)
    ctx.obj = {}
    ctx.obj["verbosity"] = verbosity
    ctx.obj["aws_profile"] = aws_profile
    envopts = {"CPL_DEBUG": (verbosity > 2)}
    if aws_profile or aws_no_sign_requests or aws_requester_pays:
        ctx.obj["env"] = rasterio.Env(
            session=AWSSession(
                profile_name=aws_profile,
                aws_unsigned=aws_no_sign_requests,
                requester_pays=aws_requester_pays,
            ),
            **envopts,
        )
    else:
        ctx.obj["env"] = rasterio.Env(**envopts)
# Buggy code
def __getstate__(self):
    return self.wkt


# Traceback (AttributeError)
In [1]: from copy import copy

In [2]: from rasterio.crs import CRS

In [3]: some_crs = CRS(init='epsg:32620')

In [4]: crs = copy(some_crs)

In [5]: bool(some_crs)
Out[5]: True

In [6]: bool(crs)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-dfa06d6ae714> in <module>
----> 1 bool(crs)

~/satellogic/env/lib/python3.6/site-packages/rasterio/crs.py in __bool__(self)
82
83     def __bool__(self):
---> 84         return bool(self.wkt)
85
86     __nonzero__ = __bool__

~/satellogic/env/lib/python3.6/site-packages/rasterio/crs.py in wkt(self)
130
131         """
--> 132         if not self._wkt:
133             self._wkt = self.to_wkt()
134         return self._wkt

AttributeError: 'CRS' object has no attribute '_wkt'

# Fixed code
def __getstate__(self):
    return self.to_wkt()
# Buggy code
def __setstate__(self, state):
    self._crs = _CRS.from_wkt(state)


# Traceback (AttributeError)
In [1]: from copy import copy

In [2]: from rasterio.crs import CRS

In [3]: some_crs = CRS(init='epsg:32620')

In [4]: crs = copy(some_crs)

In [5]: bool(some_crs)
Out[5]: True

In [6]: bool(crs)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-dfa06d6ae714> in <module>
----> 1 bool(crs)

~/satellogic/env/lib/python3.6/site-packages/rasterio/crs.py in __bool__(self)
82
83     def __bool__(self):
---> 84         return bool(self.wkt)
85
86     __nonzero__ = __bool__

~/satellogic/env/lib/python3.6/site-packages/rasterio/crs.py in wkt(self)
130
131         """
--> 132         if not self._wkt:
133             self._wkt = self.to_wkt()
134         return self._wkt

AttributeError: 'CRS' object has no attribute '_wkt'

# Fixed code
def __setstate__(self, state):
    self._wkt = None
    self._data = None
    self._crs = _CRS.from_wkt(state)
# Buggy code
def __init__(self, initialdata=None, **kwargs):
    """Make a CRS from a PROJ dict or mapping

    Parameters
    ----------
    initialdata : mapping, optional
        A dictionary or other mapping
    kwargs : mapping, optional
        Another mapping. Will be overlaid on the initialdata.

    Returns
    -------
    CRS

    """
    self._wkt = None
    self._data = None
    self._crs = None

    if initialdata or kwargs:
        data = dict(initialdata or {})
        data.update(**kwargs)
        data = {k: v for k, v in data.items() if k in all_proj_keys}

        # always use lowercase 'epsg'.
        if "init" in data:
            data["init"] = data["init"].replace("EPSG:", "epsg:")

        proj = " ".join(["+{}={}".format(key, val) for key, val in data.items()])
        self._crs = _CRS.from_proj4(proj)

    else:
        self._crs = _CRS()


# Traceback (rasterio.errors.CRSError)
src_crs = rcrs(src_proj)

dst_crs = rcrs(dst_proj)

warp.calculate_default_transform(src_crs, dst_crs, src_width, src_height, left, bottom, right, top)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/trst2284/miniconda3/envs/test/lib/python3.6/site-packages/rasterio/env.py", line 373, in wrapper
return f(*args, **kwds)
File "/home/trst2284/miniconda3/envs/test/lib/python3.6/site-packages/rasterio/warp.py", line 418, in calculate_default_transform
src_crs, dst_crs, width, height, left, bottom, right, top, gcps)
File "rasterio/_warp.pyx", line 542, in rasterio._warp._calculate_default_transform
File "rasterio/_base.pyx", line 1331, in rasterio._base._osr_from_crs
rasterio.errors.CRSError: Invalid CRS: CRS({'ellps': 'WGS84', 'h': 9000000.0, 'lat_0': -78.0, 'lon_0': 0.0, 'proj': 'nsper', 'units': 'm', 'x_0': 0, 'y_0': 0, 'wktext': True})

# Fixed code
def __init__(self, initialdata=None, **kwargs):
    """Make a CRS from a PROJ dict or mapping

    Parameters
    ----------
    initialdata : mapping, optional
        A dictionary or other mapping
    kwargs : mapping, optional
        Another mapping. Will be overlaid on the initialdata.

    Returns
    -------
    CRS

    """
    self._wkt = None
    self._data = None
    self._crs = None

    if initialdata or kwargs:
        data = dict(initialdata or {})
        data.update(**kwargs)
        data = {k: v for k, v in data.items() if k in all_proj_keys}

        # always use lowercase 'epsg'.
        if "init" in data:
            data["init"] = data["init"].replace("EPSG:", "epsg:")

        proj_parts = []

        for key, val in data.items():
            if val is False or None:
                continue
            elif val is True:
                proj_parts.append("+{}".format(key))
            else:
                proj_parts.append("+{}={}".format(key, val))

        proj = " ".join(proj_parts)
        self._crs = _CRS.from_proj4(proj)

    else:
        self._crs = _CRS()
# Buggy code
def __enter__(self):
    log.debug("Entering env context: %r", self)
    if local._env is None:
        log.debug("Starting outermost env")
        self._has_parent_env = False

        # See note directly above where _discovered_options is globally
        # defined.  This MUST happen before calling 'defenv()'.
        local._discovered_options = {}
        # Don't want to reinstate the "RASTERIO_ENV" option.
        probe_env = {k for k in self.options.keys() if k != "RASTERIO_ENV"}
        for key in probe_env:
            val = get_gdal_config(key, normalize=False)
            if val is not None:
                local._discovered_options[key] = val

        defenv(**self.options)
        self.context_options = {}
    else:
        self._has_parent_env = True
        self.context_options = getenv()
        setenv(**self.options)

    self.credentialize()

    log.debug("Entered env context: %r", self)
    return self


# Traceback (rasterio._err.CPLE_OpenFailedError)
from rasterio.crs import CRS
CRS({'init': 'epsg:4326'}).is_geographic
ERROR 4: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.
Traceback (most recent call last):
File "rasterio/_base.pyx", line 1310, in rasterio._base._osr_from_crs
File "rasterio/_err.pyx", line 182, in rasterio._err.exc_wrap_int
rasterio._err.CPLE_OpenFailedError: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "rasterio/_crs.pyx", line 37, in rasterio._crs._CRS.is_geographic
File "rasterio/_base.pyx", line 1316, in rasterio._base._osr_from_crs
rasterio.errors.CRSError: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.

# Fixed code
def __enter__(self):
    return self
# Buggy code
def __exit__(self, exc_type=None, exc_val=None, exc_tb=None):
    log.debug("Exiting env context: %r", self)
    delenv()
    if self._has_parent_env:
        defenv()
        setenv(**self.context_options)
    else:
        log.debug("Exiting outermost env")
        # See note directly above where _discovered_options is globally
        # defined.
        while local._discovered_options:
            key, val = local._discovered_options.popitem()
            set_gdal_config(key, val, normalize=False)
        local._discovered_options = None
    log.debug("Exited env context: %r", self)


# Traceback (rasterio._err.CPLE_OpenFailedError)
from rasterio.crs import CRS
CRS({'init': 'epsg:4326'}).is_geographic
ERROR 4: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.
Traceback (most recent call last):
File "rasterio/_base.pyx", line 1310, in rasterio._base._osr_from_crs
File "rasterio/_err.pyx", line 182, in rasterio._err.exc_wrap_int
rasterio._err.CPLE_OpenFailedError: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "rasterio/_crs.pyx", line 37, in rasterio._crs._CRS.is_geographic
File "rasterio/_base.pyx", line 1316, in rasterio._base._osr_from_crs
rasterio.errors.CRSError: Unable to open EPSG support file gcs.csv.  Try setting the GDAL_DATA environment variable to point to the directory containing EPSG csv files.

# Fixed code
def __exit__(self, *args):
    pass
# Buggy code
def xy(transform, rows, cols, offset="center"):
    """Returns the x and y coordinates of pixels at `rows` and `cols`.
    The pixel's center is returned by default, but a corner can be returned
    by setting `offset` to one of `ul, ur, ll, lr`.

    Parameters
    ----------
    transform : affine.Affine
        Transformation from pixel coordinates to coordinate reference system.
    rows : list or int
        Pixel rows.
    cols : list or int
        Pixel columns.
    offset : str, optional
        Determines if the returned coordinates are for the center of the
        pixel or for a corner.

    Returns
    -------
    xs : list
        x coordinates in coordinate reference system
    ys : list
        y coordinates in coordinate reference system
    """

    single_col = False
    single_row = False
    if not isinstance(cols, collections.Iterable):
        cols = [cols]
        single_col = True
    if not isinstance(rows, collections.Iterable):
        rows = [rows]
        single_row = True

    if offset == "center":
        coff, roff = (0.5, 0.5)
    elif offset == "ul":
        coff, roff = (0, 0)
    elif offset == "ur":
        coff, roff = (1, 0)
    elif offset == "ll":
        coff, roff = (0, 1)
    elif offset == "lr":
        coff, roff = (1, 1)
    else:
        raise ValueError("Invalid offset")

    xs = []
    ys = []
    for col, row in zip(cols, rows):
        x, y = transform * transform.translation(coff, roff) * (col, row)
        xs.append(x)
        ys.append(y)

    if single_row:
        ys = ys[0]
    if single_col:
        xs = xs[0]

    return xs, ys


# Traceback (ImportError)
Traceback (most recent call last):
File "buh.py", line 1, in <module>
import rasterio
File "/Users/wursterk/code/rasterio/rasterio/__init__.py", line 25, in <module>
from rasterio.io import (
File "/Users/wursterk/code/rasterio/rasterio/io.py", line 13, in <module>
from rasterio._io import (
File "rasterio/_io.pyx", line 31, in init rasterio._io
from rasterio.vrt import WarpedVRT
File "/Users/wursterk/code/rasterio/rasterio/vrt.py", line 4, in <module>
from rasterio.io import WindowMethodsMixin, TransformMethodsMixin
ImportError: cannot import name 'WindowMethodsMixin'

# Fixed code
def xy(self, row, col, offset="center"):
    """Returns the coordinates ``(x, y)`` of a pixel at `row` and `col`.
    The pixel's center is returned by default, but a corner can be returned
    by setting `offset` to one of `ul, ur, ll, lr`.

    Parameters
    ----------
    row : int
        Pixel row.
    col : int
        Pixel column.
    offset : str, optional
        Determines if the returned coordinates are for the center of the
        pixel or for a corner.

    Returns
    -------
    tuple
        ``(x, y)``
    """
    return xy(self.transform, row, col, offset=offset)
# Buggy code
def tastes_like_gdal(t):
    return t[2] == t[4] == 0.0 and t[1] > 0 and t[5] < 0


# Traceback (ValueError)
Traceback (most recent call last):
...
File "copier.py", line 15, in to_png
with rio.open(dst_path, "w", **meta) as dst:
File "xxx/anaconda/lib/python2.7/site-packages/rasterio/__init__.py", line 91, in open
transform = guard_transform(transform)
File "xxx/anaconda/lib/python2.7/site-packages/rasterio/transform.py", line 27, in guard_transform
transform.a, transform.e))
ValueError: Transform has invalid coefficients a, e: (0.000000, 0.000000)

# Fixed code
def tastes_like_gdal(seq):
    """Return True if `seq` matches the GDAL geotransform pattern."""
    return seq[2] == seq[4] == 0.0 and seq[1] > 0 and seq[5] < 0
# Buggy code
def guard_transform(transform):
    """Return an Affine transformation instance"""
    if not isinstance(transform, Affine):
        if tastes_like_gdal(transform):
            warnings.warn(
                "GDAL-style transforms are deprecated and will not "
                "be supported in Rasterio 1.0.",
                FutureWarning,
                stacklevel=2,
            )
            transform = Affine.from_gdal(*transform)
        else:
            transform = Affine(*transform)
    a, e = transform.a, transform.e
    if a == 0.0 or e == 0.0:
        raise ValueError(
            "Transform has invalid coefficients a, e: (%f, %f)"
            % (transform.a, transform.e)
        )
    return transform


# Traceback (ValueError)
Traceback (most recent call last):
...
File "copier.py", line 15, in to_png
with rio.open(dst_path, "w", **meta) as dst:
File "xxx/anaconda/lib/python2.7/site-packages/rasterio/__init__.py", line 91, in open
transform = guard_transform(transform)
File "xxx/anaconda/lib/python2.7/site-packages/rasterio/transform.py", line 27, in guard_transform
transform.a, transform.e))
ValueError: Transform has invalid coefficients a, e: (0.000000, 0.000000)

# Fixed code
def guard_transform(transform):
    """Return an Affine transformation instance"""
    if not isinstance(transform, Affine):
        if tastes_like_gdal(transform):
            warnings.warn(
                "GDAL-style transforms are deprecated and will not "
                "be supported in Rasterio 1.0.",
                FutureWarning,
                stacklevel=2,
            )
            transform = Affine.from_gdal(*transform)
        else:
            transform = Affine(*transform)
    return transform
# Buggy code
def init_cgroups():
    # Track metrics for the roll-up cgroup and for the agent cgroup
    try:
        CGroupsTelemetry.track_cgroup(CGroups.for_extension(""))
        CGroupsTelemetry.track_agent()
    except Exception as e:
        logger.error(
            "monitor: Exception tracking wrapper and agent: {0} [{1}]",
            e,
            traceback.format_exc(),
        )


# Traceback (azurelinuxagent.common.cgroups.CGroupsException)
2018/07/31 11:41:06.400633 ERROR ExtHandler monitor: Exception tracking wrapper and agent: 'Hierarchy memory is not mounted' [Traceback (most recent call last):
File "bin/WALinuxAgent-2.2.30-py2.7.egg/azurelinuxagent/ga/monitor.py", line 397, in init_cgroups
CGroupsTelemetry.track_cgroup(CGroups.for_extension(""))
File "bin/WALinuxAgent-2.2.30-py2.7.egg/azurelinuxagent/common/cgroups.py", line 360, in for_extension
return CGroups(name, CGroups._construct_custom_path_for_hierarchy)
File "bin/WALinuxAgent-2.2.30-py2.7.egg/azurelinuxagent/common/cgroups.py", line 401, in __init__
raise CGroupsException("Hierarchy {0} is not mounted".format(hierarchy))
azurelinuxagent.common.cgroups.CGroupsException: 'Hierarchy memory is not mounted'
]

# Fixed code
def init_cgroups():
    # Track metrics for the roll-up cgroup and for the agent cgroup
    try:
        CGroupsTelemetry.track_cgroup(CGroups.for_extension(""))
        CGroupsTelemetry.track_agent()
    except Exception as e:
        # when a hierarchy is not mounted, we raise an exception
        # and we should therefore only issue a warning, since this
        # is not unexpected
        logger.warn("Monitor: cgroups not initialized: {0}", ustr(e))
        logger.verbose(traceback.format_exc())
# Buggy code
def set_selinux_context(self, path, con):
    """
    Calls shell 'chcon' with 'path' and 'con' context.
    Returns exit result.
    """
    if self.is_selinux_system():
        return shellutil.run("chcon " + con + " " + path)


# Traceback (CalledProcessError)
2015/08/19 12:35:10 Created user account: azureuser
2015/08/19 12:35:10 Deploy public key:28EC0E2C8F27A2A0D081742A97D517CBD1FFFFFF
2015/08/19 12:35:10 ERROR:Failed: 28EC0E2C8F27A2A0D081742A97D517CBD1FFFFFF.pub.crt -> /home/azureuser/.ssh/authorized_keys
2015/08/19 12:35:10 ERROR:CalledProcessError.  Error Code is 1
2015/08/19 12:35:10 ERROR:CalledProcessError.  Command string was chcon unconfined_u:object_r:ssh_home_t:s0 /home/azureuser/.ssh/authorized_keys
2015/08/19 12:35:10 ERROR:CalledProcessError.  Command result was chcon: cannot access /home/azureuser/.ssh/authorized_keys: No such file or directory
2015/08/19 12:35:10 ERROR:Traceback (most recent call last):
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 6048, in main
2015/08/19 12:35:10 ERROR:    WaAgent.Run()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 5571, in Run
2015/08/19 12:35:10 ERROR:    provisionError = self.Provision()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 5457, in Provision
2015/08/19 12:35:10 ERROR:    error = ovfobj.Process()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 4566, in Process
2015/08/19 12:35:10 ERROR:    ChangeOwner(path, self.UserName)
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 2242, in ChangeOwner
2015/08/19 12:35:10 ERROR:    os.chown(filepath, p[2], p[3])
2015/08/19 12:35:10 ERROR:OSError: [Errno 2] No such file or directory: '/home/azureuser/.ssh/authorized_keys'
2015/08/19 12:35:10 ERROR:
2015/08/19 12:35:10 ERROR:Exception: [Errno 2] No such file or directory: '/home/azureuser/.ssh/authorized_keys'

# Fixed code
def set_selinux_context(self, path, con):
    """
    Calls shell 'chcon' with 'path' and 'con' context.
    Returns exit result.
    """
    if self.is_selinux_system():
        if not os.path.exists(path):
            logger.error("Path does not exist: {0}".format(path))
            return 1
        return shellutil.run("chcon " + con + " " + path)
# Buggy code
def chowner(path, owner):
    owner_info = pwd.getpwnam(owner)
    os.chown(path, owner_info[2], owner_info[3])


# Traceback (CalledProcessError)
2015/08/19 12:35:10 Created user account: azureuser
2015/08/19 12:35:10 Deploy public key:28EC0E2C8F27A2A0D081742A97D517CBD1FFFFFF
2015/08/19 12:35:10 ERROR:Failed: 28EC0E2C8F27A2A0D081742A97D517CBD1FFFFFF.pub.crt -> /home/azureuser/.ssh/authorized_keys
2015/08/19 12:35:10 ERROR:CalledProcessError.  Error Code is 1
2015/08/19 12:35:10 ERROR:CalledProcessError.  Command string was chcon unconfined_u:object_r:ssh_home_t:s0 /home/azureuser/.ssh/authorized_keys
2015/08/19 12:35:10 ERROR:CalledProcessError.  Command result was chcon: cannot access /home/azureuser/.ssh/authorized_keys: No such file or directory
2015/08/19 12:35:10 ERROR:Traceback (most recent call last):
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 6048, in main
2015/08/19 12:35:10 ERROR:    WaAgent.Run()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 5571, in Run
2015/08/19 12:35:10 ERROR:    provisionError = self.Provision()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 5457, in Provision
2015/08/19 12:35:10 ERROR:    error = ovfobj.Process()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 4566, in Process
2015/08/19 12:35:10 ERROR:    ChangeOwner(path, self.UserName)
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 2242, in ChangeOwner
2015/08/19 12:35:10 ERROR:    os.chown(filepath, p[2], p[3])
2015/08/19 12:35:10 ERROR:OSError: [Errno 2] No such file or directory: '/home/azureuser/.ssh/authorized_keys'
2015/08/19 12:35:10 ERROR:
2015/08/19 12:35:10 ERROR:Exception: [Errno 2] No such file or directory: '/home/azureuser/.ssh/authorized_keys'

# Fixed code
def chowner(path, owner):
    if not os.path.exists(path):
        logger.error("Path does not exist: {0}".format(path))
    else:
        owner_info = pwd.getpwnam(owner)
        os.chown(path, owner_info[2], owner_info[3])
# Buggy code
def chmod(path, mode):
    os.chmod(path, mode)


# Traceback (CalledProcessError)
2015/08/19 12:35:10 Created user account: azureuser
2015/08/19 12:35:10 Deploy public key:28EC0E2C8F27A2A0D081742A97D517CBD1FFFFFF
2015/08/19 12:35:10 ERROR:Failed: 28EC0E2C8F27A2A0D081742A97D517CBD1FFFFFF.pub.crt -> /home/azureuser/.ssh/authorized_keys
2015/08/19 12:35:10 ERROR:CalledProcessError.  Error Code is 1
2015/08/19 12:35:10 ERROR:CalledProcessError.  Command string was chcon unconfined_u:object_r:ssh_home_t:s0 /home/azureuser/.ssh/authorized_keys
2015/08/19 12:35:10 ERROR:CalledProcessError.  Command result was chcon: cannot access /home/azureuser/.ssh/authorized_keys: No such file or directory
2015/08/19 12:35:10 ERROR:Traceback (most recent call last):
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 6048, in main
2015/08/19 12:35:10 ERROR:    WaAgent.Run()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 5571, in Run
2015/08/19 12:35:10 ERROR:    provisionError = self.Provision()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 5457, in Provision
2015/08/19 12:35:10 ERROR:    error = ovfobj.Process()
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 4566, in Process
2015/08/19 12:35:10 ERROR:    ChangeOwner(path, self.UserName)
2015/08/19 12:35:10 ERROR:  File "/usr/sbin/waagent", line 2242, in ChangeOwner
2015/08/19 12:35:10 ERROR:    os.chown(filepath, p[2], p[3])
2015/08/19 12:35:10 ERROR:OSError: [Errno 2] No such file or directory: '/home/azureuser/.ssh/authorized_keys'
2015/08/19 12:35:10 ERROR:
2015/08/19 12:35:10 ERROR:Exception: [Errno 2] No such file or directory: '/home/azureuser/.ssh/authorized_keys'

# Fixed code
def chmod(path, mode):
    if not os.path.exists(path):
        logger.error("Path does not exist: {0}".format(path))
    else:
        os.chmod(path, mode)
# Buggy code
def __init__(self, **kwargs):
    _gp_searcher = kwargs.get("_gp_searcher")
    if _gp_searcher is None:
        _kwargs = check_and_merge_defaults(
            kwargs, *gp_fifo_searcher_defaults(), dict_name="search_options"
        )
        _gp_searcher = gp_fifo_searcher_factory(**_kwargs)
    super().__init__(
        _gp_searcher.hp_ranges.config_space,
        reward_attribute=kwargs.get("reward_attribute"),
    )
    self.gp_searcher = _gp_searcher
    # This lock protects gp_searcher. We are not using self.LOCK, this
    # can lead to deadlocks when superclass methods are called
    self._gp_lock = mp.Lock()


# Traceback (TypeError)
Traceback (most recent call last):
File "/Users/yixiaxia/Desktop/test/test.py", line 17, in <module>
searcher = GPFIFOSearcher(train_fn.cs)
TypeError: __init__() takes 1 positional argument but 2 were given

# Fixed code
def __init__(self, configspace, **kwargs):
    _gp_searcher = kwargs.get("_gp_searcher")
    if _gp_searcher is None:
        kwargs["configspace"] = configspace
        _kwargs = check_and_merge_defaults(
            kwargs, *gp_fifo_searcher_defaults(), dict_name="search_options"
        )
        _gp_searcher = gp_fifo_searcher_factory(**_kwargs)
    super().__init__(
        _gp_searcher.hp_ranges.config_space,
        reward_attribute=kwargs.get("reward_attribute"),
    )
    self.gp_searcher = _gp_searcher
    # This lock protects gp_searcher. We are not using self.LOCK, this
    # can lead to deadlocks when superclass methods are called
    self._gp_lock = mp.Lock()
# Buggy code
def unpack(g):
    def _unpack_inner(f):
        @functools.wraps(f)
        def _call(**kwargs):
            return f(**g(**kwargs))

        return _call

    return _unpack_inner


# Traceback (TypeError)
Loaded data from: https://autogluon.s3.amazonaws.com/datasets/AdultIncomeBinaryClassification/train_data.csv | Columns = 15 / 15 | Rows = 39073 -> 39073

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2666bea8bf44> in <module>
3 # train_path = data_dir + "titanic_clean.csv"
4 train_data = task.Dataset(file_path=train_path)
----> 5 predictor = task.fit(train_data, label='survived', output_directory='ag-example-out/')

TypeError: _call() takes 0 positional arguments but 1 was given

# Fixed code
def unpack(g):
    def _unpack_inner(f):
        @functools.wraps(f)
        def _call(*args, **kwargs):
            gargs, gkwargs = g(*args, **kwargs)
            return f(*gargs, **gkwargs)

        return _call

    return _unpack_inner
# Buggy code
def _unpack_inner(f):
    @functools.wraps(f)
    def _call(**kwargs):
        return f(**g(**kwargs))

    return _call


# Traceback (TypeError)
Loaded data from: https://autogluon.s3.amazonaws.com/datasets/AdultIncomeBinaryClassification/train_data.csv | Columns = 15 / 15 | Rows = 39073 -> 39073

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2666bea8bf44> in <module>
3 # train_path = data_dir + "titanic_clean.csv"
4 train_data = task.Dataset(file_path=train_path)
----> 5 predictor = task.fit(train_data, label='survived', output_directory='ag-example-out/')

TypeError: _call() takes 0 positional arguments but 1 was given

# Fixed code
def _unpack_inner(f):
    @functools.wraps(f)
    def _call(*args, **kwargs):
        gargs, gkwargs = g(*args, **kwargs)
        return f(*gargs, **gkwargs)

    return _call
# Buggy code
def _call(**kwargs):
    return f(**g(**kwargs))


# Traceback (TypeError)
Loaded data from: https://autogluon.s3.amazonaws.com/datasets/AdultIncomeBinaryClassification/train_data.csv | Columns = 15 / 15 | Rows = 39073 -> 39073

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2666bea8bf44> in <module>
3 # train_path = data_dir + "titanic_clean.csv"
4 train_data = task.Dataset(file_path=train_path)
----> 5 predictor = task.fit(train_data, label='survived', output_directory='ag-example-out/')

TypeError: _call() takes 0 positional arguments but 1 was given

# Fixed code
def _call(*args, **kwargs):
    gargs, gkwargs = g(*args, **kwargs)
    return f(*gargs, **gkwargs)
# Buggy code
def set_presets(**kwargs):
    if "presets" in kwargs:
        presets = kwargs["presets"]
        if presets is None:
            return kwargs
        if not isinstance(presets, list):
            presets = [presets]
        preset_kwargs = {}
        for preset in presets:
            if isinstance(preset, str):
                preset_orig = preset
                preset = preset_dict.get(preset, None)
                if preset is None:
                    raise ValueError(
                        f"Preset '{preset_orig}' was not found. Valid presets: {list(preset_dict.keys())}"
                    )
            if isinstance(preset, dict):
                for key in preset:
                    preset_kwargs[key] = preset[key]
            else:
                raise TypeError(
                    f"Preset of type {type(preset)} was given, but only presets of type [dict, str] are valid."
                )
        for key in preset_kwargs:
            if key not in kwargs:
                kwargs[key] = preset_kwargs[key]
    return kwargs


# Traceback (TypeError)
Loaded data from: https://autogluon.s3.amazonaws.com/datasets/AdultIncomeBinaryClassification/train_data.csv | Columns = 15 / 15 | Rows = 39073 -> 39073

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2666bea8bf44> in <module>
3 # train_path = data_dir + "titanic_clean.csv"
4 train_data = task.Dataset(file_path=train_path)
----> 5 predictor = task.fit(train_data, label='survived', output_directory='ag-example-out/')

TypeError: _call() takes 0 positional arguments but 1 was given

# Fixed code
def set_presets(*args, **kwargs):
    if "presets" in kwargs:
        presets = kwargs["presets"]
        if presets is None:
            return kwargs
        if not isinstance(presets, list):
            presets = [presets]
        preset_kwargs = {}
        for preset in presets:
            if isinstance(preset, str):
                preset_orig = preset
                preset = preset_dict.get(preset, None)
                if preset is None:
                    raise ValueError(
                        f"Preset '{preset_orig}' was not found. Valid presets: {list(preset_dict.keys())}"
                    )
            if isinstance(preset, dict):
                for key in preset:
                    preset_kwargs[key] = preset[key]
            else:
                raise TypeError(
                    f"Preset of type {type(preset)} was given, but only presets of type [dict, str] are valid."
                )
        for key in preset_kwargs:
            if key not in kwargs:
                kwargs[key] = preset_kwargs[key]
    return args, kwargs
# Buggy code
def generate_csv(inds, path):
    with open(path, "w") as csvFile:
        row = ["id", "category"]
        writer = csv.writer(csvFile)
        writer.writerow(row)
        id = 1
        for ind in inds:
            row = [id, ind.asscalar()]
            writer = csv.writer(csvFile)
            writer.writerow(row)
            id += 1
    csvFile.close()


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-9-ef60c46c4aa0> in <module>
1 import autogluon as ag
----> 2 ag.utils.generate_csv(inds, 'submission_autogluon.csv')

/opt/conda/lib/python3.6/site-packages/autogluon/utils/file_helper.py in generate_csv(inds, path)
147         id = 1
148         for ind in inds:
--> 149             row = [id, ind.asscalar()]
150             writer = csv.writer(csvFile)
151             writer.writerow(row)

AttributeError: 'numpy.int64' object has no attribute 'asscalar'

# Fixed code
def generate_csv(inds, path):
    with open(path, "w") as csvFile:
        row = ["id", "category"]
        writer = csv.writer(csvFile)
        writer.writerow(row)
        id = 1
        for ind in inds:
            row = [id, ind]
            writer = csv.writer(csvFile)
            writer.writerow(row)
            id += 1
    csvFile.close()
# Buggy code
def _get_best_hps(self):
    best_trials = self.get_best_trials()
    if best_trials:
        return best_trials[0].hyperparameters
    else:
        return self.hyperparameters


# Traceback (KeyError)
Traceback (most recent call last):
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\kerastuner\engine\hypermodel.py", line 104, in build
model = self.hypermodel.build(hp)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\kerastuner\engine\hypermodel.py", line 64, in _build_wrapper
return self._build(hp, *args, **kwargs)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\autokeras\graph.py", line 263, in build
outputs = block.build(hp, inputs=temp_inputs)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\autokeras\engine\block.py", line 48, in _build_wrapper
return super()._build_wrapper(hp, *args, **kwargs)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\kerastuner\engine\hypermodel.py", line 64, in _build_wrapper
return self._build(hp, *args, **kwargs)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\autokeras\blocks\wrapper.py", line 102, in build
output_node = self._build_block(hp, output_node, block_type)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\autokeras\blocks\wrapper.py", line 77, in _build_block
return basic.XceptionBlock().build(hp, output_node)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\autokeras\engine\block.py", line 48, in _build_wrapper
return super()._build_wrapper(hp, *args, **kwargs)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\kerastuner\engine\hypermodel.py", line 64, in _build_wrapper
return self._build(hp, *args, **kwargs)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\autokeras\blocks\basic.py", line 574, in build
model.trainable = hp.Boolean("trainable", default=False)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\kerastuner\engine\hyperparameters.py", line 814, in Boolean
return self._retrieve(hp)
File "P:\ProgramFiles\anaconda\envs\python\test\lib\site-packages\kerastuner\engine\hyperparameters.py", line 625, in _retrieve
return self.values[hp.name]
KeyError: 'image_block_1/xception_block_1/trainable'

# Fixed code
def _get_best_hps(self):
    best_trials = self.get_best_trials()
    if best_trials:
        return best_trials[0].hyperparameters.copy()
    else:
        return self.hyperparameters.copy()
# Buggy code
def __init__(self, loss=None, metrics=None, output_shape=None, **kwargs):
    super().__init__(**kwargs)
    self.output_shape = output_shape
    self.loss = loss
    self.metrics = metrics


# Traceback (TypeError)
Traceback (most recent call last):
File "mnist_model.py", line 12, in <module>
clf = ak.ImageClassifier(metrics=['accuracy', custom_metric], max_trials=3)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 67, in __init__
seed=seed)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tasks/image.py", line 19, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/auto_model.py", line 125, in __init__
project_name=name)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/task_specific.py", line 66, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/tuners/greedy.py", line 197, in __init__
**kwargs)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/engine/tuner.py", line 35, in __init__
graph_module.serialize(self.hypermodel.hypermodel))
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/site-packages/autokeras/utils.py", line 179, in save_json
obj = json.dumps(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/home/lhs18285/miniconda3/envs/nas/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type function is not JSON serializable

# Fixed code
def __init__(self, loss=None, metrics=None, output_shape=None, **kwargs):
    super().__init__(**kwargs)
    self.output_shape = output_shape
    self.loss = tf.keras.losses.get(loss)
    if metrics is None:
        metrics = []
    self.metrics = [tf.keras.metrics.get(metric) for metric in metrics]