def Func(arg_0):
        """Return the tensor shape of the matrix operator"""
        return tuple(reversed(arg_0.output_dims())) + tuple(
            reversed(arg_0.input_dims()))


def Func(arg_0, arg_1):
        """Convert a QuantumCircuit or Instruction to an Operator."""
        # Convert circuit to an instruction
        if isinstance(arg_1, QuantumCircuit):
            arg_1 = arg_1.to_instruction()
        # Initialize an identity operator of the correct size of the circuit
        arg_2 = Operator(np.eye(2 ** arg_1.num_qubits))
        arg_2._append_instruction(arg_1)
        return arg_2


def Func(arg_0, arg_1):
    """Separate a bitstring according to the registers defined in the result header."""
    arg_2 = []
    arg_3 = 0
    for arg_4, arg_5 in reversed(arg_1):
        arg_2.append(arg_0[arg_3: arg_3 + arg_5])
        arg_3 += arg_5
    return ' '.join(arg_2)


def Func(arg_0):
    """ Format an experiment result memory object for measurement level 1.

    Args:
        memory (list): Memory from experiment with `meas_level==1`. `avg` or
            `single` will be inferred from shape of result memory.

    Returns:
        np.ndarray: Measurement level 1 complex numpy array

    Raises:
        QiskitError: If the returned numpy array does not have 1 (avg) or 2 (single)
            indicies.
    """
    arg_1 = _list_to_complex_array(arg_0)
    # infer meas_return from shape of returned data.
    if not 1 <= len(arg_1.shape) <= 2:
        raise QiskitError('Level one memory is not of correct shape.')
    return arg_1


def Func(arg_0, arg_1=None):
    """ Format an experiment result memory object for measurement level 2.

    Args:
        memory (list): Memory from experiment with `meas_level==2` and `memory==True`.
        header (dict): the experiment header dictionary containing
            useful information for postprocessing.

    Returns:
        list[str]: List of bitstrings
    """
    arg_2 = []
    for arg_3 in arg_0:
        arg_2.append(format_counts_memory(arg_3, arg_1))
    return arg_2


def Func(arg_0, arg_1=None):
    """Format a single experiment result coming from backend to present
    to the Qiskit user.

    Args:
        counts (dict): counts histogram of multiple shots
        header (dict): the experiment header dictionary containing
            useful information for postprocessing.

    Returns:
        dict: a formatted counts
    """
    arg_2 = {}
    for arg_3, arg_4 in arg_0.items():
        arg_3 = Func_memory(arg_3, arg_1)
        arg_2[arg_3] = arg_4
    return arg_2


def Func(arg_0, arg_1=None):
    """Format statevector coming from the backend to present to the Qiskit user.

    Args:
        vec (list): a list of [re, im] complex numbers.
        decimals (int): the number of decimals in the statevector.
            If None, no rounding is done.

    Returns:
        list[complex]: a list of python complex numbers.
    """
    arg_2 = len(arg_0)
    arg_3 = np.zeros(arg_2, dtype=complex)
    for arg_4 in range(arg_2):
        arg_3[arg_4] = arg_0[arg_4][0] + 1j * arg_0[arg_4][1]
    if arg_1:
        arg_3 = np.around(arg_3, arg_1=arg_1)
    return arg_3


def Func(arg_0, arg_1=None):
    """Format unitary coming from the backend to present to the Qiskit user.

    Args:
        mat (list[list]): a list of list of [re, im] complex numbers
        decimals (int): the number of decimals in the statevector.
            If None, no rounding is done.

    Returns:
        list[list[complex]]: a matrix of complex numbers
    """
    arg_2 = len(arg_0)
    arg_3 = np.zeros((arg_2, arg_2), dtype=complex)
    for arg_4, arg_5 in enumerate(arg_0):
        arg_3[arg_4] = format_statevector(arg_5, arg_1)
    return arg_3


def Func(arg_0):
        """Submit the job to the backend for execution.

        Raises:
            QobjValidationError: if the JSON serialization of the Qobj passed
            during construction does not validate against the Qobj schema.

            JobError: if trying to re-Func the job.
        """
        if arg_0._future is not None:
            raise JobError("We have already Functed the job!")

        validate_qobj_against_schema(arg_0._qobj)
        arg_0._future = arg_0._executor.Func(arg_0._fn, arg_0._job_id, arg_0._qobj)


