"""
Contains models used to compute properties of interest from the Atom object.

So far, the only model implemented is the ISModel. More models will be added in future
releases.

Classes
-------
* :class:`ISModel` : Ion-sphere type model, static properties such as KS orbitals, \
                     density and energy are directly computed
"""

# import standard packages
import sys

# import external packages
from math import log, sqrt

# import internal packages
from . import check_inputs
from . import config
from . import staticKS
from . import convergence
from . import writeoutput
from . import xc
from atoMEC.postprocess import pressure

class ISModel:
    """
    The ISModel represents a particular family of AA models known as ion-sphere models.

    The implementation in atoMEC is based on the model described in [1]_.

    Parameter inputs for this model are related to particular choices of approximation,
    e.g. boundary conditions or exchange-correlation functional, rather than
    fundamental physical properties.

    Parameters
    ----------
    atom : atoMEC.Atom
        The main atom object
    xfunc_id : str or int, optional
        The exchange functional, can be the libxc code or string,
        or special internal value
        Default : "lda_x"
    cfunc_id : str or int, optional
        The correlation functional, can be the libxc code or string, or special
        internal value
        Default : "lda_c_pw"
    bc : str, optional
        The boundary condition, can be "dirichlet" or "neumann"
        Default : "dirichlet"
    spinpol : bool, optional
        Whether to run a spin-polarized calculation
        Default : False
    spinmag : int, optional
        The spin-magentization
        Default: 0 for nele even, 1 for nele odd
    unbound : str, optional
        The way in which the unbound electron density is computed
        Default : "ideal"
    v_shift : bool, optional
        Shifts the potential vertically by its value at the boundary, v(R_s)
        Default : True
    write_info : bool, optional
        Writes information about the model parameters
        Default : True

    Attributes
    ----------
    nele_tot: int
        total number of electrons
    nele: array_like
        number of electrons per spin channel (or total if spin unpolarized)

    References
    ----------
    .. [1] T. J. Callow, E. Kraisler, S. B. Hansen, and A. Cangi, (2021).
       First-principles derivation and properties of density-functional
       average-atom models, `arXiv:2103.09928 <https://arxiv.org/abs/2103.09928>`__.
    """

    def __init__(
        self,
        atom,
        xfunc_id=config.xfunc_id,
        cfunc_id=config.cfunc_id,
        bc=config.bc,
        spinpol=config.spinpol,
        spinmag=-1,
        unbound=config.unbound,
        v_shift=config.v_shift,
        write_info=True,
    ):
        # Input variables
        self.nele_tot = atom.nele
        self.spinpol = spinpol
        self.spinmag = spinmag
        self.xfunc_id = xfunc_id
        self.cfunc_id = cfunc_id
        self.bc = bc
        self.unbound = unbound
        self.v_shift = v_shift

        # print the information
        if write_info:
            print(self.info)

    @property
    def spinpol(self):
        """bool: Whether calculation will be spin-polarized."""
        return self._spinpol

    @spinpol.setter
    def spinpol(self, spinpol):
        self._spinpol = check_inputs.ISModel.check_spinpol(spinpol)
        # define the leading dimension for KS quantities (density, orbs, pot)
        if self._spinpol:
            config.spindims = 2
        else:
            config.spindims = 1

        try:
            # compute the no of electrons in each spin channel
            self.nele = check_inputs.ISModel.calc_nele(
                self.spinmag, self.nele_tot, self.spinpol
            )
            config.nele = self.nele
        except AttributeError:
            pass

        # reset the x and c functionals if spinpol changes
        try:
            config.xfunc = xc.set_xc_func(self._xfunc_id)
            config.cfunc = xc.set_xc_func(self._cfunc_id)
        except AttributeError:
            pass

    @property
    def spinmag(self):
        """int: the spin magentization (difference in no. up/down spin electrons)."""
        return self._spinmag

    @spinmag.setter
    def spinmag(self, spinmag):
        self._spinmag = check_inputs.ISModel.check_spinmag(spinmag, self.nele_tot)
        try:
            # compute the no of electrons in each spin channel
            self.nele = check_inputs.ISModel.calc_nele(
                self.spinmag, self.nele_tot, self.spinpol
            )
            config.nele = self.nele
        except AttributeError:
            pass

    @property
    def xfunc_id(self):
        """str: exchange functional shorthand id."""
        return self._xfunc_id

    @xfunc_id.setter
    def xfunc_id(self, xfunc_id):
        self._xfunc_id = check_inputs.ISModel.check_xc(xfunc_id, "exchange")
        # define the exchange func object
        config.xfunc = xc.set_xc_func(self._xfunc_id)

    @property
    def cfunc_id(self):
        """str: correlation functional shorthand id."""
        return self._cfunc_id

    @cfunc_id.setter
    def cfunc_id(self, cfunc_id):
        self._cfunc_id = check_inputs.ISModel.check_xc(cfunc_id, "correlation")
        # define the correlation func object
        config.cfunc = xc.set_xc_func(self._cfunc_id)

    @property
    def bc(self):
        """str: boundary condition for solving the KS equations in a finite sphere."""
        return self._bc

    @bc.setter
    def bc(self, bc):
        self._bc = check_inputs.ISModel.check_bc(bc)
        config.bc = self._bc

    @property
    def unbound(self):
        """str: the treatment of unbound/free electrons."""
        return self._unbound

    @unbound.setter
    def unbound(self, unbound):
        self._unbound = check_inputs.ISModel.check_unbound(unbound, self.bc)
        config.unbound = self._unbound

    @property
    def v_shift(self):
        """bool: shift the potential vertically by a constant."""
        return self._v_shift

    @v_shift.setter
    def v_shift(self, v_shift):
        self._v_shift = check_inputs.ISModel.check_v_shift(v_shift)
        config.v_shift = self._v_shift

    @property
    def info(self):
        """str: formatted description of the ISModel attributes."""
        return writeoutput.write_ISModel_data(self)

    @writeoutput.timing
    def CalcEnergy(
        self,
        nmax,
        lmax,
        grid_params={},
        conv_params={},
        scf_params={},
        band_params={},
        force_bound=[],
        grid_type="sqrt",
        verbosity=0,
        write_info=True,
        write_density=True,
        write_potential=True,
        write_eigs_occs=True,
        write_dos=True,
        density_file="density.csv",
        potential_file="potential.csv",
        eigs_occs_file="eigs_occs.csv",
        dos_file="dos.csv",
        guess=False,
        guess_pot=0,
    ):
        r"""
        Run a self-consistent calculation to minimize the Kohn-Sham free energy.

        Parameters
        ----------
        nmax : int
            maximum no. eigenvalues to compute for each value of angular momentum
        lmax : int
            maximum no. angular momentum eigenfunctions to consider
        grid_params : dict, optional
            dictionary of grid parameters as follows:
            {
            `ngrid` (``int``)        : number of grid points,
            `x0`    (``float``)      : LHS grid point takes form
            :math:`r_0=\exp(x_0)`; :math:`x_0` can be specified,
            `ngrid_coarse` (``int``) : (smaller) number of grid points for estimation
            of eigenvalues with full diagonalization
            }
        conv_params : dict, optional
            dictionary of convergence parameters as follows:
            {
            `econv` (``float``)  : convergence for total energy,
            `nconv` (``float``)  : convergence for density,
            `vconv` (``float``)  : convergence for electron number,
            `eigtol` (``float``) : convergence for eigenvalues,
            `bandtol` (``float``) : tolerance for n(l)max warning
            }
        scf_params : dict, optional
            dictionary for scf cycle parameters as follows:
            {
            `maxscf`  (``int``)   : maximum number of scf cycles,
            `mixfrac` (``float``) : density mixing fraction
            }
        band_params : dict, optional
            dictionary for band parameters as follows:
            {
            `nkpts`   (``int``)   : number of levels per band,
            `de_min`   (``float``) : minimum energy gap to make a band
            }
        force_bound : list of list of ints, optional
            force certain levels to be bound, for example:
            `force_bound = [0, 1, 0]`
            forces the orbital with quantum numbers :math:`\sigma=0,\ l=1,\ n=0` to be
            always bound even if it has positive energy. This prevents convergence
            issues.
        grid_type : str, optional
            the transformed radial grid used for the KS equations.
            can be 'sqrt' (default) or 'log'
        verbosity : int, optional
            how much information is printed at each SCF cycle.
            `verbosity=0` prints the total energy and convergence values (default).
            `verbosity=1` prints the above and the KS eigenvalues and occupations.
        write_info : bool, optional
            prints the scf cycle and final parameters
            default: True
        write_density : bool, optional
            writes the density to a text file
            default: True
        write_potential : bool, optional
            writes the potential to a text file
            default: True
        density_file : str, optional
            name of the file to write the density to
            default: `density.csv`
        potential_file : str, optional
            name of the file to write the potential to
            default: `potential.csv`
        eigs_occs_file : str, optional
            filename for the orbital energies and occupations
            default: `eigs_occs`
        dos_file : str, optional
            filename for the density-of-states and fd distribution
            default: `dos`
        guess : bool, optional
            use coulomb pot (guess=False) or given pot (guess=True) as initial guess
        guess_pot : numpy array, optional
            initial guess for the potential

        Returns
        -------
        output_dict : dict
            dictionary containing final KS quantities as follows:
            {
            `energy` (:obj:`staticKS.Energy`)       : total energy object,
            `density` (:obj:`staticKS.Density`)     : density object,
            `potential` (:obj:`staticKS.Potential`)  : potential object,
            `orbitals` (:obj:`staticKS.Orbitals`)    : orbitals object
            }
        """
        # boundary cond, unbound electrons, xc func objects
        config.bc = self.bc
        config.unbound = self.unbound

        # reset global parameters if they are changed
        config.nmax = nmax
        config.lmax = lmax
        config.grid_params = check_inputs.EnergyCalcs.check_grid_params(grid_params)
        config.conv_params = check_inputs.EnergyCalcs.check_conv_params(conv_params)
        config.scf_params = check_inputs.EnergyCalcs.check_scf_params(scf_params)
        config.band_params = check_inputs.EnergyCalcs.check_band_params(band_params)
        config.grid_type = check_inputs.EnergyCalcs.check_grid_type(grid_type)

        # experimental change
        config.force_bound = force_bound

        # set up the xgrid and rgrid
        if config.grid_type == "log":
            xgrid, rgrid = staticKS.log_grid(log(config.r_s))
        else:
            xgrid, rgrid = staticKS.sqrt_grid(sqrt(config.r_s))

        # initialize orbitals
        orbs = staticKS.Orbitals(xgrid, grid_type)
        # use coulomb potential or input given potential as initial guess
        if guess:
            v_init = guess_pot
        else:
            v_init = staticKS.Potential.calc_v_en(xgrid, grid_type)
        v_s_old = v_init  # initialize the old potential
        orbs.compute(v_init, config.bc, init=True, eig_guess=True)

        # occupy orbitals
        orbs.occupy()

        # write the initial spiel
        scf_init = writeoutput.SCF.write_init()
        if write_info:
            print(scf_init)

        # initialize the convergence object
        conv = convergence.SCF(xgrid, grid_type)

        for iscf in range(config.scf_params["maxscf"]):
            # print orbitals and occupations
            if verbosity == 1:
                eigs, occs = writeoutput.SCF.write_orb_info(orbs)
                print("\n" + "Orbital eigenvalues (Ha) :" + "\n\n" + eigs)
                print("Orbital occupations (2l+1) * f_{nl} :" + "\n\n" + occs)

            # construct density
            rho = staticKS.Density(orbs)

            # construct potential
            pot = staticKS.Potential(rho)

            # compute energies
            energy = staticKS.Energy(orbs, rho)
            E_free = energy.F_tot

            # mix potential
            if iscf > 1:
                alpha = config.scf_params["mixfrac"]
                v_s = alpha * pot.v_s + (1 - alpha) * v_s_old
            else:
                v_s = pot.v_s

            # shift potential
            if config.v_shift:
                for i in range(config.spindims):
                    v_s[i, :] = v_s[i, :] - v_s[i, -1]

            # update the orbitals with the KS potential
            if iscf < 3:
                orbs.compute(v_s, config.bc, eig_guess=True)
            else:
                orbs.compute(v_s, config.bc)
            orbs.occupy()

            # update old potential
            v_s_old = v_s

            # test convergence
            conv_vals = conv.check_conv(E_free, v_s, rho.total, iscf)

            # write scf output
            scf_string = writeoutput.SCF.write_cycle(iscf, E_free, conv_vals)
            if write_info:
                print(scf_string)

            # exit if converged
            if conv_vals["complete"]:
                break

        # compute final density and energy
        rho = staticKS.Density(orbs)
        energy = staticKS.Energy(orbs, rho)

        # write final output
        scf_final = writeoutput.SCF().write_final(energy, orbs, rho, conv_vals)
        if write_info:
            print(scf_final)

        # write the density to file
        if write_density:
            writeoutput.density_to_csv(rgrid, rho, density_file)

        # write the potential to file
        if write_potential:
            writeoutput.potential_to_csv(rgrid, pot, potential_file)

        # write the eigs and their occs to file
        if write_eigs_occs:
            writeoutput.eigs_occs_to_csv(orbs, eigs_occs_file)

        # write the dos to file if using bands bc
        if config.bc == "bands" and write_dos:
            writeoutput.dos_to_csv(orbs, dos_file)

        output_dict = {
            "energy": energy,
            "density": rho,
            "potential": pot,
            "orbitals": orbs,
        }

        return output_dict

    def CalcPressure(
        self,
        atom,
        energy_output,
        nmax=None,
        lmax=None,
        conv_params={},
        scf_params={},
        band_params={},
        force_bound=[],
        write_info=False,
        verbosity=0,
        dR=0.01,
        method="A",
    ):
        r"""
        Calculate the electronic pressure using the finite differences method.

        N.B.: This is just a wrapper for the postprocess.pressure.finite_diff function.
        It is maintained to support backwards compatibility until next major release.

        Parameters
        ----------
        atom : atoMEC.Atom
            The main atom object
        energy_output : dict
            output parameters of the function CalcEnergy
        conv_params : dict, optional
            dictionary of convergence parameters as follows:
            {
            `econv` (``float``)  : convergence for total energy,
            `nconv` (``float``)  : convergence for density,
            `vconv` (``float``)  : convergence for electron number,
            `eigtol` (``float``) : tolerance for eigenvalues
            }
        scf_params : dict, optional
           dictionary for scf cycle parameters as follows:
           {
           `maxscf`  (``int``)   : maximum number of scf cycles,
           `mixfrac` (``float``) : density mixing fraction
           }
        force_bound : list of list of ints, optional
            force certain levels to be bound, for example:
            `force_bound = [0, 1, 0]`
            forces the orbital quith quantum numbers :math:`\sigma=0,\ l=1,\ n=0` to be
            always bound even if it has positive energy. This prevents convergence
            issues.
        verbosity : int, optional
            how much information is printed at each SCF cycle.
            `verbosity=0` prints the total energy and convergence values (default)
            `verbosity=1` prints the above and the KS eigenvalues and occupations.
        write_info : bool, optional
            prints the scf cycle and final parameters
            defaults to False
        dR : float, optional
            radius difference for finite difference calculation
            defaults to 0.01

        Returns
        -------
        P_e : float
            electronic pressure in Ha
        """
        # for backwards compatibility: nmax and lmax will be removed in 2.x
        if nmax is not None or lmax is not None:
            sys.exit("nmax and lmax must inherit from CalcEnergy output")

        # call the finite diff function
        P_e = pressure.finite_diff(
            atom,
            self,
            energy_output["orbitals"],
            energy_output["potential"],
            conv_params,
            scf_params,
            force_bound,
            write_info,
            verbosity,
            dR,
            method,
        )

        return P_e


