gurudesh/pytracebugs huggingface dataset:
# Buggy code
def __init__(self, backend_prop):
    """
    Chooses a Noise Adaptive Layout

    Args:
        backend_prop (BackendProperties): backend properties object

    Raises:
        TranspilerError: if invalid options
    """
    super().__init__()
    self.backend_prop = backend_prop
    self.swap_graph = nx.DiGraph()
    self.cx_errors = {}
    self.readout_errors = {}
    self.available_hw_qubits = []
    self.gate_list = []
    self.gate_cost = {}
    self.swap_paths = {}
    self.swap_costs = {}
    self.prog_graph = nx.Graph()
    self.qarg_to_id = {}
    self.pending_program_edges = []
    self.prog2hw = {}


# Traceback (TypeError)
import qiskit as qk
from qiskit.test.mock import FakePoughkeepsie
qc = qk.QuantumCircuit.from_qasm_str('''
OPENQASM 2.0;
include "qelib1.inc";
qreg q7159[6];
qreg q7160[2];
creg c1212[1];
cx q7159[5],q7159[4];
cx q7159[3],q7159[2];
cx q7159[1],q7159[0];
cx q7160[1],q7160[0];
measure q7160[1] -> c1212[0];''')
qk.transpile(qc, backend=FakePoughkeepsie(), optimization_level=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/compiler/transpile.py", line 200, in transpile
circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_configs)))
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/tools/parallel.py", line 100, in parallel_map
return [task(values[0], *task_args, **task_kwargs)]
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/compiler/transpile.py", line 221, in _transpile_circuit
return transpile_circuit(circuit, transpile_config)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/transpile_circuit.py", line 62, in transpile_circuit
out_circuit = pass_manager.run(circuit)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 172, in run
dag = self._do_pass(pass_, dag, passset.options)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 223, in _do_pass
dag = self._run_this_pass(pass_, dag)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 255, in _run_this_pass
pass_.run(FencedDAGCircuit(dag))
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py", line 229, in run
self.prog2hw[edge[0]] = best_hw_edge[0]
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def __init__(self, backend_prop):
    """
    Chooses a Noise Adaptive Layout

    Args:
        backend_prop (BackendProperties): backend properties object

    Raises:
        TranspilerError: if invalid options
    """
    super().__init__()
    self.backend_prop = backend_prop
    self.swap_graph = nx.DiGraph()
    self.cx_reliability = {}
    self.readout_reliability = {}
    self.available_hw_qubits = []
    self.gate_list = []
    self.gate_reliability = {}
    self.swap_paths = {}
    self.swap_costs = {}
    self.prog_graph = nx.Graph()
    self.qarg_to_id = {}
    self.pending_program_edges = []
    self.prog2hw = {}
# Buggy code
def _select_best_remaining_cx(self):
    """
    Select best remaining CNOT in the hardware for the next program edge.
    """
    candidates = []
    for gate in self.gate_list:
        chk1 = gate[0] in self.available_hw_qubits
        chk2 = gate[1] in self.available_hw_qubits
        if chk1 and chk2:
            candidates.append(gate)
    best_reliab = 0
    best_item = None
    for item in candidates:
        if self.gate_cost[item] > best_reliab:
            best_reliab = self.gate_cost[item]
            best_item = item
    return best_item


