gurudesh/pytracebugs huggingface dataset:
# Buggy code
def load(self, executable):
    """
    Initialize a QAM into a fresh state.

    :param executable: Load a compiled executable onto the QAM.
    """
    assert self.status in ["connected", "done"]

    self._variables_shim = {}
    self._executable = executable
    self._bitstrings = None
    self.status = "loaded"
    return self


# Traceback (KeyError)
Traceback (most recent call last):
File "tmp.py", line 13, in <module>
print(qvm.run(p))
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_error_reporting.py", line 234, in wrapper
val = func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_quantum_computer.py", line 123, in run
return self.qam.load(executable) \
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_error_reporting.py", line 234, in wrapper
val = func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_qvm.py", line 445, in run
random_seed=self.random_seed)['ro']
KeyError: 'ro'

# Fixed code
def load(self, executable):
    """
    Initialize a QAM into a fresh state.

    :param executable: Load a compiled executable onto the QAM.
    """
    if self.status == "loaded":
        warnings.warn("Overwriting previously loaded executable.")
    assert self.status in ["connected", "done", "loaded"]

    self._variables_shim = {}
    self._executable = executable
    self._bitstrings = None
    self.status = "loaded"
    return self
# Buggy code
def run(self):
    """
    Run a pyquil program on the QPU.

    This formats the classified data from the QPU server by stacking measured bits into
    an array of shape (trials, classical_addresses). The mapping of qubit to
    classical address is backed out from MEASURE instructions in the program, so
    only do measurements where there is a 1-to-1 mapping between qubits and classical
    addresses.

    :return: The QPU object itself.
    """
    super().run()

    request = QPURequest(
        program=self._executable.program,
        patch_values=self._build_patch_values(),
        id=str(uuid.uuid4()),
    )

    job_id = self.client.call("execute_qpu_request", request=request, user=self.user)
    results = self._get_buffers(job_id)
    ro_sources = self._executable.ro_sources

    if results:
        bitstrings = _extract_bitstrings(ro_sources, results)
    else:
        bitstrings = None

    self._bitstrings = bitstrings
    self._last_results = results
    return self


# Traceback (KeyError)
Traceback (most recent call last):
File "tmp.py", line 13, in <module>
print(qvm.run(p))
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_error_reporting.py", line 234, in wrapper
val = func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_quantum_computer.py", line 123, in run
return self.qam.load(executable) \
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_error_reporting.py", line 234, in wrapper
val = func(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/pyquil/api/_qvm.py", line 445, in run
random_seed=self.random_seed)['ro']
KeyError: 'ro'

# Fixed code
def run(self):
    """
    Run a pyquil program on the QPU.

    This formats the classified data from the QPU server by stacking measured bits into
    an array of shape (trials, classical_addresses). The mapping of qubit to
    classical address is backed out from MEASURE instructions in the program, so
    only do measurements where there is a 1-to-1 mapping between qubits and classical
    addresses.

    :return: The QPU object itself.
    """
    super().run()

    request = QPURequest(
        program=self._executable.program,
        patch_values=self._build_patch_values(),
        id=str(uuid.uuid4()),
    )

    job_id = self.client.call("execute_qpu_request", request=request, user=self.user)
    results = self._get_buffers(job_id)
    ro_sources = self._executable.ro_sources

    if results:
        bitstrings = _extract_bitstrings(ro_sources, results)
    elif not ro_sources:
        warnings.warn(
            "You are running a QPU program with no MEASURE instructions. "
            "The result of this program will always be an empty array. Are "
            "you sure you didn't mean to measure some of your qubits?"
        )
        bitstrings = np.zeros((0, 0), dtype=np.int64)
    else:
        bitstrings = None

    self._bitstrings = bitstrings
    self._last_results = results
    return self
# Buggy code
def out(self):
    """
    Prints a readable Quil string representation of this gate.

    :returns: String representation of a gate
    :rtype: string
    """

    def format_matrix_element(element):
        """
        Formats a parameterized matrix element.

        :param element: {int, float, complex, str} The parameterized element to format.
        """
        if isinstance(element, integer_types) or isinstance(element, (float, complex)):
            return format_parameter(element)
        elif isinstance(element, string_types):
            return element
        else:
            raise TypeError("Invalid matrix element: %r" % element)

    result = "DEFGATE %s:\n" % self.name
    for row in self.matrix:
        result += "    "
        fcols = [format_matrix_element(col) for col in row]
        result += ", ".join(fcols)
        result += "\n"
    return result


# Traceback (AssertionError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 208, in out
fcols = [format_matrix_element(col) for col in row]
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 208, in <listcomp>
fcols = [format_matrix_element(col) for col in row]
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 68, in format_matrix_element
assert False, "Invalid matrix element: %r" % element
AssertionError: Invalid matrix element: 1

# Fixed code
def out(self):
    """
    Prints a readable Quil string representation of this gate.

    :returns: String representation of a gate
    :rtype: string
    """

    def format_matrix_element(element):
        """
        Formats a parameterized matrix element.

        :param element: {int, float, complex, str} The parameterized element to format.
        """
        if isinstance(element, integer_types) or isinstance(
            element, (float, complex, np.int_)
        ):
            return format_parameter(element)
        elif isinstance(element, string_types):
            return element
        else:
            raise TypeError("Invalid matrix element: %r" % element)

    result = "DEFGATE %s:\n" % self.name
    for row in self.matrix:
        result += "    "
        fcols = [format_matrix_element(col) for col in row]
        result += ", ".join(fcols)
        result += "\n"
    return result