'''
Given an integer k and a binary search tree, find the floor (less than or equal to) of k,
and the ceiling (larger than or equal to) of k. If either does not exist, then print them as None.
'''

class Treenode:
    def __init__(self,value=None, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

class Solution:
    def floor_ceil_of_bst(self, node, k):
        answer = [None, None]

        if root == None:
            return answer

        stack = []
        sorted_nums = []

        curr = root

        #inorder traversal
        while (curr != None or len(stack) != 0):
            while (curr != None):
                stack.append(curr)
                curr = curr.left

            curr = stack.pop()

            if (curr.value < k):
                answer[0] = curr.value
            elif (curr.value > k and answer[1] == None):
                answer[1] = curr.value
                return answer
            else: #what if we find k? [k,k]?
                return [k,k]

            curr = curr.right

        return answer

    def print_stack(self, stack):
        vals = []
        for each_node in stack:
            vals.append(each_node.value)

        print(vals)

# node5 = Treenode(10)
# node6 = Treenode(14)
# node2 = Treenode(2)
# node3 = Treenode(6)
# node1 = Treenode(4,node2,node3)
# node4 = Treenode(12,node5,node6)
# root = Treenode(8,node1,node4)

node1 = Treenode(5)
node2 = Treenode(12)
root = Treenode(10, node1,node2)

solution = Solution()
k = 5
print(solution.floor_ceil_of_bst(root, k))


import os

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from models import ConvertRequest, Base

class Database(object):
    """
    Controls database operations, viz. add, delete, update, retrieve.
    """

    db_connection_string = None
    engine = None
    session_maker = None

    def __init__(self, path, echo):
        if not os.path.exists(os.path.dirname(path)):
            raise Exception("Path doesn't exists.")
        Database.db_connection_string = "sqlite:///" + path
        Database.engine = create_engine(Database.db_connection_string, echo=echo)
        Database.session_maker = sessionmaker(bind=Database.engine)
        Base.metadata.create_all(Database.engine)
        self.session = None

    def add(self, cr: ConvertRequest):
        """
        Adds an object to database.
        :param cr: The object to store.
        :return: Database addition result.
        """
        try:
            self.session.add(cr)
            self.session.commit()
            return True
        except:
            return False

    def retrieve(self, id):
        """
        Retrieves a record from the database.
        :param id: The conversion job id to retrieve.
        :return:
        """
        req = self.session.query(ConvertRequest).filter_by(id=id).first()
        return req

    def update(self):
        """
        Updates a database record.
        :return:
        """
        self.session.commit()
        pass

    def renew(self):
        """
        Renews the session to database.
        :return:
        """
        self.session = Database.session_maker()

    def finalize(self):
        """
        Close session and commit changes to database.
        :return:
        """
        self.session.commit()
        self.session.close()


hallo = list("hallo")
klempner = list("klempner")
das = list("das")
ist = list("ist")
fantastisch = list("fantastisch")
fluggegecheimen = list("fluggegecheimen")

list = []

list.extend(hallo)
list.extend(klempner)
list.extend(das)
list.extend(ist)
list.extend(fantastisch)
list.extend(fluggegecheimen)

dict = {}

for i in list:
    dict[i] = list.count(i) / len(list)

stopWord = input()
res = 1
for i in range(0, len(stopWord)):
    res *= dict[stopWord[i]] if dict.__contains__(stopWord[i]) else 0

print(res)


import numpy as np
import pandas as pd
from sklearn.preprocessing import RobustScaler, MinMaxScaler, StandardScaler

def scale_data(train, validate, test, scale_type = None, to_scale = None):
    '''
    returns scaled data of specified type into data frame, will
    '''
    train_copy = train.copy()
    validate_copy = validate.copy()
    test_copy = test.copy()

    if to_scale == None:
        return train_copy, validate_copy, test_copy

    else:
        X_train = train_copy[to_scale]
        X_validate = validate_copy[to_scale]
        X_test = test_copy[to_scale]

        min_max_scaler = MinMaxScaler()
        robust_scaler = RobustScaler()
        standard_scaler = StandardScaler()

        min_max_scaler.fit(X_train)
        robust_scaler.fit(X_train)
        standard_scaler.fit(X_train)

        mmX_train_scaled = min_max_scaler.transform(X_train)
        rX_train_scaled = robust_scaler.transform(X_train)
        sX_train_scaled = standard_scaler.transform(X_train)

        mmX_validate_scaled = min_max_scaler.transform(X_validate)
        rX_validate_scaled = robust_scaler.transform(X_validate)
        sX_validate_scaled = standard_scaler.transform(X_validate)

        mmX_test_scaled = min_max_scaler.transform(X_test)
        rX_test_scaled = robust_scaler.transform(X_test)
        sX_test_scaled = standard_scaler.transform(X_test)

        mmX_train_scaled = pd.DataFrame(mmX_train_scaled, columns=X_train.columns)
        mmX_validate_scaled = pd.DataFrame(mmX_validate_scaled, columns=X_validate.columns)
        mmX_test_scaled = pd.DataFrame(mmX_test_scaled, columns=X_test.columns)

        rX_train_scaled = pd.DataFrame(rX_train_scaled, columns=X_train.columns)
        rX_validate_scaled = pd.DataFrame(rX_validate_scaled, columns=X_validate.columns)
        rX_test_scaled = pd.DataFrame(rX_test_scaled, columns=X_test.columns)

        sX_train_scaled = pd.DataFrame(sX_train_scaled, columns=X_train.columns)
        sX_validate_scaled = pd.DataFrame(sX_validate_scaled, columns=X_validate.columns)
        sX_test_scaled = pd.DataFrame(sX_test_scaled, columns=X_test.columns)

    if scale_type == 'MinMax':
        for i in mmX_train_scaled:
            train_copy[i] = mmX_train_scaled[i].values
            validate_copy[i] = mmX_validate_scaled[i].values
            test_copy[i] = mmX_test_scaled[i].values
    elif scale_type == 'Robust':
        for i in rX_train_scaled:
            train_copy[i] = rX_train_scaled[i].values
            validate_copy[i] = rX_validate_scaled[i].values
            test_copy[i] = rX_test_scaled[i].values
    elif scale_type == 'Standard':
          for i in sX_train_scaled:
            train_copy[i] = sX_train_scaled[i].values
            validate_copy[i] = sX_validate_scaled[i].values
            test_copy[i] = sX_test_scaled[i].values
    return train_copy, validate_copy, test_copy


from app.MicStream import MicStream
import pyaudio

class MicStreamBuilder():
    DEFAULT_CHANNEL = 2

    def build(self, format_bit: int, rate: int, frames: int):
        """マイクの入力ストリーム生成し返却します。
        デバイスを0番から順番に探し、名前によって利用できるマイクか判定します。
        予定出力チャンネルでのストリーム開設を目指すが、失敗したらチャンネル数を1減らします。"""
        print("Creating mic stream...")
        audio = pyaudio.PyAudio()
        mic_stream = None
        for channel in range(self.DEFAULT_CHANNEL, 0, -1):
            for i in range(audio.get_device_count()):
                try:
                    device_info = audio.get_device_info_by_index(i)
                    device_name: str = device_info["name"]
                    if "USB" in device_name:  # 名前に USB を含むデバイスならストリームを作成
                        # pyaudioのformatにはビット数の半分を指定する
                        stream = audio.open(format=format_bit//2,
                                            channels=channel,
                                            rate=rate,
                                            input=True,
                                            input_device_index=i, frames_per_buffer=frames)
                        mic_stream = MicStream(stream, format_bit, channel)
                        print(
                            f"Mic stream created with {device_info}")
                        break
                except OSError:  # 希望したチャンネル数にデバイスが対応していないなど
                    pass
        if mic_stream == None:
            print("[WARN] Creating mic stream failed")
        return mic_stream


import cv2
image=cv2.imread("c.jpeg")
cv2.namedWindow('Original', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Original', 350,350)
cv2.imshow('Original',image)

grey_image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.namedWindow('Greyscale', cv2.WINDOW_NORMAL)
cv2.resizeWindow('Greyscale', 350,350)
cv2.imshow('Greyscale',grey_image)
#cv2.imwrite("01.jpg",grey_image)

cv2.waitKey(0)

cv2.destroyAllWindows()


"""
small_matrix_app.matrix_app.db_widget.py
This widgets writes data to or loads data from disk
"""

import os

import h5py

from PyQt5 import QtWidgets

from typing import List

import numpy as np

from os import mkdir, remove, path, listdir
from os.path import isfile, join

from matrix_app.all_exceptions import (
    FailureMessage,
    CriticalFailure,
    InternalDbError,
)

class DisplayData:
    def __init__(self, label: str, data):
        """Class for have an organized way of keeping label with data """
        self.label = label
        self.data = data

    def __str__(self):
        return str(self.label) + ":\n" + str(self.data) + "\n"

class RunData:
    def __init__(
        self,
        run_name: str,
        matrices: List[DisplayData],
        stats: List[DisplayData],
        saved: bool = False,
        random: str = None,
    ):
        """
        Class for hold matrices and their stats
        Args:
        run_name -- name of the run
        matrices -- the two entered matrices and their product
        stats -- any calculated stats for a given run
        saved -- whether the run was previously saved
        """
        self.run_name = run_name
        self.matrices = matrices
        self.stats = stats
        self.saved = saved
        if random is None:
            self.random = ""
        else:
            self.random = random

    def __str__(self):
        basestr = self.run_name + ":\n Matrices:\n"
        for m in self.matrices:
            basestr += str(m)
        basestr += "Stats:\n"
        for s in self.stats:
            basestr += str(s)
        basestr += "Saved: " + str(self.saved) + "\n"
        return basestr

class DatabaseModel(QtWidgets.QWidget):
    MATRIX_GROUP = "matrices"
    STATS_GROUP = "stats"
    NO_STATS_RUN = "-No_Stats_Run"

    def __init__(self, DB_Name="SavedRuns", parent=None):
        """ Create DB and reads in any pre-existing data into relevant models"""
        super().__init__()
        self.db_name = DB_Name
        self._db_name_f = self.db_name + "/"
        self._past_runs = {}  # for loading the SavedRunsPage()
        self._past_runs_list = []
        self._set_up_db()

    def _set_up_db(self):
        if path.exists(self.db_name):
            if path.isdir(self.db_name):
                pass
            else:
                raise CriticalFailure(
                    "Cannot create DB, "
                    + self.db_name
                    + ", as there is a file that already exists with that name. "
                )
        else:
            mkdir(self.db_name)

        prev_run_files = [
            f
            for f in listdir(self._db_name_f)
            if isfile(join(self._db_name_f, f)) and f.endswith(".h5")
        ]
        for prf in prev_run_files:
            run_name = prf.split(".")[0].split("-")[
                0
            ]  # Doesn't matter is there is a run1-No_Stats_Run and a run1 because load will get the fullest version
            self._past_runs[run_name] = 1
            self._past_runs_list.append(run_name)

    def get_previous_runs(self):
        return list(self._past_runs.keys())

    def load_run(self, run_name: str) -> (RunData):
        """ Return data for a particular run"""
        run_data = RunData("", None, None)
        matrices = []
        stats = []
        run_file = self._db_name_f + run_name + ".h5"
        if not path.exists(run_file):
            run_file = self._db_name_f + run_name + self.NO_STATS_RUN + ".h5"
            if not path.exists(run_file):
                raise InternalDbError("ERROR: File does not exist")
        try:
            with h5py.File(run_file, "r") as hdf:
                matrix_group = hdf.get(self.MATRIX_GROUP)

                for mgi in list(matrix_group.keys()):
                    dd = DisplayData(mgi, np.array(matrix_group[mgi]))
                    matrices.append(dd)

                # Only get stats if stats were saved
                if not self.NO_STATS_RUN in run_file:
                    stats_group = hdf.get(self.STATS_GROUP)
                    for sgi in list(stats_group.keys()):
                        dd = DisplayData(sgi, np.array(stats_group[sgi]))
                        stats.append(dd)
        except Exception as e:
            raise InternalDbError(
                "ERROR: Could not read saved .h5 file. ERROR: " + str(e)
            )

        run_data.run_name = run_name
        run_data.matrices = matrices
        run_data.stats = stats
        run_data.saved = True
        return run_data

    def save_run(self, c_run: RunData) -> FailureMessage:
        """save data for a particular run to disk"""
        # error if run already exists
        run_name = c_run.run_name
        run_file = self._db_name_f + run_name + ".h5"
        if path.exists(run_file):
            return FailureMessage("ERROR: Saved File (all stats) already exists")

        if len(c_run.stats) < 1:
            run_file = self._db_name_f + run_name + self.NO_STATS_RUN + ".h5"
            if path.exists(run_file):
                return FailureMessage("ERROR: Saved File (no stats) already exists")
        if run_name in self._past_runs:
            if self._past_runs[run_name] != c_run.random:
                return FailureMessage(
                    "ERROR: Saved File already exists with that run name"
                )
        try:
            with h5py.File(run_file, "w") as hdf:
                matrix_group = hdf.create_group(self.MATRIX_GROUP)
                for m in c_run.matrices:
                    matrix_group.create_dataset(m.label, data=m.data)

                stats_group = hdf.create_group(self.STATS_GROUP)
                for s in c_run.stats:
                    stats_group.create_dataset(s.label, data=s.data)
            if self.NO_STATS_RUN not in run_file:
                if path.exists(self._db_name_f + run_name + self.NO_STATS_RUN + ".h5"):
                    os.remove(self._db_name_f + run_name + self.NO_STATS_RUN + ".h5")
        except Exception as e:
            if path.exists(run_file):
                os.remove(run_file)
            return FailureMessage("ERROR: Could not save file: " + str(e))
        self._past_runs[run_name] = c_run.random
        return None


import time

import numpy as np

from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import ops
from tensorflow.python.ops import collective_ops
from tensorflow.python.platform import test

class CollectiveOpBenchmark(test.Benchmark):
  """Benchmarks for local CPU collective op execution."""

  def benchmark_collective(self):
    """Measures the performance of local CPU collective execution."""
    shapes = [(10,), (1000,), (1000000,)]
    devices = [2, 4, 8]
    collective_key_counter = 0

    for group_size in devices:
      group_key = collective_key_counter
      instance_key = collective_key_counter
      collective_key_counter += 1

      for shape in shapes:
        config = config_pb2.ConfigProto(device_count={"CPU": group_size})
        with session.Session(config=config) as sess:
          # Use a C++ callable to minimize the Python overhead in the benchmark.
          callable_opts = config_pb2.CallableOptions()
          reduce_ops = []
          for device in range(group_size):
            with ops.device("CPU:{}".format(device)):
              t = constant_op.constant(np.multiply(range(shape[0]), 1.0))
              r = collective_ops.all_reduce(t, group_size, group_key,
                                            instance_key, "Add", "Div")
              reduce_ops.append(r)
              callable_opts.target.append(r.name)
          op_callable = sess._make_callable_from_options(callable_opts)  # pylint: disable=protected-access

          # Run five steps to warm up the session caches and do collective param
          # resolution before taking the first measurement.
          for _ in range(5):
            op_callable()
          deltas = []
          overall_start = time.time()
          # Run at least five repetitions and for at least five seconds.
          while len(deltas) < 5 or time.time() - overall_start < 5.0:
            start = time.time()
            for _ in range(100):
              op_callable()
            end = time.time()
            deltas.append(end - start)
          del op_callable

        median_wall_time = np.median(deltas) / 100.0
        iters = len(deltas) * 100

        self.report_benchmark(
            iters=iters, wall_time=median_wall_time,
            name="num_elements_{}_num_devices_{}".format(np.prod(shape),
                                                         group_size))

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


from sys import stdin

class Card:
    def __init__(self, ncard, date):
        self.date = date
        self.ncard = int(ncard)

class User:
    def __init__(self, username, card):
        self.username = username
        self.card = []
        self.card.append(card)

class No:

    def __init__(self, user, height, parent, left, right):
        self.user = user
        self.left = left
        self.right = right
        self.height = height
        self.parent = parent

class AVLTree:
    def __init__(self):
        self.root = None

    def find(self, username, no):
        if no is None:
            return None
        if username > no.user.username:
            return self.find(username, no.right)
        elif username < no.user.username:
            return self.find(username, no.left)
        return no

    def Consulta(self, username):
        no = None
        if self.root is None:
            return None
        elif self.root:
            no = self.find(username, self.root)
        for i in no.user.card:
            print(str(i.ncard) + i.date)
        print("FIM")
        return no

    def left_rotate(self, child, no):
        if child.left:
            no.right = child.left
            no.right.parent = no
        else:
            no.right_child = None
        if no != self.root:
            child.parent = no.parent
            no.parent.right = child
        else:
            child.parent = None
            self.root = child
        child.left = no
        no.parent = child
        no.height = no.height - 1

    def right_rotate(self, child, no):
        if child.right:
            no.left = child.right
            no.left.parent = no
        else:
            no.left = None
        if no != self.root:
            child.parent = no.parent
            no.parent.left = child
        else:
            child.parent = None
            self.root = child
        child.right = no
        no.parent = child
        no.height = no.height - 1

    def rotate(self, no):
        global left_height, right_height
        if no.left:
            left_height = no.left.height
        if no.right:
            right_height = no.right.height
        if abs(left_height - right_height) > 1:
            if left_height < right_height:
                self.left_rotate(no, no.right)
            else:
                self.right_rotate(no, no.left)
        else:
            no.height = max(left_height, right_height) + 1

    def insert(self, username, ncard, date, no):
        if username < no.user.usernam:
            if not no.left:
                no.left = No(User(username, Card(ncard, date)), None, no, no.left, None)
                return no.left
            return self.insert(username, ncard, date, no.lefte)
        elif username > no.user.username:
            if not no.right:
                no.right = No(User(username, Card(ncard, date)), None, no, None, no.right)
                return no.right
            return self.insert(username, ncard, date, no.right)

    def grow(self, no):
        if not no:
            return None
        else:
            self.rotate(no)
            return self.grow(no.parent)

    def Acrescenta(self, username, ncard, date):
        global no, assist
        if self.Consulta(username) is None:
            if not self.root:
                self.root = No(User(username, Card(ncard, date)), None, None, None, None)
            else:
                new_no = self.insert(username, ncard, date, self.root)
                self.grow(new_no)
            print("NOVO UTILIZADOR CRIADO”")
        else:
            no = self.Consulta(username)
            for i in no.user.card:
                if i.ncard == ncard:
                    i.date = date
                    assist = assist + 1
                    print("CARTAO ATUALIZADO")
                else:
                    assist = 0
            if assist == 0:
                no.user.card.add(Card(ncard, date))
                print("NOVO CARTAO INSERIDO")

    def listagem(self, no):
        if no.right:
            no = no.right
            print(no.user.username, end='')
            for i in no.user.card:
                print(str(i.ncard) + i.date, end='')
            print("\n")
            self.listagem(no)
        if no.left:
            no = no.left
            print(no.user.username, end='')
            for i in no.user.card:
                print(str(i.ncard) + i.date, end='')
            print("\n")
            self.listagem(no)
        print("FIM")

    def Listagem(self):
        self.listagem(self.root)

    def Apaga(self):
        self.root = None
        print("LISTAGEM APAGADA")

def read():
    instruction = [str(i) for i in stdin.readline()]
    for i in instruction:
        i.split(" ")
    return instruction

def readln():
    return stdin.readline().rstrip()

def Instructions(instruction):
    tree = AVLTree()
    for i in instruction:
        print(i[0])
        if i[0] == "ACRESCENTA":
            tree.Acrescenta(i[1], i[2], i[3])
        elif i[0] == "CONSULTA":
            tree.Consulta(i[1])
        elif i[0] == "LISTAGEM":
            tree.Listagem()
        elif i[0] == "APAGA":
            tree.Apaga()
    print("FIM")

instruction = [str(i) for i in readln().split(" ")]
for j in instruction:
    for i in range(len(instruction)):
        print(j[i])

Instructions(instruction)


from absl import flags
from absl.testing import absltest
from absl.testing import parameterized
from neural_testbed.bandit import run

FLAGS = flags.FLAGS
PAPER_AGENTS = ['mlp', 'bbb', 'dropout', 'ensemble', 'ensemble+', 'hypermodel']

class RunTest(parameterized.TestCase):

  @parameterized.parameters([[x] for x in PAPER_AGENTS])
  def test_neural_testbed(self, agent_id: str):
    FLAGS.agent_id = agent_id
    FLAGS.input_dim = 2
    FLAGS.num_steps = 2
    FLAGS.num_actions = 2
    run.main(None)

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


import sys
from random import randint
sys.path.insert(0,"/var/www/shopsnoffs/shopsnoffs/")
from  dbutil import DBUtil

import psycopg2

items = []
basepirce = 259
itemname = "Lloyd Hedin Plain Toe Shoes Black"
description = "Beautiful plain toe shoes featuring brogue detailing, rubber sole. Made in Germany."
image_url = "http://www.mensdesignershoe.com/avactis-images/lloyd-hedin-plain-toe-shoes-black.png"
items.append([itemname, basepirce, description, image_url])

basepirce = 267
itemname = "Spider Suede Boots Black"
description = "Beautiful suede chukka boots with contrast color rubber soles. Made in Germany. Runs large, order 1/2 size down."
image_url = "http://www.mensdesignershoe.com/avactis-images/lloyd-spider-suede-boots-black.png"
items.append([itemname, basepirce, description, image_url])

basepirce = 280
itemname = "Varello Split Toe Gore-Tex Boots TD Moro"
description = "Split toe boots featuring Gore-Tex, and shearling fur lining. Rubber super grip sole. International shipping available only to limited countries, contact us prior to shipping to see if we can ship to your country. "
image_url = "http://www.mensdesignershoe.com/avactis-images/lloyd-mens-varello-split-toe-boots-td-moro.png"
items.append([itemname, basepirce, description, image_url])

basepirce = 100
itemname = "Saphir Antiqued Lace Up Boots Saddle"
description = "Fine antiqued lace up boots, featuring three eyelet design, and rubber sole. Made in Germany"
image_url = "http://www.mensdesignershoe.com/avactis-images/lloyd-saphir-antiqued-lace-up-boots-saddle_0.png"
items.append([itemname, basepirce, description, image_url])

basepirce = 280
itemname = "Valdez Pebble Grain Split Toe Gore-Tex Shoes Amber"
description = "Beautiful grained leather split toe shoes featuring Gore-Tex. Rubber super grip sole. International shipping available only to limited countries, contact us prior to shipping to see if we can ship to your country."
image_url = "http://www.mensdesignershoe.com/avactis-images/lloyd-mens-valdez-pebble-grain-gore-shoes-amber.png"
items.append([itemname, basepirce, description, image_url])

basepirce = 279
itemname = "Pebble Grain Split Toe Gore-Tex Shoes Amber"
description = "Beautiful grained leather split toe shoes featuring Gore-Tex. Rubber super grip sole. International shipping available only to limited countries, contact us prior to shipping to see if we can ship to your country."
image_url = "http://www.mensdesignershoe.com/avactis-images/lloyd-mens-valdez-pebble-grain-gore-shoes-amber.png"
items.append([itemname, basepirce, description, image_url])

basepirce = 240
itemname = "Hel Suede Lace Up Shoes Ocean"
description = "Beautiful soft suede lace up shoes, featuring fine stitch detailing, and rubber sole. Made in Germany."
image_url = "http://www.mensdesignershoe.com/avactis-images/lloyd-hel-suede-lace-up-shoes-ocean_0.png"
items.append([itemname, basepirce, description, image_url])

select_category  = "shoes"
_DBUtil = DBUtil()
shopids = []
for line in open('/home/ubuntu/dbdata/bremenshops.csv','r').readlines():
        parts = line.split(',')
        shopname = parts[0]
        lat = parts[1]
        longi = parts[2]
        image_url = parts[3]
        category = parts[4].strip().lower().replace("&", " ")
        #_DBUtil.add_shop(shopname, lat, longi, "", image_url)
        #print("category:" + category)
        categories = category.split(" ");
        for category in categories:
        	if len(category) > 0:
       			if category == select_category:
       				#print(_DBUtil.get_shop_by_name(shopname, float(lat), float(longi))[0][0])
       				shopids.append(_DBUtil.get_shop_by_name(shopname, (lat), (longi))[0][0])
shopids = set(shopids)
category = select_category
for shop_id in shopids:
	for item in items:
		price = item[1] + float(randint(10,80))/100
		print(str([shop_id, item[0], item[2], price, item[3]]))
		_DBUtil.add_item([shop_id, item[0], item[2], price, item[3]], [category,  "shoes", "gift"])


from .resnet_encoder import resnet18, resnet34
import torch
import torch.nn as nn
import os
import utils

# Citation: Code borrowed from Pytorch. Minor edits by me.
class Model(nn.Module):

    def __init__(self, opt, model_dir):
        super(Model, self).__init__()
        self.encoder_frozen = opt.freeze_encoder
        self.pred_mode = opt.prediction_mode
        self.N_history = opt.N_history
        self.title = self.get_title(opt)
        self.model_dir = model_dir

        if opt.encoder == "resnet18":
            self.encoder = resnet18(pretrained=opt.download_encoder)
            self.input_dims = (self.N_history, 3, 96, 96)
        elif opt.encoder == "resnet34":
            self.encoder = resnet34(pretrained=opt.download_encoder)
            self.input_dims = (self.N_history, 3, 96, 96)
        else:
            raise ValueError("Invalid Encoder")

        if self.pred_mode == "regression":
            N_out = 3
        elif self.pred_mode == "classification":
            N_out = 5
        else:
            raise ValueError("Invalid prediction mode")
        self.decoder = self.make_decoder(opt.num_decoder_layers-1, self.encoder.N_out*opt.N_history, 64, N_out)

        # Use to store history
        self.input_buffer = torch.zeros(self.input_dims)

    def make_decoder(self, num_hidden_layers, N_in, N_hidden, N_out):
        layers = []
        current_N = N_in
        for _ in range(num_hidden_layers):
            layers.append(nn.Linear(current_N, N_hidden))
            layers.append(nn.ReLU())
            current_N = N_hidden
            layers.append(nn.BatchNorm1d(current_N))
        layers.append(nn.Linear(current_N, N_out))

        return nn.Sequential(*layers)

    def get_title(self, opt):
        t = f"Encoder={opt.encoder}-freeze_encoder={self.encoder_frozen}-Decoder={opt.num_decoder_layers}-N_history={opt.N_history}-mode={self.pred_mode}"
        if opt.num_train > 0:
            t = f"num_train={opt.num_train}-" + t
        return t

    def get_file_name(self):
        return f"{self.title}.model"

    def load(self, file_name=None):
        if file_name is None:
            file_name = self.get_file_name()
        path = os.path.join(self.model_dir, file_name)
        self.load_state_dict(torch.load(path, map_location=utils.get_device_name()))
        print(f"Loaded model state dict from {path}")

    def save(self, file_name=None):
        if file_name is None:
            file_name = self.get_file_name()
        path = os.path.join(self.model_dir, file_name)
        torch.save(self.state_dict(), path, _use_new_zipfile_serialization=False)
        print(f"Saved model state dict to {path}")

    def to(self, *args, **kwargs):
        new_self = super().to(*args, **kwargs)
        new_self.input_buffer = new_self.input_buffer.to(*args, **kwargs)
        return new_self

    def begin_episode(self):
        self.input_buffer[:, :, :, :] = 0

    # Input Dimensions [batch_size, N_history, n_channels, spatial]
    def forward(self, X):
        with torch.set_grad_enabled(not self.encoder_frozen):
            X_shape = X.size()
            assert self.N_history == X_shape[1], f"History Dimension does not match. Require {self.N_history}"

            X = X.view(X_shape[0]*X_shape[1], X_shape[2], X_shape[3], X_shape[4])
            encoding = self.encoder(X)
            encoding = encoding.view((X_shape[0], self.N_history*self.encoder.N_out))
        output = self.decoder(encoding)
        return output

    # Input dimensions: [n_channels, spatial]
    def infer_action(self, X):
        with torch.no_grad():
            self.input_buffer[1:, :, :, :] = self.input_buffer[:-1, :, :, :].clone()
            self.input_buffer[0, :, :, :] = X

            encoding = self.encoder(self.input_buffer)
            encoding = encoding.view((1, self.N_history*self.encoder.N_out))
            output = self.decoder(encoding)
            output = output.squeeze(0).cpu()
            if self.pred_mode == 'regression':
                return output
            elif self.pred_mode == 'classification':
                label = torch.argmax(output)
                mapping = [[0,0,0], [-1, 0, 0], [1, 0, 0], [0, 0, 0.2], [0, 1, 0]]
                return torch.FloatTensor(mapping[label])
            else:
                raise ValueError("Invalid Prediction Mode")

2 - Immitation Learning/Racing/model/model.py


# models.py
# Yiwen Huang (yh385) and Vicky Chou (vc265)
# December 11, 2015
"""Models module for Breakout

This module contains the model classes for the Breakout game. That is anything
that you interact with on the screen is model: the paddle, the ball, and any of
the bricks.

Technically, just because something is a model does not mean there has to be a
special class for it. Unless you need something special, both paddle and
individual bricks could just be instances of GRectangle. However, we do need
something special: collision detection. That is why we have custom classes.

You are free to add new models to this module. You may wish to do this when you
add new features to your game. If you are unsure about whether to make a new
class or not, please ask on Piazza.
"""
import random # To randomly generate the ball velocity
from constants import *
from game2d import *

# PRIMARY RULE: Models are not allowed to access anything except the module
# constants.py.
# If you need extra information from Play, then it should be a parameter in your
# method, and Play should pass it as a argument when it calls the method.

class Paddle(GRectangle):
    """An instance is the game paddle.

    This class contains a method to detect collision with the ball, as well as
    move it left and right. You may wish to add more features to this class.

    The attributes of this class are those inherited from GRectangle.

    LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY
    _x       [int or float]
            the midpoint of the paddle
    _collide [boolean]
            True if ball has collided with paddle, False otherwise
    """
    # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM)

    # INITIALIZER TO CREATE A NEW PADDLE
    def __init__(self, x1):
        """Initializer: Creates a new paddle for the game Breakout.

        Parameter x1: the width of the paddle
        Precondition: the width must be an float or int < GAME_WDITH
        """
        assert ((type(x1) == float) or type(x1)==int ) and (x1 < GAME_WIDTH)
        GRectangle.__init__(self,x=x1, y=PADDLE_OFFSET, width=PADDLE_WIDTH,
                            height=PADDLE_HEIGHT, fillcolor=colormodel.BLACK,
                            linecolor=colormodel.BLACK)
        self._x=x1

    # METHODS TO MOVE THE PADDLE AND CHECK FOR COLLISIONS
    def collides(self,ball):
        """Returns: True if the ball collides with the paddle.

        Parameter ball: the ball to check
        Precondition: the ball is of class Ball
        """
        assert isinstance(ball, Ball)
        corners = [[ball.x-BALL_RADIUS,ball.y+BALL_RADIUS],
                  [ball.x+BALL_RADIUS,ball.y+BALL_RADIUS],
                  [ball.x-BALL_RADIUS, ball.y-BALL_RADIUS],
                  [ball.x+BALL_RADIUS,ball.y-BALL_RADIUS]]
        self._collide=False
        for point in corners:
            if self.contains(point[0],point[1]):
                self._collide=True
        return self._collide

    # ADD MORE METHODS (PROPERLY SPECIFIED) AS NECESSARY

class Brick(GRectangle):
    """An instance is the game paddle.

    This class contains a method to detect collision with the ball. You may wish
    to add more features to this class.

    The attributes of this class are those inherited from GRectangle.

    LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY

    """

    # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM)

    # INITIALIZER TO LAYOUT BRICKS ON THE SCREEN
    def __init__(self, x1, y1, fillcolor1):
        """Initializer: Creates the bricks for the game Breakout.

        Parameter x1: the width of every brick
        Precondition: the width must be an int or float < GAME_WIDTH

        Parameter y1: the height of every brick
        Precondition: the height must be an int or float< GAME_HEIGHT

        Parameter fillcolor1: the color of the bricks
        Precondition: the color must be an instance of colormodel
        """
        assert ((type(x1) == int) or (type(x1)==float )) and (x1 < GAME_WIDTH)
        assert ((type(y1) == int) or (type(xy1)==float )) and (y1 < GAME_HEIGHT)
        assert isinstance(fillcolor1, colormodel.RGB)
        GRectangle.__init__(self, x=x1, y=y1, width=BRICK_WIDTH, height=
                            BRICK_HEIGHT, fillcolor=fillcolor1,
                            linecolor=fillcolor1)

    # ADD MORE METHODS (PROPERLY SPECIFIED) AS NECESSARY
    def collides(self,ball):
        """Returns: True if the ball collides with a brick, False otherwise.

        Parameter ball: the ball to check
        Precondition: the ball is of class Ball
        """
        assert isinstance(ball, Ball)
        corners=[[ball.x-BALL_RADIUS,ball.y+BALL_RADIUS],
                  [ball.x+BALL_RADIUS,ball.y+BALL_RADIUS],
                  [ball.x-BALL_RADIUS, ball.y-BALL_RADIUS],
                  [ball.x+BALL_RADIUS,ball.y-BALL_RADIUS]]
        collide=False
        for point in corners:
            if self.contains(point[0],point[1]):
                collide=True
        return collide

class Ball(GEllipse):
    """Instance is a game ball.

    We extend GEllipse because a ball must have additional attributes for
    velocity. This class adds this attributes and manages them.

    INSTANCE ATTRIBUTES:
        _vx [int or float]: Velocity in x direction
        _vy [int or float]: Velocity in y direction

    The class Play will need to look at these attributes, so you will need
    getters for them.  However, it is possible to write this assignment with no
    setters for the velocities.

    How? The only time the ball can change velocities is if it hits an obstacle
    (paddle or brick) or if it hits a wall.  Why not just write methods for these
    instead of using setters?  This cuts down on the amount of code in Gameplay.

    NOTE: The ball does not have to be a GEllipse. It could be an instance
    of GImage (why?). This change is allowed, but you must modify the class
    header up above.

    LIST MORE ATTRIBUTES (AND THEIR INVARIANTS) HERE IF NECESSARY
    """

    # GETTERS AND SETTERS (ONLY ADD IF YOU NEED THEM)
    def getVY(self):
        """Returns: the y component of velocity of the ball."""
        return self._vy

    def getVX(self):
        """Returns: the x component of velocity of the ball."""
        return self._vx

    def setVY(self, vy):
        """Sets the y component of velocity of the ball."""
        self._vy = vy

    def setVX(self, vx):
        """Sets the x component of velocity of the ball."""
        self._vx = vx

    def __init__(self):
        """Initializer: Sets the velocity and the dimensions of the ball."""
        GEllipse.__init__(self)
        self._vx = random.uniform(1.0,5.0)
        self._vx = self._vx*random.choice([-1,1])
        self._vy = -BALL_SPEED
        self.x = (GAME_WIDTH-BALL_DIAMETER)/2
        self.y = PADDLE_OFFSET+PADDLE_HEIGHT+GAME_HEIGHT/2
        self.width = BALL_DIAMETER
        self.height = BALL_DIAMETER
        self.fillcolor = colormodel.BLUE

    # METHODS TO MOVE AND/OR BOUNCE THE BALL
    def move(self):
        """Moves the ball one step."""
        self.x+=self._vx
        self.y+=self._vy

    # ADD MORE METHODS (PROPERLY SPECIFIED) AS NECESSARY

# IF YOU NEED ADDITIONAL MODEL CLASSES, THEY GO HERE


"""
Ported to Python from this source:

https://www.tweaking4all.com/hardware/arduino/adruino-led-strip-effects/#LEDStripEffectFire

Original comments and variable names maintained.
"""

import random
import typing

from light import Light
from marshmallow import Schema, fields, post_load, validate

from .animation_interface import AnimationInterface

class FireConfig:
    def __init__(self, cooling, sparking):
        self.cooling = cooling
        self.sparking = sparking

class FireConfigSchema(Schema):
    cooling = fields.Int(validate=validate.Range(min=1), missing=55)
    sparking = fields.Int(validate=validate.Range(min=1), missing=120)

    @post_load
    def make_config(self, data, **kwargs):
        return FireConfig(**data)

class Fire(AnimationInterface):
    def __init__(self, light: Light, config: typing.Dict):
        self.light = light
        config_schema = FireConfigSchema()
        self.config = config_schema.load(config)

    def _set_pixel_heat_colour(self, led, temperature, light):
        # Scale 'heat' down from 0-255 to 0-191
        t192 = round((temperature / 255) * 191)

        # calculate ramp up from
        heatramp = t192 & 63
        heatramp <<= 2  # scale up to 0..252

        # figure out which third of the spectrum we're in:
        if t192 > 128:  # hottest
            light.set_led(led, [255, 255, heatramp])
        elif t192 > 64:  # middle
            light.set_led(led, [255, heatramp, 0])
        else:  # coolest
            light.set_led(led, [heatramp, 0, 0])

    def set_next_frame(self):
        heat = [0 for led in range(self.light.num_leds)]

        # Step 1.  Cool down every cell a little
        for i in range(self.light.num_leds):
            cooldown = random.uniform(
                0, ((self.config.cooling * 10) / self.light.num_leds) + 2
            )

            if cooldown > heat[i]:
                heat[i] = 0
            else:
                heat[i] -= cooldown

        # Step 2.  Heat from each cell drifts 'up' and diffuses a little
        k = self.light.num_leds - 1
        while k >= 2:
            heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3
            k -= 1

        # Step 3.  Randomly ignite new 'sparks' near the bottom
        if random.randint(0, 255) < self.config.sparking:
            y = random.randint(0, 7)
            heat[y] += random.randint(160, 255)

        # Step 4.  Convert heat to LED colors
        for j in range(self.light.num_leds):
            self._set_pixel_heat_colour(j, heat[j], self.light)

        return False


from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
import numpy as np
import os
import cv2
#from utils import preprocess,load_dataset
from torch.utils.data import TensorDataset, Dataset
import math
import torchvision.models as models
from torchvision import transforms
import seaborn as sn
import pandas as pd
from sklearn.metrics import confusion_matrix, accuracy_score, recall_score, precision_score
from matplotlib import pyplot as plt
from skimage import color
from config import *
from utils import *
from train import model_generator
def create_cm(predictions, Y, labels='01234567', title='Confusion Matrix'):
    plt.figure()
    m1 = confusion_matrix(Y,predictions, labels=np.array([int(i) for i in labels]))
    m1 = m1.astype('float') / m1.sum(axis=1)[:, np.newaxis]
    m1 = np.round(m1, 2)
    df_cm = pd.DataFrame(m1, index=[i for i in labels],
                         columns=[i for i in labels])
    sn.heatmap(df_cm, annot=True)
    plt.title(title)
    title = title.replace(' ', '_')
    plt.xlabel('Predicted Label')
    plt.ylabel('Ground Truth Label')
    plt.savefig('./cm.png')

def compute_accuracy(y_pred, y_true):
    print('Accuracy', accuracy_score(y_true, y_pred, normalize=True))

def compute_precision(y_pred, y_true):
    print('Precision', precision_score(y_true, y_pred,average='weighted'))

def compute_recall(y_pred, y_true):
    print('Recall', recall_score(y_true, y_pred,average='weighted'))

def test(model, device, test_loader, classWeight_tensor=None):
    model.eval()  # inference mode
    results = np.zeros((len(test_loader),1))
    results_with_rejection = np.zeros((len(test_loader),1))
    i = 0
    correct = 0.0
    with torch.no_grad():
        for data, target in test_loader:  # load the data
            data, target = data.to(device), target.to(device)
            output = model(data)  # collect the outputs
            prediction,predictions_with_reject = output_transformation(output)
            result = np.argmax(prediction.cpu().data.numpy()[0])
            pred = prediction.argmax(dim=1, keepdim=True)
            results[i] = result
            results_with_rejection[i] = np.argmax(predictions_with_reject.cpu().data.numpy()[0])
            correct += pred.eq(target.long().view_as(pred)).sum().item()
            if i > 0 and i % 100 == 0:
                print("[INFO] predicted {} total images".format(i))
            i += 1
        print(correct / len(test_loader))
    return results,results_with_rejection

def createPlots(model):
    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")
    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
    train_folder = os.path.join(DATA, 'test')
    path_train_csv = os.path.join(DATA, 'labels', 'Test_labels.csv')
    x_test, y_test = load_data(train_folder, path_train_csv)
    x_test = preprocess(x_test)
    x_test = reshapeInput(x_test)
    y_test = np.argmax(y_test, axis=1)
    test_dataset = (torch.FloatTensor(x_test), torch.FloatTensor(y_test))
    test_loader = torch.utils.data.DataLoader(TensorDataset(*test_dataset), **kwargs)
    print('testing..')
    y_pred,y_pred_with_rejection = test(model, device, test_loader)
    y_pred = np.squeeze(y_pred)
    y_pred_with_rejection = np.squeeze(y_pred_with_rejection)

    create_cm((y_pred+1)%8,(y_test+1)%8)
    create_cm((y_pred_with_rejection+1)%8,(y_test+1)%8) # rotate to make rejection class 0
    compute_accuracy(y_pred,y_test)
    compute_precision(y_pred,y_test)
    compute_recall(y_pred,y_test)

    compute_accuracy(y_pred_with_rejection,y_test)
    compute_precision(y_pred_with_rejection,y_test)
    compute_recall(y_pred_with_rejection,y_test)
    # plot the training and validation loss
    val_loss = np.load('./val_loss.npy')
    train_loss = np.load('./train_loss.npy')
    epochs = np.arange(len(val_loss))
    plt.figure()
    plt.title('Loss Curve')
    plt.xlabel('Epochs')
    plt.ylabel('Loss')
    plt.plot(epochs,val_loss,label='Validation Loss')
    plt.plot(epochs,train_loss,label='Training Loss')
    plt.legend()
    plt.savefig('./training_curve.png')
    plt.show()

def main():
    # parameters
    use_cuda = torch.cuda.is_available()
    device = torch.device("cuda" if use_cuda else "cpu")
    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}

    pathToModel = './weights.pt'
    parser = argparse.ArgumentParser(description='Assignment 1')
    parser.add_argument("files", nargs="*")
    args = parser.parse_args()

    # attempt to use GPU if available
    use_cuda = torch.cuda.is_available()
    torch.manual_seed(123456789)
    device = torch.device("cuda" if use_cuda else "cpu")
    kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}
    # attempt to use GPU if available
    model = model_generator()
    model.eval()
    if (use_cuda):
        model.cuda()
    if os.path.isfile(pathToModel):
        print('Loading')
        if not use_cuda:
            model.load_state_dict(torch.load(pathToModel, map_location='cpu'))
        else:
            model.load_state_dict(torch.load(pathToModel))

    if (len(args.files) == 0):
        createPlots(model)
    else:
        for file in args.files:
            assert os.path.isfile(file),\
                print('SKIPPING: File does not exist: ', file)

            img = cv2.imread(file).astype(np.float32)
            img = cv2.resize(img, (90, 120))
            img = np.expand_dims(preprocess(img), axis=0)
            img = reshapeInput(img)
            prediction = model(torch.tensor(img).to(device))
            if (use_cuda):
                result = prediction.cpu().data.numpy()
            else:
                result = prediction.data.numpy()
            print(np.argmax(result))