# Traceback (TypeError)
import qiskit as qk
from qiskit.test.mock import FakePoughkeepsie
qc = qk.QuantumCircuit.from_qasm_str('''
OPENQASM 2.0;
include "qelib1.inc";
qreg q7159[6];
qreg q7160[2];
creg c1212[1];
cx q7159[5],q7159[4];
cx q7159[3],q7159[2];
cx q7159[1],q7159[0];
cx q7160[1],q7160[0];
measure q7160[1] -> c1212[0];''')
qk.transpile(qc, backend=FakePoughkeepsie(), optimization_level=2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/compiler/transpile.py", line 200, in transpile
circuits = parallel_map(_transpile_circuit, list(zip(circuits, transpile_configs)))
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/tools/parallel.py", line 100, in parallel_map
return [task(values[0], *task_args, **task_kwargs)]
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/compiler/transpile.py", line 221, in _transpile_circuit
return transpile_circuit(circuit, transpile_config)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/transpile_circuit.py", line 62, in transpile_circuit
out_circuit = pass_manager.run(circuit)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 172, in run
dag = self._do_pass(pass_, dag, passset.options)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 223, in _do_pass
dag = self._run_this_pass(pass_, dag)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passmanager.py", line 255, in _run_this_pass
pass_.run(FencedDAGCircuit(dag))
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/transpiler/passes/mapping/noise_adaptive_layout.py", line 229, in run
self.prog2hw[edge[0]] = best_hw_edge[0]
TypeError: 'NoneType' object is not subscriptable

# Fixed code
def _select_best_remaining_cx(self):
    """
    Select best remaining CNOT in the hardware for the next program edge.
    """
    candidates = []
    for gate in self.gate_list:
        chk1 = gate[0] in self.available_hw_qubits
        chk2 = gate[1] in self.available_hw_qubits
        if chk1 and chk2:
            candidates.append(gate)
    best_reliab = 0
    best_item = None
    for item in candidates:
        if self.gate_reliability[item] > best_reliab:
            best_reliab = self.gate_reliability[item]
            best_item = item
    return best_item
# Buggy code
def size(self):
    """Returns total number of gate operations in circuit.

    Returns:
        int: Total number of gate operations.
    """
    gate_ops = 0
    for item in self.data:
        if item.name not in ["barrier", "snapshot"]:
            gate_ops += 1
    return gate_ops


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-18ab26fa2a60> in <module>
7 #circuit.h(q[2])
8 #circuit.h(q[3])
----> 9 circuit.size()
10 circuit.draw(output='mpl',style=style)

c:\users\francoisvarchon\anaconda3\envs\qis09z\lib\site-packages\qiskit_terra-0.8.0-py3.7-win-amd64.egg\qiskit\circuit\quantumcircuit.py in size(self)
436         gate_ops = 0
437         for item in self.data:
--> 438             if item.name not in ['barrier', 'snapshot']:
439                 gate_ops += 1
440         return gate_ops

AttributeError: 'tuple' object has no attribute 'name'

# Fixed code
def size(self):
    """Returns total number of gate operations in circuit.

    Returns:
        int: Total number of gate operations.
    """
    gate_ops = 0
    for instr, _, _ in self.data:
        if instr.name not in ["barrier", "snapshot"]:
            gate_ops += 1
    return gate_ops
# Buggy code
def count_ops(self):
    """Count each operation kind in the circuit.

    Returns:
        dict: a breakdown of how many operations of each kind.
    """
    count_ops = {}
    for op in self.data:
        if op[0].name in count_ops.keys():
            count_ops[op[0].name] += 1
        else:
            count_ops[op[0].name] = 1
    return count_ops


# Traceback (AttributeError)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-20-18ab26fa2a60> in <module>
7 #circuit.h(q[2])
8 #circuit.h(q[3])
----> 9 circuit.size()
10 circuit.draw(output='mpl',style=style)

c:\users\francoisvarchon\anaconda3\envs\qis09z\lib\site-packages\qiskit_terra-0.8.0-py3.7-win-amd64.egg\qiskit\circuit\quantumcircuit.py in size(self)
436         gate_ops = 0
437         for item in self.data:
--> 438             if item.name not in ['barrier', 'snapshot']:
439                 gate_ops += 1
440         return gate_ops

AttributeError: 'tuple' object has no attribute 'name'

# Fixed code
def count_ops(self):
    """Count each operation kind in the circuit.

    Returns:
        dict: a breakdown of how many operations of each kind.
    """
    count_ops = {}
    for instr, _, _ in self.data:
        if instr.name in count_ops.keys():
            count_ops[instr.name] += 1
        else:
            count_ops[instr.name] = 1
    return count_ops
# Buggy code
def param_parse(v, pimode=False):
    for i, e in enumerate(v):
        if pimode:
            v[i] = MatplotlibDrawer.format_pi(e)
        else:
            v[i] = MatplotlibDrawer.format_numeric(e)
        if v[i].startswith("-"):
            v[i] = "$-$" + v[i][1:]
    param = ", ".join(v)
    return param


# Traceback (TypeError)
theta = sympy.Symbol('theta')
qc = qk.QuantumCircuit(cr, qr)
qc.rx(theta, qr[0])
<qiskit.extensions.standard.rx.RXGate object at 0x116d5c1d0>
qc.measure(qr[0], cr[0])
<qiskit.circuit.measure.Measure object at 0x11ed71c50>
print(qc.draw())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 437, in __str__
return self.single_string()
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 462, in single_string
return "\n".join(self.lines())
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 497, in lines
layers = self.build_layers()
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 820, in build_layers
self._instruction_to_gate(instruction, layer)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 780, in _instruction_to_gate
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 618, in label_for_box
params = TextDrawing.params_for_label(instruction)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 610, in params_for_label
return ['%.5g' % i for i in instruction.op.params
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 611, in <listcomp>
if not isinstance(i, (numpy.ndarray, sympy.Matrix))]
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/lib/python3.5/site-packages/sympy/core/expr.py", line 256, in __float__
raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float

# Fixed code
def param_parse(v, pimode=False):
    for i, e in enumerate(v):
        if pimode:
            try:
                v[i] = MatplotlibDrawer.format_pi(e)
            except TypeError:
                v[i] = str(e)
        else:
            try:
                v[i] = MatplotlibDrawer.format_numeric(e)
            except TypeError:
                v[i] = str(e)
        if v[i].startswith("-"):
            v[i] = "$-$" + v[i][1:]
    param = ", ".join(v)
    return param
# Buggy code
def params_for_label(instruction):
    """Get the params and format them to add them to a label. None if there are no params."""
    if hasattr(instruction.op, "params"):
        return [
            "%.5g" % i
            for i in instruction.op.params
            if not isinstance(i, (numpy.ndarray, sympy.Matrix))
        ]
    return None


# Traceback (TypeError)
theta = sympy.Symbol('theta')
qc = qk.QuantumCircuit(cr, qr)
qc.rx(theta, qr[0])
<qiskit.extensions.standard.rx.RXGate object at 0x116d5c1d0>
qc.measure(qr[0], cr[0])
<qiskit.circuit.measure.Measure object at 0x11ed71c50>
print(qc.draw())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 437, in __str__
return self.single_string()
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 462, in single_string
return "\n".join(self.lines())
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 497, in lines
layers = self.build_layers()
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 820, in build_layers
self._instruction_to_gate(instruction, layer)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 780, in _instruction_to_gate
BoxOnQuWire(TextDrawing.label_for_box(instruction)))
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 618, in label_for_box
params = TextDrawing.params_for_label(instruction)
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 610, in params_for_label
return ['%.5g' % i for i in instruction.op.params
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/qiskit/visualization/text.py", line 611, in <listcomp>
if not isinstance(i, (numpy.ndarray, sympy.Matrix))]
File "/Users/kevin.krsulichibm.com/q/qiskit-terra/lib/python3.5/site-packages/sympy/core/expr.py", line 256, in __float__
raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float

