gurudesh/pytracebugs huggingface dataset:
# Buggy code
def update_item_times(lib, item):
    mtime = item_mtime[item.path]
    if mtime is not None:
        item.added = mtime
        if config["importadded"]["preserve_mtimes"].get(bool):
            write_item_mtime(item, mtime)
        item.store()
        del item_mtime[item.path]


# Traceback (KeyError)
$ beet import -L

/beets/src/media/library/Younger Brother (2011) - Vaccine (9 items)
Tagging:
Younger Brother - Vaccine
URL:
http://musicbrainz.org/release/7da3a7d8-0240-4ebd-bab6-44a1a72504fe
(Similarity: 100.0%) (CD, 2011, US, SCI Fidelity Records)
Traceback (most recent call last):
File "/beets/bin/beet", line 20, in <module>
beets.ui.main()
File "/beets/src/beets/beets/ui/__init__.py", line 966, in main
_raw_main(args)
File "/beets/src/beets/beets/ui/__init__.py", line 957, in _raw_main
subcommand.func(lib, suboptions, subargs)
File "/beets/src/beets/beets/ui/commands.py", line 884, in import_func
import_files(lib, paths, query)
File "/beets/src/beets/beets/ui/commands.py", line 856, in import_files
session.run()
File "/beets/src/beets/beets/importer.py", line 293, in run
pl.run_sequential()
File "/beets/src/beets/beets/util/pipeline.py", line 376, in run_sequential
list(self.pull())
File "/beets/src/beets/beets/util/pipeline.py", line 453, in pull
out = coro.send(msg)
File "/beets/src/beets/beets/util/pipeline.py", line 158, in coro
task = func(*(args + (task,)))
File "/beets/src/beets/beets/importer.py", line 1138, in manipulate_files
task.finalize(session)
File "/beets/src/beets/beets/importer.py", line 470, in finalize
self._emit_imported(session.lib)
File "/beets/src/beets/beets/importer.py", line 502, in _emit_imported
plugins.send('album_imported', lib=lib, album=self.album)
File "/beets/src/beets/beets/plugins.py", line 379, in send
handler(**args)
File "/beets/src/beets/beetsplug/importadded.py", line 77, in update_album_times
mtime = item_mtime[item.path]
KeyError: '/beets/src/media/library/Younger Brother (2011) - Vaccine/Younger Brother - Vaccine - 01 - Crystalline.flac'

# Fixed code
def update_item_times(lib, item):
    if reimported_item(item):
        log.debug(
            "Item '{0}' is reimported, skipping import of added date.".format(
                util.displayable_path(item.path)
            )
        )
        return
    mtime = item_mtime.pop(item.path, None)
    if mtime:
        item.added = mtime
        if config["importadded"]["preserve_mtimes"].get(bool):
            write_item_mtime(item, mtime)
        log.debug(
            "Import of item '{0}', selected item.added={1}".format(
                util.displayable_path(item.path), item.added
            )
        )
        item.store()
# Buggy code
def _build_m3u_filename(basename):
    """Builds unique m3u filename by appending given basename to current
    date."""

    basename = re.sub(r"[\s,'\"]", "_", basename)
    date = datetime.datetime.now().strftime("%Y%m%d_%Hh%M")
    path = normpath(
        os.path.join(
            config["importfeeds"]["dir"].as_filename(), date + "_" + basename + ".m3u"
        )
    )
    return path


# Traceback (IOError)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/bin/beet", line 9, in <module>
load_entry_point('beets==1.3.3', 'console_scripts', 'beet')()
File "/Users/drbob/Development/beets/beets/ui/__init__.py", line 946, in main
_raw_main(args)
File "/Users/drbob/Development/beets/beets/ui/__init__.py", line 937, in _raw_main
subcommand.func(lib, suboptions, subargs)
File "/Users/drbob/Development/beets/beets/ui/commands.py", line 843, in import_func
import_files(lib, paths, query)
File "/Users/drbob/Development/beets/beets/ui/commands.py", line 779, in import_files
session.run()
File "/Users/drbob/Development/beets/beets/importer.py", line 347, in run
pl.run_parallel(QUEUE_SIZE)
File "/Users/drbob/Development/beets/beets/util/pipeline.py", line 288, in run
self.coro.send(msg)
File "/Users/drbob/Development/beets/beets/importer.py", line 927, in finalize
lib=session.lib, album=album)
File "/Users/drbob/Development/beets/beets/plugins.py", line 372, in send
handler(**arguments)
File "/Users/drbob/Development/beets/beetsplug/importfeeds.py", line 127, in album_imported
_record_items(lib, album.album, album.items())
File "/Users/drbob/Development/beets/beetsplug/importfeeds.py", line 112, in _record_items
_write_m3u(m3u_path, paths)
File "/Users/drbob/Development/beets/beetsplug/importfeeds.py", line 81, in _write_m3u
with open(syspath(m3u_path), 'a') as f:
IOError: [Errno 2] No such file or directory: '/Users/drbob/Music/beets/Imports/20140313_16h26_Poor_Boy_/_Lucky_Man.m3u'

# Fixed code
def _build_m3u_filename(basename):
    """Builds unique m3u filename by appending given basename to current
    date."""

    basename = re.sub(r"[\s,/\\'\"]", "_", basename)
    date = datetime.datetime.now().strftime("%Y%m%d_%Hh%M")
    path = normpath(
        os.path.join(
            config["importfeeds"]["dir"].as_filename(), date + "_" + basename + ".m3u"
        )
    )
    return path
# Buggy code
def save_history(self):
    """Save the directory in the history for incremental imports."""
    if self.is_album and not self.sentinel:
        history_add(self.paths)


