import unittest
import numpy as np
from scipy.linalg import expm
from scipy.sparse import csc_matrix, kron, diags

# RX and CHPHASE are never used
from openqaoa.backends.qaoa_vectorized import (
    QAOAvectorizedBackendSimulator,
    _permute_qubits,
    _get_perm,
    RX,
)
from openqaoa.utilities import X_mixer_hamiltonian, ring_of_disagrees
from openqaoa.qaoa_components import (
    QAOAVariationalExtendedParams,
    QAOAVariationalStandardParams,
    Hamiltonian,
    PauliOp,
    QAOADescriptor,
    create_qaoa_variational_params,
)

######################################################
# TESTS OF SIMPLE PERMUTATION AND RESHAPING OPERATIONS
######################################################

def Disagrees_SetUp(n_qubits):
    """
    Helper function for the tests below
    """

    register = range(n_qubits)
    p = 1
    cost_hamil = ring_of_disagrees(register)
    mixer_hamil = X_mixer_hamiltonian(n_qubits)

    betas = [np.pi / 8]
    gammas = [np.pi / 4]

    qaoa_descriptor = QAOADescriptor(cost_hamil, mixer_hamil, p)
    variational_params_std = QAOAVariationalStandardParams(
        qaoa_descriptor, betas, gammas
    )
    # Get the part of the Hamiltonian proportional to the identity

    return register, cost_hamil, qaoa_descriptor, variational_params_std

def pauli_matrix_SetUp():
    """
    Helper function for apply_gate tests.
    """

    constI = csc_matrix(np.eye(2)).toarray()
    constX = csc_matrix(np.array([[0, 1], [1, 0]])).toarray()
    constY = csc_matrix(np.array([[0, -1j], [1j, 0]])).toarray()
    constZ = csc_matrix(np.array([[1, 0], [0, -1]])).toarray()

    return constI, constX, constY, constZ

def apply_gate_problem_SetUp():
    """
    Helper function for apply_gate tests.
    """

    cost_hamil = Hamiltonian([PauliOp("ZZ", (0, 1)), PauliOp("Z", (2,))], [1, 1], 0)
    mixer_hamil = Hamiltonian(
        [PauliOp("X", (0,)), PauliOp("X", (1,)), PauliOp("X", (2,))], [1, 1, 1], 0
    )
    theta = 0  # Don't apply mixer and driver unitaries
    qaoa_descriptor = QAOADescriptor(cost_hamil, mixer_hamil, p=1)
    variate_params = QAOAVariationalStandardParams(qaoa_descriptor, theta, theta)
    vector_backend = QAOAvectorizedBackendSimulator(qaoa_descriptor, None, None, True)
    return cost_hamil.n_qubits, vector_backend