# Fixed code
def params_for_label(instruction):
    """Get the params and format them to add them to a label. None if there are no params."""
    if not hasattr(instruction.op, "params"):
        return None
    ret = []
    for param in instruction.op.params:
        if isinstance(param, (sympy.Number, float)):
            ret.append("%.5g" % param)
        else:
            ret.append("%s" % param)
    return ret
# Buggy code
def retrieve_job(self, job_id):
    """Attempt to get the specified job by job_id

    Args:
        job_id (str): the job id of the job to retrieve

    Returns:
        IBMQJob: class instance

    Raises:
        IBMQBackendError: if retrieval failed
    """
    try:
        job_info = self._api.get_status_job(job_id)
        if "error" in job_info:
            raise IBMQBackendError(
                'Failed to get job "{}": {}'.format(job_id, job_info["error"])
            )
    except ApiError as ex:
        raise IBMQBackendError('Failed to get job "{}":{}'.format(job_id, str(ex)))
    job_class = _job_class_from_job_response(job_info)
    is_device = not bool(self.configuration().simulator)
    job = job_class(
        self,
        job_info.get("id"),
        self._api,
        is_device,
        creation_date=job_info.get("creationDate"),
        api_status=job_info.get("status"),
    )
    return job


# Traceback (KeyError)
1:     b'Traceback (most recent call last):'
1:     b'  File "/home/travis/build/Qiskit/qiskit-terra/test/python/ibmq/test_ibmqjob.py", line 283, in test_get_jobs_filter_job_status'
1:     b"    self.log.info('match #%d: %s', i, job.result().status)"
1:     b'  File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 210, in result'
1:     b'    return self._result_from_job_response(job_response)'
1:     b'  File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 506, in _result_from_job_response'
1:     b'    _reorder_bits(job_response)'
1:     b'  File "/home/travis/build/Qiskit/qiskit-terra/qiskit/backends/ibmq/ibmqjob.py", line 546, in _reorder_bits'
1:     b"    for circuit_result in job_data['qasms']:"
1:     b"KeyError: 'qasms'"
1:     b''

# Fixed code
def retrieve_job(self, job_id):
    """Attempt to get the specified job by job_id

    Args:
        job_id (str): the job id of the job to retrieve

    Returns:
        IBMQJob: class instance

    Raises:
        IBMQBackendError: if retrieval failed
        DeprecatedFormatJobError: if the job retrieved has a format pre 0.7
    """
    try:
        job_info = self._api.get_status_job(job_id)
        if "error" in job_info:
            raise IBMQBackendError(
                'Failed to get job "{}": {}'.format(job_id, job_info["error"])
            )
    except ApiError as ex:
        raise IBMQBackendError('Failed to get job "{}":{}'.format(job_id, str(ex)))
    job_class = _job_class_from_job_response(job_info)
    if job_class is IBMQJobPreQobj:
        raise DeprecatedFormatJobError(
            "The result of job {} is in an old and no "
            "longer supported format, please resend the "
            "job with Qiskit 0.7".format(job_id)
        )

    is_device = not bool(self.configuration().simulator)
    job = job_class(
        self,
        job_info.get("id"),
        self._api,
        is_device,
        creation_date=job_info.get("creationDate"),
        api_status=job_info.get("status"),
    )
    return job
# Buggy code
def save_account(self, token, url=QE_URL, **kwargs):
    """Save the account to disk for future use.

    Login into Quantum Experience or IBMQ using the provided credentials,
    adding the account to the current session. The account is stored in
    disk for future use.

    Args:
        token (str): Quantum Experience or IBM Q API token.
        url (str): URL for Quantum Experience or IBM Q (for IBM Q,
            including the hub, group and project in the URL).
        **kwargs (dict):
            * proxies (dict): Proxy configuration for the API.
            * verify (bool): If False, ignores SSL certificates errors
    """
    credentials = Credentials(token, url, **kwargs)

    # Check if duplicated credentials are already stored. By convention,
    # we assume (hub, group, project) is always unique.
    stored_credentials = read_credentials_from_qiskitrc()

    if credentials.unique_id() in stored_credentials.keys():
        warnings.warn("Credentials are already stored.")
    else:
        store_credentials(credentials)


# Traceback (IBMQuantumExperience.IBMQuantumExperience.CredentialsError)
Traceback (most recent call last):
File "/anaconda3/lib/python3.7/site-packages/qiskit/backends/ibmq/ibmqsingleprovider.py", line 71, in _authenticate
credentials.verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 478, in __init__
self.req = _Request(token, config=config, verify=verify)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 253, in __init__
ntlm_credentials=self.ntlm_credentials)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 95, in __init__
self.obtain_token(config=self.config)
File "/anaconda3/lib/python3.7/site-packages/IBMQuantumExperience/IBMQuantumExperience.py", line 159, in obtain_token
raise CredentialsError('error during login: %s' % error_message)
IBMQuantumExperience.IBMQuantumExperience.CredentialsError: error during login: Wrong user or password, check your credentials.