# Buggy code
def format_matrix_element(element):
    """
    Formats a parameterized matrix element.

    :param element: {int, float, complex, str} The parameterized element to format.
    """
    if isinstance(element, integer_types) or isinstance(element, (float, complex)):
        return format_parameter(element)
    elif isinstance(element, string_types):
        return element
    else:
        raise TypeError("Invalid matrix element: %r" % element)


# Traceback (AssertionError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 208, in out
fcols = [format_matrix_element(col) for col in row]
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 208, in <listcomp>
fcols = [format_matrix_element(col) for col in row]
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 68, in format_matrix_element
assert False, "Invalid matrix element: %r" % element
AssertionError: Invalid matrix element: 1

# Fixed code
def format_matrix_element(element):
    """
    Formats a parameterized matrix element.

    :param element: {int, float, complex, str} The parameterized element to format.
    """
    if isinstance(element, integer_types) or isinstance(
        element, (float, complex, np.int_)
    ):
        return format_parameter(element)
    elif isinstance(element, string_types):
        return element
    else:
        raise TypeError("Invalid matrix element: %r" % element)
# Buggy code
def format_parameter(element):
    """
    Formats a particular parameter. Essentially the same as built-in formatting except using 'i' instead of 'j' for
    the imaginary number.

    :param element: {int, float, long, complex, Slot} Formats a parameter for Quil output.
    """
    if isinstance(element, integer_types):
        return repr(element)
    elif isinstance(element, float):
        return check_for_pi(element)
    elif isinstance(element, complex):
        r = element.real
        i = element.imag
        if i < 0:
            return repr(r) + "-" + repr(abs(i)) + "i"
        else:
            return repr(r) + "+" + repr(i) + "i"
    elif isinstance(element, Slot):
        return format_parameter(element.value())
    assert False, "Invalid parameter: %r" % element


# Traceback (AssertionError)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 208, in out
fcols = [format_matrix_element(col) for col in row]
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 208, in <listcomp>
fcols = [format_matrix_element(col) for col in row]
File "/Users/steven/workspace/pyquil/pyquil/quilbase.py", line 68, in format_matrix_element
assert False, "Invalid matrix element: %r" % element
AssertionError: Invalid matrix element: 1

# Fixed code
def format_parameter(element):
    """
    Formats a particular parameter. Essentially the same as built-in formatting except using 'i' instead of 'j' for
    the imaginary number.

    :param element: {int, float, long, complex, Slot} Formats a parameter for Quil output.
    """
    if isinstance(element, integer_types) or isinstance(element, np.int_):
        return repr(element)
    elif isinstance(element, float):
        return check_for_pi(element)
    elif isinstance(element, complex):
        r = element.real
        i = element.imag
        if i < 0:
            return repr(r) + "-" + repr(abs(i)) + "i"
        else:
            return repr(r) + "+" + repr(i) + "i"
    elif isinstance(element, Slot):
        return format_parameter(element.value())
    assert False, "Invalid parameter: %r" % element
# Buggy code
def decode(self):
    """
    Decodes the result of the job.
    :return: Depends on the type of job. A JSON object.
    """
    return json.loads(self.result["result"])


# Traceback (TypeError)
from pyquil.quil import Program
from pyquil.gates import *
import pyquil.api as api

cxn = api.JobConnection(endpoint="https://job.rigetti.com/beta")
res = cxn.run(Program(X(0)).measure(0, 0), [0])

# wait a bit
res.get()
res.decode()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-623312af8776> in <module>()
----> 1 res.decode()

/Users/willzeng/code/pyquil/pyquil/job_results.pyc in decode(self)
73         :return: Depends on the type of job. A JSON object.
74         """
---> 75         return json.loads(self.result['result'])
76
77     def __str__(self):

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
336             parse_int is None and parse_float is None and
337             parse_constant is None and object_pairs_hook is None and not kw):
--> 338         return _default_decoder.decode(s)
339     if cls is None:
340         cls = JSONDecoder

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
364
365         """
--> 366         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
367         end = _w(s, end).end()
368         if end != len(s):

TypeError: expected string or buffer

# Fixed code
def decode(self):
    """
    Decodes the result of the job.
    :return: Depends on the type of job. A JSON object.
    """
    return self.result["result"]
# Buggy code
def add_armory_library(sdk_path, name, rel_path=False):
    if rel_path:
        sdk_path = "../" + os.path.relpath(sdk_path, arm.utils.get_fp()).replace(
            "\\", "/"
        )
    return (
        ('project.addLibrary("' + sdk_path + "/" + name + '");\n')
        .replace("\\", "/")
        .replace("//", "/")
    )


