"""
The operators module contains the Operator class, instances of which
represent unitary operators on vector spaces for multi-qubit systems, and
factory functions for creating specific operators.

The Operator class inherits from the OperatorBase class, which contains
functionality common to unitary operators and the
:py:class:`.DensityOperator` class.

The Operator class and the factory functions used to create operators are
aliased at the top-level module, so that, for example, one can call
``qcircuits.Hadamard()`` instead of ``qcircuits.state.Hadamard()``.
"""

from itertools import product
import copy

import numpy as np

from qcircuits.tensors import Tensor

class OperatorBase(Tensor):
    """
    A base class for operators and density operators.

    Parameters
    ----------
    tensor : numpy complex128 multidimensional array
        The tensor representing the operator.
    """

    def __init__(self, tensor):
        super().__init__(tensor)

    @staticmethod
    def from_matrix(M):
        """
        QCircuits represents operators for d-qubit systems with type (d, d) tensors.
        This function constructs an operator from the more common matrix
        Kronecker-product representation of the operator.

        Parameters
        ----------
        numpy complex128 multidimensional array
            The matrix representation of the operator.

        Returns
        -------
        Operator
            A d-qubit operator.

        """

        if type(M) is list:
            M = np.array(M, dtype=np.complex128)

        # Check the matrix is square
        shape = M.shape
        if len(shape) != 2 or shape[0] != shape[1]:
            raise ValueError('The matrix should be square.')
        # Check the dimension is a power of 2
        d = np.log2(shape[0])
        if not d.is_integer():
            raise ValueError('The matrix dimension should be a power of 2.')
        d = int(d)

        permutation = [0] * 2 * d
        permutation[::2] = range(0, d)
        permutation[1::2] = range(d, 2*d)

        return Operator(M.reshape([2] * 2 * d).transpose(permutation))

    @staticmethod
    def _tensor_to_matrix(t):
        d = len(t.shape) // 2
        permutation = list(range(0, 2*d, 2)) + list(range(1, 2*d, 2))
        return t.transpose(permutation).reshape(2**d, 2**d)

    def to_matrix(self):
        """
        QCircuits represents operators for d-qubit systems with type (d, d) tensors.
        This function returns the more common matrix Kronecker-product
        representation of the operator.

        Returns
        -------
        numpy complex128 multidimensional array
            The matrix representation of the operator.
        """

        return self._tensor_to_matrix(self._t)

    @property
    def adj(self):
        """
        Get the adjoint of this operator,
        :math:`A^{\dagger} = (A^{*})^{T}`.
        If the operator is unitary,
        :math:`A A^{\dagger} = I`.

        Returns
        -------
        Operator
            The adjoint operator.
        """

        d = self.rank
        permutation = [0] * d
        permutation[::2] = range(1, d, 2)
        permutation[1::2] = range(0, d, 2)
        t = np.conj(self._t).transpose(permutation)
        return self.__class__(t)

    def _permuted_tensor(self, axes, inverse=False):
        if inverse:
            axes = np.argsort(axes)

        op_axes = [[2*n, 2*n+1] for n in axes]
        op_axes = [v for sublist in op_axes for v in sublist]

        return np.transpose(self._t, op_axes)

    def permute_qubits(self, axes, inverse=False):
        """
        Permute the qubits (i.e., both the incoming and outgoing wires)
        of the operator. This method modifies the operator in-place,
        but also returns the resulting operator to allow chaining of
        operations.

        Parameters
        ----------
        axes : list of int
            Permute the qubits according to the values given.
        inverse : bool
            If true, perform the inverse permutation of the qubits.

        Returns
        -------
        Operator
            The resulting operator.
        """

        self._t = self._permuted_tensor(axes, inverse=inverse)
        return self

    def swap_qubits(self, axis1, axis2):
        """
        Swap two qubits (i.e., both the incoming and outgoing wires)
        of the operator. This method modifies the operator in-place,
        but also returns the resulting operator to allow chaining of
        operations.

        Parameters
        ----------
        axis1 : int
            First axis.
        axis2 : int
            Second axis.

        Returns
        -------
        Operator
            The resulting operator.
        """

        self._t = np.swapaxes(self._t, 2*axis1, 2*axis2)
        self._t = np.swapaxes(self._t, 2*axis1 + 1, 2*axis2 + 1)
        return self

from qcircuits.density_operator import DensityOperator