# Fixed code
def save_account(self, token, url=QE_URL, overwrite=False, **kwargs):
    """Save the account to disk for future use.

    Login into Quantum Experience or IBMQ using the provided credentials,
    adding the account to the current session. The account is stored in
    disk for future use.

    Args:
        token (str): Quantum Experience or IBM Q API token.
        url (str): URL for Quantum Experience or IBM Q (for IBM Q,
            including the hub, group and project in the URL).
        overwrite (bool): overwrite existing credentials.
        **kwargs (dict):
            * proxies (dict): Proxy configuration for the API.
            * verify (bool): If False, ignores SSL certificates errors
    """
    credentials = Credentials(token, url, **kwargs)
    store_credentials(credentials, overwrite=overwrite)
# Buggy code
def random_state(num):
    """
    Return a random quantum state from the uniform (Haar) measure on
    state space.

    Args:
        num (int): the number of qubits
    Returns:
        ndarray:  state(2**num) a random quantum state.
    """
    x = np.random.random(1 << num) + 0.00000001
    x = -np.log(x)
    sumx = sum(x)
    phases = np.random.random(1 << num) * 2.0 * np.pi
    return np.sqrt(x / sumx) * np.exp(1j * phases)


# Traceback (AssertionError)
test.python.quantum_info.test_states.TestStates.test_random_state
-----------------------------------------------------------------
Captured traceback:
~~~~~~~~~~~~~~~~~~~
b'Traceback (most recent call last):'
b'  File "C:\\projects\\qiskit-sdk-py\\test\\python\\quantum_info\\test_states.py", line 90, in test_random_state'
b'    self.assertAlmostEqual(E_P0, 1/8, places=2)'
b'  File "C:\\Python35\\lib\\unittest\\case.py", line 877, in assertAlmostEqual'
b'    raise self.failureException(msg)'
b'AssertionError: nan != 0.125 within 2 places'
b''
======

# Fixed code
def random_state(num):
    """
    Return a random quantum state from the uniform (Haar) measure on
    state space.

    Args:
        num (int): the number of qubits
    Returns:
        ndarray:  state(2**num) a random quantum state.
    """
    # Random array over interval (0, 1]
    x = np.random.random(1 << num)
    x += x == 0
    x = -np.log(x)
    sumx = sum(x)
    phases = np.random.random(1 << num) * 2.0 * np.pi
    return np.sqrt(x / sumx) * np.exp(1j * phases)
# Buggy code
def status(self):
    """Gets the status of the job by querying the Python's future

    Returns:
        JobStatus: The current JobStatus

    Raises:
        JobError: If the future is in unexpected state
        concurrent.futures.TimeoutError: if timeout occurred.
    """
    # The order is important here
    if self._future.running():
        _status = JobStatus.RUNNING
    elif self._future.cancelled():
        _status = JobStatus.CANCELLED
    elif self._future.done():
        _status = (
            JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
        )
    else:
        raise JobError("Unexpected behavior of {0}".format(self.__class__.__name__))
    return _status


# Traceback (qiskit.backends.joberror.JobError)
Traceback (most recent call last):
File "/Users/paul/Desktop/Github_repos/qiskit-core/test/python/test_cpp.py", line 34, in test_aer_status
job_sim.status()
File "/Users/paul/Desktop/Github_repos/qiskit-core/qiskit/backends/aer/aerjob.py", line 37, in _wrapper
return func(self, *args, **kwargs)
File "/Users/paul/Desktop/Github_repos/qiskit-core/qiskit/backends/aer/aerjob.py", line 118, in status
self.__class__.__name__))
qiskit.backends.joberror.JobError: 'Unexpected behavior of AerJob'

# Fixed code
def status(self):
    """Gets the status of the job by querying the Python's future

    Returns:
        JobStatus: The current JobStatus

    Raises:
        JobError: If the future is in unexpected state
        concurrent.futures.TimeoutError: if timeout occurred.
    """
    # The order is important here
    if self._future.running():
        _status = JobStatus.RUNNING
    elif self._future.cancelled():
        _status = JobStatus.CANCELLED
    elif self._future.done():
        _status = (
            JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR
        )
    else:
        # Note: There is an undocumented Future state: PENDING, that seems to show up when
        # the job is enqueued, waiting for someone to pick it up. We need to deal with this
        # state but there's no public API for it, so we are assuming that if the job is not
        # in any of the previous states, is PENDING, ergo INITIALIZING for us.
        _status = JobStatus.INITIALIZING

    return _status
# Buggy code
def _run_job(self, job_id, qobj):
    """Run a Qobj on the backend."""
    self._validate(qobj)
    final_state_key = 32767  # Internal key for final state snapshot
    # Add final snapshots to circuits
    for experiment in qobj.experiments:
        experiment.instructions.append(
            QobjInstruction(name="snapshot", params=[final_state_key])
        )
    result = super()._run_job(job_id, qobj)
    # Replace backend name with current backend
    result.backend_name = self.name
    # Extract final state snapshot and move to 'statevector' data field
    for experiment_result in result.results.values():
        snapshots = experiment_result.snapshots
        if str(final_state_key) in snapshots:
            final_state_key = str(final_state_key)
        # Pop off final snapshot added above
        final_state = snapshots.pop(final_state_key, None)
        final_state = final_state["statevector"][0]
        # Add final state to results data
        experiment_result.data["statevector"] = final_state
        # Remove snapshot dict if empty
        if snapshots == {}:
            experiment_result.data.pop("snapshots", None)
    return result