if __name__ == '__main__':
    main()


# Tensorflow throws a warning:- Instructions for updating: Colocations handled automatically by placer.
# We can ignore his warning or shut it, doesnt matter code works fine(for now).

import nltk
from nltk.stem.lancaster import LancasterStemmer
import numpy as np
import tflearn
import tensorflow as tf
import json, pickle, os, string, random

with open("intents.json") as file:
    data = json.load(file)

words = []
labels = []
docs_x = []
docs_y = []

for intent in data['intents']:
    for pattern in intent['patterns']:
        pattern = pattern.lower()
        word = nltk.word_tokenize(pattern) #Creating a list of words
        words.extend(word)
        docs_x.append(word)
        docs_y.append(intent['tag'])

    if intent['tag'] not in labels:
        labels.append(intent['tag'])

# print(docs_x)
# print()
# print(docs_y)

"""
words: Holds a list of unique words.
labels: Holds a list of all the unique tags in the file.
docs_x: Holds a list of patterns.
docs_y: Holds a list of tags corresponding to the pattern in docs_x.
"""

"""
Type of vectorization we will use: BoW
We’ll be using Bag of Words (BoW) in our code. It basically describes the occurrence of a word within
a document. In our case, we’ll be representing each sentence with a list of the length of all unique
words collected in the list “words”. Each position in that list will be a unique word from “words”. If
a sentence consists of a specific word, their position will be marked as 1 and if a word is not present
 in that position, it’ll be marked as 0.
"""
string_punc = []
for i in string.punctuation:
    string_punc.append(i)