class Operator(OperatorBase):
    """
    A container class for a tensor representing an operator on a vector
    space for a quantum system, and associated methods.

    Parameters
    ----------
    tensor : numpy complex128 multidimensional array
        The tensor representing the operator.
    """

    def __init__(self, tensor):
        super().__init__(tensor)
        # TODO check unitary (maybe only check when applying?)

    def __repr__(self):
        s = 'Operator('
        s += super().__str__().replace('\n', '\n' + ' ' * len(s))
        s += ')'
        return s

    def __str__(self):
        s = 'Operator for {}-qubit state space.'.format(self.rank // 2)
        s += ' Tensor:\n'
        s += super().__str__()
        return s

    def __add__(self, arg):
        return Operator(self._t + arg._t)

    def __sub__(self, arg):
        return self + (-1) * arg

    def __mul__(self, scalar):
        if isinstance(scalar, (float, int, complex)):
            return Operator(scalar * self._t)
        else:
            return super().__mul__(scalar)

    def __rmul__(self, scalar):
        if isinstance(scalar, (float, int, complex)):
            return Operator(scalar * self._t)

    def __truediv__(self, scalar):
        return Operator(self._t / scalar)

    def __neg__(self):
        return Operator(-self._t)

    def _apply(self, arg, qubit_indices=None):
        if isinstance(arg, OperatorBase):
            d = arg.rank // 2
            arg_indices = list(range(0, 2*d, 2))
        else:
            d = arg.rank
            arg_indices = list(range(d))
        op_indices = list(range(1, self.rank, 2))

        if len(op_indices) > d:
            raise ValueError('An operator for a d-rank state space can only be applied to '
                             'a system whose rank is >= d.')
        if len(op_indices) < d and qubit_indices is None:
            raise ValueError('Applying operator to too-large system without supplying '
                             'qubit indices.')

        if qubit_indices is not None:
            qubit_indices = list(qubit_indices)

            if len(set(qubit_indices)) != len(qubit_indices):
                raise ValueError('Qubit indices list contains repeated elements.')
            if min(qubit_indices) < 0:
                raise ValueError('Supplied qubit index < 0.')
            if max(qubit_indices) >= d:
                raise ValueError('Supplied qubit index larger than system size.')
            if len(qubit_indices) != len(op_indices):
                raise ValueError('Length of qubit_indices does not match operator.')
        else:
            qubit_indices = list(range(d))

        d1 = len(qubit_indices)
        non_application_indices = sorted(list(set(range(d))  - set(qubit_indices)))
        application_permutation = qubit_indices + non_application_indices

        arg_t = arg._permuted_tensor(application_permutation)
        arg_indices = arg_indices[:len(qubit_indices)]
        result = np.tensordot(self._t, arg_t, (op_indices, arg_indices))

        # Our convention is to have lower and upper indices of operators interleaved.
        # Using tensordot on operator-operator application leaves us with all upper
        # indices followed by all lower. We transpose the result to fix this.
        if isinstance(arg, OperatorBase):
            permute = [0] * 2*d
            permute[: 2*d1 : 2] = range(d1)
            permute[1 : 2*d1 : 2] = range(d1, 2*d1)
            permute[2*d1 : 2*d] = range(2*d1, 2*d)
            result = np.transpose(result, permute)

        return_val = arg.__class__(result)
        return_val.permute_qubits(application_permutation, inverse=True)
        if not isinstance(arg, OperatorBase):
            return_val.renormalize_()

        return return_val

    def __call__(self, arg, qubit_indices=None):
        """
        Applies this Operator to another Operator, as in operator
        composition A(B), or to a :py:class:`.State` or :py:class:`.DensityOperator`,
        as in A(v). Via operator composition,
        if two operators A and B will be applied to state v in sequence,
        either B(A(v)) or (B(A))(v) are valid.

        A d-qubit operator may be applied to an n-qubit system with :math:`n>d`
        if the qubits to which it is to be applied are specified in the
        `qubit_indices` parameter.

        If x represents state :math:`|\\phi⟩` and A an operator,
        A(x) represents the state :math:`A |\\phi⟩`.
        If x represents density operator (mixed state)
        :math:`\\rho`, then A(x) represents the state
        :math:`A \\rho A^{\dagger}.`

        Parameters
        ----------
        arg : State, Operator, or DensityOperator
            The state that the operator is applied to, or the operator
            with which the operator is composed.
        qubit_indices: list of int
            If the operator is applied to a larger
            quantum system, the user must supply a list of the indices
            of the qubits to which the operator is to be applied.
            These can also be used to apply the operator to the qubits
            in arbitrary order.

        Returns
        -------
        State, Operator, or DensityOperator
            The state vector or operator resulting in applying the
            operator to the argument.
        """

        if isinstance(arg, DensityOperator):
            return self._apply(
                self._apply(arg.adj, qubit_indices).adj,
                qubit_indices
            )
        else:
            return self._apply(arg, qubit_indices)

# Factory functions for building operators

def Identity(d=1):
    """
    Produce the `d`-qubit identity operator :math:`I^{\\otimes d}`.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Operator(np.array([[1.0 + 0.0j, 0.0j],
                              [0.0j, 1.0 + 0.0j]])).tensor_power(d)

def PauliX(d=1):
    """
    Produce the `d`-qubit Pauli X operator :math:`X^{\\otimes d}`,
    or `not` gate.
    Maps: \|0⟩ -> \|1⟩, \|1⟩ -> \|0⟩.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Operator(np.array([[0.0j, 1.0 + 0.0j],
                              [1.0 + 0.0j, 0.0j]])).tensor_power(d)

def PauliY(d=1):
    """
    Produce the `d`-qubit Pauli Y operator :math:`Y^{\\otimes d}`.
    Maps: \|0⟩ -> `i` \|1⟩, \|1⟩ -> -`i` \|0⟩.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Operator(np.array([[0.0j, -1.0j],
                              [1.0j, 0.0j]])).tensor_power(d)

def PauliZ(d=1):
    """
    Produce the `d`-qubit Pauli Z operator :math:`Z^{\\otimes d}`,
    or phase inverter.
    Maps: \|0⟩ -> \|0⟩, \|1⟩ -> -\|1⟩.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """
    return Operator(np.array([[1.0 + 0.0j, 0.0j],
                              [0.0j, -1.0 + 0.0j]])).tensor_power(d)

def Hadamard(d=1):
    """
    Produce the `d`-qubit Hadamard operator :math:`H^{\\otimes d}`.
    Maps: \|0⟩ -> :math:`\\frac{1}{\\sqrt{2}}` (\|0⟩+\|1⟩) = \|+⟩,
    \|1⟩ -> :math:`\\frac{1}{\\sqrt{2}}` (\|0⟩-\|1⟩) = \|-⟩.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """
    return Operator(1/np.sqrt(2) *
        np.array([[1.0 + 0.0j,  1.0 + 0.0j],
                  [1.0 + 0.0j, -1.0 + 0.0j]])).tensor_power(d)

def Phase(d=1):
    """
    Produce the `d`-qubit Phase operator S.
    Maps: \|0⟩ -> \|0⟩, \|1⟩ -> i\|1⟩.
    Note that :math:`S^2 = Z`.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Operator(np.array([[1.0 + 0.0j, 0.0j],
                              [0.0j, 1.0j]])).tensor_power(d)
def PiBy8(d=1):
    """
    Produce the `d`-qubit :math:`\pi/8` operator T.
    Maps: \|0⟩ -> \|0⟩, \|1⟩ -> :math:`e^{i\pi/4}` \|1⟩.
    Note that :math:`T^2 = S`, where S is the phase gate,
    and :math:`T^4 = Z`.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, Rotation
    RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Operator(np.array([[1.0 + 0.0j, 0.0j],
                              [0.0j, np.exp(1j * np.pi/4)]])).tensor_power(d)

def Rotation(v, theta):
    """
    Produce the single-qubit rotation operator.
    In terms of the Bloch sphere picture of the qubit state, the
    operator rotates a state through angle :math:`\theta` around vector v.

    Parameters
    ----------
    v : list of float
        A real 3D unit vector around which the qubit's Bloch vector is to be rotated.
    theta : float
        The angle through which the qubit's Bloch vector is to be rotated.

    Returns
    -------
    Operator
        A rank 2 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase
    PiBy8, RotationX, RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    v = np.array(v)
    if v.shape != (3,) or abs(v.dot(v) - 1.0) > 1e-8 or not np.all(np.isreal(v)):
        raise ValueError('Rotation vector v should be a 3D real unit vector.')

    return np.cos(theta/2) * Identity() - 1j * np.sin(theta/2) * (
        v[0] * PauliX() + v[1] * PauliY() + v[2] * PauliZ())

def RotationX(theta):
    """
    Produce the single-qubit X-rotation operator.
    In terms of the Bloch sphere picture of the qubit state, the
    operator rotates a state through angle theta around the x-axis.

    Parameters
    ----------
    theta : float
        The angle through which the qubit's Bloch vector is to be rotated.

    Returns
    -------
    Operator
        A rank 2 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationY, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Rotation([1., 0., 0.], theta)

def RotationY(theta):
    """
    Produce the single-qubit Y-rotation operator.
    In terms of the Bloch sphere picture of the qubit state, the
    operator rotates a state through angle theta around the y-axis.

    Parameters
    ----------
    theta : float
        The angle through which the qubit's Bloch vector is to be rotated.

    Returns
    -------
    Operator
        A rank 2 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationZ, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Rotation([0., 1., 0.], theta)

def RotationZ(theta):
    """
    Produce the single-qubit Z-rotation operator.
    In terms of the Bloch sphere picture of the qubit state, the
    operator rotates a state through angle theta around the z-axis.

    Parameters
    ----------
    theta : float
        The angle through which the qubit's Bloch vector is to be rotated.

    Returns
    -------
    Operator
        A rank 2 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, SqrtNot, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Rotation([0., 0., 1.], theta)

def SqrtNot(d=1):
    """
    Produce the `d`-qubit operator that is the square root of the
    `d`-qubit NOT or :py:func:`PauliX` operator, i.e.,
    :math:`\\sqrt{\\texttt{NOT}}(\\sqrt{\\texttt{NOT}}) = X`.

    Parameters
    ----------
    d : int
        The number of qubits described by the state vector on which
        the produced operator will act.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, CNOT, Toffoli
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Operator(0.5 * np.array([[1 + 1j, 1 - 1j],
                                    [1 - 1j, 1 + 1j]])).tensor_power(d)

def CNOT():
    """
    Produce the two-qubit CNOT operator, which flips the second bit
    if the first bit is set.
    Maps \|00⟩ -> \|00⟩, \|01⟩ -> \|01⟩, \|10⟩ -> \|01⟩, \|11⟩ -> \|10⟩.

    Returns
    -------
    Operator
        A rank 4 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, Toffoli, SqrtNot
    Swap, SqrtSwap, ControlledU, U_f
    """

    return Operator((1.0 + 0.0j) *  np.array([[[[ 1.0, 0.0],
                                                [ 0.0, 1.0]],
                                               [[ 0.0, 0.0],
                                                [ 0.0, 0.0]]],
                                              [[[ 0.0, 0.0],
                                                [ 0.0, 0.0]],
                                               [[ 0.0, 1.0],
                                                [ 1.0, 0.0]]]]))

def Toffoli():
    """
    Produce the three-qubit Toffoli operator, which flips the third bit
    if the first two bits are set.
    Maps \|110⟩ -> \|111⟩, \|111⟩ -> \|110⟩, and otherwise acts as the
    identity.

    Returns
    -------
    Operator
        A rank 6 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, CNOT, SqrtNot
    Swap, SqrtSwap, ControlledU, U_f
    """

    d = 3
    shape = [2] * 2 * d
    t = np.zeros(shape, dtype=np.complex128)

    # Fill in the operator as the Identity operator.
    t[:] = Identity(d)[:]
    # In the case that the first two bits are set, it acts on the third
    # bit as the PauliX operator.
    t[:, 1, :, 1, ...] = (Identity(2) * PauliX())[:, 1, :, 1]

    return Operator(t)

def Swap():
    """
    Produce the two-qubit SWAP operator, which swaps two bits.
    Maps \|00⟩ -> \|00⟩, \|01⟩ -> \|10⟩, \|10⟩ -> \|01⟩, \|11⟩ -> \|11⟩.

    Returns
    -------
    Operator
        A rank 4 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot
    CNOT, Toffoli, SqrtSwap, ControlledU, U_f
    """

    return Operator((1.0 + 0.0j) *  np.array([[[[ 1.0, 0.0],
                                                [ 0.0, 0.0]],
                                               [[ 0.0, 0.0],
                                                [ 1.0, 0.0]]],
                                              [[[ 0.0, 1.0],
                                                [ 0.0, 0.0]],
                                               [[ 0.0, 0.0],
                                                [ 0.0, 1.0]]]]))

def SqrtSwap():
    """
    Produce the two-qubit operator that is the square root of the
    :py:func:`.Swap` operator, i.e.,
    :math:`\\sqrt{\\texttt{SWAP}}(\\sqrt{\\texttt{SWAP}}) = \\texttt{SWAP}`.

    Returns
    -------
    Operator
        A rank 4 tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot
    CNOT, Toffoli, Swap, ControlledU, U_f
    """

    return Operator(np.array([[[[ 1.0,                 0.0],
                                [ 0.0,      0.5 * (1 + 1j)]],
                               [[ 0.0,                 0.0],
                                [ 0.5 * (1 - 1j),      0.0]]],
                              [[[ 0.0,       0.5 * (1 - 1j)],
                                [ 0.0,                 0.0]],
                               [[ 0.5 * (1 + 1j),      0.0],
                                [ 0.0,                 1.0]]]]))

def ControlledU(U):
    """
    Produce a Controlled-U operator, an operator for a `d` + 1 qubit
    system where the supplied U is an operator for a `d` qubit system.
    If the first bit is set, apply U to the state for the remaining
    bits.

    Parameters
    ----------
    U : Operator
        The operator to be conditionally applied.

    Returns
    -------
    Operator
        A tensor whose rank is the rank of U plus 2,
        describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot
    CNOT, Toffoli, Swap, SqrtSwap, U_f
    """

    d = U.rank // 2 + 1
    shape = [2] * 2 * d
    t = np.zeros(shape, dtype=np.complex128)

    # If the first bit is zero, fill in as the identity operator.
    t[:, 0, ...] = Identity(d)[:, 0, ...]
    # Else, fill in as Identity tensored with U (Identity for the first bit,
    # which remains unchanged.
    t[:, 1, ...] = (Identity() * U)[:, 1, ...]
    return Operator(t)

def U_f(f, d):
    """
    Produce a U_f operator, an operator for a `d` qubit
    system that flips the last bit based on the outcome of a supplied
    boolean function :math:`f: [0, 1]^{d-1} \\to [0, 1]` applied to the
    first `d` - 1 bits.

    Parameters
    ----------
    f : function
        The boolean function used to conditionally flip the last bit.

    Returns
    -------
    Operator
        A rank `2d` tensor describing the operator.

    See Also
    --------
    Identity, PauliX, PauliY, PauliZ, Hadamard, Phase, PiBy8, Rotation
    RotationX, RotationY, RotationZ, SqrtNot
    CNOT, Toffoli, Swap, SqrtSwap, ControlledU
    """
    if d < 2:
        raise ValueError('U_f operator requires rank >= 2.')

    operator_shape = [2] * 2 * d
    t = np.zeros(operator_shape, dtype=np.complex128)

    for bits in product([0, 1], repeat=d):
        input_bits = bits[:-1]
        result = f(*input_bits)

        if result not in [0, 1]:
            raise RuntimeError('Function f for U_f operator should be Boolean,' \
                               'i.e., return 0 or 1.')

        result_bits = list(bits)
        if result:
            result_bits[-1] = 1 - result_bits[-1]
        all_bits = tuple([item for sublist in zip(result_bits, bits) for item in sublist])

        t[all_bits] = 1.0 + 0.0j

    return Operator(t)


from typing import Generator
from collections import defaultdict as dd
import numpy as np
import networkx as nx
import re, math, itertools

offsets = [(1, 0), (-1, 0), (0, 1), (0, -1)]

def contains(a, b):
    return a[0] <= b[0] and a[1] >= b[1]

def overlaps(a, b):
    return a[0] <= b[0] <= a[1]

def solve(input: str) -> Generator[any, None, None]:
    lines = [line.strip() for line in input.split("\n") if line]

    pairs = [
        [list(map(int, grp.split("-"))) for grp in line.split(",")] for line in lines
    ]

    total = 0
    for [a, b] in pairs:
        if contains(a, b) or contains(b, a):
            total += 1

    yield total

    count = 0

    for [a, b] in pairs:
        if overlaps(a, b) or overlaps(b, a):
            count += 1

    yield count


from aiogram.types import Message, InlineQuery
from loader import dp, bot, upload_client
from utils.db_api.database import Requests
from utils.instagram import InstagramStory

@dp.message_handler(is_subscriber=True, instagram_story=True, state='*')
async def instagram_story_handler(message: Message):
    post = InstagramStory(message.text)
    await post.start()
    await post.send_to(bot=bot, upload_client=upload_client, chat_id=message.chat.id)
    await Requests.add(user_id=message.from_user.id, content_type='s')

@dp.inline_handler(is_subscriber=True, instagram_inline_story=True, state='*')
async def instagram_story_inline_handler(query: InlineQuery):
    story = InstagramStory(query.query.strip())
    await story.start()
    await story.inline_to(query=query)
    await Requests.add(user_id=query.from_user.id, content_type='s')


from binary import Bin
from binary import Bin16

class Memory():
	def __init__(self):
		self.memory = [Bin()] * 65536

	def __getitem__(self, key):
		if isinstance(key, Bin16):
			return self.memory[key.toDecimal()]
		else:
			return self.memory[key]

	def __setitem__(self, key, value):
		if isinstance(key, Bin16):
			self.memory[key.toDecimal()] = value
		else:
			self.memory[key] = value
		return self.memory

	def getROM(self):
		temp = Memory()
		temp.memory = self.memory[:32767+1]
		return temp

	def load(self, file):
		with open(file, "rb") as file:
			byte = file.read(1)
			counter = 0
			while len(byte) != 0:
				byte = Bin.fromDecimal(ord(byte))
				self.memory[counter] = byte
				counter += 1
				byte = file.read(1)

class MemoryBus(Memory):
	def __init__(self, memory):
		self.memory = memory

if __name__ == "__main__":
	a = Memory()
	a.loadROM("game.gb")
	a.getROM()


from django.conf import settings
from django.contrib.gis.geos import GEOSGeometry
from rest_framework import serializers
from rest_framework.fields import empty
from rest_framework.utils import model_meta

from issues.api.utils import XMLDict
from issues.excs import MultipleJurisdictionsError
from issues.extensions import get_extensions
from issues.models import Issue, Jurisdiction, Service

class ServiceSerializer(serializers.ModelSerializer):

    class Meta:
        model = Service
        fields = ['service_code', 'service_name', 'description', 'metadata', 'type', 'keywords', 'group']

class IssueSerializer(serializers.ModelSerializer):
    distance = serializers.SerializerMethodField()
    extended_attributes = serializers.SerializerMethodField()
    jurisdiction_id = serializers.SlugRelatedField(
        queryset=Jurisdiction.objects.all(),
        source='jurisdiction',
        required=False,
        slug_field='identifier',
        write_only=True,
    )
    lat = serializers.FloatField(required=False)
    long = serializers.FloatField(required=False)
    service_name = serializers.SerializerMethodField(read_only=True)
    service_request_id = serializers.CharField(read_only=True, source='identifier')

    class Meta:
        model = Issue
        fields = [
            'address',
            'agency_responsible',
            'description',
            'expected_datetime',
            'extended_attributes',
            'distance',
            'jurisdiction_id',
            'lat',
            'long',
            'media_url',
            'requested_datetime',
            'service_code',
            'service_name',
            'service_notice',
            'service_request_id',
            'status',
            'status_notes',
            'updated_datetime',
        ]
        write_only_fields = [  # This is not directly supported by DRF; see below for the patch
            'address_string',
            'first_name',
            'last_name',
            'email',
            'phone',
        ]
        extra_kwargs = {
            'service_code': {'required': True},
        }
        for f in write_only_fields:
            extra_kwargs.setdefault(f, {})["write_only"] = True

    def __init__(self, instance=None, data=empty, **kwargs):
        super().__init__(instance, data, **kwargs)

        for ext in self.context.get('extensions', ()):
            ext.extend_issue_serializer(self)

    def get_distance(self, obj):
        if hasattr(obj, 'distance'):
            return float(obj.distance.m)
        else:
            return None

    def get_service_name(self, obj):
        return obj.service.safe_translation_getter(
            "service_name",
            default=obj.service.service_code,
            any_language=True
        )

    def get_extended_attributes(self, obj):
        extensions = self.context.get('extensions', ())
        extended_attributes = {}
        for ex in extensions:
            extended_attributes.update(
                ex.get_extended_attributes(
                    issue=obj,
                    context=self.context
                ) or {}
            )
        return extended_attributes

    def to_representation(self, instance):
        """

        :type instance: issues.models.Issue
        :rtype: dict
        """
        representation = super().to_representation(instance)
        if not (instance.lat and instance.long):  # Remove null coordinate fields
            representation.pop('lat', None)
            representation.pop('long', None)

        if not self.context.get('extensions', ()):
            representation.pop('extended_attributes', None)

        if representation.get('distance') is None:
            representation.pop('distance')

        return XMLDict(representation, "request")

    def validate(self, data):
        application = self.context.get('application')
        if application:
            data['application'] = application

        service_code = data.pop('service_code')
        service = Service.objects.filter(service_code=service_code).first()
        if not service:
            raise serializers.ValidationError(f'Service code {service_code} is invalid')
        data['service'] = service

        lat = data.pop('lat', None)
        long = data.pop('long', None)
        if lat and long:
            data['location'] = GEOSGeometry(  # TODO: Maybe remove? Looks like a GEOS dependency
                f'SRID=4326;POINT({long} {lat})'
            )

        if not data.get('jurisdiction'):
            try:
                data['jurisdiction'] = Jurisdiction.autodetermine()
            except MultipleJurisdictionsError as mjd:
                raise serializers.ValidationError(mjd.args[0])

        for ex in self.context.get('extensions', ()):
            new_data = ex.validate_issue_data(self, data)
            if new_data:
                data = new_data

        return data

    def create(self, validated_data):
        validated_data['moderation'] = getattr(settings, 'ISSUES_DEFAULT_MODERATION_STATUS', 'public')
        instance = self._create(validated_data)
        extensions = get_extensions()
        request = self.context['request']
        for ex in extensions:
            ex().post_create_issue(request=request, issue=instance, data=validated_data)
        return instance

    def _create(self, validated_data):
        validated_data = validated_data.copy()  # We're going to pop stuff off here.
        # This logic is mostly copied from super().create(),
        # aside from the concrete_data stuff and `.clean()`ing the model before saving.
        ModelClass = self.Meta.model
        info = model_meta.get_field_info(ModelClass)
        many_to_many = {}
        for field_name, relation_info in info.relations.items():
            if relation_info.to_many and (field_name in validated_data):
                many_to_many[field_name] = validated_data.pop(field_name)

        # Build a dict of fields we're guaranteed to be able to pass to `Model.create()`
        concrete_fields = set(info.fields) | set(info.forward_relations)
        concrete_data = {
            field: value
            for (field, value)
            in validated_data.items()
            if field in concrete_fields
        }
        instance = ModelClass(**concrete_data)
        instance.clean()
        instance.save()
        for field_name, value in many_to_many.items():
            setattr(instance, field_name, value)
        return instance


import pandas as pd
import collections

def make_transitions(feature_dict, clause_ends=True):
    '''
    --input--
    feature dictionary
    dict[book] = list(list(strings))

    --output--
    x2 df(trans. frequencies x book), df(trans. ratios x book)
    '''

    df_Transition_freq = dict() # Transition matrix with frequences
    df_Transition_prob = dict() # Normalized transition matrix

    # a dict to count the transition pairs per book
    transition_pairs = collections.defaultdict(lambda: collections.Counter())

    for bookname, clauses in feature_dict.items():

        # count transitions using bigrams
        transitions = list()
        for clause in clauses:

            if clause_ends:
                transitions.append("Clause_Begin")
                transitions.extend(clause)
                transitions.append("Clause_End")
            else:
                transitions.extend(clause)

        for i in range(0, len(transitions)-1):

            # assemble transition pair string
            state1 = transitions[i]
            state2 = transitions[i+1]
            transition_string = state1 + '->' + state2

            if transition_string == 'Clause_End->Clause_Begin': # ignore clause_begin to end transition pairs
                continue

            transition_pairs[bookname][transition_string] += 1

        # create the dataframes
        df_trans = pd.DataFrame(transition_pairs).fillna(0)

        # normalize:
        df_mean = df_trans.sum().mean()
        df_norm = df_trans.apply(lambda col: col * df_mean / col.sum())

    return df_trans, df_norm

def make_stacked_transitions(data_dict):
    '''
    --input--
    output from bhsa.get_data()
    i.e. dict[feature][domain][book] = list(list(strings))

    --output--
    x2 df(trans. frequencies x book), df(trans. ratios x book)
    stacked for all features/domains by book
    '''

    freq_matrices = {}
    norm_matrices = {}

    for feature, domains in data_dict.items():
        for domain in domains:

            clause_ends = True if feature != 'clause_types' else False

            # add all data together
            data = data_dict[feature][domain]
            name = feature+'|'+domain
            trans_freq, trans_norm = make_transitions(data, clause_ends)

            # save to dicts
            freq_matrices[name] = trans_freq
            norm_matrices[name] = trans_norm

    stacked_freq = pd.DataFrame()
    stacked_norm = pd.DataFrame()

    # make the frequency stacked matrices
    for data_name, matrix in freq_matrices.items():
        stacked_freq = stacked_freq.append(matrix)

    # make the normalized stacked matrices
    for data_name, matrix in norm_matrices.items():
        stacked_norm = stacked_norm.append(matrix)

    return stacked_freq.fillna(0), stacked_norm.fillna(0)


import pandas as pd
import numpy as np
import spacy
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report, confusion_matrix
import pickle

#Replace dataset_path with the dataset you want to use
df = pd.read_csv(dataset_path)
queries = np.array(df['text'])
labels = np.array(df['intent'])

# Install trained pipeline with command 'python -m spacy download en_core_web_lg'
nlp = spacy.load('en_core_web_lg')

n_queries = len(queries)
dim_embedding = nlp.vocab.vectors_length
X = np.zeros((n_queries, dim_embedding))

for idx, sentence in enumerate(queries):
    doc = nlp(sentence)
    X[idx, :] = doc.vector
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.20, random_state=42)
neigh = KNeighborsClassifier(n_neighbors=1)
neigh.fit(X_train, y_train)

