gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_path_to_ansible_inventory(self):
    venv_exe = os.path.join(self.venv_path, "bin", "ansible-inventory")
    if os.path.exists(venv_exe):
        return venv_exe
    return shutil.which("ansible-inventory")


# Traceback (RuntimeError)
stdout:
6.399 INFO     Updating inventory 239: Inventory - StaffSalary\ufffd
6.438 INFO     Reading Ansible inventory source: /awx_devel/awx/plugins/inventory/openstack_inventory.py
6.439 INFO     Using VIRTUAL_ENV: /venv/python2_ansible23/
6.439 INFO     Using PATH: /venv/python2_ansible23/bin:/venv/awx/bin:/venv/awx/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
6.439 INFO     Using PYTHONPATH: /venv/python2_ansible23/lib/python2.7/site-packages:
Traceback (most recent call last):
File "/usr/local/bin/awx-manage", line 9, in <module>
load_entry_point('awx', 'console_scripts', 'awx-manage')()
File "/awx_devel/awx/__init__.py", line 150, in manage
execute_from_command_line(sys.argv)
File "/venv/awx/lib64/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/venv/awx/lib64/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/venv/awx/lib64/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/venv/awx/lib64/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/awx_devel/awx/main/management/commands/inventory_import.py", line 1049, in handle
raise exc
File "/awx_devel/awx/main/management/commands/inventory_import.py", line 949, in handle
data = AnsibleInventoryLoader(source=source, is_custom=self.is_custom, venv_path=venv_path).load()
File "/awx_devel/awx/main/management/commands/inventory_import.py", line 194, in load
return self.command_to_json(base_args + ['--list'])
File "/awx_devel/awx/main/management/commands/inventory_import.py", line 171, in command_to_json
self.method, proc.returncode, raw_stdout, stderr))
RuntimeError: ansible-inventory failed (rc=1) with stdout:

stderr:
ERROR! Ansible sub-program not implemented: ansible-inventory

# Fixed code
def get_path_to_ansible_inventory(self):
    venv_exe = os.path.join(self.venv_path, "bin", "ansible-inventory")
    if os.path.exists(venv_exe):
        return venv_exe
    elif os.path.exists(os.path.join(self.venv_path, "bin", "ansible")):
        # if bin/ansible exists but bin/ansible-inventory doesn't, it's
        # probably a really old version of ansible that doesn't support
        # ansible-inventory
        raise RuntimeError(
            "{} does not exist (please upgrade to ansible >= 2.4)".format(venv_exe)
        )
    return shutil.which("ansible-inventory")
# Buggy code
def _default_steadystate_args():
    def_args = {
        "sparse": True,
        "use_rcm": False,
        "use_wbm": False,
        "weight": None,
        "use_precond": False,
        "all_states": False,
        "M": None,
        "x0": None,
        "drop_tol": 1e-4,
        "fill_factor": 100,
        "diag_pivot_thresh": None,
        "maxiter": 1000,
        "tol": 1e-12,
        "permc_spec": "COLAMD",
        "ILU_MILU": "smilu_2",
        "restart": 20,
        "return_info": False,
        "info": _empty_info_dict(),
        "verbose": False,
        "solver": "scipy",
    }

    return def_args


# Traceback (ValueError)
..................................................
======================================================================
ERROR: Steady state: Thermal qubit - power-gmres solver
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/shahnawaz/miniconda3/lib/python3.6/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/Users/shahnawaz/dev/qutip/qutip/tests/test_steadystate.py", line 145, in test_qubit_power_gmres
rho_ss = steadystate(H, c_op_list, method='power-gmres')
File "/Users/shahnawaz/dev/qutip/qutip/steadystate.py", line 298, in steadystate
return _steadystate_power(A, ss_args)
File "/Users/shahnawaz/dev/qutip/qutip/steadystate.py", line 863, in _steadystate_power
v = v / la.norm(v, np.inf)
File "/Users/shahnawaz/miniconda3/lib/python3.6/site-packages/scipy/linalg/misc.py", line 137, in norm
a = np.asarray_chkfinite(a)
File "/Users/shahnawaz/miniconda3/lib/python3.6/site-packages/numpy/lib/function_base.py", line 1233, in asarray_chkfinite
"array must not contain infs or NaNs")
ValueError: array must not contain infs or NaNs