# Stemming
stemmer = LancasterStemmer()
# words = [stemmer.stem(str(w).lower()) for w in words if w not in string_punc]
wording = wordings = []
for item in words:
    if type(item) == 'str':
        wording = [stemmer.stem(w.lower()) for w in words if w not in string_punc]
    elif type(item) == 'list':
        for i in item:
            if i not in string_punc:
                wording.append(i)
        wordings.extend(wording)
    else:
        pass

words = sorted(list(set(wordings)))
labels = sorted(labels)

"""
Similarly, for the output, we’ll create a list which will be the length of the labels/tags we have in
our JSON file. A “1” in any of those positions indicates the belonging of a pattern in that particular
label/tag.
"""
training = []
output = []

out_empty = [0 for _ in range(len(labels))]
for x, doc in enumerate(docs_x):
    bag = []
    wrds = [stemmer.stem(w) for w in doc]
    for w in words:
        if w in wrds:
            bag.append(1)
        else:
            bag.append(0)
    output_row = out_empty[:]
    output_row[labels.index(docs_y[x])] = 1
    training.append(bag)
    output.append(output_row)

# Converting training data into NumPy arrays
training = np.array(training)
output = np.array(output)

# Saving data to disk
with open("data.pickle", "wb") as f:
    pickle.dump((words, labels, training, output), f)