#Save the weights in neighpickle_file
neigh_pickle = open('neighpickle_file', 'wb')
pickle.dump(neigh, neigh_pickle)

print("Accuracy on Test Set: ", np.count_nonzero(neigh.predict(X_test) == y_test)/len(y_test))

y_true = labels
y_pred = []
for text in queries:
    #If you want to find out every wrong prediction, uncomment the two prints
    #print(text)
    doc = nlp(text)
    prediction = neigh.predict(doc.vector.reshape(1, -1))
    #print(prediction)
    y_pred.append(prediction)

print(classification_report(y_true, y_pred))
print(confusion_matrix(y_true, y_pred))


# %%
import matplotlib.pyplot as plt
import numpy as np
import torch
from tqdm import trange

from src.utils_exact_diagonalization import QuantumSpinSystem
from src.utils_sparse_diag import transverse_ising_sparse_simulator_sample

l = 16
j1 = -1
eps_breaking = 10 ** -3
data = np.load(
    "data/constant_field_ising_1nn_dmrg/test_unet_periodic_1nn_l_16_h_0.0_ndata_10.npz"
)

f_dmrg = data["F"]
z_dmrg = data["density"]
dens_f_dmrg = data["density_F"]
pot = data["potential"]
e_dmrg = data["energy"]
x_dmrg = data["magnetization_x"]

#%%

# %%
plt.plot(z_dmrg)
plt.plot(dens_f_dmrg)
plt.plot(pot)
plt.show()
# %%

for i in trange(10):

    (file_name, e, h, z, f_dens, f, x,) = transverse_ising_sparse_simulator_sample(
        l=16,
        h_max=2.71,
        hs=pot[i],
        j1=j1,
        j2=-1,
        pbc=True,
        file_name="nothing",
        check_2nn=False,
        eps_breaking=eps_breaking,
    )

    if i == 0:
        e_quspin = e
        hs = h
        z_quspin = z
        fs_dens_quspin = f_dens
        f_quspin = f
        x_quspin = x
    else:
        e_quspin = np.append(e_quspin, e)
        hs = np.append(hs, h, axis=0)
        z_quspin = np.append(z_quspin, z, axis=0)
        fs_dens_quspin = np.append(fs_dens_quspin, f_dens, axis=0)
        f_quspin = np.append(f_quspin, f)
        x_quspin = np.append(x_quspin, x, axis=0)

