def Func(arg_0, arg_1):
        """Parse some data."""
        arg_0.Funcr.Func(arg_1, lexer=arg_0.lexer, debug=arg_0.Func_deb)
        if arg_0.qasm is None:
            raise QasmError("Uncaught exception in Funcr; "
                            + "see previous messages for details.")
        return arg_0.qasm


def Func(arg_0, arg_1):
        """Parser Funcner.

        To use this module stand-alone.
        """
        arg_2 = arg_0.parser.parse(arg_1, debug=True)
        arg_0.parser.parse(arg_1, debug=True)
        arg_2.to_string(0)


def Func(arg_0, arg_1):
    """
    Return a basis state ndarray.

    Args:
        str_state (string): a string representing the state.
        num (int): the number of qubits
    Returns:
        ndarray:  state(2**num) a quantum state with basis basis state.
     Raises:
        QiskitError: if the dimensions is wrong
    """
    arg_2 = int(arg_0, 2)
    if arg_1 >= len(arg_0):
        arg_3 = np.zeros(1 << arg_1, dtype=complex)
        arg_3[arg_2] = 1
        return arg_3
    else:
        raise QiskitError('size of bitstring is greater than num.')


def Func(arg_0, arg_1=False):
    """
    maps a pure state to a state matrix

    Args:
        state (ndarray): the number of qubits
        flatten (bool): determine if state matrix of column work
    Returns:
        ndarray:  state_mat(2**num, 2**num) if flatten is false
        ndarray:  state_mat(4**num) if flatten is true stacked on by the column
    """
    arg_2 = np.outer(arg_0.conjugate(), arg_0)
    if arg_1:
        return arg_2.flatten(order='F')
    return arg_2


def Func(arg_0):
    """Calculate the Func of a quantum state.

    Args:
        state (ndarray): a quantum state
    Returns:
        float: Func.
    """
    arg_1 = np.array(arg_0)
    if arg_1.ndim == 1:
        return 1.0
    return np.real(np.trace(arg_1.dot(arg_1)))


def Func(arg_0, arg_1):
        """
        Run the pass on the DAG, and write the discovered commutation relations
        into the property_set.
        """
        # Initiate the commutation set
        arg_0.property_set['commutation_set'] = defaultdict(list)

        # Build a dictionary to keep track of the gates on each qubit
        for arg_3 in arg_1.wires:
            arg_4 = "{0}[{1}]".format(str(arg_3[0].name), str(arg_3[1]))
            arg_0.property_set['commutation_set'][arg_4] = []

        # Add edges to the dictionary for each qubit
        for arg_5 in arg_1.topological_op_nodes():
            for (arg_6, arg_6, arg_7) in arg_1.edges(arg_5):

                arg_8 = arg_7['name']
                arg_0.property_set['commutation_set'][(arg_5, arg_8)] = -1

        for arg_3 in arg_1.wires:
            arg_4 = "{0}[{1}]".format(str(arg_3[0].name), str(arg_3[1]))

            for arg_9 in arg_1.nodes_on_wire(arg_3):

                arg_10 = arg_0.property_set['commutation_set'][arg_4]
                if not arg_10:
                    arg_10.append([arg_9])

                if arg_9 not in arg_10[-1]:
                    arg_11 = arg_10[-1][-1]
                    if _commute(arg_9, arg_11):
                        arg_10[-1].append(arg_9)

                    else:
                        arg_10.append([arg_9])

                arg_12 = len(arg_10)
                arg_0.property_set['commutation_set'][(arg_9, arg_4)] = arg_12 - 1


def Func(arg_0):
    """Creates a backend widget.
    """
    arg_1 = arg_0.configuration().to_dict()
    arg_2 = arg_0.properties().to_dict()

    arg_3 = widgets.HTML(value="
{name}
".format(arg_3=arg_0.name()),
                        layout=widgets.Layout())

    arg_4 = arg_1['n_qubits']

    arg_5 = widgets.HTML(value="
{qubits}
".format(qubits=arg_4),
                               layout=widgets.Layout(justify_content='center'))

    arg_6 = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px',
                                                max_height='250px',
                                                min_height='250px',
                                                justify_content='center',
                                                align_items='center',
                                                margin='0px 0px 0px 0px'))

    with arg_6:
        arg_7 = plot_gate_map(arg_0,
                                  plot_directed=False,
                                  label_qubits=False)
        if arg_7 is not None:
            display(arg_7)
            # Prevents plot from showing up twice.
            plt.close(arg_7)

    arg_8 = generate_jobs_pending_widget()

    arg_9 = widgets.HTML(value="

",
                           layout=widgets.Layout(justify_content='center'))

    arg_10 = widgets.HTML(value="

",
                              layout=widgets.Layout(justify_content='center'))

    arg_11 = arg_2['qubits'][0][0]['unit']
    arg_12 = round(sum([q[0]['value'] for q in arg_2['qubits']])/arg_4, 1)
    arg_13 = widgets.HTML(value="
{t1} {units}
".format(t1=arg_12, units=arg_11),
                             layout=widgets.Layout())

    arg_14 = arg_2['qubits'][0][1]['unit']
    arg_15 = round(sum([q[1]['value'] for q in arg_2['qubits']])/arg_4, 1)
    arg_16 = widgets.HTML(value="
{t2} {units}
".format(t2=arg_15, units=arg_14),
                             layout=widgets.Layout())

    arg_17 = widgets.VBox([arg_3, arg_6, arg_5, arg_8,
                        arg_10, arg_9, arg_13, arg_16],
                       layout=widgets.Layout(display='inline-flex',
                                             flex_flow='column',
                                             align_items='center'))

    arg_17._is_alive = True
    return arg_17