# Traceback (qiskit._qiskiterror.QISKitError)
Traceback (most recent call last):
File "/Users/rchen/Developer/Quantum/qiskit-terra/qiskit/result/_result.py", line 125, in __add__
copy_of_self += other
File "/Users/rchen/Developer/Quantum/qiskit-terra/qiskit/result/_result.py", line 108, in __iadd__
raise QISKitError('Result objects from different backends cannot be combined.')
qiskit._qiskiterror.QISKitError: 'Result objects from different backends cannot be combined.'

# Fixed code
def _run_job(self, job_id, qobj):
    """Run a Qobj on the backend."""
    self._validate(qobj)
    final_state_key = 32767  # Internal key for final state snapshot
    # Add final snapshots to circuits
    for experiment in qobj.experiments:
        experiment.instructions.append(
            QobjInstruction(name="snapshot", params=[final_state_key])
        )
    result = super()._run_job(job_id, qobj)
    # Extract final state snapshot and move to 'statevector' data field
    for experiment_result in result.results.values():
        snapshots = experiment_result.snapshots
        if str(final_state_key) in snapshots:
            final_state_key = str(final_state_key)
        # Pop off final snapshot added above
        final_state = snapshots.pop(final_state_key, None)
        final_state = final_state["statevector"][0]
        # Add final state to results data
        experiment_result.data["statevector"] = final_state
        # Remove snapshot dict if empty
        if snapshots == {}:
            experiment_result.data.pop("snapshots", None)
    return result
# Buggy code
def distance(self, q1, q2):
    """Return the undirected distance between qubit q1 to qubit q2."""
    if self.dist is None:
        raise CouplingError("distance has not been computed")
    if q1 not in self.qubits:
        raise CouplingError("%s not in coupling graph" % q1)
    if q2 not in self.qubits:
        raise CouplingError("%s not in coupling graph" % q2)
    return self.dist[q1][q2]


# Traceback (TypeError)
In [1]: from qiskit.mapper._coupling import Coupling
In [2]: graph = Coupling({0: [1, 2], 1: [2]})
In [3]: graph.distance(('q0',0),('q1',1))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-88a8c8c0c516> in <module>()
----> 1 graph.distance(('q0',0),('q1',1))

/Users/luciano.bello/repos/qiskit-terra/qiskit/mapper/_coupling.py in distance(self, q1, q2)
168             raise CouplingError("distance has not been computed")
169         if q1 not in self.qubits:
--> 170             raise CouplingError("%s not in coupling graph" % q1)
171         if q2 not in self.qubits:
172             raise CouplingError("%s not in coupling graph" % q2)

TypeError: not all arguments converted during string formatting

# Fixed code
def distance(self, q1, q2):
    """Return the undirected distance between qubit q1 to qubit q2."""
    if self.dist is None:
        raise CouplingError("distance has not been computed")
    if q1 not in self.qubits:
        raise CouplingError("%s not in coupling graph" % (q1,))
    if q2 not in self.qubits:
        raise CouplingError("%s not in coupling graph" % (q2,))
    return self.dist[q1][q2]
# Buggy code
def check_range(self, j):
    """Check that j is a valid index into self."""
    if j < 0 or j >= self.size:
        raise QISKitError("register index out of range")


# Traceback (QISKitError)
(<qiskit._classicalregister.ClassicalRegister object at 0x11f5a6668>, 0)
(<qiskit._classicalregister.ClassicalRegister object at 0x11f5a6668>, 1)
---------------------------------------------------------------------------
QISKitError                               Traceback (most recent call last)
<ipython-input-19-ba21ef293e46> in <module>()
----> 1 for j in ClassicalRegister(2):
2     print(j)

~/anaconda/envs/qiskit/lib/python3.6/site-packages/qiskit/_register.py in __getitem__(self, key)
87         if not isinstance(key, int):
88             raise QISKitError("expected integer index into register")
---> 89         self.check_range(key)
90         return (self, key)

~/anaconda/envs/qiskit/lib/python3.6/site-packages/qiskit/_register.py in check_range(self, j)
81         """Check that j is a valid index into self."""
82         if j < 0 or j >= self.size:
---> 83             raise QISKitError("register index out of range")
84
85     def __getitem__(self, key):

QISKitError: 'register index out of range'

# Fixed code
def check_range(self, j):
    """Check that j is a valid index into self."""
    if j < 0 or j >= self.size:
        raise QISKitIndexError("register index out of range")
# Buggy code
def __getitem__(self, key):
    """Return tuple (self, key) if key is valid."""
    if not isinstance(key, int):
        raise QISKitError("expected integer index into register")
    self.check_range(key)
    return (self, key)


# Traceback (QISKitError)
(<qiskit._classicalregister.ClassicalRegister object at 0x11f5a6668>, 0)
(<qiskit._classicalregister.ClassicalRegister object at 0x11f5a6668>, 1)
---------------------------------------------------------------------------
QISKitError                               Traceback (most recent call last)
<ipython-input-19-ba21ef293e46> in <module>()
----> 1 for j in ClassicalRegister(2):
2     print(j)

~/anaconda/envs/qiskit/lib/python3.6/site-packages/qiskit/_register.py in __getitem__(self, key)
87         if not isinstance(key, int):
88             raise QISKitError("expected integer index into register")
---> 89         self.check_range(key)
90         return (self, key)