# %% exact diagonalization
# hs = pot
# for r in trange(10):
#     device = "cpu"
#     qs = QuantumSpinSystem(l=l, device=device)
#     # hamiltonian
#     hamiltonian = torch.zeros((2 ** l, 2 ** l), device=device)
#     for k in range(l):
#         hamiltonian = (
#             hamiltonian
#             + j1 * torch.matmul(qs.s_x[k], qs.s_x[(k + 1) % l])
#             + hs[r, k] * qs.s_z[k] + eps_breaking*qs.s_x[k]
#         )

#     e, psi = torch.linalg.eigh(hamiltonian)

#     m_z = []
#     m_x = []
#     for i in range(l):
#         m_z.append(
#             torch.einsum(
#                 "i,ij,j->", torch.conj(psi[:, 0]
#                                        ), qs.s_z[i].to(torch.float), psi[:, 0]
#             )
#             .detach()
#             .cpu()
#             .numpy()
#         )
#         m_x.append(
#             torch.einsum(
#                 "i,ij,j->", torch.conj(psi[:, 0]
#                                        ), qs.s_x[i].to(torch.float), psi[:, 0]
#             )
#             .detach()
#             .cpu()
#             .numpy()
#         )
#     m_z = np.asarray(m_z)
#     m_x = np.asarray(m_x)

#     t_xx = []
#     for i in range(l):
#         t_xx.append(
#             -1
#             * torch.einsum(
#                 "i,ij,jk,k->",
#                 torch.conj(psi[:, 0]),
#                 qs.s_x[i].to(torch.float),
#                 qs.s_x[(i + 1) % l].to(torch.float),
#                 psi[:, 0],
#             )
#             .detach()
#             .cpu()
#             .numpy()
#             # + torch.einsum(
#             #     "i,ij,jk,k->",
#             #     torch.conj(psi[:, 0]),
#             #     qs.s_z[i].to(torch.float),
#             #     qs.s_z[(i + 2) % l].to(torch.float),
#             #     psi[:, 0],
#             # )
#             # .detach()
#             # .cpu()
#             # .numpy()
#         )
#     t_xx = np.asarray(t_xx)

#     if r == 0:
#         t_xx_ed = t_xx.reshape(1, -1)
#         z_ed = m_z.reshape(1, -1)
#         x_ed = m_x.reshape(1, -1)
#     else:
#         t_xx_ed = np.append(t_xx_ed, t_xx.reshape(1, -1), axis=0)
#         z_ed = np.append(z_ed, m_z.reshape(1, -1), axis=0)
#         x_ed = np.append(x_ed, m_x.reshape(1, -1), axis=0)
# %%
for i in range(10):

    plt.plot(z_dmrg[i], label="dmrg", linestyle="--", color="green")
    # plt.plot(z_ed[i], label="ed", linestyle=":", color="blue")
    plt.plot(z_quspin[i], label="quspin", color="red")
    plt.legend()
    plt.show()
# %%
# for i in range(10):

#     plt.plot(dens_f_dmrg[i], label="dmrg", linestyle="--", color="green")
#     plt.plot(t_xx_ed[i], label="ed", linestyle=":", color="blue")
#     plt.plot(fs_dens_quspin[i], label="quspin", color="red")
#     plt.legend()
#     plt.show()
# %%
for i in range(10):

    plt.plot(np.abs(x_dmrg[i]), label="dmrg", linestyle="--", color="green")
    # plt.plot(x_ed[i], label="ed", linestyle=":", color="blue")
    plt.plot(np.abs(x_quspin[i]), label="quspin", color="red")
    plt.legend()
    plt.show()
# %% Phase transition in a costant field case

import matplotlib.pyplot as plt
import numpy as np
import torch
from tqdm import trange

from src.utils_exact_diagonalization import QuantumSpinSystem
from src.utils_sparse_diag import transverse_ising_sparse_simulator_sample

ls = [8, 16, 32, 64, 128]

for l in ls:
    j1 = -1
    eps_breaking = 10 ** -2
    data = np.load(
        f"data/constant_field_ising_1nn_dmrg/test_unet_periodic_1nn_l_{l}_h_0.0_ndata_10.npz"
    )

    f_dmrg = data["F"]
    z_dmrg = data["density"]
    dens_f_dmrg = data["density_F"]
    pot = data["potential"]
    e_dmrg = data["energy"]
    x_dmrg = data["magnetization_x"]

    mx = np.average(np.abs(x_dmrg), axis=-1)
    h = np.average(pot, axis=-1)

    plt.plot(h, mx, label=f"size={l}")
plt.legend(fontsize=10)
plt.show()
# %% with quspin
mx_quspin = np.average(x_quspin, axis=-1)
plt.plot(h, mx_quspin)
plt.show()

# %%


import os
import sys

current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.append(parent)

from argparse import ArgumentParser
from models.voice_encoder import VoiceEncoder
from models.face_decoder import FaceDecoder
import torch
from matplotlib import pyplot as plt
import librosa
import data_preprocessing.audio_spectrograms as audio_processing

parser = ArgumentParser("Use trained VoiceEncoder and FaceDecoder to generate face image out of audio file")

parser.add_argument("--audio-file-path", type=str, required=True,
                    help="Path to the audio file")

parser.add_argument("--voice-encoder-path", type=str, required=True,
                    help="Path to the saved trained model of voice encoder")

parser.add_argument("--face-decoder-path", type=str, required=True,
                    help="Path to the saved trained model of face decoder")

parser.add_argument("--gpu", type=int, default=0,
                    help="-1 for cpu prediction")

parser.add_argument("--audio-length", default=6, type=int,
                    help="length of the audio that will be converted to spectogram. Longer audio \
                          files will be clipped, and shorter files will be repeated")

parser.add_argument("--sampling-rate", default=16000, type=int,
                    help="The number of samples per second of audio")

parser.add_argument("--hop-length", default=10, type=int,
                    help="Period of time between adjacent STFT columns specified in milliseconds")

parser.add_argument("--window-length", default=25, type=int,
                    help="Length of the window of STFT columns ")

parser.add_argument("--n-fft", default=512, type=int,
                    help="Length of the windowed signal after padding with zeros")

parser.add_argument("--power", default=0.3, type=float,
                    help="power applied during power-law compression")

def get_device(choice):
    if choice >= 0:
        if torch.cuda.is_available():
            device = torch.device(f"cuda:{choice}")
        else:
            raise ValueError("GPU training was chosen but cuda is not available")
    else:
        device = torch.device("cpu")
    return device

def main():
    args = parser.parse_args()

    device = get_device(args.gpu)

    face_decoder = FaceDecoder().to(device)
    face_decoder.eval()
    face_decoder_checkpoint = torch.load(args.face_decoder_path)
    face_decoder.load_state_dict(face_decoder_checkpoint["model_state_dict"])

    voice_encoder = VoiceEncoder().to(device)
    voice_encoder.eval()
    voice_encoder_checkpoint = torch.load(args.voice_encoder_path)
    voice_encoder.load_state_dict(voice_encoder_checkpoint["model_state_dict"])

    root = os.path.dirname(args.audio_file_path)
    file_base, _ = os.path.splitext(os.path.basename(args.audio_file_path))
    normalized_file_path = audio_processing.normalize_audio(args.audio_file_path, root, file_base)
    waveform, _ = librosa.load(normalized_file_path, duration=args.audio_length, sr=args.sampling_rate, mono=True)
    waveform = audio_processing.stretch_audio(args, waveform)
    spectrogram = audio_processing.compute_spectrograms(args, waveform)
    spectrogram = audio_processing.power_law_compression(args, spectrogram)
    spectrogram = torch.tensor(spectrogram).unsqueeze(0).to(device)
    os.remove(normalized_file_path)

    with torch.no_grad():
        voice_encoder_embeddings = voice_encoder(spectrogram)
        landmarks_predicted, images_predicted = face_decoder(voice_encoder_embeddings)

    _, axes = plt.subplots(1, 1, figsize=(12, 8))
    temp_image = (images_predicted[0].cpu() * 255).to(torch.uint8)
    axes.imshow(temp_image.permute(1, 2, 0))
    axes.set_title("Reconstructed image")
    axes.axis("off")
    temp_image = landmarks_predicted[0].cpu().view(72, 2)
    x, y =zip(*temp_image.squeeze(0))
    axes.scatter(x, y, c='red', marker='o', s=2)
    plt.show()

if __name__ == "__main__":
    main()


import collections
import heapq
import functools
import itertools
import re
import sys
import math
import bisect
from typing import *

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
  def maxDepth(self, root: TreeNode) -> int:
    if root is None:
        return 0
    result = []
    def rec(tree, depth):
      if tree.left is None and tree.right is None:
        result.append(depth)
        return

      if tree.left:
        rec(tree.left, depth+1)
      if tree.right:
        rec(tree.right, depth+1)

    rec(root, 0)
    return max(result) + 1

  def book(self, root: TreeNode) -> int:
    if root is None:
      return 0

    queue = collections.deque([root])
    depth = 0

    while queue:
      depth += 1
      for _ in range(len(queue)):
        cur_root = queue.popleft()
        if cur_root.left:
          queue.append(cur_root.left)

        if cur_root.right:
          queue.append(cur_root.right)

    return depth

a = Solution()


from rtlsdr import RtlSdr
import numpy as np
import time
import scipy
import math
import matplotlib.pyplot as plt

#  zadejte prvni a posledni frekvenci pro definovani okna ktere ma byt zmereno, v MHz
f_start = input("Vloz startovni frekvenci [ MHz ] :")
print ("Fstart =", f_start)
f_stop = input("Vloz koncovou frekvenci [ MHz ] :")
print ("Fstop =", f_stop)
sirka_volba = raw_input("Vloz volbu pro rozliseni, RBW ( a = 244 Hz // b = 61 Hz // c = 15 Hz // d = 1 Hz):")
print ("volba =", sirka_volba)
log_volba = raw_input("Logaritmicka stupnice :  a = ano // n = ne   :")
print ("volba =", log_volba)
pozadi_volba = raw_input("Odecist sumove pozadi :  a = ano // n = ne   :")
print ("volba =", pozadi_volba)

if	sirka_volba is	'a' :
	pocet_vzorku = 8 * 512

if	sirka_volba is	'b' :
	pocet_vzorku = 32 * 512

if	sirka_volba ==	'c' :
	pocet_vzorku = 128 * 512

if	sirka_volba ==	'd' :
	pocet_vzorku = 1024 * 1024

sdr = RtlSdr()
pocet_oken = f_stop-f_start
f_start = f_start * 1e6
f_stop = f_stop * 1e6
sdr.sample_rate = 1.2e6  # Hz
sdr.freq_correction = +30   # korekce ochylky hodin, v PPM
sdr.gain = 12

sdr.center_freq = f_start + 0.5e6    # Hz
x = np.linspace(f_start, f_stop , pocet_oken *(int(round(pocet_vzorku*(1/1.2))))) # definice velikosti pole pro vyslednou FFT - jen pro indexy

data = sdr.read_samples(pocet_vzorku) # testovaci aktivace prijimace, prvni vzorky nejsou kvalitni
provede_mereni = 1
pozadi_temp = 0
if	pozadi_volba ==	'a' :
	pozadi_temp = 1
	raw_input("Probehne mereni pozadi, pro pokracovani stiskni ENTER")