# Traceback (FileNotFoundError)
location: <unknown location>:-1
Error: Traceback (most recent call last):
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\props_ui.py", line 457, in execute
make.play()
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 462, in play
build(target=runtime_to_target(), is_play=True)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 346, in build
export_data(fp, sdk_path)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 155, in export_data
write_data.write_compiledglsl(defs + cdefs, make_variants=has_config)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\write_data.py", line 440, in write_compiledglsl
with open(arm.utils.build_dir() + '/compiled/Shaders/compiled.inc', 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'build_0untitled/compiled/Shaders/compiled.inc'

location: <unknown location>:-1

# Fixed code
def add_armory_library(sdk_path: str, name: str, rel_path=False) -> str:
    if rel_path:
        sdk_path = "../" + os.path.relpath(sdk_path, arm.utils.get_fp()).replace(
            "\\", "/"
        )

    return (
        ('project.addLibrary("' + sdk_path + "/" + name + '");\n')
        .replace("\\", "/")
        .replace("//", "/")
    )
# Buggy code
def add_assets(path, quality=1.0, use_data_dir=False, rel_path=False):
    if not bpy.data.worlds["Arm"].arm_minimize and path.endswith(".arm"):
        path = path[:-4] + ".json"

    if rel_path:
        path = os.path.relpath(path, arm.utils.get_fp()).replace("\\", "/")

    notinlist = not path.endswith(".ttf")  # TODO
    s = 'project.addAssets("' + path + '", { notinlist: ' + str(notinlist).lower() + " "
    if quality < 1.0:
        s += ", quality: " + str(quality)
    if use_data_dir:
        s += ', destination: "data/{name}"'
    s += "});\n"
    return s


# Traceback (FileNotFoundError)
location: <unknown location>:-1
Error: Traceback (most recent call last):
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\props_ui.py", line 457, in execute
make.play()
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 462, in play
build(target=runtime_to_target(), is_play=True)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 346, in build
export_data(fp, sdk_path)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 155, in export_data
write_data.write_compiledglsl(defs + cdefs, make_variants=has_config)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\write_data.py", line 440, in write_compiledglsl
with open(arm.utils.build_dir() + '/compiled/Shaders/compiled.inc', 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'build_0untitled/compiled/Shaders/compiled.inc'

location: <unknown location>:-1

# Fixed code
def add_assets(path: str, quality=1.0, use_data_dir=False, rel_path=False) -> str:
    if not bpy.data.worlds["Arm"].arm_minimize and path.endswith(".arm"):
        path = path[:-4] + ".json"

    if rel_path:
        path = os.path.relpath(path, arm.utils.get_fp()).replace("\\", "/")

    notinlist = not path.endswith(".ttf")  # TODO
    s = 'project.addAssets("' + path + '", { notinlist: ' + str(notinlist).lower() + " "
    if quality < 1.0:
        s += ", quality: " + str(quality)
    if use_data_dir:
        s += ', destination: "data/{name}"'
    s += "});\n"
    return s
# Buggy code
def add_shaders(path, rel_path=False):
    if rel_path:
        path = os.path.relpath(path, arm.utils.get_fp())
    return 'project.addShaders("' + path.replace("\\", "/").replace("//", "/") + '");\n'


# Traceback (FileNotFoundError)
location: <unknown location>:-1
Error: Traceback (most recent call last):
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\props_ui.py", line 457, in execute
make.play()
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 462, in play
build(target=runtime_to_target(), is_play=True)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 346, in build
export_data(fp, sdk_path)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\make.py", line 155, in export_data
write_data.write_compiledglsl(defs + cdefs, make_variants=has_config)
File "C:\Users\nobody\Documents\ArmorySDK//armory/blender\arm\write_data.py", line 440, in write_compiledglsl
with open(arm.utils.build_dir() + '/compiled/Shaders/compiled.inc', 'w') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'build_0untitled/compiled/Shaders/compiled.inc'

location: <unknown location>:-1

# Fixed code
def add_shaders(path: str, rel_path=False) -> str:
    if rel_path:
        path = os.path.relpath(path, arm.utils.get_fp())
    return 'project.addShaders("' + path.replace("\\", "/").replace("//", "/") + '");\n'
# Buggy code
def _filter_missing(repo, paths):
    repo_tree = RepoTree(repo, stream=True)
    for path in paths:
        metadata = repo_tree.metadata(path)
        if metadata.is_dvc:
            out = metadata.outs[0]
            if out.status().get(str(out)) == "not in cache":
                yield path


# Traceback (FileNotFoundError)
$ git status                                                                                                                  ⏎
On branch master
Changes not staged for commit:
deleted:    .gitignore
deleted:    foo.txt.dvc

no changes added to commit

$ dvc diff -v
2020-12-28 15:43:46,270 DEBUG: Check for update is enabled.
2020-12-28 15:43:46,584 ERROR: unexpected error
------------------------------------------------------------
Traceback (most recent call last):
File "/Users/pmrowla/git/dvc/dvc/main.py", line 90, in main
ret = cmd.run()
File "/Users/pmrowla/git/dvc/dvc/command/diff.py", line 131, in run
diff = self.repo.diff(
File "/Users/pmrowla/git/dvc/dvc/repo/__init__.py", line 53, in wrapper
return f(repo, *args, **kwargs)
File "/Users/pmrowla/git/dvc/dvc/repo/diff.py", line 60, in diff
missing = sorted(_filter_missing(self, deleted_or_missing))
File "/Users/pmrowla/git/dvc/dvc/repo/diff.py", line 151, in _filter_missing
metadata = repo_tree.metadata(path)
File "/Users/pmrowla/git/dvc/dvc/tree/repo.py", line 446, in metadata
raise FileNotFoundError
FileNotFoundError
------------------------------------------------------------

# Fixed code
def _filter_missing(repo, paths):
    repo_tree = RepoTree(repo, stream=True)
    for path in paths:
        try:
            metadata = repo_tree.metadata(path)
            if metadata.is_dvc:
                out = metadata.outs[0]
                if out.status().get(str(out)) == "not in cache":
                    yield path
        except FileNotFoundError:
            pass
# Buggy code
def __init__(self, iterator):  # pylint: disable=super-init-not-called
    self.iterator = iterator
    self.leftover = None


# Traceback (RuntimeError)
with dvc.api.open("model.save", mode="rb") as f:
...:     x = joblib.load(f)
...:
---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-36-5d9cb3fe0cb1> in <module>
1 with dvc.api.open("model.save", mode="rb") as f:
----> 2     x = joblib.load(f)
3

~/repos/iterative/dvc/.env/env38/lib/python3.8/site-packages/joblib/numpy_pickle.py in load(filename, mmap_mode)
572         fobj = filename
573         filename = getattr(fobj, 'name', '')
--> 574         with _read_fileobject(fobj, filename, mmap_mode) as fobj:
575             obj = _unpickle(fobj)
576     else:

/usr/lib/python3.8/contextlib.py in __enter__(self)
111         del self.args, self.kwds, self.func
112         try:
--> 113             return next(self.gen)
114         except StopIteration:
115             raise RuntimeError("generator didn't yield") from None

~/repos/iterative/dvc/.env/env38/lib/python3.8/site-packages/joblib/numpy_pickle_utils.py in _read_fileobject(fileobj, filename, mmap_mode)
122     """
123     # Detect if the fileobj contains compressed data.
--> 124     compressor = _detect_compressor(fileobj)
125
126     if compressor == "compat":

~/repos/iterative/dvc/.env/env38/lib/python3.8/site-packages/joblib/numpy_pickle_utils.py in _detect_compressor(fileobj)
71         # Fallback to seek if the fileobject is not peekable.
72         first_bytes = fileobj.read(max_prefix_len)
---> 73         fileobj.seek(0)
74
75     if first_bytes.startswith(_ZFILE_PREFIX):

UnsupportedOperation: seek

# Fixed code
def __init__(self, iterator):  # pylint: disable=super-init-not-called
    self.iterator = iterator
    self.leftover = b""
# Buggy code
def read1(self, n=-1):
    try:
        chunk = self.leftover or next(self.iterator)
    except StopIteration:
        return b""

    # Return an arbitrary number or bytes
    if n <= 0:
        self.leftover = None
        return chunk

    output, self.leftover = chunk[:n], chunk[n:]
    return output


# Traceback (RuntimeError)
with dvc.api.open("model.save", mode="rb") as f:
...:     x = joblib.load(f)
...:
---------------------------------------------------------------------------
UnsupportedOperation                      Traceback (most recent call last)
<ipython-input-36-5d9cb3fe0cb1> in <module>
1 with dvc.api.open("model.save", mode="rb") as f:
----> 2     x = joblib.load(f)
3

~/repos/iterative/dvc/.env/env38/lib/python3.8/site-packages/joblib/numpy_pickle.py in load(filename, mmap_mode)
572         fobj = filename
573         filename = getattr(fobj, 'name', '')
--> 574         with _read_fileobject(fobj, filename, mmap_mode) as fobj:
575             obj = _unpickle(fobj)
576     else:

/usr/lib/python3.8/contextlib.py in __enter__(self)
111         del self.args, self.kwds, self.func
112         try:
--> 113             return next(self.gen)
114         except StopIteration:
115             raise RuntimeError("generator didn't yield") from None

~/repos/iterative/dvc/.env/env38/lib/python3.8/site-packages/joblib/numpy_pickle_utils.py in _read_fileobject(fileobj, filename, mmap_mode)
122     """
123     # Detect if the fileobj contains compressed data.
--> 124     compressor = _detect_compressor(fileobj)
125
126     if compressor == "compat":

~/repos/iterative/dvc/.env/env38/lib/python3.8/site-packages/joblib/numpy_pickle_utils.py in _detect_compressor(fileobj)
71         # Fallback to seek if the fileobject is not peekable.
72         first_bytes = fileobj.read(max_prefix_len)
---> 73         fileobj.seek(0)
74
75     if first_bytes.startswith(_ZFILE_PREFIX):

UnsupportedOperation: seek

# Fixed code
def read1(self, n=-1):
    try:
        chunk = self.leftover or next(self.iterator)
    except StopIteration:
        return b""

    # Return an arbitrary number or bytes
    if n <= 0:
        self.leftover = b""
        return chunk

    output, self.leftover = chunk[:n], chunk[n:]
    return output
# Buggy code
def commit(
    cls,
    scm: "Git",
    exp_hash: str,
    exp_name: Optional[str] = None,
    force: bool = False,
    checkpoint: bool = False,
):
    """Commit stages as an experiment and return the commit SHA."""
    rev = scm.get_rev()
    if not scm.is_dirty(untracked_files=True):
        logger.debug("No changes to commit")
        raise UnchangedExperimentError(rev)

    branch = scm.get_ref(EXEC_BRANCH, follow=False)
    if branch:
        old_ref = rev
        logger.debug("Commit to current experiment branch '%s'", branch)
    else:
        baseline_rev = scm.get_ref(EXEC_BASELINE)
        name = exp_name if exp_name else f"exp-{exp_hash[:5]}"
        ref_info = ExpRefInfo(baseline_rev, name)
        branch = str(ref_info)
        old_ref = None
        if not force and scm.get_ref(branch):
            if checkpoint:
                raise CheckpointExistsError(ref_info.name)
            raise ExperimentExistsError(ref_info.name)
        logger.debug("Commit to new experiment branch '%s'", branch)

    scm.gitpython.repo.git.add(update=True)
    scm.commit(f"dvc: commit experiment {exp_hash}")
    new_rev = scm.get_rev()
    scm.set_ref(branch, new_rev, old_ref=old_ref)
    scm.set_ref(EXEC_BRANCH, branch, symbolic=True)
    if checkpoint:
        scm.set_ref(EXEC_CHECKPOINT, new_rev)
    return new_rev


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib64/python3.7/concurrent/futures/process.py", line 205, in _sendback_result
exception=exception))
File "/usr/lib64/python3.7/multiprocessing/queues.py", line 358, in put
obj = _ForkingPickler.dumps(obj)
File "/usr/lib64/python3.7/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'CommitMsgShellHook.__init__.<locals>.prepare_msg'

# Fixed code
def commit(
    cls,
    scm: "Git",
    exp_hash: str,
    exp_name: Optional[str] = None,
    force: bool = False,
    checkpoint: bool = False,
):
    """Commit stages as an experiment and return the commit SHA."""
    rev = scm.get_rev()
    if not scm.is_dirty(untracked_files=True):
        logger.debug("No changes to commit")
        raise UnchangedExperimentError(rev)

    branch = scm.get_ref(EXEC_BRANCH, follow=False)
    if branch:
        old_ref = rev
        logger.debug("Commit to current experiment branch '%s'", branch)
    else:
        baseline_rev = scm.get_ref(EXEC_BASELINE)
        name = exp_name if exp_name else f"exp-{exp_hash[:5]}"
        ref_info = ExpRefInfo(baseline_rev, name)
        branch = str(ref_info)
        old_ref = None
        if not force and scm.get_ref(branch):
            if checkpoint:
                raise CheckpointExistsError(ref_info.name)
            raise ExperimentExistsError(ref_info.name)
        logger.debug("Commit to new experiment branch '%s'", branch)

    scm.gitpython.repo.git.add(update=True)
    scm.commit(f"dvc: commit experiment {exp_hash}", no_verify=True)
    new_rev = scm.get_rev()
    scm.set_ref(branch, new_rev, old_ref=old_ref)
    scm.set_ref(EXEC_BRANCH, branch, symbolic=True)
    if checkpoint:
        scm.set_ref(EXEC_CHECKPOINT, new_rev)
    return new_rev
# Buggy code
def commit(self, msg: str):
    pass


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib64/python3.7/concurrent/futures/process.py", line 205, in _sendback_result
exception=exception))
File "/usr/lib64/python3.7/multiprocessing/queues.py", line 358, in put
obj = _ForkingPickler.dumps(obj)
File "/usr/lib64/python3.7/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'CommitMsgShellHook.__init__.<locals>.prepare_msg'