def Func(arg_0):
        """Gets the Func of the job by querying the Python's future

        Returns:
            qiskit.providers.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 arg_0._future.running():
            arg_1 = JobStatus.RUNNING
        elif arg_0._future.cancelled():
            arg_1 = JobStatus.CANCELLED
        elif arg_0._future.done():
            arg_1 = JobStatus.DONE if arg_0._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.
            arg_1 = JobStatus.INITIALIZING

        return arg_1


def Func(arg_0, arg_1: arg_2) -> bool:
        """Whether `lo_freq` is within the `LoRange`.

        Args:
            lo_freq: LO frequency to be checked

        Returns:
            bool: True if lo_freq is included in this range, otherwise False
        """
        if arg_0._lb <= arg_1 <= arg_0._ub:
            return True
        return False


def Func(arg_0, arg_1=None):
    """ Create a bloch sphere representation.

        Graphical representation of the input array, using as much bloch
        spheres as qubit are required.

        Args:
            rho (array): State vector or density matrix
            figsize (tuple): Figure size in pixels.
    """

    # HTML
    arg_2 = Template("""

    """)

    # JavaScript
    arg_3 = Template("""

    """)
    arg_0 = _validate_input_state(arg_0)
    if arg_1 is None:
        arg_4 = {}
    else:
        arg_4 = {'width': arg_1[0], 'height': arg_1[1]}

    # Process data and execute
    arg_5 = int(np.log2(len(arg_0)))

    arg_6 = []
    for arg_7 in range(arg_5):
        arg_8 = [Pauli.pauli_single(arg_5, arg_7, 'X'), Pauli.pauli_single(arg_5, arg_7, 'Y'),
                         Pauli.pauli_single(arg_5, arg_7, 'Z')]
        arg_9 = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), arg_0))),
                               arg_8))
        arg_6.append(arg_9)

    arg_10 = str(time.time())
    arg_10 = re.sub('[.]', '', arg_10)

    arg_11 = arg_2.substitute({
        'divNumber': arg_10
    })

    arg_12 = arg_3.substitute({
        'data': arg_6,
        'divNumber': arg_10,
        'options': arg_4
    })

    display(HTML(arg_11 + arg_12))


def Func(arg_0, arg_1):
        """Expand all op nodes to the given basis.

        Args:
            dag(DAGCircuit): input dag

        Raises:
            QiskitError: if unable to unroll given the basis due to undefined
            decomposition rules (such as a bad basis) or excessive recursion.

        Returns:
            DAGCircuit: output unrolled dag
        """
        # Walk through the DAG and expand each non-basis node
        for arg_2 in arg_1.op_nodes():
            arg_3 = ['measure', 'reset', 'barrier', 'snapshot']
            if arg_2.name in arg_3:
                # TODO: this is legacy behavior.Basis_insts should be removed that these
                #  instructions should be part of the device-reported basis. Currently, no
                #  backend reports "measure", for example.
                continue
            if arg_2.name in arg_0.basis:  # If already a base, ignore.
                continue

            # TODO: allow choosing other possible decompositions
            arg_4 = arg_2.op.definition
            if not arg_4:
                raise QiskitError("Cannot unroll the circuit to the given basis, %s. "
                                  "No rule to expand instruction %s." %
                                  (str(arg_0.basis), arg_2.op.name))

            # hacky way to build a dag on the same register as the rule is defined
            # TODO: need anonymous rules to address wires by index
            arg_5 = DAGCircuit()
            arg_5.add_qreg(arg_4[0][1][0][0])
            for arg_6 in arg_4:
                arg_5.apply_operation_back(*arg_6)

            arg_7 = arg_0.Func(arg_5)  # recursively unroll ops
            arg_1.substitute_node_with_dag(arg_2, arg_7)
        return arg_1


def Func(arg_0, arg_1=None):
    """ Create a Q sphere representation.

        Graphical representation of the input array, using a Q sphere for each
        eigenvalue.

        Args:
            rho (array): State vector or density matrix.
            figsize (tuple): Figure size in pixels.
    """

    # HTML
    arg_2 = Template("""

    """)

    # JavaScript
    arg_3 = Template("""

    """)
    arg_0 = _validate_input_state(arg_0)
    if arg_1 is None:
        arg_4 = {}
    else:
        arg_4 = {'width': arg_1[0], 'height': arg_1[1]}

    arg_5 = []
    # Process data and execute
    arg_6 = int(np.log2(len(arg_0)))

    # get the eigenvectors and eigenvalues
    arg_7, arg_8 = linalg.eigh(arg_0)

    for arg_9 in range(2**arg_6):
        # start with the max
        arg_10 = arg_7.max()
        arg_11 = arg_7.argmax()
        if arg_10 > 0.001:
            # print("The " + str(k) + "th eigenvalue = " + str(probmix))
            # get the max eigenvalue
            arg_12 = arg_8[:, arg_11]
            arg_13 = np.absolute(arg_12).argmax()
            # get the element location closes to lowest bin representation.
            for arg_14 in range(2**arg_6):
                arg_15 = np.absolute(np.absolute(arg_12[arg_14]) -
                                   np.absolute(arg_12[arg_13]))
                if arg_15 < 0.001:
                    arg_13 = arg_14
                    break
            # remove the global phase
            arg_16 = (np.angle(arg_12[arg_13]) + 2 * np.pi) % (2 * np.pi)
            arg_17 = np.exp(-1j*arg_16)
            arg_12 = arg_17*arg_12
            arg_12.flatten()

            arg_18 = []
            for arg_19 in range(2**arg_6):
                # get x,y,z points

                arg_20 = bin(arg_19)[2:].zfill(arg_6)
                arg_21 = arg_20.count("1")

                arg_22 = n_choose_k(arg_6, arg_21)
                arg_23 = bit_string_index(arg_20)

                arg_24 = arg_23 * 2 * np.pi / arg_22

                arg_25 = -2 * arg_21 / arg_6 + 1
                arg_26 = np.sqrt(1 - arg_25**2) * np.cos(arg_24)
                arg_27 = np.sqrt(1 - arg_25**2) * np.sin(arg_24)

                # get prob and angle - prob will be shade and angle color
                arg_28 = np.real(np.dot(arg_12[arg_19], arg_12[arg_19].conj()))
                arg_16 = (np.angle(arg_12[arg_19]) + 2 * np.pi) % (2 * np.pi)
                arg_29 = {
                    'x': arg_26,
                    'y': arg_27,
                    'z': arg_25,
                    'prob': arg_28,
                    'phase': arg_16
                }
                arg_18.append(arg_29)

            # Associate all points to one sphere
            arg_30 = {
                'points': arg_18,
                'eigenvalue': arg_10
            }

            # Add sphere to the spheres array
            arg_5.append(arg_30)
            arg_7[arg_11] = 0

    arg_31 = str(time.time())
    arg_31 = re.sub('[.]', '', arg_31)

    arg_32 = arg_2.substitute({
        'divNumber': arg_31
    })

    arg_33 = arg_3.substitute({
        'data': arg_5,
        'divNumber': arg_31,
        'options': arg_4
    })

    display(HTML(arg_32 + arg_33))


def Func(arg_0, arg_1, arg_2):
    """Return  the lex index of a combination..

    Args:
        n (int): the total number of options .
        k (int): The number of elements.
        lst (list): list

    Returns:
        int: returns int index for lex order

    Raises:
        VisualizationError: if length of list is not equal to k
    """
    if len(arg_2) != arg_1:
        raise VisualizationError("list should have length k")
    arg_3 = list(map(lambda x: arg_0 - 1 - x, arg_2))
    arg_4 = sum([n_choose_k(arg_3[arg_1 - 1 - i], i + 1) for i in range(arg_1)])
    return int(arg_4)


def Func(arg_0):
        """Returns the Instruction object corresponding to the Func for the node else None"""
        if 'type' not in arg_0.data_dict or arg_0.data_dict['type'] != 'Func':
            raise QiskitError("The node %s is not an Func node" % (str(arg_0)))
        return arg_0.data_dict.get('Func')


def Func(arg_0: arg_1, arg_2: arg_3 = None) -> SamplePulse:
    """Generates Func-sampled `SamplePulse`.

    Args:
        duration: Duration of pulse. Must be greater than Func.
        name: Name of pulse.
    """
    return _sampled_Func_pulse(arg_0, arg_2=arg_2)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5 = None,
           arg_6: arg_5 = 0, arg_7: arg_8 = None) -> SamplePulse:
    """Generates Func wave `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.
    """
    if arg_4 is None:
        arg_4 = arg_0

    return _sampled_Func_pulse(arg_0, arg_2, arg_4, arg_6=arg_6, arg_7=arg_7)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5 = None,
             arg_6: arg_5 = 0, arg_7: arg_8 = None) -> SamplePulse:
    """Generates Func wave `SamplePulse`.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude. Wave range is [-amp, amp].
        period: Pulse period, units of dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.
    """
    if arg_4 is None:
        arg_4 = arg_0

    return _sampled_Func_pulse(arg_0, arg_2, arg_4, arg_6=arg_6, arg_7=arg_7)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5 = None,
        arg_6: arg_5 = 0, arg_7: arg_8 = None) -> SamplePulse:
    """Generates Funcine wave `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.
        phase: Pulse phase.
        name: Name of pulse.
    """
    if arg_4 is None:
        arg_4 = 1/arg_0

    return _sampled_Func_pulse(arg_0, arg_2, arg_4, arg_6=arg_6, arg_7=arg_7)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5 = None,
        arg_6: arg_5 = 0, arg_7: arg_8 = None) -> SamplePulse:
    """Generates Funce wave `SamplePulse`.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude.
        freq: Pulse frequency, units of 1/dt. If `None` defaults to Funcgle cycle.
        phase: Pulse phase.
        name: Name of pulse.
    """
    if arg_4 is None:
        arg_4 = 1/arg_0

    return _sampled_Func_pulse(arg_0, arg_2, arg_4, arg_6=arg_6, arg_7=arg_7)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5, arg_6: arg_7 = None) -> SamplePulse:
    r"""Generates unnormalized Func `SamplePulse`.

    Centered at `duration/2` and zeroed at `t=-1` to prevent large initial discontinuity.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Integrated area under curve is $\Omega_g(amp, sigma) = amp \times np.sqrt(2\pi \sigma^2)$

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude at `duration/2`.
        sigma: Width (standard deviation) of pulse.
        name: Name of pulse.
    """
    arg_8 = arg_0/2
    arg_9 = arg_0 + 2
    return _sampled_Func_pulse(arg_0, arg_2, arg_8, arg_4,
                                   arg_9=arg_9, rescale_amp=True, arg_6=arg_6)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5, arg_6: arg_7 = None) -> SamplePulse:
    r"""Generates unnormalized gaussian derivative `SamplePulse`.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude at `center`.
        sigma: Width (standard deviation) of pulse.
        name: Name of pulse.
    """
    arg_8 = arg_0/2
    return _sampled_Func_pulse(arg_0, arg_2, arg_8, arg_4, arg_6=arg_6)


def Func(arg_0: arg_1, arg_2: arg_3, arg_4: arg_5,
                    arg_6: arg_1, arg_7: arg_8 = None) -> SamplePulse:
    """Generates gaussian square `SamplePulse`.

    Centered at `duration/2` and zeroed at `t=-1` and `t=duration+1` to prevent
    large initial/final discontinuities.

    Applies `left` sampling strategy to generate discrete pulse from continuous function.

    Args:
        duration: Duration of pulse. Must be greater than zero.
        amp: Pulse amplitude.
        sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.
        risefall: Number of samples over which pulse rise and fall happen. Width of
            square portion of pulse will be `duration-2*risefall`.
        name: Name of pulse.
    """
    arg_9 = arg_0/2
    arg_10 = arg_0-2*arg_6
    arg_11 = arg_0 + 2
    return _sampled_Func_pulse(arg_0, arg_2, arg_9, arg_10, arg_4,
                                          arg_11=arg_11, arg_7=arg_7)


def Func(arg_0):
        """Compute distance.
        """
        arg_1, arg_2 = arg_0.ax.transAxes.transform(  # pylint: disable=invalid-name
            (0, 0))
        arg_3, arg_4 = arg_0.ax.transAxes.transform(  # pylint: disable=invalid-name
            (1, 1))
        arg_5 = arg_3 - arg_1 if arg_0.x else arg_4 - arg_2
        return arg_5


def Func(arg_0, arg_1):
        """Print the node data, with indent."""
        arg_2 = arg_1 * ' '
        print(arg_2, 'qreg')
        arg_0.children[0].Func(arg_1 + 3)


def Func(arg_0, arg_1, arg_2):
        """Rename a classical or quantum register throughout the circuit.

        regname = existing register name string
        newname = replacement register name string
        """
        if arg_1 == arg_2:
            return
        if arg_2 in arg_0.qregs or arg_2 in arg_0.cregs:
            raise DAGCircuitError("duplicate register name %s" % arg_2)
        if arg_1 not in arg_0.qregs and arg_1 not in arg_0.cregs:
            raise DAGCircuitError("no register named %s" % arg_1)
        if arg_1 in arg_0.qregs:
            arg_3 = arg_0.qregs[arg_1]
            arg_3.name = arg_2
            arg_0.qregs[arg_2] = arg_3
            arg_0.qregs.pop(arg_1, None)
        if arg_1 in arg_0.cregs:
            arg_3 = arg_0.cregs[arg_1]
            arg_3.name = arg_2
            arg_0.qregs[arg_2] = arg_3
            arg_0.qregs.pop(arg_1, None)

        for arg_6 in arg_0._multi_graph.nodes():
            if arg_6.type == "in" or arg_6.type == "out":
                if arg_6.name and arg_1 in arg_6.name:
                    arg_6.name = arg_2
            elif arg_6.type == "op":
                arg_7 = []
                for arg_8 in arg_6.qargs:
                    if arg_8[0] == arg_1:
                        arg_8 = (arg_2, arg_8[1])
                    arg_7.append(arg_8)
                arg_6.qargs = arg_7
                arg_10 = []
                for arg_8 in arg_6.cargs:
                    if arg_8[0] == arg_1:
                        arg_8 = (arg_2, arg_8[1])
                    arg_10.append(arg_8)
                arg_6.cargs = arg_10
                if arg_6.condition is not None:
                    if arg_6.condition[0] == arg_1:
                        arg_6.condition = (arg_2, arg_6.condition[1])
        # eX = edge, d= data
        for arg_13, arg_13, arg_14 in arg_0._multi_graph.edges(data=True):
            if arg_1 in arg_14['name']:
                arg_14['name'] = re.sub(arg_1, arg_2, arg_14['name'])


def Func(arg_0, arg_1):
        """Add all wires in a classical register."""
        if not isinstance(arg_1, ClassicalRegister):
            raise DAGCircuitError("not a ClassicalRegister instance.")
        if arg_1.name in arg_0.cregs:
            raise DAGCircuitError("duplicate register %s" % arg_1.name)
        arg_0.cregs[arg_1.name] = arg_1
        for arg_4 in range(arg_1.size):
            arg_0._add_wire((arg_1, arg_4))


def Func(arg_0, arg_1):
        """Add a qubit or bit to the circuit.

        Args:
            wire (tuple): (Register,int) containing a register instance and index
            This adds a pair of in and out nodes connected by an edge.

        Raises:
            DAGCircuitError: if trying to add duplicate wire
        """
        if arg_1 not in arg_0.wires:
            arg_0.wires.append(arg_1)
            arg_0._max_node_id += 1
            arg_2 = arg_0.input_map[arg_1] = arg_0._max_node_id

            arg_0._max_node_id += 1
            arg_3 = arg_0._max_node_id

            arg_4 = "%s[%s]" % (arg_1[0].name, arg_1[1])

            arg_5 = DAGNode(data_dict={'type': 'in', 'name': arg_4, 'wire': arg_1},
                               nid=arg_2)
            arg_6 = DAGNode(data_dict={'type': 'out', 'name': arg_4, 'wire': arg_1},
                                nid=arg_3)
            arg_0._id_to_node[arg_2] = arg_5
            arg_0._id_to_node[arg_3] = arg_6

            arg_0.input_map[arg_1] = arg_5
            arg_0.output_map[arg_1] = arg_6

            arg_0._multi_graph.add_node(arg_5)
            arg_0._multi_graph.add_node(arg_6)

            arg_0._multi_graph.add_edge(arg_5,
                                       arg_6)

            arg_0._multi_graph.adj[arg_5][arg_6][0]["name"] \
                = "%s[%s]" % (arg_1[0].name, arg_1[1])
            arg_0._multi_graph.adj[arg_5][arg_6][0]["wire"] \
                = arg_1
        else:
            raise DAGCircuitError("duplicate wire %s" % (arg_1,))


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Add a new operation node to the graph and assign properties.

        Args:
            op (Instruction): the operation associated with the DAG node
            qargs (list): list of quantum wires to attach to.
            cargs (list): list of classical wires to attach to.
            condition (tuple or None): optional condition (ClassicalRegister, int)
        """
        arg_5 = {
            "type": "op",
            "op": arg_1,
            "name": arg_1.name,
            "qargs": arg_2,
            "cargs": arg_3,
            "condition": arg_4
        }

        # Add a new operation node to the graph
        arg_0._max_node_id += 1
        arg_6 = DAGNode(data_dict=arg_5, nid=arg_0._max_node_id)
        arg_0._multi_graph.add_node(arg_6)
        arg_0._id_to_node[arg_0._max_node_id] = arg_6


def Func(arg_0, arg_1, arg_2, arg_3):
        """Check that the wiremap is consistent.

        Check that the wiremap refers to valid wires and that
        those wires have consistent types.

        Args:
            wire_map (dict): map from (register,idx) in keymap to
                (register,idx) in valmap
            keymap (dict): a map whose keys are wire_map keys
            valmap (dict): a map whose keys are wire_map values

        Raises:
            DAGCircuitError: if wire_map not valid
        """
        for arg_4, arg_5 in arg_1.items():
            arg_6 = "%s[%d]" % (arg_4[0].name, arg_4[1])
            arg_7 = "%s[%d]" % (arg_5[0].name, arg_5[1])
            if arg_4 not in arg_2:
                raise DAGCircuitError("invalid wire mapping key %s" % arg_6)
            if arg_5 not in arg_3:
                raise DAGCircuitError("invalid wire mapping value %s" % arg_7)
            if type(arg_4) is not type(arg_5):
                raise DAGCircuitError("inconsistent wire_map at (%s,%s)" %
                                      (arg_6, arg_7))


def Func(arg_0, arg_1, arg_2):
        """Use the wire_map dict to change the condition tuple's creg name.

        Args:
            wire_map (dict): a map from wires to wires
            condition (tuple): (ClassicalRegister,int)
        Returns:
            tuple(ClassicalRegister,int): new condition
        """
        if arg_2 is None:
            arg_3 = None
        else:
            # Map the register name, using fact that registers must not be
            # fragmented by the wire_map (this must have been checked
            # elsewhere)
            arg_4 = (arg_2[0], 0)
            arg_3 = (arg_1.get(arg_4, arg_4)[0], arg_2[1])
        return arg_3