while provede_mereni==1 :  # test zda-li se provede dvakrat pro kontrolu pozadi
	fft = np.linspace(0,0,  pocet_oken *(int(round(pocet_vzorku*(1/1.2))))) # definice velikosti pole pro vyslednou FFT - zde se zapisuje
	for aktualni_okno in range(1, pocet_oken+1):
		print('Merim')
		time.sleep(0.08) # bezpecnostni prodleva pro preladeni a ustaleni
		data = sdr.read_samples(pocet_vzorku)
		sdr.center_freq = sdr.center_freq + 1e6;
		data = abs(scipy.fft(data)) # provede se FFT

		for index in range(-1,1): # vymaze se pripadna velika stejnosmerna hodnota
	        	data[index] = 0

		data = np.roll(data, pocet_vzorku/2) # vycentruje se

		for index in range(0, int(round(pocet_vzorku*(1/1.2)))): # sklada obraz do jednoho velkeho po 1 MHz oknech, ovsem navzorkovanych je 1.2 MHz, okraje 100kHz se zahodi
		        fft[index+(int(round(pocet_vzorku*(1/1.2)))*(aktualni_okno - 1))] = data[index+int(round(pocet_vzorku*(0.1/1.2)))]
		provede_mereni = 0

	if 	pozadi_temp == 1 :      # pozadi_temp je "1" pri prvnim kole mereni pozadi, pri mereni uzitecneho signalu je "0"
		pozadi_data = fft     # zaloha pozadi
		provede_mereni = 1
		pozadi_temp = 0
		raw_input("Probehne mereni s pritomnosti uzitecneho signalu, pro pokracovani stiskni ENTER")
		for index in range(0, pocet_oken *(int(round(pocet_vzorku*(1/1.2))))):
			fft[index] = 0

max_hodnota = 0
for index in range(0, pocet_oken *(int(round(pocet_vzorku*(1/1.2))))): # proscanuje indexy vysledneho FFT okna
	if fft[index] > max_hodnota:
		max_hodnota = fft[index]
		index_max_hodnoty = index
	if	log_volba is	'a' :
		if	fft[index] < 1 :
			fft[index]= 1
		fft[index]=20*math.log10(fft[index])
	if	pozadi_volba ==	'a' :
		fft[index] = fft[index] - pozadi_data[index]

plt.close('all')
f, ax = plt.subplots()
ax.plot(x,fft )
ax.set_title('FFT')
ax.set_ylabel('Amplituda [-]')
if	log_volba is	'a' :
	ax.set_ylabel('Amplituda [dB]')
ax.set_xlabel('Frekvence [ MHz ]')

print('*********')
print('Start [ MHz ]:')
print(f_start/1e6)
print('---------')
print('Stop  [ MHz ]:')
print(f_stop/1e6)
print('---------')
print('Sirka pasma  [ MHz ]:')
print((f_stop - f_start )/1e6)
print('---------')
print('Pocet oken  [ - ]:')
print(pocet_oken)
print('---------')
print('Rozliseni, RBW :')
print(1e6/pocet_vzorku)
print('---------')
print('Dominantni frekvence:')
print(x[index_max_hodnoty])
print('*********')
plt.show()


import numpy as np
import matplotlib.pyplot as plt
import random

class GridWorld:
    ACTIONS = [(1, 0), (0, 1), (-1, 0), (0, -1)]

    def __init__(self, height, width, starting_state, terminal_state):
        self.height = height
        self.width = width
        self.starting_state = starting_state
        self.grid = np.zeros((height, width))
        self._current_location = starting_state
        self.terminal_state = terminal_state
        self.terminated = False

    def action(self, a):
        new_location = tuple(np.add(self.current_location, a))

        if new_location[0] >= self.height or new_location[1] >= self.width or np.any(np.array(new_location) < 0):
            return -1  # throws index error if outside grid

        self._current_location = new_location
        if tuple(self.current_location) == self.terminal_state:
            self.terminated = True
            return 0
        return -1

    def reset(self):
        self._current_location = self.starting_state
        self.terminated = False

    @property
    def current_location(self):
        return tuple(self._current_location)

class Agent:

    def __init__(self, epsilon, alpha, gamma, env: GridWorld):
        self.Qs = {}
        self.epsilon = epsilon
        self.env = env
        self.alpha = alpha
        self.gamma = gamma

        inds = [(i, j) for i in range(env.height) for j in range(env.width)]
        for pos in (inds):
            self.Qs[pos] = {}
            for a in env.ACTIONS:
                self.Qs[pos][a] = 0  # initialize all Qs to 0

    def act(self):
        if np.random.uniform(0, 1) < self.epsilon:
            return random.choice(self.env.ACTIONS)
        else:
            return max(self.Qs[env.current_location], key=self.Qs[env.current_location].get)

    def update_qs(self, old_state, reward, new_state, a):
        self.Qs[old_state][a] = (1 - self.alpha) * self.Qs[old_state][a] \
                                + self.alpha * (reward + self.gamma * max(self.Qs[new_state].values()))

env = GridWorld(height=5, width=5, starting_state=(1, 1), terminal_state=(4, 4))

agent = Agent(env=env, alpha=0.1, gamma=1.0, epsilon=0.1)
reward_per_episode = []
for trial in range(500):  # Run trials
    cumulative_reward = 0  # Initialise values of each game
    env.reset()  # re-init environment
    while not env.terminated:  # Run until max steps or until game is finished
        old_state = env.current_location
        a = agent.act()
        reward = env.action(a)
        assert type(a) == tuple
        new_state = env.current_location
        assert new_state in agent.Qs.keys()
        agent.update_qs(old_state, reward, new_state, a)
        cumulative_reward += reward
    reward_per_episode.append(cumulative_reward)  # Append reward for current trial to performance log
plt.plot(reward_per_episode)
plt.show()


# Python program to find current
# weather details of any city
# using openweathermap api

# import required modules
import requests, json

# Enter your API key here
api_key = "Your_API_Key"

# base_url variable to store url
base_url = "http://api.openweathermap.org/data/2.5/weather?"

# Give city name
city_name = input("Enter city name : ")

# complete_url variable to store
# complete url address
complete_url = base_url + "appid=" + api_key + "&q=" + city_name

# get method of requests module
# return response object
response = requests.get(complete_url)

# json method of response object
# convert json format data into
# python format data
x = response.json()

# Now x contains list of nested dictionaries
# Check the value of "cod" key is equal to
# "404", means city is found otherwise,
# city is not found
if x["cod"] != "404":

	# store the value of "main"
	# key in variable y
	y = x["main"]

	# store the value corresponding
	# to the "temp" key of y
	current_temperature = y["temp"]

	# store the value corresponding
	# to the "pressure" key of y
	current_pressure = y["pressure"]

	# store the value corresponding
	# to the "humidity" key of y
	current_humidiy = y["humidity"]

	# store the value of "weather"
	# key in variable z
	z = x["weather"]

	# store the value corresponding
	# to the "description" key at
	# the 0th index of z
	weather_description = z[0]["description"]

	# print following values
	print(" Temperature (in kelvin unit) = " +
					str(current_temperature) +
		"\n atmospheric pressure (in hPa unit) = " +
					str(current_pressure) +
		"\n humidity (in percentage) = " +
					str(current_humidiy) +
		"\n description = " +
					str(weather_description))

else:
	print(" City Not Found ")

Find current weather of any city using openweathermap API.py


# -*- coding:utf-8 -*-
from datetime import timedelta
from celery import Celery
from celery.schedules import crontab
from flask import current_app

# object
class Config:
    BROKER_URL = "redis://localhost:6379/1"
    CELERY_RESULT_BACKEND = "redis://localhost:6379/1"
    CELERY_ENABLE_UTC = False
    CELERY_ACCEPT_CONTENT = ["pickle", "json", "msgpack", "yaml"]

    CELERYBEAT_SCHEDULE = {

        "interrupt_timer": {
            "task": "imhm.utils.async.functions.interrupt_timer",
            "schedule": timedelta(seconds=60)
        },

        "warning_processor": {
            "task": "imhm.utils.async.functions.warning_processor",
            "schedule": timedelta(seconds=15)
        }
    }

celery_app = Celery(current_app, include=["functions"])
celery_app.config_from_object(Config)


import ephem
import datetime
"""
m = ephem.Mars('2016')
print(ephem.constellation(m))

m = ephem.Mars('2016/7/20')
#print('%s %s %.10f' % (m.name, m.elong, m.size))

print('%s %s %.10f' % (m.ra, m.dec, m.size))
"""

#Function to define date range to iterate over
def daterange( start_date, end_date ):
    if start_date <= end_date:
        for n in range( ( end_date - start_date ).days + 1 ):
            yield start_date + datetime.timedelta( n )
    else:
        for n in range( ( start_date - end_date ).days + 1 ):
            yield start_date - datetime.timedelta( n )

start = datetime.date( year = 2017, month = 1, day = 1 )
end = datetime.date( year = 2017, month = 12, day = 31 )

#Generate RA and Dec for Sun over date range
for date in daterange( start, end ):
    m = ephem.Sun(date)
    print ('{} {} {}'.format(date, m.ra, m.dec))

#Export to text file


from flask import Flask
from flask_compress import Compress
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SESSION_COOKIE_SECURE'] = True
app.config['SESSION_COOKIE_HTTPONLY'] = True
app.config['SESSION_COOKIE_SAMESITE'] = 'LAX'
Compress(app)

app.game_modes = []

for mode in app.config['GAME_MODES']:
    if mode == 'pictures':
        display_name = 'Pictures'
    elif mode.startswith('classic_'):
        lang = mode.split('classic_', 1)[1]
        display_name = f'Classic ({lang})'
    else:
        continue
    app.game_modes.append((mode, display_name))

socketio = SocketIO(app)
db = SQLAlchemy(app)

from . import models, routes, helper, websocket

#: create database if not exists
db.create_all()

if __name__ == '__main__':
    #: start flask
    app.run()

    #: start websocket
    socketio.run(app)


import numpy as np
import cv2,cozmo,time,PIL
import cv2.aruco as aruco

def myProgram(robot,dict_name=aruco.DICT_5X5_100):
  adict = aruco.Dictionary_get(dict_name)
  params = aruco.DetectorParameters_create()

  robot.camera.image_stream_enabled = True

  #wait until images have started
  while(True):
    if(robot.world.latest_image is not None):
      break
    else:
      time.sleep(0.2)

  #continuously look for aruco tags
  while(True):
    cozmoim = robot.world.latest_image.raw_image
    cozmoim = cozmoim.resize((cozmoim.width*2,cozmoim.height*2))
    curim = np.array(cozmoim).astype(np.uint8)
    gray = cv2.cvtColor(curim,cv2.COLOR_BGR2GRAY)
    (corners,ids,rejected) = aruco.detectMarkers(gray,adict,parameters=params)

    annotated_im = aruco.drawDetectedMarkers(curim,corners,ids)

    cv2.imshow('frame',annotated_im)
    if(cv2.waitKey(1) & 0xFF == ord('q')):
      break

cozmo.robot.Robot.drive_off_charger_on_connect = False
cozmo.run_program(myProgram)
cv2.destroyAllWindows()


from pathlib import Path
import unittest

import core