"""
Now that we’re done with data preprocessing, it’s time to build a model and feed our preprocessed data
to it. The network architecture is not too complicated. We will be using Fully Connected Layers
(FC layers) with two of them being hidden layers and one giving out the target probabilities. Hence,
the last layer will be having a softmax activation.
"""

tf.reset_default_graph()

net = tflearn.input_data(shape = [None, len(training[0])])
net = tflearn.fully_connected(net,8)
net = tflearn.fully_connected(net,8)
net = tflearn.fully_connected(net,len(output[0]), activation = "softmax")
net = tflearn.regression(net)

model = tflearn.DNN(net)
model.fit(training, output, n_epoch = 200, batch_size = 8, show_metric = True)
model.save("model.tflearn")


import sys

from PyQt5.QtWidgets import (QApplication, QWidget,
                             QHBoxLayout, QVBoxLayout, QFrame, QFormLayout,
                             QPushButton, QTabWidget, QGroupBox,
                             QLineEdit, QTextEdit, QLabel, QScrollArea,
                             QInputDialog, QMenu, QMessageBox)

from .combobox_nowheel import QComboBoxNoWheel

class SheetUI():
    def __init__(self, changefunc):
        self.valid = True
        self.changefunc = changefunc
        self.container = self.make_page()

    def onChange(self):
        self.changefunc()

    def rebuild_stations(self, stations):
        station_list = str(stations).split()
        start_text = self.edit_start.currentText()
        end_text = self.edit_end.currentText()
        self.edit_start.clear()
        self.edit_start.addItem("Start: Inner")
        self.edit_end.clear()
        self.edit_end.addItem("End: Outer")
        for index,station in enumerate(station_list):
            text = "Start: " + str(station)
            self.edit_start.addItem(text)
            text = "End: " + str(station)
            self.edit_end.addItem(text)
        index = self.edit_start.findText(start_text)
        if index != None:
            self.edit_start.setCurrentIndex(index)
        index = self.edit_end.findText(end_text)
        if index != None:
            self.edit_end.setCurrentIndex(index)

    def delete_self(self):
        if self.valid:
            self.changefunc()
            self.container.deleteLater()
            self.valid = False

    def make_page(self):
        page = QFrame()
        layout = QVBoxLayout()
        page.setLayout( layout )

        line1 = QFrame()
        layout1 = QHBoxLayout()
        line1.setLayout( layout1 )
        layout.addWidget( line1 )

        line2 = QFrame()
        layout2 = QHBoxLayout()
        line2.setLayout( layout2 )
        layout.addWidget( line2 )

        layout1.addWidget( QLabel("Depth: ") )

        self.edit_depth = QLineEdit()
        self.edit_depth.setFixedWidth(70)
        self.edit_depth.textChanged.connect(self.onChange)
        layout1.addWidget( self.edit_depth )

        self.edit_start = QComboBoxNoWheel()
        self.edit_start.addItem("-")
        self.edit_start.addItem("1")
        self.edit_start.addItem("2")
        self.edit_start.addItem("3")
        self.edit_start.currentIndexChanged.connect(self.onChange)
        layout1.addWidget(self.edit_start)

        self.edit_end = QComboBoxNoWheel()
        self.edit_end.addItem("-")
        self.edit_end.addItem("1")
        self.edit_end.addItem("2")
        self.edit_end.addItem("3")
        self.edit_end.currentIndexChanged.connect(self.onChange)
        layout1.addWidget(self.edit_end)

        layout1.addStretch(1)

        delete = QPushButton('Delete')
        delete.clicked.connect(self.delete_self)
        layout1.addWidget(delete)

        layout2.addWidget( QLabel("Start Pos: ") )

        self.edit_xstart = QLineEdit()
        self.edit_xstart.setFixedWidth(50)
        self.edit_xstart.textChanged.connect(self.onChange)
        layout2.addWidget( self.edit_xstart )

        self.edit_xmode = QComboBoxNoWheel()
        self.edit_xmode.addItem("Sheet Width")
        self.edit_xmode.addItem("End Position")
        self.edit_xmode.currentIndexChanged.connect(self.onChange)
        layout2.addWidget(self.edit_xmode)

        self.edit_xend = QLineEdit()
        self.edit_xend.setFixedWidth(50)
        self.edit_xend.textChanged.connect(self.onChange)
        layout2.addWidget( self.edit_xend )

        self.edit_surface = QComboBoxNoWheel()
        self.edit_surface.addItem("Top")
        self.edit_surface.addItem("Bottom")
        self.edit_surface.currentIndexChanged.connect(self.onChange)
        layout2.addWidget(self.edit_surface)

        layout2.addStretch(1)

        return page

    def get_widget(self):
        return self.container

    def load(self, node):
        self.edit_depth.setText(node.getString('depth'))
        self.edit_xstart.setText(node.getString('xstart'))
        index = self.edit_xmode.findText(node.getString('xmode'))
        if index == None:
            index = 1
        self.edit_xmode.setCurrentIndex(index)
        self.edit_xend.setText(node.getString('xend'))
        index = self.edit_surface.findText(node.getString('surface'))
        if index == None:
            index = 1
        self.edit_surface.setCurrentIndex(index)
        index = self.edit_start.findText(node.getString('start_station'))
        if index != None:
            self.edit_start.setCurrentIndex(index)
        index = self.edit_end.findText(node.getString('end_station'))
        if index != None:
            self.edit_end.setCurrentIndex(index)

    def save(self, node):
        node.setString('depth', self.edit_depth.text())
        node.setString('xstart', self.edit_xstart.text())
        node.setString('xmode', self.edit_xmode.currentText())
        node.setString('xend', self.edit_xend.text())
        node.setString('surface', self.edit_surface.currentText())
        node.setString('start_station', self.edit_start.currentText())
        node.setString('end_station', self.edit_end.currentText())