# Traceback (TypeError)
Traceback (most recent call last):
File "/usr/local/bin/beet", line 9, in <module>
load_entry_point('beets==1.3.3', 'console_scripts', 'beet')()
File "/usr/local/lib/python2.7/dist-packages/beets/ui/__init__.py", line 946, in main
_raw_main(args)
File "/usr/local/lib/python2.7/dist-packages/beets/ui/__init__.py", line 937, in _raw_main
subcommand.func(lib, suboptions, subargs)
File "/usr/local/lib/python2.7/dist-packages/beets/ui/commands.py", line 843, in import_func
import_files(lib, paths, query)
File "/usr/local/lib/python2.7/dist-packages/beets/ui/commands.py", line 779, in import_files
session.run()
File "/usr/local/lib/python2.7/dist-packages/beets/importer.py", line 347, in run
pl.run_parallel(QUEUE_SIZE)
File "/usr/local/lib/python2.7/dist-packages/beets/util/pipeline.py", line 288, in run
self.coro.send(msg)
File "/usr/local/lib/python2.7/dist-packages/beets/importer.py", line 952, in finalize
task.save_history()
File "/usr/local/lib/python2.7/dist-packages/beets/importer.py", line 458, in save_history
history_add(self.paths)
File "/usr/local/lib/python2.7/dist-packages/beets/importer.py", line 210, in history_add
state[HISTORY_KEY].add(tuple(paths))
TypeError: 'NoneType' object is not iterable

# Fixed code
def save_history(self):
    """Save the directory in the history for incremental imports."""
    if self.is_album and self.paths and not self.sentinel:
        history_add(self.paths)
# Buggy code
def do_i_hate_this(cls, task, action_patterns):
    """Process group of patterns (warn or skip) and returns True if
    task is hated and not whitelisted.
    """
    if action_patterns:
        for query_string in action_patterns:
            query = None
            if task.is_album:
                query = get_query(query_string, Album)
            else:
                query = get_query(query_string, Item)
            if any(query.match(item) for item in task.items):
                return True
    return False


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/beet", line 8, in <module>
load_entry_point('beets==1.3.0', 'console_scripts', 'beet')()
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/ui/__init__.py", line 776, in main
_raw_main(args)
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/ui/__init__.py", line 768, in _raw_main
subcommand.func(lib, suboptions, subargs)
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/ui/commands.py", line 845, in import_func
import_files(lib, paths, query)
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/ui/commands.py", line 783, in import_files
session.run()
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/importer.py", line 341, in run
pl.run_parallel(QUEUE_SIZE)
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/util/pipeline.py", line 243, in run
out = self.coro.send(msg)
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/importer.py", line 952, in item_query
plugins.send('import_task_choice', session=session, task=task)
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beets/plugins.py", line 372, in send
handler(**arguments)
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beetsplug/ihate.py", line 104, in import_task_choice_event
self.config['skip_whitelist'].as_str_seq()):
File "/Library/Python/2.7/site-packages/beets-1.3.0-py2.7.egg/beetsplug/ihate.py", line 79, in do_i_hate_this
if not hate and task.cur_album and album_patterns:
AttributeError: 'ImportTask' object has no attribute 'cur_album'

# Fixed code
def do_i_hate_this(cls, task, action_patterns):
    """Process group of patterns (warn or skip) and returns True if
    task is hated and not whitelisted.
    """
    if action_patterns:
        for query_string in action_patterns:
            query = None
            if task.is_album:
                query = get_query(query_string, Album)
            else:
                query = get_query(query_string, Item)
            if any(query.match(item) for item in task.imported_items()):
                return True
    return False
# Buggy code
def cli_convert(infile, outfile, silent, verbosity, **options):
    """
    canmatrix.cli.convert [options] import-file export-file

    import-file: *.dbc|*.dbf|*.kcd|*.arxml|*.json|*.xls(x)|*.sym
    export-file: *.dbc|*.dbf|*.kcd|*.arxml|*.json|*.xls(x)|*.sym|*.py

    \n"""

    root_logger = canmatrix.log.setup_logger()

    if silent is True:
        # only print error messages, ignore verbosity flag
        verbosity = -1
        options["silent"] = True

    canmatrix.log.set_log_level(root_logger, verbosity)
    if options["ignoreEncodingErrors"]:
        options["ignoreEncodingErrors"] = "ignore"
    else:
        options["ignoreEncodingErrors"] = ""

    canmatrix.convert.convert(infile, outfile, **options)
    return 0


# Traceback (LookupError)
canconvert --deleteZeroSignals --ignoreEncodingErrors --cutLongFrames=8 -vv file.arxml file.dbf
...
...
Traceback (most recent call last):
File "/usr/local/bin/canconvert", line 11, in <module>
load_entry_point('canmatrix==0.9.1', 'console_scripts', 'canconvert')()
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.8/site-packages/canmatrix/cli/convert.py", line 131, in cli_convert
canmatrix.convert.convert(infile, outfile, **options)
File "/usr/local/lib/python3.8/site-packages/canmatrix/convert.py", line 214, in convert
canmatrix.formats.dumpp(out_dbs, out_file_name, **options)
File "/usr/local/lib/python3.8/site-packages/canmatrix/formats/__init__.py", line 135, in dumpp
dump(db, file_object, export_type, **options)
File "/usr/local/lib/python3.8/site-packages/canmatrix/formats/__init__.py", line 110, in dump
module_instance.dump(can_matrix_or_cluster, file_object, **options)  # type: ignore
File "/usr/local/lib/python3.8/site-packages/canmatrix/formats/dbf.py", line 521, in dump
f.write(out_str.encode(dbf_export_encoding, ignore_encoding_errors))
LookupError: unknown error handler name ''