def Func(arg_0, arg_1, arg_2=None):
        """Apply the input circuit to the output of this circuit.

        The two bases must be "compatible" or an exception occurs.
        A subset of input qubits of the input circuit are mapped
        to a subset of output qubits of this circuit.

        Args:
            input_circuit (DAGCircuit): circuit to append
            edge_map (dict): map {(Register, int): (Register, int)}
                from the output wires of input_circuit to input wires
                of self.

        Raises:
            DAGCircuitError: if missing, duplicate or incosistent wire
        """
        arg_2 = arg_2 or {}

        # Check the wire map for duplicate values
        if len(set(arg_2.values())) != len(arg_2):
            raise DAGCircuitError("duplicates in wire_map")

        arg_3 = arg_0._check_edgemap_registers(arg_2,
                                                  arg_1.qregs,
                                                  arg_0.qregs)
        for arg_4 in arg_3:
            arg_0.add_qreg(arg_4)

        arg_5 = arg_0._check_edgemap_registers(arg_2,
                                                  arg_1.cregs,
                                                  arg_0.cregs)
        for arg_6 in arg_5:
            arg_0.add_creg(arg_6)

        arg_0._check_wiremap_validity(arg_2, arg_1.input_map,
                                     arg_0.output_map)

        # Compose
        for arg_7 in arg_1.topological_nodes():
            if arg_7.type == "in":
                # if in wire_map, get new name, else use existing name
                arg_8 = arg_2.get(arg_7.wire, arg_7.wire)
                # the mapped wire should already exist
                if arg_8 not in arg_0.output_map:
                    raise DAGCircuitError("wire %s[%d] not in self" % (arg_8[0].name, arg_8[1]))

                if arg_7.wire not in arg_1.wires:
                    raise DAGCircuitError("inconsistent wire type for %s[%d] in input_circuit"
                                          % (arg_7.wire[0].name, arg_7.wire[1]))

            elif arg_7.type == "out":
                # ignore output nodes
                pass
            elif arg_7.type == "op":
                arg_9 = arg_0._map_condition(arg_2, arg_7.condition)
                arg_0._check_condition(arg_7.name, arg_9)
                arg_10 = list(map(lambda x: arg_2.get(x, x), arg_7.qargs))
                arg_11 = list(map(lambda x: arg_2.get(x, x), arg_7.cargs))
                arg_0.apply_operation_back(arg_7.op, arg_10, arg_11, arg_9)
            else:
                raise DAGCircuitError("bad node type %s" % arg_7.type)


def Func(arg_0, arg_1, arg_2):
        """Check that a list of wires is compatible with a node to be replaced.

        - no duplicate names
        - correct length for operation
        Raise an exception otherwise.

        Args:
            wires (list[register, index]): gives an order for (qu)bits
                in the input circuit that is replacing the node.
            node (DAGNode): a node in the dag

        Raises:
            DAGCircuitError: if check doesn't pass.
        """
        if len(set(arg_1)) != len(arg_1):
            raise DAGCircuitError("duplicate wires")

        arg_3 = len(arg_2.qargs) + len(arg_2.cargs)
        if arg_2.condition is not None:
            arg_3 += arg_2.condition[0].size

        if len(arg_1) != arg_3:
            raise DAGCircuitError("expected %d wires, got %d"
                                  % (arg_3, len(arg_1)))


def Func(arg_0, arg_1):
        """Return predecessor and successor dictionaries.

        Args:
            node (DAGNode): reference to multi_graph node

        Returns:
            tuple(dict): tuple(predecessor_map, successor_map)
                These map from wire (Register, int) to predecessor (successor)
                nodes of n.
        """

        arg_2 = {e[2]['wire']: e[0] for e in
                    arg_0._multi_graph.in_edges(nbunch=arg_1, data=True)}
        arg_3 = {e[2]['wire']: e[1] for e in
                    arg_0._multi_graph.out_edges(nbunch=arg_1, data=True)}
        return arg_2, arg_3


def Func(arg_0, arg_1, arg_2, arg_3,
                             arg_4):
        """Map all wires of the input circuit.

        Map all wires of the input circuit to predecessor and
        successor nodes in self, keyed on wires in self.

        Args:
            pred_map (dict): comes from _make_pred_succ_maps
            succ_map (dict): comes from _make_pred_succ_maps
            input_circuit (DAGCircuit): the input circuit
            wire_map (dict): the map from wires of input_circuit to wires of self

        Returns:
            tuple: full_pred_map, full_succ_map (dict, dict)

        Raises:
            DAGCircuitError: if more than one predecessor for output nodes
        """
        arg_5 = {}
        arg_6 = {}
        for arg_7 in arg_3.input_map:
            # If w is wire mapped, find the corresponding predecessor
            # of the node
            if arg_7 in arg_4:
                arg_5[arg_4[arg_7]] = arg_1[arg_4[arg_7]]
                arg_6[arg_4[arg_7]] = arg_2[arg_4[arg_7]]
            else:
                # Otherwise, use the corresponding output nodes of self
                # and compute the predecessor.
                arg_6[arg_7] = arg_0.output_map[arg_7]
                arg_5[arg_7] = arg_0._multi_graph.predecessors(
                    arg_0.output_map[arg_7])[0]
                if len(list(arg_0._multi_graph.predecessors(arg_0.output_map[arg_7]))) != 1:
                    raise DAGCircuitError("too many predecessors for %s[%d] "
                                          "output node" % (arg_7[0], arg_7[1]))

        return arg_5, arg_6


def Func(arg_0):
        """
        Yield nodes in topological order.

        Returns:
            generator(DAGNode): node in topological order
        """
        return nx.lexicographical_topological_sort(arg_0._multi_graph,
                                                   key=lambda x: str(x.qargs))


def Func(arg_0, arg_1=None):
        """Get the list of "op" nodes in the dag.

        Args:
            op (Type): Instruction subclass op nodes to return. if op=None, return
                all op nodes.
        Returns:
            list[DAGNode]: the list of node ids containing the given op.
        """
        arg_2 = []
        for arg_3 in arg_0._multi_graph.nodes():
            if arg_3.type == "op":
                if arg_1 is None or isinstance(arg_3.op, arg_1):
                    arg_2.append(arg_3)
        return arg_2


def Func(arg_0):
        """Get the list of gate nodes in the dag.

        Returns:
            list: the list of node ids that represent gates.
        """
        arg_1 = []
        for arg_2 in arg_0.op_nodes():
            if isinstance(arg_2.op, Gate):
                arg_1.append(arg_2)
        return arg_1


def Func(arg_0):
        """Get list of 2-qubit gates. Ignore snapshot, barriers, and the like."""
        arg_1 = []
        for arg_2 in arg_0.gate_nodes():
            if len(arg_2.qargs) == 2:
                arg_1.append(arg_2)
        return arg_1


def Func(arg_0, arg_1):
        """Returns set of the Func of a node as DAGNodes."""
        if isinstance(arg_1, int):
            warnings.warn('Calling Func() with a node id is deprecated,'
                          ' use a DAGNode instead',
                          DeprecationWarning, 2)
            arg_1 = arg_0._id_to_node[arg_1]

        return nx.Func(arg_0._multi_graph, arg_1)


def Func(arg_0, arg_1):
        """Returns list of the successors of a node that are
        connected by a quantum edge as DAGNodes."""
        if isinstance(arg_1, int):
            warnings.warn('Calling Func() with a node id is deprecated,'
                          ' use a DAGNode instead',
                          DeprecationWarning, 2)
            arg_1 = arg_0._id_to_node[arg_1]

        arg_2 = []
        for arg_3 in arg_0.successors(arg_1):
            if isinstance(arg_0._multi_graph.get_edge_data(
                    arg_1, arg_3, key=0)['wire'][0],
                          QuantumRegister):
                arg_2.append(arg_3)
        return arg_2


def Func(arg_0, arg_1):
        """Remove an operation node n.

        Add edges from predecessors to successors.
        """
        if isinstance(arg_1, int):
            warnings.warn('Calling Func() with a node id is deprecated,'
                          ' use a DAGNode instead',
                          DeprecationWarning, 2)
            arg_1 = arg_0._id_to_node[arg_1]

        if arg_1.type != 'op':
            raise DAGCircuitError('The method Func only works on op node types. An "%s" '
                                  'node type was wrongly provided.' % arg_1.type)

        arg_2, arg_3 = arg_0._make_pred_succ_maps(arg_1)

        # remove from graph and map
        arg_0._multi_graph.remove_node(arg_1)

        for arg_4 in arg_2.keys():
            arg_0._multi_graph.add_edge(arg_2[arg_4], arg_3[arg_4],
                                       name="%s[%s]" % (arg_4[0].name, arg_4[1]), wire=arg_4)


def Func(arg_0, arg_1):
        """Remove all of the descendant operation nodes of node."""
        if isinstance(arg_1, int):
            warnings.warn('Calling Func() with a node id is deprecated,'
                          ' use a DAGNode instead',
                          DeprecationWarning, 2)
            arg_1 = arg_0._id_to_node[arg_1]

        arg_2 = nx.descendants(arg_0._multi_graph, arg_1)
        for arg_3 in arg_2:
            if arg_3.type == "op":
                arg_0.remove_op_node(arg_3)


def Func(arg_0, arg_1):
        """Remove all of the non-ancestors operation nodes of node."""
        if isinstance(arg_1, int):
            warnings.warn('Calling Func() with a node id is deprecated,'
                          ' use a DAGNode instead',
                          DeprecationWarning, 2)
            arg_1 = arg_0._id_to_node[arg_1]

        arg_2 = nx.ancestors(arg_0._multi_graph, arg_1)
        arg_3 = list(set(arg_0._multi_graph.nodes()) - set(arg_2))
        for arg_4 in arg_3:
            if arg_4.type == "op":
                arg_0.remove_op_node(arg_4)


def Func(arg_0):
        """Yield a shallow view on a layer of this DAGCircuit for all d Func of this circuit.

        A layer is a circuit whose gates act on disjoint qubits, i.e.
        a layer has depth 1. The total number of Func equals the
        circuit depth d. The Func are indexed from 0 to d-1 with the
        earliest layer at index 0. The Func are constructed using a
        greedy algorithm. Each returned layer is a dict containing
        {"graph": circuit graph, "partition": list of qubit lists}.

        TODO: Gates that use the same cbits will end up in different
        Func as this is currently implemented. This may not be
        the desired behavior.
        """
        arg_1 = arg_0.multigraph_Func()
        try:
            next(arg_1)  # Remove input nodes
        except StopIteration:
            return

        def add_nodes_from(arg_2, arg_3):
            """ Convert DAGNodes into a format that can be added to a
             multigraph and then add to graph"""
            arg_2._multi_graph.add_nodes_from(arg_3)

        for arg_4 in arg_1:

            # Get the op nodes from the layer, removing any input and output nodes.
            arg_5 = [node for node in arg_4 if node.type == "op"]

            # Stop yielding once there are no more op_nodes in a layer.
            if not arg_5:
                return

            # Construct a shallow copy of self
            arg_6 = DAGCircuit()
            arg_6.name = arg_0.name

            for arg_8 in arg_0.cregs.values():
                arg_6.add_creg(arg_8)
            for arg_9 in arg_0.qregs.values():
                arg_6.add_qreg(arg_9)

            add_nodes_from(arg_6, arg_0.input_map.values())
            add_nodes_from(arg_6, arg_0.output_map.values())
            add_nodes_from(arg_6, arg_5)

            # The quantum registers that have an operation in this layer.
            arg_10 = [
                arg_12.qargs
                for arg_12 in arg_5
                if arg_12.name not in {"barrier", "snapshot", "save", "load", "noise"}
            ]

            # Now add the edges to the multi_graph
            # By default we just wire inputs to the outputs.
            arg_11 = {arg_0.input_map[wire]: arg_0.output_map[wire]
                     for wire in arg_0.wires}
            # Wire inputs to op nodes, and op nodes to outputs.
            for arg_12 in arg_5:
                arg_13 = arg_0._bits_in_condition(arg_12.condition) \
                       + arg_12.cargs + arg_12.qargs
                arg_14 = (arg_0.input_map[(arg[0], arg[1])] for arg in arg_13)
                for arg_15 in arg_14:
                    arg_11[arg_15], arg_11[arg_12] = arg_12, arg_11[arg_15]

            # Add wiring to/from the operations and between unused inputs & outputs.
            arg_6._multi_graph.add_edges_from(arg_11.items())
            yield {"graph": arg_6, "partition": arg_10}