import re
import time
def get_record(url):
    #读文件函数
    with open(url,'r')as fp:
        vlst=fp.read().split() #读取全部文件并分裂成列表
    fp.close()
    return vlst
def get_v(vlst):
    # 获取全部不同的ETC编号，构成集合
    vset=set()         #新建空集合
    for i in vlst:     #将每条记录的车辆加入集合中，利用集合的性质自动去重
        vset.add(i[:10])
    return vset
def count_v(vlst, vset):
    # 构造车辆进出校园次数的字典
    keys=vset          #将车辆列表设为关键词集合
    lst=[]
    for i in vlst:
        lst.append(i[:10])
    values=list(lst.count(i) for i in vset)   #根据每辆车出现的次数列表设为值表
    fre=dict(zip(keys,values))                 #根据关键词列表与值列表构成字典
    return fre
def count_t(vlst, vset):
    # 构造车辆累计停留时间的字典
    tlst=dict.fromkeys(vset,0)           #根据车辆列表建立关键词字典，且值都为0
    for i in vlst:
        sp=i.split('|')
        tim2=time.mktime(time.strptime(sp[2],'%Y-%m-%d#%H:%M:%S'))
        tim1=time.mktime(time.strptime(sp[1],'%Y-%m-%d#%H:%M:%S'))
        tlst[sp[0]]+=(tim2-tim1)           #计算每个记录的时间差，并累加
    return tlst