# Fixed code
def cli_convert(infile, outfile, silent, verbosity, **options):
    """
    canmatrix.cli.convert [options] import-file export-file

    import-file: *.dbc|*.dbf|*.kcd|*.arxml|*.json|*.xls(x)|*.sym
    export-file: *.dbc|*.dbf|*.kcd|*.arxml|*.json|*.xls(x)|*.sym|*.py

    \n"""

    root_logger = canmatrix.log.setup_logger()

    if silent is True:
        # only print error messages, ignore verbosity flag
        verbosity = -1
        options["silent"] = True

    canmatrix.log.set_log_level(root_logger, verbosity)
    if options["ignoreEncodingErrors"]:
        options["ignoreEncodingErrors"] = "ignore"
    else:
        options["ignoreEncodingErrors"] = "strict"

    canmatrix.convert.convert(infile, outfile, **options)
    return 0
# Buggy code
def _parse_import_alias(cls, leaves):
    assert [leaf.type for leaf in leaves] == [token.NAME] * 3
    assert leaves[1].value == "as"
    return (leaves[0].value, leaves[2].value)


# Traceback (AssertionError)
$ cat import-bug.py
import collections.abc as abc
$ cat import-bug.pyi
import collections.abc as abc
$ pytype --version
2020.10.08
$ merge-pyi import-bug.py import-bug.pyi
Traceback (most recent call last):
File "/Users/shane/pymongo-pycharm-3.8/bin/merge-pyi", line 8, in <module>
sys.exit(main())
File "/Users/shane/pymongo-pycharm-3.8/lib/python3.8/site-packages/pytype/tools/merge_pyi/main.py", line 82, in main
annotated_src = merge_pyi.annotate_string(args, py_src, pyi_src)
File "/Users/shane/pymongo-pycharm-3.8/lib/python3.8/site-packages/pytype/tools/merge_pyi/merge_pyi.py", line 936, in annotate_string
parsed_pyi = Pyi.parse(pyi_src)
File "/Users/shane/pymongo-pycharm-3.8/lib/python3.8/site-packages/pytype/tools/merge_pyi/merge_pyi.py", line 763, in parse
pkg, names = cls.parse_top_import(match_results)
File "/Users/shane/pymongo-pycharm-3.8/lib/python3.8/site-packages/pytype/tools/merge_pyi/merge_pyi.py", line 834, in parse_top_import
pkg_out = cls._parse_import_alias(list(pkg[0].leaves()))
File "/Users/shane/pymongo-pycharm-3.8/lib/python3.8/site-packages/pytype/tools/merge_pyi/merge_pyi.py", line 801, in _parse_import_alias
assert [leaf.type for leaf in leaves] == [token.NAME] * 3
AssertionError

# Fixed code
def _parse_import_alias(cls, leaves):
    assert leaves[-2].value == "as"
    name = "".join(leaf.value for leaf in leaves[:-2])
    return (name, leaves[-1].value)
# Buggy code
def __enter__(self):
    self._start_time = time.clock()