----------------------------------------------------------------------
Ran 561 tests in 576.175s

FAILED (SKIP=19, errors=1)

# Fixed code
def _default_steadystate_args():
    def_args = {
        "sparse": True,
        "use_rcm": False,
        "use_wbm": False,
        "weight": None,
        "use_precond": False,
        "all_states": False,
        "M": None,
        "x0": None,
        "drop_tol": 1e-4,
        "fill_factor": 100,
        "diag_pivot_thresh": None,
        "maxiter": 1000,
        "tol": 1e-12,
        "matol": 1e-15,
        "mtol": None,
        "permc_spec": "COLAMD",
        "ILU_MILU": "smilu_2",
        "restart": 20,
        "return_info": False,
        "info": _empty_info_dict(),
        "verbose": False,
        "solver": "scipy",
    }

    return def_args
# Buggy code
def _mkl_steadystate_args():
    def_args = {
        "max_iter_refine": 10,
        "scaling_vectors": True,
        "weighted_matching": True,
        "return_info": False,
        "info": _empty_info_dict(),
        "verbose": False,
        "solver": "mkl",
        "use_rcm": False,
        "use_wbm": False,
        "weight": None,
        "tol": 1e-12,
        "maxiter": 1000,
    }

    return def_args


# Traceback (ValueError)
..................................................
======================================================================
ERROR: Steady state: Thermal qubit - power-gmres solver
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/shahnawaz/miniconda3/lib/python3.6/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/Users/shahnawaz/dev/qutip/qutip/tests/test_steadystate.py", line 145, in test_qubit_power_gmres
rho_ss = steadystate(H, c_op_list, method='power-gmres')
File "/Users/shahnawaz/dev/qutip/qutip/steadystate.py", line 298, in steadystate
return _steadystate_power(A, ss_args)
File "/Users/shahnawaz/dev/qutip/qutip/steadystate.py", line 863, in _steadystate_power
v = v / la.norm(v, np.inf)
File "/Users/shahnawaz/miniconda3/lib/python3.6/site-packages/scipy/linalg/misc.py", line 137, in norm
a = np.asarray_chkfinite(a)
File "/Users/shahnawaz/miniconda3/lib/python3.6/site-packages/numpy/lib/function_base.py", line 1233, in asarray_chkfinite
"array must not contain infs or NaNs")
ValueError: array must not contain infs or NaNs

----------------------------------------------------------------------
Ran 561 tests in 576.175s

FAILED (SKIP=19, errors=1)

# Fixed code
def _mkl_steadystate_args():
    def_args = {
        "max_iter_refine": 10,
        "scaling_vectors": True,
        "weighted_matching": True,
        "return_info": False,
        "info": _empty_info_dict(),
        "verbose": False,
        "solver": "mkl",
        "use_rcm": False,
        "use_wbm": False,
        "weight": None,
        "tol": 1e-12,
        "matol": 1e-15,
        "mtol": None,
        "maxiter": 1000,
    }

    return def_args
# Buggy code
def _blas_info():
    config = np.__config__
    blas_info = config.blas_opt_info
    blas = None
    if hasattr(config, "mkl_info") or any(
        "mkl" in lib for lib in blas_info["libraries"]
    ):
        blas = "INTEL MKL"
    elif hasattr(config, "openblas_info") or any(
        "openblas" in lib for lib in blas_info["libraries"]
    ):
        blas = "OPENBLAS"
    elif "extra_link_args" in blas_info.keys() and (
        "-Wl,Accelerate" in blas_info["extra_link_args"]
    ):
        blas = "Accelerate"
    else:
        blas = "Generic"
    return blas


# Traceback (KeyError)
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import qutip
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/oliviadimatteo/tomo_test/qutip/qutip/__init__.py", line 174, in <module>
import qutip._mkl
File "/Users/oliviadimatteo/tomo_test/qutip/qutip/_mkl/__init__.py", line 3, in <module>
_set_mkl()
File "/Users/oliviadimatteo/tomo_test/qutip/qutip/_mkl/utilities.py", line 47, in _set_mkl
if _blas_info() == 'INTEL MKL':
File "/Users/oliviadimatteo/tomo_test/qutip/qutip/utilities.py", line 405, in _blas_info
if hasattr(config,'mkl_info') or any('mkl' in lib for lib in blas_info['libraries']):
KeyError: 'libraries'

