import turtle
import math
import random
import time

wn = turtle.Screen()
wn.bgcolor("pink")
wn.title("Playing Game")
wn.bgpic("blue-rose-glitter-animated 1.gif")
wn.tracer(3)

#draw border
mypen = turtle.Turtle()
mypen.penup()
mypen.setposition(-300,-300)
mypen.pendown()
mypen.pensize(3)
mypen.color("black")
for side in range(4):
    mypen.forward(600)
    mypen.left(90)
mypen.hideturtle()
player = turtle.Turtle()
player.color("red")
player.shape("turtle")
player.penup()
player.speed(0)

#create the score variable
Your_Score= 0
High_score= 0

#create goals
maxgoals = 8
goals = []

for count in range(maxgoals):
    goals.append(turtle.Turtle())
    goals[count].color("orange")
    goals[count].shape("circle")
    goals[count].penup()
    goals[count].speed(0)
    goals[count].setposition(random.randint(-300, 300), random.randint(-300,300))

#speed variable
speed = 1

#define functions
def turnleft():
    player.left(45)

def turnright():
    player.right(45)

def increasespeed():
    global speed
    speed +=1

def decreasespeed():
    global speed
    speed -=2

def isCollision(t1, t2):
    d = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2) + math.pow(t1.ycor()-t2.ycor(),2))
    if d < 20:
        return True
    else:
        return False

#set keyword binding
turtle.listen()
turtle.onkey(turnleft, "Left")

turtle.onkey(turnright, "Right")

turtle.onkey(increasespeed, "Up")

turtle.onkey(decreasespeed, "Down")

while True:
    player.forward(speed)

    #boundary checking
    if player.xcor() >300 or player.xcor() < -300:
        time.sleep(20)
        player.goto(0, 0)
        player.direction = "stop"

    #boundary for y
    if player.ycor() >300 or player.ycor() < -300:
        player.right(180)
        time.sleep(20)
        player.goto(0, 0)
        player.direction = "stop"
    #collision checking

    for count in range(maxgoals):
        goals[count].forward(3)

        if goals[count].xcor() >290 or goals[count].xcor() < -290:
             goals[count].right(180)

        #boundary for y
        if goals[count].ycor() >290 or goals[count].ycor() < -290:
             goals[count].right(180)

        #collison checking
        if isCollision(player, goals[count]):
            goals[count].setposition(random.randint(-300, 300), random.randint(-300,300))
            #for moving the goal
            goals[count].right(random.randint(0,360))
            Your_Score += 10

            #making the score in the screen
            mypen.undo()
            mypen.penup()
            mypen.hideturtle()
            mypen.setposition(-290, 310)
            scorestring = "Your_Score: %s" %Your_Score
            mypen.write(scorestring, False, align="left", font=("Arial",14, "normal"))


__license__ = "2019, Romain Graziani"
__docformat__ = 'reStructuredText'
__author__ = 'Romain Graziani <romain.graziani@clermont.in2p3.fr>'
__date__ = '2020/10/02 10:46:12'
__adv__ = 'plots.py'

import matplotlib.pyplot as mpl
from matplotlib.gridspec import GridSpec
from scipy.stats import binned_statistic_2d
import numpy as np

def make_focal_plane():
    fig = mpl.figure(figsize=(8,7.75))
    gs = GridSpec(4, 5, figure=fig,wspace=0.1,hspace=0.1, width_ratios = [1,1,1,1,0.1], height_ratios=[1,1,1,1])
    return fig, gs

def get_ax_cbar(fig, gs):
    ax = fig.add_subplot(gs[:,-1])
    return ax