def Func(arg_0, arg_1):
        """Return a set of non-conditional runs of "op" nodes with the given names.

        For example, "... h q[0]; cx q[0],q[1]; cx q[0],q[1]; h q[1]; .."
        would produce the tuple of cx nodes as an element of the set returned
        from a call to Func(["cx"]). If instead the cx nodes were
        "cx q[0],q[1]; cx q[1],q[0];", the method would still return the
        pair in a tuple. The namelist can contain names that are not
        in the circuit's basis.

        Nodes must have only one successor to continue the run.
        """
        arg_2 = []

        # Iterate through the nodes of self in topological order
        # and form tuples containing sequences of gates
        # on the same qubit(s).
        arg_3 = list(arg_0.topological_op_nodes())
        arg_4 = dict(zip(arg_3, [False] * len(arg_3)))
        for arg_5 in arg_3:
            if arg_5.name in arg_1 and arg_5.condition is None \
                    and not arg_4[arg_5]:
                arg_6 = [arg_5]
                arg_4[arg_5] = True
                arg_7 = list(arg_0._multi_graph.successors(arg_5))
                while len(arg_7) == 1 and \
                        arg_7[0].type == "op" and \
                        arg_7[0].name in arg_1:
                    arg_6.append(arg_7[0])
                    arg_4[arg_7[0]] = True
                    arg_7 = list(arg_0._multi_graph.successors(arg_7[0]))
                if len(arg_6) >= 1:
                    arg_2.append(tuple(arg_6))
        return set(arg_2)


def Func(arg_0, arg_1, arg_2=False):
        """
        Iterator for nodes that affect a given wire

        Args:
            wire (tuple(Register, index)): the wire to be looked at.
            only_ops (bool): True if only the ops nodes are wanted
                        otherwise all nodes are returned.
        Yield:
             DAGNode: the successive ops on the given wire

        Raises:
            DAGCircuitError: if the given wire doesn't exist in the DAG
        """
        arg_3 = arg_0.input_map.get(arg_1, None)

        if not arg_3:
            raise DAGCircuitError('The given wire %s is not present in the circuit'
                                  % str(arg_1))

        arg_4 = True
        while arg_4:
            arg_4 = False
            # allow user to just get ops on the wire - not the input/output nodes
            if arg_3.type == 'op' or not arg_2:
                yield arg_3

            # find the adjacent node that takes the wire being looked at as input
            for arg_5, arg_6 in arg_0._multi_graph.adj[arg_3].items():
                if any(arg_1 == arg_7['wire'] for arg_7 in arg_6.values()):
                    arg_3 = arg_5
                    arg_4 = True
                    break


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Generate a TomographyBasis object.

    See TomographyBasis for further details.abs

    Args:
        prep_fun (callable) optional: the function which adds preparation
            gates to a circuit.
        meas_fun (callable) optional: the function which adds measurement
            gates to a circuit.

    Returns:
        TomographyBasis: A tomography basis.
    """
    arg_3 = TomographyBasis(arg_0)
    arg_3.prep_fun = arg_1
    arg_3.meas_fun = arg_2
    return arg_3


def Func(arg_0, arg_1, arg_2):
    """
    Add state measurement gates to a circuit.
    """
    if arg_2 not in ['X', 'Y', 'Z']:
        raise QiskitError("There's no X, Y or Z basis for this Pauli "
                          "measurement")

    if arg_2 == "X":
        arg_0.u2(0., np.pi, arg_1)  # H
    elif arg_2 == "Y":
        arg_0.u2(0., 0.5 * np.pi, arg_1)


def Func(arg_0,
                   arg_1='Pauli',
                   arg_2=None,
                   arg_3=None):
    """
    Generate a dictionary of tomography experiment configurations.

    This returns a data structure that is used by other tomography functions
    to generate state and process tomography circuits, and extract tomography
    data from results after execution on a backend.

    Quantum State Tomography:
        Be default it will return a set for performing Quantum State
        Tomography where individual qubits are measured in the Pauli basis.
        A custom measurement basis may also be used by defining a user
        `tomography_basis` and passing this in for the `meas_basis` argument.

    Quantum Process Tomography:
        A quantum process tomography set is created by specifying a preparation
        basis along with a measurement basis. The preparation basis may be a
        user defined `tomography_basis`, or one of the two built in basis 'SIC'
        or 'Pauli'.
        - SIC: Is a minimal symmetric informationally complete preparation
               basis for 4 states for each qubit (4 ^ number of qubits total
               preparation states). These correspond to the |0> state and the 3
               other vertices of a tetrahedron on the Bloch-sphere.
        - Pauli: Is a tomographically overcomplete preparation basis of the six
                 eigenstates of the 3 Pauli operators (6 ^ number of qubits
                 total preparation states).

    Args:
        meas_qubits (list): The qubits being measured.
        meas_basis (tomography_basis or str): The qubit measurement basis.
            The default value is 'Pauli'.
        prep_qubits (list or None): The qubits being prepared. If None then
            meas_qubits will be used for process tomography experiments.
        prep_basis (tomography_basis or None): The optional qubit preparation
            basis. If no basis is specified state tomography will be performed
            instead of process tomography. A built in basis may be specified by
            'SIC' or 'Pauli'  (SIC basis recommended for > 2 qubits).

    Returns:
        dict: A dict of tomography configurations that can be parsed by
        `create_tomography_circuits` and `tomography_data` functions
        for implementing quantum tomography experiments. This output contains
        fields "qubits", "meas_basis", "circuits". It may also optionally
        contain a field "prep_basis" for process tomography experiments.
        ```
        {
            'qubits': qubits (list[ints]),
            'meas_basis': meas_basis (tomography_basis),
            'circuit_labels': (list[string]),
            'circuits': (list[dict])  # prep and meas configurations
            # optionally for process tomography experiments:
            'prep_basis': prep_basis (tomography_basis)
        }
        ```
    Raises:
        QiskitError: if the Qubits argument is not a list.
    """
    if not isinstance(arg_0, list):
        raise QiskitError('Qubits argument must be a list')
    arg_4 = len(arg_0)

    if arg_2 is None:
        arg_2 = arg_0
    if not isinstance(arg_2, list):
        raise QiskitError('prep_qubits argument must be a list')
    if len(arg_2) != len(arg_0):
        raise QiskitError('meas_qubits and prep_qubitsare different length')

    if isinstance(arg_1, str):
        if arg_1.lower() == 'pauli':
            arg_1 = PAULI_BASIS

    if isinstance(arg_3, str):
        if arg_3.lower() == 'pauli':
            arg_3 = PAULI_BASIS
        elif arg_3.lower() == 'sic':
            arg_3 = SIC_BASIS

    arg_5 = []
    arg_6 = []

    # add meas basis configs
    if arg_3 is None:
        # State Tomography
        for arg_7 in product(arg_1.keys(), repeat=arg_4):
            arg_8 = dict(zip(arg_0, arg_7))
            arg_5.append({'meas': arg_8})
            # Make label
            arg_9 = '_meas_'
            for arg_10, arg_11 in arg_8.items():
                arg_9 += '%s(%d)' % (arg_11[0], arg_10)
            arg_6.append(arg_9)
        return {'qubits': arg_0,
                'circuits': arg_5,
                'circuit_labels': arg_6,
                'meas_basis': arg_1}

    # Process Tomography
    arg_12 = len(list(arg_3.values())[0])
    arg_13 = [(b, s)
                   for b in arg_3.keys()
                   for s in range(arg_12)]
    for arg_14 in product(arg_13, repeat=arg_4):
        for arg_7 in product(arg_1.keys(),
                                    repeat=arg_4):
            arg_15 = dict(zip(arg_2, arg_14))
            arg_8 = dict(zip(arg_0, arg_7))
            arg_5.append({'prep': arg_15, 'meas': arg_8})
            # Make label
            arg_9 = '_prep_'
            for arg_10, arg_11 in arg_15.items():
                arg_9 += '%s%d(%d)' % (arg_11[0], arg_11[1], arg_10)
            arg_9 += '_meas_'
            for arg_10, arg_11 in arg_8.items():
                arg_9 += '%s(%d)' % (arg_11[0], arg_10)
            arg_6.append(arg_9)
    return {'qubits': arg_0,
            'circuits': arg_5,
            'circuit_labels': arg_6,
            'prep_basis': arg_3,
            'meas_basis': arg_1}


def Func(arg_0, arg_1='Pauli',
                           arg_2=None, arg_3='SIC'):
    """
    Generate a dictionary of process tomography experiment configurations.

    This returns a data structure that is used by other tomography functions
    to generate state and process tomography circuits, and extract tomography
    data from results after execution on a backend.

   A quantum process tomography set is created by specifying a preparation
    basis along with a measurement basis. The preparation basis may be a
    user defined `tomography_basis`, or one of the two built in basis 'SIC'
    or 'Pauli'.
    - SIC: Is a minimal symmetric informationally complete preparation
           basis for 4 states for each qubit (4 ^ number of qubits total
           preparation states). These correspond to the |0> state and the 3
           other vertices of a tetrahedron on the Bloch-sphere.
    - Pauli: Is a tomographically overcomplete preparation basis of the six
             eigenstates of the 3 Pauli operators (6 ^ number of qubits
             total preparation states).

    Args:
        meas_qubits (list): The qubits being measured.
        meas_basis (tomography_basis or str): The qubit measurement basis.
            The default value is 'Pauli'.
        prep_qubits (list or None): The qubits being prepared. If None then
            meas_qubits will be used for process tomography experiments.
        prep_basis (tomography_basis or str): The qubit preparation basis.
            The default value is 'SIC'.

    Returns:
        dict: A dict of tomography configurations that can be parsed by
        `create_tomography_circuits` and `tomography_data` functions
        for implementing quantum tomography experiments. This output contains
        fields "qubits", "meas_basis", "prep_basus", circuits".
        ```
        {
            'qubits': qubits (list[ints]),
            'meas_basis': meas_basis (tomography_basis),
            'prep_basis': prep_basis (tomography_basis),
            'circuit_labels': (list[string]),
            'circuits': (list[dict])  # prep and meas configurations
        }
        ```
    """
    return tomography_set(arg_0, arg_1=arg_1,
                          arg_2=arg_2, arg_3=arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Add tomography measurement circuits to a QuantumProgram.

    The quantum program must contain a circuit 'name', which is treated as a
    state preparation circuit for state tomography, or as teh circuit being
    measured for process tomography. This function then appends the circuit
    with a set of measurements specified by the input `tomography_set`,
    optionally it also prepends the circuit with state preparation circuits if
    they are specified in the `tomography_set`.

    For n-qubit tomography with a tomographically complete set of preparations
    and measurements this results in $4^n 3^n$ circuits being added to the
    quantum program.

    Args:
        circuit (QuantumCircuit): The circuit to be appended with tomography
                                  state preparation and/or measurements.
        qreg (QuantumRegister): the quantum register containing qubits to be
                                measured.
        creg (ClassicalRegister): the classical register containing bits to
                                  store measurement outcomes.
        tomoset (tomography_set): the dict of tomography configurations.

    Returns:
        list: A list of quantum tomography circuits for the input circuit.

    Raises:
        QiskitError: if circuit is not a valid QuantumCircuit

    Example:
        For a tomography set specifying state tomography of qubit-0 prepared
        by a circuit 'circ' this would return:
        ```
        ['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']
        ```
        For process tomography of the same circuit with preparation in the
        SIC-POVM basis it would return:
        ```
        [
            'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',
            'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',
            'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',
            'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',
            'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',
            'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'
        ]
        ```
    """

    if not isinstance(arg_0, QuantumCircuit):
        raise QiskitError('Input circuit must be a QuantumCircuit object')

    arg_4 = arg_3['circuits']
    arg_5 = tomography_circuit_names(arg_3, arg_0.name)
    arg_6 = []
    for arg_7, arg_8 in zip(arg_5, arg_4):
        arg_9 = arg_0
        # Add prep circuits
        if 'prep' in arg_8:
            arg_10 = QuantumCircuit(arg_1, arg_2, arg_14='tmp_prep')
            for arg_11, arg_12 in arg_8['prep'].items():
                arg_3['prep_basis'].prep_gate(arg_10, arg_1[arg_11], arg_12)
                arg_10.barrier(arg_1[arg_11])
            arg_9 = arg_10 + arg_9
        # Add measurement circuits
        arg_13 = QuantumCircuit(arg_1, arg_2, arg_14='tmp_meas')
        for arg_11, arg_12 in arg_8['meas'].items():
            arg_13.barrier(arg_1[arg_11])
            arg_3['meas_basis'].meas_gate(arg_13, arg_1[arg_11], arg_12)
            arg_13.measure(arg_1[arg_11], arg_2[arg_11])
        arg_9 = arg_9 + arg_13
        # Add label to the circuit
        arg_9.name = arg_7
        arg_6.append(arg_9)

    logger.info('>> created tomography circuits for "%s"', arg_0.name)
    return arg_6