# Fixed code
def _blas_info():
    config = np.__config__
    blas_info = config.blas_opt_info
    _has_lib_key = "libraries" in blas_info.keys()
    blas = None
    if hasattr(config, "mkl_info") or (
        _has_lib_key and any("mkl" in lib for lib in blas_info["libraries"])
    ):
        blas = "INTEL MKL"
    elif hasattr(config, "openblas_info") or (
        _has_lib_key and any("openblas" in lib for lib in blas_info["libraries"])
    ):
        blas = "OPENBLAS"
    elif "extra_link_args" in blas_info.keys() and (
        "-Wl,Accelerate" in blas_info["extra_link_args"]
    ):
        blas = "Accelerate"
    else:
        blas = "Generic"
    return blas
# Buggy code
def __div__(self, other):
    """
    DIVISION (by numbers only)
    """
    if isinstance(other, Qobj):  # if both are quantum objects
        raise TypeError(
            "Incompatible Qobj shapes " + "[division with Qobj not implemented]"
        )

    if isinstance(other, (int, float, complex, np.int64)):
        out = Qobj(type=self.type)
        out.data = self.data / other
        out.dims = self.dims
        out.shape = self.shape
        if isinstance(other, (int, float, np.int64)):
            out._isherm = self._isherm
        else:
            out._isherm = out.isherm

        return out.tidyup() if qset.auto_tidyup else out

    else:
        raise TypeError("Incompatible object for division")


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def __div__(self, other):
    """
    DIVISION (by numbers only)
    """
    if isinstance(other, Qobj):  # if both are quantum objects
        raise TypeError(
            "Incompatible Qobj shapes " + "[division with Qobj not implemented]"
        )

    if isinstance(other, (int, float, complex, np.int64)):
        out = Qobj()
        out.data = self.data / other
        out.dims = self.dims
        out.shape = self.shape
        if isinstance(other, (int, float, np.int64)):
            out._isherm = self._isherm
        else:
            out._isherm = out.isherm

        return out.tidyup() if qset.auto_tidyup else out

    else:
        raise TypeError("Incompatible object for division")
# Buggy code
def __neg__(self):
    """
    NEGATION operation.
    """
    out = Qobj()
    out.data = -self.data
    out.dims = self.dims
    out.shape = self.shape
    out.type = self.type
    out._isherm = self._isherm
    return out.tidyup() if qset.auto_tidyup else out


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def __neg__(self):
    """
    NEGATION operation.
    """
    out = Qobj()
    out.data = -self.data
    out.dims = self.dims
    out.shape = self.shape
    out.superrep = self.superrep
    out._isherm = self._isherm
    return out.tidyup() if qset.auto_tidyup else out
# Buggy code
def dag(self):
    """Adjoint operator of quantum object."""
    out = Qobj()
    out.data = self.data.T.conj().tocsr()
    out.dims = [self.dims[1], self.dims[0]]
    out.shape = [self.shape[1], self.shape[0]]
    out._isherm = self._isherm
    out.type = _typecheck(out)
    return out


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def dag(self):
    """Adjoint operator of quantum object."""
    out = Qobj()
    out.data = self.data.T.conj().tocsr()
    out.dims = [self.dims[1], self.dims[0]]
    out.shape = [self.shape[1], self.shape[0]]
    out._isherm = self._isherm
    return out
# Buggy code
def conj(self):
    """Conjugate operator of quantum object."""
    out = Qobj(type=self.type)
    out.data = self.data.conj()
    out.dims = [self.dims[1], self.dims[0]]
    out.shape = [self.shape[1], self.shape[0]]
    return out


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def conj(self):
    """Conjugate operator of quantum object."""
    out = Qobj()
    out.data = self.data.conj()
    out.dims = [self.dims[1], self.dims[0]]
    out.shape = [self.shape[1], self.shape[0]]
    return out