def get_ax_ccd(fig, gs, ccd):
    j = ((ccd-1) % 4)
    i = 3- ((ccd-1) // 4)
    ax = fig.add_subplot(gs[i,j])
    return ax, i, j

def vminvmax_parser(data, vmin, vmax):
    """ """
    if vmin is None:
        vmin="0"
    if vmax is None:
        vmax = "100"
    if type(vmin) == str:
        vmin = np.percentile(data, float(vmin))
    if type(vmax) == str:
        vmax = np.percentile(data, float(vmax))
    return vmin, vmax

def get_threeplot_axes(fig=None, scalex=1, scaley=1, globalbottom=0, globalleft=0,
                        left= 0.05, width=0.25, bottom=0.15, heigth=0.75,
                        hspan=0.015, hxspan=0.1,
                        cwidth = 0.01):
    """ """
    if fig is None:
        fig = mpl.figure(figsize=[9,3])

    left, width = globalleft+left*scalex, width*scalex
    bottom, heigth = globalbottom+bottom*scaley, heigth*scaley
    hspan, hxspan = hspan*scalex,hxspan*scalex
    cwidth = cwidth*scalex

    axd = fig.add_axes([left+0*(width+hspan)     ,bottom,width,heigth])
    axm = fig.add_axes([left+1*(width+hspan)     ,bottom,width,heigth])
    cax = fig.add_axes([left+2*(width+hspan)     ,bottom,cwidth,heigth])
    axr = fig.add_axes([left+2*(width+hspan) +hxspan,bottom,width,heigth])
    caxr = fig.add_axes([left+3*(width+hspan)+hxspan,bottom,cwidth,heigth])
    axes = [axd,axm,axr]
    caxes = [cax, caxr]

    return fig, axes, caxes

def display_binned2d(ax, binneddata, xbins=None, ybins=None, vmin="5", vmax="95", cax=None,
                         transpose=False, cmap=None, **kwargs):
    """ """
    from ziff.plots import vminvmax_parser
    vmin_, vmax_ = vminvmax_parser(binneddata, vmin, vmax)
    if xbins is not None and ybins is not None:
        extent = (xbins[0],xbins[-1],ybins[0],ybins[-1])
    else:
        extent = None

    prop = dict(origin="lower", extent=extent)
    im = ax.imshow(binneddata.T if transpose else binneddata, cmap=cmap,
                    vmin=vmin_, vmax=vmax_, **{**prop,**kwargs})

    if cax is not None:
        ax.figure.colorbar(im, cax=cax)

    return im

def show_shapebinned(dataframe, nbins=50,
                     which="sigma", vmin="2", vmax="98", cmap='RdBu_r', normres=True,
                     tight_layout=True, rmflagout=True, cvmin=None, cvmax=None, suffix=["_stars","_model"],
                     normed_by=["ccdid", "obsjd"], ref="_model",normstat="median",
                     rvmin=-0.05, rvmax=0.05,
              ):
    """ """
    import matplotlib.pyplot as mpl
    from ziff.utils import vminvmax_parser
    from scipy.stats import binned_statistic_2d
    #
    # - Input
    if cvmax is None:
        cvmax = vmax
    if cvmin is None:
        cvmin = vmin
    # - end: Input
    #

    #
    if rmflagout:
        dataframe = dataframe[~(dataframe[f"flagout{suffix[0]}"] | dataframe[f"flagout{suffix[0]}"])]

    u,v, data, model = dataframe[["u_model","v_stars",f"{which}{suffix[0]}",f"{which}{suffix[1]}"]].values.T
    residual = (data-model)/model

    if normed_by is not None:
        grouped = dataframe.groupby(normed_by)
        normalisation = grouped[f"{which}{ref}"].transform(normstat)
        data  = data/normalisation
        model = model/normalisation

    #

    fig = mpl.figure(figsize=[10,3])
    left,width = 0.05, 0.25
    hspan, hxspan = 0.01,0.08

    axd = fig.add_axes([left+0*(width+hspan)     ,0.1,width,0.8])
    axm = fig.add_axes([left+1*(width+hspan)     ,0.1,width,0.8])
    axc = fig.add_axes([left+2*(width+hspan)     ,0.1,0.01,0.8])
    axr = fig.add_axes([left+2*(width+hspan) +hxspan,0.1,width,0.8])
    axcr = fig.add_axes([left+3*(width+hspan)+hxspan,0.1,0.01,0.8])
    axes = [axd,axm,axr]

    # Data to show

    vmin_, vmax_ = vminvmax_parser(model, vmin, vmax)

    bins_u = np.linspace(np.min(u),np.max(u),nbins)
    bins_v =  np.linspace(np.min(v),np.max(v),nbins)

    data_bstat = binned_statistic_2d(u, v, data, statistic="median", bins=[bins_u,bins_v]).statistic
    model_bstat = binned_statistic_2d(u, v, model, statistic="median", bins=[bins_u,bins_v]).statistic
    res_bstat = binned_statistic_2d(u, v, residual, statistic="median", bins=[bins_u,bins_v]).statistic

    default_imshow_kwargs =  {'cmap' : cmap, 'origin':'lower',
                              'extent' : (bins_u[0],bins_u[-1],bins_v[0],bins_v[-1]),
                              "vmin":vmin_, "vmax":vmax_}

    im = axd.imshow(data_bstat.T,  **default_imshow_kwargs)
    im = axm.imshow(model_bstat.T, **default_imshow_kwargs)
    fig.colorbar(im,cax=axc)
    im = axr.imshow(res_bstat.T, **{**default_imshow_kwargs,**{"vmin":rvmin, "vmax":rvmax}})
    fig.colorbar(im,cax=axcr)

    # Main axes
    [ax_.tick_params(labelsize="small", labelcolor="0.5") for ax_ in [axm, axd, axr]]
    # Color bars
    [ax_.tick_params(labelsize="medium", labelcolor="k") for ax_ in [axc, axcr]]
    axm.set_yticks([])
    axr.set_yticks([])
#    [[ax_.set_xticks([]),ax_.set_yticks([])] for ax_ in axes]

#
#   Plotting
#
def show_psfresults(psf, nstars=9, index=None, savefile=None, **kwargs):
    """
    if index given, nstars is ignored.
    """
    all_indexes = np.arange(len(psf.stars))
    if index is not None:
        nstars = len(index)
    elif nstars is not None:
        index = np.random.choice(all_indexes, nstars, replace=False)
    else:
        raise ValueError("you must provide easer nstars or index ; both are None")

    print(index)

    fig = mpl.figure(figsize=[9,3*nstars])
    for i, index_ in enumerate(index):
        _ = show_single_psfstar(psf, index_, fig=fig,
                            globalbottom=i/nstars, scaley=1/nstars, **kwargs)
        if i ==0:
            fig, axes, cax = _

    axes[0].set_xlabel("Data", weight="medium")
    axes[1].set_xlabel("Model", weight="medium")
    axes[2].set_xlabel("Residual", weight="medium")

    if savefile:
        fig.savefig(savefile)

    return fig

def show_single_psfstar(psf, index, fig=None,
                        scalex=1, scaley=1, globalbottom=0, globalleft=0,
                       vmin="1", vmax="99",cvmin="1", cvmax="99",
                        show_text=True, **kwargs):
    """ """
    fig, axes, caxes= get_threeplot_axes(fig=fig, scalex=scalex, scaley=scaley,
                                             globalbottom=globalbottom, globalleft=globalleft)
    [axd,axm,axr] = axes
    [cax, caxr] = caxes

    # Star and Model
    star_plotted  = psf.stars[index]
    model_plotted = psf.drawStar(star_plotted)

    data = star_plotted.image.array
    model = model_plotted.image.array
    residual = data-model

    vmin_, vmax_ = vminvmax_parser(data, vmin, vmax)
    cvmin_, cvmax_ = vminvmax_parser(residual, cvmin, cvmax)

    prop = dict(origin="lower", cmap="cividis", vmin=vmin_, vmax=vmax_)

    # Data
    scd = axd.imshow(data, **{**prop,**kwargs})
    fig.colorbar(scd, cax=cax)
    # Model
    scm = axm.imshow(model, **prop)
    fig.colorbar(scm, cax=cax)
    # Dif
    scr = axr.imshow(residual, **{**prop,**{"vmin":cvmin_, "vmax":cvmax_}, **kwargs})
    fig.colorbar(scr, cax=caxr)

    [[ax_.set_xticks([]),ax_.set_yticks([])] for ax_ in axes]
    [ax_.tick_params(labelsize="small") for ax_ in caxes]
    # - Text
    if show_text:
        axd.text(-0.02, 0.5, f"index: {index} (x={star_plotted.image.center.x}, y={star_plotted.image.center.y})",
                 transform=axd.transAxes, rotation=90, va="center", ha="right", fontsize="x-small", color="0.3")

    return fig, axes, caxes

# End of plots.py ========================================================


from typing import Optional
import numpy as np
from inputs import X, Y, Z, start_pts, end_pts, x_length, y_length, z_length

# set N, S, E, W to action keys for ease of understanding
N = 0
S = 1
E = 2
W = 3

actions_key = {
    0 : (0,1,0),  # North
    1 : (0,-1,0), # South
    2 : (1,0,0),  # East
    3 : (-1,0,0), # West
    4 : (0,0,1),  # Up
    5 : (0,0,-1),  # Down
    6 : (1,1,0),  # North-East
    7 : (1,-1,0), # North-West
    8 : (-1,1,0), # South-East
    9 : (-1,-1,0), # South-West
    10: (0,1,1),   # Up-North
    11: (0,1,-1),  # Down-North
    12: (0,-1,1),   # Up-South
    13: (0,-1,-1),  # Down-South
    14: (1,0,1),   # Up-East
    15: (1,0,-1),  # Down-East
    16: (-1,0,1),   # Up-West
    17: (-1,0,-1),  # Down-West
    # 18: (1,1,1),   # Up-North-East
    # 19: (1,1,-1),  # Down-North-East
    # 20: (-1,1,1),   # Up-North-West
    # 21: (-1,1,-1),  # Down-North-West
    # 22: (1,-1,1),   # Up-South-East
    # 23: (1,-1,-1),  # Down-South-East
    # 24: (-1,-1,1),   # Up-South-West
    # 25: (-1,-1,-1),  # Down-South-West
}

class PipeAgent:
    def __init__(self, start_pt, end_pt):
        self.position: Optional[np.darray] = None
        self.start_pt = start_pt
        self.end_pt = end_pt

    def initialize(self) -> None:
        # Pipe should be initialized to its start point

        self.position = self.start_pt
        self.goal = self.end_pt
        return self.position,self.goal

    def get_position(self):
        return self.position

    def move(self, direction: int) -> None:
        # 0,0 is top left for rendering, y down is positive

        # move agent to new position based on action
        self.position = np.add(self.position, actions_key[direction])

        # don't let agent move out of field
        if self.position[X] >= x_length:
            self.position[X] = x_length
        elif self.position[X] < 0.0:
            self.position[X] = 0.0
        if self.position[Y] >= y_length:
            self.position[Y] = y_length
        elif self.position[Y] < 0.0:
            self.position[Y] = 0.0
        if self.position[Z] >= z_length:
            self.position[Z] = z_length
        elif self.position[Z] < 0.0:
            self.position[Z] = 0.0

        return self.position


evidenciasPOO=[]
unidad1={}
unidad2={}
unidad3={}

class Promedio(Exception):
    def __init__(self,mensaje = 'El promedio no puede ser mayor a 10'):
        self.mensaje=mensaje
        super().__init__(self.mensaje)

    def __str__(self):
        return f'{self.mensaje}'

class Evidencias(Exception):
    def __init__(self,mensaje2 = 'Exceso o insuficiencia de evidencias'):
        self.mensaje2 = mensaje2
        super().__init__(self.mensaje2)

    def __str__(self):
        return f'{self.mensaje2}'
class Calificacion(Exception):
    def __init__(self,mensaje3 = 'Lo siento, Reprobaste'):
        self.mensaje3 = mensaje3
        super().__init__(self.mensaje3)

    def __str__(self):
        return f'{self.mensaje3}'

def evalu(num):
    if num > 3:
        return False
    elif num < 3:
        return False
    else:
        return True

def final(c1,c2,c3):
    calFi = (c1 + c2 +c3)/3.0
    ca = round(calFi,2)
    if calFi < 7:
        print('Calificacion: ',ca)
        raise Calificacion
    else:
        print('Felicidades aprobaste la materia con calificacion final: ',ca)

def promU(prom):
    if prom > 10:
        return False
    else:
        return True

def Ordinario(unidad,prom=0):
    for i in unidad:
        print('-----------------------------------')
        print('Evidencia {}  Calificacion: {} '.format(i+1,unidad[i]))
    print('-----------------------------------')
    cali = 0
    for i in unidad:
        cali = cali + unidad[i]
    prom = cali/3.0
    prome = promU(prom)
    if not(prome):
        raise Promedio
    if prom < 7:
        ot=Recuperacion(unidad)
        cali = 0
        for i in unidad:
            cali = cali + unidad[i]
        ot = cali/3.0
        return ot
    else:
        return prom

def Recuperacion(unidad,prom=0):
    print('Recuperacion de evidencias reprobadas')
    for i in unidad:
        if unidad[i] < 7:
            unidad[i] = float(input('Nueva calificacion de evidencia reprobada: '))
    for n in unidad:
        print('-----------------------------------')
        print('Evidencia {}  Calificacion: {} '.format(n+1,unidad[n]))
    print('-----------------------------------')
    cali = 0
    for i in unidad:
        cali = cali + unidad[i]
    prom = cali/3.0
    prome = promU(prom)
    if not(prome):
        raise Promedio
    if prom < 7:
        ot = Extraordinario(unidad)
        cali = 0
        for i in unidad:
            cali = cali + unidad[i]
        ot = cali/3.0
        return ot
    else:
        return prom

def Extraordinario(unidad,prom=0):
    print('Recuperacion extraordinaria de evidencias reprobadas')
    for i in unidad:
        if unidad[i] < 7:
            unidad[i] = float(input('Nueva calificacion de evidencia reprobada: '))
    for n in unidad:
        print('-----------------------------------')
        print('Evidencia {}  Calificacion: {} '.format(n+1,unidad[n]))
    print('-----------------------------------')
    cali = 0
    for i in unidad:
        cali = cali + unidad[i]
    prom = cali/3.0
    prome = promU(prom)
    if not(prome):
        raise Promedio
    else:
        return prom

def Lista(un1,un2,un3):
    evidenciasPOO=[un1,un2,un3]
    return evidenciasPOO

def calificacion(c1,c2,c3,evidenciasPOO):
    cali=[CAL1,CAL2,CAL3]
    for i in range(len(evidenciasPOO)):
        print('Unidad ',i+1,' ',evidenciasPOO[i])
        ca = round(cali[i],2)
        print('Promedio Unidad',i+1,' :',ca,'\n')

try:
    ciclo = 1
    while(ciclo):
        print('1.-Evidencias Unidad 1 ')
        print('2.-Evidencias Unidad 2 ')
        print('3.-Evidencias Unidad 3 ')
        print('4.-Promedio general de la materia')
        print('5.- Salir ')
        op=int(input("   :"))
        if op == 1:
            unidad1={}
            evidencias=int(input('Numero de evidencias: '))
            tot = evalu(evidencias)
            if not(tot):
                raise Evidencias
            for n in range(evidencias):
                ev=float(input('Evidencia: '))
                if(not(n in unidad1)):
                    unidad1[n]=ev
            CAL1=Ordinario(unidad1)
            ca = round(CAL1,2)
            print('Este es tu promedio',ca)

        elif(op == 2):
            unidad2={}
            evidencias=int(input('Numero de evidencias: '))
            tot = evalu(evidencias)
            if not(tot):
                raise Evidencias
            for n in range(evidencias):
                ev=float(input('Evidencia: '))
                if(not(n in unidad2)):
                    unidad2[n]=ev
            CAL2=Ordinario(unidad2)
            ca = round(CAL2,2)
            print('Este es tu promedio',ca)

        elif(op == 3):
            unidad3={}
            evidencias=int(input('Numero de evidencias: '))
            tot = evalu(evidencias)
            if not(tot):
                raise Evidencias
            for n in range(evidencias):
                ev=float(input('Evidencia: '))
                if(not(n in unidad3)):
                    unidad3[n]=ev
            CAL3=Ordinario(unidad3)
            ca = round(CAL1,2)
            print('Este es tu promedio',ca)

        elif(op == 4):
            lis = Lista(unidad1,unidad2,unidad3)
            calificacion(CAL1,CAL2,CAL3,lis)
            final(CAL1,CAL2,CAL3)

        elif(op == 5):
            ciclo=0
            print('Gracias por su atencion')

        else:
            print('Opcion no valida, Intentalo de nuevo')

except Promedio as err:
    print('El error es: ',err.mensaje)

except Evidencias as err:
    print('El error es: ',err.mensaje2)

except Calificacion as err:
    print('Mensaje: ',err.mensaje3)

except Exception as err:
    print('El error es',err)

Nueva carpeta (2)/Extraordinario Programas Excepciones.py


"""
Core components for plant implementations.
"""

import ode
from gymwipe.simtools import SimMan

class Plant:
    """
    Plants are supposed to hold the state of a simulated plant and make it
    accessible to simulated sensors and modifyable by simulated actuators.
    The :class:`Plant` class itself does not provide any features.
    """

class OdePlant(Plant):
    """
    A :class:`Plant` implementation that interacts with an ODE world object: It
    offers an :meth:`updateState` method that makes the ODE world simulate
    physics for the SimPy simulation time that has passed since the most recent
    :meth:`updateState` call.
    """

    def __init__(self, world: ode.World = None):
        """
        Args:
            world: A py3ode :class:`World` object. If not provided, a new one will be
                created with gravity ``(0,-9.81,0)``.
        """
        if world is None:
            world = ode.World()
            world.setGravity((0,-9.81,0))
        self.world = world
        self.maxStepSize = 0.05
        self._lastUpdateSimTime = SimMan.now
        SimMan.process(self._stateUpdater())

    def updateState(self):
        """
        Performs an ODE time step to update the plant's state according to the
        current simulation time.
        """
        now = SimMan.now
        # Rounding difference to nanoseconds to prevent strange ODE behavior
        difference = round(now - self._lastUpdateSimTime, 9)

        if difference > 0:
            self.world.step(difference)
            self._lastUpdateSimTime = now

    def _stateUpdater(self):
        """
        A SimPy process that regularly performs ODE time steps when no ODE time step
        was previously taken within maxStepSize
        """
        while True:
            yield SimMan.timeout(self.maxStepSize)
            if self._lastUpdateSimTime <= SimMan.now - self.maxStepSize:
                self.updateState()


import os
import os.path as op
import pydicom
import pandas as pd
import matplotlib.pyplot as plt
import json
import sys

BASE_DIR = op.dirname(op.dirname(op.abspath(__file__)))

NEEDED_TAGS = {
    'PatientID': '0010,0020',
    'PatientAge': '0010,1010',
    'PatientSex': '0010,0040',
    'PatientWeight': '0010,1030',
    'PatientSize': '0010,1020',
    'PatientBirthDate': '0010,0030',
    'StudyDate': '0008,0020',
    'StudyTime': '0008,0030',
    'StudyID': '0020,0010',
    'StudyDescription': '0008,1030',
    'StudyInstanceUID': '0020,000D',
    'StudyComments': '0032,4000',
    'Modality': '0008,0060',
    'SeriesInstanceUID' : '0020,000E',
    'SeriesDescription': '0008,103E',
    'SeriesNumber': '0020,0011',
    'SeriesInstanceUID': '0020,000E',
    'ManufacturerModelName': '0008,1090',
    'SliceThickness': '0018,0050',
    'WindowWidth': '0028,1051',
}

PATIENT_TAGS = {
    'PatientID': '0010,0020',
    'PatientAge': '0010,1010',
    'PatientSex': '0010,0040',
    'PatientWeight': '0010,1030',
    'PatientSize': '0010,1020',
    'PatientBirthDate': '0010,0030',
}

STUDY_TAGS = {
    'StudyDate': '0008,0020',
    'StudyTime': '0008,0030',
    'StudyID': '0020,0010',
    'StudyDescription': '0008,1030',
    'StudyInstanceUID': '0020,000D',
    'StudyComments': '0032,4000',
}

SERIES_TAGS = {
    'SeriesDate': '0008,0021',
    'SeriesTime': '0008,0031',
    'SeriesNumber': '0020,0011',
    'SeriesDescription': '0008,103E',
    'SeriesInstanceUID': '0020,000E',
    'SeriesComments': '0032,4000',
    'Modality': '0008,0060',
    'ProtocolName': '0018,1030',
    'BodyPartExamined': '0018,0015',
    'Manufacturer': '0008,0070',
    'ManufacturerModelName': '0008,1090',
    'MagenticFieldStrength': '0018,0087',
    'EchoTime': '0018,0081',
    'RepetitionTime': '0018,0080',
    'InversionTime': '0018,0082',
    'FlipAngle': '0018,1314',
    'RadiopharmaceuticalInformationSequence': '0054,0010',
    'Radiopharmaceutical': '0018,0031',
}

IMAGE_TAGS = {
    'ImageType': '0008,0008',
    'InstanceNumber': '0020,0013',
    'ImagePositionPatient': '0020,0032',
    'ImageOrientationPatient': '0020,0037',
    'SliceLocation': '0020,1041',
    'PixelSpacing': '0028,0030',
    'SliceThickness': '0018,0050',
    'Rows': '0028,0010',
    'Columns': '0028,0011',
    'WindowCenter': '0028,1050',
    'WindowWidth': '0028,1051',
    'RescaleIntercept': '0028,1052',
    'RescaleSlope': '0028,1053',
    'RescaleType': '0028,1054',
    'SOPInstanceUID': '0008,0018',
}

MODALITY_TAGS = {
    'PT': 'pet',
    'CT': 'ct',
    'MR': 'mr',
    'US': 'us',
    'XA': 'xa',
}

def guess_mri_sequence(ds):
    """ Find out MRI sequence by reading meaningful DICOM tags """

    et = ds.EchoTime
    rt = ds.RepetitionTime
    it = ds.InversionTime
    fa = ds.FlipAngle

    if et == 0.0 and rt == 0.0 and it == 0.0 and fa == 0.0:
        return 'T1'
    elif et == 0.0 and rt == 0.0 and it == 0.0 and fa != 0.0:
        return 'T2'
    elif et != 0.0 and rt != 0.0 and it == 0.0 and fa == 0.0:
        return 'FLAIR'
    elif et != 0.0 and rt != 0.0 and it == 0.0 and fa != 0.0:
        return 'PD'
    elif et != 0.0 and rt != 0.0 and it != 0.0 and fa != 0.0:
        return 'SWI'
    else:
        return 'UNKNOWN'

def get_series_modality(dcm_file):
    """ Get series modality """
    modality = pydicom.dcmread(dcm_file).Modality
    print("modality: ",modality)
    return

def get_study_instance_uid(dcm_file):
    """ Get study instance UID """
    uid = pydicom.dcmread(dcm_file).StudyInstanceUID
    print("study instance id: ",uid)
    return

def get_patient_id(dcm_file):
    """ Get patient ID """
    id = pydicom.dcmread(dcm_file).PatientID
    print("patient id: ",id)
    return id

def read_dicom2(dcm_file,dataset,dataset_name):
    ds = pydicom.dcmread(dcm_file)
    tags_values = [(tag, ds.data_element(tag).value) if tag in ds else (tag,'') for tag in NEEDED_TAGS]

    #check if dataset is empty, if so, add the tags and values to the dataset
    if dataset.empty:
        #the columns are defined by the tags
        dataset = pd.DataFrame(columns=[tag for tag, value in tags_values])
        dataset.loc[len(dataset.index)] = [value for tag, value in tags_values]
        #for tag, value in tags_values:
        #    dataset[tag] = value
    #store the tags and values in the dataset only if the patientid is not already in the pandas dataset
    #elif ds.data_element("PatientID").value not in dataset["PatientID"].values:
    elif (dataset.loc[(dataset["PatientID"] == ds.data_element("PatientID").value) & (dataset["StudyInstanceUID"] == ds.data_element("StudyInstanceUID").value) & (dataset["StudyID"] == ds.data_element("StudyID").value) & (dataset['SeriesInstanceUID'] == ds.data_element("SeriesInstanceUID").value)]).empty:
        #print rows where patientid is the same as the one in the dicom file
        #if (dataset.loc[dataset["PatientID"] == ds.data_element("PatientID").value & dataset["StudyInstanceUID"] == ds.data_element("SeriesInstanceUID").value & dataset["StudyID"] == ds.data_element("StudyID").value]).empty:
        #    print("aaaaaaaaaaaaa")
        #print("ooooooooo")
        #print(dataset.loc[(dataset["PatientID"] == ds.data_element("PatientID").value) & (dataset["StudyInstanceUID"] == ds.data_element("StudyInstanceUID").value)])
        #dataset.loc[len(dataset.index)] = [value for tag, value in tags_values]
        #for tag, value in tags_values add the value to the dataset
        #dataset.append(tags_values)
        dataset.loc[len(dataset.index)] = [value for tag, value in tags_values]
    #dataset.loc[len(dataset.index)] = [value for tag, value in tags_values]
    #dataset = pd.concat([dataset, pd.DataFrame(columns=[tag for tag, value in tags_values])])

    #print(dataset)
    return dataset

def read_dicom(dcm_file,patient_list):
    """ Read DICOM tags of interest """

    ds = pydicom.dcmread(dcm_file)
    #print(f"DICOM metadata: \n {ds}")

    # Patient tags
    #for t in PATIENT_TAGS:
    #    print(ds.data_element(t).value)
    #print(ds.data_element("PatientID").value)
    #tags_values = [ds.data_element(tag).value for tag in PATIENT_TAGS.values()]
    #tags_values = [(tag,ds.data_element(tag).value) for tag in PATIENT_TAGS]
    tags_values = [(tag, ds.data_element(tag).value) if tag in ds else (tag,'') for tag in PATIENT_TAGS]

    patient_id = ds.data_element("PatientID").value
    study_id = ds.data_element("StudyID").value
    series_id = ds.data_element("SeriesInstanceUID").value

    #we suppose that the patient id is unique and that all files have the same patient id,study id and series id has the same useful information to change
    #TODO
    #this has to be changed to another function later as now is being used to store patient data in a csv file and json file

    if not patient_list:
        patient_list = [(patient_id,study_id,series_id)]
    elif (patient_id,study_id,series_id) not in patient_list:
        patient_list.append((patient_id,study_id,series_id))
    else:
        #print("Patient already in the list")
        return patient_list
    dict_values = dict(tags_values)
    df = pd.DataFrame.from_dict(dict_values, orient='index')
    df.to_csv(op.join(BASE_DIR, 'data', 'patient-{patient_id}-data.csv'.format(patient_id=patient_id)), header=False)
    #df.to_json(op.join(BASE_DIR, 'data', 'patient-{patient_id}-data.json'), orient='records')
    #df.to_csv(op.join(BASE_DIR, 'data', 'patient-{patient_id}-data.csv'), header=False)
    #df.to_json(op.join(BASE_DIR, 'data', 'patient-{patient_id}-data.json',orient='index'))
    #with open(op.join(BASE_DIR, 'data', 'patient-{patient_id}-data.json'), "w") as outfile:
    json_file = open(op.join(BASE_DIR, 'data', 'patient-{patient_id}-data.json'.format(patient_id=patient_id)), "w")
    json.dump(dict_values,json_file, indent=4)
    json_file.close()

    # Study tags
    [(tag, ds.data_element(tag).value) if tag in ds else (tag,'') for tag in STUDY_TAGS]

    dict_values = dict(tags_values)
    df = pd.DataFrame(tags_values)
    df.to_csv(op.join(BASE_DIR, 'data', 'study-{study_id}-data.csv'.format(study_id=study_id)), header=False)
    json_file = open(op.join(BASE_DIR, 'data', 'study-{study_id}-data.json'.format(study_id=study_id)), "w")
    json.dump(dict_values,json_file, indent=4)
    json_file.close()

    # Series tags
    [(tag, ds.data_element(tag).value) if tag in ds else (tag,'') for tag in SERIES_TAGS]

    dict_values = dict(tags_values)
    df = pd.DataFrame(tags_values)
    df.to_csv(op.join(BASE_DIR, 'data', 'series-{series_id}-data.csv').format(series_id=series_id), header=False)
    json_file = open(op.join(BASE_DIR, 'data', 'series-{series_id}-data.json'.format(series_id=series_id)), "w")
    json.dump(dict_values,json_file, indent=4)
    json_file.close()

    return patient_list

def grab_dataset_deatiled_info(dcm_file):
    """ Create a CSV file summarizing the relavant information for this dataset """

    TAGS = {
        'PID': 'PatientID',
        'IID': 'ImageID',
        'SID': 'DatasetID',
        'IMAGING': 'ImagesModalities',
        'ORIGIN': 'ImagesOrigin',
        'DESTINATION': 'ImagesDestination',
    }

    df = pd.DataFrame(columns=TAGS.keys())
    # TODO Fill whit the data

def plot_dicom(ds):

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(ds.pixel_array, cmap="gnuplot2")
    fig.savefig(op.join(BASE_DIR, 'data', 'pet-dicom.png'))

if __name__ == "__main__":
    dicom_files = os.listdir(op.join(BASE_DIR, 'data'))
    for dcm_file in dicom_files:
        dcm_file = op.join(BASE_DIR, 'data', dcm_file)
        read_dicom(dcm_file)
        # plot_dicom(dcm_file)

def list_files(directory, output):
    #creates in the output file a list of files and sub directories of the directory given
    #if there is output file it will write to it, else it will print to the console
    original_stdout = sys.stdout # Save a reference to the original standard output
    if output:
        f = open(output, 'w')
        sys.stdout = f # Change the standard output to the file
    #walk through the directory
    for dir, dirs, files in os.walk(directory, topdown=False):
    #print(dir)
        for name in files:
            #fwriteline = dir + '/' + name
            print(dir + '/' + name)
    f.close()
    sys.stdout = original_stdout # Reset the standard output to its original value

def read_list_files(directory, output):
    #gets only the name of the subdirectory
    output_name = os.path.basename(directory)
    output_dir_dataset = op.join(output, output_name)
    os.makedirs(output_dir_dataset, exist_ok=True)
    patient_list = list()
    #creates empty pandas dataframe
    df = pd.DataFrame()
    total_df = pd.DataFrame()

    #reads each subdirectory of the directory given and creates a folder with the name of the subdirectory at the output
    # Loop through each subdirectory in the input directory
    for subdir in os.listdir(directory):
        # Check if the subdirectory is a directory (not a file)
        if os.path.isdir(os.path.join(directory, subdir)):
            # Create a new directory with the same name as the subdirectory
            new_dir = os.path.join(output_dir_dataset, subdir)
            os.makedirs(new_dir, exist_ok=True)

        #transform the DICOM files in NIFTI files
        #os.sytem(f'dcm2niix -z y -f {op.basename(nifti_file)} -o {output_dir} {dicom_dir}')

        #reads the DICOM files from the list of files and sub directories of the directory given
        for dir, dirs, files in os.walk(directory, topdown=False):
        #print(dir)
            for name in files:
                #print(dir + '/' + name)
                #print("\n______----------------_______\n")
                #check if is a DICOM file
                if name.endswith(".dcm"):
                    #patient_list = read_dicom(dir + '/' + name,patient_list)
                    df = read_dicom2(dir + '/' + name,df,output_name)
                #print("\n**********\n\n**********\n\n**********\n")
        #stores the pandas dataframe in a csv file in the output directory named with the name of the last sub directory of the directory given
        df.to_csv(op.join(new_dir, output_name + '.csv'), header=True)
        #for each modality creates a csv file with the information of all the patients
        for series_description in df['SeriesDescription'].unique():
            df[df['SeriesDescription'] == series_description].to_csv(op.join(new_dir, series_description + '.csv'), header=True)
            df[df['SeriesDescription'] == series_description].to_json(op.join(new_dir, series_description + "_read" + '.json'),orient="records",lines=True)

        if total_df.empty:
            #the columns are defined by the tags
            total_df = df.copy()
        else:
            total_df = pd.concat([total_df, df], ignore_index=True)
    total_df.to_csv(op.join(output_dir_dataset, output_name + '.csv'), header=True)

def read_list_files2(directory, output):
    #gets only the name of the subdirectory
    output_name = os.path.basename(directory)
    output_dir_dataset = op.join(output, output_name)
    os.makedirs(output_dir_dataset, exist_ok=True)
    patient_list = list()
    #creates empty pandas dataframe
    df = pd.DataFrame()
    total_df = pd.DataFrame()

    #reads each subdirectory of the directory given and creates a folder with the name of the subdirectory at the output
    # Loop through each subdirectory in the input directory
    for subdir in os.listdir(directory):

        #transform the DICOM files in NIFTI files
        #os.sytem(f'dcm2niix -z y -f {op.basename(nifti_file)} -o {output_dir} {dicom_dir}')

        #reads the DICOM files from the list of files and sub directories of the directory given
        for dir, dirs, files in os.walk(directory, topdown=False):
        #print(dir)
            for name in files:
                #print(dir + '/' + name)
                #print("\n______----------------_______\n")
                #check if is a DICOM file
                if name.endswith(".dcm"):
                    #patient_list = read_dicom(dir + '/' + name,patient_list)
                    total_df = read_dicom2(dir + '/' + name,total_df,output_name)
                #print("\n**********\n\n**********\n\n**********\n")
        #if total_df.empty:
            #the columns are defined by the tags
        #    total_df = df.copy()
        #else:
            #total_df = pd.concat([total_df, df], ignore_index=True)
    #total_df = total_df.drop_duplicates()
    #df.loc[df.astype(str).drop_duplicates().index]
    total_df.to_csv(op.join(output_dir_dataset, output_name + '.csv'), header=True)

    #for each PatientID it creates a folder with the name of the PatientID
    for patientid in total_df["PatientID"].unique():
        new_dir = os.path.join(output_dir_dataset, patientid)
        os.makedirs(new_dir, exist_ok=True)
        #for each modality creates a csv file with the information of the patient
        df_patient = total_df[total_df["PatientID"] == patientid]
        for series_description in df_patient['SeriesDescription'].unique():
            df_patient[df_patient['SeriesDescription'] == series_description].to_csv(op.join(new_dir, series_description + '.csv'), header=True)
            df_patient[df_patient['SeriesDescription'] == series_description].to_json(op.join(new_dir, series_description + "_read" + '.json'),orient="records",lines=True)

def read_dicom3(dcm_file):
    ds = pydicom.dcmread(dcm_file)
    tags_values = [(tag, ds.data_element(tag).value) if tag in ds else (tag,'') for tag in NEEDED_TAGS]
    dataset = pd.DataFrame(columns=[tag for tag, value in tags_values])
    dataset.loc[len(dataset.index)] = [value for tag, value in tags_values]
    return dataset

def read_list_files3(directory, output,filter,notdcm2nix,tojson):
    filter_list = filter.split(",")
    print(filter_list)
    #gets only the name of the subdirectory
    output_name = os.path.basename(directory)
    output_dir_dataset = op.join(output, output_name)
    os.makedirs(output_dir_dataset, exist_ok=True)
    patient_list = list()
    #creates empty pandas dataframe
    df = pd.DataFrame()
    total_df = pd.DataFrame()

    #reads each subdirectory of the directory given and creates a folder with the name of the subdirectory at the output
    # Loop through each subdirectory in the input directory
    for subdir in os.listdir(directory):

        #reads each file of in all the subdirectories of the directory given
        for dir, dirs, files in os.walk(directory, topdown=False):
            for name in files:
                #check if is a DICOM file and if all the filters are in the path
                if name.endswith(".dcm") and all(x in (dir + '/' + name) for x in filter_list):
                    #reads the directory of the DICOM file, being the last directory the seriesid,the second to last the studyid and the third to last the patientid
                    #the directory is split by the character "/"
                    dir_split = os.path.normpath(dir).split(os.sep)
                    #the patientid is the third to last element of the list
                    patientid = dir_split[-3]
                    #the studyid is the second to last element of the list
                    studyid = dir_split[-2]
                    #the seriesid is the last element of the list
                    seriesid = dir_split[-1]
                    #total_df = read_dicom2(dir + '/' + name,total_df,output_name)
                    line = read_dicom3(dir + '/' + name)
                    line['PatientID'] = patientid
                    line['StudyID'] = studyid
                    line['SeriesID'] = seriesid
                    line["Path"] = dir
                    #total_df = total_df.append(line)
                    total_df = pd.concat([total_df, line])
                    total_df = total_df.loc[:,["PatientID","StudyID","SeriesID","Path"]]

    if not total_df.empty:
        print(total_df)
        #for each PatientID it creates a folder with the name of the PatientID
        for patientid in total_df["PatientID"].unique():
            new_dir = os.path.join(output_dir_dataset, patientid)
            os.makedirs(new_dir, exist_ok=True)

            #for each seriesid it stores in a csv file the information of the first dataframe line
            df = total_df.loc[(total_df["PatientID"] == patientid)]
            df = df.drop_duplicates(subset=['PatientID', 'SeriesID'], keep='first')
            df.to_csv(op.join(new_dir, "series.csv"), header=True)
            df.to_json(op.join(new_dir, 'series.json'),orient="records",lines=True)

            #creates a nifti file for each seriesid
            for seriesid in df['SeriesID'].unique():
                #takes the path of the seriesid
                path = df.loc[(df["SeriesID"] == seriesid), "Path"].iloc[0]
                #print(path)
                #print(new_dir)
                if not notdcm2nix:
                    #os.system(f'dcm2niix.exe -z y -f %p -o "{new_dir}" "{path}"')
                    os.system(f'dcm2niix -z y -f %p -o "{new_dir}" "{path}"')

        #

            total_df.to_csv(op.join(output_dir_dataset, output_name + '.csv'), header=True)
            if tojson:
                total_df.to_json(op.join(output_dir_dataset, output_name + '.json'),orient="records",lines=True)

def list_series(path,output):
    #for each directory and subdirectory of the path given it reads the first dicom file, stores it in a dataframe and prints it
    list_series = pd.DataFrame()
    for dir, dirs, files in os.walk(path, topdown=False):
        for name in files:
            if name.endswith(".dcm"):
                ds = pydicom.dcmread(dir + '/' + name)
                serie = ds.data_element("SeriesInstanceUID").value
                path = os.path.normpath(dir)
                list_series = list_series.append({'SeriesInstanceUID': serie, 'Path': path}, ignore_index=True)
                break
    print(list_series)
    #if output is a string
    if output != "":
        list_series.to_csv(op.join(output, 'serieslist' + '.csv') , header=True)


import graphene
from graphene import NonNull, Schema, String
from graphene.test import Client
from graphene_django.utils import GraphQLTestCase

from courses.models.Category import Category
from courses.models.Course import Course
from courses.models.LearningFormat import LearningFormat
from users.models import User
from users.models.Teacher import Teacher

from ...models.Lesson import Lesson
from ...models.LessonTypeChoices import LessonTypeChoices
from ...nodes.LessonTypeNode import LessonTypeNode
from ...schema.PublicLessonType import PublicLessonType

class PublicLessonTypeTestCase(GraphQLTestCase):
    databases = {'master', }

    @classmethod
    def setUpTestData(cls):
        cls.tested_class = PublicLessonType
        cls.model = Lesson

        user = User.objects.create_user(**{
            'email': 'q' * 50 + '@q.qq',
            'password': 'q' * 50,
        })

        teacher = Teacher.objects.create(**{
            'user': user,
            'description': 'q' * 50,
        })

        category = Category.objects.create(**{
            'title': 'q' * 50,
        })

        course = Course.objects.create(**{
            'teacher': teacher,
            'title': 'q' * 50,
            'price': 50.0,
            'count_lectures': 50,
            'count_independents': 50,
            'duration': 50,
            'learning_format': LearningFormat.REMOTE,
            'category': category,
            'preview': 'temporary_img',
            'short_description': 'q' * 50,
        })

        lesson = Lesson.objects.create(**{
            'id': 1,
            'course': course,
            'title': 'q' * 50,
            'description': 'q' * 50,
            'lesson_type': LessonTypeChoices.THEME,
        })

        Lesson.objects.create(**{
            'id': 2,
            'course': course,
            'title': 'q' * 50,
            'description': 'q' * 50,
            'lesson_type': LessonTypeChoices.THEORY,
            'parent': lesson,
        })

        Lesson.objects.create(**{
            'id': 3,
            'course': course,
            'title': 'q' * 50,
            'description': 'q' * 50,
            'lesson_type': LessonTypeChoices.TEST,
            'parent': lesson,
        })

    def setUp(self):
        class PublicLessonQuery(graphene.ObjectType):
            public_lesson = LessonTypeNode.Field(PublicLessonType)

        schema = Schema(query=PublicLessonQuery)
        self.gql_client = Client(schema=schema)

    def test_Should_IncludeDefiniteDjangoModel(self):
        expected_model = self.model
        real_model = self.tested_class._meta.model

        self.assertEqual(expected_model, real_model)

    def test_Should_IncludeDefiniteInterfaces(self):
        expected_interfaces = [
            LessonTypeNode,
        ]
        real_interfaces = list(self.tested_class._meta.interfaces)

        self.assertEqual(expected_interfaces, real_interfaces)

    def test_Should_IncludeDefiniteFieldsFromModel(self):
        expected_fields = [
            'id', 'serial_number', 'title', 'description', 'lesson_type',
        ]
        real_fields = list(self.tested_class._meta.fields)

        self.assertEqual(expected_fields, real_fields)

    def test_Should_SpecificTypeForEachField(self):
        expected_fields = {
            'lesson_type': String,
            'serial_number': String,
        }
        real_fields = {
            key: value.type
            for key, value in self.tested_class._meta.fields.items()
        }

        all_fields_is_nonnull = all([
            real_fields.pop(field).__class__ == NonNull for field in [
                'id', 'title', 'description',
            ]
        ])

        self.assertEqual(expected_fields, real_fields)
        self.assertTrue(all_fields_is_nonnull)

    def test_When_SendQueryWithParentId_Should_ReturnDataWithOutErrors(self):
        response = self.gql_client.execute(
            """
            query {
                publicLesson (id: "UHVibGljTGVzc29uVHlwZTox") {
                    id
                    title
                    description
                    lessonType
                    serialNumber
                }
            }
            """
        )

        expected_response = {
            'data': {
                'publicLesson': {
                    'id': 'TGVzc29uVHlwZTox',
                    'title': 'q' * 50,
                    'description': 'q' * 50,
                    'lessonType': 'Тема',
                    'serialNumber': '1.',
                },
            },
        }
        real_response = response

        self.assertEqual(expected_response, real_response)

    def test_When_SendQueryWithChildrenId_Should_ReturnDataWithOutErrors(self):
        response = self.gql_client.execute(
            """
            query {
                publicLesson (id: "UHVibGljTGVzc29uVHlwZToy") {
                    id
                    title
                    description
                    lessonType
                    serialNumber
                }
            }
            """
        )

        expected_response = {
            'data': {
                'publicLesson': {
                    'id': 'TGVzc29uVHlwZToy',
                    'title': 'q' * 50,
                    'description': 'q' * 50,
                    'lessonType': 'Теория',
                    'serialNumber': '1.1.',
                },
            },
        }
        real_response = response

        self.assertEqual(expected_response, real_response)

    def test_When_SendQueryWithTestId_Should_ReturnDataWithOutErrors(self):
        response = self.gql_client.execute(
            """
            query {
                publicLesson (id: "UHVibGljTGVzc29uVHlwZToz") {
                    lessonType
                }
            }
            """
        )

        expected_response = {
            'data': {
                'publicLesson': {
                    'lessonType': 'Тест',
                },
            },
        }
        real_response = response

        self.assertEqual(expected_response, real_response)


import sys

"""
expected: P6A_T02
  18 - trip_id: None
  28 - trip_id: P5A_T01
  43 - trip_id: P5A_T02
 716 - trip_id: P6A_T02
i: 2021-12-08-07-04-tcrta-0
expected: D2_T01
  26 - trip_id: None
  63 - trip_id: DCW_T01
 916 - trip_id: D2_T01
  94 - trip_id: D4_T01
i: 2021-12-08-07-09-tcrta-0
expected: D1_T01
"""

EXPECTED_KEY = 'expected: '
TRIP_ID_KEY = '- trip_id: '
NAME_KEY = 'i: '

def main(filename):
    with open(filename, 'r') as f:
        lines = f.readlines()
        lines.append('i: sentinel')
        index = 0
        correct = 0
        incorrect = 0
        expected_trip_id = None
        name = None
        sum = 0
        items = 0

        while index < len(lines):
            line = lines[index].strip()
            index += 1
            #print(f'- line: {line}')

            if line.startswith(NAME_KEY):
                total = correct + incorrect

                if total > 0:
                    correct_pct = int(correct * 100 / total)
                    print(f'{name}: {correct_pct}%')
                    sum += correct_pct
                    items += 1

                correct = 0
                incorrect = 0
                name = line[len(NAME_KEY):]

            if line.startswith(EXPECTED_KEY):
                expected_trip_id = line[len(EXPECTED_KEY):]
                #print(f'- expected_trip_id: \'{expected_trip_id}\'')

            i = line.find(TRIP_ID_KEY)
            if i > 0:
                tok = line.split(' ')
                trip_id = tok[-1]
                #print(f'- trip_id: \'{trip_id}\'')
                count = int(tok[0])
                #print(f'- count: {count}')

                if trip_id == expected_trip_id:
                    correct += count
                else:
                    incorrect += count

        print(f'-----------------------------')
        print(f'                     avg: {int(sum / items)}%')

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(f'usage: {sys.argv[0]} <filename>')
        exit(1)

    main(sys.argv[1])


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 10 22:49:06 2022

@author: aggelen
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import seaborn as sns
import torchvision
from torchvision import transforms

class SimpleConstantCurrentSource:
    def __init__(self, dt, t_stop, signal):
        self.t_stop = t_stop
        self.dt = dt
        self.steps = np.arange(int(self.t_stop / self.dt))

        self.currents = signal
        self.current_step = 0
        self.source_type = 'current'

    def plot(self):
        plt.figure()
        plt.plot(np.arange(self.currents.shape[1])*self.dt, self.currents.T)
        plt.title('Injected Currents')
        plt.xlabel('Time (ms)')
        plt.ylabel('Current ()')

    def I(self):
        I = self.currents[:,self.current_step]
        self.current_step += 1
        return I

class ConstantCurrentSource:
    def __init__(self, params):
        ts, te, self.t_stop, amp = params['t_cur_start'], params['t_cur_end'], params['t_stop'], params['amplitudes']
        self.dt = params['dt']
        self.steps = np.arange(int(self.t_stop / self.dt))

        # signals = np.multiply(np.ones((ts.size, self.steps.size)), amp[:, np.newaxis])
        signals = np.zeros((ts.size, self.steps.size))
        ind_s, ind_e = ts/self.dt, te/self.dt

        for i in range(ts.size):
            signals[i, int(ind_s[i]):int(ind_e[i])] = amp[i]

        self.currents = signals
        self.current_step = 0
        self.source_type = 'current'

    def plot(self):
        plt.figure()
        plt.plot(np.arange(self.currents.shape[1])*self.dt, self.currents.T)
        plt.title('Injected Currents')
        plt.xlabel('Time (ms)')
        plt.ylabel('Current ()')

    def I(self):
        I = self.currents[:,self.current_step]
        self.current_step += 1
        return I

class SpikeTrain:
    def __init__(self):
        self.current_step = 0

    def reset(self):
        self.current_step = 0

    def current_spikes(self):
        spikes = self.spikes[:,self.current_step]
        self.current_step += 1
        return spikes

    def raster_plot(self, color_array=None, first_n=None, title=None, title_pad=0):
        f = plt.figure()
        if title is not None:
            plt.title(title, pad=title_pad)
        else:
            plt.title('Raster Plot', pad=title_pad)
        plt.xlabel('Time (ms)')
        plt.ylabel('Neuron ID')
        # spike_times = []

        mean_spike_rate = np.sum(self.spikes,1).mean() / (self.t_stop/1000)
        print('Output Mean Spike Rate: {}'.format(mean_spike_rate))

        if first_n is not None:
            spike_loc = np.argwhere(self.spikes[:first_n,:])
        else:
            spike_loc = np.argwhere(self.spikes)

        sns.set()
        colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
        if color_array is not None:
            # c = plt.cm.Set1(color_array[spike_loc[:,0]])
            c = []
            for k in color_array[spike_loc[:,0]]:
                c.append(colors[int(k)])
        else:
            c = colors[0]

        plt.scatter(spike_loc[:,1]*self.dt, spike_loc[:,0], s=3, color=c)
        plt.xlim([0,(spike_loc[:,1]*self.dt)[-1]])

class ExternalSpikeTrain(SpikeTrain):
    def __init__(self, dt, t_stop, no_neurons, spike_train):
        super().__init__()
        self.dt = dt
        self.t_stop = t_stop
        self.no_neurons = no_neurons
        self.steps = np.arange(int(t_stop / dt))

        self.spikes = spike_train

        self.source_type = 'spike_train'
        self.current_step = 0

        if self.spikes.shape.__len__() == 1:
            self.mean_spike_rate = self.spikes.mean() / (self.t_stop/1000)
        else:
            self.mean_spike_rate = np.sum(self.spikes,1).mean() / (self.t_stop/1000)

        print('External Spike Train Mean Spike Rate: {}'.format(self.mean_spike_rate))

    def current_spikes(self):
        if self.spikes.shape.__len__() == 1:
            self.spikes = np.expand_dims(self.spikes, axis=0)
        spikes = self.spikes[:,self.current_step]
        self.current_step += 1
        return spikes

class PoissonSpikeTrain(SpikeTrain):
    def __init__(self, dt, t_stop, no_neurons, spike_rates):
        super().__init__()
        #dt in ms
        self.dt = dt
        self.t_stop = t_stop
        self.no_neurons = no_neurons
        self.steps = np.arange(int(t_stop / dt))
        prob = np.random.uniform(0, 1, (self.steps.size, self.no_neurons))
        self.spikes = np.less(prob, np.array(spike_rates)*dt*1e-3).T
        self.source_type = 'spike_train'
        self.current_step = 0

        self.mean_spike_rate = np.sum(self.spikes,1).mean() / (self.t_stop/1000)
        print('Spike Train Mean Spike Rate: {}'.format(self.mean_spike_rate))

def poisson_spike_train_generator(dt, t_stop, rates, variable_rate=True):
    if variable_rate:
        s = np.random.uniform(-50, 50, size=rates.size)

    spike_train = []
    for t in range(int(t_stop/dt)):
        prob = np.random.uniform(0, 1, rates.shape)
        spikes = np.less(prob, np.array(rates)*dt*1e-3)
        spike_train.append(spikes)
        if variable_rate:
            rates = np.clip(rates + s*dt*1e-3 , 0, 90)
            ds = np.random.uniform(-5, 5, size=rates.size)
            s = np.clip(s + ds, -50, 50)

    # prob = np.random.uniform(0, 1, (int(t_stop / dt), rates.size))
    # spikes = np.less(prob, np.array(rates)*dt*1e-3).T
    return np.array(spike_train).T

class ExternalCurrentSignal:
    def __init__(self, signal):
        self.signal = signal
        self.idx = 0

    def I(self):
        I = self.signal[self.idx]
        self.idx += 1
        return I

class SpikingClassificationDataset:
    triangle = np.array([[0,0,0,0,0],
                         [0,1,0,0,0],
                         [0,1,1,0,0],
                         [0,1,1,1,0],
                         [0,0,0,0,0]])

    frame = np.array([[1,1,1,1,1],
                      [1,0,0,0,1],
                      [1,0,0,0,1],
                      [1,0,0,0,1],
                      [1,1,1,1,1]])

    square = np.array([[0,0,0,0,0],
                       [0,1,1,1,0],
                       [0,1,1,1,0],
                       [0,1,1,1,0],
                       [0,0,0,0,0]])

    class_templates = [triangle, frame, square]

    def __init__(self, dt, t_sample, t_stop):
        self.dt = dt
        self.t_sample = t_sample
        self.t_stop = t_stop
        self.no_samples = int(self.t_stop/self.t_sample)
        self.rate_constant = 40

        self.n_synapses = self.class_templates[0].flatten().size

        self.classes = np.random.randint(0,3,self.no_samples)

        target_spikes = np.zeros((self.class_templates.__len__(), t_stop))
        k = 0
        for t in range(t_stop):
            if t == int(t_sample/2) + t_sample*k:
                target_spikes[self.classes[k-1],t] = 1
                k += 1

        self.target_spike_train = ExternalSpikeTrain(dt, t_stop, self.class_templates.__len__(), np.array(target_spikes))

        spikes = []

        for c in self.classes:
            st = poisson_spike_train_generator(dt, t_sample, self.class_templates[c].flatten()*self.rate_constant)
            spikes.append(st)

        spikes = np.hstack(spikes)
        self.spike_train = ExternalSpikeTrain(dt, t_stop, self.class_templates[c].flatten().size, spikes)

class SpikingMNIST:
    def __init__(self, root='../'):
        self.transform = transforms.Compose([
           transforms.ToTensor(),
           # transforms.Normalize((0.1307,), (0.3081,))
        ])
        self.mnist = torchvision.datasets.MNIST(root=root+"datasets/", train=True, transform=self.transform, download=True)
        # img, label = self.mnist[10]

        self.images = []
        for i in range(10):
            indices = self.mnist.targets == i
            self.images.append(self.mnist.data[indices].detach().numpy())

    def get_random_sample(self, label, dt, t_stop, jitter=10, max_fr=50):
        # flat_arr = self.images[label][np.random.randint(self.images[label].shape[0])].flatten()
        flat_arr = self.images[label][0].flatten()
        # frates = flat_arr*(50/255) + np.random.uniform(0,1, flat_arr.shape)*15
        frates = flat_arr*(max_fr/255)

        print('Frates mean: {}, std: {}'.format(frates.mean(), frates.std()))
        print('Frates min: {}, max: {}'.format(frates.min(), frates.max()))
        spike_train = poisson_spike_train_generator(dt, t_stop, frates)

        if jitter:
            #jitter | for stability
            jitter_prob = np.random.uniform(0,1,spike_train.shape)
            jitter_st = jitter_prob < jitter*dt*1e-3
            spike_train = np.logical_or(spike_train, jitter_st)
        return spike_train, self.images[label][0]

    def generate_test_spike_train(self, n_samples, dt, t_sample):
        self.mnist = torchvision.datasets.MNIST(root="../datasets/", train=False, transform=self.transform, download=True)
        spikes = []
        labels = []
        for i in range(n_samples):
            img, label = self.mnist[i]
            flat_arr = img.detach().numpy().flatten()
            frates = flat_arr*(50/255)
            spike_train = poisson_spike_train_generator(dt, t_sample, frates)
            spikes.append(spike_train)
            labels.append(label)

        spikes = np.hstack(spikes)

        jitter_prob = np.random.uniform(0,1,spikes.shape)
        jitter = jitter_prob < 10*dt*1e-3
        spikes = np.logical_or(spikes, jitter)

        return spikes, np.array(labels)

    def special_spike_train(self, dt, t_stop, t_sample, distribute_5=True):
        self.mnist = torchvision.datasets.MNIST(root="../datasets/", train=True, transform=self.transform, download=True)
        #%% base spike train
        no_neurons = 784*2

        print('creating stimuli')
        r = np.random.uniform(0, 30, size=(no_neurons))
        s = np.random.uniform(-50, 50, size=(no_neurons))
        spike_train = []
        for t in range(t_stop):
            prob = np.random.uniform(0, 1, r.shape)
            spikes = np.less(prob, np.array(r)*dt*1e-3)
            spike_train.append(spikes)
            r = np.clip(r + s*dt*1e-3 , 0, 30)
            ds = np.random.uniform(-5, 5, size=(no_neurons))
            s = np.clip(s + ds, -50, 50)

        spike_train = np.array(spike_train).T

        selected_labels = np.random.choice(np.arange(10), int(t_stop/t_sample))

        for sid, sl in enumerate(selected_labels):
            sel_imgs = self.images[sl]
            flat_arr = sel_imgs[np.random.randint(sel_imgs.shape[0])].flatten()
            frates = flat_arr*(50/255)
            pattern = poisson_spike_train_generator(dt, t_sample, frates)

            jitter_prob = np.random.uniform(0,1,pattern.shape)
            jitter = jitter_prob < 10*dt*1e-3
            pattern = np.logical_or(pattern, jitter)

            spike_train[:784, sid*50:(sid+1)*50] = np.copy(pattern)

        if distribute_5:
            pattern_img = self.images[5][0]
            flat_arr = pattern_img.flatten()
            frates = flat_arr*(50/255)
            pattern = poisson_spike_train_generator(dt, t_sample, frates)
            jitter_prob = np.random.uniform(0,1,pattern.shape)
            jitter = jitter_prob < 10*dt*1e-3
            pattern = np.logical_or(pattern, jitter)

            first_repeat = 50
            spike_train[:784, first_repeat:first_repeat+50] = np.copy(pattern)

            repeat_times = [first_repeat]
            repeat_mode = [1]
            last_repeat_time = first_repeat

            for t in range(t_stop-50):
                if t > last_repeat_time + 100:
                    r = np.random.uniform(0,1,25)
                    mask = r < 0.25
                    c = np.argwhere(mask).min()
                    start_at = t + c*50
                    if start_at + 50 > t_stop:
                        break

                    repeat_times.append(start_at)
                    last_repeat_time = start_at

                    spike_train[:784, last_repeat_time:last_repeat_time+50] = np.copy(pattern)
                    repeat_mode.append(1)

            repeat_times = np.array(repeat_times)
        # repeat_labels = np.array(repeat_labels)
        else:
            repeat_times = False

        return spike_train, repeat_times, selected_labels

    def special_spike_train2(self, dt, t_stop, t_sample, distribute_5=True):
        self.mnist = torchvision.datasets.MNIST(root="../datasets/", train=True, transform=self.transform, download=True)
        #%% base spike train
        no_neurons = 784*2
        max_fr = 60
        r = np.random.uniform(0, max_fr, size=(no_neurons))
        s = np.random.uniform(-50, 50, size=(no_neurons))
        spike_train = []
        for t in range(t_stop):
            prob = np.random.uniform(0, 1, r.shape)
            spikes = np.less(prob, np.array(r)*dt*1e-3)
            spike_train.append(spikes)
            r = np.clip(r + s*dt*1e-3 , 0, max_fr)
            ds = np.random.uniform(-5, 5, size=(no_neurons))
            s = np.clip(s + ds, -50, 50)

        spike_train = np.array(spike_train).T

        selected_labels = np.random.choice(np.arange(10), int(t_stop/t_sample))

        for sid, sl in enumerate(selected_labels):
            sel_imgs = self.images[sl]
            flat_arr = sel_imgs[np.random.randint(sel_imgs.shape[0])].flatten()
            frates = flat_arr*(90/255)
            pattern = poisson_spike_train_generator(dt, t_sample, frates)

            jitter_prob = np.random.uniform(0,1,pattern.shape)
            jitter = jitter_prob < 10*dt*1e-3
            pattern = np.logical_or(pattern, jitter)

            spike_train[:784, sid*50:(sid+1)*50] = np.copy(pattern)

        if distribute_5:
            pattern_img = self.images[5][0]
            flat_arr = pattern_img.flatten()
            frates = flat_arr*(50/255)
            pattern = poisson_spike_train_generator(dt, t_sample, frates)
            jitter_prob = np.random.uniform(0,1,pattern.shape)
            jitter = jitter_prob < 10*dt*1e-3
            pattern = np.logical_or(pattern, jitter)

            first_repeat = 50
            spike_train[:784, first_repeat:first_repeat+50] = np.copy(pattern)

            repeat_times = [first_repeat]
            repeat_mode = [1]
            last_repeat_time = first_repeat

            for t in range(t_stop-50):
                if t > last_repeat_time + 100:
                    r = np.random.uniform(0,1,25)
                    mask = r < 0.25
                    c = np.argwhere(mask).min()
                    start_at = t + c*50
                    if start_at + 50 > t_stop:
                        break

                    repeat_times.append(start_at)
                    last_repeat_time = start_at

                    spike_train[:784, last_repeat_time:last_repeat_time+50] = np.copy(pattern)
                    repeat_mode.append(1)

            repeat_times = np.array(repeat_times)
        # repeat_labels = np.array(repeat_labels)
        else:
            repeat_times = False

        return spike_train, repeat_times, selected_labels


from sklearn import tree
import pandas as pd

data = pd.read_csv("Lab_exp_5/DT.csv")
print(data)
from sklearn.preprocessing import LabelEncoder

Le = LabelEncoder()
data["OL"] = Le.fit_transform(data["OL"])
data["Temp"] = Le.fit_transform(data["Temp"])
data["Hum"] = Le.fit_transform(data["Hum"])
data["Wind"] = Le.fit_transform(data["Wind"])
data["PT"] = Le.fit_transform(data["PT"])
print(data)
y = data["PT"]
X = data.drop(["PT"], axis=1)
clf = tree.DecisionTreeClassifier(criterion="entropy")
clf = clf.fit(X, y)
# To view the tree as a graph
import graphviz

dot_data = tree.export_graphviz(clf, out_file=None)
graph = graphviz.Source(dot_data)
print(graph)
# To view the tree in Text Format
from sklearn.tree import export_text
feature_names = list(X.columns)
r = export_text(clf,feature_names=feature_names)
print(r)


#
# @lc app=leetcode id=29 lang=python3
#
# [29] Divide Two Integers
#
# Given two integers dividend and divisor, divide two integers without using multiplication, division and mod operator.

# Return the quotient after dividing dividend by divisor.

# The integer division should truncate toward zero.

# Example 1:

# Input: dividend = 10, divisor = 3
# Output: 3
# Example 2:

# Input: dividend = 7, divisor = -3
# Output: -2
# Note:
# Both dividend and divisor will be 32-bit signed integers.
# The divisor will never be 0.

# Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

class Solution:
    def divide(self, dividend: int, divisor: int) -> int:
        # Accepted
        # 989/989 cases passed (36 ms)
        # Your runtime beats 90.81 % of python3 submissions
        # Your memory usage beats 99.52 % of python3 submissions (12.7 MB)
        ind = (dividend < 0) is (divisor < 0)
        dividend, divisor = abs(dividend), abs(divisor)
        result = 0
        while dividend >= divisor:
            temp, i = divisor, 1
            while dividend >= temp:
                dividend -= temp
                result += i
                i <<= 1
                temp <<= 1
        if not ind:
            result *= -1
        if result > (1 << 31)-1:
            return (1 << 31)-1
        elif result < -1 << 31:
            return -1 << 31
        else:
            return result

    def divide2(self, dividend: int, divisor: int) -> int:
        # Accepted
        # 989/989 cases passed (32 ms)
        # Your runtime beats 96.74 % of python3 submissions
        # Your memory usage beats 99.52 % of python3 submissions (12.7 MB)
        result = int(dividend/divisor)
        if result > (1 << 31)-1:
            return (1 << 31)-1
        elif result < -1 << 31:
            return -1 << 31
        else:
            return result


#!/usr/bin/env python

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

def get_tpm(id,tpm):
    # Compute TPM metrics for snoRNA
    tpm_genes = tpm.iloc[:,0]

    # remove . for NR_
    id_format = id.split(".")
    id = id_format[0]

    values = tpm.loc[tpm_genes.isin([id]),].drop(['gene_id','gene_name'],axis=1).reset_index(drop=True).to_numpy()
    avg,min,max = 0,0,0
    if len(values) != 0:
        avg = np.mean(values)
        min = np.amin(values)
        max = np.amax(values)
    return avg, min, max

def main():
    df_tpm = pd.read_csv('../../resources/coco_tpm.tsv',sep='\t',usecols=['gene_id','gene_name','HCT116_1','HCT116_2','MCF7_1','MCF7_2',
                                                    'PC3_1','PC3_2','SKOV_frg_1','SKOV_frg_2','TOV112D_1','TOV112D_2'])
    print(get_tpm('ENSG00000277194',df_tpm))

if __name__ == '__main__':
    main()


import sys
import datetime

import django
from webalessio.models import User

##########################################
# Little schema to see when to send emails
# F=from, T=to, TD=today
#
#   ---------------------
#   | F | T |  SEND IF  |
#   |   |   |  always   |
#   | A |   |   TD<A    |
#   |   | A |   TD>A    |
#   | A | B | !A<=TD<=B |
#   ---------------------

if __name__ == '__main__':
    #export DJANGO_SETTINGS_MODULE=alessiobot.settings
    django.setup()
    today = datetime.date.today() #time are UTC !
    users_today = []

    for user in User.objects.all():
        if ((not user.suspend_from and not user.suspend_until) or
           (user.suspend_from and today < user.suspend_from) or
           (user.suspend_until and today > user.suspend_until) or
           (user.suspend_from and user.suspend_until and not
           (user.suspend_from <= today <= user.suspend_until))):
            users_today.append(user)

    if users_today:
        print("To: " + ', '.join([user.email for user in users_today]))
        sys.exit(0)
    else:
        sys.exit(1)


"""Tests for the run module"""

from tada.util import run

def test_run_command_returns_echo():
    """Checks that a single line is returned from command"""
    output, error = run.run_command('echo \"Hello!\"')
    assert error == b""
    assert output is not None

# pylint: disable=invalid-name
def test_run_benchmark_provided_function():
    """Checks that chosen built-in sum function is run correctly"""
    chosen_function = sum
    chosen_arguments = [1, 2, 3]
    expected_sum_output = 6
    run_output = run.run_benchmark(chosen_function, chosen_arguments)
    assert run_output == expected_sum_output


# -----------------------------------------------------------------------------
# Name:        TallsLiDAR.py
# Purpose:     Generar arxius GeoJSON amb els talls LiDAR que escollim, a
#              partir dels identificadors del tall 2kmx2km
#              Per exemple, pels projectes SOLAR processarem el tall 500mx500m
#
# Author:      a.termens
#
# Created:     18/09/2019
# Copyright:   (c) a.termens 2019
# Licence:     CC-BY-4.0
# Last Update: 20/04/2022
# -----------------------------------------------------------------------------
# References ...
# BBOX Tall 2km x 2km: 256000,4488000,528000,4752000
# -----------------------------------------------------------------------------
# !/usr/bin/env python

import sys
import os

import csv
import json

# -----------------------------------------------------------------------------
# ... constants ...
CRS = {"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::25831"}}