# Fixed code
def commit(self, msg: str, no_verify: bool = False):
    pass
# Buggy code
def commit(self, msg: str):
    from dulwich.porcelain import commit

    commit(self.root_dir, message=msg)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib64/python3.7/concurrent/futures/process.py", line 205, in _sendback_result
exception=exception))
File "/usr/lib64/python3.7/multiprocessing/queues.py", line 358, in put
obj = _ForkingPickler.dumps(obj)
File "/usr/lib64/python3.7/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'CommitMsgShellHook.__init__.<locals>.prepare_msg'

# Fixed code
def commit(self, msg: str, no_verify: bool = False):
    from dulwich.errors import CommitError
    from dulwich.porcelain import commit

    try:
        commit(self.root_dir, message=msg, no_verify=no_verify)
    except CommitError as exc:
        raise SCMError("Git commit failed") from exc
# Buggy code
def commit(self, msg: str):
    self.repo.index.commit(msg)


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib64/python3.7/concurrent/futures/process.py", line 205, in _sendback_result
exception=exception))
File "/usr/lib64/python3.7/multiprocessing/queues.py", line 358, in put
obj = _ForkingPickler.dumps(obj)
File "/usr/lib64/python3.7/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'CommitMsgShellHook.__init__.<locals>.prepare_msg'