def Func(arg_0, arg_1, arg_2):
    """
    Return a results dict for a state or process tomography experiment.

    Args:
        results (Result): Results from execution of a process tomography
            circuits on a backend.
        name (string): The name of the circuit being reconstructed.
        tomoset (tomography_set): the dict of tomography configurations.

    Returns:
        list: A list of dicts for the outcome of each process tomography
        measurement circuit.
    """

    arg_3 = tomography_circuit_names(arg_2, arg_1)
    arg_4 = arg_2['circuits']
    arg_5 = []
    arg_6 = None
    for arg_7, arg_8 in enumerate(arg_3):
        arg_9 = marginal_counts(arg_0.get_counts(arg_3[arg_7]),
                                 arg_2['qubits'])
        arg_10 = sum(arg_9.values())
        arg_11 = arg_4[arg_7]['meas']
        arg_6 = arg_4[arg_7].get('prep', None)
        arg_12 = sorted(arg_11.keys())
        if arg_6:
            arg_13 = sorted(arg_6.keys())
        arg_14 = {}
        for arg_15 in arg_9.keys():
            arg_14[arg_15] = {}
            arg_14[arg_15]['meas'] = [(arg_11[arg_12[k]], int(arg_15[-1 - k]))
                                  for k in range(len(arg_12))]
            if arg_6:
                arg_14[arg_15]['prep'] = [arg_6[arg_13[k]]
                                      for k in range(len(arg_13))]
        arg_5.append({'counts': arg_9, 'shots': arg_10, 'circuit': arg_14})

    arg_16 = {'data': arg_5, 'meas_basis': arg_2['meas_basis']}
    if arg_6:
        arg_16['prep_basis'] = arg_2['prep_basis']
    return arg_16


def Func(arg_0, arg_1='wizard', arg_2=None):
    """
    Reconstruct a density matrix or process-matrix from tomography data.

    If the input data is state_tomography_data the returned operator will
    be a density matrix. If the input data is process_tomography_data the
    returned operator will be a Choi-matrix in the column-vectorization
    convention.

    Args:
        tomo_data (dict): process tomography measurement data.
        method (str): the fitting method to use.
            Available methods:
                - 'wizard' (default)
                - 'leastsq'
        options (dict or None): additional options for fitting method.

    Returns:
        numpy.array: The fitted operator.

    Available methods:
        - 'wizard' (Default): The returned operator will be constrained to be
                              positive-semidefinite.
            Options:
            - 'trace': the trace of the returned operator.
                       The default value is 1.
            - 'beta': hedging parameter for computing frequencies from
                      zero-count data. The default value is 0.50922.
            - 'epsilon: threshold for truncating small eigenvalues to zero.
                        The default value is 0
        - 'leastsq': Fitting without positive-semidefinite constraint.
            Options:
            - 'trace': Same as for 'wizard' method.
            - 'beta': Same as for 'wizard' method.
    Raises:
        Exception: if the `method` parameter is not valid.
    """

    if isinstance(arg_1, str) and arg_1.lower() in ['wizard', 'leastsq']:
        # get options
        arg_3 = __get_option('trace', arg_2)
        arg_4 = __get_option('beta', arg_2)
        # fit state
        arg_5 = __leastsq_fit(arg_0, arg_3=arg_3, arg_4=arg_4)
        if arg_1 == 'wizard':
            # Use wizard method to constrain positivity
            arg_6 = __get_option('epsilon', arg_2)
            arg_5 = __wizard(arg_5, arg_6=arg_6)
        return arg_5
    else:
        raise Exception('Invalid reconstruction method "%s"' % arg_1)


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None):
    """
    Reconstruct a state from unconstrained least-squares fitting.

    Args:
        tomo_data (list[dict]): state or process tomography data.
        weights (list or array or None): weights to use for least squares
            fitting. The default is standard deviation from a binomial
            distribution.
        trace (float or None): trace of returned operator. The default is 1.
        beta (float or None): hedge parameter (>=0) for computing frequencies
            from zero-count data. The default value is 0.50922.

    Returns:
        numpy.array: A numpy array of the reconstructed operator.
    """
    if arg_2 is None:
        arg_2 = 1.  # default to unit trace

    arg_4 = arg_0['data']
    arg_5 = arg_4[0]['circuit'].keys()

    # Get counts and shots
    arg_6 = []
    arg_7 = []
    arg_8 = []
    for arg_9 in arg_4:
        for arg_10 in arg_5:
            arg_6.append(arg_9['counts'][arg_10])
            arg_7.append(arg_9['shots'])
            arg_11 = arg_9['circuit'][arg_10]
            arg_12 = __projector(arg_11['meas'], arg_0['meas_basis'])
            if 'prep' in arg_11:
                arg_13 = __projector(arg_11['prep'],
                                      arg_0['prep_basis'])
                arg_12 = np.kron(arg_13.conj(), arg_12)
            arg_8.append(arg_12)

    # Convert counts to frequencies
    arg_6 = np.array(arg_6)
    arg_7 = np.array(arg_7)
    arg_14 = arg_6 / arg_7

    # Use hedged frequencies to calculate least squares fitting weights
    if arg_1 is None:
        if arg_3 is None:
            arg_3 = 0.50922
        arg_15 = len(arg_5)
        arg_16 = (arg_6 + arg_3) / (arg_7 + arg_15 * arg_3)
        arg_1 = np.sqrt(arg_7 / (arg_16 * (1 - arg_16)))

    return __tomo_linear_inv(arg_14, arg_8, arg_1, arg_2=arg_2)


def Func(arg_0, arg_1):
    """Returns a projectors.
    """
    arg_2 = 1
    # list is from qubit 0 to 1
    for arg_3 in arg_0:
        arg_4, arg_5 = arg_3
        arg_2 = np.kron(arg_1[arg_4][arg_5], arg_2)
    return arg_2


def Func(arg_0, arg_1=None, arg_2=False, arg_3=False, arg_4=arg_5.stdout):
    """Monitor the status of a IBMQJob instance.

    Args:
        job (BaseJob): Job to monitor.
        interval (int): Time interval between status queries.
        monitor_async (bool): Monitor asyncronously (in Jupyter only).
        quiet (bool): If True, do not print status messages.
        output (file): The file like object to write status messages to.
        By default this is sys.stdout.

    Raises:
        QiskitError: When trying to run async outside of Jupyter
        ImportError: ipywidgets not available for notebook.
    """
    if arg_1 is None:
        arg_7 = False
        arg_1 = 2
    else:
        arg_7 = True
    if _NOTEBOOK_ENV:
        if arg_2:
            try:
                import ipywidgets as widgets  # pylint: disable=import-error
            except ImportError:
                raise ImportError('These functions  need ipywidgets. '
                                  'Run "pip install ipywidgets" before.')
            from qiskit.tools.jupyter.jupyter_magics import _html_checker  # pylint: disable=C0412

            arg_8 = "font-size:16px;"
            arg_9 = "<p style='{style}'>Job Status: %s </p>".format(
                arg_8=arg_8)
            arg_10 = widgets.HTML(value=arg_9 % arg_0.status().value)
            display(arg_10)

            arg_11 = threading.Thread(target=_html_checker, args=(arg_0, arg_1,
                                                                  arg_10, arg_9))
            arg_11.start()
        else:
            _text_checker(arg_0, arg_1, arg_7,
                          arg_3=arg_3, arg_4=arg_4)

    else:
        if arg_2:
            raise QiskitError(
                'monitor_async only available in Jupyter notebooks.')
        _text_checker(arg_0, arg_1, arg_7, arg_3=arg_3, arg_4=arg_4)


def Func(arg_0):
    """Compute Euler angles for a single-qubit gate.

    Find angles (theta, phi, lambda) such that
    unitary_matrix = phase * Rz(phi) * Ry(theta) * Rz(lambda)

    Args:
        unitary_matrix (ndarray): 2x2 unitary matrix

    Returns:
        tuple: (theta, phi, lambda) Euler angles of SU(2)

    Raises:
        QiskitError: if unitary_matrix not 2x2, or failure
    """
    if arg_0.shape != (2, 2):
        raise QiskitError("Func: expected 2x2 matrix")
    arg_1 = la.det(arg_0)**(-1.0/2.0)
    arg_2 = arg_1 * arg_0  # U in SU(2)
    # OpenQASM SU(2) parameterization:
    # U[0, 0] = exp(-i(phi+lambda)/2) * cos(theta/2)
    # U[0, 1] = -exp(-i(phi-lambda)/2) * sin(theta/2)
    # U[1, 0] = exp(i(phi-lambda)/2) * sin(theta/2)
    # U[1, 1] = exp(i(phi+lambda)/2) * cos(theta/2)
    # Find theta
    if abs(arg_2[0, 0]) > _CUTOFF_PRECISION:
        arg_3 = 2 * math.acos(abs(arg_2[0, 0]))
    else:
        arg_3 = 2 * math.asin(abs(arg_2[1, 0]))
    # Find phi and lambda
    arg_4 = 0.0
    arg_5 = 0.0
    if abs(math.cos(arg_3/2.0)) > _CUTOFF_PRECISION:
        arg_4 = arg_2[1, 1] / math.cos(arg_3/2.0)
    if abs(math.sin(arg_3/2.0)) > _CUTOFF_PRECISION:
        arg_5 = arg_2[1, 0] / math.sin(arg_3/2.0)
    arg_6 = 2 * math.atan2(np.imag(arg_4), np.real(arg_4))
    arg_7 = 2 * math.atan2(np.imag(arg_5), np.real(arg_5))
    arg_8 = 0.0
    if abs(arg_2[0, 0]) > _CUTOFF_PRECISION and abs(arg_2[1, 0]) > _CUTOFF_PRECISION:
        arg_8 = (arg_6 + arg_7) / 2.0
        arg_9 = (arg_6 - arg_7) / 2.0
    else:
        if abs(arg_2[0, 0]) < _CUTOFF_PRECISION:
            arg_9 = -arg_7
        else:
            arg_9 = arg_6
    # Check the solution
    arg_10 = np.array([[np.exp(-1j*arg_8/2.0), 0],
                      [0, np.exp(1j*arg_8/2.0)]], dtype=complex)
    arg_11 = np.array([[np.cos(arg_3/2.0), -np.sin(arg_3/2.0)],
                        [np.sin(arg_3/2.0), np.cos(arg_3/2.0)]], dtype=complex)
    arg_12 = np.array([[np.exp(-1j*arg_9/2.0), 0],
                         [0, np.exp(1j*arg_9/2.0)]], dtype=complex)
    arg_13 = np.dot(arg_10, np.dot(arg_11, arg_12))
    if la.norm(arg_13 - arg_2) > _CUTOFF_PRECISION:
        raise QiskitError("Func: incorrect result")
    return arg_3, arg_8, arg_9