class TestingQAOAvectorizedBackend(unittest.TestCase):
    """
    Unittest based testing of QAOACostVector
    """

    def test_permute(self):
        nqubits = 3

        arr = np.arange(2**nqubits)
        arr.shape = [2] * nqubits
        # reshaped_arr = backend._reshape_qubits(nqubits, arr)
        perm = [2, 0, 1]
        permuted_arr = _permute_qubits(arr, perm)

        expected_arr = np.array([[[0, 2], [4, 6]], [[1, 3], [5, 7]]])

        assert np.array_equal(permuted_arr, expected_arr)

    def test_get_perm(self):
        nqubits = 4

        perm1, perminv1 = _get_perm(nqubits, [1, 3])
        perm2, perminv2 = _get_perm(nqubits, [0, 2])

        perm1_expected = np.array([2, 0, 1, 3])
        perminv1_expected = np.array([1, 2, 0, 3])

        perm2_expected = np.array([3, 1, 0, 2])
        perminv2_expected = np.array([2, 1, 3, 0])

        assert np.array_equal(perm1, perm1_expected)
        assert np.array_equal(perminv1, perminv1_expected)
        assert np.array_equal(perm2, perm2_expected)
        assert np.array_equal(perminv2, perminv2_expected)

    ##########################################################
    # TESTS OF BASIC CIRCUIT OPERATIONS (SAME AS FOR PROJECTQ)
    ##########################################################

    def test_qaoa_circuit(self):
        # Test circuit with p = 1 on 3 qubits
        # Performs a round of ZZ rotations through pi, and a round of X mixer rotations through pi
        nqubits = 3
        register = [i for i in range(nqubits)]
        p = 1
        bias_qubits = []
        bias_angles = []
        pairs = [[0, 1], [0, 2], [1, 2]]
        weights = [1, 1, 1]
        pairs_angles = [np.pi]  # [[np.pi]*len(pairs)]
        mixer_angles = [np.pi]  # [[np.pi]*nqubits]

        cost_hamiltonian = Hamiltonian.classical_hamiltonian(pairs, weights, constant=0)
        mixer_hamiltonian = X_mixer_hamiltonian(nqubits)
        qaoa_descriptor = QAOADescriptor(cost_hamiltonian, mixer_hamiltonian, p)
        variational_params_std = QAOAVariationalStandardParams(
            qaoa_descriptor, mixer_angles, pairs_angles
        )

        backend_vectorized = QAOAvectorizedBackendSimulator(
            qaoa_descriptor, prepend_state=None, append_state=None, init_hadamard=True
        )

        backend_vectorized.qaoa_circuit(variational_params_std)
        wf = backend_vectorized.wavefn
        wf.shape = 2**nqubits
        wf = wf / wf[0]

        expected_wf = np.array([1, 1, 1, 1, 1, 1, 1, 1])

        assert np.allclose(wf, expected_wf)

    def test_wavefunction_single_terms(self):
        # Test wavefunction and expectation values with hamiltonian object, without 2-qubit terms
        cost_hamil = Hamiltonian([PauliOp("Z", (0,)), PauliOp("Z", (1,))], [1, 1], 1)
        mixer_hamil = X_mixer_hamiltonian(n_qubits=2)
        qaoa_descriptor = QAOADescriptor(cost_hamil, mixer_hamil, p=1)
        variate_params = create_qaoa_variational_params(
            qaoa_descriptor, "standard", "ramp"
        )
        backend_obj = QAOAvectorizedBackendSimulator(qaoa_descriptor, None, None, True)

        args = [np.pi / 4, np.pi / 4]  # beta, gamma
        variate_params.update_from_raw(args)

        assert np.allclose(backend_obj.wavefunction(variate_params), [0, 0, 0, 1j])
        assert np.isclose(backend_obj.expectation(variate_params), -1)

    def test_wavefunction(self):
        nqubits = 3

        # Test circuit with p = 1 on 3 qubits
        terms = [[0, 1], [0, 2], [0]]
        weights = [1, 1, -0.5]
        register = [0, 1, 2]
        p = 1

        betas_singles = [np.pi, 0, 0]
        betas_pairs = []
        gammas_singles = [np.pi]
        gammas_pairs = [[np.pi / 2] * 2]

        cost_hamiltonian = Hamiltonian.classical_hamiltonian(terms, weights, constant=0)
        mixer_hamiltonian = X_mixer_hamiltonian(nqubits)
        qaoa_descriptor = QAOADescriptor(cost_hamiltonian, mixer_hamiltonian, p)
        variational_params_ext = QAOAVariationalExtendedParams(
            qaoa_descriptor, betas_singles, betas_pairs, gammas_singles, gammas_pairs
        )

        backend_vectorized = QAOAvectorizedBackendSimulator(
            qaoa_descriptor, prepend_state=None, append_state=None, init_hadamard=True
        )

        wf = backend_vectorized.wavefunction(variational_params_ext)

        cost_op1 = diags([-1, 1, 1, -1, -1, 1, 1, -1], 0, format="csc")
        cost_op2 = diags([-1, 1, -1, 1, 1, -1, 1, -1], 0, format="csc")
        cost_op3 = -1j * diags([-1, 1, -1, 1, -1, 1, -1, 1], 0, format="csc")

        # Factors of 2 needed to produce a rotation for total
        mixer = kron(RX(0), kron(RX(0), RX(-2 * np.pi)))
        # time of pi (pi-pulse) on the Bloch sphere

        input_wf = np.ones(2**nqubits) / np.sqrt(2**nqubits)
        direct_wf = -mixer @ cost_op3 @ cost_op2 @ cost_op1 @ input_wf

        expected_wf = -1j * np.array([-1, 1, 1, -1, 1, -1, -1, 1]) / (2 * np.sqrt(2))

        assert np.allclose(wf, direct_wf)
        assert np.allclose(wf, expected_wf)

    def test_execute_exp_val(self):
        n_qubits = 8
        register, cost_hamil, qaoa_descriptor, variate_params = Disagrees_SetUp(
            n_qubits
        )

        backend_vectorized = QAOAvectorizedBackendSimulator(
            qaoa_descriptor, prepend_state=None, append_state=None, init_hadamard=True
        )
        exp_val, std_dev1 = backend_vectorized.expectation_w_uncertainty(variate_params)

        # Check correct expecation value
        assert np.isclose(exp_val, -6)

        # Check standard deviation
        # Get the matrix form of the Hamiltonian (note we just keep the diagonal part) and square it
        ham_matrix = np.zeros((2 ** len(register)))
        for i, term in enumerate(cost_hamil.terms):
            out = np.real(cost_hamil.coeffs[i])
            for qubit in register:
                if qubit in term.qubit_indices:
                    out = np.kron([1, -1], out)
                else:
                    out = np.kron([1, 1], out)
            ham_matrix += out
        ham_matrix += cost_hamil.constant

        ham_matrix_sq = np.square(ham_matrix)

        # Get the wavefunction
        wf = backend_vectorized.wavefunction(variate_params)

        # Get the probabilities
        probs = [np.abs(el) ** 2 for el in wf]

        # Standard deviation
        exp_2 = np.dot(probs, ham_matrix)
        std_dev2 = np.sqrt(np.dot(probs, ham_matrix_sq) - exp_2**2)

        assert np.isclose(std_dev1, std_dev2)

    def test_cost_call(self):
        """
        testing the __call__ method of the base class.
        Only for vectorized and Qiskit Local Statevector Backends.
        """

        n_qubits = 8
        register = range(n_qubits)
        p = 1

        betas = [np.pi / 8]
        gammas = [np.pi / 4]
        cost_hamiltonian = ring_of_disagrees(register)
        mixer_hamiltonian = X_mixer_hamiltonian(n_qubits)
        qaoa_descriptor = QAOADescriptor(cost_hamiltonian, mixer_hamiltonian, p)
        variational_params_std = QAOAVariationalStandardParams(
            qaoa_descriptor, betas, gammas
        )

        backend_vectorized = QAOAvectorizedBackendSimulator(
            qaoa_descriptor, prepend_state=None, append_state=None, init_hadamard=True
        )

        exp_vec = backend_vectorized.expectation(variational_params_std)

        assert np.isclose(exp_vec, -6)

    def test_get_wavefunction(self):
        n_qubits = 3
        terms = [[0, 1], [0, 2], [0]]
        weights = [1, 1, -0.5]
        p = 1

        betas_singles = [np.pi, 0, 0]
        betas_pairs = []
        gammas_singles = [np.pi]
        gammas_pairs = [[1 / 2 * np.pi] * 2]

        cost_hamiltonian = Hamiltonian.classical_hamiltonian(
            terms=terms, coeffs=weights, constant=0
        )
        mixer_hamiltonian = X_mixer_hamiltonian(n_qubits)
        qaoa_descriptor = QAOADescriptor(cost_hamiltonian, mixer_hamiltonian, p)
        variational_params_std = QAOAVariationalExtendedParams(
            qaoa_descriptor,
            betas_singles=betas_singles,
            betas_pairs=betas_pairs,
            gammas_singles=gammas_singles,
            gammas_pairs=gammas_pairs,
        )

        backend_vectorised_statevec = QAOAvectorizedBackendSimulator(
            qaoa_descriptor, prepend_state=None, append_state=None, init_hadamard=True
        )

        wf_vectorised_statevec = backend_vectorised_statevec.wavefunction(
            (variational_params_std)
        )
        expected_wf = 1j * np.array([-1, 1, 1, -1, 1, -1, -1, 1]) / (2 * np.sqrt(2))

        try:
            assert np.allclose(wf_vectorised_statevec, expected_wf)
        except AssertionError:
            assert np.allclose(
                np.real(np.conjugate(wf_vectorised_statevec) * wf_vectorised_statevec),
                np.conjugate(expected_wf) * expected_wf,
            )

    def test_exact_solution(self):
        """
        NOTE:Since the implementation of exact solution is backend agnostic
            Checking it once should be okay.

        Nevertheless, for the sake of completeness it will be tested for all backend
        instances.

        """

        n_qubits = 8
        register = range(n_qubits)
        p = 1

        correct_energy = -8
        correct_config = [0, 1, 0, 1, 0, 1, 0, 1]

        # The tests pass regardless of the value of betas and gammas is this correct?
        betas = [np.pi / 8]
        gammas = [np.pi / 4]

        cost_hamiltonian = ring_of_disagrees(register)
        mixer_hamiltonian = X_mixer_hamiltonian(n_qubits)
        qaoa_descriptor = QAOADescriptor(cost_hamiltonian, mixer_hamiltonian, p)
        variational_params_std = QAOAVariationalStandardParams(
            qaoa_descriptor, betas, gammas
        )

        backend_vectorized = QAOAvectorizedBackendSimulator(
            qaoa_descriptor, prepend_state=None, append_state=None, init_hadamard=True
        )
        # exact solution is defined as the property of the cost function
        energy_vec, config_vec = backend_vectorized.exact_solution

        assert np.isclose(energy_vec, correct_energy)

        config_vec = [config.tolist() for config in config_vec]

        assert correct_config in config_vec

    def test_afunction_throws_exception(self):
        # Make sure that exception is raised when Hamiltonian contains nonclassical (non-Z or ZZ terms)

        def test_nonclassical_hamiltonian_error():
            cost_hamil = Hamiltonian(
                [PauliOp("Y", (0,)), PauliOp("Z", (1,))], [1, 1], 1
            )
            mixer_hamil = X_mixer_hamiltonian(n_qubits=2)
            qaoa_descriptor = QAOADescriptor(cost_hamil, mixer_hamil, p=1)
            variate_params = create_qaoa_variational_params(
                qaoa_descriptor, "standard", "ramp"
            )
            backend_obj = QAOAvectorizedBackendSimulator(
                qaoa_descriptor, None, None, True
            )

        self.assertRaises(Exception, test_nonclassical_hamiltonian_error)

    ##########################################################
    # TESTS OF APPLY GATE METHODS
    ##########################################################

    def test_apply_rx(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_rx method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rx(0, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constI, constX)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_ry(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_ry method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_ry(0, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constI, constY)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_rz(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_rz method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rz(0, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constI, constZ)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_rxx(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_rxx method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rxx(0, 1, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constX, constX)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_ryy(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_ryy method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_ryy(0, 1, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constY, constY)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_rzz(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_rzz method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rzz(0, 1, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constZ, constZ)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_rzx(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_rzx method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rzx(0, 1, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constX, constZ)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_rxz(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_rxz method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rzx(1, 0, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constZ, constX)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_rxy(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_rxy method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rxy(0, 1, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constY, constX)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_ryx(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_ryx method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_rxy(1, 0, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constX, constY)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_ryz(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_ryz method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_ryz(0, 1, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constZ, constY)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    def test_apply_rzy(self):
        constI, constX, constY, constZ = pauli_matrix_SetUp()

        # Result from apply_ryz method
        angles = [0.1, np.pi / 2, np.pi / 4]

        for angle in angles:
            n_qubits, vector_backend = apply_gate_problem_SetUp()
            vector_backend.apply_ryz(1, 0, angle)

            # Result from matrix multiply exponentiated gate
            wavefn = np.ones((2**n_qubits,), dtype=complex) / np.sqrt(2**n_qubits)
            unitary = expm(
                -kron(constI, kron(constY, constZ)).toarray() * angle * 1j / 2
            )
            res_wfn = np.matmul(unitary, wavefn).reshape([2] * n_qubits)

            assert np.allclose(
                vector_backend.wavefn, res_wfn
            ), f"angle = {angle} failed, {vector_backend.wavefn} != {res_wfn}"

    # ADD TESTS FOR PREPEND AND APPEND STATES BELOW
    # def test_with_init_prog_A(self):

    #     """
    #     Checks the trivial case that when we use a given set of params (params_std) as the
    #     init_prog followed by a circuit whose angles are zero (new_params), we should get the same as
    #     if we run the program with no init_prog, but where the angles are given by params_std
    #     """

    #     n_qubits = 8
    #     _,_,_, params_std = Disagrees_SetUp(n_qubits)

    #     new_params = copy(params_std)
    #     new_params.betas = [0]
    #     new_params.gammas = [0]

    #     vector_cost = QAOACostVector(params_std, init_prog=params_std)
    #     exp_val = vector_cost.execute_exp_val(new_params)

    #     # Check correct expecation value
    #     assert np.isclose(exp_val, -6)

    # def test_with_init_prog_B(self):

    #     """
    #     Set up a problem with p = 2 and solve directly
    #     Set up the same problem with an init_prog corresponding to the p=1 params,
    #     and the program to execute being the p=2 params.
    #     """

    #     n = 4
    #     p = 2
    #     register = range(n)
    #     terms = [[0, 1], [0, 2], [0, 3], [3, 0], [1, 3]]
    #     weights = [0.1, 1, -0.5, 0.3, 3]

    #     # Direct way for p=2
    #     hyperparams = HyperParams(terms,weights,p=p)
    #     stand_params = StandardParams.linear_ramp_from_hamiltonian(hyperparams)
    #     vector_cost = QAOACostVector(stand_params)
    #     wf_direct = vector_cost.wavefunction(stand_params)

    #     # Indirect way
    #     init_hyperparams = HyperParams(terms,weights,p=1)
    #     init_betas = stand_params.betas[0]
    #     init_gammas = stand_params.gammas[0]
    #     init_prog = StandardParams(init_hyperparams, (init_betas, init_gammas))

    #     betas_step2 = stand_params.betas[1]
    #     gammas_step2 = stand_params.gammas[1]
    #     params_step2 = StandardParams(init_hyperparams,(betas_step2, gammas_step2))
    #     vector_cost = QAOACostVector(params_step2, init_prog = init_prog)
    #     wf_indirect = vector_cost.wavefunction(params_step2)

    #     assert np.allclose(wf_direct, wf_indirect)

    # def test_with_init_prog_C(self):

    #     """
    #     Similar to above, but uses a random example with ExtendedParams
    #     """

    #     n = 8
    #     p = 3
    #     reg = range(n)
    #     terms, weights = zip(*random_hamiltonian(reg).items())
    #     terms, weights = list(terms),list(weights)
    #     hyperparams = HyperParams(terms,weights,p=p)
    #     abs_params = AbstractParams(hyperparams)
    #     n_gammas_singles = len(abs_params.qubits_singles)
    #     n_gammas_pairs = len(abs_params.qubits_pairs)

    #     # Direct way
    #     betas = np.random.rand(p,n)
    #     gammas_singles = np.random.rand(p,n_gammas_singles)
    #     gammas_pairs = np.random.rand(p,n_gammas_pairs)
    #     params = (betas,gammas_singles, gammas_pairs)
    #     ext_params = ExtendedParams.from_AbstractParameters(abs_params,params)
    #     vector_cost = QAOACostVector(ext_params)
    #     wf_direct = vector_cost.wavefunction(ext_params)

    #     # Indirect way: pass in the p=2 state as the init_prog to the final step
    #     init_hyperparams = HyperParams(terms,weights,p=2)
    #     init_betas = [ext_params.betas[0], ext_params.betas[1]]
    #     init_gammas_singles = [ext_params.gammas_singles[0], ext_params.gammas_singles[1]]
    #     init_gammas_pairs = [ext_params.gammas_pairs[0], ext_params.gammas_pairs[1]]
    #     init_prog = ExtendedParams(init_hyperparams, (init_betas, init_gammas_singles, init_gammas_pairs))

    #     hyperparams3 = HyperParams(terms,weights,p=1)
    #     betas_step3 = ext_params.betas[2]
    #     gammas_singles_step3 = ext_params.gammas_singles[2]
    #     gammas_pairs_step3 = ext_params.gammas_pairs[2]
    #     params_step3 = ExtendedParams(hyperparams3,(betas_step3, gammas_singles_step3, gammas_pairs_step3))
    #     vector_cost = QAOACostVector(params_step3, init_prog = init_prog)
    #     wf_indirect = vector_cost.wavefunction(params=params_step3)

    #     assert np.allclose(wf_direct, wf_indirect)

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


from ..Plugin import Plugin
import bpy
from bpy.types import Operator
from bpy.props import StringProperty, IntProperty
from .multiple_image_objects import multiple_image_objects
from .evaluate_pattern import evaluate_pattern, PatternError

class AssignSlotsInPatternOperator(Operator, Plugin):
    """Assign slots in a pattern."""
    bl_idname = "font.assignslotsinpattern"
    bl_label = "Assign Slots"
    bl_options = {'UNDO'}

    pattern: StringProperty(
        name="Pattern",
        description="A python expression to return the filename given the index i"
    )
    slot_start: IntProperty(name="Slot start")

    def execute(self, context):
        # type: (bpy.ContextType) -> set[bpy.Literal["FINISHED"]]
        self.assign_slots_in_pattern(context)
        return {'FINISHED'}

    def assign_slots_in_pattern(self, context):
        # type: (bpy.ContextType) -> None
        objects = multiple_image_objects(context)
        if objects is None:
            return
        objects.sort(key=lambda o: o.name)
        for i in range(len(objects)):
            o = objects[i]
            try:
                o["font_slot_name"] = evaluate_pattern(
                    i, self.pattern)
            except PatternError as e:
                self.report(
                    {'ERROR'}, f"Error while running your pattern on i={e.i}. Try your pattern out in the blender script editor.")
            o['font_slot_number'] = i + self.slot_start
            o['font_is_a_slot'] = True


#!/usr/bin/python3

def mysum(*numbers):
    result = 0
    for number in numbers:
        result += number
    return result

if __name__=='__main__':
    a = [1,2,3]
    b = [0]
    c = [-1, 2]
    print(sum(a) == mysum(*a))
    print(sum(b) == mysum(*b))
    print(sum(c) == mysum(*c))


'''
给你一串字符串，判断是否是手机号码

'''
import re
def checkPhone(str):

    if len(str) != 11:
        return False
    elif str[0] != '1':
        return False
    for i in range(3,11):
        if str[i] > '9' or str[i] <'0':
            return False
    return True

def checkPhone2(str):
    #17382865078
    #93910385@qq.com
    pat1 = r"^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$"# 判断邮箱
    pat2 = r"^\w*\@\w*\.com$" # 判断邮箱
    res = re.match(pat1,str)
    print(res)

checkPhone2("93910385@qq.com")
print(checkPhone("17382865078"))
print(checkPhone("173828650781"))

正则表达式/1、判断手机号码.py


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 10:35:25 2020

@author: derek.bickhart-adm
"""

import argparse
import sys
from collections import defaultdict
import os
from os.path import basename
import subprocess as sp
import upsetplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pandas as pd

def arg_parse():
    parser = argparse.ArgumentParser(
            description = "A wrapper script for my modified version of meryl"
            )
    parser.add_argument('-m', '--meryl',
                        help="The full path to the meryl executable.",
                        default="meryl", type=str
                        )
    parser.add_argument('-o', '--output',
                        help="Output file basename. Produces a text file (.raw.tab) and a plot (.pdf)",
                        required=True, type=str,
                        )
    parser.add_argument('-d', '--db',
                        help="Meryl database folder name. At least two are required",
                        action="append", default=[],
                        )
    return parser.parse_args(), parser

def main(args, parser):
    if len(args.db) < 2:
        print("Must provide two or more meryl databases!")
        parser.print_usage()
        sys.exit(-1)

    worker = merylWrapper(args.meryl, args.db)

    worker.run(args.output)

    print(f'Finished! Output is in {args.output}')

class merylWrapper:

    def __init__(self, meryl, dbs):
        self.meryl = meryl
        self.dbs = dbs
        self.numdbs = len(dbs)

        # Non final attributes
        self.counter = defaultdict(int)

    def run(self, output):
        dcount = 0
        dbstr = " ".join(self.dbs)

        if os.path.exists(output + ".raw.tab"):
            print("Starting from previous task")
            with open(output + ".raw.tab", 'r') as input:
                for l in input:
                    s = l.rstrip().split()
                    self.counter[s[0]] = int(s[1])
        else:
            with sp.Popen(f'{self.meryl} print venn {dbstr}', shell=True, stdout=sp.PIPE, bufsize=1, universal_newlines=True) as sf:
                for h in sf.stdout:
                    s = h.split()
                    self.counter[s[1]] += 1
                    dcount += 1
                    if dcount % 10000000 == 0:
                        print(f'Progress: {dcount}')

            # print out raw data
            with open(output + ".raw.tab", 'w') as out:
                for w in sorted(self.counter, key=self.counter.get, reverse=True):
                    out.write(f'{w}\t{self.counter[w]}\n')

            print("Created raw output file")

        # Prepare membership df
        array = list()
        data = list()
        for k, v in self.counter.items():
            tlist = list()
            for i, e in enumerate(self.dbs):
                if (int(k) & (1 << int(i))):
                    # The bit is set, add the file name
                    tlist.append(basename(e).split('.')[0])
            array.append(tlist)
            data.append(v)

        # Plot things out
        dataset = upsetplot.from_memberships(array, data=data)
        print(dataset)

        upset = upsetplot.UpSet(dataset, sort_by='cardinality', show_percentages=True)
        upset.plot()

        plt.savefig(output + ".pdf")

if __name__ == "__main__":
    args, parser = arg_parse()
    main(args, parser)


import re

INPUT_FILE = f"input/{__file__.split('.')[0].rstrip('b')}"

def getInput():
    with open(INPUT_FILE, 'r') as f:
        inp = f.read().splitlines()

    l = re.split("[x|y]=", inp[0])
    x = list(map(int, l[1].rstrip(', ').split("..")))
    y = list(map(int, l[2].split("..")))

    return [x, y]

def partOne(partTwo = False):
    inTargetArea = 0
    x, y = getInput()
    maxY = maxYGlobal = 0
    xVel = yVel = 1

    for xVelOrig in range(x[1] + 10):
        for yVelOrig in range(y[0], abs(y[0])):
            maxY = 0
            xVel = xVelOrig
            yVel = yVelOrig
            pos = [0, 0]

            while True:
                if yVel > 0:
                    maxY += yVel

                # Step forward
                pos[0] += xVel
                pos[1] += yVel
                xVel = xVel - 1 if xVel > 0 else xVel
                yVel -= 1

                # Are we in the target zone?
                if pos[0] >= x[0] and pos[0] <= x[1] and pos[1] >= y[0] and pos[1] <= y[1]:
                    inTargetArea += 1

                    # If we are, check if our iteration's maxY is greater than the global maxY
                    if maxY > maxYGlobal:
                        maxYGlobal = maxY
                    break

                # Out of bounds
                if pos[0] > x[1] or pos[1] < y[0]:
                    break

    return inTargetArea if partTwo else maxYGlobal

if __name__ == "__main__":
    one = partOne()
    two = partOne(True)
    print(f"Part one: {one}")
    print(f"Part two: {two}")


import turtle   # 导入turtle

turtle.title("五角星绘制")
turtle.speed(5)  # 调节画笔速度
turtle.bgcolor('#10aec2')  # 画布背景颜色
turtle.pencolor('#93d5dc')  # 画笔颜色

for i in range(5):  # for循环画五角星
    turtle.forward(100)
    turtle.right(144)

turtle.done()  # 画图界面暂停而不退出,方便截图


# script to play tic-tac-toe against the computer in the console

coords = [' ',' ' ,' ',' ',' ',' ',' ',' ',' ']

computer_win = False
player_win = False
game_over = False

def drawboard():
    print(coords[0], '|',coords[1], '|',coords[2])
    print('-' * 10)
    print(coords[3], '|',coords[4], '|',coords[5])
    print('-' * 10)
    print(coords[6], '|',coords[7], '|',coords[8])

def one_round():
    player_move = int(input('Where would you like to play, coordinates are 1-9: '))
    while True:
        if coords[player_move-1] != ' ':
            print("you cannot move there, try again: ")
            player_move = int(input('Where would you like to play, coordinates are 1-9: '))
        else:
            break

    coords[player_move-1] = 'x'

    while True:
        if ' ' not in coords:
            break
        computer_move = computermove(coords, True)
        best_computer_move = computer_move[1]
        if coords[best_computer_move] == ' ' and computer_move != player_move:
            coords[best_computer_move] = 'o'
            break

    drawboard()

def wincheck():
    global player_win
    global computer_win
    for i in range(0,9,3):
        if coords[i] == coords[i+1] and coords[i+1] == coords[i+2]:
            if coords[i] == 'x':
                player_win = True
            elif coords[i] == 'o':
                computer_win = True

    for i in range(0,3):
        if coords[i] == coords[i+3] and coords[i+3] == coords[i+6]:
            if coords[i] == 'x':
                player_win = True
            elif coords[i] == 'o':
                computer_win = True

    if coords[0] == coords[4] and coords[4] == coords[8]:
        if coords[4] == 'x':
            player_win = True

        elif coords[4] == 'o':
            computer_win = True

    if coords[2] == coords[4] and coords[4] == coords[6]:
        if coords[4] == 'x':
            player_win = True

        elif coords[4] == 'o':
            computer_win = True

def getempty(coords):
    empty = [index for index, item in enumerate(coords) if item == ' ']
    return empty

# using the minmax algorithm
def computermove(coords, player):
    global player_win
    global computer_win

    available = getempty(coords)
    wincheck()

    if player_win:
        player_win = False
        return -1, None
    if computer_win:
        computer_win = False
        return 1, None
    if len(available) == 0:
        return 0, None

    if player:
        max_eval = float('-inf')
        best_move = None

        for move in available:
            coords[move] = 'o'
            eval_score, _ = computermove(coords, False)
            coords[move] = ' '

            if eval_score > max_eval:
                max_eval = eval_score
                best_move = move

        return max_eval, best_move
    else:
        min_eval = float('inf')
        best_move = None

        for move in available:
            coords[move] = 'x'
            eval_score, _ = computermove(coords, True)
            coords[move] = ' '

            if eval_score < min_eval:
                min_eval = eval_score
                best_move = move

        return min_eval, best_move

def playgame():
    global player_win
    global computer_win
    global coords
    global game_over
    while True:
        one_round()
        wincheck()
        if player_win == True:
            drawboard()
            print("You win!")
            game_over = True
        elif computer_win:
            drawboard()
            print("You lose! :(")
            game_over = True
        if ' ' not in coords:
             print('Tie :/')
             game_over = True
        if game_over:
            play_again = input('Would you like to play again? (y/n): ')
            if play_again == 'y':
                coords = [' ',' ' ,' ',' ',' ',' ',' ',' ',' ']
                computer_win = False
                player_win = False
                game_over = False
                drawboard()
            else:
                return print('See you next time :)')

playgame()


from nanpy import (ArduinoApi, SerialManager)
from time import sleep

ledPin = 7
btnPin = 8
ledStat = False
btnstat = 0

try:
    connection = serialManager()
    a = ArduinoApi (connection = connection)
except:
    print("fail to connect to ardinno")

# Setup t
a.pinMode(ledPin,a.OUTPUT)
a.pinMode(btnPin,a.INPUT)

try:
    while True:
        btnStat - a.digitalRead(btnPin)
        print("btn state is : {}".format(btnStat))
        if btnStat:
            if ledStat:
                a.digitalWrite(ledPin, a.LOW)
                ledstat = False
                print("leeed offff")
                sleep(1)
            else:
                a.digitalWrite(ledPin, a.HIGH)
                ledState = True
                print("leeed onnnn")
                sleep(1)
except:
    a.digitalWrite(ledPin, a.LOW)


import pygame
import random

from src.Util import *
from src.DragDescriptor import DragDescriptor
from src.ImageLibrary import IMAGES
from src.RoomRenderer import ROOM_RENDERER

class Tile:
	def __init__(self, id, flags):
		self.id = id
		passable = False
		self.denoted = False
		for flag in list(flags):
			if flag == 'p':
				passable = True
			elif flag == 'd':
				self.denoted = True

		self.passable = passable

_TILE_MANIFEST = """
.	p
x	-
i	d
j	d
t	d
c	d
""".strip()

RAW_OFFICE = """
xxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxx
xi...c.............x
x..................x
x..................x
x..................x
x..................x
x.t..j.............x
xxxxxxxx...........x
@      x...........x
@      x...........x
@      x...........x
@      x...........x
@      x...........x
@      xxxxxxxxxxxxx
""".lower().strip()

TILE_MANIFEST = {}
for row in _TILE_MANIFEST.split('\n'):
	row = row.strip()
	cols = row.split('\t')
	id = cols[0]
	flags = cols[1]
	TILE_MANIFEST[id] = Tile(id, flags)

office_rows = RAW_OFFICE.split('\n')
office_height = len(office_rows)
office_width = len(office_rows[0])

INTERESTING_COORDS = {}

# session is nullable
def build_office_map(session, interesting_coords_out, model):

	interesting_coords = []
	output = make_grid(office_width, office_height)
	y = 0
	while y < office_height:
		x = 0
		row = office_rows[y].strip().replace('@', ' ')
		while x < office_width:
			id = row[x]
			tile = TILE_MANIFEST.get(id, None)
			if tile != None and tile.denoted:
				interesting_coords.append((id, x, y))
				tile = TILE_MANIFEST['.']
			output[x][y] = tile
			x += 1
		y += 1

	blocking = TILE_MANIFEST['x']
	furniture = []
	for mf in model.furniture:
		interesting_coords.append((mf[0], mf[1], mf[2]))

	interesting_coords += furniture

	while len(interesting_coords_out) > 0:
		interesting_coords_out.pop(0)

	for interesting in interesting_coords:
		interesting_coords_out.append(interesting)
		key, x, y = interesting
		if key == 'i':
			if session == None or session.is_iv_available():
				output[x][y] = blocking
				output[x + 1][y] = blocking
		elif key == 'c':
			if session == None or session.is_cucumber_available():
				output[x][y] = blocking
				output[x + 1][y] = blocking
		elif key == 't':
			if session == None or session.is_tape_available():
				output[x][y] = blocking
				output[x + 1][y] = blocking
		elif key == 'j':
			if session == None or session.is_jacket_available():
				output[x][y] = blocking
				output[x + 1][y] = blocking
		elif key in '12345':
			width, height = {
				'1': (1, 1),
				'2': (2, 1),
				'3': (1, 1),
				'4': (2, 2),
				'5': (3, 2)
			}[key]
			xstart = x
			ystart = y
			xend = x + width
			yend = y + height
			for x in range(xstart, xend):
				for y in range(ystart, yend):
					output[x][y] = blocking

	return output

class PlayBoard:
	def __init__(self, model):
		self.interesting_coords = []
		self.office = build_office_map(model.session, self.interesting_coords, model)
		self.selected = None
		self.model = model
		self.drag_descriptor = []
		self.active_drag = None
		self.drag_offset = None
		self.level_completed = False
		self.animations = []

	def update(self, events):

		if self.active_drag != None and self.active_drag.done:
			self.active_drag = None

		for event in events:
			if event.mousedown:
				members = self.find_staff_members(event.x, event.y) # find staff in range
				if len(members) > 0:
					sorted_members = []
					for member in members:
						dx = member.x - event.x
						dy = member.y - event.y
						dist = dx ** 2 + dy ** 2
						if self.is_line_segment_okay(event.x, event.y, member.x, member.y):
							sorted_members.append((dist, member, False))
						else:
							sorted_members.append((dist, member, True)) # this 3rd item is whether or not the clicked point is okay. If it isn't, then fall back to the old behavior with the offset
					sorted_members.sort(key=lambda x:x[0])

					if len(sorted_members) > 0:
						ignore, member, use_offset = sorted_members[0]
						if use_offset:
							self.drag_offset = (member.x - event.x, member.y - event.y)
						else:
							self.drag_offset = (0, 0)
						drag = DragDescriptor(member)
						drag.is_active = True
						self.drag_descriptor.append(drag)
						member.drag_path = drag
						self.active_drag = drag
						if not use_offset:
							self.active_drag.add_point(event.x, event.y, self)
			elif event.mouseup:
				if self.active_drag != None:
					self.active_drag.is_active = False
					self.active_drag = None

			elif event.mousemove:
				if self.active_drag != None:
					nx = event.x + self.drag_offset[0]
					ny = event.y + self.drag_offset[1]

					px, py = self.active_drag.points[-1]
					if self.is_line_segment_okay(px, py, nx, ny):
						self.active_drag.add_point(nx, ny, self)

		self.model.session.update(self)

		for member in self.model.staff:
			member.update(self)

		self.level_completed = self.model.session.is_done()

	def get_hover_buttons(self):
		bins = {}
		for interesting in self.interesting_coords:
			if interesting[0] in 'ictj':
				key, x, y = interesting
				bins[key] = (x, y)

		output = []
		for staff in self.model.staff:
			if bins.get('i') != None and (staff.holding == None or staff.holding == 'iv') and self.model.inventory_ivs > 0:
				x, y = bins['i']
				x += 1
				y += 1
				x *= 32
				y *= 32
				dx = staff.x - x
				dy = staff.y - y

				if dx ** 2 + dy ** 2 < 48 ** 2:
					if staff.holding == None:
						command = 'iv_take_' + str(staff.id)
						label = 'Take IV'
					else:
						command = 'iv_drop_' + str(staff.id)
						label = 'Put back'

					button = {
						'id': command,
						'label': label,
						'x': x,
						'y': y - 50
					}
					output.append(button)

			if bins.get('c') != None and (staff.holding == None or staff.holding == 'cucumber') and self.model.inventory_cucumbers > 0:
				x, y = bins['c']
				x += 1
				y += 1
				x *= 32
				y *= 32
				dx = staff.x - x
				dy = staff.y - y
				if dx ** 2 + dy ** 2 < 48 ** 2:
					if staff.holding == None:
						command = 'cuc_take_' + str(staff.id)
						label = 'Take Cucumbers'
					else:
						command = 'cuc_drop_' + str(staff.id)
						label = 'Put back'

					button = {
						'id': command,
						'label': label,
						'x': x,
						'y': y - 50
					}
					output.append(button)

			if bins.get('t') != None and (staff.holding == None or staff.holding == 'tape') and self.model.inventory_tapes > 0:
				x, y = bins['t']
				x += 1
				y += 1
				x *= 32
				y *= 32
				dx = staff.x - x
				dy = staff.y - y
				if dx ** 2 + dy ** 2 < 48 ** 2:
					if staff.holding == None:
						command = 'tape_take_' + str(staff.id)
						label = 'Pick Tape'
					else:
						command = 'tape_drop_' + str(staff.id)
						label = 'Put back'

					button = {
						'id': command,
						'label': label,
						'x': x,
						'y': y - 50
					}
					output.append(button)

			if bins.get('j') != None and (staff.holding == None or staff.holding == 'jacket') and self.model.inventory_jackets > 0:
				x, y = bins['j']
				x += 1
				y += 1
				x *= 32
				y *= 32
				dx = staff.x - x
				dy = staff.y - y
				if dx ** 2 + dy ** 2 < 48 ** 2:
					if staff.holding == None:
						command = 'jacket_take_' + str(staff.id)
						label = 'Take Jacket'
					else:
						command = 'jacket_drop_' + str(staff.id)
						label = 'Put back'

					button = {
						'id': command,
						'label': label,
						'x': x,
						'y': y - 50
					}
					output.append(button)

			if staff.holding != None:
				for device in self.model.session.active_devices:
					if abs(device.x - staff.x) < 32 and abs(device.y - staff.y) < 32 and device.state == 'ailed':
						t = staff.holding + '-' + device.ailment
						if t in ('iv-sick', 'cucumber-sad', 'tape-angry', 'jacket-crazy'):
							output.append({
								'id': 'device_treat_' + str(device.id) + "_" + str(staff.id),
								'label': "Treat",
								'x': device.x,
								'y': device.y - 50
							})

		return None if len(output) == 0 else output

	def get_random_open_tile(self, allow_overlap=False):
		# this isn't called very often so it can be stupid and brute force
		potential = []

		current_devices = {}
		if not allow_overlap:
			for device in self.model.session.active_devices:
				x = device.x // 32
				y = device.y // 32

				for dx in (x - 1, x, x + 1):
					for dy in (y - 1, y, y + 1):
						current_devices[str(dx) + '-' + str(dy)] = True

		foosball = None
		for furn in self.model.furniture:
			if furn[0] == '5':
				foosball = (furn[1], furn[2])

		y = 4
		while y <= 14:
			x = 10
			while x <= 18:
				tile = self.office[x][y]
				if tile != None and tile.passable:
					if not current_devices.get(str(x) + '-' + str(y), False):
						allow = True
						if foosball != None:
							dx = x - foosball[0] + 1
							dy = y - foosball[1]
							dist = (dx ** 2 + dy ** 2) ** .5
							if dist <= 4:
								allow = False
						if allow:
							potential.append((x, y))
				x += 1
			y += 1

		if not allow_overlap and len(potential) == 0:
			return self.get_random_open_tile(True)
		random.shuffle(potential)
		return potential[0]

	def is_line_segment_okay(self, start_x, start_y, end_x, end_y):
		start_col = int(start_x // 32)
		start_row = int(start_y // 32)
		end_col = int(end_x // 32)
		end_row = int(end_y // 32)

		if start_col == end_col and start_row == end_row:
			return self.is_tile_okay(start_col, start_row)

		start_and_end_okay = self.is_tile_okay(start_col, start_row) and self.is_tile_okay(end_col, end_row)
		if not start_and_end_okay:
			return False

		d = abs(end_row - start_row) + abs(end_col - start_col)
		if d == 1:
			return True
		if d == 2 and end_row != start_row and end_col != start_col:
			if start_x > end_x:
				start_x, end_x = end_x, start_x
				start_y, end_y = end_y, start_y
				start_col, end_col = end_col, start_col
				start_row, end_row = end_row, start_row

			dx = end_x - start_x
			dy = end_y - start_y

			if dx == 0: # HOW?!?!?
				return True
			m = dy / dx

			if m == 1 or m == -1:
				for x in [start_col, end_col]:
					for y in [start_row, end_row]:
						if not self.is_tile_okay(start_col, start_row):
							return False
				return True
			to_next_x = start_col * 32 - start_x
			y = m * to_next_x + start_y
			row = int(y // 32)
			if row == start_row:
				return self.is_tile_okay(end_col, row)
			else:
				return self.is_tile_okay(start_col, row)

		mx = (start_x + end_x) // 2
		my = (start_y + end_y) // 2

		return self.is_line_segment_okay(start_x, start_y, mx, my) and self.is_line_segment_okay(mx, my, end_x, end_y)

	def is_tile_okay(self, col, row):
		if col < 0: return False
		if row < 0: return False
		if col >= office_width: return False
		if row >= office_height: return False
		tile = self.office[col][row]
		if tile == None: return False
		return tile.passable

	def find_staff_members(self, x, y):
		output = []
		for member in self.model.staff:
			left = member.x - 16
			right = member.x + 16
			top = member.y - 64
			bottom = member.y

			padding = 16

			left -= padding
			right += padding
			top -= padding
			bottom += padding

			if x >= left and x <= right and y >= top and y <= bottom:
				output.append(member)
		return output

	def render(self, screen, rc, left_offset, top_offset, staff):

		supplies = {
			'i': self.model.inventory_ivs > 0,
			'c': self.model.inventory_cucumbers > 0,
			't': self.model.inventory_tapes > 0,
			'j': self.model.inventory_jackets > 0
		}

		employee = self.model.session.get_current_angry_employee()

		ROOM_RENDERER.render(screen, rc, self.model.session.active_devices, staff, self.interesting_coords, supplies, self.animations, False, employee)


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

def make_move(fbs):
    new_fbs = {}
    for fb in fbs:
        for f in fbs[fb]:
            ny, nx = (fb[0]+direct[f[2]][0]*f[1])%N, (fb[1]+direct[f[2]][1]*f[1])%N
            if (ny, nx) in new_fbs:
                new_fbs[(ny, nx)].append(f)
            else:
                new_fbs[(ny, nx)] = [f]
    return new_fbs

def div_fb(fbs):
    new_fbs = {}
    for fb in fbs:
        if len(fbs[fb]) >= 2:
            m = s = 0
            d = set()
            for f in fbs[fb]:
                m += f[0]
                s += f[1]
                d.add(f[2]%2)
            if m//5 != 0:
                if len(d) == 1:
                    d = [0,2,4,6]
                else:
                    d = [1,3,5,7]
                for i in d:
                    if fb in new_fbs:
                        new_fbs[fb].append((m//5, s//len(fbs[fb]), i))
                    else:
                        new_fbs[fb] = [(m//5, s//len(fbs[fb]), i)]
        else:
            new_fbs[fb] = fbs[fb]
    return new_fbs

N, M, K = map(int, input().split())
fbs = {}
for _ in range(M):
    r, c, m, s, d = map(int, input().split())
    fbs[(r-1,c-1)] = [(m, s, d)]

for _ in range(K):
    fbs = make_move(fbs)
    fbs = div_fb(fbs)
ans = 0
for fb in fbs:
    for f in fbs[fb]:
        ans += f[0]
print(ans)


import string
from string import *
import os
import subprocess
import re
from win32com import client as win32
import win32com
from  docx2csv import extract

#Путь подается в ковычках  'path'
#ft_cnvrt_to_xls_csv() - главная функция
#создает файлы xls, csv  по одному на таблицу

def ft_docx_to_csv_xls_converteer(path_to_docx):
		extract(filename=path_to_docx, format="csv",singlefile=False)
		extract(filename=path_to_docx, format="xls",singlefile=False)

def ft_doc_to_docx(path):
		word = win32.genchache.EnsureDispatch('Word.Application')
		doc = word.Documents.Open(path)
		doc.Activate()
		new_file = os.path.abspath(path)
		new_file = re.sub(r'\.\w+$', 'docx', new_file)
		word.ActivateDocuments.SaveAs(new_file, FileFormat=constants.wdFormatXMLDocument)
		doc.close(False)

def ft_rtf_to_docx(path):
		word = win32com.client.Dispatch("Word.Application")
		wdFormatDocumentDefault = 16
		wdHeaderFooterPrimary = 1
		doc = word.Documents.Open(path)
		new_file = os.path.abspath(path)
		new_file = re.sub(r'\.\w+$', 'docx', new_file)
		doc.SaveAs(new_file, FileFormat=wdFormatDocumentDefault)
		doc.Close()
		word.Quit()

def ft_cnvrt_to_xls_csv(path):
		if path.find(path, ".rtf") != -1:
			ft_rtf_to_docx(path)
			path = path + 'x'
			ft_cnvrt_to_xls_csv(path)
		if path.find('.doc') != -1:
			ft_doc_to_docx(path)
			path = path + 'x'
			ft_cnvrt_to_xls_csv(path)
		if path.find('.docx') != -1:
			ft_cnvrt_to_xls_csv(path)


def currency_converter_pesos(currency,dollar_value):
    pesos=float(input("How many {} do you have?: $".format(currency)))
    dollars=round(pesos/dollar_value, 2)
    print("💲{} dollars".format(dollars))
def currency_converter_US(currency,peso_value):
    dollars=float(input("How many US dollars do you have?: $"))
    pesos=round(dollars/peso_value, 2)
    print("💲{} {}".format(pesos, currency))
print("""Welcome 😄❕
This program is a currency converter 💸💰💵
Choose the currency you want to convert:
1-Colombian pesos to US dollars
2-US dollars to Colombian pesos
3-Argentine pesos to US dollars
4-US dollars to Argentine pesos
5-Mexican pesos to US dollars
6-US dollars to Mexican pesos
7-Exit""")
on=True
while on:
    option=input("Type the number of the option: ")
    if option == "1":
        currency_converter_pesos("Colombian pesos", 3814)
    elif option == "2":
        currency_converter_US("Colombian pesos", 0.0002621919)
    elif option == "3":
        currency_converter_pesos("Argentine pesos", 96)
    elif option == "4":
        currency_converter_US("Argentine pesos", 0.010416)
    elif option == "5":
        currency_converter_pesos("Mexican pesos", 20)
    elif option == "6":
        currency_converter_US("Mexican pesos", 0.05)
    elif option == "7":
        on=False
    else:
        print("*ERROR* You must type a number from 1 to 7 depending on the option.")
print("Bye👋🏻, see you later😊.")


class Settings:
    # class for all settings for Alien Invasion
    def __init__(self):
        """ static settings """
        # Screen settings
        self.screen_width = 800
        self.screen_height = 600
        self.bg_color = (230, 230, 230)

        # ship settings
        self.ship_limit = 3

        # bullet settings
        self.bullet_width = 3
        self.bullet_height = 10
        self.bullet_color = (60, 60, 60)

        # alien settings
        self.fleet_drop_speed = 10

        # difficulty scaling values
        self.speedup_scale = 1.2
        self.score_scale = 1.5
        """ dynamic settings """
        self.initialize_dynamics()

    def initialize_dynamics(self):
        # settings that change throughout a play-through
        self.ship_speed = 3.5
        self.alien_speed = 1.0
        self.bullet_speed = 10.0

        # fleet direction, 1 is right -1 is left
        self.fleet_direction = 1

        # scoring
        self.alien_points = 50

    def increase_difficulty(self):
        # difficulty increase
        self.ship_speed *= self.speedup_scale
        self.alien_speed *= self.speedup_scale
        self.bullet_speed *= self.speedup_scale

        # score value increase with difficulty
        self.alien_points = int(self.alien_points * self.score_scale)


from tests import unittest
import time

import mock
import dateutil.parser

import botocore.parameters
import botocore.exceptions

class FakeService(object):

    def __init__(self, timestamp_format):
        self.timestamp_format = timestamp_format

class FakeOperation(object):

    def __init__(self, timestamp_format):
        self.service = FakeService(timestamp_format)

class TestParameters(unittest.TestCase):

    def test_iso_timestamp_from_iso(self):
        op = FakeOperation('iso8601')
        p = botocore.parameters.TimestampParameter(op, name='paramname',
                                                   type='timestamp')
        d = {}
        ts = '2012-10-12T00:00'
        dt = dateutil.parser.parse(ts)
        p.build_parameter_query(ts, d)
        self.assertEqual(d['paramname'], dt.isoformat())
        with self.assertRaisesRegexp(botocore.exceptions.ValidationError,
                                     'timestamp:paramname'):
            p.build_parameter_query(value='not a date string',
                                    built_params=d)

    def test_iso_timestamp_from_epoch(self):
        op = FakeOperation('iso8601')
        p = botocore.parameters.TimestampParameter(op, name='foo')
        d = {}
        iso = '2013-04-11T23:23:15'
        epoch = 1365722595
        p.build_parameter_query(epoch, d)
        self.assertEqual(d['foo'], iso)
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value='not a date string',
                                    built_params=d)

    def test_epoch_timestamp_from_iso(self):
        op = FakeOperation('unixTimestamp')
        p = botocore.parameters.TimestampParameter(op, name='foo')
        d = {}
        iso = '2013-04-11T23:23:15'
        epoch = 1365722595
        p.build_parameter_query(iso, d)
        self.assertEqual(d['foo'], str(epoch))
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value='not a date string',
                                    built_params=d)

    def test_epoch_timestamp_from_epoch(self):
        op = FakeOperation('unixTimestamp')
        p = botocore.parameters.TimestampParameter(op, name='foo')
        d = {}
        epoch = 1365722595
        p.build_parameter_query(epoch, d)
        self.assertEqual(d['foo'], str(epoch))
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value='not a date string',
                                    built_params=d)

    def test_string(self):
        p = botocore.parameters.StringParameter(None, name='foo')
        d = {}
        value = 'This is a test'
        p.build_parameter_query(value, d)
        self.assertEqual(d['foo'], value)
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value=1,
                                    built_params=d)

    def test_integer(self):
        p = botocore.parameters.IntegerParameter(None, name='foo')
        d = {}
        p.build_parameter_query(123, d)
        self.assertEqual(d['foo'], '123')
        p.build_parameter_json(123, d)
        self.assertEqual(d['foo'], 123)
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value=123.4,
                                    built_params=d)

    def test_integer_range(self):
        p = botocore.parameters.IntegerParameter(None, name='foo',
                                                 min=0, max=10)
        d = {}
        p.build_parameter_query(9, d)
        self.assertEqual(d['foo'], '9')
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value=8.4,
                                    built_params=d)
        with self.assertRaisesRegexp(botocore.exceptions.RangeError,
                                     'foo'):
            p.build_parameter_query(value=100,
                                    built_params=d)

    def test_float(self):
        p = botocore.parameters.FloatParameter(None, name='foo')
        d = {}
        p.build_parameter_query(123.4, d)
        self.assertEqual(d['foo'], '123.4')
        p.build_parameter_json(123.4, d)
        self.assertEqual(d['foo'], 123.4)
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value=True,
                                    built_params=d)

    def test_float_range(self):
        p = botocore.parameters.FloatParameter(None, name='foo',
                                               min=0, max=10)
        d = {}
        p.build_parameter_query(9.0, d)
        self.assertEqual(d['foo'], '9.0')
        p.build_parameter_json(9.0, d)
        self.assertEqual(d['foo'], 9.0)
        with self.assertRaises(botocore.exceptions.RangeError):
            p.build_parameter_query(value=100.0,
                                    built_params=d)

    def test_boolean(self):
        p = botocore.parameters.BooleanParameter(None, name='foo')
        d = {}
        p.build_parameter_query('true', d)
        self.assertEqual(d['foo'], 'true')
        p.build_parameter_query('True', d)
        self.assertEqual(d['foo'], 'true')
        p.build_parameter_query('TRUE', d)
        self.assertEqual(d['foo'], 'true')
        p.build_parameter_query('false', d)
        self.assertEqual(d['foo'], 'false')
        p.build_parameter_query('False', d)
        self.assertEqual(d['foo'], 'false')
        p.build_parameter_query('FALSE', d)
        self.assertEqual(d['foo'], 'false')
        p.build_parameter_query(True, d)
        self.assertEqual(d['foo'], 'true')
        p.build_parameter_json(True, d)
        self.assertEqual(d['foo'], True)
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter_query(value='100',
                                    built_params=d)

    def test_list_fails_member_validation(self):
        p = botocore.parameters.ListParameter(operation=None, name='foo',
                                              members={'type': 'string'})
        d = {}
        # None is not of type string.
        value = ['This', 'is', None, 'test']
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter('query', value, d)

    def test_list_type_validation(self):
        p = botocore.parameters.ListParameter(operation=None, name='foo',
                                              members={'type': 'string'})
        d = {}
        # None is not of type string.
        value = 'not a list'
        with self.assertRaises(botocore.exceptions.ValidationError):
            p.build_parameter('query', value, d)

    def test_list_struct_fails_validation(self):
        members = {
            "shape_name": "Foo",
            "type": "structure",
            "members": {
                "foo": {
                    "shape_name": "String",
                    "type": "string",
                    "required": True,
                },
            },
        }
        p = botocore.parameters.ListParameter(operation=None, name='foo',
                                              members=members)
        d = {}
        # 'notfoo' is an unknown key so this will raise an exception
        # when we try to validate this value.
        value = [{'foo': 'bar'}, {'foo': 'baz'}, {'notfoo': 'bad'}]
        with self.assertRaisesRegexp(botocore.exceptions.ValidationError,
                                     'element of None:foo'):
            p.build_parameter('query', value, d)

    def test_plain_list(self):
        # Test a plain vanilla list.
        p = botocore.parameters.ListParameter(operation=None, name='foo',
                                              members={'type': 'string'})
        d = {}
        value = ['This', 'is', 'a', 'test']
        p.build_parameter_query(value, d)
        self.assertEquals(d, {'foo.member.4': 'test',
                              'foo.member.2': 'is',
                              'foo.member.3': 'a',
                              'foo.member.1': 'This'})

    def test_list_with_xmlname(self):
        # Test a list where the member specifies an xmlname.
        # This should be ignored.
        p = botocore.parameters.ListParameter(
            operation=None, name='foo',
            members={'type': 'string', 'xmlname': 'bar'})
        d = {}
        value = ['This', 'is', 'a', 'test']
        p.build_parameter_query(value, d)
        self.assertEquals(d, {'foo.member.4': 'test',
                              'foo.member.2': 'is',
                              'foo.member.3': 'a',
                              'foo.member.1': 'This'})
        d = {}
        p.build_parameter_json(value, d)
        self.assertEquals(d, {'foo': ['This', 'is', 'a', 'test']})

    def test_flattened_list(self):
        # Test a flattened list.  Member should always define
        # and xmlname attribute.
        p = botocore.parameters.ListParameter(
            operation=None, name='foo', flattened=True,
            members={'type': 'string', 'xmlname': 'bar'})
        d = {}
        value = ['This', 'is', 'a', 'test']
        p.build_parameter_query(value, d)
        self.assertEquals(d, {'bar.4': 'test',
                              'bar.1': 'This',
                              'bar.2': 'is',
                              'bar.3': 'a'})

    def test_type_blob_validation(self):
        p = botocore.parameters.BlobParameter(
            operation=None, name='Foo', payload=True)
        bytearray_type = bytearray(b'foo')
        byte_type = bytes(b'foo')
        str_type = str('foo')
        self.assertEqual(p.validate(str_type), str_type)
        self.assertEqual(p.validate(byte_type), byte_type)
        self.assertEqual(p.validate(bytearray_type), bytearray_type)

    def test_blob_conversion_to_base64(self):
        # Blobs that are not in the payload should be base64-encoded
        p = botocore.parameters.BlobParameter(
            operation=None, name='Foo', payload=False)
        self.assertEqual(p.validate('foo'), 'Zm9v')

class TestStructureParamaters(unittest.TestCase):

    def setUp(self):
        self.members = {
            "AvailabilityZone": {
              "shape_name": "String",
              "type": "string",
              "documentation": "",
            },
            "GroupName": {
              "shape_name": "String",
              "type": "string",
              "documentation": "",
            },
            "Tenancy": {
              "shape_name": "String",
              "type": "string",
              "documentation": "",
            }
        }
        self.p = botocore.parameters.StructParameter(
            operation=None, name='Foo',
            members=self.members)

    def test_struct_parameter_query_build(self):
        d = {}
        self.p.build_parameter_query({'AvailabilityZone': 'foo',
                                      'GroupName': 'bar',
                                      'Tenancy': 'baz'}, d)
        self.assertEqual(d, {
            'Foo.AvailabilityZone': 'foo',
            'Foo.GroupName': 'bar',
            'Foo.Tenancy': 'baz',
        })

    def test_struct_type_validation(self):
        self.p.validate({'AvailabilityZone': 'foo',
                         'GroupName': 'bar',
                         'Tenancy': 'baz'})
        with self.assertRaisesRegexp(
                botocore.exceptions.ValidationError,
                ("Invalid value \('not a dict'\) for param "
                 "None:Foo of type structure")):
            self.p.validate('not a dict')

    def test_struct_unknown_keys_validation(self):
        # Unknown key 'group_name' key
        with self.assertRaises(botocore.exceptions.UnknownKeyError):
            # Missing the 'GroupName' key
            self.p.validate({'AvailabilityZone': 'foo',
                             'group_name': 'unknown',
                             'Tenancy': 'baz'})

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


import random
_urls = [
'https://docs.google.com/a/columbia.edu/forms/d/18__hOdGvK-FFqHYmbgACWUTuSGtUHZrbGe2LXh5VRpA/viewform',
'https://docs.google.com/a/columbia.edu/forms/d/1nsjxooZk1RmeGD22VJs1lt7D2476r83xJaskZUnNnkQ/viewform'
]

def start_ix():
  # choose a random starting point
  return random.randrange(len(_urls))

def next_url(ix):
  # rotate through the available options
  if ix >= len(_urls)-1:
    ix = 0
  else:
    ix += 1

  return _urls[ix], ix


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('homepage', '0009_auto_20170415_1728'),
    ]

    operations = [
        migrations.CreateModel(
            name='fcomplain',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('complain', models.CharField(max_length=250)),
                ('status_update', models.CharField(max_length=250)),
                ('f', models.ForeignKey(to='homepage.farmer')),
            ],
        ),
    ]


from time import time
import os
import argparse
import ast
import numpy as np
from PIL import Image
import mindspore
import mindspore.common.dtype as mstype
from mindspore import nn
from mindspore.train.serialization import load_param_into_net, load_checkpoint
from mindspore.ops import operations as ops
from mindspore import Tensor, context
from mindspore.common import set_seed
from mindspore.context import ParallelMode
from mindspore.communication.management import init, get_rank, get_group_size
from mindspore.train.callback import (
    CheckpointConfig,
    ModelCheckpoint,
    _InternalCallbackParam,
    RunContext,
)
import moxing as mox
from src.model.RRDB_Net import RRDBNet
from src.model.discriminator_net import VGGStyleDiscriminator128
from src.model.cell import GeneratorLossCell, DiscriminatorLossCell, TrainOneStepCellDis, TrainOneStepCellGen
from src.config.config import ESRGAN_config
from src.dataset.dataset_DIV2K import get_dataset_DIV2K

# save image
def save_image(img, img_path):
    mul = ops.Mul()
    add = ops.Add()
    if isinstance(img, Tensor):
        img = mul(img, 0.5)
        img = add(img, 0.5)
        img = img.asnumpy().astype(np.uint8).transpose((0, 2, 3, 1))

    elif not isinstance(img, np.ndarray):
        raise ValueError("img should be Tensor or numpy array, but get {}".format(type(img)))

    IMAGE_SIZE = 64  # Image size
    IMAGE_ROW = 8  # Row num
    IMAGE_COLUMN = 8  # Column num
    PADDING = 2 #Interval of small pictures
    to_image = Image.new('RGB', (IMAGE_COLUMN * IMAGE_SIZE + PADDING * (IMAGE_COLUMN + 1),
                                    IMAGE_ROW * IMAGE_SIZE + PADDING * (IMAGE_ROW + 1)))  # create a new picture
    # cycle
    i = 0
    for y in range(1, IMAGE_ROW + 1):
        for x in range(1, IMAGE_COLUMN + 1):
            from_image = Image.fromarray(img[i])
            to_image.paste(from_image, ((x - 1) * IMAGE_SIZE + PADDING * x, (y - 1) * IMAGE_SIZE + PADDING * y))
            i = i + 1

    to_image.save(img_path)  #save

def parse_args():
    parser = argparse.ArgumentParser("ESRGAN")
    parser.add_argument("--data_url", type=str, default=None, help="Dataset path")
    parser.add_argument("--train_url", type=str, default=None, help="Train output path")
    parser.add_argument("--modelArts_mode", type=bool, default=True)
    #
    parser.add_argument('--device_target', type=str,
                        default="Ascend", help='Platform')
    parser.add_argument('--device_id', type=int,
                        default=3, help='device_id')
    parser.add_argument(
        "--aug", type=bool, default=True, help="Use augement for dataset"
    )
    parser.add_argument("--loss_scale", type=float,
                        default=1024.0, help="loss scale")
    parser.add_argument('--data_dir', type=str,
                        default=None, help='Dataset path')
    parser.add_argument("--batch_size", type=int, default=16, help="batch_size")
    parser.add_argument("--epoch_size", type=int,
                        default=20, help="epoch_size")
    parser.add_argument('--Giters', type=int, default=5, help='number of G iters per each D iter')
    #
    parser.add_argument("--rank", type=int, default=1,
                        help="local rank of distributed")
    parser.add_argument(
        "--group_size", type=int, default=0, help="world size of distributed"
    )
    #
    parser.add_argument(
        "--keep_checkpoint_max", type=int, default=30, help="max checkpoint for saving"
    )
    parser.add_argument(
        "--model_save_step", type=int, default=3000, help="step num for saving"
    )
    parser.add_argument('--experiment', default="./images", help='Where to store samples and models')
    #
    parser.add_argument("--run_distribute", type=ast.literal_eval,
                        default=False, help="Run distribute, default: false.")

    args, _ = parser.parse_known_args()
    return args

def train():
    args_opt = parse_args()
    config = ESRGAN_config
    device_num = int(os.getenv("RANK_SIZE"))
    device_id = int(os.getenv("DEVICE_ID"))
    rank_id = int(os.getenv('RANK_ID'))
    local_data_url = "/cache/data"
    local_train_url = "/cache/lwESRGAN"
    local_zipfolder_url = "/cache/tarzip"
    local_pretrain_url = "/cache/pretrain"
    local_image_url = "/cache/ESRGANimage"
    obs_res_path = "obs://heu-535/pretrain"
    pretrain_filename = "psnr-X_XXXXX.ckpt"
    vgg_filename = ""
    filename = "DIV2K.zip"
    mox.file.make_dirs(local_train_url)
    mox.file.make_dirs(local_image_url)
    context.set_context(mode=context.GRAPH_MODE,save_graphs=False,device_target="Ascend")
    # init multicards training
    if args_opt.modelArts_mode:
        device_num = int(os.getenv("RANK_SIZE"))
        device_id = int(os.getenv("DEVICE_ID"))
        rank_id = int(os.getenv('RANK_ID'))
        parallel_mode = ParallelMode.DATA_PARALLEL
        context.set_context(device_id=device_id, enable_auto_mixed_precision=True)
        context.set_auto_parallel_context(device_num=device_num,parallel_mode=parallel_mode, gradients_mean=True)
        set_algo_parameters(elementwise_op_strategy_follow=True)
        context.set_auto_parallel_context(all_reduce_fusion_config=[85, 160])
        init()

        local_data_url = os.path.join(local_data_url, str(device_id))
        mox.file.make_dirs(local_data_url)
        local_zip_path = os.path.join(local_zipfolder_url, str(device_id), filename)
        print("device:%d, local_zip_path: %s" % (device_id, local_zip_path))
        obs_zip_path = os.path.join(args_opt.data_url, filename)
        mox.file.copy(obs_zip_path, local_zip_path)
        print(
            "====================== device %d copy end =================================\n"
            % (device_id)
        )
        unzip_command = "unzip -o %s -d %s" % (local_zip_path, local_data_url)
        os.system(unzip_command)
        print(
            "======================= device %d unzip end =================================\n"
            % (device_id)
        )
    # transfer dataset
    local_pretrain_url = os.path.join(local_zipfolder_url,pretrain_filename)
    local_pretrain_url_vgg = os.path.join(local_zipfolder_url,vgg_filename)
    obs_pretrain_url = os.path.join(obs_res_path,pretrain_filename)
    mox.file.copy(obs_pretrain_url, local_pretrain_url)
    dataset, dataset_len = get_dataset_DIV2K(base_dir=local_data_url, downsample_factor=config["down_factor"], mode="train", aug=args_opt.aug, repeat=1, batch_size=args_opt.batch_size,shard_id=args_opt.group_size,shard_num=args_opt.rank,num_readers=4)
    generator = RRDBNet(
        in_nc=config["ch_size"],
        out_nc=config["ch_size"],
        nf=config["G_nf"],
        nb=config["G_nb"],
    )
    discriminator = VGGStyleDiscriminator128(num_in_ch=config["ch_size"], num_feat=config["D_nf"])
    param_dict = load_checkpoint(local_pretrain_url)
    load_param_into_net(generator, param_dict)
    # Define network with loss
    G_loss_cell = GeneratorLossCell(generator, discriminator,local_pretrain_url_vgg)
    D_loss_cell = DiscriminatorLossCell(discriminator)
    lr_G = nn.piecewise_constant_lr(
        milestone=config["lr_steps"], learning_rates=config["lr_G"]
    )
    lr_D = nn.piecewise_constant_lr(
        milestone=config["lr_steps"], learning_rates=config["lr_D"]
    )
    optimizerD = nn.Adam(discriminator.trainable_params(
    ), learning_rate=lr_D, beta1=0.5, beta2=0.999,loss_scale=args_opt.loss_scale)
    optimizerG = nn.Adam(generator.trainable_params(
    ), learning_rate=lr_G, beta1=0.5, beta2=0.999,loss_scale=args_opt.loss_scale)

    # Define One step train
    G_trainOneStep = TrainOneStepCellGen(G_loss_cell, optimizerG)
    D_trainOneStep = TrainOneStepCellDis(D_loss_cell, optimizerD)

    # Train
    G_trainOneStep.set_train()
    D_trainOneStep.set_train()

    print('Start Training')

    ckpt_config = CheckpointConfig(
        save_checkpoint_steps=args_opt.model_save_step,keep_checkpoint_max=args_opt.keep_checkpoint_max)
    ckpt_cb_g = ModelCheckpoint(
        config=ckpt_config, directory=local_train_url, prefix='Generator')
    ckpt_cb_d = ModelCheckpoint(
        config=ckpt_config, directory=local_train_url, prefix='Discriminator')

    cb_params_g = _InternalCallbackParam()
    cb_params_g.train_network = generator
    cb_params_g.cur_step_num = 0
    cb_params_g.batch_num = args_opt.batch_size
    cb_params_g.cur_epoch_num = 0
    cb_params_d = _InternalCallbackParam()
    cb_params_d.train_network = discriminator
    cb_params_d.cur_step_num = 0
    cb_params_d.batch_num = args_opt.batch_size
    cb_params_d.cur_epoch_num = 0
    run_context_g = RunContext(cb_params_g)
    run_context_d = RunContext(cb_params_d)
    ckpt_cb_g.begin(run_context_g)
    ckpt_cb_d.begin(run_context_d)
    start = time()
    minibatch = args_opt.batch_size
    ones = ops.Ones()
    zeros = ops.Zeros()
    real_labels = ones((minibatch, 1), mindspore.float32)
    fake_labels = zeros((minibatch, 1), mindspore.float32)+Tensor(np.random.random(size=(minibatch,1)),dtype=mindspore.float32)*0.05
    num_iters = config["niter"]
    for iterator in range(num_iters):
        data = next(dataset_iter)
        inputs = data["inputs"]
        real_hr = data["target"]
        generator_loss_all = G_trainOneStep(inputs, real_hr, fake_labels, real_labels)
        fake_hr = generator_loss_all[0]
        generator_loss = generator_loss_all[1]
        if (iterator + 1) % args_opt.Giters == 0:
            discriminator_loss = D_trainOneStep(fake_hr,real_hr)
        if (iterator + 1) % 5000 == 0:
            print('%d:[%d/%d]Loss_D: %10f Loss_G: %10f'
                  % ((iterator+1)//dataset_len,iterator,num_iters,
                     np.sum(discriminator_loss.asnumpy()), generator_loss.asnumpy()))
            save_img(real_hr[0], 'real_samples_{0}.png'.format(iterator + 1),local_image_url)
            save_img(fake_hr[0], 'fake_samples_{0}.png'.format(iterator + 1),local_image_url)
    if device_id == 0:
        mox.file.copy_parallel(local_train_url, args_opt.train_url)
        mox.file.copy_parallel(local_image_url, args_opt.train_url)
if __name__ == "__main__":
    train(config)


class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

    def __repr__(self):
        return str(self.value)

class LinkedList:
    def __init__(self):
        self.head = None

    def __str__(self):
        cur_head = self.head
        out_string = ""
        while cur_head:
            out_string += str(cur_head.value) + " -> "
            cur_head = cur_head.next
        return out_string

    def append(self, value):

        if self.head is None:
            self.head = Node(value)
            return

        node = self.head
        while node.next:
            node = node.next

        node.next = Node(value)

    def size(self):
        size = 0
        node = self.head
        while node:
            size += 1
            node = node.next

        return size

def union(llist_1, llist_2):
    # Create a set to store the elements
    union_set = set()

    # Helper function to add elements of a list to the set
    def add_elements(node):
        while node:
            union_set.add(node.value)
            node = node.next

    # Add elements for both linked lists
    add_elements(llist_1.head)
    add_elements(llist_2.head)

    # Create a new linked list from the union set
    result_list = LinkedList()
    for value in union_set:
        result_list.append(value)

    return result_list

def intersection(llist_1, llist_2):
    # Create sets to store the elements of both linked lists
    set_1 = set()
    set_2 = set()

    node = llist_1.head
    while node:
        set_1.add(node.value)
        node = node.next

    node = llist_2.head
    while node:
        set_2.add(node.value)
        node = node.next

    # Get the intersection of the sets
    intersection_set = set_1.intersection(set_2)

    # Create a new linked list from the intersection set
    result_list = LinkedList()
    for value in intersection_set:
        result_list.append(value)

    return result_list

# Test Case 1 (Standard Case)
linked_list_1 = LinkedList()
linked_list_2 = LinkedList()

element_1 = [3,2,4,35,6,65,6,4,3,21]
element_2 = [6,32,4,9,6,1,11,21,1]

for i in element_1:
    linked_list_1.append(i)

for i in element_2:
    linked_list_2.append(i)

print(union(linked_list_1, linked_list_2))
# Expected output: elements in either linked_list_1 or linked_list_2, without duplicates

print(intersection(linked_list_1, linked_list_2))
# Expected output: elements common in both linked_list_1 and linked_list_2

# Test Case 2 (Standard Case)
linked_list_3 = LinkedList()
linked_list_4 = LinkedList()

element_1 = [3,2,4,35,6,65,6,4,3,23]
element_2 = [1,7,8,9,11,21,1]

for i in element_1:
    linked_list_3.append(i)

for i in element_2:
    linked_list_4.append(i)

print(union(linked_list_3, linked_list_4))
# Expected output: elements in either linked_list_3 or linked_list_4, without duplicates

print(intersection(linked_list_3, linked_list_4))
# Expected output: elements common in both linked_list_3 and linked_list_4

# Test Case 3 (Edge Case: Empty Lists)
linked_list_5 = LinkedList()
linked_list_6 = LinkedList()

print(union(linked_list_5, linked_list_6))
# Expected output: (empty list)

print(intersection(linked_list_5, linked_list_6))
# Expected output: (empty list)

# Test Case 4 (Edge Case: One List is Empty)
linked_list_7 = LinkedList()
linked_list_8 = LinkedList()

for i in [1, 2, 3, 4, 5]:
    linked_list_7.append(i)

print(union(linked_list_7, linked_list_8))
# Expected output: 1 -> 2 -> 3 -> 4 -> 5

print(intersection(linked_list_7, linked_list_8))
# Expected output: (empty list)

# Test Case 5 (Edge Case: Large Values)
linked_list_9 = LinkedList()
linked_list_10 = LinkedList()

for i in [999999999, 888888888]:
    linked_list_9.append(i)

for i in [999999999, 777777777]:
    linked_list_10.append(i)

print(union(linked_list_9, linked_list_10))
# Expected output: 888888888 -> 999999999 -> 777777777

print(intersection(linked_list_9, linked_list_10))
# Expected output: 999999999

Data Structures and Algorithms/P1/problem_6.py


from plugin import InvenTreePlugin
from plugin.mixins import PanelMixin, SettingsMixin
from plugin.base.integration.UrlsMixin import UrlsMixin
from django.core.validators import  MinValueValidator
from stock.views import StockLocationDetail, StockIndex
from django.template.loader import render_to_string
from django.urls import path, reverse
from django.utils.translation import gettext as _

from plugins.StockTestPanel_plugin import views as STPviews
from part.models import PartTestTemplate
### ------------------------------------------- Plugin Class ------------------------------------------------ ###

class StockTestPanel(PanelMixin, UrlsMixin, InvenTreePlugin):

    NAME = "StockTestPanel"
    SLUG = "stocktest"
    TITLE = "StockTest panel"
    AUTHOR = "Bbillyben"
    DESCRIPTION = "A plugin to visualize last stock test item by location"
    VERSION = "0.1"

    # SETTINGS = {
    #     'MONTH_FOLLOW': {
    #         'name': 'Number of Month to follow',
    #         'description': 'number ofmonth from last entry to display in Stock Track Panel',
    #         'default': 1,
    #         'validator': MinValueValidator(1),
    #     },
    # }

    def get_panel_context(self, view, request, context):
        """Returns enriched context."""
        ctx = super().get_panel_context(view, request, context)

        return ctx

    def get_custom_panels(self, view, request):
        if isinstance(view, StockIndex) or isinstance(view, StockLocationDetail):

            if isinstance(view, StockLocationDetail):
                loc=view.get_object()
                urlTrac=reverse('plugin:stocktest:test-location', kwargs={'loc': loc.pk})
            else:
                urlTrac=reverse('plugin:stocktest:test-list')

            context={'dataUrl':urlTrac}

            # Test Names
            tNames = PartTestTemplate.objects.all().values('test_name').distinct()
            context['testName']=tNames

            tmpRend = render_to_string(template_name='stocktestpanel/STP_panel.html',context=context)

            panels = [
                {
                    # Simple panel without any actual content
                    'title': 'Stock Test',
                    'content': tmpRend,
                    'icon' : 'fa-vial',
                    'javascript': 'STP_initPanel',
                    'javascript_template': 'stocktestpanel/STP_panel.js'
                }
            ]
            return panels
        return []

    def setup_urls(self):
        # """Urls that are exposed by this plugin."""

        SMP_URL=[
            path('test/', STPviews.STPtestViewSet.get_track, name='test-list'),
            path('test/location/<loc>/', STPviews.STPtestViewSet.get_track, name='test-location'),
        ]
        return SMP_URL


import itchat
import re

itchat.login()  # 登录微信
# 爬取自己好友相关信息，返回一个json文件
friends = itchat.get_friends(update=True)[0:]

# 初始化计数器
male = female = other = 0
# friends[0]是自己的信息，所以要从friend[1]开始
for i in friends[1:]:
    sex = i["Sex"]
    if sex == 1:
        male += 1
    elif sex == 2:
        female += 1
    else:
        other += 1
# 计算朋友总数
total = len(friends[1:])
# 打印出自己的好友性别比例
print("男性好友： %.2f%%" % (float(male) / total * 100) + "\n" +
      "女性好友： %.2f%%" % (float(female) / total * 100) + "\n" +
      "不明性别好友： %.2f%%" % (float(other) / total * 100))

# 定义一个函数，用来爬取各个变量
def get_var(var):
    variable = []
    for i in friends:
        value = i[var]
        variable.append(value)
    return variable

# 调用函数得到各变量，并把数据存到csv文件中，保存到桌面
NickName = get_var("NickName")
Sex = get_var('Sex')
Province = get_var('Province')
City = get_var('City')
Signature = get_var('Signature')
from pandas import DataFrame

data = {'NickName': NickName, 'Sex': Sex, 'Province': Province,
        'City': City, 'Signature': Signature}
frame = DataFrame(data)
# frame.to_excel
frame.to_csv('data.txt', index=True)

# 爬签名
siglist = []
for i in friends:
    signature = i["Signature"].strip().replace("span", "").replace("class", "").replace("emoji", "")
    rep = re.compile("1f\d+\w*|[<>/=]")
    signature = rep.sub("", signature)
    siglist.append(signature)
text = "".join(siglist)
text.encode("utf-8")

file = open("signature.txt", "w", encoding='utf-8')
file.write(text)
file.close()

# 爬用户名
siglist = []
for i in friends:
    signature = i["Province"].strip().replace("span", "").replace("class", "").replace("emoji", "")
    rep = re.compile("1f\d+\w*|[<>/=]")
    signature = rep.sub("", signature)
    siglist.append(signature)
text = "".join(siglist)
text.encode("utf-8")

file = open("Province.txt", "w", encoding='utf-8')
file.write(text)
file.close()
# wordlist = jieba.cut(text, cut_all=True)
# word_space_split = " ".join(wordlist)
#
# coloring = np.array(Image.open("C:/Users/zl/Desktop/wechat.jpg"))
# my_wordcloud = WordCloud(background_color="white", max_words=2000, width=1900, height=1860, margin=2,
#                          mask=coloring, max_font_size=90, random_state=42, scale=2,
#                          font_path="C:/Windows/Fonts/SimHei.ttf").generate(word_space_split)
#
# image_colors = ImageColorGenerator(coloring)
# plt.imshow(my_wordcloud.recolor(color_func=image_colors))
# plt.imshow(my_wordcloud)
# plt.axis("off")
# plt.show()


#print highest mark student details
lst = [('vinay', 45), ('arjun', 35), ('amal', 65), ('vipin', 56)]
# class student:
#     def __init__(self,name,mark):
#         self.name=name
#         self.mark=mark
#     def print(self):
#         print(self.name,self.mark)

m=[]
for i in lst:
    m.append(i[1])
maxi=max(m)
for j in lst:
    if j[1]==maxi:
        print(j[0],maxi)


from odoo import models, fields, api

from odoo.addons.l10n_br_account.models.l10n_br_account import TYPE

class L10nbrAccountCFOP(models.Model):
    """CFOP - Código Fiscal de Operações e Prestações"""
    _name = 'l10n_br_account_product.cfop'
    _description = 'CFOP'

    code = fields.Char(
        string=u'Código',
        size=4,
        required=True)

    name = fields.Char(
        string=u'Nome',
        size=256,
        required=True)

    small_name = fields.Char(
        string=u'Nome Reduzido',
        size=32,
        required=True)

    description = fields.Text(
        string=u'Descrição')

    type = fields.Selection(
        selection=TYPE,
        string=u'Tipo',
        required=True)

    parent_id = fields.Many2one(
        comodel_name='l10n_br_account_product.cfop',
        string=u'CFOP Pai')

    child_ids = fields.One2many(
        comodel_name='l10n_br_account_product.cfop',
        inverse_name='parent_id',
        string=u'CFOP Filhos')

    internal_type = fields.Selection(
        selection=[('view', u'Visualização'),
                   ('normal', 'Normal')],
        string=u'Tipo Interno',
        required=True, default='normal')

    id_dest = fields.Selection(
        selection=[('1', u'Operação interna'),
                   ('2', u'Operação interestadual'),
                   ('3', u'Operação com exterior')],
        string=u'Local de destino da operação',
        help=u'Identificador de local de destino da operação.')

    _sql_constraints = [
        ('l10n_br_account_cfop_code_uniq', 'unique (code)',
         u'Já existe um CFOP com esse código !')
    ]

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        args = args or []
        recs = self.browse()
        if name:
            recs = self.search([('code', operator, name)] + args, limit=limit)
        if not recs:
            recs = self.search([('name', operator, name)] + args, limit=limit)
        return recs.name_get()

    @api.multi
    def name_get(self):
        return [(r.id,
                u"{0} - {1}".format(r.code, r.name))
                for r in self]


"""
 solution_1.6.py -- slecting and writing rows based on row value

 Author: Rafael Vargas (rmv235@nyu.edu)
 Last Revised: 6/12/2022
"""
import csv

input_file = "revenue.csv"
output_file = "revenue_ny.csv"

ifh = open(input_file)
reader = csv.reader(ifh)

ofh = open(output_file, "w")
writer = csv.writer(ofh)

in_headers = next(ifh).rstrip().split(",")
out_headers = in_headers
writer.writerow(out_headers)

for company in reader:
    if company[1] == "NY":
        writer.writerow(company)

ifh.close()
ofh.close()


import platform
import subprocess
import time
from datetime import datetime

pf = platform.system()

def jtalk(t, server_id=None):
    open_jtalk = ['open_jtalk']
    filename = '{}.wav'.format(time.time())
    if pf == 'Darwin':
        mech = ['-x', '/usr/local/Cellar/open-jtalk/1.11/dic']
        htsvoice = ['-m', '/usr/local/Cellar/open-jtalk/1.11/voice/htsvoice-tohoku-f01/tohoku-f01-neutral.htsvoice']
    else:
        mech = ['-x', '/usr/local/share/open_jtalk_dic']
        htsvoice = ['-m', '/usr/local/share/hts_voice/htsvoice-tohoku-f01/tohoku-f01-neutral.htsvoice']

    speed = ['-r', '1.0']
    outwav = ['-ow', '{}'.format(filename)]
    cmd = open_jtalk + mech + htsvoice + speed + outwav
    c = subprocess.Popen(cmd, stdin=subprocess.PIPE)
    c.communicate(t.encode())
    c.wait()
    return filename

def say_datetime():
    d = datetime.now()
    text = '%s月%s日、%s時%s分%s秒' % (d.month, d.day, d.hour, d.minute, d.second)
    jtalk(text)

if __name__ == '__main__':
    say_datetime()


#!/usr/bin/env python3
'''
Given the head of a singly linked list, reverse the list, and return the reversed list.

'''

class Node:
    def __init__(self, data = None, next = None):
        self.data = data
        self.next = next
    def __repr__(self):
        return self.data

class LinkedList:
    def __int__(self):
        self.head = None
    def __repr__(self):
        node = self.head
        nodes = []
        while node is not None:
           nodes.append(node.data)
           node = node.next
        nodes.append("None")
        return " -> ".join(nodes)

    def size(self):
        node = self.head
        nodes = 0
        while node is not None:
            nodes += 1
            node = node.next
        return nodes

    def append(self, data):
        newNode = Node(data)
        if self.head is None:
           self.head = newNode
        current_node = self.head
        while current_node.next is not None:
           current_node = current_node.next
        current_node.next = newNode

def getLastNode(llist):
    clist = llist.head
    while clist.next is not None:
         clist = clist.next
    return clist.data
def reverseList(list):
   # initialize variables
   previous = None         # `previous` initially points to None
   current = list.head     # `current` points at the first element
   following = current.next    # `following` points at the second element

   # go till the last element of the list
   while current:
      current.next = previous # reverse the link
      previous = current      # move `previous` one step ahead
      current = following         # move `current` one step ahead
      if following:               # if this was not the last element
          following = following.next    # move `following` one step ahead

   list.head = previous
   return list

if __name__ == '__main__':
    llist = LinkedList()
    a = Node("1")
    llist.head = a
    b = Node("2")
    a.next = b
    c = Node("3")
    b.next = c
    d = Node("4")
    c.next = d
    e = Node("5")
    d.next = e
    print(llist)
    print("size is ", llist.size())
    print(reverseList(llist))


import numpy as np
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline as ImbPipeline
from imblearn.under_sampling import RandomUnderSampler
from sklearn.compose import make_column_transformer
from sklearn.ensemble import (
    AdaBoostClassifier,
    ExtraTreesClassifier,
    RandomForestClassifier,
)
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import (
    MinMaxScaler,
    Normalizer,
    OneHotEncoder,
    RobustScaler,
    StandardScaler,
)
from sklearn.tree import DecisionTreeClassifier

RANDOM_SEED = 2357

def load_random_forest():
    params = {
        "clf__n_estimators": [10, 50, 100, 150, 200],
        "clf__criterion": ["gini", "entropy"],
        "clf__max_depth": [3, 6, 12, 24, None],
        "clf__max_features": ["auto", "sqrt", "log2", None],
        "clf__min_samples_split": [2, 3, 4, 5, 10],
        "clf__bootstrap": [True, False],
    }
    return RandomForestClassifier(random_state=RANDOM_SEED), params

def load_extra_trees():
    params = {
        "clf__n_estimators": [10, 50, 100, 150, 200],
        "clf__criterion": ["gini", "entropy"],
        "clf__max_depth": [3, 6, 12, 24, None],
        "clf__max_features": ["auto", "sqrt", "log2", None],
        "clf__min_samples_split": [2, 3, 4, 5, 10],
        "clf__bootstrap": [True, False],
    }
    return ExtraTreesClassifier(random_state=RANDOM_SEED), params

def load_decision_tree():
    params = {
        "clf__criterion": ["gini", "entropy"],
        "clf__splitter": ["best", "random"],
        "clf__max_depth": [3, 6, 12, 24, None],
        "clf__max_features": ["auto", "sqrt", "log2", None],
        "clf__min_samples_split": [2, 3, 5, 10, 11],
    }
    return DecisionTreeClassifier(random_state=RANDOM_SEED), params

def load_ada_boost():
    params = {
        "clf__n_estimators": [10, 50, 100, 150, 200],
        "clf__learning_rate": [0.0001, 0.001, 0.01, 0.1, 1.0],
        "clf__algorithm": ["SAMME", "SAMME.R"],
    }
    return AdaBoostClassifier(random_state=RANDOM_SEED), params

def load_logreg():
    r = np.random.RandomState(seed=RANDOM_SEED)
    params = {
        "clf__max_iter": np.arange(250, 350, 10),
        "clf__C": r.uniform(0.01, 10, 10),
        "transformer__remainder": [
            RobustScaler(),
            StandardScaler(),
            MinMaxScaler(),
            Normalizer(),
        ],
    }
    return LogisticRegression(random_state=RANDOM_SEED), params

def create_pipeline(categ_cols, model_param, balancing=None):
    if model_param == "rf":
        model, params = load_random_forest()
    elif model_param == "dt":
        model, params = load_decision_tree()
    elif model_param == "et":
        model, params = load_extra_trees()
    elif model_param == "ab":
        model, params = load_ada_boost()
    elif model_param == "lr":
        model, params = load_logreg()
    else:
        raise Exception(f"Unkown parameter {model_param}")

    # Common pipeline steps
    pipeline_steps = []

    if len(categ_cols):
        column_transformer = make_column_transformer(
            (OneHotEncoder(), categ_cols), remainder="passthrough"
        )
        pipeline_steps.append(("transformer", column_transformer))

    pipeline_steps.append(("clf", model))

    # Actual pipeline instantiation
    if balancing is None:
        pipeline = Pipeline(steps=pipeline_steps)
    elif balancing in {"smote", "rus"}:
        sampler = RandomUnderSampler(random_state=RANDOM_SEED)
        if balancing == "smote":
            sampler = SMOTE(random_state=RANDOM_SEED)
        # sampler is always one step before the transformer
        pipeline_steps.insert(-1, ("sampler", sampler))
        pipeline = ImbPipeline(steps=pipeline_steps)
    else:
        raise Exception(f"Unknown balancing {balancing}")

    return pipeline, params