# Fixed code
def commit(self, msg: str, no_verify: bool = False):
    from git.exc import HookExecutionError

    try:
        self.repo.index.commit(msg, skip_hooks=no_verify)
    except HookExecutionError as exc:
        raise SCMError("Git pre-commit hook failed") from exc
# Buggy code
def commit(self, msg: str):
    raise NotImplementedError


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/lib64/python3.7/concurrent/futures/process.py", line 205, in _sendback_result
exception=exception))
File "/usr/lib64/python3.7/multiprocessing/queues.py", line 358, in put
obj = _ForkingPickler.dumps(obj)
File "/usr/lib64/python3.7/multiprocessing/reduction.py", line 51, in dumps
cls(buf, protocol).dump(obj)
AttributeError: Can't pickle local object 'CommitMsgShellHook.__init__.<locals>.prepare_msg'

# Fixed code
def commit(self, msg: str, no_verify: bool = False):
    raise NotImplementedError
# Buggy code
def ignore(self, path):
    entry, gitignore = self._get_gitignore(path)

    if self._ignored(path):
        return

    msg = "Adding '{}' to '{}'.".format(relpath(path), relpath(gitignore))
    logger.debug(msg)

    self._add_entry_to_gitignore(entry, gitignore)

    self.track_file(relpath(gitignore))

    self.ignored_paths.append(path)