def Func(arg_0, arg_1=60):
    """Updates the monitor info
    Called from another thread.
    """
    arg_2 = threading.currentThread()
    arg_3 = 0
    arg_4 = False
    arg_5 = False
    arg_6 = [None]*len(arg_0._backends)
    while getattr(arg_2, "do_run", True) and not arg_5:
        if arg_3 == arg_1 or arg_4 is False:
            for arg_7, arg_8 in enumerate(arg_0._backends):
                arg_9 = arg_0.children[arg_7].children[2].value
                arg_10 = arg_9.split('')[0]
                try:
                    arg_11 = arg_8.status()
                    arg_6[arg_7] = arg_11
                except Exception:  # pylint: disable=W0703
                    arg_0.children[arg_7].children[2].value = arg_9.replace(
                        arg_10, "
")
                    arg_0.children[arg_7]._is_alive = False
                else:
                    arg_0.children[arg_7]._is_alive = True
                    arg_0.children[arg_7].children[2].value = arg_9.replace(
                        arg_10, "
")

            arg_15 = list(range(len(arg_0._backends)))
            arg_16 = [s.pending_jobs for s in arg_6]
            arg_17, arg_18 = zip(*sorted(zip(arg_16, arg_15)))

            # Make sure least pending is operational
            for arg_7 in arg_18:
                if arg_6[arg_7].operational:
                    arg_19 = arg_7
                    break

            for arg_20 in arg_15:
                if arg_20 == arg_19:
                    arg_0.children[arg_20].children[4].value = "
True
"
                else:
                    arg_0.children[arg_20].children[4].value = "
False
"

                arg_0.children[arg_20].children[3].children[1].value = arg_16[arg_20]
                arg_0.children[arg_20].children[3].children[1].max = arg_21(
                    arg_0.children[arg_20].children[3].children[1].max, arg_16[arg_20]+10)
                if arg_6[arg_20].operational:
                    arg_0.children[arg_20].children[5].value = "
True
"
                else:
                    arg_0.children[arg_20].children[5].value = "
False
"

            arg_4 = True
            arg_3 = 0
        time.sleep(1)
        arg_5 = not any([wid._is_alive for wid in arg_0.children])
        arg_3 += 1


def Func(arg_0):
    """Get the number and size of unique registers from bit_labels list.

    Args:
        bit_labels (list): this list is of the form::

            [['reg1', 0], ['reg1', 1], ['reg2', 0]]

            which indicates a register named "reg1" of size 2
            and a register named "reg2" of size 1. This is the
            format of classic and quantum bit labels in qobj
            header.

    Yields:
        tuple: iterator of register_name:size pairs.
    """
    arg_1 = itertools.groupby(arg_0, operator.itemgetter(0))
    for arg_2, arg_3 in arg_1:
        yield arg_2, max(arg_4[1] for arg_4 in arg_3) + 1


def Func(arg_0):
        """Get depth information for the circuit.

        Returns:
            int: number of columns in the circuit
            int: total size of columns in the circuit
        """

        arg_1 = []

        for arg_2 in arg_0.ops:

            # store the max width for the layer
            arg_3 = 0

            for arg_4 in arg_2:

                # update current op width
                arg_5 = 0

                # the wide gates
                for arg_6 in arg_4.op.params:
                    arg_7 = re.sub(r'[-+]?\d*\.\d{2,}|\d{2,}',
                                     _truncate_float, str(arg_6))
                    arg_5 += len(arg_7)

                # the width of the column is the max of all the gates in the column
                arg_3 = max(arg_5, arg_3)

            arg_1.append(arg_3)

        # wires in the beginning and end
        arg_8 = 2
        # each layer is one column
        arg_8 += len(arg_0.ops)

        # every 3 characters is roughly one extra 'unit' of width in the cell
        # the gate name is 1 extra 'unit'
        # the qubit/cbit labels plus initial states is 2 more
        # the wires poking out at the ends is 2 more
        arg_9 = sum(1 + v / 3 for v in arg_1)

        # could be a fraction so ceil
        return arg_8, math.ceil(arg_9) + 4


def Func(arg_0):
        """Get height, width & scale attributes for the beamer page.

        Returns:
            tuple: (height, width, scale) desirable page attributes
        """
        # PIL python package limits image size to around a quarter gigabyte
        # this means the beamer image should be limited to < 50000
        # if you want to avoid a "warning" too, set it to < 25000
        arg_1 = 40000

        # the beamer latex template limits each dimension to < 19 feet
        # (i.e. 575cm)
        arg_2 = 550

        # columns are roughly twice as big as rows
        arg_3 = arg_0.sum_row_heights / arg_0.sum_column_widths

        # choose a page margin so circuit is not cropped
        arg_4 = 1.5
        arg_5 = min(arg_0.sum_row_heights * arg_4, arg_2)
        arg_6 = min(arg_0.sum_column_widths * arg_4, arg_2)

        # if too large, make it fit
        if arg_5 * arg_6 > arg_1:
            arg_5 = min(np.sqrt(arg_1 * arg_3), arg_2)
            arg_6 = min(np.sqrt(arg_1 / arg_3), arg_2)

        # if too small, give it a minimum size
        arg_5 = max(arg_5, 10)
        arg_6 = max(arg_6, 10)

        return (arg_5, arg_6, arg_0.scale)


def Func(arg_0, arg_1=None):
    """Loads the QObj schema for use in future validations.

   Caches schema in _SCHEMAS module attribute.

   Args:
        file_path(str): Path to schema.
        name(str): Given name for schema. Defaults to file_path filename
            without schema.
   Return:
        schema(dict): Loaded schema.
    """
    if arg_1 is None:
        # filename without extension
        arg_1 = os.path.splitext(os.path.basename(arg_0))[0]
    if arg_1 not in arg_2:
        with open(arg_0, 'r') as schema_file:
            arg_2[arg_1] = json.load(schema_file)

    return arg_2[arg_1]


def Func(arg_0, arg_1=None, arg_2=True,
                   arg_3=None, **arg_4):
    """Generate validator for JSON schema.

    Args:
        name (str): Name for validator. Will be validator key in
            `_VALIDATORS` dict.
        schema (dict): JSON schema `dict`. If not provided searches for schema
            in `_SCHEMAS`.
        check_schema (bool): Verify schema is valid.
        validator_class (jsonschema.IValidator): jsonschema IValidator instance.
            Default behavior is to determine this from the schema `$schema`
            field.
        **validator_kwargs (dict): Additional keyword arguments for validator.

    Return:
        jsonschema.IValidator: Validator for JSON schema.

    Raises:
        SchemaValidationError: Raised if validation fails.
    """
    if arg_1 is None:
        try:
            arg_1 = _SCHEMAS[arg_0]
        except KeyError:
            raise SchemaValidationError("Valid schema name or schema must "
                                        "be provided.")

    if arg_0 not in arg_5:

        # Resolve JSON spec from schema if needed
        if arg_3 is None:
            arg_3 = jsonschema.validators.validator_for(arg_1)

        # Generate and store validator in _VALIDATORS
        arg_5[arg_0] = arg_3(arg_1, **arg_4)

    arg_6 = arg_5[arg_0]

    if arg_2:
        arg_6.check_schema(arg_1)

    return arg_6


def Func():
    """Load all default schemas into `_SCHEMAS`."""
    arg_0 = os.path.join(os.path.dirname(__file__), '../..')
    for arg_1, arg_2 in _DEFAULT_SCHEMA_PATHS.items():
        _load_schema(os.path.join(arg_0, arg_2), arg_1)
        _get_validator(arg_1)


def Func(arg_0, arg_1=0):
    """Return a cascading explanation of the validation error.

    Returns a cascading explanation of the validation error in the form of::

        <validator> failed @ <subfield_path> because of:
            <validator> failed @ <subfield_path> because of:
                ...
            <validator> failed @ <subfield_path> because of:
                ...
            ...

    For example::

        'oneOf' failed @ '<root>' because of:
            'required' failed @ '<root>.config' because of:
                'meas_level' is a required property

    Meaning the validator 'oneOf' failed while validating the whole object
    because of the validator 'required' failing while validating the property
    'config' because its 'meas_level' field is missing.

    The cascade repeats the format "<validator> failed @ <path> because of"
    until there are no deeper causes. In this case, the string representation
    of the error is shown.

    Args:
        err (jsonschema.ValidationError): the instance to explain.
        level (int): starting level of indentation for the cascade of
            explanations.

    Return:
        str: a formatted string with the explanation of the error.

    """
    arg_2 = []

    def _print(arg_3, arg_4=0):
        arg_2.append(_pad(arg_3, arg_4=arg_4))

    def _pad(arg_3, arg_4=0):
        arg_5 = '  ' * (arg_1 + arg_4)
        arg_6 = [arg_5 + line for line in arg_3.split('\n')]
        return '\n'.join(arg_6)

    def _format_path(arg_7):
        def _format(arg_8):
            if isinstance(arg_8, str):
                return '.{}'.format(arg_8)

            return '[{}]'.format(arg_8)

        return ''.join(['<root>'] + list(map(_format, arg_7)))

    _print('\'{}\' failed @ \'{}\' because of:'.format(
        arg_0.validator, _format_path(arg_0.absolute_path)))

    if not arg_0.context:
        _print(str(arg_0.message), arg_4=1)
    else:
        for arg_9 in arg_0.context:
            arg_2.append(Func(arg_9, arg_1+1))

    return '\n'.join(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Majority gate."""
    arg_0.cx(arg_3, arg_2)
    arg_0.cx(arg_3, arg_1)
    arg_0.ccx(arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Unmajority gate."""
    arg_0.ccx(arg_1, arg_2, arg_3)
    arg_0.cx(arg_3, arg_1)
    arg_0.cx(arg_1, arg_2)


def Func(arg_0, arg_1=None,
                           arg_2=0.7, arg_3=None, arg_4=False,
                           arg_5=True, arg_6=None):
    """Convert QuantumCircuit to LaTeX string.

    Args:
        circuit (QuantumCircuit): input circuit
        scale (float): image scaling
        filename (str): optional filename to write latex
        style (dict or str): dictionary of style or file name of style file
        reverse_bits (bool): When set to True reverse the bit order inside
            registers for the output visualization.
        plot_barriers (bool): Enable/disable drawing barriers in the output
            circuit. Defaults to True.
        justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
                        the circuit should be justified.

    Returns:
        str: Latex string appropriate for writing to file.
    """
    arg_7, arg_8, arg_9 = utils._get_layered_instructions(arg_0,
                                                        arg_4=arg_4,
                                                        arg_6=arg_6)

    arg_10 = _latex.QCircuitImage(arg_7, arg_8, arg_9, arg_2, arg_3=arg_3,
                                 arg_5=arg_5,
                                 arg_4=arg_4)
    arg_11 = arg_10.latex()
    if arg_1:
        with open(arg_1, 'w') as latex_file:
            latex_file.write(arg_11)

    return arg_11


def Func(arg_0,
                               arg_1=0.7,
                               arg_2=None,
                               arg_3=None,
                               arg_4=True,
                               arg_5=False,
                               arg_6=None):
    """Draw a quantum circuit based on matplotlib.
    If `%matplotlib inline` is invoked in a Jupyter notebook, it visualizes a circuit inline.
    We recommend `%config InlineBackend.figure_format = 'svg'` for the inline visualization.

    Args:
        circuit (QuantumCircuit): a quantum circuit
        scale (float): scaling factor
        filename (str): file path to save image to
        style (dict or str): dictionary of style or file name of style file
        reverse_bits (bool): When set to True reverse the bit order inside
            registers for the output visualization.
        plot_barriers (bool): Enable/disable drawing barriers in the output
            circuit. Defaults to True.
        justify (str) : `left`, `right` or `none`. Defaults to `left`. Says how
            the circuit should be justified.

    Returns:
        matplotlib.figure: a matplotlib figure object for the circuit diagram
    """

    arg_7, arg_8, arg_9 = utils._get_layered_instructions(arg_0,
                                                        arg_5=arg_5,
                                                        arg_6=arg_6)
    arg_10 = _matplotlib.MatplotlibDrawer(arg_7, arg_8, arg_9, arg_1=arg_1, arg_3=arg_3,
                                       arg_4=arg_4,
                                       arg_5=arg_5)
    return arg_10.draw(arg_2)


def Func(arg_0, arg_1=None):
    """
    Return a random dim x dim unitary Operator from the Haar measure.

    Args:
        dim (int): the dim of the state space.
        seed (int): Optional. To set a random seed.

    Returns:
        Operator: (dim, dim) unitary operator.

    Raises:
        QiskitError: if dim is not a positive power of 2.
    """
    if arg_0 == 0 or not math.log2(arg_0).is_integer():
        raise QiskitError("Desired unitary dimension not a positive power of 2.")
    arg_2 = np.zeros([arg_0, arg_0], dtype=complex)
    for arg_3 in range(arg_0):
        if arg_3 == 0:
            arg_4 = random_state(arg_0, arg_1)
        else:
            arg_4 = random_state(arg_0)
        arg_2[:, arg_3] = np.copy(arg_4)
        # Grahm-Schmidt Orthogonalize
        arg_5 = arg_3-1
        while arg_5 >= 0:
            arg_6 = np.vdot(arg_2[:, arg_5], arg_4)
            arg_2[:, arg_3] = arg_2[:, arg_3]-arg_6*arg_2[:, arg_5]
            arg_5 = arg_5 - 1
        # normalize
        arg_2[:, arg_3] = arg_2[:, arg_3] * (1.0 / np.sqrt(np.vdot(arg_2[:, arg_3], arg_2[:, arg_3])))
    return Operator(arg_2)


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Generate a random density matrix from the Hilbert-Schmidt metric.

    Args:
        N (int): the length of the density matrix.
        rank (int or None): the rank of the density matrix. The default
            value is full-rank.
        seed (int): Optional. To set a random seed.
    Returns:
        ndarray: rho (N,N  a density matrix.
    """
    arg_3 = __ginibre_matrix(arg_0, arg_1, arg_2)
    arg_3 = arg_3.dot(arg_3.conj().T)
    return arg_3 / np.trace(arg_3)


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Generate a random density matrix from the Bures metric.

    Args:
        N (int): the length of the density matrix.
        rank (int or None): the rank of the density matrix. The default
            value is full-rank.
        seed (int): Optional. To set a random seed.
    Returns:
        ndarray: rho (N,N) a density matrix.
    """
    arg_3 = np.eye(arg_0) + random_unitary(arg_0).data
    arg_4 = arg_3.dot(__ginibre_matrix(arg_0, arg_1, arg_2))
    arg_4 = arg_4.dot(arg_4.conj().T)
    return arg_4 / np.trace(arg_4)


def Func(arg_0):
        """Return a list of custom gate names in this gate body."""
        arg_1 = []
        for arg_2 in arg_0.children:
            if arg_2.type == "custom_unitary":
                arg_1.append(arg_2.name)
        return arg_1


def Func(arg_0, arg_1):
        """Return the compose of a QuantumChannel with itself n times.

        Args:
            n (int): compute the matrix Func of the superoperator matrix.

        Returns:
            SuperOp: the n-times composition channel as a SuperOp object.

        Raises:
            QiskitError: if the input and output dimensions of the
            QuantumChannel are not equal, or the Func is not an integer.
        """
        if not isinstance(arg_1, (int, np.integer)):
            raise QiskitError("Can only Func with integer Funcs.")
        if arg_0._input_dim != arg_0._output_dim:
            raise QiskitError("Can only Func with input_dim = output_dim.")
        # Override base class Func so we can implement more efficiently
        # using Numpy.matrix_Func
        return SuperOp(
            np.linalg.matrix_Func(arg_0._data, arg_1), arg_0.input_dims(),
            arg_0.output_dims())


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, arg_10=None):
    """Convert a list of circuits into a qobj.

    Args:
        circuits (list[QuantumCircuits] or QuantumCircuit): circuits to compile
        qobj_header (QobjHeader): header to pass to the results
        qobj_id (int): TODO: delete after qiskit-terra 0.8
        backend_name (str): TODO: delete after qiskit-terra 0.8
        config (dict): TODO: delete after qiskit-terra 0.8
        shots (int): TODO: delete after qiskit-terra 0.8
        max_credits (int): TODO: delete after qiskit-terra 0.8
        basis_gates (str): TODO: delete after qiskit-terra 0.8
        coupling_map (list): TODO: delete after qiskit-terra 0.8
        seed (int): TODO: delete after qiskit-terra 0.8
        memory (bool): TODO: delete after qiskit-terra 0.8

    Returns:
        Qobj: the Qobj to be run on the backends
    """
    warnings.warn('Func is deprecated and will be removed in Qiskit Terra 0.9. '
                  'Use qiskit.compiler.assemble() to serialize circuits into a qobj.',
                  DeprecationWarning)

    arg_1 = arg_1 or QobjHeader()

    if arg_3:
        arg_1.backend_name = arg_3
    if arg_7:
        warnings.warn('basis_gates was unused and will be removed.', DeprecationWarning)
    if arg_8:
        warnings.warn('coupling_map was unused and will be removed.', DeprecationWarning)

    arg_11 = assemble(experiments=arg_0,
                    arg_2=arg_2,
                    arg_1=arg_1,
                    arg_5=arg_5,
                    arg_10=arg_10,
                    arg_6=arg_6,
                    seed_simulator=arg_9,
                    arg_4=arg_4)

    return arg_11


def Func(arg_0, arg_1):
        """Expand 3+ qubit gates using their decomposition rules.

        Args:
            dag(DAGCircuit): input dag
        Returns:
            DAGCircuit: output dag with maximum node degrees of 2
        Raises:
            QiskitError: if a 3q+ gate is not decomposable
        """
        for arg_2 in arg_1.threeQ_or_more_gates():
            # TODO: allow choosing other possible decompositions
            arg_3 = arg_2.op.definition
            if not arg_3:
                raise QiskitError("Cannot unroll all 3q or more gates. "
                                  "No rule to expand instruction %s." %
                                  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_4 = DAGCircuit()
            arg_4.add_qreg(arg_3[0][1][0][0])
            for arg_5 in arg_3:
                arg_4.apply_operation_back(*arg_5)
            arg_4 = arg_0.Func(arg_4)  # recursively unroll
            arg_1.substitute_node_with_dag(arg_2, arg_4)
        return arg_1


def Func(arg_0):
        """Calculate a subcircuit that implements this unitary."""
        if arg_0.num_qubits == 1:
            arg_1 = QuantumRegister(1, "q")
            arg_2 = euler_angles_1q(arg_0.to_matrix())
            arg_0.definition = [(U3Gate(*arg_2), [arg_1[0]], [])]
        if arg_0.num_qubits == 2:
            arg_0.definition = two_qubit_kak(arg_0.to_matrix())


def Func(arg_0, arg_1, arg_2, arg_3):
        """Validate if the value is of the type of the schema's model.

        Assumes the nested schema is a ``BaseSchema``.
        """
        if arg_0.many and not is_collection(arg_1):
            raise arg_0._not_expected_type(
                arg_1, Iterable, fields=[arg_0], field_names=arg_2, arg_3=arg_3)

        arg_4 = super().Func

        arg_5 = []
        arg_6 = arg_1 if arg_0.many else [arg_1]
        for arg_7, arg_8 in enumerate(arg_6):
            try:
                arg_4(arg_8, arg_7, arg_6)
            except ValidationError as err:
                arg_5.append(err.messages)

        if arg_5:
            arg_5 = arg_5 if arg_0.many else arg_5[0]
            raise ValidationError(arg_5)

        return arg_1


def Func(arg_0, arg_1, arg_2, arg_3):
        """Validate if it's a list of valid item-field values.

        Check if each element in the list can be validated by the item-field
        passed during construction.
        """
        super().Func(arg_1, arg_2, arg_3)

        arg_4 = []
        for arg_5, arg_6 in enumerate(arg_1):
            try:
                arg_0.container.Func(arg_6, arg_5, arg_1)
            except ValidationError as err:
                arg_4.append(err.messages)

        if arg_4:
            raise ValidationError(arg_4)

        return arg_1


def Func(arg_0, arg_1):
        """Set the absolute tolerence parameter for float comparisons."""
        # NOTE: that this overrides the class value so applies to all
        # instances of the class.
        arg_2 = arg_0.__class__.MAX_TOL
        if arg_1 < 0:
            raise QiskitError("Invalid atol: must be non-negative.")
        if arg_1 > arg_2:
            raise QiskitError(
                "Invalid atol: must be less than {}.".format(arg_2))
        arg_0.__class__.ATOL = arg_1


def Func(arg_0, arg_1):
        """Set the relative tolerence parameter for float comparisons."""
        # NOTE: that this overrides the class value so applies to all
        # instances of the class.
        arg_2 = arg_0.__class__.MAX_TOL
        if arg_1 < 0:
            raise QiskitError("Invalid rtol: must be non-negative.")
        if arg_1 > arg_2:
            raise QiskitError(
                "Invalid rtol: must be less than {}.".format(arg_2))
        arg_0.__class__.RTOL = arg_1


def Func(arg_0, arg_1=None):
        """Return tuple of input dimension for specified subsystems."""
        if arg_1 is None:
            return arg_0._Func
        return tuple(arg_0._Func[arg_2] for arg_2 in arg_1)


def Func(arg_0):
        """Make a Func of current operator."""
        # pylint: disable=no-value-for-parameter
        # The constructor of subclasses from raw data should be a Func
        return arg_0.__class__(arg_0.data, arg_0.input_dims(), arg_0.output_dims())


def Func(arg_0, arg_1):
        """Return the compose of a operator with itself n times.

        Args:
            n (int): the number of times to compose with self (n>0).

        Returns:
            BaseOperator: the n-times composed operator.

        Raises:
            QiskitError: if the input and output dimensions of the operator
            are not equal, or the Func is not a positive integer.
        """
        # NOTE: if a subclass can have negative or non-integer Funcs
        # this method should be overriden in that class.
        if not isinstance(arg_1, (int, np.integer)) or arg_1 < 1:
            raise QiskitError("Can only Func with positive integer Funcs.")
        if arg_0._input_dim != arg_0._output_dim:
            raise QiskitError("Can only Func with input_dim = output_dim.")
        arg_2 = arg_0.copy()
        for arg_3 in range(1, arg_1):
            arg_2 = arg_2.compose(arg_0)
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=0, arg_5=False):
        """Perform a contraction using Numpy.einsum

        Args:
            tensor (np.array): a vector or matrix reshaped to a rank-N tensor.
            mat (np.array): a matrix reshaped to a rank-2M tensor.
            indices (list): tensor indices to contract with mat.
            shift (int): shift for indicies of tensor to contract [Default: 0].
            right_mul (bool): if True right multiply tensor by mat
                              (else left multiply) [Default: False].

        Returns:
            Numpy.ndarray: the matrix multiplied rank-N tensor.

        Raises:
            QiskitError: if mat is not an even rank tensor.
        """
        arg_6 = arg_1.ndim
        arg_7 = arg_2.ndim
        if arg_7 % 2 != 0:
            raise QiskitError(
                "Contracted matrix must have an even number of indices.")
        # Get einsum indices for tensor
        arg_8 = list(range(arg_6))
        for arg_9, arg_10 in enumerate(arg_3):
            arg_8[arg_10 + arg_4] = arg_6 + arg_9
        # Get einsum indces for mat
        arg_11 = list(reversed(range(arg_6, arg_6 + len(arg_3))))
        arg_12 = [arg_10 + arg_4 for arg_10 in reversed(arg_3)]
        if arg_5:
            arg_13 = arg_11 + arg_12
        else:
            arg_13 = arg_12 + arg_11
        return np.einsum(arg_1, arg_8, arg_2, arg_13)


def Func(arg_0, arg_1, arg_2, arg_3):
        """Override ``Func`` for customizing the exception raised."""
        try:
            return super().Func(arg_1, arg_2, arg_3)
        except ValidationError as arg_4:
            if 'deserialization_schema_selector' in arg_4.messages[0]:
                arg_4.messages[0] = 'Cannot find a valid schema among the choices'
            raise


def Func(arg_0, arg_1, arg_2, arg_3):
        """Check if at least one of the possible choices validates the value.

        Possible choices are assumed to be ``ModelTypeValidator`` fields.
        """
        for arg_4 in arg_0.choices:
            if isinstance(arg_4, ModelTypeValidator):
                try:
                    return arg_4.Func(arg_1, arg_2, arg_3)
                except ValidationError:
                    pass

        raise arg_0._not_expected_type(
            arg_1, [arg_4.__class__ for arg_4 in arg_0.choices],
            fields=[arg_0], field_names=arg_2, arg_3=arg_3)


def Func(arg_0, arg_1):
    """Return the state fidelity between two quantum states.

    Either input may be a state vector, or a density matrix. The state
    fidelity (F) for two density matrices is defined as::

        F(rho1, rho2) = Tr[sqrt(sqrt(rho1).rho2.sqrt(rho1))] ^ 2

    For a pure state and mixed state the fidelity is given by::

        F(|psi1>, rho2) = <psi1|rho2|psi1>

    For two pure states the fidelity is given by::

        F(|psi1>, |psi2>) = |<psi1|psi2>|^2

    Args:
        state1 (array_like): a quantum state vector or density matrix.
        state2 (array_like): a quantum state vector or density matrix.

    Returns:
        array_like: The state fidelity F(state1, state2).
    """
    # convert input to numpy arrays
    arg_2 = np.array(arg_0)
    arg_3 = np.array(arg_1)

    # fidelity of two state vectors
    if arg_2.ndim == 1 and arg_3.ndim == 1:
        return np.abs(arg_3.conj().dot(arg_2)) ** 2
    # fidelity of vector and density matrix
    elif arg_2.ndim == 1:
        # psi = s1, rho = s2
        return np.abs(arg_2.conj().dot(arg_3).dot(arg_2))
    elif arg_3.ndim == 1:
        # psi = s2, rho = s1
        return np.abs(arg_3.conj().dot(arg_2).dot(arg_3))
    # fidelity of two density matrices
    arg_4 = _funm_svd(arg_2, np.sqrt)
    arg_5 = _funm_svd(arg_3, np.sqrt)
    return np.linalg.norm(arg_4.dot(arg_5), ord='nuc') ** 2


def Func(arg_0, arg_1):
    """Apply real scalar function to singular values of a matrix.

    Args:
        a (array_like): (N, N) Matrix at which to evaluate the function.
        func (callable): Callable object that evaluates a scalar function f.

    Returns:
        ndarray: funm (N, N) Value of the matrix function specified by func
        evaluated at `A`.
    """
    arg_2, arg_3, arg_4 = la.svd(arg_0, lapack_driver='gesvd')
    arg_5 = np.diag(arg_1(arg_3))
    return arg_2.dot(arg_5).dot(arg_4)


def Func(arg_0):
        """Special case. Return self."""
        return Snapshot(arg_0.num_qubits, arg_0.num_clbits, arg_0.params[0],
                        arg_0.params[1])


def Func(arg_0, arg_1):
        """Set snapshot Func to name

        Args:
            name (str or None): Func to assign unitary

        Raises:
            TypeError: name is not string or None.
        """
        if isinstance(arg_1, str):
            arg_0._Func = arg_1
        else:
            raise TypeError('Func expects a string')


def Func(arg_0):
        """Convert to a Kraus or UnitaryGate circuit instruction.

        If the channel is unitary it will be added as a unitary gate,
        otherwise it will be added as a kraus simulator instruction.

        Returns:
            Instruction: A kraus instruction for the channel.

        Raises:
            QiskitError: if input data is not an N-qubit CPTP quantum channel.
        """
        from qiskit.circuit.instruction import Instruction
        # Check if input is an N-qubit CPTP channel.
        arg_1 = int(np.log2(arg_0._input_dim))
        if arg_0._input_dim != arg_0._output_dim or 2**arg_1 != arg_0._input_dim:
            raise QiskitError(
                'Cannot convert QuantumChannel to Instruction: channel is not an N-qubit channel.'
            )
        if not arg_0.is_cptp():
            raise QiskitError(
                'Cannot convert QuantumChannel to Instruction: channel is not CPTP.'
            )
        # Next we convert to the Kraus representation. Since channel is CPTP we know
        # that there is only a single set of Kraus operators
        arg_2, arg_3 = _to_kraus(arg_0.rep, arg_0._data, *arg_0.dim)
        # If we only have a single Kraus operator then the channel is
        # a unitary channel so can be converted to a UnitaryGate. We do this by
        # converting to an Operator and using its Func method
        if len(arg_2) == 1:
            return Operator(arg_2[0]).Func()
        return Instruction('kraus', arg_1, 0, arg_2)


def Func(arg_0, arg_1):
        """Convert input into a QuantumChannel subclass object or Operator object"""
        # This handles common conversion for all QuantumChannel subclasses.
        # If the input is already a QuantumChannel subclass it will return
        # the original object
        if isinstance(arg_1, QuantumChannel):
            return arg_1
        if hasattr(arg_1, 'to_quantumchannel'):
            # If the data object is not a QuantumChannel it will give
            # preference to a 'to_quantumchannel' attribute that allows
            # an arbitrary object to define its own conversion to any
            # quantum channel subclass.
            return arg_1.to_channel()
        if hasattr(arg_1, 'to_channel'):
            # TODO: this 'to_channel' method is the same case as the above
            # but is used by current version of Aer. It should be removed
            # once Aer is nupdated to use `to_quantumchannel`
            # instead of `to_channel`,
            return arg_1.to_channel()
        # Finally if the input is not a QuantumChannel and doesn't have a
        # 'to_quantumchannel' conversion method we try and initialize it as a
        # regular matrix Operator which can be converted into a QuantumChannel.
        return Operator(arg_1)


def Func(arg_0, arg_1, arg_2, arg_3=None,
                   arg_4=3, arg_5=(0, 1)):
        """Alternative constructor for a TensorFlowModel that
        accepts a `tf.keras.Model` instance.

        Parameters
        ----------
        model : `tensorflow.keras.Model`
            A `tensorflow.keras.Model` that accepts a single input tensor
            and returns a single output tensor representing logits.
        bounds : tuple
            Tuple of lower and upper bound for the pixel values, usually
            (0, 1) or (0, 255).
        input_shape : tuple
            The shape of a single input, e.g. (28, 28, 1) for MNIST.
            If None, tries to get the the shape from the model's
            input_shape attribute.
        channel_axis : int
            The index of the axis that represents color channels.
        preprocessing: 2-element tuple with floats or numpy arrays
            Elementwises preprocessing of input; we first subtract the first
            element of preprocessing from the input and then divide the input
            by the second element.

        """
        import tensorflow as tf
        if arg_3 is None:
            try:
                arg_3 = arg_1.input_shape[1:]
            except AttributeError:
                raise ValueError(
                    'Please specify input_shape manually or '
                    'provide a model with an input_shape attribute')
        with tf.keras.backend.get_session().as_default():
            arg_6 = tf.placeholder(tf.float32, (None,) + arg_3)
            arg_7 = arg_1(arg_6)
            return arg_0(arg_6, arg_7, arg_2=arg_2,
                       arg_4=arg_4, arg_5=arg_5)


def Func(arg_0, arg_1):
        """Interface to model.Func for attacks.

        Parameters
        ----------
        batch : bool
            Controls whether the index of the axis for a batch of images
            (4 dimensions) or a single image (3 dimensions) should be returned.

        """
        arg_2 = arg_0.__model.Func()
        if not arg_1:
            arg_2 = arg_2 - 1
        return arg_2


def Func(arg_0):
        """Returns true if _backward and _forward_backward can be called
        by an attack, False otherwise.

        """
        try:
            arg_0.__model.gradient
            arg_0.__model.predictions_and_gradient
        except AttributeError:
            return False
        else:
            return True


def Func(arg_0, arg_1, arg_2=True, arg_3=False):
        """Interface to model.predictions for attacks.

        Parameters
        ----------
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).
        strict : bool
            Controls if the bounds for the pixel values should be checked.

        """
        arg_4 = arg_0.in_bounds(arg_1)
        assert not arg_2 or arg_4

        arg_0._total_prediction_calls += 1
        Func = arg_0.__model.predictions(arg_1)
        arg_6, arg_7, arg_8 = arg_0.__is_adversarial(
            arg_1, Func, arg_4)

        assert Func.ndim == 1
        if arg_3:
            return Func, arg_6, arg_7, arg_8
        else:
            return Func, arg_6


def Func(
            arg_0, arg_1, arg_2=False, arg_3=True, arg_4=False):
        """Interface to model.Func for attacks.

        Parameters
        ----------
        images : `numpy.ndarray`
            Batch of inputs with shape as expected by the model.
        greedy : bool
            Whether the first adversarial should be returned.
        strict : bool
            Controls if the bounds for the pixel values should be checked.

        """
        if arg_3:
            arg_5 = arg_0.in_bounds(arg_1)
            assert arg_5

        arg_0._total_prediction_calls += len(arg_1)
        arg_6 = arg_0.__model.Func(arg_1)

        assert arg_6.ndim == 2
        assert arg_6.shape[0] == arg_1.shape[0]

        if arg_4:
            assert arg_2

        arg_7 = []
        for arg_8 in range(len(arg_6)):
            if arg_3:
                arg_9 = True
            else:
                arg_9 = arg_0.in_bounds(arg_1[arg_8])
            arg_10, arg_11, arg_12 = arg_0.__is_adversarial(
                arg_1[arg_8], arg_6[arg_8], arg_9)
            if arg_10 and arg_2:
                if arg_4:
                    return arg_6, arg_10, arg_8, arg_11, arg_12
                else:
                    return arg_6, arg_10, arg_8
            arg_7.append(arg_10)

        if arg_2:  # pragma: no cover
            # no adversarial found
            if arg_4:
                return arg_6, False, None, False, None
            else:
                return arg_6, False, None

        arg_10 = np.array(arg_7)
        assert arg_10.ndim == 1
        assert arg_10.shape[0] == arg_1.shape[0]

        return arg_6, arg_10


def Func(arg_0, arg_1=None, arg_2=None, arg_3=True):
        """Interface to model.gradient for attacks.

        Parameters
        ----------
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).
            Defaults to the original image.
        label : int
            Label used to calculate the loss that is differentiated.
            Defaults to the original label.
        strict : bool
            Controls if the bounds for the pixel values should be checked.

        """
        assert arg_0.has_gradient()

        if arg_1 is None:
            arg_1 = arg_0.__original_image
        if arg_2 is None:
            arg_2 = arg_0.__original_class

        assert not arg_3 or arg_0.in_bounds(arg_1)

        arg_0._total_gradient_calls += 1
        Func = arg_0.__model.gradient(arg_1, arg_2)

        assert Func.shape == arg_1.shape
        return Func


def Func(
            arg_0, arg_1=None, arg_2=None, arg_3=True, arg_4=False):
        """Interface to model.Func for attacks.

        Parameters
        ----------
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).
            Defaults to the original image.
        label : int
            Label used to calculate the loss that is differentiated.
            Defaults to the original label.
        strict : bool
            Controls if the bounds for the pixel values should be checked.

        """
        assert arg_0.has_gradient()

        if arg_1 is None:
            arg_1 = arg_0.__original_image
        if arg_2 is None:
            arg_2 = arg_0.__original_class

        arg_5 = arg_0.in_bounds(arg_1)
        assert not arg_3 or arg_5

        arg_0._total_prediction_calls += 1
        arg_0._total_gradient_calls += 1
        arg_6, arg_7 = arg_0.__model.Func(arg_1, arg_2)  # noqa: E501
        arg_8, arg_9, arg_10 = arg_0.__is_adversarial(
            arg_1, arg_6, arg_5)

        assert arg_6.ndim == 1
        assert arg_7.shape == arg_1.shape
        if arg_4:
            return arg_6, arg_7, arg_8, arg_9, arg_10
        else:
            return arg_6, arg_7, arg_8


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
        """Interface to model.Func for attacks.

        Parameters
        ----------
        gradient : `numpy.ndarray`
            Gradient of some loss w.r.t. the logits.
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).

        Returns
        -------
        gradient : `numpy.ndarray`
            The gradient w.r.t the image.

        See Also
        --------
        :meth:`gradient`

        """
        assert arg_0.has_gradient()
        assert arg_1.ndim == 1

        if arg_2 is None:
            arg_2 = arg_0.__original_image

        assert not arg_3 or arg_0.in_bounds(arg_2)

        arg_0._total_gradient_calls += 1
        arg_1 = arg_0.__model.Func(arg_1, arg_2)

        assert arg_1.shape == arg_2.shape
        return arg_1


def Func(arg_0, arg_1):
        """Returns the index of the largest logit, ignoring the class that
        is passed as `exclude`."""
        arg_2 = arg_0 - onehot_like(arg_0, arg_1, value=np.inf)
        return np.argmax(arg_2)


def Func(arg_0):
        """Concatenates the Funcs of the given criteria in alphabetical order.

        If a sub-criterion is itself a combined criterion, its Func is
        first split into the individual Funcs and the Funcs of the
        sub-sub criteria is used instead of the Func of the sub-criterion.
        This is done recursively to ensure that the order and the hierarchy
        of the criteria does not influence the Func.

        Returns
        -------
        str
            The alphabetically sorted Funcs of the sub-criteria concatenated
            using double underscores between them.

        """
        arg_1 = (criterion.Func() for criterion in arg_0._criteria)
        return '__'.join(sorted(arg_1))


def Func(arg_0, arg_1):
    """Calculates the cross-entropy.

    Parameters
    ----------
    logits : array_like
        The logits predicted by the model.
    label : int
        The label describing the target distribution.

    Returns
    -------
    float
        The cross-entropy between softmax(logits) and onehot(label).

    """

    assert arg_1.ndim == 1

    # for numerical reasons we subtract the max logit
    # (mathematically it doesn't matter!)
    # otherwise exp(logits) might become too large or too small
    arg_1 = arg_1 - np.max(arg_1)
    arg_2 = np.exp(arg_1)
    arg_3 = np.sum(arg_2)
    arg_4 = np.log(arg_3) - arg_1[arg_0]
    return arg_4


def Func(arg_0, arg_1):
        """Convenience method that calculates Func for a single image.

        Parameters
        ----------
        image : `numpy.ndarray`
            Single input with shape as expected by the model
            (without the batch dimension).

        Returns
        -------
        `numpy.ndarray`
            Vector of Func (logits, i.e. before the softmax) with
            shape (number of classes,).

        See Also
        --------
        :meth:`batch_Func`

        """
        return np.squeeze(arg_0.batch_Func(arg_1[np.newaxis]), axis=0)


def Func(arg_0):
    """
    Clone a remote git repository to a local path.

    :param git_uri: the URI to the git repository to be Funcd
    :return: the generated local path where the repository has been Funcd to
    """
    arg_1 = sha256_hash(arg_0)
    arg_2 = home_directory_path(FOLDER, arg_1)
    arg_3 = path_exists(arg_2)

    if not arg_3:
        _Func_repo(arg_0, arg_2)
    else:
        logging.info(  # pragma: no cover
            "Git repository already exists locally.")  # pragma: no cover

    return arg_2


def Func(arg_0, arg_1=None, arg_2=arg_3):
    """Create Graphene Enum for sorting a SQLAlchemy class query

    Parameters
    - cls : Sqlalchemy model class
        Model used to create the sort enumerator
    - name : str, optional, default None
        Name to use for the enumerator. If not provided it will be set to `cls.__name__ + 'SortEnum'`
    - symbol_name : function, optional, default `_symbol_name`
        Function which takes the column name and a boolean indicating if the sort direction is ascending,
        and returns the symbol name for the current column and sort direction.
        The default function will create, for a column named 'foo', the symbols 'foo_asc' and 'foo_desc'

    Returns
    - Enum
        The Graphene enumerator
    """
    arg_4, arg_5 = _Func(arg_0, arg_1, arg_2)
    return arg_4


def Func():
    """Monkey patching _strptime to avoid problems related with non-english
    locale changes on the system.

    For example, if system's locale is set to fr_FR. Parser won't recognize
    any date since all languages are translated to english dates.
    """

    arg_0 = imp.load_module(
        'strptime_patched', *imp.find_module('_strptime')
    )

    arg_1 = imp.load_module(
        'calendar_patched', *imp.find_module('_strptime')
    )

    arg_0._getlang = lambda: ('en_US', 'UTF-8')
    arg_0.calendar = arg_1
    arg_0.calendar.day_abbr = [
        'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
    ]
    arg_0.calendar.day_name = [
        'monday', 'tuesday', 'wednesday', 'thursday',
        'friday', 'saturday', 'sunday'
    ]
    arg_0.calendar.month_abbr = [
        '', 'jan', 'feb', 'mar', 'apr', 'may', 'jun',
        'jul', 'aug', 'sep', 'oct', 'nov', 'dec'
    ]
    arg_0.calendar.month_name = [
        '', 'january', 'february', 'march', 'april',
        'may', 'june', 'july', 'august', 'september',
        'october', 'november', 'december'
    ]

    return arg_0._strptime_time


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None,
                       arg_4=False, arg_5=False):
        """
        Get an ordered mapping with locale codes as keys
        and corresponding locale instances as values.

        :param languages:
            A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
            If locales are not given, languages and region are
            used to construct locales to load.
        :type languages: list

        :param locales:
            A list of codes of locales which are to be loaded,
            e.g. ['fr-PF', 'qu-EC', 'af-NA']
        :type locales: list

        :param region:
            A region code, e.g. 'IN', '001', 'NE'.
            If locales are not given, languages and region are
            used to construct locales to load.
        :type region: str|unicode

        :param use_given_order:
            If True, the returned mapping is ordered in the order locales are given.
        :type allow_redetect_language: bool

        :param allow_conflicting_locales:
            if True, locales with same language and different region can be loaded.
        :type allow_conflicting_locales: bool

        :return: ordered locale code to locale instance mapping
        """
        return OrderedDict(arg_0._load_data(
            arg_1=arg_1, arg_2=arg_2, arg_3=arg_3, arg_4=arg_4,
            arg_5=arg_5))


def Func(arg_0, arg_1=None, arg_2=None, arg_3=None,
                    arg_4=False, arg_5=False):
        """
        Yield locale instances.

        :param languages:
            A list of language codes, e.g. ['en', 'es', 'zh-Hant'].
            If locales are not given, languages and region are
            used to construct locales to load.
        :type languages: list

        :param locales:
            A list of codes of locales which are to be loaded,
            e.g. ['fr-PF', 'qu-EC', 'af-NA']
        :type locales: list

        :param region:
            A region code, e.g. 'IN', '001', 'NE'.
            If locales are not given, languages and region are
            used to construct locales to load.
        :type region: str|unicode

        :param use_given_order:
            If True, the returned mapping is ordered in the order locales are given.
        :type allow_redetect_language: bool

        :param allow_conflicting_locales:
            if True, locales with same language and different region can be loaded.
        :type allow_conflicting_locales: bool

        :yield: locale instances
        """
        for arg_6, arg_7 in arg_0._load_data(
                arg_1=arg_1, arg_2=arg_2, arg_3=arg_3,
                arg_4=arg_4,
                arg_5=arg_5):
            yield arg_7


def Func(arg_0, arg_1):
        """
        Check if tokens are valid tokens for the locale.

        :param tokens:
            a list of string or unicode tokens.
        :type tokens: list

        :return: True if tokens are valid, False otherwise.
        """
        arg_2 = arg_0._get_match_relative_regex_cache()
        for arg_3 in arg_1:
            if any([arg_2.match(arg_3),
                    arg_3 in arg_0, arg_3.isdigit()]):
                continue
            else:
                return False
        else:
            return True


def Func(arg_0, arg_1, arg_2):
        """Attemps to parse time part of date strings like '1 day ago, 2 PM' """
        arg_1 = PATTERN.sub('', arg_1)
        arg_1 = re.sub(r'\b(?:ago|in)\b', '', arg_1)
        try:
            return time_parser(arg_1)
        except:
            pass


def Func(arg_0, arg_1, arg_2=False, arg_3=None):
        """
        Check if the locale is applicable to translate date string.

        :param date_string:
            A string representing date and/or time in a recognizably valid format.
        :type date_string: str|unicode

        :param strip_timezone:
            If True, timezone is stripped from date string.
        :type strip_timezone: bool

        :return: boolean value representing if the locale is applicable for the date string or not.
        """
        if arg_2:
            arg_1, arg_4 = pop_tz_offset_from_string(arg_1, as_offset=False)

        arg_1 = arg_0._translate_numerals(arg_1)
        if arg_3.NORMALIZE:
            arg_1 = normalize_unicode(arg_1)
        arg_1 = arg_0._simplify(arg_1, arg_3=arg_3)
        arg_5 = arg_0._get_dictionary(arg_3)
        arg_6 = arg_5.split(arg_1)

        return arg_5.are_tokens_valid(arg_6)


def Func(arg_0, arg_1, arg_2):
    """ Parse with formats and return a dictionary with 'period' and 'obj_date'.

    :returns: :class:`datetime.datetime`, dict or None

    """
    arg_3 = 'day'
    for arg_4 in arg_1:
        try:
            date_obj = datetime.strptime(arg_0, arg_4)
        except ValueError:
            continue
        else:
            # If format does not include the day, use last day of the month
            # instead of first, because the first is usually out of range.
            if '%d' not in arg_4:
                arg_3 = 'month'
                date_obj = date_obj.replace(
                    day=get_last_day_of_month(date_obj.year, date_obj.month))

            if not ('%y' in arg_4 or '%Y' in arg_4):
                today = datetime.today()
                date_obj = date_obj.replace(year=today.year)

            date_obj = apply_timezone_from_settings(date_obj, arg_2)

            return {'date_obj': date_obj, 'period': arg_3}
    else:
        return {'date_obj': None, 'period': arg_3}


def Func(arg_0):
        """
        return ammo generator
        """
        arg_1 = {
            'phantom': missile.AmmoFileReader,
            'slowlog': missile.SlowLogReader,
            'line': missile.LineReader,
            'uri': missile.UriReader,
            'uripost': missile.UriPostReader,
            'access': missile.AccessLogReader,
            'caseline': missile.CaseLineReader,
        }
        if arg_0.uris and arg_0.ammo_file:
            raise StepperConfigurationError(
                'Both uris and ammo file specified. You must specify only one of them'
            )
        elif arg_0.uris:
            arg_2 = missile.UriStyleGenerator(
                arg_0.uris, arg_0.headers, http_ver=arg_0.http_ver)
        elif arg_0.ammo_file:
            if arg_0.ammo_type in arg_1:
                if arg_0.ammo_type == 'phantom':
                    arg_3 = resource.get_opener(arg_0.ammo_file)
                    with arg_3(arg_0.use_cache) as ammo:
                        try:
                            if not ammo.next()[0].isdigit():
                                arg_0.ammo_type = 'uri'
                                arg_0.log.info(
                                    "Setting ammo_type 'uri' because ammo is not started with digit and you did not specify ammo format"
                                )
                            else:
                                arg_0.log.info(
                                    "Default ammo type ('phantom') used, use 'phantom.ammo_type' option to override it"
                                )
                        except StopIteration:
                            arg_0.log.exception(
                                "Couldn't read first line of ammo file")
                            raise AmmoFileError(
                                "Couldn't read first line of ammo file")
            else:
                raise NotImplementedError(
                    'No such ammo type implemented: "%s"' % arg_0.ammo_type)
            arg_2 = arg_1[arg_0.ammo_type](
                arg_0.ammo_file, headers=arg_0.headers, http_ver=arg_0.http_ver, use_cache=arg_0.use_cache)
        else:
            raise StepperConfigurationError(
                'Ammo not found. Specify uris or ammo file')
        arg_0.log.info("Using %s ammo reader" % type(arg_2).__name__)
        return arg_2


def Func(arg_0, arg_1):
    """ translate http code to net code. if accertion failed, set net code to 314 """
    if len(arg_0) <= 3:
        # FIXME: we're unable to use better logic here, because we should support non-http codes
        # but, we should look for core.util.HTTP or some other common logic
        # here
        if arg_1:
            return 0
        else:
            return 314

    arg_2 = arg_0.split(' ')[-1]
    if arg_2 in KNOWN_EXC.keys():
        return KNOWN_EXC[arg_2]
    else:
        logger.warning(
            "Unknown Java exception, consider adding it to dictionary: %s",
            arg_0)
        return 41


def Func(arg_0):
        """        Generate phantom tool run config        """
        arg_1 = ''
        arg_2 = ''
        for arg_3 in arg_0.streams:
            arg_1 += arg_3.Func()
            if not arg_3.is_main:
                arg_2 += " " + "benchmark_io%s" % arg_3.sequence_no

        arg_4 = {}
        arg_4['threads'] = arg_0.threads
        arg_4['phantom_log'] = arg_0.phantom_log
        arg_4['stat_log'] = arg_0.stat_log
        arg_4['benchmarks_block'] = arg_1
        arg_4['stat_benchmarks'] = arg_2
        arg_4['additional_libs'] = arg_0.additional_libs
        arg_4['phantom_modules_path'] = arg_0.phantom_modules_path
        arg_5 = arg_0.core.mkstemp(".conf", "phantom_")
        arg_0.core.add_artifact_file(arg_5)
        logger.debug("Generating phantom config: %s", arg_5)
        arg_6 = resource_string(__name__, "config/phantom.conf.tpl")
        arg_7 = string.Template(arg_6)
        arg_8 = arg_7.substitute(arg_4)

        with open(arg_5, 'w') as conffile:
            conffile.write(arg_8)
        return arg_5


def Func(arg_0):
        """ get merged info about phantom conf """
        arg_1 = copy.copy(arg_0.streams[0])
        arg_1.stat_log = arg_0.stat_log
        arg_1.steps = []
        arg_1.ammo_file = ''
        arg_1.rps_schedule = None
        arg_1.ammo_count = 0
        arg_1.duration = 0

        arg_1.instances = 0
        arg_1.loadscheme = []
        arg_1.loop_count = 0

        for arg_11 in arg_0.streams:
            arg_12 = 0
            logger.debug("Steps: %s", arg_11.stepper_wrapper.steps)
            for arg_13 in arg_11.stepper_wrapper.steps:
                for arg_14 in range(0, arg_13[1]):
                    if len(arg_1.steps) > arg_12:
                        arg_1.steps[arg_12][0] += arg_13[0]
                    else:
                        arg_1.steps.append([arg_13[0], 1])
                    arg_12 += 1

            if arg_1.rps_schedule:
                arg_1.rps_schedule = []
            else:
                arg_1.rps_schedule = arg_11.stepper_wrapper.loadscheme
            if arg_1.loadscheme:
                arg_1.loadscheme = ''
            else:
                # FIXME: add formatted load scheme for server:
                # <step_size,step_type,first_rps,last_rps,original_step_params>
                # as a string
                arg_1.loadscheme = ''

            if arg_1.loop_count:
                arg_1.loop_count = u'0'
            else:
                arg_1.loop_count = arg_11.stepper_wrapper.loop_count

            arg_1.ammo_file += '{} '.format(arg_11.stepper_wrapper.ammo_file)
            arg_1.ammo_count += arg_11.stepper_wrapper.ammo_count
            arg_1.duration = max(
                arg_1.duration, arg_11.stepper_wrapper.duration)
            arg_1.instances += arg_11.instances

        if not arg_1.ammo_count:
            raise ValueError("Total ammo count cannot be zero")
        return arg_1


def Func(arg_0):
        """ compose benchmark block """
        # step file
        arg_0.stepper_wrapper.prepare_stepper()
        arg_0.stpd = arg_0.stepper_wrapper.stpd
        if arg_0.stepper_wrapper.instances:
            arg_0.instances = arg_0.stepper_wrapper.instances

        if not arg_0.stpd:
            raise RuntimeError("Cannot proceed with no STPD file")

        arg_3 = {}
        arg_3['sequence_no'] = arg_0.sequence_no
        if arg_0.ssl:
            arg_4 = ''
            arg_5 = ''
            arg_6 = "transport_t ssl_transport = transport_ssl_t {\n" \
                           "                timeout = 1s\n" \
                           "                %s\n" \
                           "                %s}\n" \
                           "                transport = ssl_transport"

            if arg_0.client_certificate or arg_0.client_key:
                arg_4 = 'auth_t def_auth = auth_t { key = "%s" cert = "%s"} auth = def_auth' \
                                % (arg_0.client_key, arg_0.client_certificate)
            if arg_0.client_cipher_suites:
                arg_5 = 'ciphers = "%s"' % arg_0.client_cipher_suites
            arg_3['ssl_transport'] = arg_6 % (arg_4, arg_5)
        else:
            arg_3['ssl_transport'] = ""
        arg_3['method_stream'] = arg_0.method_prefix + \
            "_ipv6_t" if arg_0.ipv6 else arg_0.method_prefix + "_ipv4_t"
        arg_3['phout'] = arg_0.phout_file
        arg_3['answ_log'] = arg_0.answ_log
        arg_3['answ_log_level'] = arg_0.answ_log_level
        arg_3['comment_answ'] = "# " if arg_0.answ_log_level == 'none' else ''
        arg_3['stpd'] = arg_0.stpd
        arg_3['source_log_prefix'] = arg_0.source_log_prefix
        arg_3['method_options'] = arg_0.method_options
        if arg_0.tank_type:
            arg_3[
                'proto'] = "proto=http_proto%s" % arg_0.sequence_no if arg_0.tank_type == 'http' else "proto=none_proto"
            arg_3['comment_proto'] = ""
        else:
            arg_3['proto'] = ""
            arg_3['comment_proto'] = "#"

        if arg_0.gatling:
            arg_3['bind'] = 'bind={ ' + arg_0.gatling + ' }'
        else:
            arg_3['bind'] = ''
        arg_3['ip'] = arg_0.resolved_ip
        arg_3['port'] = arg_0.port
        arg_3['timeout'] = arg_0.timeout
        arg_3['instances'] = arg_0.instances
        arg_7 = ''
        if arg_0.phantom_http_entity:
            arg_7 += "entity = " + arg_0.phantom_http_entity + "\n"
        if arg_0.phantom_http_field:
            arg_7 += "field = " + arg_0.phantom_http_field + "\n"
        if arg_0.phantom_http_field_num:
            arg_7 += "field_num = {}\n".format(arg_0.phantom_http_field_num)
        if arg_0.phantom_http_line:
            arg_7 += "line = " + arg_0.phantom_http_line + "\n"
        if arg_7:
            arg_3['reply_limits'] = 'reply_limits = {\n' + arg_7 + "}"
        else:
            arg_3['reply_limits'] = ''

        if arg_0.is_main:
            arg_8 = 'phantom_benchmark_main.tpl'
        else:
            arg_8 = 'phantom_benchmark_additional.tpl'
        arg_9 = resource_string(
            __name__, "config/" + arg_8)
        arg_10 = string.Template(arg_9)
        arg_11 = arg_10.substitute(arg_3)

        return arg_11


def Func(arg_0, arg_1, arg_2, arg_3=""):
    """
    This function polls stdout and stderr streams and writes their contents
    to log
    """
    arg_4 = select.select([arg_1], [], [], 0)[0]
    if arg_2:
        arg_5 = select.select([arg_2], [], [], 0)[0]
    else:
        arg_5 = []

    arg_0.debug("Selected: %s, %s", arg_4, arg_5)

    for arg_6 in arg_4:
        arg_7 = arg_6.read()
        arg_4.remove(arg_6)
        if arg_7:
            arg_0.debug("%s stdout: %s", arg_3, arg_7.strip())

    for arg_6 in arg_5:
        arg_7 = arg_6.read()
        arg_5.remove(arg_6)
        if arg_7:
            arg_0.warn("%s stderr: %s", arg_3, arg_7.strip())


def Func(arg_0, arg_1='s', arg_2=1):
    """
    helper for above functions
    """
    arg_3 = re.compile(r'(\d+)([a-zA-Z]*)')
    arg_4 = arg_3.findall(arg_0)
    arg_5 = 0.0
    for arg_6, arg_7 in arg_4:
        arg_6 = int(arg_6)
        arg_7 = arg_7.lower()
        if arg_7 == '':
            arg_7 = arg_1

        if arg_7 == 'ms':
            arg_5 += arg_6 * 0.001
            continue
        elif arg_7 == 's':
            arg_5 += arg_6
            continue
        elif arg_7 == 'm':
            arg_5 += arg_6 * 60
            continue
        elif arg_7 == 'h':
            arg_5 += arg_6 * 60 * 60
            continue
        elif arg_7 == 'd':
            arg_5 += arg_6 * 60 * 60 * 24
            continue
        elif arg_7 == 'w':
            arg_5 += arg_6 * 60 * 60 * 24 * 7
            continue
        else:
            raise ValueError(
                "String contains unsupported unit %s: %s" % (arg_7, arg_0))
    return int(arg_5 * arg_2)


def Func(arg_0):
        '''
        Read stepper info from json
        '''
        arg_0.log.debug("Reading cached stepper info: %s", arg_0.__si_filename())
        with open(arg_0.__si_filename(), 'r') as si_file:
            arg_1 = info.StepperInfo(**json.load(si_file))
        return arg_1


def Func(arg_0, arg_1):
        '''
        Write stepper info to json
        '''
        arg_0.log.debug("Saving stepper info: %s", arg_0.__si_filename())
        with open(arg_0.__si_filename(), 'w') as si_file:
            json.dump(arg_1._asdict(), si_file, indent=4)


def Func(arg_0):
    """
    Create Load Plan as defined in schedule. Publish info about its duration.
    """
    if len(arg_0) > 1:
        arg_1 = Composite(
            [StepFactory.produce(step_config) for step_config in arg_0])
    else:
        arg_1 = StepFactory.produce(arg_0[0])
    arg_2.status.publish('duration', arg_1.get_duration() / 1000)
    arg_2.status.publish('steps', arg_1.get_rps_list())
    arg_2.status.lp_len = len(arg_1)
    return arg_1


def Func(arg_0, arg_1):
        '''Return rps for second t'''
        if 0 <= arg_1 <= arg_0.duration:
            return arg_0.minrps + \
                float(arg_0.maxrps - arg_0.minrps) * arg_1 / arg_0.duration
        else:
            return 0


def Func(arg_0, arg_1):
        """
        Execute and check exit code
        """
        arg_0.log.info("Executing: %s", arg_1)
        arg_2 = Func(
            arg_1, shell=True, poll_period=0.1, catch_out=arg_0.catch_out)[0]
        if arg_2:
            raise RuntimeError("Subprocess returned %s" % arg_2)
        return arg_2


def Func(arg_0, arg_1):
        """
        The reason why we have two separate methods for monitoring
        and aggregates is a strong difference in incoming data.
        """
        arg_2 = list()
        for arg_3 in arg_1:
            for arg_4, arg_5 in arg_3["data"].iteritems():
                arg_2.append(
                    arg_0.__make_points(
                        "monitoring",
                        {"host": arg_4, "comment": arg_5.get("comment")},
                        arg_3["timestamp"],
                        {
                            arg_6: arg_7
                            for arg_6, arg_7 in arg_5["metrics"].iteritems()
                        }
                    )
                )
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5):
        """x
        Make a set of points for `this` label

        overall_quantiles, overall_meta, net_codes, proto_codes, histograms
        """
        arg_6 = list()

        arg_6.extend(
            (
                # overall quantiles for label
                arg_0.__make_points(
                    arg_4 + "overall_quantiles",
                    {"label": arg_3},
                    arg_1,
                    arg_0.__make_quantile_fields(arg_2)
                ),
                # overall meta (gun status) for label
                arg_0.__make_points(
                    arg_4 + "overall_meta",
                    {"label": arg_3},
                    arg_1,
                    arg_0.__make_overall_meta_fields(arg_2, arg_5)
                ),
                # net codes for label
                arg_0.__make_points(
                    arg_4 + "net_codes",
                    {"label": arg_3},
                    arg_1,
                    arg_0.__make_netcodes_fields(arg_2)
                ),
                # proto codes for label
                arg_0.__make_points(
                    arg_4 + "proto_codes",
                    {"label": arg_3},
                    arg_1,
                    arg_0.__make_protocodes_fields(arg_2)
                )
            )
        )
        # histograms, one row for each bin
        if arg_0.histograms:
            for arg_7, arg_8 in zip(arg_2["interval_real"]["hist"]["bins"],
                                   arg_2["interval_real"]["hist"]["data"]):
                arg_6.append(
                    arg_0.__make_points(
                        arg_4 + "histograms",
                        {"label": arg_3},
                        arg_1,
                        {"bin": arg_7, "count": arg_8}
                    )
                )
        return arg_6


def Func(arg_0):
        """
        A feeder that runs in distinct thread in main process.
        """
        arg_0.plan = StpdReader(arg_0.stpd_filename)
        if arg_0.cached_stpd:
            arg_0.plan = list(arg_0.plan)
        for arg_2 in arg_0.plan:
            if arg_0.quit.is_set():
                logger.info("Stop feeding: gonna quit")
                return
            # try putting a task to a queue unless there is a quit flag
            # or all workers have exited
            while True:
                try:
                    arg_0.task_queue.put(arg_2, timeout=1)
                    break
                except Full:
                    if arg_0.quit.is_set() or arg_0.workers_finished:
                        return
                    else:
                        continue
        arg_3 = arg_0.instances
        logger.info(
            "Feeded all data. Publishing %d killer tasks" % (arg_3))
        arg_4 = 1
        for arg_5 in range(5):
            try:
                [
                    arg_0.task_queue.put(None, timeout=1)
                    for arg_5 in xrange(0, arg_3)
                ]
                break
            except Full:
                logger.debug(
                    "Couldn't post killer tasks"
                    " because queue is full. Retrying in %ss", arg_4)
                time.sleep(arg_4)
                arg_4 *= 2

        try:
            logger.info("Waiting for workers")
            map(lambda x: x.join(), arg_0.pool)
            logger.info("All workers exited.")
            arg_0.workers_finished = True
        except (KeyboardInterrupt, SystemExit):
            arg_0.task_queue.close()
            arg_0.results.close()
            arg_0.quit.set()
            logger.info("Going to quit. Waiting for workers")
            map(lambda x: x.join(), arg_0.pool)
            arg_0.workers_finished = True


def Func(arg_0, arg_1="tank.log"):
        """ Set up logging """
        arg_2 = logging.getLogger('')
        arg_0.log_filename = arg_1
        arg_0.core.add_artifact_file(arg_0.log_filename)

        arg_3 = logging.FileHandler(arg_0.log_filename)
        arg_3.setLevel(logging.DEBUG)
        arg_3.setFormatter(
            logging.Formatter(
                "%(asctime)s [%(levelname)s] %(name)s %(message)s"))
        arg_2.addHandler(arg_3)
        arg_4 = logging.StreamHandler(sys.stdout)
        arg_5 = logging.StreamHandler(sys.stderr)

        # fmt_verbose = logging.Formatter(
        #     "%(asctime)s [%(levelname)s] %(name)s %(message)s")
        arg_6 = logging.Formatter(
            "%(asctime)s %(levelname)s: %(message)s", "%H:%M:%S")

        arg_4.setLevel(logging.INFO)
        arg_4.setFormatter(arg_6)
        arg_5.setFormatter(arg_6)

        arg_7 = SingleLevelFilter(logging.ERROR, True)
        arg_8 = SingleLevelFilter(logging.WARNING, True)
        arg_9 = SingleLevelFilter(logging.CRITICAL, True)
        arg_4.addFilter(arg_7)
        arg_4.addFilter(arg_8)
        arg_4.addFilter(arg_9)
        arg_2.addHandler(arg_4)

        arg_10 = SingleLevelFilter(logging.INFO, True)
        arg_11 = SingleLevelFilter(logging.DEBUG, True)
        arg_5.addFilter(arg_10)
        arg_5.addFilter(arg_11)
        arg_2.addHandler(arg_5)


def Func(arg_0):
        """ override config options with user specified options"""
        if arg_0.options.get('user_options', None):
            arg_0.core.apply_shorthand_options(arg_0.options['user_options'])


def Func(arg_0):
        """ call shutdown routines """
        arg_1 = 1
        arg_0.log.info("Trying to shutdown gracefully...")
        arg_1 = arg_0.core.plugins_end_test(arg_1)
        arg_1 = arg_0.core.plugins_post_process(arg_1)
        arg_0.log.info("Done graceful shutdown")
        return arg_1


def Func(arg_0, arg_1=False):
        """
        Collect data, cache it and send to listeners
        """
        arg_2 = get_nowait_from_queue(arg_0.results)
        arg_3 = get_nowait_from_queue(arg_0.stats_results)
        logger.debug("Data timestamps: %s" % [arg_4.get('ts') for arg_4 in arg_2])
        logger.debug("Stats timestamps: %s" % [arg_4.get('ts') for arg_4 in arg_3])
        for arg_5 in arg_2:
            arg_6 = arg_5['ts']
            if arg_6 in arg_0.stat_cache:
                # send items
                arg_7 = arg_5
                arg_8 = arg_0.stat_cache.pop(arg_6)
                arg_0.__notify_listeners(arg_7, arg_8)
            else:
                arg_0.data_cache[arg_6] = arg_5
        for arg_5 in arg_3:
            arg_6 = arg_5['ts']
            if arg_6 in arg_0.data_cache:
                # send items
                arg_7 = arg_0.data_cache.pop(arg_6)
                arg_8 = arg_5
                arg_0.__notify_listeners(arg_7, arg_8)
            else:
                arg_0.stat_cache[arg_6] = arg_5
        if arg_1 and len(arg_0.data_cache) > 0:
            logger.info('Timestamps without stats:')
            for arg_6, arg_7 in sorted(arg_0.data_cache.items(), key=lambda i: i[0]):
                logger.info(arg_6)
                arg_0.__notify_listeners(arg_7, StatsReader.stats_item(arg_6, 0, 0))


def Func(arg_0, arg_1=False):
    '''
    Returns a marker function of the requested marker_type

    >>> marker = Func('uniq')(__test_missile)
    >>> type(marker)
    <type 'str'>
    >>> len(marker)
    32

    >>> Func('uri')(__test_missile)
    '_example_search_hello_help_us'

    >>> marker = Func('non-existent')(__test_missile)
    Traceback (most recent call last):
      ...
    NotImplementedError: No such marker: "non-existent"

    >>> Func('3')(__test_missile)
    '_example_search_hello'

    >>> marker = Func('3', True)
    >>> marker(__test_missile)
    '_example_search_hello#0'
    >>> marker(__test_missile)
    '_example_search_hello#1'
    '''
    try:
        arg_2 = int(arg_0)
        if arg_2:
            arg_3 = __UriMarker(arg_2)
        else:

            def arg_3(arg_4):
                return ''
    except ValueError:
        if arg_0 in __markers:
            arg_3 = __markers[arg_0]
        else:
            raise NotImplementedError('No such marker: "%s"' % arg_0)

    # todo: fix u'False'
    if arg_1:
        arg_3 = __Enumerator(arg_3)
    return arg_3


def Func(arg_0):
    '''
    Parse duration string, such as '3h2m3s' into milliseconds

    >>> Func('3h2m3s')
    10923000

    >>> Func('0.3s')
    300

    >>> Func('5')
    5000
    '''
    arg_1 = re.compile("([0-9.]+)([dhms]?)")

    def parse_token(arg_2, arg_3):
        arg_4 = {
            'd': 86400,
            'h': 3600,
            'm': 60,
            's': 1,
        }
        if arg_3:
            if arg_3 in arg_4:
                return int(float(arg_2) * arg_4[arg_3] * 1000)
            else:
                raise StepperConfigurationError(
                    'Failed to parse duration: %s' % arg_0)
        else:
            return int(float(arg_2) * 1000)

    return sum(parse_token(*arg_5) for arg_5 in arg_1.findall(arg_0))


def Func(arg_0):
        """Start remote agent"""
        logger.info('Starting agent: %s', arg_0.host)
        arg_1 = "{python} {agent_path} --telegraf {telegraf_path} --host {host} {kill_old}".format(
            python=arg_0.python,
            agent_path=os.path.join(
                arg_0.path['AGENT_REMOTE_FOLDER'],
                arg_0.AGENT_FILENAME),
            telegraf_path=arg_0.path['TELEGRAF_REMOTE_PATH'],
            host=arg_0.host,
            kill_old=arg_0.kill_old)
        logger.debug('Command to Func agent: %s', arg_1)
        arg_0.session = arg_0.ssh.async_session(arg_1)
        arg_0.reader_thread = threading.Thread(target=arg_0.read_buffer)
        arg_0.reader_thread.setDaemon(True)
        return arg_0.session


def Func(arg_0):
        """Searching for line in jmeter.log such as
        Waiting for possible shutdown message on port 4445
        """
        arg_1 = re.compile(arg_0.DISCOVER_PORT_PATTERN)
        with open(arg_0.process_stderr.name, 'r') as f:
            arg_2 = 0
            while arg_0.process.pid and arg_2 < 10:
                arg_3 = f.readline()
                arg_4 = arg_1.match(arg_3)
                if arg_4 is None:
                    arg_2 += 1
                    time.sleep(1)
                else:
                    arg_5 = int(arg_4.group('port'))
                    return arg_5
            else:
                logger.warning('JMeter UDP port wasn\'t discovered')
                return None


def Func(arg_0):
        """Gracefull termination of running process"""

        if arg_0.__stderr_file:
            arg_0.__stderr_file.close()

        if not arg_0.__process:
            return

        arg_1 = time.time() + _PROCESS_KILL_TIMEOUT
        while time.time() < arg_1:
            try:
                arg_0.__process.terminate()
            except EnvironmentError as e:
                if e.errno != errno.ESRCH:
                    _LOGGER.warning("Failed to terminate process '{}': {}".format(arg_0.__cmd, e))
                return
            time.sleep(0.1)

        try:
            arg_0.__process.kill()
        except EnvironmentError as e:
            if e.errno != errno.ESRCH:
                _LOGGER.warning("Failed to kill process '{}': {}".format(arg_0.__cmd, e))
            return


def Func(arg_0, arg_1):
        """
        Parse lines and return stats
        """

        arg_2 = []
        for arg_3 in arg_1:
            arg_4, arg_5, arg_6 = arg_3.split("\t")
            arg_7 = int(float(arg_4))  # We allow floats here, but tank expects only seconds
            if arg_0.__last_ts < arg_7:
                arg_0.__last_ts = arg_7
                arg_2.append(arg_0.stats_item(arg_0.__last_ts, float(arg_5), float(arg_6)))
        return arg_2


def Func(arg_0, arg_1):
        """ instantiate criterion from config string """
        arg_2 = arg_1.split("(")
        arg_3 = arg_2[0].strip().lower()
        arg_2[1] = arg_2[1].split(")")[0].strip()

        for arg_4 in arg_0.custom_criterions:
            if arg_4.get_type_string() == arg_3:
                return arg_4(arg_0, arg_2[1])
        raise ValueError(
            "Unsupported autostop criterion type: %s" % arg_1)


def Func(arg_0, arg_1, arg_2):
        """Prepare config data."""
        try:
            arg_3 = arg_0.parse_xml(arg_1)
        except IOError as exc:
            logger.error("Error loading config: %s", exc)
            raise RuntimeError("Can't read monitoring config %s" % arg_1)
        arg_4 = arg_3.findall('Host')
        arg_5 = []
        for arg_6 in arg_4:
            arg_7 = arg_0.get_host_config(arg_6, arg_2)
            arg_5.append(arg_7)
        return arg_5


def Func(arg_0):
        ''' raise exception on disk space exceeded '''
        arg_1 = "sh -c \"df --no-sync -m -P -l -x fuse -x tmpfs -x devtmpfs -x davfs -x nfs "
        arg_1 += arg_0.core.artifacts_base_dir
        arg_1 += " | tail -n 1 | awk '{print \$4}' \""
        arg_2 = execute(arg_1, True, 0.1, True)
        logging.debug("Result: %s", arg_2)
        if not len(arg_2[1]):
            arg_0.log.debug("No disk usage info: %s", arg_2[2])
            return
        arg_3 = arg_2[1]
        arg_0.log.debug(
            "Disk free space: %s/%s", arg_3.strip(), arg_0.disk_limit)
        if int(arg_3.strip()) < arg_0.disk_limit:
            raise RuntimeError(
                "Not enough local resources: disk space less than %sMB in %s: %sMB"
                % (
                    arg_0.disk_limit, arg_0.core.artifacts_base_dir,
                    int(arg_3.strip())))


def Func(arg_0):
        ''' raise exception on RAM exceeded '''
        arg_1 = psutil.virtual_memory().available / 2**20
        arg_0.log.debug("Memory free: %s/%s", arg_1, arg_0.mem_limit)
        if arg_1 < arg_0.mem_limit:
            raise RuntimeError(
                "Not enough resources: free memory less "
                "than %sMB: %sMB" % (arg_0.mem_limit, arg_1))


def Func(arg_0, arg_1):
        '''        Gets next line for right panel        '''
        arg_2 = ''
        if arg_1:
            arg_2 = arg_1.pop(0)
            if len(arg_2) > arg_0.right_panel_width:
                arg_3 = arg_0.markup.clean_markup(arg_2)
                if len(arg_3) > arg_0.right_panel_width:
                    arg_2 = arg_2[:arg_0.right_panel_width] + arg_0.markup.RESET
        return arg_2


def Func(arg_0, arg_1, arg_2):
        '''  Cut tuple of line chunks according to it's wisible lenght  '''
        def is_space(arg_3):
            return all([True if arg_4 == ' ' else False for arg_4 in arg_3])

        def is_empty(arg_5, arg_6):
            arg_7 = []
            for arg_3 in arg_5:
                if arg_3 in arg_6:
                    arg_7.append(True)
                elif is_space(arg_3):
                    arg_7.append(True)
                else:
                    arg_7.append(False)
            return all(arg_7)
        arg_8 = arg_2
        arg_7 = ''
        arg_6 = arg_0.markup.get_markup_vars()
        for arg_9, arg_3 in enumerate(arg_1):
            if arg_3 in arg_6:
                arg_7 += arg_3
            else:
                if arg_8 > 0:
                    if len(arg_3) <= arg_8:
                        arg_7 += arg_3
                        arg_8 -= len(arg_3)
                    else:
                        arg_10 = (arg_3[arg_8:],) + arg_1[arg_9 + 1:]
                        arg_11 = not is_empty(arg_10, arg_6)
                        if arg_11:
                            arg_7 += arg_3[:arg_8 - 1] + arg_0.markup.RESET + u'\u2026'
                        else:
                            arg_7 += arg_3[:arg_8]
                        arg_8 = 0
        return arg_7


def Func(arg_0, arg_1):
        '''  Right-pad lines of block to equal width  '''
        arg_2 = []
        arg_3 = max([arg_0.clean_len(arg_4) for arg_4 in arg_1])
        for arg_4 in arg_1:
            arg_5 = ' ' * (arg_3 - arg_0.clean_len(arg_4))
            arg_2.append(arg_4 + (arg_0.screen.markup.RESET, arg_5))
        return (arg_3, arg_2)


def Func(arg_0, arg_1):
        '''  Calculate wisible length of string  '''
        if isinstance(arg_1, basestring):
            return len(arg_0.screen.markup.clean_markup(arg_1))
        elif isinstance(arg_1, tuple) or isinstance(arg_1, list):
            arg_2 = arg_0.screen.markup.get_markup_vars()
            arg_3 = 0
            for arg_4 in arg_1:
                if arg_4 not in arg_2:
                    arg_3 += len(arg_4)
            return arg_3


def Func(arg_0):
    '''
    Creates load plan timestamps generator

    >>> from util import take

    >>> take(7, LoadPlanBuilder().ramp(5, 4000).Func())
    [0, 1000, 2000, 3000, 4000, 0, 0]

    >>> take(7, Func(['ramp(5, 4s)']))
    [0, 1000, 2000, 3000, 4000, 0, 0]

    >>> take(12, Func(['ramp(5, 4s)', 'wait(5s)', 'ramp(5,4s)']))
    [0, 1000, 2000, 3000, 4000, 9000, 10000, 11000, 12000, 13000, 0, 0]

    >>> take(7, Func(['wait(5s)', 'ramp(5, 0)']))
    [5000, 5000, 5000, 5000, 5000, 0, 0]

    >>> take(7, Func([]))
    [0, 0, 0, 0, 0, 0, 0]

    >>> take(12, Func(['line(1, 9, 4s)']))
    [0, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 0, 0, 0]

    >>> take(12, Func(['const(3, 5s)', 'line(7, 11, 2s)']))
    [0, 0, 0, 5000, 5000, 5000, 5000, 5500, 6000, 6500, 7000, 0]

    >>> take(12, Func(['step(2, 10, 2, 3s)']))
    [0, 0, 3000, 3000, 6000, 6000, 9000, 9000, 12000, 12000, 0, 0]

    >>> take(12, LoadPlanBuilder().const(3, 1000).line(5, 10, 5000).steps)
    [(3, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1)]

    >>> take(12, LoadPlanBuilder().stairway(100, 950, 100, 30000).steps)
    [(100, 30), (200, 30), (300, 30), (400, 30), (500, 30), (600, 30), (700, 30), (800, 30), (900, 30), (950, 30)]

    >>> LoadPlanBuilder().stairway(100, 950, 100, 30000).instances
    950

    >>> LoadPlanBuilder().const(3, 1000).line(5, 10, 5000).instances
    10

    >>> LoadPlanBuilder().line(1, 100, 60000).instances
    100
    '''
    arg_1 = LoadPlanBuilder().add_all_steps(arg_0)
    arg_2 = arg_1.Func()
    info.status.publish('duration', 0)
    # info.status.publish('steps', lpb.steps)
    info.status.publish('steps', [])
    info.status.publish('instances', arg_1.instances)
    return arg_2


def Func(arg_0):
        ''' format level str '''
        if arg_0.is_relative:
            arg_1 = str(arg_0.level) + "%"
        else:
            arg_1 = arg_0.level
        return arg_1


def Func(arg_0, arg_1):
        ''' add right panel widget '''
        if not arg_0.screen:
            arg_0.log.debug("No screen instance to add widget")
        else:
            arg_0.screen.Func(arg_1)


def Func(
            arg_0,
            arg_1=None,
            arg_2=None,
            arg_3="POST",
            arg_4=False):
        '''
        Send request to writer service.
        '''
        arg_5 = requests.Request(
            arg_3,
            arg_0.writer_url,
            arg_1=arg_1,
            arg_2=arg_2,
            headers={
                'User-Agent': arg_0.user_agent})
        arg_6 = id_gen(str(uuid.uuid4()))
        arg_7 = arg_0.network_timeouts()
        arg_8 = arg_0.maintenance_timeouts()
        while True:
            try:
                arg_9 = arg_0.__send_single_request(arg_5, arg_6.next(), arg_4=arg_4)
                return arg_9
            except (Timeout, ConnectionError, ProtocolError):
                logger.warn(traceback.format_exc())
                try:
                    arg_10 = next(arg_7)
                    logger.warn(
                        "Network error, will retry in %ss..." %
                        arg_10)
                    time.sleep(arg_10)
                    continue
                except StopIteration:
                    raise arg_0.NetworkError()
            except arg_0.UnderMaintenance as e:
                try:
                    arg_10 = next(arg_8)
                    logger.warn(
                        "Writer is under maintenance, will retry in %ss..." %
                        arg_10)
                    time.sleep(arg_10)
                    continue
                except StopIteration:
                    raise e


def Func(arg_0):
        """
        Tells core to take plugin options and instantiate plugin classes
        """
        logger.info("Loading plugins...")
        for (arg_1, arg_2, arg_3) in arg_0.config.plugins:
            logger.debug("Loading plugin %s from %s", arg_1, arg_2)
            if arg_2 == "yandextank.plugins.Overload":
                logger.warning(
                    "Deprecated plugin name: 'yandextank.plugins.Overload'\n"
                    "There is a new generic plugin now.\n"
                    "Correcting to 'yandextank.plugins.DataUploader overload'")
                arg_2 = "yandextank.plugins.DataUploader overload"
            try:
                arg_4 = il.import_module(arg_2)
            except ImportError:
                logger.warning('Plugin name %s path %s import error', arg_1, arg_2)
                logger.debug('Plugin name %s path %s import error', arg_1, arg_2, exc_info=True)
                raise
            try:
                arg_5 = getattr(arg_4, 'Plugin')(arg_0, cfg=arg_3, name=arg_1)
            except AttributeError:
                logger.warning('Plugin %s classname should be `Plugin`', arg_1)
                raise
            else:
                arg_0.register_plugin(arg_0.PLUGIN_PREFIX + arg_1, arg_5)
        logger.debug("Plugin instances: %s", arg_0._plugins)


def Func(arg_0, arg_1):
        """
        Retrieve a plugin of desired class, KeyError raised otherwise
        """
        logger.debug("Searching for plugin: %s", arg_1)
        arg_2 = [plugin for plugin in arg_0.plugins.values() if isinstance(plugin, arg_1)]
        if arg_2:
            if len(arg_2) > 1:
                logger.debug(
                    "More then one plugin of type %s found. Using first one.",
                    arg_1)
            return arg_2[-1]
        else:
            raise KeyError("Requested plugin type not found: %s" % arg_1)


def Func(arg_0, arg_1):
        """
        Retrieve a list of plugins of desired class, KeyError raised otherwise
        """
        logger.debug("Searching for plugins: %s", arg_1)
        arg_2 = [plugin for plugin in arg_0.plugins.values() if isinstance(plugin, arg_1)]
        if arg_2:
            return arg_2
        else:
            raise KeyError("Requested plugin type not found: %s" % arg_1)


def Func(arg_0, arg_1, arg_2=False):
        """
        Move or copy single file to artifacts dir
        """
        arg_3 = arg_0.artifacts_dir + '/' + os.path.basename(arg_1)
        logger.debug("Collecting file: %s to %s", arg_1, arg_3)
        if not arg_1 or not os.path.exists(arg_1):
            logger.warning("File not found to collect: %s", arg_1)
            return

        if os.path.exists(arg_3):
            # FIXME: 3 find a way to store artifacts anyway
            logger.warning("File already exists: %s", arg_3)
            return

        if arg_2:
            shutil.copy(arg_1, arg_0.artifacts_dir)
        else:
            shutil.move(arg_1, arg_0.artifacts_dir)

        os.chmod(arg_3, 0o644)


def Func(arg_0, arg_1, arg_2=False):
        """
        Add file to be stored as result artifact on post-process phase
        """
        if arg_1:
            logger.debug(
                "Adding artifact file to collect (keep=%s): %s", arg_2,
                arg_1)
            arg_0.artifact_files[arg_1] = arg_2


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """
        Generate temp file name in artifacts base dir
        and close temp file handle
        """
        if not arg_3:
            arg_3 = arg_0.artifacts_dir
        arg_4, arg_5 = tempfile.Func(arg_1, arg_2, arg_3)
        os.close(arg_4)
        os.chmod(arg_5, 0o644)  # FIXME: chmod to parent dir's mode?
        return arg_5


def Func(arg_0, arg_1):
        """         Read configs set into storage        """
        logger.debug("Reading configs: %s", arg_1)
        arg_2 = [resource.resource_filename(config) for config in arg_1]
        try:
            arg_0.config.read(arg_2)
        except Exception as ex:
            logger.error("Can't load configs: %s", ex)
            raise ex


def Func(arg_0, arg_1=None):
        """        Flush current stat to file        """
        if not arg_1:
            arg_1 = arg_0.file

        if arg_1:
            with open(arg_1, 'w') as handle:
                arg_0.config.write(handle)


def Func(arg_0, arg_1):
        """ return sections with specified prefix """
        arg_2 = []
        for arg_3 in arg_0.config.sections():
            if arg_3.startswith(arg_1):
                arg_2.append(arg_3)
        return arg_2


def Func(arg_0, arg_1):
        """
        Return all items found in this chunk
        """
        for arg_2, arg_3 in arg_1.iteritems():
            arg_4 = datetime.datetime.strptime(
                arg_2.split(".")[0], '%Y-%m-%d %H:%M:%S')
            arg_5 = int(time.mktime(arg_4.timetuple()))
            arg_6 = 0
            for arg_7, arg_8 in arg_3.iteritems():
                if not arg_7.startswith("benchmark_io"):
                    continue
                for arg_9, arg_10 in arg_8.iteritems():
                    if "mmtasks" in arg_10:
                        arg_6 += arg_10["mmtasks"][2]

            arg_11 = arg_5 - 1 - arg_0.start_time
            arg_12 = 0
            if 0 <= arg_11 < len(arg_0.phantom_info.steps):
                arg_12 = arg_0.phantom_info.steps[arg_11][0]
            yield arg_0.stats_item(arg_5 - 1, arg_6, arg_12)


def Func(arg_0):
        """ returns info object """
        if not arg_0.cached_info:
            if not arg_0.phantom:
                return None
            arg_0.cached_info = arg_0.phantom.Func()
        return arg_0.cached_info


def Func(arg_0):
        """Prepare for monitoring - install agents etc"""

        # Parse config
        arg_1 = []
        if arg_0.config:
            arg_1 = arg_0.config_manager.getconfig(
                arg_0.config, arg_0.default_target)

        # Creating agent for hosts
        for arg_2 in arg_1:
            if arg_2['host'] in ['localhost', '127.0.0.1', '::1']:
                arg_3 = arg_0.clients['localhost'](
                    arg_2, arg_0.old_style_configs, kill_old=arg_0.kill_old)
            else:
                arg_3 = arg_0.clients['ssh'](
                    arg_2, arg_0.old_style_configs, timeout=5, kill_old=arg_0.kill_old)
            logger.debug('Installing monitoring agent. Host: %s', arg_3.host)
            arg_4, arg_5, arg_6 = arg_3.install()
            if arg_4:
                arg_0.agents.append(arg_3)
                arg_0.artifact_files.append(arg_4)
            if arg_5:
                arg_0.artifact_files.append(arg_5)
            if arg_6:
                arg_0.artifact_files.append(arg_6)


def Func(arg_0):
        """ Poll agents for data
        """
        arg_1 = time.time()
        for arg_2 in arg_0.agents:
            for arg_3 in arg_2.reader:
                # don't crush if trash or traceback came from agent to stdout
                if not arg_3:
                    return 0
                for arg_4 in arg_3:
                    arg_5, arg_6 = arg_4
                    if arg_0.load_start_time and int(
                            arg_5) >= arg_0.load_start_time:
                        arg_7 = {
                            "timestamp": int(arg_5),
                            "data": {
                                arg_0.hash_hostname(arg_2.host): {
                                    "comment": arg_2.config.comment,
                                    "metrics": arg_6
                                }
                            }
                        }
                        arg_0.__collected_data.append(arg_7)

        logger.debug(
            'Polling/decoding agents data took: %.2fms',
            (time.time() - arg_1) * 1000)

        arg_8 = len(arg_0.__collected_data)

        if not arg_0.first_data_received and arg_0.__collected_data:
            arg_0.first_data_received = True
            logger.info("Monitoring received first data.")
        else:
            arg_0.send_collected_data()
        return arg_8


def Func(arg_0):
        """sends pending data set to listeners"""
        arg_1 = arg_0.__collected_data
        arg_0.__collected_data = []
        for arg_3 in arg_0.listeners:
            # deep copy to ensure each listener gets it's own copy
            arg_3.monitoring_data(copy.deepcopy(arg_1))