def Func(arg_0, arg_1):
        """
        Extends dag with virtual qubits that are in layout but not in the circuit yet.

        Args:
            dag (DAGCircuit): DAG to extend.

        Returns:
            DAGCircuit: An extended DAG.

        Raises:
            TranspilerError: If there is not layout in the property set or not set at init time.
        """
        arg_0.layout = arg_0.layout or arg_0.property_set['layout']

        if arg_0.layout is None:
            raise TranspilerError("EnlargeWithAncilla requires property_set[\"layout\"] or"
                                  " \"layout\" parameter to Func")

        arg_3 = arg_0.layout.get_virtual_bits().keys()
        arg_4 = set(virtual_qubit[0] for virtual_qubit in arg_3
                        if virtual_qubit not in arg_1.wires)

        for arg_5 in arg_4:
            arg_1.add_qreg(arg_5)

        return arg_1


def Func(arg_0):
    """The qubits properties widget

    Args:
        backend (IBMQbackend): The backend.

    Returns:
        VBox: A VBox widget.
    """
    arg_1 = arg_0.properties().to_dict()

    arg_2 = "
{key}: {value}
"
    arg_2 = arg_2.format(key='last_update_date',
                                     value=arg_1['last_update_date'])
    arg_3 = widgets.HTML(value=arg_2)

    arg_4 = "
"
    arg_4 += """"""

    arg_4 += "
	Frequency	T1	T2	"
    arg_4 += "U1 gate error	U2 gate error	U3 gate error	"
    arg_4 += "Readout error
"
    arg_5 = "