def write_to_file(vlst, fre, tlst, url):
    # 输出结果到文件中
    with open(url,'w')as fp:      #依次输出每行信息
        fp.write('记录条数：'+str(len(vlst))+'\n')
        fp.write('车辆数：'+str(len(tlst))+'\n')
        fp.write('进校次数最多的5辆车（单位：次）：\n')
        fri=sorted(fre.items(),key=lambda x:x[1],reverse=True) #根据车辆出现次数由高向低排序
        for i in range(5):
            fp.write(fri[i][0]+','+str(fri[i][1])+'\n')
        fp.write('累计停留时间最长的5辆车（单位：秒）：\n')
        inter=sorted(tlst.items(),key=lambda x:x[1],reverse=True) #根据停留时间由高向低排序
        for i in range(5):
            fp.write(inter[i][0]+','+str(inter[i][1])+'\n')
    fp.close()

def main():
    vehicle_lst = get_record("data.txt")			# 读文件，获取全部ETC记录，构成列表
    vehicle_set = get_v(vehicle_lst)				# 获取全部不同的ETC编号，构成集合
    fre_dict = count_v(vehicle_lst, vehicle_set)		# 构造车辆进出校园次数的字典
    inter_dict = count_t(vehicle_lst, vehicle_set)		# 构造车辆累计停留时间的字典
    write_to_file(vehicle_lst, fre_dict, inter_dict, "report.txt")	# 输出结果到文件中
    return

main()	# 调用main函数

复试笔记/本科python试题/1602模拟题_90min/1602模拟题.py


from typing import List

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        n=len(nums)
        nums.sort()
        res=nums[0]+nums[1]+nums[2]
        for i in range(n):
            l,r=i+1,n-1
            while(l<r):
                sum=nums[i] + nums[l] + nums[r]
                if abs(sum-target)<abs(res-target):
                    res = sum
                if(res-target>0):
                    r-=1
                elif(res-target<0):
                    l+=1
                else:
                    return res
        return res

if __name__ == '__main__':
    nums=[-1,2,1,4]
    target=10
    print(Solution().threeSumClosest(nums,target))


length = float(input("Enter the scale factor "))
heightOffset = float(input("Enter the height offset: "))

with open('KAI Logo Scaled 1.txt') as f:
    my_list = f.read().splitlines()

f= open("output.txt","w+")

for i in range(len(my_list)):
    if (my_list[i] == 'on' or my_list[i] == 'off' ):
        f.write(my_list[i])
        f.write("\n")

    else:
        x,y,z = my_list[i].split(',')

        x = float(x)
        y = float(y)
        z = float(z)

        x = x*length
        y = y*length
        z = 0

        f.write("%d,%d,%d\n" %(round(x),round(y),round(z+heightOffset)))

        print (x, '**', y, '**', z+heightOffset, '**')

f.close()

Tello Python Control/Scale Coordinates v1.py


import time

from script.simulator.game_status import GameStatus
from wordy.utils import ALL_WORDS
from script.simulator.wordle_simulator import WordleSimulator
from wordy.simulator.wordy_simulator import WordySimulator

def simulate_game(answer_word: str):
    wordle = WordleSimulator(answer_word=answer_word)
    wordy = WordySimulator(possible_words_answer=ALL_WORDS)

    # initial game state
    game_status = GameStatus.ON_GOING
    round = 1
    played_words = []
    feedback_cases = []
    while game_status == GameStatus.ON_GOING:
        start_time = time.time()
        word_to_play = wordy.guess(round=round, played_words=played_words, feedback_cases=feedback_cases)
        time_to_calculate_next_word_to_play = time.time() - start_time
        game_status, feedback = wordle.get_game_state(played_word=word_to_play)
        played_words.append(word_to_play)
        feedback_cases.append(feedback)
        print(f'({round}) play:\t{word_to_play} ({time_to_calculate_next_word_to_play: .2f} sec)')
        print(f'feedback:\t{"".join(feedback)}')
        print(f'possible answer: {wordy.possible_words_answer}')
        print()
        round += 1

    if game_status == GameStatus.WIN:
        print(f'🎉 I found "{word_to_play.upper()}" within round {round - 1}!')
    else:
        print("☠ I'm unable to catch that word in time :(")

vocabs = ['those', 'moist', 'shard', 'pleat', 'aloft', 'skill', 'elder', 'frame', 'humor', 'pause', 'ulcer', 'ultra',
          'robin', 'cynic', 'aroma', 'caulk', 'shake', 'dodge', 'swill', 'tacit', 'other', 'thorn', 'trove', 'bloke',
          'vivid', 'spill', 'chant', 'choke', 'nasty', 'ahead']
for vocab in vocabs:
    print(f'======= Vocab is "{vocab.upper()}" =======')
    simulate_game(vocab)


import os, time
from colorama import Fore, init
import getpass
import socket
import subprocess as sp

def times():
	times = time.strftime("%H:%M:%S")
	times = str(times)
	return(times)

def clear():
	if os.name == 'nt':
		return os.system('cls')
	else:
		return os.system('clear')

def check_host():
    version = 'HOST_CHECK'
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    result = sock.connect_ex(('vps-1f21facc.vps.ovh.net', 6677))
    if result == 0:
        ver = sock.send(version.encode('utf-8'))
        return str(Fore.LIGHTGREEN_EX + "Online" + Fore.RESET)
    else:
        return str(Fore.LIGHTRED_EX + "Offline" + Fore.RESET)

if os.name == 'nt':
    init(convert=True)
else:
    init(convert=False)

user = getpass.getuser()

smoke_layer1 = (Fore.LIGHTBLACK_EX+'('+Fore.RESET)
smoke_layer2 = (Fore.LIGHTBLACK_EX+')'+Fore.RESET)

class Menu():
    design_txt_layer_1 = ("                          _    ")
    design_txt_layer_2 = ("     ___ _ __   ___  __ _| | __")
    design_txt_layer_3 = ("    / __| '_ \ / _ \/ _` | |/ /")
    design_txt_layer_4 = ("    \__ \ |_) |  __/ (_| |   < ")
    design_txt_layer_5 = ("    |___/ .__/ \___|\__,_|_|\_\ ")
    design_txt_layer_6 = ("        |_|                    ")
    design_ui = ("""
         %s
        %s
       __%s__
    C\|     \  %s
      \     /  %s
       \___/   %s

%s
%s
%s
%s
%s
%s

    """ %(
            str(smoke_layer2),
            str(smoke_layer1),
            str(smoke_layer2),
            str("     Heure : [" + Fore.LIGHTBLUE_EX + times() + Fore.RESET + str("]")),
            str("     Utilisateur (PC) : [" + Fore.LIGHTBLUE_EX + str(user) + Fore.RESET + str("]")),
            str("     Statut Serveur : [") + check_host() + str("]"),
            str(design_txt_layer_1),
            str(design_txt_layer_2),
            str(design_txt_layer_3),
            str(design_txt_layer_4),
            str(design_txt_layer_5),
            str(design_txt_layer_6)

         ))
clear()


import numpy as np
import cv2
from skimage.feature import hog

def get_hog_features(img, orient, pix_per_cell, cell_per_block,
                        vis=False, feature_vec=True):
    # Call with two outputs if vis==True
    if vis == True:
        features, hog_image = hog(img, orientations=orient,
                                  pixels_per_cell=(pix_per_cell, pix_per_cell),
                                  cells_per_block=(cell_per_block, cell_per_block),
                                  transform_sqrt=True,
                                  visualise=vis, feature_vector=feature_vec)
        return features, hog_image
    # Otherwise call with one output
    else:
        features = hog(img, orientations=orient,
                       pixels_per_cell=(pix_per_cell, pix_per_cell),
                       cells_per_block=(cell_per_block, cell_per_block),
                       transform_sqrt=True,
                       visualise=vis, feature_vector=feature_vec)
        return features

# Define a function to compute binned color features
def bin_spatial(img, size=(32, 32)):
    # Use cv2.resize().ravel() to create the feature vector
    features = cv2.resize(img, size).ravel()
    # Return the feature vector
    return features