# Traceback (FileNotFoundError)
Traceback (most recent call last):
File "dvc\main.py", line 49, in main
File "dvc\command\init.py", line 21, in run
File "dvc\repo__init.py", line 155, in init
File "dvc\repo\init.py", line 108, in init
File "dvc\scm\git__init.py", line 194, in add
File "site-packages\git\index\base.py", line 740, in add
File "site-packages\git\util.py", line 68, in wrapper
File "site-packages\git\index\util.py", line 91, in set_git_working_dir
File "site-packages\git\index\base.py", line 626, in _entries_for_paths
File "site-packages\git\index\base.py", line 587, in _store_path
FileNotFoundError: [WinError 2] Das System kann die angegebene Datei nicht finden: '.dvc\.gitignore'

# Fixed code
def ignore(self, path):
    entry, gitignore = self._get_gitignore(path)

    if self.is_ignored(path):
        return

    msg = "Adding '{}' to '{}'.".format(relpath(path), relpath(gitignore))
    logger.debug(msg)

    self._add_entry_to_gitignore(entry, gitignore)

    self.track_file(relpath(gitignore))

    self.ignored_paths.append(path)
# Buggy code
def _filter_missing(repo, paths):
    repo_tree = RepoTree(repo, stream=True)
    for path in paths:
        metadata = repo_tree.metadata(path)
        if metadata.is_dvc:
            out = metadata.outs[0]
            if out.status()[str(out)] == "not in cache":
                yield path


# Traceback (KeyError)
Traceback (most recent call last):
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/main.py", line 76, in main
ret = cmd.run()
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/command/diff.py", line 130, in run
diff = self.repo.diff(self.args.a_rev, self.args.b_rev)
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/repo/__init__.py", line 54, in wrapper
return f(repo, *args, **kwargs)
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/repo/diff.py", line 43, in diff
missing = sorted(_filter_missing(self, deleted_or_missing))
File "/home/ubuntu/.local/share/virtualenvs/speech-api-EI_ft4iY/lib/python3.7/site-packages/dvc/repo/diff.py", line 125, in _filter_missing
if out.status()[str(out)] == "not in cache":
KeyError: 'data/KPI/KPI_from_dvc/en/post_probs'

# Fixed code
def _filter_missing(repo, paths):
    repo_tree = RepoTree(repo, stream=True)
    for path in paths:
        metadata = repo_tree.metadata(path)
        if metadata.is_dvc:
            out = metadata.outs[0]
            if out.status().get(str(out)) == "not in cache":
                yield path
# Buggy code
def _update(dict_, other):
    for key, value in other.items():
        if isinstance(value, Mapping):
            dict_[key] = _update(dict_.get(key, {}), value)
        else:
            dict_[key] = value
    return dict_