"

    for arg_6 in range(len(arg_1['qubits'])):
        arg_7 = 'Q%s' % arg_6
        arg_8 = arg_1['qubits'][arg_6]
        arg_9 = arg_1['gates'][3*arg_6:3*arg_6+3]
        arg_10 = arg_8[0]
        arg_11 = arg_8[1]
        arg_12 = arg_8[2]
        arg_13 = arg_8[3]

        arg_14 = str(round(arg_12['value'], 5))+' '+arg_12['unit']
        arg_15 = str(round(arg_10['value'],  # pylint: disable=invalid-name
                       5))+' ' + arg_10['unit']
        arg_16 = str(round(arg_11['value'],  # pylint: disable=invalid-name
                       5))+' ' + arg_11['unit']
        # pylint: disable=invalid-name
        arg_17 = str(round(arg_9[0]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        arg_18 = str(round(arg_9[1]['parameters'][0]['value'], 5))
        # pylint: disable=invalid-name
        arg_19 = str(round(arg_9[2]['parameters'][0]['value'], 5))

        arg_20 = round(arg_13['value'], 5)
        arg_4 += "
%s	%s	"
        arg_4 += "%s	%s	%s	%s	%s	%s
"
        arg_4 = arg_4 % (arg_7, arg_14, arg_15, arg_16, arg_17, arg_18, arg_19, arg_20)
    arg_4 += arg_5

    arg_21 = widgets.HTML(value=arg_4)

    arg_22 = widgets.VBox([arg_3,
                        arg_21])

    return arg_22


def Func(arg_0):
    """Widget for displaying job history

    Args:
     backend (IBMQbackend): The backend.

    Returns:
        Tab: A tab widget for history images.
    """
    arg_1 = widgets.Output(layout=widgets.Layout(display='flex-inline',
                                                align_items='center',
                                                min_height='400px'))

    arg_2 = widgets.Output(layout=widgets.Layout(display='flex-inline',
                                                 align_items='center',
                                                 min_height='400px'))

    arg_3 = widgets.Output(layout=widgets.Layout(display='flex-inline',
                                                align_items='center',
                                                min_height='400px'))

    arg_4 = widgets.Tab(layout=widgets.Layout(max_height='620px'))
    arg_4.children = [arg_1, arg_2, arg_3]
    arg_4.set_title(0, 'Year')
    arg_4.set_title(1, 'Month')
    arg_4.set_title(2, 'Week')
    arg_4.selected_index = 1

    _build_Func(arg_4, arg_0)
    return arg_4


def Func(arg_0, arg_1='year'):
    """Plots the job history of the user from the given list of jobs.

    Args:
        jobs (list): A list of jobs with type IBMQjob.
        interval (str): Interval over which to examine.

    Returns:
        fig: A Matplotlib figure instance.
    """
    def get_date(arg_2):
        """Returns a datetime object from a IBMQJob instance.

        Args:
            job (IBMQJob): A job.

        Returns:
            dt: A datetime object.
        """
        return datetime.datetime.strptime(arg_2.creation_date(),
                                          '%Y-%m-%dT%H:%M:%S.%fZ')

    arg_3 = datetime.datetime.now()

    if arg_1 == 'year':
        arg_4 = [(arg_3 - datetime.timedelta(days=k*365/12))
                for k in range(12)]
    elif arg_1 == 'month':
        arg_4 = [(arg_3 - datetime.timedelta(days=k)) for k in range(30)]
    elif arg_1 == 'week':
        arg_4 = [(arg_3 - datetime.timedelta(days=k)) for k in range(7)]

    arg_5 = [0]*len(arg_4)

    if arg_1 == 'year':
        for arg_2 in arg_0:
            for arg_6, arg_7 in enumerate(arg_4):
                date = get_date(arg_2)
                if date.month == arg_7.month:
                    arg_5[arg_6] += 1
                    break
            else:
                continue
    else:
        for arg_2 in arg_0:
            for arg_6, arg_7 in enumerate(arg_4):
                date = get_date(arg_2)
                if date.day == arg_7.day and date.month == arg_7.month:
                    arg_5[arg_6] += 1
                    break
            else:
                continue

    arg_8 = []
    arg_9 = []
    for arg_6, arg_10 in enumerate(arg_5):
        if arg_10 != 0:
            arg_9.append(arg_6)
            arg_8.append(arg_10)

    arg_11 = sum(arg_5)

    arg_12 = ['#003f5c', '#ffa600', '#374c80', '#ff764a',
              '#7a5195', '#ef5675', '#bc5090']

    if arg_1 == 'year':
        arg_13 = ['{}-{}'.format(str(arg_4[b].year)[2:], arg_4[b].month) for b in arg_9]
    else:
        arg_13 = ['{}-{}'.format(arg_4[b].month, arg_4[b].day) for b in arg_9]
    arg_14, arg_15 = plt.subplots(1, 1, figsize=(5, 5))  # pylint: disable=invalid-name
    arg_15.pie(arg_8[::-1], arg_13=arg_13, arg_12=arg_12, textprops={'fontsize': 14},
           rotatelabels=True, counterclock=False)
    arg_15.add_artist(Circle((0, 0), 0.7, color='white', zorder=1))
    arg_15.text(0, 0, arg_11, horizontalalignment='center',
            verticalalignment='center', fontsize=26)
    arg_14.tight_layout()
    return arg_14


def Func(arg_0,
              arg_1=None,
              arg_2=None, arg_3=None, arg_4=None,
              arg_5=None, arg_6=None,
              arg_7=None,
              arg_8=None,
              arg_9=None):  # deprecated
    """Func one or more circuits, according to some desired
    transpilation targets.

    All arguments may be given as either singleton or list. In case of list,
    the length must be equal to the number of circuits being Funcd.

    Transpilation is done in parallel using multiprocessing.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]):
            Circuit(s) to Func

        backend (BaseBackend):
            If set, Funcr options are automatically grabbed from
            backend.configuration() and backend.properties().
            If any other option is explicitly set (e.g. coupling_map), it
            will override the backend's.
            Note: the backend arg is purely for convenience. The resulting
                circuit may be run on any backend as long as it is compatible.

        basis_gates (list[str]):
            List of basis gate names to unroll to.
            e.g:
                ['u1', 'u2', 'u3', 'cx']
            If None, do not unroll.

        coupling_map (CouplingMap or list):
            Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:
            a. CouplingMap instance

            b. list
                Must be given as an adjacency matrix, where each entry
                specifies all two-qubit interactions supported by backend
                e.g:
                    [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]

        backend_properties (BackendProperties):
            properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. For a backend
            that provides this information, it can be obtained with:
            ``backend.properties()``

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used.
            The final layout is not guaranteed to be the same, as the Funcr
            may permute qubits through swaps or other means.

            Multiple formats are supported:
            a. Layout instance

            b. dict
                virtual to physical:
                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

                physical to virtual:
                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            c. list
                virtual to physical:
                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

                physical to virtual:
                    [qr[0], None, None, qr[1], None, qr[2]]

        seed_Funcr (int):
            sets random seed for the stochastic parts of the Funcr

        optimization_level (int):
            How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.
                0: no optimization
                1: light optimization
                2: heavy optimization

        pass_manager (PassManager):
            The pass manager to use for a custom pipeline of Funcr passes.
            If this arg is present, all other args will be ignored and the
            pass manager will be used directly (Qiskit will not attempt to
            auto-select a pass manager based on Func options).

        seed_mapper (int):
            DEPRECATED in 0.8: use ``seed_Funcr`` kwarg instead

    Returns:
        QuantumCircuit or list[QuantumCircuit]: Funcd circuit(s).

    Raises:
        TranspilerError: in case of bad inputs to Funcr or errors in passes
    """
    # Deprecation matter
    if arg_9:
        warnings.warn("seed_mapper has been deprecated and will be removed in the "
                      "0.9 release. Instead use seed_Funcr to set the seed "
                      "for all stochastic parts of the.", DeprecationWarning)
        arg_6 = arg_9

    # transpiling schedules is not supported yet.
    if isinstance(arg_0, Schedule) or \
       (isinstance(arg_0, list) and all(isinstance(arg_10, Schedule) for arg_10 in arg_0)):
        return arg_0

    # Get TranspileConfig(s) to configure the circuit transpilation job(s)
    arg_0 = arg_0 if isinstance(arg_0, list) else [arg_0]
    arg_11 = _parse_Func_args(arg_0, arg_1, arg_2, arg_3,
                                              arg_4, arg_5,
                                              arg_6, arg_7,
                                              arg_8)

    # Transpile circuits in parallel
    arg_0 = parallel_map(_Func_circuit, list(zip(arg_0, arg_11)))

    if len(arg_0) == 1:
        return arg_0[0]
    return arg_0


def Func(arg_0, arg_1,
            arg_2=None, arg_3=None,  # circuit transpile options
            arg_4=None, arg_5=None,
            arg_6=None, arg_7=None, arg_8=None,
            arg_9=None, arg_10=None, arg_11=1024,  # common run options
            arg_12=False, arg_13=10, arg_14=None,
            arg_15=None, arg_16=None,  # schedule run options
            arg_17=None, arg_18=2, arg_19='avg',
            arg_20=None, arg_21=100, arg_22=None, arg_23=None,
            arg_24=None, arg_25=None,  # deprecated
            arg_26=None, arg_27=None,
            **arg_28):
    """Execute a list of circuits or pulse schedules on a backend.

    The execution is asynchronous, and a handle to a job instance is returned.

    Args:
        experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]):
            Circuit(s) or pulse schedule(s) to Func

        backend (BaseBackend):
            Backend to Func circuits on.
            Transpiler options are automatically grabbed from
            backend.configuration() and backend.properties().
            If any other option is explicitly set (e.g. coupling_map), it
            will override the backend's.

        basis_gates (list[str]):
            List of basis gate names to unroll to.
            e.g:
                ['u1', 'u2', 'u3', 'cx']
            If None, do not unroll.

        coupling_map (CouplingMap or list):
            Coupling map (perhaps custom) to target in mapping.
            Multiple formats are supported:
            a. CouplingMap instance

            b. list
                Must be given as an adjacency matrix, where each entry
                specifies all two-qubit interactions supported by backend
                e.g:
                    [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]

        backend_properties (BackendProperties):
            Properties returned by a backend, including information on gate
            errors, readout errors, qubit coherence times, etc. For a backend
            that provides this information, it can be obtained with:
            ``backend.properties()``

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits.
            If this layout makes the circuit compatible with the coupling_map
            constraints, it will be used.
            The final layout is not guaranteed to be the same, as the transpiler
            may permute qubits through swaps or other means.

            Multiple formats are supported:
            a. Layout instance

            b. dict
                virtual to physical:
                    {qr[0]: 0,
                     qr[1]: 3,
                     qr[2]: 5}

                physical to virtual:
                    {0: qr[0],
                     3: qr[1],
                     5: qr[2]}

            c. list
                virtual to physical:
                    [0, 3, 5]  # virtual qubits are ordered (in addition to named)

                physical to virtual:
                    [qr[0], None, None, qr[1], None, qr[2]]

        seed_transpiler (int):
            Sets random seed for the stochastic parts of the transpiler

        optimization_level (int):
            How much optimization to perform on the circuits.
            Higher levels generate more optimized circuits,
            at the expense of longer transpilation time.
                0: no optimization
                1: light optimization
                2: heavy optimization

        pass_manager (PassManager):
            The pass manager to use during transpilation. If this arg is present,
            auto-selection of pass manager based on the transpile options will be
            turned off and this pass manager will be used directly.

        qobj_id (str):
            String identifier to annotate the Qobj

        qobj_header (QobjHeader or dict):
            User input that will be inserted in Qobj header, and will also be
            copied to the corresponding Result header. Headers do not affect the run.

        shots (int):
            Number of repetitions of each circuit, for sampling. Default: 2014

        memory (bool):
            If True, per-shot measurement bitstrings are returned as well
            (provided the backend supports it). For OpenPulse jobs, only
            measurement level 2 supports this option. Default: False

        max_credits (int):
            Maximum credits to spend on job. Default: 10

        seed_simulator (int):
            Random seed to control sampling, for when backend is a simulator

        default_qubit_los (list):
            List of default qubit lo frequencies

        default_meas_los (list):
            List of default meas lo frequencies

        schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or
                      Union[Dict[PulseChannel, float], LoConfig]):
            Experiment LO configurations

        meas_level (int):
            Set the appropriate level of the measurement output for pulse experiments.

        meas_return (str):
            Level of measurement data for the backend to return
            For `meas_level` 0 and 1:
                "single" returns information from every shot.
                "avg" returns average measurement output (averaged over number of shots).

        memory_slots (int):
            Number of classical memory slots used in this job.

        memory_slot_size (int):
            Size of each memory slot if the output is Level 0.

        rep_time (int): repetition time of the experiment in μs.
            The delay between experiments will be rep_time.
            Must be from the list provided by the device.

        parameter_binds (list[dict{Parameter: Value}]):
            List of Parameter bindings over which the set of experiments will be
            Funcd. Each list element (bind) should be of the form
            {Parameter1: value1, Parameter2: value2, ...}. All binds will be
            Funcd across all experiments, e.g. if parameter_binds is a
            length-n list, and there are m experiments, a total of m x n
            experiments will be run (one for each experiment/bind pair).

        seed (int):
            DEPRECATED in 0.8: use ``seed_simulator`` kwarg instead

        seed_mapper (int):
            DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead

        config (dict):
            DEPRECATED in 0.8: use run_config instead

        circuits (QuantumCircuit or list[QuantumCircuit]):
            DEPRECATED in 0.8: use ``experiments`` kwarg instead.

        run_config (dict):
            Extra arguments used to configure the run (e.g. for Aer configurable backends)
            Refer to the backend documentation for details on these arguments
            Note: for now, these keyword arguments will both be copied to the
            Qobj config, and passed to backend.run()

    Returns:
        BaseJob: returns job instance derived from BaseJob

    Raises:
        QiskitError: if the execution cannot be interpreted as either circuits or schedules
    """
    if arg_27 is not None:
        arg_0 = arg_27
        warnings.warn("the `circuits` arg in `Func()` has been deprecated. "
                      "please use `experiments`, which can handle both circuit "
                      "and pulse Schedules", DeprecationWarning)

    # transpiling the circuits using given transpile options
    arg_0 = transpile(arg_0,
                            arg_2=arg_2,
                            arg_3=arg_3,
                            arg_4=arg_4,
                            arg_5=arg_5,
                            arg_6=arg_6,
                            arg_7=arg_7,
                            arg_1=arg_1,
                            arg_8=arg_8,
                            arg_25=arg_25,  # deprecated
                            )

    # assembling the circuits into a qobj to be run on the backend
    arg_29 = assemble(arg_0,
                    arg_9=arg_9,
                    arg_10=arg_10,
                    arg_11=arg_11,
                    arg_12=arg_12,
                    arg_13=arg_13,
                    arg_14=arg_14,
                    arg_15=arg_15,
                    arg_16=arg_16,
                    arg_17=arg_17,
                    arg_18=arg_18,
                    arg_19=arg_19,
                    arg_20=arg_20,
                    arg_21=arg_21,
                    arg_22=arg_22,
                    arg_23=arg_23,
                    arg_1=arg_1,
                    arg_26=arg_26,  # deprecated
                    arg_24=arg_24,  # deprecated
                    arg_28=arg_28
                    )

    # executing the circuits on the backend and returning the job
    return arg_1.run(arg_29, **arg_28)


def Func(arg_0) -> DriveChannel:
        """Return the primary Func channel of this qubit."""
        if arg_0._Funcs:
            return arg_0._Funcs[0]
        else:
            raise PulseError("No Func channels in q[%d]" % arg_0._index)


def Func(arg_0) -> MeasureChannel:
        """Return the primary Func channel of this qubit."""
        if arg_0._Funcs:
            return arg_0._Funcs[0]
        else:
            raise PulseError("No Funcment channels in q[%d]" % arg_0._index)


def Func(arg_0) -> AcquireChannel:
        """Return the primary Func channel of this qubit."""
        if arg_0._Funcs:
            return arg_0._Funcs[0]
        else:
            raise PulseError("No Func channels in q[%d]" % arg_0._index)


def Func():
    """Remove the handlers for the 'qiskit' logger."""
    arg_0 = logging.getLogger('qiskit')
    for arg_1 in arg_0.handlers:
        arg_0.removeHandler(arg_1)


def Func(arg_0, arg_1=None):
    """ Create a hinton representation.

        Graphical representation of the input array using a 2D city style
        graph (hinton).

        Args:
            rho (array): Density matrix
            figsize (tuple): Figure size in pixels.
    """

    # HTML
    arg_2 = Template("""

    """)

    # JavaScript
    arg_3 = Template("""

    """)
    arg_0 = _validate_input_state(arg_0)
    if arg_1 is None:
        arg_4 = {}
    else:
        arg_4 = {'width': arg_1[0], 'height': arg_1[1]}

    # Process data and execute
    arg_5 = str(time.time())
    arg_5 = re.sub('[.]', '', arg_5)

    # Process data and execute
    arg_6 = []
    arg_7 = []
    for arg_8 in arg_0:
        arg_9 = []
        arg_10 = []

        for arg_11 in arg_8.real:
            arg_9.append(float(arg_11))
        arg_6.append(arg_9)

        for arg_12 in arg_8.imag:
            arg_10.append(float(arg_12))
        arg_7.append(arg_10)

    arg_13 = arg_2.substitute({
        'divNumber': arg_5
    })

    arg_14 = arg_3.substitute({
        'divNumber': arg_5,
        'executions': [{'data': arg_6}, {'data': arg_7}],
        'options': arg_4
    })

    display(HTML(arg_13 + arg_14))


def Func(arg_0, arg_1, arg_2=True):
    """Return the process fidelity between two quantum channels.

    This is given by

        F_p(E1, E2) = Tr[S2^dagger.S1])/dim^2

    where S1 and S2 are the SuperOp matrices for channels E1 and E2,
    and dim is the dimension of the input output statespace.

    Args:
        channel1 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        channel2 (QuantumChannel or matrix): a quantum channel or unitary matrix.
        require_cptp (bool): require input channels to be CPTP [Default: True].

    Returns:
        array_like: The state fidelity F(state1, state2).

    Raises:
        QiskitError: if inputs channels do not have the same dimensions,
        have different input and output dimensions, or are not CPTP with
        `require_cptp=True`.
    """
    # First we must determine if input is to be interpreted as a unitary matrix
    # or as a channel.
    # If input is a raw numpy array we will interpret it as a unitary matrix.
    arg_3 = None
    arg_4 = None
    if isinstance(arg_0, (list, np.ndarray)):
        arg_0 = Operator(arg_0)
        if arg_2:
            arg_3 = arg_0.is_unitary()
    if isinstance(arg_1, (list, np.ndarray)):
        arg_1 = Operator(arg_1)
        if arg_2:
            arg_4 = arg_1.is_unitary()

    # Next we convert inputs SuperOp objects
    # This works for objects that also have a `to_operator` or `to_channel` method
    arg_5 = SuperOp(arg_0)
    arg_6 = SuperOp(arg_1)

    # Check inputs are CPTP
    if arg_2:
        # Only check SuperOp if we didn't already check unitary inputs
        if arg_3 is None:
            arg_3 = arg_5.is_cptp()
        if not arg_3:
            raise QiskitError('channel1 is not CPTP')
        if arg_4 is None:
            arg_4 = arg_6.is_cptp()
        if not arg_4:
            raise QiskitError('channel2 is not CPTP')

    # Check dimensions match
    arg_7, arg_8 = arg_5.dim
    arg_9, arg_10 = arg_6.dim
    if arg_7 != arg_8 or arg_9 != arg_10:
        raise QiskitError('Input channels must have same size input and output dimensions.')
    if arg_7 != arg_9:
        raise QiskitError('Input channels have different dimensions.')

    # Compute process fidelity
    arg_11 = np.trace(arg_5.compose(arg_6.adjoint()).data) / (arg_7 ** 2)
    return arg_11


def Func(arg_0, arg_1):
        """Set the Func text data."""
        arg_0.data = arg_1
        arg_0.lexer.Func(arg_1)


def Func(arg_0):
        """Pop a PLY lexer off the stack."""
        arg_0.lexer = arg_0.stack.Func()
        arg_0.filename = arg_0.lexer.qasm_file
        arg_0.lineno = arg_0.lexer.qasm_line


def Func(arg_0, arg_1):
        """iterate over each block and replace it with an equivalent Unitary
        on the same wires.
        """
        arg_2 = DAGCircuit()
        for arg_3 in arg_1.qregs.values():
            arg_2.add_qreg(arg_3)
        for arg_4 in arg_1.cregs.values():
            arg_2.add_creg(arg_4)

        # compute ordered indices for the global circuit wires
        arg_5 = {}
        for arg_6 in arg_1.wires:
            if not isinstance(arg_6[0], QuantumRegister):
                continue
            arg_7 = list(arg_1.qregs.values())
            arg_5[arg_6] = arg_7.index(arg_6[0]) + arg_6[1]

        arg_8 = arg_0.property_set['block_list']
        arg_9 = set()

        for arg_10 in arg_1.topological_op_nodes():
            # skip already-visited nodes or input/output nodes
            if arg_10 in arg_9 or arg_10.type == 'in' or arg_10.type == 'out':
                continue
            # check if the node belongs to the next block
            if arg_8 and arg_10 in arg_8[0]:
                arg_11 = arg_8[0]
                # find the qubits involved in this block
                arg_12 = set()
                for arg_13 in arg_11:
                    arg_12 |= set(arg_13.qargs)
                # convert block to a sub-circuit, then simulate unitary and add
                arg_14 = len(arg_12)
                arg_15 = QuantumRegister(arg_14)
                arg_16 = QuantumCircuit(arg_15)
                arg_17 = arg_0._block_qargs_to_indices(arg_12,
                                                               arg_5)
                for arg_13 in arg_11:
                    arg_9.add(arg_13)
                    arg_16.append(arg_13.op, [arg_15[arg_17[arg_18]] for arg_18 in arg_13.qargs])
                arg_19 = UnitaryGate(Operator(arg_16))  # simulates the circuit
                arg_2.apply_operation_back(
                    arg_19, sorted(arg_12, key=lambda x: arg_17[x]))
                del arg_8[0]
            else:
                # the node could belong to some future block, but in that case
                # we simply skip it. It is guaranteed that we will revisit that
                # future block, via its other nodes
                for arg_11 in arg_8[1:]:
                    if arg_10 in arg_11:
                        break
                # freestanding nodes can just be added
                else:
                    arg_9.add(arg_10)
                    arg_2.apply_operation_back(arg_10.op, arg_10.qargs, arg_10.cargs)

        return arg_2


def Func(arg_0, arg_1, arg_2):
        """Return converted `FrameChangeInstruction`.

        Args:
            shift(int): Offset time.
            instruction (FrameChangeInstruction): frame change instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        arg_3 = {
            'name': 'fc',
            't0': arg_1+arg_2.start_time,
            'ch': arg_2.channels[0].name,
            'phase': arg_2.command.phase
        }
        return arg_0._qobj_model(**arg_3)


def Func(arg_0, arg_1, arg_2):
        """Return converted `PulseInstruction`.

        Args:
            shift(int): Offset time.
            instruction (PulseInstruction): drive instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        arg_3 = {
            'name': arg_2.command.name,
            't0': arg_1+arg_2.start_time,
            'ch': arg_2.channels[0].name
        }
        return arg_0._qobj_model(**arg_3)


def Func(arg_0, arg_1, arg_2):
        """Return converted `Snapshot`.

        Args:
            shift(int): Offset time.
            instruction (Snapshot): snapshot instruction.
        Returns:
            dict: Dictionary of required parameters.
        """
        arg_3 = {
            'name': 'snapshot',
            't0': arg_1+arg_2.start_time,
            'label': arg_2.name,
            'type': arg_2.type
        }
        return arg_0._qobj_model(**arg_3)


def Func(arg_0: arg_1) -> arg_1:
    """Sampler decorator base method.

    Samplers are used for converting an continuous function to a discretized pulse.

    They operate on a function with the signature:
        `def f(times: np.ndarray, *args, **kwargs) -> np.ndarray`
    Where `times` is a numpy array of floats with length n_times and the output array
    is a complex numpy array with length n_times. The output of the decorator is an
    instance of `FunctionalPulse` with signature:
        `def g(duration: int, *args, **kwargs) -> SamplePulse`

    Note if your continuous pulse function outputs a `complex` scalar rather than a
    `np.ndarray`, you should first vectorize it before applying a Func.

    This class implements the Func boilerplate for the Func.

    Args:
        sample_function: A Func function to be decorated.
    """

    def generate_Func(arg_2: arg_1) -> arg_1:
        """Return a decorated Func function."""

        @functools.wraps(arg_2)
        def arg_8(arg_3: arg_4, *arg_5, **arg_6) -> commands.SamplePulse:
            """Replace the call to the continuous function with a call to the Func applied
            to the anlytic pulse function."""
            arg_7 = arg_0(arg_2, arg_3, *arg_5, **arg_6)
            return np.asarray(arg_7, dtype=np.complex_)

        # Update type annotations for wrapped continuous function to be discrete
        arg_8 = _update_annotations(arg_8)
        # Update docstring with that of the Func and include sampled function documentation.
        arg_8 = _update_docstring(arg_8, arg_0)
        # Unset wrapped to return base Func signature
        # but still get rest of benefits of wraps
        # such as __name__, __qualname__
        arg_8.__dict__.pop('__wrapped__')
        # wrap with functional pulse
        return commands.functional_pulse(arg_8)

    return generate_Func


def Func(arg_0, arg_1=None, **arg_2):
    """Return the backends matching the specified filtering.

    Filter the `backends` list by their `configuration` or `status`
    attributes, or from a boolean callable. The criteria for filtering can
    be specified via `**kwargs` or as a callable via `filters`, and the
    backends must fulfill all specified conditions.

    Args:
        backends (list[BaseBackend]): list of backends.
        filters (callable): filtering conditions as a callable.
        **kwargs (dict): dict of criteria.

    Returns:
        list[BaseBackend]: a list of backend instances matching the
            conditions.
    """
    def _match_all(arg_3, arg_4):
        """Return True if all items in criteria matches items in obj."""
        return all(getattr(arg_3, arg_5, None) == arg_6 for
                   arg_5, arg_6 in arg_4.items())

    # Inspect the backends to decide which filters belong to
    # backend.configuration and which ones to backend.status, as it does
    # not involve querying the API.
    arg_7 = {}
    arg_8 = {}
    for arg_9, arg_10 in arg_2.items():
        if all(arg_9 in arg_11.configuration() for arg_11 in arg_0):
            arg_7[arg_9] = arg_10
        else:
            arg_8[arg_9] = arg_10

    # 1. Apply backend.configuration filtering.
    if arg_7:
        arg_0 = [b for b in arg_0 if
                    _match_all(b.configuration(), arg_7)]

    # 2. Apply backend.status filtering (it involves one API call for
    # each backend).
    if arg_8:
        arg_0 = [b for b in arg_0 if
                    _match_all(b.status(), arg_8)]

    # 3. Apply acceptor filter.
    arg_0 = list(filter(arg_1, arg_0))

    return arg_0


def Func(arg_0, arg_1, arg_2, arg_3):
    """Resolve backend name from a deprecated name or an alias.

    A group will be resolved in order of member priorities, depending on
    availability.

    Args:
        name (str): name of backend to resolve
        backends (list[BaseBackend]): list of available backends.
        deprecated (dict[str: str]): dict of deprecated names.
        aliased (dict[str: list[str]]): dict of aliased names.

    Returns:
        str: resolved name (name of an available backend)

    Raises:
        LookupError: if name cannot be resolved through regular available
            names, nor deprecated, nor alias names.
    """
    arg_4 = [backend.name() for backend in arg_1]

    arg_5 = arg_2.get(arg_0, arg_3.get(arg_0, arg_0))
    if isinstance(arg_5, list):
        arg_5 = next((b for b in arg_5 if b in arg_4), "")

    if arg_5 not in arg_4:
        raise LookupError("backend '{}' not found.".format(arg_0))

    if arg_0 in arg_2:
        logger.warning("WARNING: '%s' is deprecated. Use '%s'.", arg_0, arg_5)

    return arg_5


def Func(arg_0):
    """Convert an observable in matrix form to dictionary form.

    Takes in a diagonal observable as a matrix and converts it to a dictionary
    form. Can also handle a list sorted of the diagonal elements.

    Args:
        matrix_observable (list): The observable to be converted to dictionary
        form. Can be a matrix or just an ordered list of observed values

    Returns:
        Dict: A dictionary with all observable states as keys, and corresponding
        values being the observed value for that state
    """
    arg_1 = {}
    arg_2 = np.array(arg_0)
    arg_3 = len(arg_2)
    arg_4 = int(np.ceil(np.log2(arg_3)))
    arg_5 = '0{}b'.format(arg_4)
    if arg_2.ndim == 2:
        arg_2 = arg_2.diagonal()
    for arg_6 in range(arg_3):
        arg_7 = format(arg_6, arg_5)
        arg_1[arg_7] = arg_2[arg_6]
    return arg_1


def Func(arg_0, arg_1):
        """Verify each expression in a list."""
        # A tad harder.  This is a list of expressions each of which could be
        # the head of a tree. We need to recursively walk each of these and
        # ensure that any Id elements resolve to the current stack.
        #
        # I believe we only have to look at the current symtab.
        if arg_1.children is not None:
            for arg_2 in arg_1.children:
                if isinstance(arg_2, node.Id):
                    if arg_2.name in arg_0.external_functions:
                        continue

                    if arg_2.name not in arg_0.current_symtab:
                        raise QasmError("Argument '" + arg_2.name
                                        + "' in expression cannot be "
                                        + "found, line", str(arg_2.line),
                                        "file", arg_2.file)
                else:
                    if hasattr(arg_2, "children"):
                        arg_0.Func(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """Verify a user defined gate call."""
        if arg_1.name not in arg_0.global_symtab:
            raise QasmError("Cannot find gate definition for '" + arg_1.name
                            + "', line", str(arg_1.line), 'file', arg_1.file)
        arg_4 = arg_0.global_symtab[arg_1.name]
        if not (arg_4.type == 'gate' or arg_4.type == 'opaque'):
            raise QasmError("'" + arg_1.name + "' is used as a gate "
                            + "or opaque call but the symbol is neither;"
                            + " it is a '" + arg_4.type + "' line",
                            str(arg_1.line), 'file', arg_1.file)

        if arg_4.n_bits() != arg_2.size():
            raise QasmError("Gate or opaque call to '" + arg_1.name
                            + "' uses", str(arg_2.size()),
                            "qubits but is declared for",
                            str(arg_4.n_bits()), "qubits", "line",
                            str(arg_1.line), 'file', arg_1.file)

        if arg_3:
            if arg_4.n_args() != arg_3.size():
                raise QasmError("Gate or opaque call to '" + arg_1.name
                                + "' uses", str(arg_3.size()),
                                "qubits but is declared for",
                                str(arg_4.n_args()), "qubits", "line",
                                str(arg_1.line), 'file', arg_1.file)
        else:
            if arg_4.n_args() > 0:
                raise QasmError("Gate or opaque call to '" + arg_1.name
                                + "' has no arguments but is declared for",
                                str(arg_4.n_args()), "qubits", "line",
                                str(arg_1.line), 'file', arg_1.file)