class Test(unittest.TestCase):
  def test_one(self):
    # to-do: specify a temporary data folder
    dir_path = core.ensure_data_folder()

    print(f'The data folder:{dir_path}')
    self.assertTrue(dir_path.exists())

    # Get Data base...
    db = core.DataBase(str(dir_path))
    self.assertTrue(Path(db.path).exists())

    # Save quote...
    q = {
      "author": 'author 1',
      "content": 'text',
      "year": 100
    } # the quote
    res = db.quotes.save(q)

    # Retrive quote...
    res = db.quotes.get({'author': q['author']})

    # Check if saved...
    self.assertEqual(res[0].content, q['content'])

    # Delete all quotes...
    res = db.quotes.delete()
    self.assertEqual(res['count'], 1)

    res = db.quotes.get()
    self.assertEqual(len(res), 0)

if __name__ == '__main__':
  unittest.main()

RIRIN (by Yhoxin Rossell and Hernán Guerrero)/src/test.py


import os
import threading
from typing import Callable
import io

import datetime
import service.serial.manager
import service.sensor.camera
from service.sensor_manager import Sensor, SensorType

def _get_index(str_in: str, find: str):
    out = -1
    try:
        out = str_in.index(find)
    except:
        pass
    return out

def _recursive_unwrapper(data):
    out = {}
    merging = {}
    for element in data:
        element = element  # type: str
        array_start = _get_index(element, "[")
        object_start = _get_index(element, ".")
        if array_start != -1 or object_start != -1:
            if array_start != -1 and object_start != -1:
                pass
            elif array_start != -1:
                first_part = element[0:array_start]
                second_part = element[array_start + 1:]
                second_part = second_part[:second_part.index("]")]
                if first_part not in merging:
                    merging[first_part] = []
                merging[first_part].insert(int(second_part), data[element])
            elif object_start != -1:
                first_part = element[0:object_start]
                second_part = element[object_start + 1:]
                if first_part not in merging:
                    merging[first_part] = []
                merging[first_part][second_part] = data[element]
        else:
            out[element] = data[element]

    for element in merging:
        out[element] = merging[element]
    return out

def _generic_callback_handler(data,
                              connection: service.serial.manager.SerialConnection,
                              callback_options):
    data["data"] = _recursive_unwrapper(data["data"])
    callback_options["callback"](data, connection, callback_options["options"])

def _sync_callback(data, connection: service.serial.manager.SerialConnection,
                   callback_options):
    callback_options["results"] = data
    # Will make the object available again.
    callback_options["lock"].release()
    callback_options["done"] = True

class AbstractCommunicator:
    def get_help(self, sensor: Sensor, callback: Callable, callback_options):
        command = "help"
        options = ""
        callback_options_wrapper = {"options": callback_options,
                                    "callback": callback}
        sensor.connection.send_command(command, options,
                                       _generic_callback_handler,
                                       callback_options_wrapper)

    def get_sensor_values(self, sensor: Sensor, callback: Callable, options):
        raise NotImplemented()

    def synchronous_call(self, function: Callable, sensor: Sensor, options):
        _lock = threading.Lock()  # type: threading.Lock

        callback_options = {
            "options": options,
            "lock": _lock,
            "results": None,
            "done": False
        }
        # Will lock the request.
        _lock.acquire()
        function(sensor, _sync_callback, callback_options)

        # Will lock the request. But that can only be done, after the previous
        # one is unlocked, which happens when the response comes back :)
        _lock.acquire()

        # Lets be nice and just release it.
        _lock.relase()
        return callback_options["results"]

class AbstractArduinoCommunicator(AbstractCommunicator):
    def get_sensor_values(self, sensor: Sensor, callback: Callable,
                          callback_options):
        command = self.get_command()
        options = self.get_options()
        callback_options_wrapper = {"options": callback_options,
                                    "callback": callback}
        sensor.connection.send_command(command, options,
                                       _generic_callback_handler,
                                       callback_options_wrapper)

    def get_command(self) -> str:
        return ""

    def get_options(self) -> str:
        return ""

class ExampleCommunicator(AbstractArduinoCommunicator):
    def get_command(self) -> str:
        return "getCurrentCount"

class HumidityTemperatureSensorCommunicator(AbstractArduinoCommunicator):
    def get_command(self) -> str:
        return "getCurrentCount"

class CO2SensorCommunicator(AbstractArduinoCommunicator):
    def get_command(self) -> str:
        return "getValue"

class HeartRateSensorCommunicator(AbstractArduinoCommunicator):
    def get_command(self) -> str:
        return "getCurrentCount"

class PiCamCommunicator(AbstractCommunicator):
    def get_sensor_values(self, sensor: Sensor, callback: Callable,
                          callback_options):
        recording = callback_options["recording"]  # type: Recording
        if not os.path.exists(recording.path):
            os.mkdir(recording.path)
        photo_folder = os.path.join(recording.path, "PI_CAMERA")
        if not os.path.exists(photo_folder):
            os.mkdir(photo_folder)
        now = datetime.datetime.now()
        photo_path = os.path.join(photo_folder,
                                  now.strftime("%y.%m.%d@%H.%M.%S.%f.jpg"))
        service.sensor.camera.camera.capture(photo_path)

        callback({
            "location": photo_path,
            "date": now.strftime("%y-%m-%d"),
            "time": now.strftime("%H-%M-%S")
        }, None, callback_options)

class GSRSensorCommunicator(AbstractArduinoCommunicator):
    def get_command(self) -> str:
        return "getCurrentCount"

def get_communicator_instance(sensor: Sensor) -> AbstractArduinoCommunicator:
    if sensor.sensor_type == SensorType.EXAMPLE_SENSOR:
        return ExampleCommunicator()
    elif sensor.sensor_type == SensorType.PI_CAMERA:
        return PiCamCommunicator()
    elif sensor.sensor_type == SensorType.HUMIDITY_TEMPERATURE_SENSOR:
        return HumidityTemperatureSensorCommunicator()
    elif sensor.sensor_type == SensorType.CO2_SENSOR:
        return CO2SensorCommunicator()
    elif sensor.sensor_type == SensorType.HEART_RATE_SENSOR:
        return HeartRateSensorCommunicator()
    elif sensor.sensor_type == SensorType.GALVANIC_SKIN_RESPONSE_SENSOR:
        return GSRSensorCommunicator()
    raise Exception("Unkown sensor")


from collections import Counter

def st_print(a):
	dic  = dict(Counter(a))
	keys = []
	values = []
	for key,value in dic.items():
		keys.append(key)
		values.append(value)

	m = len(values)-1
	while( m >= 0):
		for n in range(m):
			if(values[n] < values[n+1]):
				temp_va = values[n+1]
				values[n+1] = values[n]
				values[n] = temp_va
				temp_key = keys[n+1]
				keys[n+1] = keys[n]
				keys[n] = temp_key
			if(values[n] == values[n+1] and keys[n] > keys[n+1]):
				temp_key = keys[n+1]
				keys[n+1] = keys[n]
				keys[n] = temp_key
		m -=1
	string = ''
	for i in range(len(keys)):
		while(values[i] > 0):
			if(i != len(keys)-1 or values[i] != 1):
				string += str(keys[i])+' '
				values[i]-=1
			else:
				string += str(keys[i])+' '
				values[i]-=1
	print(string)
	return string

T = int(input())
x = 0
N,Arr = [],[]
while(x < T):
    N.append(int(input()))
    Arr.append([int(i) for i in input().split()])
    x+=1
result = []
for item in Arr :
    result.append(st_print(item))


from art import logo
print(logo)
letters = [
    'a','b','c','d','e','f','g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v','w','x','y','z'
    ]

def encode(word, shift):
    shifted_letters = []
    encoded_word = ''
    # creating our shifted letters from the default letters
    for x in range(shift,len(letters)):
        shifted_letters.append(letters[x])
    # adding the shifted letters to the back of our already shifted letters
    # so that it will also be 26 alphabetical letters
    for x in range(shift):
        shifted_letters.append(letters[x])
    # getting each letter in the inserted text by user
    for letter in word:
        # if an alphabet, then encode it by:
        if letter.isalpha():
            # tracing the position of the letter in the default letters
            position = letters.index(letter)
            # and using it to trace the same index in the shifted_letters
            encoded_word += shifted_letters[position]
        # if a number/space/symbol don't do anything, add it to the encoded text before moving to the next.
        else:
            encoded_word += letter
    # returning both the encoded word and the derived shifted_letters
    # why are we returing shifted_letters?
    # because our decode function will use it and not to be repeating ourself below:
    return encoded_word, shifted_letters

def decode(word,shift):
    decoded_word = ""
    # wow, this is where we made use of encode
    shifted_letters = encode(word, shift)[1]
    for letter in word:
        if letter == " ":
            decoded_word += letter
        elif letter.isdigit():
            decoded_word += letter
        elif letter.isalpha():
            positon = shifted_letters.index(letter)
            decoded_word += letters[positon]
        else:
            decoded_word += letter
    return decoded_word

start = input("Press any key to continue!!!\n")
# validating our start statement
while len(start) >= 0 :
    if len(start) == 0:
        print("OOPS, empty text is not allowed!!!")
        start = input("Press any key to continue!!!\n")
    # if the text is a string break the loop and continue the program
    elif start.isalpha():
        print("We are about to start now, gather all your text together...")
        break
    else:
        print("You are only meant to insert only alphabet keys not symbols\\numbers")
        start = input("Press any key to continue!!!\n")
# while start is a true statement
while start:
    # checking if user inserted start value as stop,no,end.
    if start=="stop" or start=="end" or start=="no":
        print("Thanks for making use of our program, will like to see you again!!!")
        break

    text = input("insert your text here...\n").lower()
    shift_num = int(input("What is your shift number\n"))
    coding = input("Do you want to encode or decode?\n (e\\d)").lower()
    # calling on encode function,if coding value is encode
    if coding=="encode" or coding=="e":
        print(encode(text,shift_num)[0])
    # if the user want to decode
    else:
        print(decode(text,shift_num))
    start = input("Press any key to continue!!!\n")


import math
import numpy as np
from statsmodels.tsa.stattools import adfuller

def calculate_entropy(data, normalized=False):
    frequency = np.bincount(data)
    n = 0
    entropy = 0

    for i, x in enumerate(frequency):
        px = x / len(data)
        if px > 0:
            n += 1
            entropy += -px * math.log2(px)

    if normalized:
        if math.log2(n) > 0:
            normalized_ent = entropy / math.log2(n)
            return entropy, normalized_ent
    else:
        return entropy

def calculate_entropy_gain(entropy, constant, sum_entropy):
    entropy_gain = entropy - (constant * sum_entropy)
    return entropy_gain

def calculate_normalized_entropy_gain(entropy_gain, num_parameters):
    normalized_entropy_gain = entropy_gain / num_parameters
    return normalized_entropy_gain

def calculate_degree_of_ddos(entropy_gains, num_parameters):
    sum_normalized_entropy_gains = sum(entropy_gains)
    degree_of_ddos = sum_normalized_entropy_gains / num_parameters
    return degree_of_ddos