~/anaconda/envs/qiskit/lib/python3.6/site-packages/qiskit/_register.py in check_range(self, j)
81         """Check that j is a valid index into self."""
82         if j < 0 or j >= self.size:
---> 83             raise QISKitError("register index out of range")
84
85     def __getitem__(self, key):

QISKitError: 'register index out of range'

# Fixed code
def __getitem__(self, key):
    """
    Arg:
        key (int): index of the bit/qubit to be retrieved.

    Returns:
        tuple[Register, int]: a tuple in the form `(self, key)`.

    Raises:
        QISKitError: if the `key` is not an integer.
        QISKitIndexError: if the `key` is not in the range
            `(0, self.size)`.
    """
    if not isinstance(key, int):
        raise QISKitError("expected integer index into register")
    self.check_range(key)
    return self, key
# Buggy code
def build_unannotated_method_args(
    method_node: FuncDef,
) -> Tuple[List[Argument], MypyType]:
    prepared_arguments = []
    for argument in method_node.arguments[1:]:
        argument.type_annotation = AnyType(TypeOfAny.unannotated)
        prepared_arguments.append(argument)
    return_type = AnyType(TypeOfAny.unannotated)
    return prepared_arguments, return_type


# Traceback (AttributeError)
./test_app/models.py:6: error: INTERNAL ERROR -- Please try using mypy master on Github:
https://mypy.rtfd.io/en/latest/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 0.770
Traceback (most recent call last):
File "mypy/semanal.py", line 4679, in accept
File "mypy/nodes.py", line 939, in accept
File "mypy/semanal.py", line 1001, in visit_class_def
File "mypy/semanal.py", line 1078, in analyze_class
File "mypy/semanal.py", line 1087, in analyze_class_body_common
File "mypy/semanal.py", line 1147, in apply_class_plugin_hooks
File "<venv>/mypytest/lib/python3.7/site-packages/mypy_django_plugin/main.py", line 37, in transform_model_class
process_model_class(ctx, django_context)
File "<venv>/mypytest/lib/python3.7/site-packages/mypy_django_plugin/transformers/models.py", line 357, in process_model_class
initializer_cls(ctx, django_context).run()
File "<venv>/mypytest/lib/python3.7/site-packages/mypy_django_plugin/transformers/models.py", line 71, in run
self.run_with_model_cls(model_cls)
File "<venv>/mypytest/lib/python3.7/site-packages/mypy_django_plugin/transformers/models.py", line 231, in run_with_model_cls
base_manager_info=manager_info)
File "<venv>/mypytest/lib/python3.7/site-packages/mypy_django_plugin/transformers/models.py", line 186, in create_new_model_parametrized_manager
method_node=sym.node)
File "<venv>/mypytest/lib/python3.7/site-packages/mypy_django_plugin/lib/helpers.py", line 329, in copy_method_to_another_class
arguments, return_type = build_unannotated_method_args(method_node)
File "<venv>/mypytest/lib/python3.7/site-packages/mypy_django_plugin/lib/helpers.py", line 314, in build_unannotated_method_args
for argument in method_node.arguments[1:]:
AttributeError: attribute 'arguments' of 'FuncItem' undefined
./test_app/models.py:6: : note: use --pdb to drop into pdb

# Fixed code
def build_unannotated_method_args(
    method_node: FuncDef,
) -> Tuple[List[Argument], MypyType]:
    prepared_arguments = []
    try:
        arguments = method_node.arguments[1:]
    except AttributeError:
        arguments = []
    for argument in arguments:
        argument.type_annotation = AnyType(TypeOfAny.unannotated)
        prepared_arguments.append(argument)
    return_type = AnyType(TypeOfAny.unannotated)
    return prepared_arguments, return_type
# Buggy code
def get_field_nullability(self, field: Field, method: Optional[str]) -> bool:
    nullable = field.null
    if not nullable and isinstance(field, CharField) and field.blank:
        return True
    if method == "__init__":
        if field.primary_key or isinstance(field, ForeignKey):
            return True
    if method == "create":
        if isinstance(field, AutoField):
            return True
    if field.has_default():
        return True
    return nullable


# Traceback (AttributeError)
Traceback (most recent call last):
File "mypy/checkexpr.py", line 3603, in accept
File "mypy/nodes.py", line 1532, in accept
File "mypy/checkexpr.py", line 264, in visit_call_expr
File "mypy/checkexpr.py", line 341, in visit_call_expr_inner
File "mypy/checkexpr.py", line 730, in check_call_expr_with_callee_type
File "mypy/checkexpr.py", line 789, in check_call
File "mypy/checkexpr.py", line 897, in check_callable_call
File "mypy/checkexpr.py", line 638, in apply_function_plugin
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/transformers/querysets.py", line 184, in extract_proper_type_queryset_values
lookup=field_lookup, method='values')
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/transformers/querysets.py", line 57, in get_field_type_from_lookup
lookup_field, method=method)
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/django/context.py", line 268, in get_field_get_type
is_nullable = self.get_field_nullability(field, method)
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/django/context.py", line 241, in get_field_nullability
if field.has_default():
AttributeError: 'ManyToManyRel' object has no attribute 'has_default'