# Define a function to compute color histogram features
# NEED TO CHANGE bins_range if reading .png files with mpimg!
def color_hist(img, nbins=32, bins_range=(0, 256)):
    # Compute the histogram of the color channels separately
    channel1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range)
    channel2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range)
    channel3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range)
    # Concatenate the histograms into a single feature vector
    hist_features = np.concatenate((channel1_hist[0], channel2_hist[0], channel3_hist[0]))
    # Return the individual histograms, bin_centers and feature vector
    return hist_features

Part III - Vehicle Detection and Tracking/features.py


import torch
import torch.nn as nn
import torch.nn.functional as F

from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
# from Model.model import CharRNN

from Utils.utils.metric_reward import MetricsReward
import torch.nn.utils.rnn as rnn_utils
class CharRNN(nn.Module):

    def __init__(self, vocabulary, config):
        super(CharRNN, self).__init__()

        self.vocabulary = vocabulary
        self.hidden_size = config.hidden
        self.num_layers = config.num_layers
        self.dropout = config.dropout
        self.device=config.cuda
        self.vocab_size = self.input_size = self.output_size = len(vocabulary)

        self.embedding_layer = nn.Embedding(self.vocab_size, self.vocab_size,
                                            padding_idx=vocabulary.vocab['<pad>'])
        self.lstm_layer = nn.LSTM(self.input_size, self.hidden_size,
                                  self.num_layers, dropout=self.dropout,
                                  batch_first=True)
        self.linear_layer = nn.Linear(self.hidden_size, self.output_size)

    # @property
    # def device(self):
    #     return next(self.parameters()).device

    def forward(self, x, lengths, hiddens=None):
        x = self.embedding_layer(x)
        x = rnn_utils.pack_padded_sequence(x, lengths, batch_first=True)
        x, hiddens = self.lstm_layer(x, hiddens)
        x, _ = rnn_utils.pad_packed_sequence(x, batch_first=True)
        x = self.linear_layer(x)

        return x, lengths, hiddens

class Discriminator(nn.Module):
    def __init__(self,embedding_layer,  config,convs, dropout=0):
        super(Discriminator, self).__init__()

        self.embedding_layer = embedding_layer
        self.conv_layers = nn.ModuleList(
            [nn.Conv2d(1, f, kernel_size=(
                n, self.embedding_layer.embedding_dim)
                       ) for f, n in convs])
        sum_filters = sum([f for f, _ in convs])
        self.highway_layer = nn.Linear(sum_filters, sum_filters)
        self.dropout_layer = nn.Dropout(p=dropout)
        self.output_layer = nn.Linear(sum_filters, 1)
        self.device=config.cuda

    def forward(self, x):
        x = self.embedding_layer(x)
        x = x.unsqueeze(1)

        convs = [F.elu(conv_layer(x)).squeeze(3)
                 for conv_layer in self.conv_layers]
        x = [F.max_pool1d(c, c.shape[2]).squeeze(2) for c in convs]
        x = torch.cat(x, dim=1)

        h = self.highway_layer(x)
        t = torch.sigmoid(h)
        x = t * F.elu(h) + (1 - t) * x
        x = self.dropout_layer(x)
        out = self.output_layer(x)

        return out
def reback(model,toens,n_batch):
    smis=[]

    for i in range(n_batch):
        stri=''
        for j in range(len(toens[i].cuda().cpu().numpy())):
            smi=model.vocabulary.reversed_vocab[int(toens[i][j])]
            stri+=smi
        smis.append(stri)

    return smis

class ORGAN(nn.Module):
    def __init__(self, vocabulary, config):
        super(ORGAN, self).__init__()

        self.metrics_reward = MetricsReward(
            config.n_ref_subsample, config.rollouts,
            config.n_jobs, config.additional_rewards)
        self.reward_weight = config.reward_weight

        self.vocabulary = vocabulary
        self.device=config.cuda

        self.generator_embeddings = nn.Embedding(
            len(vocabulary), config.embedding_size, padding_idx=vocabulary.vocab['<pad>']
        )
        self.discriminator_embeddings = nn.Embedding(
            len(vocabulary), config.embedding_size, padding_idx=vocabulary.vocab['<pad>']
        )
        # self.generator = Generator(
        #     self.generator_embeddings, config.hidden,
        #     config.num_layers, config.dropout,config.cuda
        # )
        self.generator=CharRNN(vocabulary, config)
        self.discriminator = Discriminator(
            self.discriminator_embeddings,
           config, config.discriminator_layers, config.discriminator_dropout
        )

    # @property
    # def device(self):
    #     return next(self.parameters()).device

    def generator_forward(self, *args, **kwargs):
        return self.generator(*args, **kwargs)

    def discriminator_forward(self, *args, **kwargs):
        return self.discriminator(*args, **kwargs)

    def forward(self, *args, **kwargs):
        return self.sample(*args, **kwargs)

    def string2tensor(self, string, device='model'):
        ids = self.vocabulary.string2ids(string, add_bos=True, add_eos=True)
        tensor = torch.tensor(ids, dtype=torch.long,
                              device=self.device
                              if device == 'model' else device)

        return tensor

    def tensor2string(self, tensor):
        str=''
        ids = tensor.tolist()
        for i in range(len(ids)):
            str+=self.vocabulary.reversed_vocab[ids[i]]
        # string = self.vocabulary.ids2string(ids, rem_bos=True, rem_eos=True)

        return str[5:-5]

    def _proceed_sequences(self, prevs, states, max_len):
        with torch.no_grad():
            n_sequences = prevs.shape[0]

            sequences = []
            lengths = torch.zeros(n_sequences,
                                  dtype=torch.long,
                                  device=prevs.device)

            one_lens = torch.ones(n_sequences,
                                  dtype=torch.long,
                                  device=prevs.device)
            is_end = prevs.eq(self.vocabulary.vocab['<eos>']).view(-1)

            for _ in range(max_len):
                outputs, _, states = self.generator(prevs, one_lens, states)
                probs = F.softmax(outputs, dim=-1).view(n_sequences, -1)
                currents = torch.multinomial(probs, 1)

                currents[is_end, :] = self.vocabulary.vocab['<pad>']
                sequences.append(currents)
                lengths[~is_end] += 1

                is_end[currents.view(-1) ==self.vocabulary.vocab['<eos>']] = 1
                if is_end.sum() == n_sequences:
                    break

                prevs = currents

            sequences = torch.cat(sequences, dim=-1)

        return sequences, lengths

    def rollout(self,
                n_samples, n_rollouts, ref_smiles,
                ref_mols, max_len=100):
        with torch.no_grad():
            sequences = []
            rewards = []
            lengths = torch.zeros(n_samples,
                                  dtype=torch.long,
                                  device=self.device)

            one_lens = torch.ones(n_samples,
                                  dtype=torch.long,
                                  device=self.device)
            prevs = torch.empty(n_samples, 1,
                                dtype=torch.long,
                                device=self.device).fill_(self.vocabulary.vocab['<bos>'])
            is_end = torch.zeros(n_samples,
                                 dtype=torch.uint8,
                                 device=self.device)
            states = None

            sequences.append(prevs)
            lengths += 1

            for current_len in range(max_len):
                outputs, _, states = self.generator(prevs, one_lens, states)
                probs = F.softmax(outputs, dim=-1).view(n_samples, -1)
                currents = torch.multinomial(probs, 1)

                currents[is_end, :] = self.vocabulary.vocab['<pad>']
                sequences.append(currents)
                lengths[~is_end] += 1

                rollout_prevs = currents[~is_end, :].repeat(n_rollouts, 1)
                rollout_states = (
                    states[0][:, ~is_end, :].repeat(1, n_rollouts, 1),
                    states[1][:, ~is_end, :].repeat(1, n_rollouts, 1)
                )
                rollout_sequences, rollout_lengths = self._proceed_sequences(
                    rollout_prevs, rollout_states, max_len - current_len
                )

                rollout_sequences = torch.cat(
                    [s[~is_end, :].repeat(n_rollouts, 1)
                     for s in sequences] + [rollout_sequences],
                    dim=-1
                )
                rollout_lengths += lengths[~is_end].repeat(n_rollouts)

                rollout_rewards = torch.sigmoid(
                    self.discriminator(rollout_sequences).detach()
                )

                if self.metrics_reward is not None and self.reward_weight > 0:
                    strings = [
                        self.tensor2string(t[:l])
                        for t, l in zip(rollout_sequences, rollout_lengths)
                    ]
                    obj_rewards = torch.tensor(
                        self.metrics_reward(strings, ref_smiles, ref_mols),
                        device=rollout_rewards.device
                    ).view(-1, 1)
                    rollout_rewards = (
                        rollout_rewards * (1 - self.reward_weight) +
                        obj_rewards * self.reward_weight
                    )

                current_rewards = torch.zeros(n_samples, device=self.device,dtype=float)
                rollout_rewards=rollout_rewards.double()

                current_rewards[~is_end] = rollout_rewards.view(
                    n_rollouts, -1
                ).mean(dim=0)
                rewards.append(current_rewards.view(-1, 1))

                is_end[currents.view(-1) == self.vocabulary.vocab['<eos>']] = 1
                if is_end.sum() == n_samples:
                    break

                prevs = currents

            sequences = torch.cat(sequences, dim=1)
            rewards = torch.cat(rewards, dim=1)

        return sequences, rewards, lengths

    def sample_tensor(self, n, max_len=100):
        prevs = torch.empty(n, 1,
                            dtype=torch.long,
                            device=self.device).fill_(self.vocabulary.vocab['<bos>'])
        samples, lengths = self._proceed_sequences(prevs, None, max_len)

        samples = torch.cat([prevs, samples], dim=-1)
        lengths += 1

        return samples, lengths

    def sample(self, batch_n, args,max_len=100):
        samples, lengths = self.sample_tensor(batch_n, max_len)
        samples = [t[:l] for t, l in zip(samples, lengths)]

        return samples


from app_prof_retraining.models import ProgramProfRetrain, CategoryProfRetrain
import csv
from django.core.management.base import BaseCommand

def import_data():
    with open('/Users/artemgoranskij/Desktop/25.csv') as csvfile:
        reader = csv.reader(csvfile, delimiter=';')
        for row in reader:
            ProgramProfRetrain.objects.create(
                category=CategoryProfRetrain.objects.get(pk=26),
                title=row[2],
                hours=row[1],
                qualification=row[0]
            )

class Command(BaseCommand):
    def handle(self, *args, **options):
        import_data()
        print('success')


def solve(string1, string2):
    s1 = ''
    s1_l = len(string1)-1

    flag = 0
    for i in range(s1_l, -1, -1):
        if string1[i]!='#' and flag==0:
            s1+=string1[i]

        elif string1[i]!='#' and flag!=0:
            flag-=1

        else:
            flag+=1

    s2 = ''
    s2_l = len(string2)-1
    flag = 0
    for i in range(s2_l, -1, -1):
        if string2[i]!='#' and flag==0:
            s2+=string2[i]

        elif string2[i]!='#' and flag!=0:
            flag-=1

        else:
            flag+=1

    return s1==s2

print(solve("a##c", "#a#c#"))