def detect_ddos_attack(data, significance_level=0.05):
    parameters = ['packet_count_per_second', 'byte_count_per_second', 'flow_duration_sec']
    entropy_gains = []
    num_parameters = len(parameters)

    for parameter in parameters:
        entropy = calculate_entropy(data[parameter])
        entropy_gain = calculate_entropy_gain(entropy, 0.1, sum(entropy_gains))
        entropy_gains.append(entropy_gain)

    normalized_entropy_gains = [calculate_normalized_entropy_gain(eg, num_parameters) for eg in entropy_gains]
    degree_of_ddos = calculate_degree_of_ddos(normalized_entropy_gains, num_parameters)

    if degree_of_ddos > 0.5:
        # Perform augmented Dickey-Fuller test
        adf_result = adfuller(data['packet_count'], regression='nc')

        if adf_result[1] < significance_level:
            return True

    return False

# Example usage
import pandas as pd

# Load dataset
dataset = pd.read_csv('FlowStatsfile.csv')

# Convert timestamp column to datetime if needed
dataset['timestamp'] = pd.to_datetime(dataset['timestamp'])

# Remove unnecessary columns if needed
dataset = dataset[['packet_count_per_second', 'byte_count_per_second', 'flow_duration_sec']]

is_ddos_attack = detect_ddos_attack(dataset)
if is_ddos_attack:
    print("DDoS attack detected!")
else:
    print("No DDoS attack detected.")


'''
Approach
    - 한번에 최대 2명
    - 최대한 적게 사용하여 모든 사람을 구출
    - 1<=n<=5만, 40<=w<=240, 40<=limit<=240

>>> 그리디
    : w가 크거나 작은 순서대로 집어넣어본다
      -> fail
>>> limit을 만족하는 사람을 태운다
    : p를 꺼내고, (limit-p)-다른사람, 이 0에 가장 가까운 사람을 태운다

'''
from collections import deque
def solution(people, limit):
    answer = 0
    people.sort(reverse=True)
    dq = deque(people)
    while dq:
        fst = dq.popleft()
        if not dq:
            answer +=1
            print(fst)
            break
        scd = dq.pop()

        if fst + scd <= limit:
            print(fst,scd)
            answer +=1
        else:
            print(fst)
            answer +=1
            dq.append(scd)

    return answer

프로그래머스/lv2/42885. 구명보트/구명보트.py


#a executer depuis le repertoire ou se trouve le script (exercice_BOW_Camille)

from glob import glob
import os
import random
# from scripts.Evaluation import Evaluation
from PredictBOW_cam_V3 import *
#from Evaluation import Evaluation
import spacy
predicted = []
expected = []

nlp=spacy.load('en_core_web_sm')
# from Predict import Predict

import pandas as pd
import numpy as np
from nltk.tokenize import word_tokenize
from nltk import pos_tag
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.preprocessing import LabelEncoder
from collections import defaultdict
from nltk.corpus import wordnet as wn
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import model_selection, naive_bayes, svm
from sklearn.metrics import accuracy_score, classification_report

def pipeline(fic):
    corpus=pd.read_csv(fic,sep='\t')
    corpus['text']=[elem.lower() for elem in corpus['text']]
    return corpus
    #print(corpus.head())
    #Train_X, Test_X, Train_Y, Test_Y = model_selection.train_test_split(corpus['text'],corpus['label'],test_size=0.2)
    #Encoder = LabelEncoder()
    #Train_Y = Encoder.fit_transform(Train_Y)

    #Test_Y = Encoder.fit_transform(Test_Y)
    #print(Train_Y)
    #print(Test_Y)

def files2csv(text,out,label):

   texte_clean=re.sub(r'(<[^>]*>)|\(|\)|\n|\t',' ',text)
   with open(out, 'a') as file:
       file.write(texte_clean+"\t"+label+"\n")

def getFile(fic,pol):
    x = 0
    for f in glob(fic+'/*') :
        x += 1
        if x >= 2000 :
            os.system(f'mv {f} /home/schaub/Téléchargements/aclImdb_v1/aclImdb/test/{pol}/')

        if x == 8000 :
            break

def getcontentlabel(file) :

    expect = ''
    if 'pos/' in file :
        expect = 'pos'
    else :
        expect = 'neg'

    return open(file).read(),expect

def prediction(file,expect) :

    pred = Predict(file, pw, nw, nlp)
    pred.predict()
    predicted.append(pred.predicted)
    expected.append(expect)

if __name__ == '__main__':

    #with open("./csv_test.csv", 'w') as file:
        #file.write("text\tlabel\n")

    #for fic in random.sample(glob('../../../imdb_test/*/*.txt'),len(glob('../../../imdb_test/*/*.txt'))) :
        #text,label=getcontentlabel(fic)
        #files2csv(text,"./csv_test.csv",label)

    corpus=CorpusCSV(pipeline("./csv_test.csv"))
    print(corpus.voc)
    corpus.getBOW()
    print(corpus.bow)
    print(corpus.bigram)
    print(corpus.trigram)
    corpus.getTFIDF_voc()
    print(corpus.tfidf_voc)
    corpus.getTFIDF_bigram()
    print(corpus.tfidf_bigram)
    corpus.getTFIDF_trigram()
    print(corpus.tfidf_trigram)
    print("ca marche ! bravo")


import requests
r =requests.get('https://api.mcsrvstat.us/2/216.49.241.192')
import json
from random import randint
# parse x:
y = r.json()
#return('The server is up! \nPlayers online: '+str(test.r.json()['players']['list']))

# the result is a Python dictionary:
print(y["online"])
print(r.text)
#return('The server is up! \nPlayers online: '+str(test.r.json()['players']['list']))
def respond():
  global r
  r =requests.get('https://api.mcsrvstat.us/2/216.49.241.192')
  response = ('The server is up! \n')
  '''if r.json()['players']['online']==0:
    response.join('No one is online.')
  else:
    response = response+'Players online: '
    for i in range(0,r.json()['players']['online']):
      response = response+r.json()['players']['list'][i]+'
  '''
  print(response)
  return(response)

print(respond())


# -*- coding: utf-8 -*-
"""
Created on Fri Sep 21 14:26:55 2018

@author: shen1994
"""

from keras.models import Model
from keras.layers import Input
from keras.layers import Lambda
from keras.layers.merge import Concatenate

from blocks import vgg_block
from blocks import stage1_block
from blocks import stageT_block
from blocks import mask_block