# Fixed code
def get_field_nullability(
    self, field: Union[Field, ForeignObjectRel], method: Optional[str]
) -> bool:
    nullable = field.null
    if not nullable and isinstance(field, CharField) and field.blank:
        return True
    if method == "__init__":
        if (isinstance(field, Field) and field.primary_key) or isinstance(
            field, ForeignKey
        ):
            return True
    if method == "create":
        if isinstance(field, AutoField):
            return True
    if isinstance(field, Field) and field.has_default():
        return True
    return nullable
# Buggy code
def resolve_lookup_into_field(self, model_cls: Type[Model], lookup: str) -> Field:
    query = Query(model_cls)
    lookup_parts, field_parts, is_expression = query.solve_lookup_type(lookup)
    if lookup_parts:
        raise LookupsAreUnsupported()

    return self._resolve_field_from_parts(field_parts, model_cls)


# Traceback (AttributeError)
Traceback (most recent call last):
File "mypy/checkexpr.py", line 3603, in accept
File "mypy/nodes.py", line 1532, in accept
File "mypy/checkexpr.py", line 264, in visit_call_expr
File "mypy/checkexpr.py", line 341, in visit_call_expr_inner
File "mypy/checkexpr.py", line 730, in check_call_expr_with_callee_type
File "mypy/checkexpr.py", line 789, in check_call
File "mypy/checkexpr.py", line 897, in check_callable_call
File "mypy/checkexpr.py", line 638, in apply_function_plugin
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/transformers/querysets.py", line 184, in extract_proper_type_queryset_values
lookup=field_lookup, method='values')
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/transformers/querysets.py", line 57, in get_field_type_from_lookup
lookup_field, method=method)
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/django/context.py", line 268, in get_field_get_type
is_nullable = self.get_field_nullability(field, method)
File "/home/christopher/.local/share/virtualenvs/workbench-yfRj1nF_-/home/christopher/.pyenv/shims/python/lib/python3.6/site-packages/mypy_django_plugin/django/context.py", line 241, in get_field_nullability
if field.has_default():
AttributeError: 'ManyToManyRel' object has no attribute 'has_default'

# Fixed code
def resolve_lookup_into_field(
    self, model_cls: Type[Model], lookup: str
) -> Union[Field, ForeignObjectRel]:
    query = Query(model_cls)
    lookup_parts, field_parts, is_expression = query.solve_lookup_type(lookup)
    if lookup_parts:
        raise LookupsAreUnsupported()

    return self._resolve_field_from_parts(field_parts, model_cls)
# Buggy code
def is_model_subclass_info(info: TypeInfo, django_context: "DjangoContext") -> bool:
    return info.fullname() in django_context.model_base_classes or info.has_base(
        fullnames.MODEL_CLASS_FULLNAME
    )


# Traceback (ValueError)
Traceback (most recent call last):
File "mypy/newsemanal/semanal.py", line 4550, in accept
File "mypy/nodes.py", line 921, in accept__Node_glue
File "mypy/nodes.py", line 922, in accept
File "mypy/newsemanal/semanal.py", line 989, in visit_class_def__StatementVisitor_glue
File "mypy/newsemanal/semanal.py", line 992, in visit_class_def
File "mypy/newsemanal/semanal.py", line 1063, in analyze_class
File "mypy/newsemanal/semanal.py", line 1072, in analyze_class_body_common
File "mypy/newsemanal/semanal.py", line 1131, in apply_class_plugin_hooks
File "/venv/site-packages/mypy_django_plugin/main.py", line 33, in transform_model_class
process_model_class(ctx, django_context)
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 228, in process_model_class
initializer_cls(ctx, django_context).run()
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 60, in run
self.run_with_model_cls(model_cls)
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 104, in run_with_model_cls
rel_primary_key_field = self.django_context.get_primary_key_field(related_model_cls)
File "/venv/site-packages/mypy_django_plugin/django/context.py", line 231, in get_primary_key_field
raise ValueError('No primary key defined')

# Fixed code
def is_model_subclass_info(info: TypeInfo, django_context: "DjangoContext") -> bool:
    return (
        info.fullname() in django_context.all_registered_model_class_fullnames
        or info.has_base(fullnames.MODEL_CLASS_FULLNAME)
    )