# Traceback (AttributeError)
2020-10-21 16:59:00,192 ERROR: unexpected error - 'CommentedSeq' object has no attribute 'get'
------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/dvc/main.py", line 76, in main
ret = cmd.run()
File "/usr/local/lib/python3.8/dist-packages/dvc/command/experiments.py", line 419, in run
self.repo.experiments.run(
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 801, in run
return run(self.repo, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/__init__.py", line 51, in wrapper
return f(repo, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/run.py", line 62, in run
return repo.experiments.reproduce_one(
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 345, in reproduce_one
stash_rev = self.new(**kwargs)
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 38, in wrapper
return f(exp, *args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 407, in new
stash_rev = self._stash_exp(
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 265, in _stash_exp
self._update_params(params)
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 309, in _update_params
_update(data, params[params_fname])
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 299, in _update
dict_[key] = _update(dict_.get(key, {}), value)
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 299, in _update
dict_[key] = _update(dict_.get(key, {}), value)
File "/usr/local/lib/python3.8/dist-packages/dvc/repo/experiments/__init__.py", line 299, in _update
dict_[key] = _update(dict_.get(key, {}), value)
[Previous line repeated 1 more time]
AttributeError: 'CommentedSeq' object has no attribute 'get'
------------------------------------------------------------
2020-10-21 16:59:00,284 DEBUG: Version info for developers:
DVC version: 1.8.4 (pip)
---------------------------------
Platform: Python 3.8.0 on Linux-5.4.0-51-generic-x86_64-with-glibc2.27
Supports: http, https, s3
Cache types: hardlink, symlink
Repo: dvc, git

# Fixed code
def _update(dict_, other):
    for key, value in other.items():
        if isinstance(dict_, list) and key.isdigit():
            key = int(key)
        if isinstance(value, Mapping):
            if isinstance(dict_, list):
                fallback_value = dict_[key]
            else:
                fallback_value = dict_.get(key, {})
            dict_[key] = _update(fallback_value, value)
        else:
            dict_[key] = value
    return dict_
# Buggy code
def open(self, path, mode="r", encoding="utf-8", **kwargs):  # pylint: disable=arguments-differ
    if "b" in mode:
        encoding = None

    tree, dvc_tree = self._get_tree_pair(path)
    try:
        return tree.open(path, mode=mode, encoding=encoding)
    except FileNotFoundError:
        if not dvc_tree:
            raise

    return dvc_tree.open(path, mode=mode, encoding=encoding, **kwargs)


# Traceback (AssertionError)
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-x-xxxxxxxxxxxx> in <module>
----> 1 with open('test/foo') as file:
2     pass
3

.../python3.6/contextlib.py in __enter__(self)
79     def __enter__(self):
80         try:
---> 81             return next(self.gen)
82         except StopIteration:
83             raise RuntimeError("generator didn't yield") from None

.../python3.6/site-packages/dvc/api.py in _open(path, repo, rev, remote, mode, encoding)
82     with _make_repo(repo, rev=rev) as _repo:
83         with _repo.open_by_relpath(
---> 84             path, remote=remote, mode=mode, encoding=encoding
85         ) as fd:
86             yield fd

.../python3.6/contextlib.py in __enter__(self)
79     def __enter__(self):
80         try:
---> 81             return next(self.gen)
82         except StopIteration:
83             raise RuntimeError("generator didn't yield") from None

.../python3.6/site-packages/dvc/repo/__init__.py in open_by_relpath(self, path, remote, mode, encoding)
616             with self.state:
617                 with tree.open(
--> 618                     path, mode=mode, encoding=encoding, remote=remote,
619                 ) as fobj:
620                     yield fobj

.../python3.6/site-packages/dvc/tree/repo.py in open(self, path, mode, encoding, **kwargs)
157                 raise
158
--> 159         return dvc_tree.open(path, mode=mode, encoding=encoding, **kwargs)
160
161     def exists(

.../python3.6/site-packages/dvc/tree/dvc.py in open(self, path, mode, encoding, remote)
80             if self.stream:
81                 if out.is_dir_checksum:
---> 82                     checksum = self._get_granular_checksum(path, out)
83                 else:
84                     checksum = out.hash_info.value

.../python3.6/site-packages/dvc/tree/dvc.py in _get_granular_checksum(self, path, out, remote)
47
48     def _get_granular_checksum(self, path, out, remote=None):
---> 49         assert isinstance(path, PathInfo)
50         if not self.fetch and not self.stream:
51             raise FileNotFoundError

AssertionError:

# Fixed code
def open(self, path, mode="r", encoding="utf-8", **kwargs):  # pylint: disable=arguments-differ
    if "b" in mode:
        encoding = None

    tree, dvc_tree = self._get_tree_pair(path)
    path_info = PathInfo(path)
    try:
        return tree.open(path_info, mode=mode, encoding=encoding)
    except FileNotFoundError:
        if not dvc_tree:
            raise

    return dvc_tree.open(path_info, mode=mode, encoding=encoding, **kwargs)
# Buggy code
def _update_names(names, items):
    from flatten_json import flatten

    for name, item in items:
        if isinstance(item, dict):
            item = flatten(item, ".")
            names.update(item.keys())
        else:
            names.add(name)


# Traceback (ImportError)
2020-08-30 08:57:43,226 DEBUG: fetched: [(3,)]
2020-08-30 08:57:43,228 DEBUG: fetched: [(21770,)]
2020-08-30 08:57:43,246 ERROR: unexpected error - cannot import name 'check_if_numbers_are_consecutive'
------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/dvc/main.py", line 75, in main
ret = cmd.run()
File "/usr/local/lib/python3.6/dist-packages/dvc/command/repro.py", line 47, in run
params=self.args.params,
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/__init__.py", line 34, in wrapper
ret = f(repo, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/scm_context.py", line 4, in run
result = method(repo, *args, **kw)
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/reproduce.py", line 74, in reproduce
params = _parse_params(kwargs.pop("params", []))
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/reproduce.py", line 122, in _parse_params
from flatten_json import unflatten
File "/usr/local/lib/python3.6/dist-packages/flatten_json.py", line 13, in <module>
from util import check_if_numbers_are_consecutive
ImportError: cannot import name 'check_if_numbers_are_consecutive'
------------------------------------------------------------
Having any troubles? Hit us up at https://dvc.org/support, we are always happy to help!
2020-08-30 08:57:43,249 DEBUG: Analytics is enabled.
2020-08-30 08:57:43,279 DEBUG: Trying to spawn '['daemon', '-q', 'analytics', '/tmp/tmpkskduifx']'
2020-08-30 08:57:43,280 DEBUG: Spawned '['daemon', '-q', 'analytics', '/tmp/tmpkskduifx']'

# Fixed code
def _update_names(names, items):
    for name, item in items:
        if isinstance(item, dict):
            item = flatten(item)
            names.update(item.keys())
        else:
            names.add(name)
# Buggy code
def _extend_row(row, names, items, precision):
    from flatten_json import flatten

    def _round(val):
        if isinstance(val, float):
            return round(val, precision)

        return val

    if not items:
        row.extend(["-"] * len(names))
        return

    for fname, item in items:
        if isinstance(item, dict):
            item = flatten(item, ".")
        else:
            item = {fname: item}
        for name in names:
            if name in item:
                value = item[name]
                text = str(_round(value)) if value is not None else "-"
                row.append(text)
            else:
                row.append("-")


# Traceback (ImportError)
2020-08-30 08:57:43,226 DEBUG: fetched: [(3,)]
2020-08-30 08:57:43,228 DEBUG: fetched: [(21770,)]
2020-08-30 08:57:43,246 ERROR: unexpected error - cannot import name 'check_if_numbers_are_consecutive'
------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/dvc/main.py", line 75, in main
ret = cmd.run()
File "/usr/local/lib/python3.6/dist-packages/dvc/command/repro.py", line 47, in run
params=self.args.params,
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/__init__.py", line 34, in wrapper
ret = f(repo, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/scm_context.py", line 4, in run
result = method(repo, *args, **kw)
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/reproduce.py", line 74, in reproduce
params = _parse_params(kwargs.pop("params", []))
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/reproduce.py", line 122, in _parse_params
from flatten_json import unflatten
File "/usr/local/lib/python3.6/dist-packages/flatten_json.py", line 13, in <module>
from util import check_if_numbers_are_consecutive
ImportError: cannot import name 'check_if_numbers_are_consecutive'
------------------------------------------------------------
Having any troubles? Hit us up at https://dvc.org/support, we are always happy to help!
2020-08-30 08:57:43,249 DEBUG: Analytics is enabled.
2020-08-30 08:57:43,279 DEBUG: Trying to spawn '['daemon', '-q', 'analytics', '/tmp/tmpkskduifx']'
2020-08-30 08:57:43,280 DEBUG: Spawned '['daemon', '-q', 'analytics', '/tmp/tmpkskduifx']'

# Fixed code
def _extend_row(row, names, items, precision):
    def _round(val):
        if isinstance(val, float):
            return round(val, precision)

        return val

    if not items:
        row.extend(["-"] * len(names))
        return

    for fname, item in items:
        if isinstance(item, dict):
            item = flatten(item)
        else:
            item = {fname: item}
        for name in names:
            if name in item:
                value = item[name]
                text = str(_round(value)) if value is not None else "-"
                row.append(text)
            else:
                row.append("-")
# Buggy code
def _flatten(d):
    if not d:
        return defaultdict(lambda: None)

    if isinstance(d, dict):
        from flatten_json import flatten as fltn

        return defaultdict(lambda: None, fltn(d, "."))

    return defaultdict(lambda: "unable to parse")


# Traceback (ImportError)
2020-08-30 08:57:43,226 DEBUG: fetched: [(3,)]
2020-08-30 08:57:43,228 DEBUG: fetched: [(21770,)]
2020-08-30 08:57:43,246 ERROR: unexpected error - cannot import name 'check_if_numbers_are_consecutive'
------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/dvc/main.py", line 75, in main
ret = cmd.run()
File "/usr/local/lib/python3.6/dist-packages/dvc/command/repro.py", line 47, in run
params=self.args.params,
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/__init__.py", line 34, in wrapper
ret = f(repo, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/scm_context.py", line 4, in run
result = method(repo, *args, **kw)
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/reproduce.py", line 74, in reproduce
params = _parse_params(kwargs.pop("params", []))
File "/usr/local/lib/python3.6/dist-packages/dvc/repo/reproduce.py", line 122, in _parse_params
from flatten_json import unflatten
File "/usr/local/lib/python3.6/dist-packages/flatten_json.py", line 13, in <module>
from util import check_if_numbers_are_consecutive
ImportError: cannot import name 'check_if_numbers_are_consecutive'
------------------------------------------------------------
Having any troubles? Hit us up at https://dvc.org/support, we are always happy to help!
2020-08-30 08:57:43,249 DEBUG: Analytics is enabled.
2020-08-30 08:57:43,279 DEBUG: Trying to spawn '['daemon', '-q', 'analytics', '/tmp/tmpkskduifx']'
2020-08-30 08:57:43,280 DEBUG: Spawned '['daemon', '-q', 'analytics', '/tmp/tmpkskduifx']'

# Fixed code
def _flatten(d):
    if not d:
        return defaultdict(lambda: None)

    if isinstance(d, dict):
        return defaultdict(lambda: None, flatten(d))

    return defaultdict(lambda: "unable to parse")
# Buggy code
def upload(self, from_info, to_info, name=None, no_progress_bar=False):
    if not hasattr(self, "_upload"):
        raise RemoteActionNotImplemented("upload", self.scheme)

    if to_info.scheme != self.scheme:
        raise NotImplementedError

    if from_info.scheme != "local":
        raise NotImplementedError

    logger.debug("Uploading '%s' to '%s'", from_info, to_info)

    name = name or from_info.name

    try:
        self._upload(
            from_info.fspath,
            to_info,
            name=name,
            no_progress_bar=no_progress_bar,
        )
    except Exception as e:
        return self._handle_transfer_exception(from_info, to_info, e, "upload")

    return 0


# Traceback (AttributeError)
Traceback (most recent call last):
File "d:\miniconda3\lib\site-packages\dvc\main.py", line 49, in main
ret = cmd.run()
File "d:\miniconda3\lib\site-packages\dvc\command\get_url.py", line 17, in run
Repo.get_url(self.args.url, out=self.args.out)
File "d:\miniconda3\lib\site-packages\dvc\repo\get_url.py", line 17, in get_url
(dep,) = dependency.loads_from(None, [url])
File "d:\miniconda3\lib\site-packages\dvc\dependency\__init__.py", line 83, in loads_from
ret.append(_get(stage, s, info))
File "d:\miniconda3\lib\site-packages\dvc\dependency\__init__.py", line 68, in _get
return LocalDependency(stage, p, info)
File "d:\miniconda3\lib\site-packages\dvc\output\local.py", line 25, in __init__
super().__init__(stage, path, *args, **kwargs)
File "d:\miniconda3\lib\site-packages\dvc\output\base.py", line 98, in __init__
self.path_info = self._parse_path(remote, path)
File "d:\miniconda3\lib\site-packages\dvc\output\local.py", line 40, in _parse_path
p = self.stage.wdir / p
AttributeError: 'NoneType' object has no attribute 'wdir'

# Fixed code
def upload(self, from_info, to_info, name=None, no_progress_bar=False):
    if not hasattr(self, "_upload"):
        raise RemoteActionNotImplemented("upload", self.scheme)

    if to_info.scheme != self.scheme:
        raise NotImplementedError

    if from_info.scheme != "local":
        raise NotImplementedError

    logger.debug("Uploading '%s' to '%s'", from_info, to_info)

    name = name or from_info.name

    self._upload(
        from_info.fspath,
        to_info,
        name=name,
        no_progress_bar=no_progress_bar,
    )