def train_pose_model(input_shape=(368, 368, 3), stride=8, stages=6, weight_decay=None):

    image_input = Input(shape=input_shape, name='train_pose_input')
    vect_input = Input(shape=(input_shape[0]//stride, input_shape[1]//stride, 38))
    heat_input = Input(shape=(input_shape[0]//stride, input_shape[1]//stride, 19))

    image_norm = Lambda(lambda x: x / 256. - 0.5)(image_input)

    outputs = []

    # vgg
    stage0_out = vgg_block(image_norm, weight_decay)

    # stage 1 - branch 1 (PAFs)
    stage1_branch1_out = stage1_block(stage0_out, 38, 1, weight_decay)
    w1 = mask_block(stage1_branch1_out, vect_input, heat_input, 38, 1, 1)

    # stage 1 - branch 2 (configdence maps)
    stage1_branch2_out = stage1_block(stage0_out, 19, 2, weight_decay)
    w2 = mask_block(stage1_branch2_out, vect_input, heat_input, 19, 1, 2)

    outputs.append(w1)
    outputs.append(w2)

    x = Concatenate()([stage1_branch1_out, stage1_branch2_out, stage0_out])

    for sn in range(2, stages + 1):
        # stage SN - branch 1 (PAFs)
        stageT_branch1_out = stageT_block(x, 38, sn, 1, weight_decay)
        w1 = mask_block(stageT_branch1_out, vect_input, heat_input, 38, sn, 1)

        # stage SN - branch 2 (confidence maps)
        stageT_branch2_out = stageT_block(x, 19, sn, 2, weight_decay)
        w2 = mask_block(stageT_branch2_out, vect_input, heat_input, 19, sn, 2)

        outputs.append(w1)
        outputs.append(w2)

        if (sn < stages):
            x = Concatenate()([stageT_branch1_out, stageT_branch2_out, stage0_out])

    return Model(inputs=[image_input, vect_input, heat_input], outputs=outputs)

def pose_model(input_shape=(368, 368, 3), stages=6):

    image_input = Input(shape=input_shape, name='pose_input')

    image_morm = Lambda(lambda x: x / 256. - 0.5)(image_input)

    # VGG
    stage0_out = vgg_block(image_morm, None)

    # stage 1 - branch 1 (PAFs)
    stage1_branch1_out = stage1_block(stage0_out, 38, 1, None)

    # stage 1 - branch 2 (confidence maps)
    stage1_branch2_out = stage1_block(stage0_out, 19, 2, None)

    x = Concatenate()([stage1_branch1_out, stage1_branch2_out, stage0_out])

    # stage t >= 2
    for sn in range(2, stages + 1):
        stageT_branch1_out = stageT_block(x, 38, sn, 1, None)
        stageT_branch2_out = stageT_block(x, 19, sn, 2, None)

        if (sn < stages):
            x = Concatenate()([stageT_branch1_out, stageT_branch2_out, stage0_out])

    return Model(inputs=[image_input], outputs=[stageT_branch1_out, stageT_branch2_out])


#coding=utf-8
import os,re,xlrd,xlwt
os.chdir("C:\\Users\\quiet_wang\\Desktop\\python")
p = re.compile('.*本科.*')
f = xlrd.open_workbook('20181021105223_34042.xls')
sheet1 = f.sheet_by_index(1)
ncols = sheet1.ncols
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = "Times New Roman"
font.height = 220
font.bold = False
style.font = font
aln = xlwt.Alignment()
aln.horz = 0
aln.shri = 0
aln.vert = 0
style.alignment = aln
bd = xlwt.Borders()
bd
i=0
row_num=[]
for r in sheet1.col_values(13):
    if p.search(r) is not None:
        #print(r)
        row_num.append(i)
    i=i+1
fw=xlwt.Workbook(encoding='utf-8')
sheet2=fw.add_sheet('sheet2', cell_overwrite_ok=True)
for m in range(0,2):
    print(m)
    for n in range(0,ncols):
        sheet2.write(m, n, label=sheet1.cell_value(m, n), style=style)
for m in range(2, len(row_num)+2):
    k=row_num[m-2]
    for n in range(0, ncols):
        sheet2.write(m, n, label=sheet1.cell_value(k, n), style=style)
fw.save("t2.xls")


from keras.models import load_model
from keras.datasets import mnist
import matplotlib

import matplotlib.pyplot as plt
from splice import splice_image
import numpy
tf.logging.set_verbosity(tf.logging.ERROR)

model = load_model('digits.h5')
import cv2
#odel.summary()

def prepare(img):
	img_size = 28
	#img_arr = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
	new_arr = cv2.resize(img, (img_size, img_size)) #resize for CNN
	new_arr = numpy.invert(new_arr) #mnist dataset has data that is inverted so we must invert our input
	#plt.imshow(new_arr)
	#plt.show()
	return new_arr.reshape(-1, img_size, img_size, 1)

'''
(X_train, y_train), (X_test, y_test) = mnist.load_data()
#plt.imshow(X_train[1], cmap="gray")
#plt.show()
img = X_train[1]
img = img.reshape(-1, 28, 28, 1)
'''

def blankSpot(blank):

	s = set()
	for i in range(10):
		for j in range(10):
			#for k in range(2):
			s.add(blank[i + 10][j + 10])
	if len(s) == 1:
		return True
	else:
		return False

def CNN_predict_single(image):
	if blankSpot(image) == True:
		return int(0)
	else:
		prediction = model.predict_classes(prepare(image))
		return(prediction[0])
'''
def CNN_predict_single(image):
	print(blankSpot(image))
	prediction = model.predict_classes(prepare(image))
	return(prediction[0])
'''
def CNN_predict_grid(filepath):
	image_grid = cv2.imread(filepath,cv2.IMREAD_GRAYSCALE)
	imgArr = splice_image(image_grid)
	grid = []
	for i in range(81):
		grid.append(CNN_predict_single(imgArr[i]))
	return grid
def hello():
    return 'Hi'


from multiprocessing import Pool
from datetime import datetime
from itertools import chain
from utils.cache import LMDBClient
from utils import string_utils
from utils import data_utils

def transform_feature(data, f_name, k=1):#变换特征 输入数据， 特征名
    if type(data) is str:
        data = data.split() #按空白字符分词
    assert type(data) is list #data 是一个 str列表
    features = [] #列表
    for d in data: #枚举d
        features.append("__%s__%s" % (f_name.upper(), d)) #（特征名的大写， 单词） 中间的%代表格式化操作 __$f_name.upper()$__$d$
    return features #返回的是字符串列表， 每一项是 __$f_name的大写$__$特征单词$ 的形式

def extract_common_features(item): #提取共同特征
    title_features = transform_feature(string_utils.clean_sentence(item["title"], stemming=True).lower(), "title") #将title项提取特征
    keywords_features = []
    keywords = item.get("keywords") #提取 keywords 项
    if keywords:
        keywords_features = transform_feature([string_utils.clean_name(k) for k in keywords], 'keyword') #提取keyword中的单词， 去除连接符
    fields_features = []
    fields = item.get('fields')
    if fields:
        fields_features = transform_feature([string_utils.clean_name(k) for k in fields], 'fields')
    venue_features = [] #提取机构venue项
    venue_name = item.get('venue', '')
    if venue_name:
        if len(venue_name) > 2:
            venue_features = transform_feature(string_utils.clean_sentence(venue_name.lower()), "venue") #小写化 去除分界符 变换特征
    abst_features = []
    abst = item.get('abst')
    if abst:
        abst_features = transform_feature(string_utils.clean_sentence(abst.lower()), "abst")
    return title_features, keywords_features, venue_features, abst_features, fields_features

def extract_author_features(item, order=None): #提取作者特征 item中的order
    title_features, keywords_features, venue_features, abst_features, fields_features = extract_common_features(item) #提取共同特征 标题， 关键字， 收录机构
    author_features = []
    for i, author in enumerate(item["authors"]): #枚举第i个作者， author
        if order is not None and i != order: #找到所要的 第order个作者
            continue
        name_feature = [] #姓名特征
        org_features = [] #机构特征
        org_name = string_utils.clean_name(author.get("org", "")) #格式化机构名 按".", "-", " "分割 小写化
        if len(org_name) > 2:
            org_features.extend(transform_feature(org_name, "org")) #列表加列表
        for j, coauthor in enumerate(item["authors"]): #枚举 合作者
            if i == j:
                continue
            coauthor_name = coauthor.get("name", "") #获得名字
            coauthor_org = string_utils.clean_name(coauthor.get("org", "")) #获得格式化机构名
            if len(coauthor_name) > 2:
                name_feature.extend(
                    transform_feature([string_utils.clean_name(coauthor_name)], "name") #格式化 与 特征变换
                ) #将合作者名特征加入 名字特征中
            if len(coauthor_org) > 2:
                org_features.extend(
                    transform_feature(string_utils.clean_sentence(coauthor_org.lower()), "org") #格式化 与 特征变换
                ) #将合作者机构特征加入 机构特征中
        author_features.append(
            name_feature + org_features + title_features + keywords_features + venue_features + abst_features + fields_features
        ) #将以上特征 都 整合 到 作者特征 中
    author_features = list(chain.from_iterable(author_features)) #创建 为 迭代器 列表
    return author_features # 到这里 就是把 各个特征 对应的单词列表 合并到一个列表里了


from Main_program.code import coord_functions
import pygame

class Car(pygame.sprite.Sprite):
    def __init__(self,  df, color):
        super().__init__()
        self.image = pygame.Surface((12, 12))  # De auto (12x12 pixel rechthoek)
        self.image.fill(pygame.Color(color))
        self.position = [-200, -200]  # Positie buiten het scherm
        self.rect = self.image.get_rect(center=self.position)  # Tekent het vierkantje
        self.df = df

    def update(self, timestamp):
        """De update functie wordt elke frame gerund. Hierin word de nieuwe positie van de auto berekend"""
        df_cor = self.df.loc[self.df['timestamp'] == timestamp][['latitude', 'longitude']]

        if len(df_cor) == 1:  # Doet geen update als er geen positie is voor de auto op deze tijd
            df_cor = df_cor.reset_index()
            self.position = coord_functions.latlngToScreenXY(df_cor['latitude'][0], df_cor['longitude'][0])
            self.rect.center = self.position


import os

from fastapi import FastAPI
from routes.api import router as api_router
from starlette.middleware.cors import CORSMiddleware

def create_app():
    app = FastAPI(
        title="Simple FastAPI CRUD",
        description="Simple CRUD implementation using FastAPI",
        version="0.0.1",
        root_path=os.getenv("API_PATH"),
        docs_url="/",
        redoc_url="/docs",
    )

    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

    app.include_router(api_router)

    return app


from rest_framework import generics
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import TenantSerializer, ApartmentSerializer, LeaseSerializer, MaintenanceRequestSerializer
from .models import Tenant, Apartment, Lease, MaintenanceRequest

##### START OF TENANT VIEWS ######
class TenantList(generics.ListCreateAPIView):
    queryset = Tenant.objects.all()
    serializer_class = TenantSerializer

@api_view(["GET", "PUT", "PATCH", "DELETE"])
def tenant_by_name(request, name):
    try:
        tenant = Tenant.objects.get(name=name)
    except:
        return Response({"error": f"No tenants with name {name} found"}, status=404)

    if request.method == "GET":
        serializer = TenantSerializer(tenant)
        return Response(serializer.data)

    elif request.method == "PUT" or request.method == "PATCH":
        serializer = TenantSerializer(tenant, data=request.data) if request.method == "PUT" else TenantSerializer(tenant, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
    elif request.method == "DELETE":
        tenant.delete()
        return Response(status=204)

@api_view(["GET"])
def tenants_by_apartment(request, number):
    if request.method == "GET":
        tenants = Tenant.objects.filter(apartment__number=number)
        serializer = TenantSerializer(tenants, many=True)
        return Response(serializer.data)

##### START OF APARTMENT VIEWS #####
class ApartmentList(generics.ListCreateAPIView):
    queryset = Apartment.objects.all().order_by("number")
    serializer_class = ApartmentSerializer

@api_view(["GET", "PUT", "PATCH", "DELETE"])
def apartment_by_number(request, number):
    try:
        apartment = Apartment.objects.get(number=number)
    except:
        return Response({"error": f"No apartments with number {number} found"}, status=404)

    if request.method == "GET":
        serialzer = ApartmentSerializer(apartment)
        return Response(serialzer.data)

    elif request.method == "PUT" or request.method == "PATCH":
        serialzer = ApartmentSerializer(apartment, request.data) if request.method == "PUT" else ApartmentSerializer(apartment, request.data, partial=True)
        if serialzer.is_valid():
            serialzer.save()
            return Response(serialzer.data, status=201)
        return Response(serialzer.errors, status=400)

    elif request.method == "DELETE":
        apartment.delete()
        return Response(status=204)

@api_view(["GET"])
def available_apartments(request, end_date):
    try:
        apartments = Apartment.objects.filter(lease__end_date__lte=end_date, tenant__is_renewing=False)
    except Lease.DoesNotExist:
       return Response({"error": "No leases found"}, status=404)

    if request.method == "GET":
        serializer = ApartmentSerializer(apartments, many=True)
        return Response(serializer.data)

@api_view(["GET"])
def apartments_by_bedrooms(request, bedrooms):
    try:
        apartments = Apartment.objects.filter(bedrooms=bedrooms)
    except Apartment.DoesNotExist:
        return Response({"error": f"No apartments with {bedrooms} bedrooms found"}, status=404)

    if request.method == "GET":
        serializer = ApartmentSerializer(apartments, many=True)
        return Response(serializer.data, status=200)

##### START OF LEASE VIEWS #####
class LeaseList(generics.ListCreateAPIView):
    queryset = Lease.objects.all()
    serializer_class = LeaseSerializer

@api_view(["GET", "PUT", "PATCH", "DELETE"])
def lease_by_tenant_name(request, name):
    try:
        tenant = Tenant.objects.get(name=name)
    except:
        return Response({"error": f"No lease associated with {name} were found"}, status=404)

    lease = Lease.objects.get(tenant_id=tenant.id)
    if request.method == "GET":
        serializer = LeaseSerializer(lease)
        return Response(serializer.data, status=201)

    elif request.method == "PUT" or request.method == "PATCH":
        serializer = LeaseSerializer(lease, request.data) if request.method == "PUT" else LeaseSerializer(lease, request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

    elif request.method == "DELETE":
        lease.delete()
        return Response(status=204)

##### START OF MAINTENANCE RECORD VIEWS #####
class MaintenanceRecordList(generics.ListCreateAPIView):
    queryset = MaintenanceRequest.objects.all().order_by("-open_date")
    serializer_class = MaintenanceRequestSerializer

@api_view(["GET", "PUT", "PATCH", "DELETE"])
def maintenance_request_by_apartment(request, number):
    try:
        maintenance_request = MaintenanceRequest.objects.filter(apartment__number=number)
    except Apartment.DoesNotExist:
        return Response({"error": f"No maintenance requests associated with apartment {number} were found"}, status=404)

    if request.method == "GET":
        serializer = MaintenanceRequestSerializer(maintenance_request, many=True)
        return Response(serializer.data, status=200)
    elif request.method == "PUT" or request.method == "PATCH":
        serializer = MaintenanceRequestSerializer(maintenance_request, request.data) if request.method == "PUT" else MaintenanceRequestSerializer(maintenance_request, request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
    elif request.method == "DELETE":
        maintenance_request.delete()
        return Response(status=204)

@api_view(["GET"])
def open_maintenance_requests(request):
    try:
        maintenance_requests = MaintenanceRequest.objects.filter(close_date=None)
    except MaintenanceRequest.DoesNotExist:
        return Response({"error": "No open maintenance requests were found"}, status=404)

    if request.method == "GET":
        serializer = MaintenanceRequestSerializer(maintenance_requests, many=True)
        return Response(serializer.data, status=200)


import os
import sys
import redis
from cloudfiles import CloudFiles

TASK_KEY = sys.argv[1]

try:
    r = redis.Redis(host=os.environ["REDIS_SERVER"], db=int(os.environ["REDIS_DB"]))
    if r.exists(TASK_KEY) and r.get(TASK_KEY).decode() == "DONE":
        sys.exit(0)
    else:
        sys.exit(1)
except:
    cf = CloudFiles(os.environ["SCRATCH_PATH"])
    if cf.exists(f"done/{TASK_KEY}.txt"):
        sys.exit(0)
    else:
        sys.exit(1)