# Buggy code
def trans(self):
    """Transposed operator.

    Returns
    -------
    oper : qobj
        Transpose of input operator.

    """
    out = Qobj()
    out.data = self.data.T.tocsr()
    out.dims = [self.dims[1], self.dims[0]]
    out.shape = [self.shape[1], self.shape[0]]
    out.type = _typecheck(out)
    return out


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def trans(self):
    """Transposed operator.

    Returns
    -------
    oper : qobj
        Transpose of input operator.

    """
    out = Qobj()
    out.data = self.data.T.tocsr()
    out.dims = [self.dims[1], self.dims[0]]
    out.shape = [self.shape[1], self.shape[0]]
    return out
# Buggy code
def iscp(self):
    # FIXME: this needs to be cached in the same ways as isherm.
    if self.type == "super" or self.type == "oper":
        try:
            q_oper = sr.to_choi(self)
            eigs = q_oper.eigenenergies()
            return all(eigs >= 0)
        except:
            return False
    else:
        return False


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def iscp(self):
    # FIXME: this needs to be cached in the same ways as isherm.
    if self.type in ["super", "oper"]:
        try:
            q_oper = sr.to_choi(self)
            eigs = q_oper.eigenenergies()
            return all(eigs >= 0)
        except:
            return False
    else:
        return False
# Buggy code
def istp(self):
    if self.type == "super" or self.type == "oper":
        try:
            q_oper = sr.to_choi(self)
            # We use the condition from John Watrous' lecture notes,
            # Tr_1(J(Phi)) = identity_2.
            tr_oper = ptrace(q_oper, (0,))
            ident = ops.identity(tr_oper.shape[0])

            return isequal(tr_oper, ident)
        except:
            return False
    else:
        return False


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def istp(self):
    if self.type in ["super", "oper"]:
        try:
            q_oper = sr.to_choi(self)
            # We use the condition from John Watrous' lecture notes,
            # Tr_1(J(Phi)) = identity_2.
            tr_oper = ptrace(q_oper, (0,))
            ident = ops.identity(tr_oper.shape[0])

            return isequal(tr_oper, ident)
        except:
            return False
    else:
        return False
# Buggy code
def iscptp(self):
    if self.type == "super" or self.type == "oper":
        q_oper = sr.to_choi(self)
        return q_oper.iscp and q_oper.istp
    else:
        return False


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def iscptp(self):
    if self.type in ["super", "oper"]:
        q_oper = sr.to_choi(self)
        return q_oper.iscp and q_oper.istp
    else:
        return False
# Buggy code
def isbra(self):
    return isinstance(self.dims[1], list) and np.prod(self.dims[0]) == 1


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def isbra(self):
    return (
        np.prod(self.dims[0]) == 1
        and isinstance(self.dims[1], list)
        and isinstance(self.dims[1][0], int)
    )
# Buggy code
def isket(self):
    return isinstance(self.dims[0], list) and np.prod(self.dims[1]) == 1


# Traceback (TypeError)
rho_psi = operator_to_vector(Qobj(np.diag(np.array([0.9, 0.1], dtype=complex))))>>> E_psi = rho_psi.dag()
S = to_super(sigmax())
(E_psi * S) * rho_psi
Traceback (most recent call last):
File "<ipython-input-22-90cbfac2a43e>", line 1, in <module>
(E_psi * S) * rho_psi
File "qutip/qobj.py", line 416, in __mul__
raise TypeError("Incompatible Qobj shapes")
TypeError: Incompatible Qobj shapes

E_psi * (S * rho_psi)
Quantum object: dims = [[1], [1]], shape = [1, 1], type = oper, isherm = True
Qobj data =
[[ 0.18]]
E_psi
Quantum object: dims = [[1], [[2], [2]]], shape = [1, 4], type = bra
Qobj data =
[[ 0.9  0.   0.   0.1]]
rho_psi
Quantum object: dims = [[[2], [2]], [1]], shape = [4, 1], type = operator-vector
Qobj data =
[[ 0.9]
[ 0. ]
[ 0. ]
[ 0.1]]
S
Quantum object: dims = [[[2], [2]], [[2], [2]]], shape = [4, 4], type = super, isherm = True
Qobj data =
[[ 0.  0.  0.  1.]
[ 0.  0.  1.  0.]
[ 0.  1.  0.  0.]
[ 1.  0.  0.  0.]]