TALL_CONFIG = {
    "2km": {"tpare":"2km", "ncols":1, "nrows":1, "dxy":2000, "factor":1000, "ip":3}, # default
    "1km": {"tpare":"2km", "ncols":2, "nrows":2, "dxy":1000, "factor":1000, "ip":3},
    "500m":{"tpare":"2km", "ncols":4, "nrows":4, "dxy": 500, "factor": 100, "ip":4},
    }

class Tall_configuration:
    def __init__(self, ktall="2km"):
        self.tall = ktall
        data = TALL_CONFIG.get(ktall, {"tpare":"none", "ncols":0, "nrows":0, "dxy":0, "factor":0, "ip":0} )
        # data es un diccionari on si no existeix ens assegurem que retorna els valors de control
        self.tpare = data["tpare"]
        self.ncols = data["ncols"]
        self.nrows = data["nrows"]
        self.dxy = data["dxy"]
        self.factor = data["factor"]
        self.ip = data["ip"]

def LoadIdsLiDARcat():
    tconfig = Tall_configuration("2km")

    id_list = []
    # Tall_LiDARCAT_2x2.csv has id,bloc (i.e. "1",260512.00000) tall 2km x 2km
    # id,bloc
    # "1",260512.000000000000000  >>> cantonada SW (260000.0,4512000.0)
    # "2",260514.000000000000000  >>> cantonada SW (260000.0,4514000.0)
    # ...
    with open('Tall_LiDARCAT_2x2.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        nlin = 0
        for row in csv_reader:
            if nlin > 0:
                x = int(float(row[1][:tconfig.ip]))*1000.0 #
                y = 4000000.0 + int(float(row[1][tconfig.ip:]))*1000.0
                id_list.append([x,y])
            nlin += 1

    return id_list

def LoadIdsLiDAR(ktall="2km"):
    tconfig = Tall_configuration(ktall)

    id_list = []
    for sw in LoadIdsLiDARcat():
        for cr in range(tconfig.ncols):
            x = sw[0] + cr*tconfig.dxy
            for fr in range(tconfig.nrows):
                y = sw[1] + fr*tconfig.dxy
                id_list.append([x,y])

    return id_list

class LiDARbloc:
    def __init__(self, x, y, ktall="2km"):
        # id es l'identificador del bloc del tall ktall on es fa referencia a les
        # coordenades de la cantonada SW
        # x,y son els coordenades de la cantonada SW que servira per
        # identificar el bloc
        # key del tall "2km", "1km", "500m",...
        tconfig = Tall_configuration(ktall)
        ix = int(x / tconfig.factor)
        iy = int((y-4000000) / tconfig.factor)

        self.id = int("{}{}".format(ix,iy))
        self.SW = [x, y]
        self.NW = [x, y + tconfig.dxy]
        self.NE = [x + tconfig.dxy, y + tconfig.dxy]
        self.SE = [x + tconfig.dxy, y]
        # assignem geometria GeoJSON
        pol = [self.SW, self.NW, self.NE, self.SE, self.SW]
        self.jsgeom = {}
        self.jsgeom["type"] = "MultiPolygon"
        self.jsgeom["coordinates"] = [[pol]]

def write_LiDAR_geojson(ktall="2km"):
    bloc_data_list = []
    nb = 0
    for sw in LoadIdsLiDAR(ktall):
        nb += 1
        bloc = LiDARbloc(sw[0], sw[1], ktall)
        bloc_data = {}
        bloc_data["type"] = "Feature"
        bloc_data["properties"] = {"id": nb, "bloc": bloc.id }
        bloc_data["geometry"] =  bloc.jsgeom
        bloc_data_list.append(bloc_data)

    print(" Total de blocs a generar tall {} {} {}".format(ktall, nb, len(bloc_data_list)))

    dict = {}
    dict["type"] = "FeatureCollection"
    dict["name"] = "Tall LiDAR {}".format(ktall)
    dict["crs"] = CRS
    dict["features"] = bloc_data_list

    with open('LiDAR_{}.geojson'.format(ktall), 'w') as f:
        json.dump(dict, f, ensure_ascii=False, indent=4)

    return 0

def main(argv=None):
    ierr = 0
    for ktall in ["2km", "1km", "500m"]:
        ierr += write_LiDAR_geojson(ktall)
    return ierr

if __name__ == '__main__':
    sys.exit(main(sys.argv))


# AoC 2021 Day 22
# Challenge 1
# Answer 653798

import sys
import os
import numpy as np

def read_input(fname, t=lambda x: x, strip_lines=True, force_multi=False):
    with open(os.path.join(sys.path[0], fname), "r") as f:
        contents = f.read()
    if strip_lines:
        lines = contents.strip().split('\n')
    else:
        lines = contents.split('\n')
    if len(lines) == 1 and not force_multi:
        return t(lines[0])
    return list(map(t, lines))

A = read_input('Input.txt')

for i in range(len(A)):
    A[i] = A[i].split(' ')
    if A[i][0] == 'on':
        A[i][0] = 1
    else:
        A[i][0] = 0

minS = sys.maxsize
maxS = 0

for i in range(len(A)):
    x,y,z = A[i][1].split(',')
    _, x = x.split('=')
    _, y = y.split('=')
    _, z = z.split('=')
    x1,x2 = x.split('..')
    y1,y2 = y.split('..')
    z1,z2 = z.split('..')

    x1 = int(x1)
    x2 = int(x2)

    y1 = int(y1)
    y2 = int(y2)

    z1 = int(z1)
    z2 = int(z2)

    if x1 >= -50 and x2 <= 50 and y1 >= -50 and y2 <= 50 and z1 >= -50 and z2 <= 50:
        if x1 < minS: minS = x1
        if y1 < minS: minS = y1
        if z1 < minS: minS = z1

        if x2 > maxS: maxS = x2
        if y2 > maxS: maxS = y2
        if z2 > maxS: maxS = z2
    else:
        A[i][0] = 2 # skip

    A[i][1] = [[x1,x2],[y1,y2],[z1,z2]]

maxS += 1
minS -= 1
gSize = maxS + abs(minS)
G = np.zeros((gSize,gSize,gSize))

for i in range(len(A)):
    change = 0
    if A[i][0] != 2:
        if A[i][0] == 1: print("on")
        elif A[i][0] == 0: print("off")
        for x in range(A[i][1][0][0], A[i][1][0][1]+1):
            for y in range(A[i][1][1][0], A[i][1][1][1]+1):
                for z in range(A[i][1][2][0], A[i][1][2][1]+1):
                    if G[x,y,z] != A[i][0]:
                        G[x,y,z] = A[i][0]
                        change += 1

        print(change)

count = 0
for x in range(len(G)):
    for y in range(len(G)):
        for z in range(len(G)):
            if G[x,y,z] == 1:
                count += 1

print(count)


from selenium import webdriver
from selenium.webdriver.common.by import By

import time

try:
    link = 'http://suninjuly.github.io/registration2.html'
    browser = webdriver.Chrome()
    browser.get(link)

    # Ваш код, который заполняет обязательные поля

    input_1 = browser.find_element(By.CSS_SELECTOR, '.first_block .first')
    input_1.send_keys('test.txt')

    input_2 = browser.find_element(By.CSS_SELECTOR, '.first_block .second')
    input_2.send_keys('test.txt')

    input_3 = browser.find_element(By.CSS_SELECTOR, '.first_block .third')
    input_3.send_keys('test.txt')

    button = browser.find_element(By.CSS_SELECTOR, 'button.btn')
    button.click()

    time.sleep(1)
    welcome_text_elt = browser.find_element(By.TAG_NAME, 'h1')
    welcome_text = welcome_text_elt.text

    assert 'Congratulations! You have successfully registered!' == welcome_text

finally:
    time.sleep(10)
    browser.quit()

section_1/1_6_Уникальность селекторов_2.py

1_6_Уникальность селекторов_2.py


import telegram
from telegram import Update, Bot
from telegram.ext import MessageHandler, Updater, CommandHandler, CallbackContext
import requests
import re
bot = telegram.Bot(token="1979535666:AAENGjjo0OXFF7-_5ne5EnMhcJZvfhkf6Yk")
def get_url():
    contents = requests.get('https://api.thecatapi.com/v1/images/search').json()
    image_url = contents[0]['url']
    return image_url

# def get_image_url():
#     allowed_extension = ['jpg','jpeg','png']
#     file_extension = ''
#     while file_extension not in allowed_extension:
#         url = get_url()
#         file_extension = re.search("([^.]*)$",url).group(1).lower()
#     return url

def boop(update: Update, context: CallbackContext):
    url=get_url()
    bot.send_photo(update.effective_message.chat_id, photo=url)

def main():
    updater = Updater('xxxx', use_context = True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler('boop',boop))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()


import keras
from keras.layers import Input, Embedding, LSTM, Dense
from keras.models import Model

class LSTM_M:
    def __init__(self, input_size, input_dim, embedding_size, hidden_size, n_classes, drop_out=0.5,
                 optimizer='rmsprop', loss_function='binary_crossentropy'):
        self.input_size = input_size
        self.input_dim = input_dim
        self.embedding_size = embedding_size
        self.hidden_size = hidden_size
        self.n_classes = n_classes
        self.drop_out = drop_out
        self.optimizer = optimizer
        self.loss_function = loss_function

    def create_model(self):
        # 입력 값
        main_input = Input(shape=(self.input_size,), dtype='int32', name='main_input')

        # 임베딩 층
        x = Embedding(output_dim=self.embedding_size, input_dim=self.input_dim, input_length=self.input_size)(main_input)

        # LSTM 층
        lstm_out = LSTM(self.hidden_size, dropout=self.drop_out)(x)

        # 출력 층
        main_output = Dense(1, activation='sigmoid', name='main_output')(lstm_out)

        # 모델
        model = Model(inputs=main_input, outputs=main_output)

        # 모델 컴파일
        model.compile(optimizer=self.optimizer, loss=self.loss_function, metrics=['acc'])

        return model


import os
import time

import HandTrackingModule as hm
import cv2

wCam, hCam = 640, 488
cap = cv2.VideoCapture(0)
cap.set(3, wCam)
cap.set(4, wCam)

folderPath: str = "finger"
mylist = os.listdir(folderPath)
print(mylist)
overlay = []

for impath in mylist:
    Image = cv2.imread(f'{folderPath}/{impath}')
    overlay.append(Image)
   # print(f'{folderPath}/{impath}')
#print(len(overlay))

pTime = 0

dectector = hm.handDetector()

while True:

    success, img = cap.read()
    img=dectector.findHands(img)

    h, w, c = overlay[3].shape

    img[0:h, 0:w] = overlay[3]

    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime=cTime

    cv2.putText(img, f'FPS: {int(fps)}', (400,70), cv2.FONT_HERSHEY_PLAIN,
                3, (255,0,0), 3)

    cv2.imshow("Image", img)
    cv2.waitKey(1)


import sys
from collections import deque

sys.setrecursionlimit(10**4)
n, m = map(int, sys.stdin.readline().split())
memo = [[0, 0] for _ in range(101)]
queue = deque([])

for _ in range(n):
    x, y = map(int, sys.stdin.readline().split())
    memo[x][1] = y
for _ in range(m):
    u, v = map(int, sys.stdin.readline().split())
    memo[u][1] = v

queue.append((0, 1))

while queue:
    if memo[100][0] != 0:
        break
    point = queue.popleft()
    for i in range(1, 7):
        dx = point[1]+i
        if dx > 100:
            continue
        if memo[dx][0] == 0:
            if memo[dx][1] != 0:
                memo[point[1]] = [point[0] + 1, memo[dx][1]]
                queue.append((point[0] + 1, memo[dx][1]))
                continue
            memo[dx] = [point[0]+1, dx]
            queue.append((point[0]+1, dx))

print(memo[100][0])


#
#    --- Sparkplub B - Discovery application ---
#
#   The application will display information about all spB entities
#
import os
import time
import json
import paho.mqtt.client as mqtt
from mqtt_spb_wrapper import *

# APPLICATION default configuration parameters -----------------------------------------------
_DEBUG = False   # Enable debug messages

# Sparkplug B parameters
_config_spb_group_name = os.environ.get("SPB_GROUP", "*")

# MQTT Configuration
_config_mqtt_host = os.environ.get("MQTT_HOST", "localhost")
_config_mqtt_port = int(os.environ.get("MQTT_PORT", 1883))
_config_mqtt_user = os.environ.get("MQTT_USER", "")
_config_mqtt_pass = os.environ.get("MQTT_PASS", "")

# Global Variables -------------------------------------------------------
spb_groups = {}    # Variable to store the discord groups and entities

topic = MqttSpbTopic()  # spB Topic parser

def on_connect(client, userdata, flags, rc):
    """
        MQTT Callback function for connect events
    """
    if rc == 0:
        if _config_spb_group_name == "*":
            topic = "spBv1.0/#"
        else:
            topic = "spBv1.0/%s/#" % _config_spb_group_name

        # Subscribe to the specific topic
        client.subscribe(topic)
        print("MQTT Client connected and subscribed to topic: " + topic)

    else:
        print("MQTT Client failed to connect with result code " + str(rc))

def on_message(client, userdata, msg):
    """
        MQTT Callback function for received messages events
    """

    global topic, spb_groups

    # print(msg.topic)

    # Parse the topic
    topic.parse_topic(msg.topic)

    group_name = topic.group_name
    eon_name = topic.eon_name
    eon_device_name = topic.eon_device_name
    entity_name = topic.entity_name

    # Check if the group is present in the ones detected
    if group_name not in spb_groups.keys():
        spb_groups[group_name] = {}

    # Check if the eon is present in the group
    if eon_name not in spb_groups[group_name].keys():
        spb_groups[group_name][eon_name] = {}

    # Check if the entity is present in the group and eon
    if entity_name not in spb_groups[group_name][eon_name].keys():
        entity = MqttSpbEntity( spb_group_name= group_name,
                                spb_eon_name= eon_name,
                                spb_eon_device_name=eon_device_name,
                                debug_info=_DEBUG)
        spb_groups[group_name][eon_name][entity_name] = entity     # Save the reference
    else:
        entity = spb_groups[group_name][eon_name][entity_name]  # Get the reference

    # BIRTH,  parse the data into the entity object, for later display
    if "BIRTH" in topic.message_type:

        # Parse payload
        entity.deserialize_payload_birth(msg.payload)

print("--- Sparkplug B entity discovery application ---")

# Set up the MQTT client connection that will listen to all Sparkplug B messages
_mqtt_client = mqtt.Client()
if _config_mqtt_user != "":
    _mqtt_client.username_pw_set(_config_mqtt_user, _config_mqtt_pass)
_mqtt_client.on_connect = on_connect
_mqtt_client.on_message = on_message
_mqtt_client.connect(_config_mqtt_host, _config_mqtt_port)  # Connect to MQTT
print("Connecting to MQTT broker server - %s:%d" % (_config_mqtt_host, _config_mqtt_port))

# Start the mqtt client thread
_mqtt_client.loop_start()

# Wait some time to receive the persisted messages in the broker.
time.sleep(4)

# Stop the mqtt client
_mqtt_client.loop_stop()

# Let's show the result
PIPE = "│  "
ELBOW = "└──"
TEE = "├──"
SPACE = "   "

out_dict = {}   # output data

for group_name in spb_groups.keys():

    print("\nspBv1.0 / %s" % group_name)

    if group_name not in out_dict.keys():    # Create if it doesn't exist
        out_dict[group_name] = {}

    for eon_name in spb_groups[group_name].keys():

        # Check if last item
        L1_last = (eon_name == list(spb_groups[group_name].keys())[-1])
        if L1_last:
            L1 = ELBOW
        else:
            L1 = TEE

        # ├── EON
        print("  %s %s" % (L1, eon_name))

        # Create if it doesn't exist
        if eon_name not in out_dict[group_name].keys():
            out_dict[group_name][eon_name] = []

        for entity_name in spb_groups[group_name][eon_name].keys():

            # ├── EON
            # │    ├── ENTITY
            L2_last = (entity_name == list(spb_groups[group_name][eon_name].keys())[-1])
            if L1_last:
                L1 = SPACE
            else:
                L1 = PIPE

            if L2_last:  # Check if last item
                L2 = ELBOW
            else:
                L2 = TEE

            entity = spb_groups[group_name][eon_name][entity_name]  # Get entity object

            print("  %s %s %s" % (L1, L2, entity_name))

            # Add the entity information
            out_dict[group_name][eon_name].append(entity.get_dictionary())

            if L2_last:
                L2 = SPACE
            else:
                L2 = PIPE

            MAX_STR_LEN = 40    # Display only a maximum of characters

            # Print entity Attributes, commands, data
            print("  %s %s %s ATTR/" % (L1, L2, TEE))
            attributes = entity.attribures.get_dictionary()
            if len(attributes) != 0:
                for field in attributes:
                    _value = field['value']
                    if isinstance(_value, str):
                        if len(_value) > MAX_STR_LEN:
                            _value = _value[:MAX_STR_LEN].replace("\n", "").replace("\r", "") + " ..."
                        else:
                            _value = _value
                    else:
                        _value = str(_value)
                    print("  %s %s %s - %s : %s (%s)" % (L1, L2, PIPE, field['name'], _value, type(field['value'])))

            print("  %s %s %s CMD/" % (L1, L2, TEE))
            commands = entity.commands.get_dictionary()
            if len(commands) != 0:
                for field in commands:
                    _value = field['value']
                    if isinstance(_value, str):
                        if len(_value) > MAX_STR_LEN:
                            _value = _value[:MAX_STR_LEN].replace("\n", "").replace("\r", "") + " ..."
                        else:
                            _value = _value
                    else:
                        _value = str(_value)
                    print("  %s %s %s - %s : %s (%s)" % (L1, L2, PIPE, field['name'], _value, type(field['value'])))

            print("  %s %s %s DATA/" % (L1, L2, ELBOW))
            data = entity.data.get_dictionary()
            if len(data) != 0:
                for field in data:
                    _value = field['value']
                    if isinstance(_value, str):
                        if len(_value) > MAX_STR_LEN:
                            _value = _value[:MAX_STR_LEN].replace("\n", "").replace("\r", "") + " ..."
                        else:
                            _value = _value
                    else:
                        _value = str(_value)
                    print("  %s %s %s - %s : %s (%s)" % (L1, L2, SPACE, field['name'], _value, type(field['value'])))

# Save discovery results into json file
filename = "spb_discovery_results.json"
print("\nSaving results to file: " + filename)
with open(filename, "w") as fw:
    fw.write( json.dumps(out_dict))


import time
import pygame as _pygame
from monitor.ui.menu.pgm import config_controls as _ctrl
from monitor.ui.menu.pgm.widgets.widget import Widget
from monitor.ui.menu.pgm import locals as _locals

class KnobSelector(Widget):
    """
    KnobSelector widget.
    """

    def __init__(self,
                 title,
                 min_val,
                 max_val,
                 start_val,
                 incr=0.1,
                 speed_thresh=0.2,
                 alarm_color=(255, 0, 0),
                 off_on_limit=False,
                 selector_id='',
                 sfmt='{:1f}',
                 onchange=None,
                 onreturn=None,
                 **kwargs
                 ):
        """
        Description of the specific paramaters (see Widget class for generic ones):

        :param title: Title of the selector
        :type title: basestring
        :param elements: Elements of the selector
        :type elements: list
        :param selector_id: ID of the selector
        :type selector_id: basestring
        :param default: Index of default element to display
        :type default: int
        :param onchange: Callback when changing the selector
        :type onchange: function, NoneType
        :param onreturn: Callback when pressing return button
        :type onreturn: function, NoneType
        :param kwargs: Optional keyword-arguments for callbacks
        """
        super(KnobSelector, self).__init__(widget_id=selector_id, onchange=onchange,
                                           onreturn=onreturn, kwargs=kwargs)
        self._elements = []
        self._index = 0
        self._sformat = sfmt
        self._labelsize = 0

        # numerical value of selector
        self._min_val = min_val
        self._max_val = max_val
        self._value = start_val
        self._incr = incr
        self._speed_thresh = speed_thresh
        # behaviour when the selector reaches a limit: show "Off"?
        self._off_on_limit = off_on_limit

        # a list of timestamps for the 5 most recent clicks
        self._clicks = []
        # if value has reached min or max
        self._alarm_color = alarm_color

        # Public attributs
        self.label = title

    def _apply_font(self):
        """
        See upper class doc.
        """
        self._labelsize = self._font.size(self.label)[0]

    def draw(self, surface):
        """
        See upper class doc.
        """
        self._render()
        surface.blit(self._surface, self._rect.topleft)

    def get_value(self):
        """
        Return the current value of the selector.

        :return: Value and index as a float
        :rtype: float
        """
        return self._value

    def set_value(self, value):
        """
        Overriden from parent
        """
        self._value = value

    def get_step(self):
        """
        Return the nonlinear step size. This detects scrolling speed
        (via a moving window buffer of "click" timestamps),
        and adjusts the step size:
        step_value = 0.1 (default);
        step_value = 1.0 (fast);

        :return: Value
        :rtype: float
        """
        step_value = None
        # if click window is no yet fully populated
        if (len(self._clicks) < 5):
            step_value = self._incr
        else:
            delta_time = (self._clicks[-1] - self._clicks[0])
            if delta_time > self._speed_thresh:  # slow, more than 0.9 s for the last 5 clicks
                step_value = self._incr
            else:
                step_value = self._incr * 10
        return step_value

    def decrement(self):
        """
        decrement the value.
        The lowest value is capped at min_val

        :return: None
        """
        # update timestamps
        self._clicks.append(time.time())
        while (len(self._clicks) > 5):
            self._clicks.pop(0)
        self._value -= self.get_step()
        if self._value < self._min_val:
            self._value = self._min_val
        self.change()

    def increment(self):
        """
        increment the value
        The highest value is capped at max_val

        :return: None
        """
        # update timestamps
        self._clicks.append(time.time())
        while (len(self._clicks) > 5):
            self._clicks.pop(0)
        self._value += self.get_step()
        if self._value > self._max_val:
            self._value = self._max_val
        self.change()

    def _render(self):
        """
        See upper class doc.
        """
        if self._off_on_limit:
            if self._value == self._min_val or self._value == self._max_val:
                color = self._alarm_color
                string = "Off"
            else:
                color = self._font_selected_color
                string = self._sformat.format(self.get_value())
        else:
            string = self._sformat.format(self.get_value())
            if self.selected:
                color = self._font_selected_color
            else:
                color = self._font_color
            if self._value == self._min_val or self._value == self._max_val:
                color = self._alarm_color

        self._surface = self.render_string(string, color)

    def set_selection_format(self, s):
        """
        Change the text format.

        :param s: Selection text
        :type s: basestring
        :return: None
        """
        self._sformat = s

    def update(self, events):
        """
        See upper class doc.
        """
        updated = False
        for event in events:
            if event.type == _pygame.KEYDOWN:
                if event.key == _ctrl.MENU_CTRL_LEFT:
                    self.decrement()
                    updated = True
                elif event.key == _ctrl.MENU_CTRL_RIGHT:
                    self.increment()
                    updated = True
                elif event.key == _ctrl.MENU_CTRL_ENTER:
                    self.apply()
                    updated = True

            elif self.joystick_enabled and event.type == _pygame.JOYHATMOTION:
                if event.value == _locals.JOY_LEFT:
                    self.decrement()
                    updated = True
                elif event.value == _locals.JOY_RIGHT:
                    self.increment()
                    updated = True

            elif self.joystick_enabled and event.type == _pygame.JOYAXISMOTION:
                if event.axis == _locals.JOY_AXIS_X and event.value < _locals.JOY_DEADZONE:
                    self.decrement()
                    updated = True
                if event.axis == _locals.JOY_AXIS_X and event.value > -_locals.JOY_DEADZONE:
                    self.increment()
                    updated = True

            elif self.mouse_enabled and event.type == _pygame.MOUSEBUTTONUP:
                if self._rect.collidepoint(*event.pos):
                    # Check if mouse collides left or right as percentage, use only X coordinate
                    mousex, _ = event.pos
                    topleft, _ = self._rect.topleft
                    topright, _ = self._rect.topright
                    dist = mousex - (topleft + self._labelsize)  # Distance from label
                    if dist > 0:  # User clicked options, not label

                        # Position in percentage, if <0.5 user clicked left
                        pos = dist / float(topright - topleft - self._labelsize)
                        if pos <= 0.5:
                            self.decrement()
                        else:
                            self.increment()
                        updated = True

        return updated