# Traceback (AttributeError)
$  pytype --config ./setup.cfg -V 3.7 ./*.py ./gramhopper ./tests
Computing dependencies
Analyzing 44 sources with 0 local dependencies
ninja: Entering directory `/code/python/gramhopper/.pytype'
[1/44] check gramhopper.gramhopper.responses.response_helper
FAILED: /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi
pytype-single --disable wrong-keyword-args --imports_info /code/python/gramhopper/.pytype/imports/gramhopper.gramhopper.responses.response_helper.imports --module-name gramhopper.gramhopper.responses.response_helper -V 3.7 -o /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi --analyze-annotated --nofail --quick /code/python/gramhopper/gramhopper/responses/response_helper.py
Traceback (most recent call last):
File "/opt/anaconda3/envs/gh_2019_12_03-2/bin/pytype-single", line 8, in <module>
sys.exit(main())
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/main.py", line 86, in main
with metrics.StopWatch("total_time"):
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/metrics.py", line 154, in __enter__
self._start_time = time.clock()
AttributeError: module 'time' has no attribute 'clock'
ninja: build stopped: subcommand failed.

# Fixed code
def __enter__(self):
    self._start_time = get_cpu_clock()
# Buggy code
def __exit__(self, exc_type, exc_value, traceback):
    self._total = time.clock() - self._start_time
    del self._start_time


# Traceback (AttributeError)
$  pytype --config ./setup.cfg -V 3.7 ./*.py ./gramhopper ./tests
Computing dependencies
Analyzing 44 sources with 0 local dependencies
ninja: Entering directory `/code/python/gramhopper/.pytype'
[1/44] check gramhopper.gramhopper.responses.response_helper
FAILED: /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi
pytype-single --disable wrong-keyword-args --imports_info /code/python/gramhopper/.pytype/imports/gramhopper.gramhopper.responses.response_helper.imports --module-name gramhopper.gramhopper.responses.response_helper -V 3.7 -o /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi --analyze-annotated --nofail --quick /code/python/gramhopper/gramhopper/responses/response_helper.py
Traceback (most recent call last):
File "/opt/anaconda3/envs/gh_2019_12_03-2/bin/pytype-single", line 8, in <module>
sys.exit(main())
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/main.py", line 86, in main
with metrics.StopWatch("total_time"):
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/metrics.py", line 154, in __enter__
self._start_time = time.clock()
AttributeError: module 'time' has no attribute 'clock'
ninja: build stopped: subcommand failed.

# Fixed code
def __exit__(self, exc_type, exc_value, traceback):
    self._total = get_cpu_clock() - self._start_time
    del self._start_time
# Buggy code
def __enter__(self):
    if not self._calls:
        self._start_time = time.clock()
    self._calls += 1


# Traceback (AttributeError)
$  pytype --config ./setup.cfg -V 3.7 ./*.py ./gramhopper ./tests
Computing dependencies
Analyzing 44 sources with 0 local dependencies
ninja: Entering directory `/code/python/gramhopper/.pytype'
[1/44] check gramhopper.gramhopper.responses.response_helper
FAILED: /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi
pytype-single --disable wrong-keyword-args --imports_info /code/python/gramhopper/.pytype/imports/gramhopper.gramhopper.responses.response_helper.imports --module-name gramhopper.gramhopper.responses.response_helper -V 3.7 -o /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi --analyze-annotated --nofail --quick /code/python/gramhopper/gramhopper/responses/response_helper.py
Traceback (most recent call last):
File "/opt/anaconda3/envs/gh_2019_12_03-2/bin/pytype-single", line 8, in <module>
sys.exit(main())
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/main.py", line 86, in main
with metrics.StopWatch("total_time"):
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/metrics.py", line 154, in __enter__
self._start_time = time.clock()
AttributeError: module 'time' has no attribute 'clock'
ninja: build stopped: subcommand failed.

# Fixed code
def __enter__(self):
    if not self._calls:
        self._start_time = get_cpu_clock()
    self._calls += 1
# Buggy code
def __exit__(self, exc_type, exc_value, traceback):
    self._calls -= 1
    if not self._calls:
        self._time += time.clock() - self._start_time
        del self._start_time


# Traceback (AttributeError)
$  pytype --config ./setup.cfg -V 3.7 ./*.py ./gramhopper ./tests
Computing dependencies
Analyzing 44 sources with 0 local dependencies
ninja: Entering directory `/code/python/gramhopper/.pytype'
[1/44] check gramhopper.gramhopper.responses.response_helper
FAILED: /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi
pytype-single --disable wrong-keyword-args --imports_info /code/python/gramhopper/.pytype/imports/gramhopper.gramhopper.responses.response_helper.imports --module-name gramhopper.gramhopper.responses.response_helper -V 3.7 -o /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi --analyze-annotated --nofail --quick /code/python/gramhopper/gramhopper/responses/response_helper.py
Traceback (most recent call last):
File "/opt/anaconda3/envs/gh_2019_12_03-2/bin/pytype-single", line 8, in <module>
sys.exit(main())
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/main.py", line 86, in main
with metrics.StopWatch("total_time"):
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/metrics.py", line 154, in __enter__
self._start_time = time.clock()
AttributeError: module 'time' has no attribute 'clock'
ninja: build stopped: subcommand failed.

# Fixed code
def __exit__(self, exc_type, exc_value, traceback):
    self._calls -= 1
    if not self._calls:
        self._time += get_cpu_clock() - self._start_time
        del self._start_time
# Buggy code
def _Visit(node, visitor, *args, **kwargs):
    """Visit the node."""
    name = type(visitor).__name__
    recursive = name in _visiting
    _visiting.add(name)

    start = time.clock()
    try:
        return _VisitNode(node, visitor, *args, **kwargs)
    finally:
        if not recursive:
            _visiting.remove(name)
            elapsed = time.clock() - start
            metrics.get_metric("visit_" + name, metrics.Distribution).add(elapsed)
            if _visiting:
                metrics.get_metric("visit_nested_" + name, metrics.Distribution).add(
                    elapsed
                )


# Traceback (AttributeError)
$  pytype --config ./setup.cfg -V 3.7 ./*.py ./gramhopper ./tests
Computing dependencies
Analyzing 44 sources with 0 local dependencies
ninja: Entering directory `/code/python/gramhopper/.pytype'
[1/44] check gramhopper.gramhopper.responses.response_helper
FAILED: /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi
pytype-single --disable wrong-keyword-args --imports_info /code/python/gramhopper/.pytype/imports/gramhopper.gramhopper.responses.response_helper.imports --module-name gramhopper.gramhopper.responses.response_helper -V 3.7 -o /code/python/gramhopper/.pytype/pyi/gramhopper/gramhopper/responses/response_helper.pyi --analyze-annotated --nofail --quick /code/python/gramhopper/gramhopper/responses/response_helper.py
Traceback (most recent call last):
File "/opt/anaconda3/envs/gh_2019_12_03-2/bin/pytype-single", line 8, in <module>
sys.exit(main())
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/main.py", line 86, in main
with metrics.StopWatch("total_time"):
File "/opt/anaconda3/envs/gh_2019_12_03-2/lib/python3.8/site-packages/pytype/metrics.py", line 154, in __enter__
self._start_time = time.clock()
AttributeError: module 'time' has no attribute 'clock'
ninja: build stopped: subcommand failed.

# Fixed code
def _Visit(node, visitor, *args, **kwargs):
    """Visit the node."""
    name = type(visitor).__name__
    recursive = name in _visiting
    _visiting.add(name)

    start = metrics.get_cpu_clock()
    try:
        return _VisitNode(node, visitor, *args, **kwargs)
    finally:
        if not recursive:
            _visiting.remove(name)
            elapsed = metrics.get_cpu_clock() - start
            metrics.get_metric("visit_" + name, metrics.Distribution).add(elapsed)
            if _visiting:
                metrics.get_metric("visit_nested_" + name, metrics.Distribution).add(
                    elapsed
                )
# Buggy code
def get_type_key(self, seen=None):
    cached_changestamps, saved_key = self._cached_type_key
    if saved_key and cached_changestamps == (
        self.members.changestamp,
        self.instance_type_parameters.changestamp,
    ):
        return saved_key
    if not seen:
        seen = set()
    seen.add(self)
    key = set()
    if self.cls:
        key.add(self.cls)
    for name, var in self.instance_type_parameters.items():
        subkey = frozenset(
            value.data.get_default_type_key()
            if value.data in seen
            else value.data.get_type_key(seen)
            for value in var.bindings
        )
        key.add((name, subkey))
    if key:
        type_key = frozenset(key)
    else:
        type_key = super(SimpleAbstractValue, self).get_type_key()
    self._cached_type_key = (
        (self.members.changestamp, self.instance_type_parameters.changestamp),
        type_key,
    )
    return type_key


# Traceback (AssertionError)
FAIL: pytype.tests.test_dict.DictTest.testPop_py3
Traceback (most recent call last):
File "/root/pytype/out/pytype/tests/test_base.py", line 536, in Replacement
return actual_method(self, *args, **kwargs)
File "/root/pytype/out/pytype/tests/test_dict.py", line 22, in testPop
""")
File "/root/pytype/out/pytype/tests/test_base.py", line 459, in assertTypesMatchPytd
self.assertMultiLineEqual(pytd_tree_src, ty_src)
AssertionError: 'from typing import Dict\n\nd: Dict[str, int]\nv1: int\nv2: None\n' != 'from typing import Any, Dict\n\nd: Dict[str, int]\nv1: Any\nv2: Any\n'
- from typing import Dict
+ from typing import Any, Dict
?                    +++++

d: Dict[str, int]
- v1: int
?     ^ ^
+ v1: Any
?     ^ ^
- v2: None
+ v2: Any

# Fixed code
def get_type_key(self, seen=None):
    cached_changestamps, saved_key = self._cached_type_key
    if saved_key and cached_changestamps == (
        self.members.changestamp,
        self.instance_type_parameters.changestamp,
    ):
        return saved_key
    if not seen:
        seen = set()
    seen.add(self)
    key = set()
    if self.cls:
        key.add(self.cls)
    for name, var in self.instance_type_parameters.items():
        subkey = frozenset(
            value.data.get_default_type_key()  # pylint: disable=g-long-ternary
            if value.data in seen
            else value.data.get_type_key(seen)
            for value in var.bindings
        )
        key.add((name, subkey))
    if key:
        type_key = frozenset(key)
    else:
        type_key = super(SimpleAbstractValue, self).get_type_key()
    self._cached_type_key = (
        (self.members.changestamp, self.instance_type_parameters.changestamp),
        type_key,
    )
    return type_key
# Buggy code
def call(self, node, _, args):
    posargs = args.posargs
    namedargs = self.vm.convert.value_to_constant(args.namedargs, dict)
    if namedargs and self.vm.python_version < (3, 6):
        errmsg = "Keyword syntax for NamedTuple is only supported in Python 3.6+"
        self.vm.errorlog.invalid_namedtuple_arg(self.vm.frames, err_msg=errmsg)
    if namedargs and len(posargs) == 1:
        namedargs = [
            abstract.Tuple(
                (self.vm.convert.build_string(node, k), v), self.vm
            ).to_variable(node)
            for k, v in namedargs.items()
        ]
        namedargs = abstract.List(namedargs, self.vm).to_variable(node)
        posargs += (namedargs,)
        args = function.Args(posargs)
    elif namedargs:
        errmsg = (
            "Either list of fields or keywords can be provided to NamedTuple, not both"
        )
        self.vm.errorlog.invalid_namedtuple_arg(self.vm.frames, err_msg=errmsg)
    return self.namedtuple.call(node, None, args)


# Traceback (AssertionError)
FAIL: pytype.tests.test_dict.DictTest.testPop_py3
Traceback (most recent call last):
File "/root/pytype/out/pytype/tests/test_base.py", line 536, in Replacement
return actual_method(self, *args, **kwargs)
File "/root/pytype/out/pytype/tests/test_dict.py", line 22, in testPop
""")
File "/root/pytype/out/pytype/tests/test_base.py", line 459, in assertTypesMatchPytd
self.assertMultiLineEqual(pytd_tree_src, ty_src)
AssertionError: 'from typing import Dict\n\nd: Dict[str, int]\nv1: int\nv2: None\n' != 'from typing import Any, Dict\n\nd: Dict[str, int]\nv1: Any\nv2: Any\n'
- from typing import Dict
+ from typing import Any, Dict
?                    +++++

d: Dict[str, int]
- v1: int
?     ^ ^
+ v1: Any
?     ^ ^
- v2: None
+ v2: Any

# Fixed code
def call(self, node, _, args):
    posargs = args.posargs
    if isinstance(args.namedargs, dict):
        namedargs = args.namedargs
    else:
        namedargs = self.vm.convert.value_to_constant(args.namedargs, dict)
    if namedargs and self.vm.python_version < (3, 6):
        errmsg = "Keyword syntax for NamedTuple is only supported in Python 3.6+"
        self.vm.errorlog.invalid_namedtuple_arg(self.vm.frames, err_msg=errmsg)
    if namedargs and len(posargs) == 1:
        namedargs = [
            abstract.Tuple(
                (self.vm.convert.build_string(node, k), v), self.vm
            ).to_variable(node)
            for k, v in namedargs.items()
        ]
        namedargs = abstract.List(namedargs, self.vm).to_variable(node)
        posargs += (namedargs,)
        args = function.Args(posargs)
    elif namedargs:
        errmsg = (
            "Either list of fields or keywords can be provided to NamedTuple, not both"
        )
        self.vm.errorlog.invalid_namedtuple_arg(self.vm.frames, err_msg=errmsg)
    return self.namedtuple.call(node, None, args)
# Buggy code
def byte_LOAD_METHOD(self, state, op):
    # We don't support this 3.7 opcode yet; simply don't crash.
    # TODO(rechen): Implement
    # https://docs.python.org/3/library/dis.html#opcode-LOAD_METHOD.
    unused_name = self.frame.f_code.co_names[op.arg]
    state, unused_self_obj = state.pop()
    return state


# Traceback (AssertionError)
FAIL: pytype.tests.test_dict.DictTest.testPop_py3
Traceback (most recent call last):
File "/root/pytype/out/pytype/tests/test_base.py", line 536, in Replacement
return actual_method(self, *args, **kwargs)
File "/root/pytype/out/pytype/tests/test_dict.py", line 22, in testPop
""")
File "/root/pytype/out/pytype/tests/test_base.py", line 459, in assertTypesMatchPytd
self.assertMultiLineEqual(pytd_tree_src, ty_src)
AssertionError: 'from typing import Dict\n\nd: Dict[str, int]\nv1: int\nv2: None\n' != 'from typing import Any, Dict\n\nd: Dict[str, int]\nv1: Any\nv2: Any\n'
- from typing import Dict
+ from typing import Any, Dict
?                    +++++

d: Dict[str, int]
- v1: int
?     ^ ^
+ v1: Any
?     ^ ^
- v2: None
+ v2: Any

# Fixed code
def byte_LOAD_METHOD(self, state, op):
    name = self.frame.f_code.co_names[op.arg]
    state, self_obj = state.pop()
    state, result = self.load_attr(state, self_obj, name)
    # https://docs.python.org/3/library/dis.html#opcode-LOAD_METHOD says that
    # this opcode should push two values onto the stack: either the unbound
    # method and its `self` or NULL and the bound method. However, pushing only
    # the bound method and modifying CALL_METHOD accordingly works in all cases
    # we've tested.
    return state.push(result)
# Buggy code
def byte_CALL_METHOD(self, state, op):
    # We don't support this 3.7 opcode yet; simply don't crash.
    # TODO(rechen): Implement
    # https://docs.python.org/3/library/dis.html#opcode-CALL_METHOD.
    for _ in range(op.arg):
        state = state.pop_and_discard()
    return state.push(self.new_unsolvable(state.node))


# Traceback (AssertionError)
FAIL: pytype.tests.test_dict.DictTest.testPop_py3
Traceback (most recent call last):
File "/root/pytype/out/pytype/tests/test_base.py", line 536, in Replacement
return actual_method(self, *args, **kwargs)
File "/root/pytype/out/pytype/tests/test_dict.py", line 22, in testPop
""")
File "/root/pytype/out/pytype/tests/test_base.py", line 459, in assertTypesMatchPytd
self.assertMultiLineEqual(pytd_tree_src, ty_src)
AssertionError: 'from typing import Dict\n\nd: Dict[str, int]\nv1: int\nv2: None\n' != 'from typing import Any, Dict\n\nd: Dict[str, int]\nv1: Any\nv2: Any\n'
- from typing import Dict
+ from typing import Any, Dict
?                    +++++

d: Dict[str, int]
- v1: int
?     ^ ^
+ v1: Any
?     ^ ^
- v2: None
+ v2: Any

# Fixed code
def byte_CALL_METHOD(self, state, op):
    state, args = state.popn(op.arg)
    state, func = state.pop()
    state, result = self.call_function_with_state(state, func, args)
    return state.push(result)
# Buggy code
def __init__(
    self,
    base_module,
    python_version,
    pythonpath=(),
    imports_map=None,
    use_typeshed=True,
    modules=None,
):
    self._modules = modules or self._base_modules(python_version)
    if self._modules["__builtin__"].needs_unpickling():
        self._unpickle_module(self._modules["__builtin__"])
    if self._modules["typing"].needs_unpickling():
        self._unpickle_module(self._modules["typing"])
    self.builtins = self._modules["__builtin__"].ast
    self.typing = self._modules["typing"].ast
    self.base_module = base_module
    self.python_version = python_version
    self.pythonpath = pythonpath
    self.imports_map = imports_map
    self.use_typeshed = use_typeshed
    self._concatenated = None
    self._import_name_cache = {}  # performance cache
    self._aliases = {}
    # Paranoid verification that pytype.main properly checked the flags:
    if imports_map is not None:
        assert pythonpath == [""], pythonpath


# Traceback (AttributeError)
Command: `PYTHONPATH=.. python3.6 main.py`
Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
y = test2.far.b.B(2)
AttributeError: module 'test2' has no attribute 'far'

# Fixed code
def __init__(
    self,
    base_module,
    python_version,
    pythonpath=(),
    imports_map=None,
    use_typeshed=True,
    modules=None,
):
    self._modules = modules or self._base_modules(python_version)
    if self._modules["__builtin__"].needs_unpickling():
        self._unpickle_module(self._modules["__builtin__"])
    if self._modules["typing"].needs_unpickling():
        self._unpickle_module(self._modules["typing"])
    self.builtins = self._modules["__builtin__"].ast
    self.typing = self._modules["typing"].ast
    self.base_module = base_module
    self.python_version = python_version
    self.pythonpath = pythonpath
    self.imports_map = imports_map
    self.use_typeshed = use_typeshed
    self._concatenated = None
    self._import_name_cache = {}  # performance cache
    self._aliases = {}
    self._prefixes = set()
    # Paranoid verification that pytype.main properly checked the flags:
    if imports_map is not None:
        assert pythonpath == [""], pythonpath
# Buggy code
def _process_module(self, module_name, filename, ast):
    """Create a module from a loaded ast and save it to the loader cache.

    Args:
      module_name: The fully qualified name of the module being imported.
      filename: The file the ast was generated from.
      ast: The pytd.TypeDeclUnit representing the module.

    Returns:
      The ast (pytd.TypeDeclUnit) as represented in this loader.
    """
    module = Module(module_name, filename, ast)
    self._modules[module_name] = module
    try:
        module.ast = self._postprocess_pyi(module.ast)
        # Now that any imported TypeVar instances have been resolved, adjust type
        # parameters in classes and functions.
        module.ast = module.ast.Visit(visitors.AdjustTypeParameters())
        # Now we can fill in internal cls pointers to ClassType nodes in the
        # module. This code executes when the module is first loaded, which
        # happens before any others use it to resolve dependencies, so there are
        # no external pointers into the module at this point.
        module.ast.Visit(
            visitors.FillInLocalPointers({"": module.ast, module_name: module.ast})
        )
    except:
        # don't leave half-resolved modules around
        del self._modules[module_name]
        raise
    return module.ast


# Traceback (AttributeError)
Command: `PYTHONPATH=.. python3.6 main.py`
Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
y = test2.far.b.B(2)
AttributeError: module 'test2' has no attribute 'far'

# Fixed code
def _process_module(self, module_name, filename, ast):
    """Create a module from a loaded ast and save it to the loader cache.

    Args:
      module_name: The fully qualified name of the module being imported.
      filename: The file the ast was generated from.
      ast: The pytd.TypeDeclUnit representing the module.

    Returns:
      The ast (pytd.TypeDeclUnit) as represented in this loader.
    """
    module = Module(module_name, filename, ast)
    self._modules[module_name] = module
    try:
        module.ast = self._postprocess_pyi(module.ast)
        # Now that any imported TypeVar instances have been resolved, adjust type
        # parameters in classes and functions.
        module.ast = module.ast.Visit(visitors.AdjustTypeParameters())
        # Now we can fill in internal cls pointers to ClassType nodes in the
        # module. This code executes when the module is first loaded, which
        # happens before any others use it to resolve dependencies, so there are
        # no external pointers into the module at this point.
        module.ast.Visit(
            visitors.FillInLocalPointers({"": module.ast, module_name: module.ast})
        )
    except:
        # don't leave half-resolved modules around
        del self._modules[module_name]
        raise
    self.add_module_prefixes(module_name)
    return module.ast
# Buggy code
def run_instruction(self, op, state):
    """Run a single bytecode instruction.

    Args:
      op: An opcode, instance of pyc.opcodes.Opcode
      state: An instance of state.FrameState, the state just before running
        this instruction.
    Returns:
      A tuple (why, state). "why" is the reason (if any) that this opcode aborts
      this function (e.g. through a 'raise'), or None otherwise. "state" is the
      FrameState right after this instruction that should roll over to the
      subsequent instruction.
    """
    _opcode_counter.inc(op.name)
    self.frame.current_opcode = op
    if log.isEnabledFor(logging.INFO):
        self.log_opcode(op, state)
    try:
        # dispatch
        bytecode_fn = getattr(self, "byte_%s" % op.name, None)
        if bytecode_fn is None:
            raise VirtualMachineError("Unknown opcode: %s" % op.name)
        state = bytecode_fn(state, op)
    except RecursionException:
        # This is not an error - it just means that the block we're analyzing
        # goes into a recursion, and we're already two levels deep.
        state = state.set_why("recursion")
    if state.why in ("reraise", "NoReturn"):
        state = state.set_why("exception")
    self.frame.current_opcode = None
    return state


# Traceback (AttributeError)
Command: `PYTHONPATH=.. python3.6 main.py`
Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
y = test2.far.b.B(2)
AttributeError: module 'test2' has no attribute 'far'

# Fixed code
def run_instruction(self, op, state):
    """Run a single bytecode instruction.

    Args:
      op: An opcode, instance of pyc.opcodes.Opcode
      state: An instance of state.FrameState, the state just before running
        this instruction.
    Returns:
      A tuple (why, state). "why" is the reason (if any) that this opcode aborts
      this function (e.g. through a 'raise'), or None otherwise. "state" is the
      FrameState right after this instruction that should roll over to the
      subsequent instruction.
    """
    _opcode_counter.inc(op.name)
    self.frame.current_opcode = op
    self._importing = "IMPORT" in op.__class__.__name__
    if log.isEnabledFor(logging.INFO):
        self.log_opcode(op, state)
    try:
        # dispatch
        bytecode_fn = getattr(self, "byte_%s" % op.name, None)
        if bytecode_fn is None:
            raise VirtualMachineError("Unknown opcode: %s" % op.name)
        state = bytecode_fn(state, op)
    except RecursionException:
        # This is not an error - it just means that the block we're analyzing
        # goes into a recursion, and we're already two levels deep.
        state = state.set_why("recursion")
    if state.why in ("reraise", "NoReturn"):
        state = state.set_why("exception")
    self.frame.current_opcode = None
    return state
# Buggy code
def import_module(self, name, full_name, level):
    try:
        module = self._import_module(name, level)
    except (
        parser.ParseError,
        load_pytd.BadDependencyError,
        visitors.ContainerError,
        visitors.SymbolLookupError,
    ) as e:
        self.errorlog.pyi_error(self.frames, full_name, e)
        module = self.convert.unsolvable
    return module


# Traceback (AttributeError)
Command: `PYTHONPATH=.. python3.6 main.py`
Output:
Traceback (most recent call last):
File "main.py", line 3, in <module>
y = test2.far.b.B(2)
AttributeError: module 'test2' has no attribute 'far'

# Fixed code
def import_module(self, name, full_name, level):
    """Import a module and return the module object or None."""
    # Do not import new modules if we aren't in an IMPORT statement.
    # The exception is if we have an implicit "package" module (e.g.
    # `import a.b.c` adds `a.b` to the list of instantiable modules.)
    if not (self._importing or self.loader.has_module_prefix(full_name)):
        return None
    try:
        module = self._import_module(name, level)
        # Since we have explicitly imported full_name, add it to the prefix list.
        self.loader.add_module_prefixes(full_name)
    except (
        parser.ParseError,
        load_pytd.BadDependencyError,
        visitors.ContainerError,
        visitors.SymbolLookupError,
    ) as e:
        self.errorlog.pyi_error(self.frames, full_name, e)
        module = self.convert.unsolvable
    return module
# Buggy code
def check_for_updates():
    """
    Checks if updates are available by reading the cached release number from the
    config file and notifies the user. Prints an update note to the command line.
    """
    from packaging.version import Version
    from maestral import __version__

    state = MaestralState("maestral")
    latest_release = state.get("app", "latest_release")

    has_update = Version(__version__) < Version(latest_release)

    if has_update:
        click.secho(
            f"Maestral v{latest_release} has been released, you have v{__version__}. "
            f"Please use your package manager to update.",
            fg="orange",
        )


# Traceback (KeyError)
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/click/termui.py", line 498, in style
bits.append("\033[{}m".format(_ansi_colors[fg]))
KeyError: 'orange'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/bin/maestral", line 11, in <module>
load_entry_point('maestral==1.0.0.dev5', 'console_scripts', 'maestral')()
File "/usr/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/lib/python3.8/site-packages/click/core.py", line 1256, in invoke
Command.invoke(self, ctx)
File "/usr/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/maestral/cli.py", line 388, in main
check_for_updates()
File "/usr/lib/python3.8/site-packages/maestral/cli.py", line 147, in check_for_updates
click.secho(
File "/usr/lib/python3.8/site-packages/click/termui.py", line 547, in secho
message = style(message, **styles)
File "/usr/lib/python3.8/site-packages/click/termui.py", line 500, in style
raise TypeError("Unknown color '{}'".format(fg))
TypeError: Unknown color 'orange'

# Fixed code
def check_for_updates():
    """
    Checks if updates are available by reading the cached release number from the
    config file and notifies the user. Prints an update note to the command line.
    """
    from packaging.version import Version
    from maestral import __version__

    state = MaestralState("maestral")
    latest_release = state.get("app", "latest_release")

    has_update = Version(__version__) < Version(latest_release)

    if has_update:
        click.echo(
            f"Maestral v{latest_release} has been released, you have v{__version__}. "
            f"Please use your package manager to update."
        )
# Buggy code
def __str__(self):
    return "{0}: {1}".format(self.title, self.message)


# Traceback (maestral.errors.PathError)
dropbox.exceptions.ApiError: ApiError('30f1d5eeaac843c1ff555c04e08561b8', UploadError('path', UploadWriteFailed(reason=WriteError('disallowed_name', None), upload_session_id='AAAAAAAAM9FqZ1pyxzgvlA')))

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/nix/store/jjccwr48ahjxvzg7v6gigacwhsj8k2m4-maestral-gui-0.2.6/lib/python3.7/site-packages/maestral/monitor.py", line 188, in wrapper
res = func(self, *args, **kwargs)
File "/nix/store/jjccwr48ahjxvzg7v6gigacwhsj8k2m4-maestral-gui-0.2.6/lib/python3.7/site-packages/maestral/monitor.py", line 710, in _apply_event
self._on_created(evnt)
File "/nix/store/jjccwr48ahjxvzg7v6gigacwhsj8k2m4-maestral-gui-0.2.6/lib/python3.7/site-packages/maestral/monitor.py", line 812, in _on_created
md = self.client.upload(path, dbx_path, autorename=True, mode=mode)
File "/nix/store/jjccwr48ahjxvzg7v6gigacwhsj8k2m4-maestral-gui-0.2.6/lib/python3.7/site-packages/maestral/client.py", line 282, in upload
raise to_maestral_error(exc, dbx_path) from exc
maestral.errors.PathError: Could not upload file: Dropbox will not save the file or folder because of its name.
2019-08-13 21:50:09 maestral.monitor ERROR: Sync error
Traceback (most recent call last):
File "/nix/store/jjccwr48ahjxvzg7v6gigacwhsj8k2m4-maestral-gui-0.2.6/lib/python3.7/site-packages/maestral/client.py", line 257, in upload
f.read(), dbx_path, client_modified=mtime_dt, **kwargs)
File "/nix/store/5ajzqlpk5l37lc4x2q4sb5hkszvf9kir-python3.7-dropbox-9.4.0/lib/python3.7/site-packages/dropbox/base.py", line 2458, in files_upload
f,
File "/nix/store/5ajzqlpk5l37lc4x2q4sb5hkszvf9kir-python3.7-dropbox-9.4.0/lib/python3.7/site-packages/dropbox/dropbox.py", line 296, in request
user_message_locale)
dropbox.exceptions.ApiError: ApiError('0c98289b3e80e3259fe670566c2d7f98', UploadError('path', UploadWriteFailed(reason=WriteError('disallowed_name', None), upload_session_id='AAAAAAAAM9IdJt1oBQwYjg')))

# Fixed code
def __str__(self):
    return "'{0}': {1}. {2}".format(self.dbx_path, self.title, self.message)
# Buggy code
def bulk_history_create(self, objs, batch_size=None):
    """Bulk create the history for the objects specified by objs"""

    historical_instances = [
        self.model(
            history_date=getattr(instance, "_history_date", now()),
            history_user=getattr(instance, "_history_user", None),
            **{
                field.attname: getattr(instance, field.attname)
                for field in instance._meta.fields
            },
        )
        for instance in objs
    ]

    return self.model.objects.bulk_create(historical_instances, batch_size=batch_size)


# Traceback (TypeError)
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/srv/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/srv/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/srv/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/srv/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/srv/venv/local/lib/python2.7/site-packages/simple_history/management/commands/populate_history.py", line 65, in handle
self._process(to_process, batch_size=options['batchsize'])
File "/srv/venv/local/lib/python2.7/site-packages/simple_history/management/commands/populate_history.py", line 110, in _process
utils.bulk_history_create(model, history_model, batch_size)
File "/srv/venv/local/lib/python2.7/site-packages/simple_history/management/commands/_populate_utils.py", line 28, in bulk_history_create
) for instance in model.objects.all()]
File "/srv/venv/local/lib/python2.7/site-packages/django/db/models/base.py", line 572, in __init__
raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0])
TypeError: 'description' is an invalid keyword argument for this function

# Fixed code
def bulk_history_create(self, objs, batch_size=None):
    """Bulk create the history for the objects specified by objs"""

    historical_instances = [
        self.model(
            history_date=getattr(instance, "_history_date", now()),
            history_user=getattr(instance, "_history_user", None),
            **{
                field.attname: getattr(instance, field.attname)
                for field in instance._meta.fields
                if field.name not in self.model._history_excluded_fields
            },
        )
        for instance in objs
    ]

    return self.model.objects.bulk_create(historical_instances, batch_size=batch_size)