# Fixed code
def isket(self):
    return (
        np.prod(self.dims[1]) == 1
        and isinstance(self.dims[0], list)
        and isinstance(self.dims[0][0], int)
    )
# Buggy code
def cancel(self, engine):
    if self.stopped:
        return
    self.stopped = True

    if self.result.cancelled():
        engine.send_line("?")

    if ponder:
        engine.send_line("easy")

        n = id(self) & 0xFFFF
        self.final_pong = "pong {}".format(n)
        engine._ping(n)


# Traceback (asyncio.futures.InvalidStateError)
Exception in callback EngineProtocol.pipe_data_received(1, b'you play bo...Drawn game}\n')
handle: <Handle EngineProtocol.pipe_data_received(1, b'you play bo...Drawn game}\n')>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/events.py", line 126, in _run
self._callback(*self._args)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 602, in pipe_data_received
self._line_received(line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 615, in _line_received
self.command._line_received(self, line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 869, in _line_received
self.line_received(engine, line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 1716, in line_received
self._move(engine, line.split(" ", 1)[1])
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 1748, in _move
self.result.set_result(PlayResult(move, None, self.info, self.draw_offered))
File "/usr/lib/python3.5/asyncio/futures.py", line 348, in set_result
raise InvalidStateError('{}: {!r}'.format(self._state, self))
asyncio.futures.InvalidStateError: FINISHED: <Future finished result=<PlayResult a...ffered=False)>>
Traceback (most recent call last):
File "./tournament.py", line 96, in <module>
board.push(result.move)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/__init__.py", line 1942, in push
move = self._to_chess960(move)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/__init__.py", line 3318, in _to_chess960
if move.from_square == E1 and self.kings &amp; BB_E1:
AttributeError: 'NoneType' object has no attribute 'from_square'

# Fixed code
def cancel(self, engine):
    if self.stopped:
        return
    self.stopped = True

    if self.result.cancelled():
        engine.send_line("?")

    if ponder:
        engine.send_line("easy")

        n = (id(self) + 1) & 0xFFFF
        self.pong_after_ponder = "pong {}".format(n)
        engine._ping(n)
# Buggy code
def _move(self, engine, arg):
    if not self.result.cancelled():
        try:
            move = engine.board.push_xboard(arg)
        except ValueError as err:
            self.result.set_exception(EngineError(err))
        else:
            self.result.set_result(
                PlayResult(move, None, self.info, draw_offered=self.draw_offered)
            )

    if not ponder:
        self.end(engine)


# Traceback (asyncio.futures.InvalidStateError)
Exception in callback EngineProtocol.pipe_data_received(1, b'you play bo...Drawn game}\n')
handle: <Handle EngineProtocol.pipe_data_received(1, b'you play bo...Drawn game}\n')>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/events.py", line 126, in _run
self._callback(*self._args)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 602, in pipe_data_received
self._line_received(line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 615, in _line_received
self.command._line_received(self, line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 869, in _line_received
self.line_received(engine, line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 1716, in line_received
self._move(engine, line.split(" ", 1)[1])
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 1748, in _move
self.result.set_result(PlayResult(move, None, self.info, self.draw_offered))
File "/usr/lib/python3.5/asyncio/futures.py", line 348, in set_result
raise InvalidStateError('{}: {!r}'.format(self._state, self))
asyncio.futures.InvalidStateError: FINISHED: <Future finished result=<PlayResult a...ffered=False)>>
Traceback (most recent call last):
File "./tournament.py", line 96, in <module>
board.push(result.move)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/__init__.py", line 1942, in push
move = self._to_chess960(move)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/__init__.py", line 3318, in _to_chess960
if move.from_square == E1 and self.kings &amp; BB_E1:
AttributeError: 'NoneType' object has no attribute 'from_square'

# Fixed code
def _move(self, engine, arg):
    if not self.result.done() and self.play_result.move is None:
        try:
            self.play_result.move = engine.board.push_xboard(arg)
        except ValueError as err:
            self.result.set_exception(EngineError(err))
        else:
            self._ping_after_move(engine)
    else:
        try:
            engine.board.push_xboard(arg)
        except ValueError:
            LOGGER.exception("exception playing unexpected move")
# Buggy code
def _post(self, engine, line):
    if not self.result.done():
        self.info = _parse_xboard_post(line, engine.board, info)


# Traceback (asyncio.futures.InvalidStateError)
Exception in callback EngineProtocol.pipe_data_received(1, b'you play bo...Drawn game}\n')
handle: <Handle EngineProtocol.pipe_data_received(1, b'you play bo...Drawn game}\n')>
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/events.py", line 126, in _run
self._callback(*self._args)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 602, in pipe_data_received
self._line_received(line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 615, in _line_received
self.command._line_received(self, line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 869, in _line_received
self.line_received(engine, line)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 1716, in line_received
self._move(engine, line.split(" ", 1)[1])
File "/home/pascal/.local/lib/python3.5/site-packages/chess/engine.py", line 1748, in _move
self.result.set_result(PlayResult(move, None, self.info, self.draw_offered))
File "/usr/lib/python3.5/asyncio/futures.py", line 348, in set_result
raise InvalidStateError('{}: {!r}'.format(self._state, self))
asyncio.futures.InvalidStateError: FINISHED: <Future finished result=<PlayResult a...ffered=False)>>
Traceback (most recent call last):
File "./tournament.py", line 96, in <module>
board.push(result.move)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/__init__.py", line 1942, in push
move = self._to_chess960(move)
File "/home/pascal/.local/lib/python3.5/site-packages/chess/__init__.py", line 3318, in _to_chess960
if move.from_square == E1 and self.kings &amp; BB_E1:
AttributeError: 'NoneType' object has no attribute 'from_square'

# Fixed code
def _post(self, engine, line):
    if not self.result.done():
        self.play_result.info = _parse_xboard_post(line, engine.board, info)
# Buggy code
async def content_as_text(self, max_concurrency=1, encoding="UTF-8"):
    """Download the contents of this blob, and decode as text.

    This operation is blocking until all data is downloaded.

    :keyword int max_concurrency:
        The number of parallel connections with which to download.
    :param str encoding:
        Test encoding to decode the downloaded bytes. Default is UTF-8.
    :rtype: str
    """
    warnings.warn(
        "content_as_text is deprecated, use readall instead", DeprecationWarning
    )
    self._max_concurrency = max_concurrency
    self._encoding = encoding
    return await self.readall()


# Traceback (azure.storage.blob._generated.models._models_py3.StorageErrorException)
ERROR:Task exception was never retrieved

future: <Task finished coro=<_AsyncChunkDownloader.process_chunk() done, defined at /usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py:53> exception=ResourceModifiedError('The condition specified using HTTP conditional header(s) is not met.\nRequestId:XXX\nTime:2020-10-06T03:09:34.2866006Z\nErrorCode:ConditionNotMet\nError:None',)>

Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py", line 101, in _download_chunk
**self.request_options
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/_generated/aio/operations_async/_blob_operations_async.py", line 180, in download
raise models.StorageErrorException(response, self._deserialize)
azure.storage.blob._generated.models._models_py3.StorageErrorException: Operation returned an invalid status 'The condition specified using HTTP conditional header(s) is not met.'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py", line 55, in process_chunk
chunk_data = await self._download_chunk(chunk_start, chunk_end - 1)
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py", line 104, in _download_chunk
process_storage_error(error)
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/_shared/response_handlers.py", line 147, in process_storage_error
raise error
azure.core.exceptions.ResourceModifiedError: The condition specified using HTTP conditional header(s) is not met.
Time:2020-10-06T03:09:34.2866006Z
ErrorCode:ConditionNotMet
Error:None

# Fixed code
async def content_as_text(self, max_concurrency=1, encoding="UTF-8"):
    """Download the contents of this blob, and decode as text.

    This operation is blocking until all data is downloaded.

    :param int max_concurrency:
        The number of parallel connections with which to download.
    :param str encoding:
        Test encoding to decode the downloaded bytes. Default is UTF-8.
    :rtype: str
    """
    warnings.warn(
        "content_as_text is deprecated, use readall instead", DeprecationWarning
    )
    self._max_concurrency = max_concurrency
    self._encoding = encoding
    return await self.readall()
# Buggy code
async def download_to_stream(self, stream, max_concurrency=1):
    """Download the contents of this blob to a stream.

    :param stream:
        The stream to download to. This can be an open file-handle,
        or any writable stream. The stream must be seekable if the download
        uses more than one parallel connection.
    :returns: The properties of the downloaded blob.
    :rtype: Any
    """
    warnings.warn(
        "download_to_stream is deprecated, use readinto instead", DeprecationWarning
    )
    self._max_concurrency = max_concurrency
    await self.readinto(stream)
    return self.properties


# Traceback (azure.storage.blob._generated.models._models_py3.StorageErrorException)
ERROR:Task exception was never retrieved

future: <Task finished coro=<_AsyncChunkDownloader.process_chunk() done, defined at /usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py:53> exception=ResourceModifiedError('The condition specified using HTTP conditional header(s) is not met.\nRequestId:XXX\nTime:2020-10-06T03:09:34.2866006Z\nErrorCode:ConditionNotMet\nError:None',)>

Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py", line 101, in _download_chunk
**self.request_options
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/_generated/aio/operations_async/_blob_operations_async.py", line 180, in download
raise models.StorageErrorException(response, self._deserialize)
azure.storage.blob._generated.models._models_py3.StorageErrorException: Operation returned an invalid status 'The condition specified using HTTP conditional header(s) is not met.'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py", line 55, in process_chunk
chunk_data = await self._download_chunk(chunk_start, chunk_end - 1)
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/aio/_download_async.py", line 104, in _download_chunk
process_storage_error(error)
File "/usr/local/lib/python3.6/dist-packages/azure/storage/blob/_shared/response_handlers.py", line 147, in process_storage_error
raise error
azure.core.exceptions.ResourceModifiedError: The condition specified using HTTP conditional header(s) is not met.
Time:2020-10-06T03:09:34.2866006Z
ErrorCode:ConditionNotMet
Error:None

# Fixed code
async def download_to_stream(self, stream, max_concurrency=1):
    """Download the contents of this blob to a stream.

    :param stream:
        The stream to download to. This can be an open file-handle,
        or any writable stream. The stream must be seekable if the download
        uses more than one parallel connection.
    :param int max_concurrency:
        The number of parallel connections with which to download.
    :returns: The properties of the downloaded blob.
    :rtype: Any
    """
    warnings.warn(
        "download_to_stream is deprecated, use readinto instead", DeprecationWarning
    )
    self._max_concurrency = max_concurrency
    await self.readinto(stream)
    return self.properties
# Buggy code
def op_count(
    self, op_type: Optional[str] = None, precision: Optional[int] = None
) -> Optional[int]:
    if op_type != "mac":
        raise ValueError("Currently only counting of MAC-operations is supported.")

    if isinstance(self._layer, op_count_supported_layer_types):
        count = 0
        for op in self.op_profiles:
            if (precision is None or op.precision == precision) and (
                op_type is None or op.op_type == op_type
            ):
                count += op.n
        return count
    return None


# Traceback (TypeError)
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/BNN-Playground/summary_bug.py", line 68, in <module>
cli()
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\zookeeper\core\task.py", line 59, in command
task_instance.run()
File "C:/Users/User/PycharmProjects/BNN-Playground/summary_bug.py", line 64, in run
larq.models.summary(model)
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 466, in summary
model_profile = ModelProfile(model)
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 261, in __init__
self.layer_profiles = [LayerProfile(l) for l in model.layers]
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 261, in <listcomp>
self.layer_profiles = [LayerProfile(l) for l in model.layers]
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 158, in __init__
n=p.count * self.output_pixels,
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 227, in output_pixels
if len(self.output_shape) == 4:
TypeError: object of type 'NoneType' has no len()

# Fixed code
def op_count(
    self, op_type: Optional[str] = None, precision: Optional[int] = None
) -> Optional[int]:
    if op_type != "mac":
        raise ValueError("Currently only counting of MAC-operations is supported.")

    if isinstance(self._layer, op_count_supported_layer_types) and self.output_pixels:
        count = 0
        for op in self.op_profiles:
            if (precision is None or op.precision == precision) and (
                op_type is None or op.op_type == op_type
            ):
                count += op.n
        return count
    return None
# Buggy code
def output_pixels(self) -> int:
    """Number of pixels for a single feature map (1 for fully connected layers)."""
    if len(self.output_shape) == 4:
        return int(np.prod(self.output_shape[1:3]))
    elif len(self.output_shape) == 2:
        return 1
    else:
        raise NotImplementedError()


# Traceback (TypeError)
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/BNN-Playground/summary_bug.py", line 68, in <module>
cli()
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\User\Anaconda3\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Users\User\Anaconda3\lib\site-packages\zookeeper\core\task.py", line 59, in command
task_instance.run()
File "C:/Users/User/PycharmProjects/BNN-Playground/summary_bug.py", line 64, in run
larq.models.summary(model)
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 466, in summary
model_profile = ModelProfile(model)
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 261, in __init__
self.layer_profiles = [LayerProfile(l) for l in model.layers]
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 261, in <listcomp>
self.layer_profiles = [LayerProfile(l) for l in model.layers]
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 158, in __init__
n=p.count * self.output_pixels,
File "C:\Users\User\Anaconda3\lib\site-packages\larq\models.py", line 227, in output_pixels
if len(self.output_shape) == 4:
TypeError: object of type 'NoneType' has no len()

# Fixed code
def output_pixels(self) -> Optional[int]:
    """Number of pixels for a single feature map (1 for fully connected layers)."""
    if not self.output_shape:
        return None
    if len(self.output_shape) == 4:
        return int(np.prod(self.output_shape[1:3]))
    if len(self.output_shape) == 2:
        return 1
    raise NotImplementedError()
# Buggy code
def try_get(keys, dictionary):
    for key in keys:
        if key in dictionary:
            ret = dictionary[key]
            if type(ret) == list:
                ret = ret[0]
            return ret
    return None


# Traceback (TypeError)
"""
Traceback (most recent call last):
File "/usr/lib/python3.8/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
File "/home/fabio/src/git_repositories/FARM/farm/infer.py", line 569, in _create_datasets_chunkwise
dataset, tensor_names, baskets = processor.dataset_from_dicts(dicts, indices, return_baskets=True)
File "/home/fabio/src/git_repositories/FARM/farm/data_handler/processor.py", line 361, in dataset_from_dicts
id_external = self._id_from_dict(d)
File "/home/fabio/src/git_repositories/FARM/farm/data_handler/processor.py", line 403, in _id_from_dict
ext_id = try_get(ID_NAMES, d["qas"][0])
File "/home/fabio/src/git_repositories/FARM/farm/utils.py", line 432, in try_get
ret = dictionary[key]
TypeError: string indices must be integers
"""

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

Traceback (most recent call last):
File "/home/fabio/src/git_repositories/FARM/examples/natural_questions.py", line 142, in <module>
question_answering()
File "/home/fabio/src/git_repositories/FARM/examples/natural_questions.py", line 135, in question_answering
result = model.inference_from_dicts(dicts=QA_input, return_json=False) # result is a list of QAPred objects
File "/home/fabio/src/git_repositories/FARM/farm/infer.py", line 696, in inference_from_dicts
return Inferencer.inference_from_dicts(self, dicts, return_json=return_json,
File "/home/fabio/src/git_repositories/FARM/farm/infer.py", line 474, in inference_from_dicts
return list(predictions)
File "/home/fabio/src/git_repositories/FARM/farm/infer.py", line 545, in _inference_with_multiprocessing
for dataset, tensor_names, baskets in results:
File "/usr/lib/python3.8/multiprocessing/pool.py", line 865, in next
raise value
TypeError: string indices must be integers

# Fixed code
def try_get(keys, dictionary):
    try:
        for key in keys:
            if key in dictionary:
                ret = dictionary[key]
                if type(ret) == list:
                    ret = ret[0]
                return ret
    except Exception as e:
        logger.warning(f"Cannot extract from dict {dictionary} with error: {e}")
    return None