# Buggy code
def get_base_class_hook(
    self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
    if (
        fullname in self.django_context.model_base_classes
        or fullname in self._get_current_model_bases()
    ):
        return partial(transform_model_class, django_context=self.django_context)

    if fullname in self._get_current_manager_bases():
        return add_new_manager_base

    if fullname in self._get_current_form_bases():
        return transform_form_class
    return None


# Traceback (ValueError)
Traceback (most recent call last):
File "mypy/newsemanal/semanal.py", line 4550, in accept
File "mypy/nodes.py", line 921, in accept__Node_glue
File "mypy/nodes.py", line 922, in accept
File "mypy/newsemanal/semanal.py", line 989, in visit_class_def__StatementVisitor_glue
File "mypy/newsemanal/semanal.py", line 992, in visit_class_def
File "mypy/newsemanal/semanal.py", line 1063, in analyze_class
File "mypy/newsemanal/semanal.py", line 1072, in analyze_class_body_common
File "mypy/newsemanal/semanal.py", line 1131, in apply_class_plugin_hooks
File "/venv/site-packages/mypy_django_plugin/main.py", line 33, in transform_model_class
process_model_class(ctx, django_context)
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 228, in process_model_class
initializer_cls(ctx, django_context).run()
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 60, in run
self.run_with_model_cls(model_cls)
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 104, in run_with_model_cls
rel_primary_key_field = self.django_context.get_primary_key_field(related_model_cls)
File "/venv/site-packages/mypy_django_plugin/django/context.py", line 231, in get_primary_key_field
raise ValueError('No primary key defined')

# Fixed code
def get_base_class_hook(
    self, fullname: str
) -> Optional[Callable[[ClassDefContext], None]]:
    if (
        fullname in self.django_context.all_registered_model_class_fullnames
        or fullname in self._get_current_model_bases()
    ):
        return partial(transform_model_class, django_context=self.django_context)

    if fullname in self._get_current_manager_bases():
        return add_new_manager_base

    if fullname in self._get_current_form_bases():
        return transform_form_class
    return None
# Buggy code
def add_new_node_to_model_class(self, name: str, typ: MypyType) -> None:
    var = self.create_new_var(name, typ)
    self.model_classdef.info.names[name] = SymbolTableNode(
        MDEF, var, plugin_generated=True
    )


# Traceback (ValueError)
Traceback (most recent call last):
File "mypy/newsemanal/semanal.py", line 4550, in accept
File "mypy/nodes.py", line 921, in accept__Node_glue
File "mypy/nodes.py", line 922, in accept
File "mypy/newsemanal/semanal.py", line 989, in visit_class_def__StatementVisitor_glue
File "mypy/newsemanal/semanal.py", line 992, in visit_class_def
File "mypy/newsemanal/semanal.py", line 1063, in analyze_class
File "mypy/newsemanal/semanal.py", line 1072, in analyze_class_body_common
File "mypy/newsemanal/semanal.py", line 1131, in apply_class_plugin_hooks
File "/venv/site-packages/mypy_django_plugin/main.py", line 33, in transform_model_class
process_model_class(ctx, django_context)
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 228, in process_model_class
initializer_cls(ctx, django_context).run()
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 60, in run
self.run_with_model_cls(model_cls)
File "/venv/site-packages/mypy_django_plugin/transformers/models.py", line 104, in run_with_model_cls
rel_primary_key_field = self.django_context.get_primary_key_field(related_model_cls)
File "/venv/site-packages/mypy_django_plugin/django/context.py", line 231, in get_primary_key_field
raise ValueError('No primary key defined')

# Fixed code
def add_new_node_to_model_class(self, name: str, typ: MypyType) -> None:
    helpers.add_new_sym_for_info(self.model_classdef.info, name=name, sym_type=typ)
# Buggy code
def get_field_related_model_cls(
    self, field: Union[RelatedField, ForeignObjectRel]
) -> Type[Model]:
    if isinstance(field, RelatedField):
        related_model_cls = field.remote_field.model
    else:
        related_model_cls = field.field.model

    if isinstance(related_model_cls, str):
        if related_model_cls == "self":
            # same model
            related_model_cls = field.model
        elif "." not in related_model_cls:
            # same file model
            related_model_fullname = field.model.__module__ + "." + related_model_cls
            related_model_cls = self.get_model_class_by_fullname(related_model_fullname)
        else:
            related_model_cls = self.apps_registry.get_model(related_model_cls)

    return related_model_cls


# Traceback (AttributeError)
Traceback (most recent call last):
File "/usr/local/bin/mypy", line 10, in <module>
sys.exit(console_entry())
File "/usr/local/lib/python3.6/site-packages/mypy/__main__.py", line 8, in console_entry
main(None, sys.stdout, sys.stderr)
File "/usr/local/lib/python3.6/site-packages/mypy/main.py", line 83, in main
res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
File "/usr/local/lib/python3.6/site-packages/mypy/build.py", line 164, in build
result = _build(sources, options, alt_lib_path, flush_errors, fscache, stdout, stderr)
File "/usr/local/lib/python3.6/site-packages/mypy/build.py", line 224, in _build
graph = dispatch(sources, manager, stdout)
File "/usr/local/lib/python3.6/site-packages/mypy/build.py", line 2526, in dispatch
graph = load_graph(sources, manager)
File "/usr/local/lib/python3.6/site-packages/mypy/build.py", line 2748, in load_graph
caller_state=st, caller_line=st.dep_line_map.get(dep, 1))
File "/usr/local/lib/python3.6/site-packages/mypy/build.py", line 1772, in __init__
self.compute_dependencies()
File "/usr/local/lib/python3.6/site-packages/mypy/build.py", line 2059, in compute_dependencies
self.manager.plugin.get_additional_deps(self.tree))
File "/usr/local/lib/python3.6/site-packages/mypy/plugin.py", line 743, in get_additional_deps
deps.extend(plugin.get_additional_deps(file))
File "/usr/local/lib/python3.6/site-packages/mypy_django_plugin/main.py", line 152, in get_additional_deps
related_model_module = related_model_cls.__module__
AttributeError: 'NoneType' object has no attribute '__module__'

# Fixed code
def get_field_related_model_cls(
    self, field: Union[RelatedField, ForeignObjectRel]
) -> Optional[Type[Model]]:
    if isinstance(field, RelatedField):
        related_model_cls = field.remote_field.model
    else:
        related_model_cls = field.field.model

    if isinstance(related_model_cls, str):
        if related_model_cls == "self":
            # same model
            related_model_cls = field.model
        elif "." not in related_model_cls:
            # same file model
            related_model_fullname = field.model.__module__ + "." + related_model_cls
            related_model_cls = self.get_model_class_by_fullname(related_model_fullname)
        else:
            related_model_cls = self.apps_registry.get_model(related_model_cls)

    return related_model_cls