from datetime import date, timedelta
from django.http import HttpResponse
from django.http import FileResponse

from .models import *

from proyecto.models import ActividadesCronograma, Equipo, RegistroPerfil
from mensaje.funciones import isVisto

from statistics import mean, pstdev

def isActividad(equipo, nombre):
    estudiante = equipo.datosestudiante_set.first()
    if estudiante.actividad.filter(nombre=nombre):
        return True
    else:
        return False

def mensajesAvisosLista(equipo, usuario):
    aviso = AvisoActividad.objects.filter(usuario=usuario, equipo=equipo)
    if aviso.exists():
        lista_actividades = aviso[0].actividades.all()
        mensajes = [f"{n.nombre}" for n in lista_actividades]
    else:
        mensajes = []
    return mensajes

def avisosEstudiantes(datos_est, usuario):
    avisos = AvisoActividad.objects.filter(usuario=usuario)
    grupo = usuario.groups.get().name
    datos_estudiantes = {}
    for dato_est in datos_est:
        aviso_estudiante = avisos.filter(equipo=dato_est.equipo)
        if aviso_estudiante.exists():
            lista_actividades = aviso_estudiante[0].actividades.all()
            if lista_actividades.count() != 0:
                nombre_actividades = [f"{n}: {a.nombre}" for n, a in enumerate(lista_actividades, 1)]
                mensaje = "\n".join(nombre_actividades)
            else:
                mensaje = "No realizó actividad nueva"
            if grupo == 'tutor' or grupo == 'docente':
                datos_estudiantes[dato_est] = [aviso_estudiante[0].actividades.all().count(), mensaje,
                    isVisto(dato_est.usuario, usuario)]
            else:
                datos_estudiantes[dato_est] = [aviso_estudiante[0].actividades.all().count(), mensaje]
        else:
            if grupo == 'tutor' or grupo == 'docente':
                datos_estudiantes[dato_est] = [0, "No tiene ninguna actividad", isVisto(dato_est.usuario, usuario)]
            else:
                datos_estudiantes[dato_est] = [0, "No tiene ninguna actividad"]
    orden_datos_estudiantes = dict(sorted(datos_estudiantes.items(), key=lambda cantidad: cantidad[1][0], reverse=True))
    return orden_datos_estudiantes

def avisosEquipos(equipos_multiple, usuario):
    avisos = AvisoActividad.objects.filter(usuario=usuario)
    datos_equipos= {}
    for equipo in equipos_multiple:
        aviso_equipo = avisos.filter(equipo=equipo)
        if aviso_equipo.exists():
            lista_actividades = aviso_equipo[0].actividades.all()
            if lista_actividades.count() != 0:
                nombre_actividades = [f"{n}: {a.nombre}" for n, a in enumerate(lista_actividades, 1)]
                mensaje = "\n".join(nombre_actividades)
            else:
                mensaje = "No realizó actividad nueva"
            datos_equipos[equipo] = [aviso_equipo[0].actividades.all().count(), mensaje]
        else:
            datos_equipos[equipo] = [0, "No tiene ninguna actividad"]
    orden_datos_equipos = dict(sorted(datos_equipos.items(), key=lambda cantidad: cantidad[1][0], reverse=True))
    return orden_datos_equipos

def agregarAviso(texto_actividad, equipo, usuario):
    aviso, created = AvisoActividad.objects.get_or_create(
        usuario=usuario,
        equipo=equipo,
    )
    actividad = Actividad.objects.get(nombre=texto_actividad)
    aviso.actividades.add(actividad)
    aviso.save()

def marcarAvisosVistos(equipo, usuario):
    aviso = AvisoActividad.objects.filter(usuario=usuario, equipo=equipo)
    if aviso.exists():
        aviso[0].actividades.clear()

def progress(estudiante):
    actividades = Actividad.objects.all()
    actividades_estudiante = estudiante.actividad.all()
    suma_valores = 0
    for actividad in actividades:
        suma_valores += actividad.valor
    porcentaje_por_unidad = 100/suma_valores
    suma_valores_estudiante = 0
    for actividad in actividades_estudiante:
        suma_valores_estudiante += actividad.valor
    progreso_sobre_100 = int(suma_valores_estudiante * porcentaje_por_unidad)
    return progreso_sobre_100

def agregarActividadEstudiante(texto_actividad, estudiante):
    actividad = Actividad.objects.get(nombre=texto_actividad)
    estudiante.actividad.add(actividad)
    estudiante.save()

def agregarActividadEquipo(texto_actividad, equipo):
    estudiantes = equipo.datosestudiante_set.all()
    for estudiante in estudiantes:
        actividad = Actividad.objects.get(nombre=texto_actividad)
        estudiante.actividad.add(actividad)
        estudiante.save()

def actividadRealizadaEstudiante(texto_actividad, estudiante):
    hecho = estudiante.actividad.filter(nombre=texto_actividad).exists()
    return hecho

def pasosRealizados(estudiante):
    pasos = {1:2, 2:3, 3:7, 4:13, 5:18, 6:26}
    cantidad_actividades = estudiante.actividad.all().count()
    pasos_realizados = []
    # print(cantidad_actividades)

    for paso, actividad in pasos.items():
        if cantidad_actividades >= actividad:
            pasos_realizados.append(paso)
    # print(pasos_realizados)

    return pasos_realizados

def informarCronograma(pk):
    equipo = Equipo.objects.get(id=pk)
    cronograma_existe = ActividadesCronograma.objects.filter(equipo=equipo).exists()
    estudiante = equipo.datosestudiante_set.first()
    progreso = progress(estudiante)
    # mensaje_limite = 'Aún tienes tiempo para elaborar el sistema'
    mensaje_limite = ''
    if cronograma_existe:
        cronograma = ActividadesCronograma.objects.filter(equipo=estudiante.equipo)
            # fecha de registro del cronograma o fecha de registro del proyecto
        fecha = RegistroPerfil.objects.get(equipo=estudiante.equipo).fecha_creacion
            # fecha limite sistema 2 años y medio
        # prueba modificar el 0 del delta para eliminar al usuario
        fecha = fecha.astimezone().date()#-timedelta(0)
        fecha_limite_sistema = fecha+ timedelta(365*2.5)
        dia_restante_sistema = fecha_limite_sistema - date.today()
        dia_restante_sistema = dia_restante_sistema.days
        # fecha transcurrida desde el inicio
        dias_transcurridos = date.today() - fecha
        dias_transcurridos = dias_transcurridos + timedelta(0)
        # dias a semanas:
        semanas = dias_transcurridos.days // 7# - 1
        num_semana = dias_transcurridos.days // 7 + 1
        dias = dias_transcurridos.days % 7
        dias_transcurridos = dias_transcurridos.days# - 7
        # duracion del proyecto
        max_semana = range(1,1+max([n.semana_final for n in cronograma]))
        semana_total = len(max_semana)
        dia_total = 7*semana_total
        # fecha limite cronograma
        fecha_limite_crono = fecha + timedelta(dia_total)
        dia_restante_crono = fecha_limite_crono - date.today()
        dia_restante_crono = dia_restante_crono.days
        # fecha limite sistema 2 años y medio
        fecha_limite_sistema = fecha + timedelta(365*2.5)
        dia_restante_sistema = fecha_limite_sistema - date.today()
        dia_restante_sistema= dia_restante_sistema.days
        # porcentaje
        por_dia_crono = (dia_restante_crono* 100) / dia_total
        por_dia_sistema = dia_restante_sistema* 100 / (365*2.5)
        por_dia_crono = str(por_dia_crono)
        por_dia_sistema = str(por_dia_sistema)

        dia_retrazo = dia_restante_crono * -1
        por_dia_retrazo = ( dia_restante_crono *-1* 100)/(365*2.5-dia_total)
        por_dia_retrazo= str(por_dia_retrazo)

        if num_semana <= semana_total:
            limite_cronograma = False
        else:
            actividades = []
            limite_cronograma = True
        # ********** casos de eliminacion del estudiante
        # pasa 2 años y medio
        if dia_restante_sistema <= -1 and progreso.nivel < 100:
            # estudiante.usuario.delete()
            print('Se jodio')
            mensaje_limite = 'El estudiante fue eliminado del sistema por pasar los 2 años sin concluir el proyecto'
            return (mensaje_limite)
        # En caso de conclusion de proyecto
        if progress(estudiante) >= 100:
            fecha_100 = equipo.fecha_conclusion
            fecha_eliminar = fecha_100 + timedelta(180)
            if fecha_eliminar.date() < date.today():
                # estudiante.usuario.delete()
                print('cuenta eliminada')
            mensaje_limite = 'Concluiste con éxito el Proyecto de Grado, en 6 meses se eliminará tu cuenta'
            dia_restante_crono = ''
            dia_restante_sistema = ''
            dia_retrazo = ''
            semana_total = ''
            por_dia_crono = ''
            por_dia_sistema = ''
            por_dia_retrazo = ''
            limite_cronograma = ''
        # caso de reglamento sanabria, no conclusion de perfil
        if not estudiante.equipo.registroperfil:
            fecha_ingreso = estudiante.fecha_inscripcion.date()
        # se establese fecha limite del semestre de fin de septiembre y fin de marzo
            if fecha_ingreso.month < 6:
                fecha_limite = date(fecha_ingreso.year,9,30)
            else:
                fecha_limite = date(fecha_ingreso.year+1,3,30)
            if fecha_limite < date.today():
                # estudiante.usuario.delete()
                print('cuenta eliminada')
                print('Se jodio')
                mensaje_limite = 'El estudiante fue eliminado del sistema por no aprobar el perfil en el semestre inscrito'
                return (mensaje_limite)
    else:
        dia_restante_crono = ''
        dia_restante_sistema = ''
        dia_retrazo = ''
        semana_total = ''
        por_dia_crono = ''
        por_dia_sistema = ''
        por_dia_retrazo = ''
        limite_cronograma = ''
        mensaje_limite = ''
    context = {
        'dia_restante_crono':dia_restante_crono,
        'dia_restante_sistema':dia_restante_sistema,
        'dia_retrazo':dia_retrazo,
        'semana_total':semana_total,
        'por_dia_crono':por_dia_crono,
        'por_dia_sistema':por_dia_sistema,
        'por_dia_retrazo':por_dia_retrazo,
        'limite_cronograma':limite_cronograma,
        'cronograma_existe':cronograma_existe,
        'estudiante':estudiante,
        'dia_restante_sistema':dia_restante_sistema,
        'mensaje_limite':mensaje_limite}
    return context

def diasRestantes(pk):
    equipo = Equipo.objects.get(id=pk)
    cronograma_existe = ActividadesCronograma.objects.filter(equipo=equipo).exists()
    estudiante = equipo.datosestudiante_set.first()
    progreso = progress(estudiante)
    mensaje_limite = ''
    if cronograma_existe:
        cronograma = ActividadesCronograma.objects.filter(equipo=estudiante.equipo)
        # fecha de registro del cronograma o fecha de registro del proyecto
        fecha = RegistroPerfil.objects.get(equipo=estudiante.equipo).fecha_creacion
        # fecha limite sistema 2 años y medio
        # prueba modificar el 0 del delta para eliminar al usuario
        fecha = fecha.astimezone().date()#-timedelta(0)
        # fecha limite sistema 2 años y medio
        fecha_limite_sistema = fecha+ timedelta(365*2.5)
        dias_restantes_sistema = fecha_limite_sistema - date.today()
        dias_restantes_sistema = dias_restantes_sistema.days
        # fecha transcurrida desde el inicio
        dias_transcurridos = date.today() - fecha
        dias_transcurridos = dias_transcurridos + timedelta(0)
        dias_transcurridos = dias_transcurridos.days
        # duracion del proyecto
        max_semana = range(1,1+max([n.semana_final for n in cronograma]))
        semana_total = len(max_semana)
        dia_total = 7*semana_total
        # fecha limite cronograma
        fecha_limite_crono = fecha + timedelta(dia_total)
        dias_restantes_cronograma = fecha_limite_crono - date.today()
        dias_restantes_cronograma = dias_restantes_cronograma.days

    else:
        dias_restantes_sistema = ''
        dias_restantes_cronograma = ''
        dias_transcurridos = ''

    return dias_restantes_cronograma, dias_restantes_sistema, dias_transcurridos

def distanciaEntreActividades(lista_actividades, equipo):
    """Extrae un numero que ayudará para ordenar por esfuerzo del estudiante.
    Se realiza un análisis entre las diferencias de tiempo entre cada
    actividad.
    A menor el nivel, mas esfuerzo el estudiante tiene en completar las
    actividades.
    Se nombrea nivel_ie"""

    actividades = lista_actividades.order_by('fecha_creacion')
    fecha_inicio = equipo.fecha_creacion
    fechas_actividades = [n.fecha_creacion for n in actividades]
    fechas_actividades.insert(0, fecha_inicio)

    # diff_tiempo = []
    diff_tiempo_dias = []
    for x, y in zip(fechas_actividades[0::], fechas_actividades[1::]):
        diff = y- x
        diff_dias = diff.total_seconds()/(3600*24)
        # diff_dias = diff.days
        diff_tiempo_dias.append(diff_dias)

    # Por media y desviasion estandar, datos la diferencia de tiempos
    # print(diff_tiempo_dias)
    media = mean(diff_tiempo_dias)
    desviacion = pstdev(diff_tiempo_dias)
    nivel_ie = media + desviacion
    return nivel_ie


from django.urls import path
from . import views

urlpatterns = [
    path('', views.index, name='home'),
    path('schedule/<int:year>', views.schedule, name='scheduleyear'),
    path('submitpick/<pickid>', views.submitpick),
    path('league/create', views.createleague),
    path('league/<int:leagueid>', views.league)
]


from game import Game

class Parser:
  def __init__(self):
    self._game = False
    self._game_number = 1

  def check_kill(self, killer_id: int, killed_id: int):
    """
    This function add new kills to the counter of kills and check who killed who,
    if someone kills itself or the world kills someone, the player loses 1 score.
    If someone kills somebody else, the killer get 1 more score
    """
    self._game._total_kills += 1

    if killer_id == killed_id or killer_id == '1022':
      self._game._kills[killed_id]["score"] -= 1

    else:
      self._game._kills[killer_id]["score"] += 1

  def new_game_started(self):
    """
    Starts a new Game instance
    """
    if self._game:
      self._game = Game()
      self._game_number += 1

    else:
      self._game = Game()

  def user_info_changed(self, line_read: list):
    """
    Checks if the player username changed. If it does, the username is updated.
    Otherwise, it means that a new player has been connected to the match and the
    function to add a new player is executed.
    """
    if len(line_read) == 4:
      current_username = self.get_username(line_read[3])

    else:
      full_info = ''
      for i in range(3, len(line_read)):
        full_info += line_read[i]

      current_username = self.get_username(full_info)

    user_id = line_read[2]

    if user_id in self._game._kills.keys():
      if self._game._kills[user_id]["name"] != current_username:
        old_username = self._game._kills[user_id]["name"]
        self._game._players[self._game._players.index(old_username)] = current_username
        self._game._kills[user_id]["name"] = current_username

    else:
      self._game.add_player(current_username, user_id)

  def get_username(self, string: str):
    """
    Gets the player username
    """
    username = ''
    char_index = 2 # first letter
    char = string[char_index]

    while char != '\\':
      username += char
      char_index += 1
      char = string[char_index]

    return username

  def print_game(self, game_hash: str):
    """
    Just prints the game more nicely
    """
    print(f'Game {self._game_number}\n')
    print(f'Hash: {game_hash}\n')
    for user_id in self._game._kills:
      print(f'Score: {self._game._kills[user_id]["score"]}   Player: {self._game._kills[user_id]["name"]}')
    print('\n # # # # # # # # # # # # # # # # # # # #\n')

  def generate_hash(self):
      return self._game.generate_hash()


import os
from datetime import datetime
from app.exceptions import *

class Post:
    def __init__(self, subject, body, username) -> None:
        """
        Construct a Post

        Args:
            subject: post subject
            body   : post body
        """
        self.subject = subject
        self.body = body
        self.date = datetime.now()
        self.owner = username

    def __lt__(self, other):
         """
         Define less than to sort posts according to post date
         """
         return self.date < other.date

    def show_post(self):
        """
        Show the post
        """
        print("-----------------------------")
        print("Subject: {}".format(self.subject))
        print("-------- ")
        print(self.body)

class AddPost:
    def __init__(self, username, authorizor, authenticator) -> None:
        """
        Create Adapter to add posts

        Args:
            username: namd of the user who will add the post
            authorizor: authorizor will manage permissions
            authenticator: authenticator will manage users
        """
        self.username = username
        self.authorizor = authorizor
        self.authenticator = authenticator

    def post(self):
        """
        Create Post and check if the post added successfully

        Raises:
            NotLoggedInError: If the user isn't logged in
            PermissionError : If permission doesn't exists
        """
        os.system("clear")
        subject = input("Enter the subject: ")
        body    = input("Enter post body  : ")
        post    = Post(subject, body, self.username)

        try:
            self.authorizor.check_permission("add post", self.username)
            self.authenticator.users[self.username].posts.append(post)
            os.system("clear")
            print("-----------------------------")
            print("Your post added successfully")
            print("-----------------------------")

        except NotLoggedInError:
            os.system("clear")
            print("---------------------------------")
            print("You should login first")
            print("---------------------------------")

        except PermissionError:
            os.system("clear")
            print("-----------------------------------------")
            print("You don't have the permission to add post")
            print("-----------------------------------------")


# Add the root path of the dmrgpy library
import os ; import sys ; sys.path.append(os.getcwd()+'/../../src')

import numpy as np
from dmrgpy import spinchain

n = 20 # number of sites in your chain
spins = ["S=1" for i in range(n)] # create the sites
sc = spinchain.Spin_Chain(spins) # create the chain
#sc.itensor_version = "julia"

# now define the Hamiltonian
h = 0
for i in range(n-1):
    h = h + sc.Sx[i]*sc.Sx[i+1] # add exchange
    h = h + sc.Sy[i]*sc.Sy[i+1] # add exchange
    h = h + sc.Sz[i]*sc.Sz[i+1] # add exchange
for i in range(n-1):
    h = h + -1.1*sc.Sz[i]*sc.Sz[i] # add single ion anisotropy
sc.maxm = 20
sc.kpmmaxm = sc.maxm
sc.set_hamiltonian(sum(sc.Sx)) ; wf = sc.get_gs()
sc.set_hamiltonian(h) # and initialize the Hamiltonian
wf0 = sc.get_gs(wf0=wf)
# setup some parameters

# now define the operator for which you want the distribution
M = (1/(2*n))*sum([sc.Sz[i]*(-1)**i for i in range(len(sc.Sz))])
import time
t0 = time.time()
x,y = sc.get_distribution(X=M,delta=5e-2) # compute a distribution
t1 = time.time()
print("Time KPM",t1-t0)
from dmrgpy import distribution
x1,y1 = distribution.get_distribution_maxent(sc,X=M,n=6) # compute a distribution
t2 = time.time()
print("Time max ent",t2-t1)
#x1,y1 = sc.get_distribution(X=M,delta=1e-1,mode="ED") # compute a distribution

# plot the result and save it in a file
print("Integral KPM=",np.trapz(y.real,dx=x[1]-x[0]))
print("Integral Max ent=",np.trapz(y1.real,dx=x1[1]-x1[0]))
import matplotlib.pyplot as plt
np.savetxt("DISTRIBUTION.OUT",np.array([x,y.real]).T)
plt.plot(x,y.real,marker="o",label="KPM") # correlator using DMRG
plt.plot(x1,y1.real,marker="o",label="Max ent") # correlator using DMRG
plt.xlabel("magnetization")
plt.ylabel("distribution")
plt.legend()
plt.show()


class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children

def levelOrder(root: Node) -> [[int]]:
    """
    同二叉树的层序loop，只是每一层的个数不一定
    """
    queue = []
    if root is not None:
        queue.append(root)

    results = []
    while len(queue) > 0:
        size = len(queue)
        vector = []
        # 这里一定要使用固定大小size，不要使用que.size()，因为que.size是不断变化的
        for i in range(size):     # loop每一层的tree node
            front_node = queue.pop(0)
            vector.append(front_node.val)
            if front_node.children:
                for j in range(len(front_node.children)):     # 此处要loop过所有的children node并加入到queue里面
                    if front_node.children[j]:
                        queue.append(front_node.children[j])
        results.append(vector)

    return results

t1 = Node(val=1)
t2 = Node(val=2)
t3 = Node(val=3)
t4 = Node(val=4)
t1.children = [t2, t3, t4]
print(levelOrder(t1))


from keras.legacy import interfaces
from keras.optimizers import Optimizer
from keras import backend as K

class MySGD(Optimizer):
    """Keras中简单自定义SGD优化器
    每隔一定的batch才更新一次参数
    """
    def __init__(self, lr=0.01, steps_per_update=1, **kwargs):
        super(MySGD, self).__init__(**kwargs)
        with K.name_scope(self.__class__.__name__):
            self.iterations = K.variable(0, dtype='int64', name='iterations')
            self.lr = K.variable(lr, name='lr')
            self.steps_per_update = steps_per_update # 多少batch才更新一次

    @interfaces.legacy_get_updates_support
    def get_updates(self, loss, params):
        """主要的参数更新算法
        """
        shapes = [K.int_shape(p) for p in params]
        sum_grads = [K.zeros(shape) for shape in shapes] # 平均梯度，用来梯度下降
        grads = self.get_gradients(loss, params) # 当前batch梯度
        self.updates = [K.update_add(self.iterations, 1)] # 定义赋值算子集合
        self.weights = [self.iterations] + sum_grads # 优化器带来的权重，在保存模型时会被保存
        for p, g, sg in zip(params, grads, sum_grads):
            # 梯度下降
            new_p = p - self.lr * sg / float(self.steps_per_update)
            # 如果有约束，对参数加上约束
            if getattr(p, 'constraint', None) is not None:
                new_p = p.constraint(new_p)
            cond = K.equal(self.iterations % self.steps_per_update, 0)
            # 满足条件才更新参数
            self.updates.append(K.switch(cond, K.update(p, new_p), p))
            # 满足条件就要重新累积，不满足条件直接累积
            self.updates.append(K.switch(cond, K.update(sg, g), K.update(sg, sg+g)))
        return self.updates

    def get_config(self):
        config = {'lr': float(K.get_value(self.lr)),
                  'steps_per_update': self.steps_per_update}
        base_config = super(MySGD, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))


import rclpy
from rclpy.context import Context
from rclpy.node import Node
from geometry_msgs.msg import PoseArray, Pose, PoseStamped, TransformStamped
from std_msgs.msg import String
from typing import List
from pytransform3d import transformations as pt
from pytransform3d import rotations as pr
import numpy as np
import pycolmap
import trimesh
from pathlib import Path
import pickle
from sensor_msgs.msg import PointCloud2, PointField
from viewpoint_planner import ViewpointPlanner, PlannerModes
from viewpoint_planning.viewpoint import Camera
from std_msgs.msg import ColorRGBA, Header, Bool

from rclpy.parameter import Parameter

class ViewpointPlanningNode(Node):
    def __init__(self) -> None:
        super().__init__("viewpoint_planner")
        print('Hi from the viewpoint planner.')

        self.declare_parameter("home_directory", "/home")
        home_directory = self.get_parameter(
            'home_directory').get_parameter_value().string_value

        self.declare_parameter("map_name", "map-00195")
        map_name = self.get_parameter(
            'map_name').get_parameter_value().string_value
        environment = map_name.split(sep="-")[-1]

        self.declare_parameter(
            "cam_string", "PINHOLE 1280 720 609.5238037109375 610.1694946289062 640 360")
        cam_string = self.get_parameter(
            'cam_string').get_parameter_value().string_value

        self.declare_parameter(
            "mode_string", "trf_clf")
        mode_string = self.get_parameter(
            'mode_string').get_parameter_value().string_value

        self.declare_parameter(
            "planning_topic_name", "planning_poses")
        planning_topic_name = self.get_parameter(
            'planning_topic_name').get_parameter_value().string_value

        self.declare_parameter("occlusion", False)
        occlusion = self.get_parameter(
            'occlusion').get_parameter_value().bool_value

        self.declare_parameter("num_viewpoint_samples", 100)
        num_viewpoint_samples = self.get_parameter(
            'num_viewpoint_samples').get_parameter_value().integer_value

        self.plan_poses_sub = self.create_subscription(
            PoseArray, planning_topic_name, self.plan_poses_callback, 10)

        self.plan_single_pose_sub = self.create_subscription(TransformStamped, "plan_viewpoint", self.plan_viewpoint_callback, 10)
        self.viewpoint_result_map_pub = self.create_publisher(PoseStamped, "plan_viewpoint_result_map", 10)
        self.viewpoint_result_loc_cam_pub = self.create_publisher(PoseStamped, "plan_viewpoint_result_loc_cam", 10)
        self.planner_loc_pub = self.create_publisher(PoseStamped, "planner_loc", 10)
        self.mode_sub = self.create_subscription(String, "planner_mode", self.planner_mode_callback, 10)

        self.result_pose_publisher_map = self.create_publisher(
            PoseArray, 'viewpoint_poses_map', 10)

        self.result_pose_publisher_base = self.create_publisher(
            PoseArray, 'viewpoint_poses_base', 10)

        home_dir = Path(home_directory)
        environment_data = home_dir / \
            ('viewpoint_planning/data/' + environment)
        model_dir = home_dir / "viewpoint_planning/data/models"

        _, c_width, c_height, cfx, cfy, cx, cy = cam_string.split()
        camera = Camera(width=int(c_width),
                        height=int(c_height),
                        fx=float(cfx),
                        fy=float(cfy),
                        cx=float(cx),
                        cy=float(cy))

        reconstruction_dir = str(
            home_dir
        ) + f"/Hierarchical-Localization/outputs/{environment}/reconstruction"

        reconstruction = pycolmap.Reconstruction(reconstruction_dir)

        self.pc_publisher = self.create_publisher(PointCloud2, 'planning_pc', 10)

        self.landmark_list = list(reconstruction.points3D.keys())
        self.pcd_points = np.zeros((len(self.landmark_list), 3))

        for idx, landmark in enumerate(self.landmark_list):
            self.pcd_points[idx] = np.array(
                reconstruction.points3D[landmark].xyz)
        self.pointcloud_msg = self.point_cloud(points=self.pcd_points, parent_frame="map")
        self.pc_publisher.publish(self.pointcloud_msg)

        if occlusion:
            scene: trimesh.Trimesh = trimesh.load(
                str(environment_data) + f"/{environment}_mesh.ply")
        else:
            scene = None

        file = open(environment_data / "pose_dict.pkl", 'rb')
        pose_dict = pickle.load(file)
        file.close()

        file = open(environment_data / "landmark_dict.pkl", 'rb')
        landmark_dict = pickle.load(file)
        file.close()

        file = open(environment_data / "min_max.pkl", 'rb')
        min_max_dict = pickle.load(file)
        file.close()
        min_max_viewing_angles = min_max_dict["angles"]
        min_max_viewing_distances = min_max_dict["distances"]

        try:
            file = open(environment_data / "dino_3_landmark_dict.pkl", 'rb')
            dino_dict = pickle.load(file)
            file.close()
        except:
            print("ERROR")

        planner_mode = PlannerModes(mode_string)

        self.planner = ViewpointPlanner(
            pc_publisher = self.pc_publisher,
            mode=planner_mode,
            occlusion=occlusion,
            num_samples=num_viewpoint_samples,
            reconstruction=reconstruction,
            rc_scene=scene, camera=camera,
            landmark_dict=landmark_dict,
            dino_dict=dino_dict,
            model_dir=str(model_dir),
            min_max_viewing_angles=min_max_viewing_angles,
            min_max_viewing_distances=min_max_viewing_distances)

        self.T_zforward_zup = pt.transform_from(
            np.array([[0.0, -1.0, 0.0], [0.0, 0.0, -1.0], [1.0, 0.0,
                                                           0.0]]),
            np.array([0, 0.0, 0.0]))
        self.T_zup_zforward = np.linalg.inv(self.T_zforward_zup)

        self.mode_publisher = self.create_publisher(String, 'current_planner_mode', 10)
        timer_period = 0.5
        self.timer = self.create_timer(timer_period, self.timer_callback)

    def point_cloud(self, points, parent_frame):
        """ Creates a point cloud message.
        Args:
            points: Nx3 array of xyz positions.
            parent_frame: frame in which the point cloud is defined
        Returns:
            sensor_msgs/PointCloud2 message
        Code source:
            https://gist.github.com/pgorczak/5c717baa44479fa064eb8d33ea4587e0
        """
        ros_dtype = PointField.FLOAT32
        dtype = np.float32
        itemsize = np.dtype(dtype).itemsize  # A 32-bit float takes 4 bytes.

        data = points.astype(dtype).tobytes()
        fields = [PointField(
            name=n, offset=i * itemsize, datatype=ros_dtype, count=1)
            for i, n in enumerate('xyz')]
        header = Header(frame_id=parent_frame)

        return PointCloud2(
            header=header,
            height=1,
            width=points.shape[0],
            is_dense=False,
            is_bigendian=False,
            fields=fields,
            # Every point consists of three float32s.
            point_step=(itemsize * 3),
            row_step=(itemsize * 3 * points.shape[0]),
            data=data
        )

    def timer_callback(self):
        msg = String()
        msg.data = self.planner.mode.value
        self.mode_publisher.publish(msg)

    def plan_viewpoint_callback(self, msg: TransformStamped):
        translation = np.array([
            msg.transform.translation.x,
            msg.transform.translation.y,
            msg.transform.translation.z
        ])
        rotation = np.array([
            msg.transform.rotation.w,
            msg.transform.rotation.x,
            msg.transform.rotation.y,
            msg.transform.rotation.z,
        ])
        print(translation)

        planner_pose = PoseStamped()
        planner_pose.header.frame_id = "map"
        planner_pose.header.stamp = self.get_clock().now().to_msg()

        planner_pose.pose.position.x = msg.transform.translation.x
        planner_pose.pose.position.y = msg.transform.translation.y
        planner_pose.pose.position.z = msg.transform.translation.z

        planner_pose.pose.orientation.x = msg.transform.rotation.x
        planner_pose.pose.orientation.y = msg.transform.rotation.y
        planner_pose.pose.orientation.z = msg.transform.rotation.z
        planner_pose.pose.orientation.w = msg.transform.rotation.w

        self.planner_loc_pub.publish(planner_pose)

        pq = np.concatenate([translation, rotation])
        transformation_matrix = pt.invert_transform(pt.transform_from_pq(pq))
        planning_poses = [transformation_matrix]

        viewpoint_dict = self.planner.plan_viewpoints(planning_poses)

        viewpoint_poses_map = []
        viewpoint_poses_base = []

        viewpoint_poses_map_d = []
        viewpoint_poses_base_d = []

        for result in viewpoint_dict.keys():
            T_cam_map = viewpoint_dict[result]["T_cam_map"]
            T_map_cam = np.linalg.inv(self.T_zup_zforward @ T_cam_map)

            T_cam_base = viewpoint_dict[result]["T_cam_base"]
            T_base_cam = np.linalg.inv(self.T_zup_zforward @ T_cam_base)

            viewpoint_poses_map.append(self.transform_to_pose_stamped(T_map_cam, "map"))
            viewpoint_poses_base.append(self.transform_to_pose_stamped(T_base_cam, "hand"))

            viewpoint_poses_map_d.append(self.transform_to_pose(T_map_cam))
            viewpoint_poses_base_d.append(self.transform_to_pose(T_base_cam))
            # print(pt.pq_from_transform(T_base_cam))
            # print(pr.euler_from_quaternion(pt.pq_from_transform(T_base_cam)[3:], 2,1,0, False))
        self.viewpoint_result_map_pub.publish(viewpoint_poses_map[0])
        self.viewpoint_result_loc_cam_pub.publish(viewpoint_poses_base[0])

        result_pose_array_map = self.create_pose_array(viewpoint_poses_map_d)
        result_pose_array_base = self.create_pose_array(viewpoint_poses_base_d)
        self.result_pose_publisher_map.publish(result_pose_array_map)
        self.result_pose_publisher_base.publish(result_pose_array_base)

    def plan_poses_callback(self, msg):
        # Convert each pose in the received request to a 4x4 transformation matrix

        T_cam_base_orig = np.array(
            [[0.0, -1.0, 0.0, 0.0],
             [0.0, 0.0, -1.0, 0.0],
             [1.0, 0.0, 0.0, 0.0],
             [0.0, 0.0, 0.0, 1.0]])
        planning_poses = []
        for pose in msg.poses:

            translation = np.array([
                -pose.position.x,
                -pose.position.y,
                -pose.position.z
            ])
            rotation = np.array([
                pose.orientation.w,
                pose.orientation.x,
                pose.orientation.y,
                pose.orientation.z,

            ])
            pq = np.concatenate([translation, rotation])
            transformation_matrix = pt.transform_from_pq(pq)
            planning_poses.append(transformation_matrix)

        viewpoint_dict = self.planner.plan_viewpoints(planning_poses)

        viewpoint_poses_map = []
        viewpoint_poses_base = []
        for result in viewpoint_dict.keys():
            T_cam_map = viewpoint_dict[result]["T_cam_map"]
            T_map_cam = np.linalg.inv(self.T_zup_zforward @ T_cam_map)

            T_cam_base = viewpoint_dict[result]["T_cam_base"]
            T_base_cam = np.linalg.inv(self.T_zup_zforward @ T_cam_base)

            viewpoint_poses_map.append(self.transform_to_pose(T_map_cam))
            viewpoint_poses_base.append(self.transform_to_pose(T_base_cam))

        result_pose_array_map = self.create_pose_array(viewpoint_poses_map)
        result_pose_array_base = self.create_pose_array(viewpoint_poses_base)

        self.result_pose_publisher_map.publish(result_pose_array_map)
        self.result_pose_publisher_base.publish(result_pose_array_base)

    def planner_mode_callback(self, msg: String):
        self.planner.change_mode(msg.data)
        print(f"Planner mode changed to {msg.data}")

    def transform_to_pose(self, transformation_matrix):
        pq = pt.pq_from_transform(transformation_matrix)
        pose = Pose()
        pose.position.x = pq[0]
        pose.position.y = pq[1]
        pose.position.z = pq[2]

        pose.orientation.x = pq[4]
        pose.orientation.y = pq[5]
        pose.orientation.z = pq[6]
        pose.orientation.w = pq[3]
        return pose

    def transform_to_pose_stamped(self, transformation_matrix, frame):
        pq = pt.pq_from_transform(transformation_matrix)
        pose = PoseStamped()
        pose.header.frame_id = frame
        pose.header.stamp = self.get_clock().now().to_msg()
        pose.pose.position.x = pq[0]
        pose.pose.position.y = pq[1]
        pose.pose.position.z = pq[2]

        pose.pose.orientation.x = pq[4]
        pose.pose.orientation.y = pq[5]
        pose.pose.orientation.z = pq[6]
        pose.pose.orientation.w = pq[3]
        return pose

    def rotation_matrix_to_quaternion(self, rotation_matrix):
        qw = np.sqrt(
            1 + rotation_matrix[0, 0] + rotation_matrix[1, 1] + rotation_matrix[2, 2]) / 2
        qx = (rotation_matrix[2, 1] - rotation_matrix[1, 2]) / (4 * qw)
        qy = (rotation_matrix[0, 2] - rotation_matrix[2, 0]) / (4 * qw)
        qz = (rotation_matrix[1, 0] - rotation_matrix[0, 1]) / (4 * qw)
        return [qx, qy, qz, qw]

    def create_pose_array(self, poses):
        pose_array = PoseArray()
        pose_array.header.frame_id = 'map'  # Set the frame ID for the PoseArray
        pose_array.poses = poses
        return pose_array

def main(args=None):
    rclpy.init(args=args)
    print('Hi from learned_viewpoint_planning.')

    viewpoint_planner = ViewpointPlanningNode()

    rclpy.spin(viewpoint_planner)

    viewpoint_planner.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()


"""
Created on Sun Oct  4 12:47:45 2020

@author: Marc
"""
# Importing the libraries
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Loading the data
data = pd.read_csv('College_Data.csv')

# Plot (just for visualization)
sns.lmplot(x = 'Outstate', y = 'F.Undergrad', data = data, hue = 'Private',
           fit_reg = False)
plt.savefig('outstate_f-undergrad.png')

# Outstate VS Private Visualization
sns.set_style('darkgrid')
g = sns.FacetGrid(data, hue = 'Private', palette = 'coolwarm')
g.map(plt.hist, 'Outstate', bins = 20, alpha = 0.7)
plt.savefig('outstate_private.png')

# Grad. Rate VS Private Visualization
g = sns.FacetGrid(data, hue = 'Private', palette = 'coolwarm')
g.map(plt.hist, 'Grad.Rate', bins = 20, alpha = 0.7)
plt.savefig('grad-rate_private.png')

# In the plot we saw there was a school with a grad. rate > 100
school = data[data['Grad.Rate'] > 100]
# We need to change it at 100 (so it makes sense)
data['Grad.Rate']['Cazenovia College'] = 100

# K MEANS
from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters = 2)
kmeans.fit(data.drop(['Private', 'Unnamed: 0'], axis = 1))

# New dataframe (only for visualization)
d = {'Name': data['Unnamed: 0'],
     'Private': data['Private'],
     'Cluster': kmeans.labels_}
new_df = pd.DataFrame(d)
def check(df):
    if df['Private'] == 'Yes' and df['Cluster'] == 1:
        return 'YES'
    if df['Private'] == 'No' and df['Cluster'] == 0:
        return 'YES'
    return 'NO'
new_df['Same'] = new_df.apply(check, axis = 1)

# Final plot (only for visualization)
sns.countplot(x = 'Same', data = new_df)
plt.xlabel('K Means Clusters & Real Clusters')
plt.savefig('kmeans_results.png')

# Evaluation
# We can do this because we had labeled data
# In a real world project, you will use K Means Algorithm when
# you won't have labeled data
def conversion(x):
    if x == 'Yes':
        return 1
    return 0
from sklearn.metrics import confusion_matrix,classification_report
data['Cluster'] = data['Private'].apply(conversion)
print('------------------------------------------------------')
print('-----CONFUSION MATRIX---------------------------------')
print(confusion_matrix(data['Cluster'], kmeans.labels_))
print('------------------------------------------------------')
print('-----CLASSIFICATION REPORT----------------------------')
print(classification_report(data['Cluster'], kmeans.labels_))


import requests
from bs4 import BeautifulSoup

URL = "http://www.alba.co.kr"
daiso = "http://daiso.alba.co.kr/job/brand/"

result = requests.get(daiso)
soup = BeautifulSoup(result.text, "html.parser")

def extract_job(whatever):
    place = whatever.find("div", {"class": "L_MyAd_woowayouth0"})

    title = whatever.find("span", {"class": "title"})

    time = whatever.find("span", {"class": "time"})

    pay = whatever.find("span", {"class": "number"})

    date = whatever.find("td", {"class": "regDate last"})

    return {
        "place":
        place,
        "title":
        title,
        "time":
        time,
        "pay":
        pay,
        "date":
        date
    }

def extract_jobs(last_page):
    jobs = []
    for page in range(last_page):
        print(f"Scrapping page {page}")
        result = requests.get(daiso)
        soup = BeautifulSoup(result.text, "html.parser")
        results = soup.find_all("div", {"class": "goodsList goodsJob"})
        for result in results:
            job = extract_job(result)
            jobs.append(job)
    return jobs

def get_jobs():
  last_page = []
  jobs = extract_jobs([last_page])
  return jobs

# 정답 #
import os
import csv
import requests
from bs4 import BeautifulSoup

os.system("clear")

def write_company(company):
    file = open(f"{company['name']}.csv", mode="w")
    writer = csv.writer(file)
    writer.writerow(["place", "title", "time", "pay", "date"])
    for job in company["jobs"]:
      writer.writerow(list(job.values()))

alba_url = "http://www.alba.co.kr"

alba_request = requests.get(alba_url)
alba_soup = BeautifulSoup(alba_request.text, "html.parser")
main = alba_soup.find("div", {"id": "MainSuperBrand"})
brands = main.find_all("li", {"class": "impact"})
for brand in brands:
    link = brand.find("a", {"class": "goodsBox-info"})
    name = brand.find("span", {"class": "company"})
    if link and name:
        link = link["href"]
        name = name.text
        company = {'name': name, 'jobs': []}
        jobs_request = requests.get(link)
        jobs_soup = BeautifulSoup(jobs_request.text, "html.parser")
        tbody = jobs_soup.find("div", {"id": "NormalInfo"}).find("tbody")
        rows = tbody.find_all("tr", {"class": ""})
        for row in rows:
            local = row.find("td", {"class": "local"})
            if local:
                local = local.text.replace(u'\xa0', ' ')
            title = row.find("td", {"class": "title"})
            if title:
                title = title.find("a").find("span", {
                    "class": "company"
                }).text.strip()
                title = title.replace(u'\xa0', ' ')
            time = row.find("td", {"class": "data"})
            if time:
                time = time.text.replace(u'\xa0', ' ')
            pay = row.find("td", {"class": "pay"})
            if pay:
                pay = pay.text.replace(u'\xa0', ' ')
            date = row.find("td", {"class": "regDate"})
            if date:
                date = date.text.replace(u'\xa0', ' ')
            job = {
                "place": local,
                "title": title,
                "time": time,
                "pay": pay,
                "date": date
            }
            company['jobs'].append(job)
        write_company(company)

Assignment/DAY 8 OF 10 PYTHON CHALLENGE.py


from pathlib import Path

def find_Primes(x):
    for i in range (1,x//2):
        p1= i
        #print(p1)
        if(is_Prime(p1)):
            #print(p1, "is prime")
            p2 = x - p1
            if(is_Prime(p2)):
                #print(p2, " is prime")
                #print(p1, " ", p2, " is the answer")
                return [p1,p2]
def is_Prime(x):
    for i in range(2,x):
        if(x%i==0):
            #print(x, "is not prime")
            return False
    return True

inputFile = open("all_data\s2\s2.1-11.in", 'r')
lines = inputFile.readlines()[1:]
for line in lines:
    print(line)
    answer = find_Primes(int (line)*2)
    print(answer)
inputFile.close()


from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render

from .forms import CommentForm, PostForm
from .models import Follow, Group, Post

COUNT_POSTS = 10
User = get_user_model()

def index(request):
    posts = Post.objects.all()
    paginator = Paginator(posts, COUNT_POSTS)
    page_number = request.GET.get('page')
    page = paginator.get_page(page_number)
    return render(request, 'posts/index.html', {'page': page})

def group_posts(request, slug):
    group = get_object_or_404(Group, slug=slug)
    posts = group.posts.all()
    paginator = Paginator(posts, COUNT_POSTS)
    page_number = request.GET.get('page')
    page = paginator.get_page(page_number)
    return render(request, "group.html", {"group": group, "page": page})

@login_required
def new_post(request):
    form = PostForm(request.POST or None, files=request.FILES or None)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.author = request.user
        comment.save()
        return redirect("posts:index")
    return render(
        request, "posts/new_post.html",
        {"form": form, "is_new": True})

def profile(request, username):
    user_profile = get_object_or_404(User, username=username)
    paginator = Paginator(user_profile.posts.all(), COUNT_POSTS)
    page_number = request.GET.get('page')
    page = paginator.get_page(page_number)
    following = (request.user.is_authenticated and Follow.objects.filter(
        user__username=request.user,
        author=user_profile).exists())
    return render(
        request, 'posts/profile.html',
        {'page': page, 'user_profile': user_profile,
         'following': following})

def post_view(request, username, post_id):
    post = get_object_or_404(Post, id=post_id, author__username=username)
    user_profile = post.author
    comments = post.comments.all()
    form = CommentForm()
    return render(
        request, 'posts/post.html',
        {'post': post, 'user_profile': user_profile, 'form': form,
         'comments': comments})

@login_required
def post_edit(request, username, post_id):
    post = get_object_or_404(Post, id=post_id, author__username=username)
    if request.user != post.author:
        return redirect('posts:post_view', username, post_id)
    form = PostForm(
        request.POST or None, files=request.FILES or None, instance=post)
    if form.is_valid():
        form.save()
        return redirect('posts:post_view', username, post_id)
    return render(
        request, 'posts/new_post.html',
        {"form": form, "post": post, "is_new": False})

def page_not_found(request, exception):
    return render(
        request,
        "misc/404.html",
        {"path": request.path},
        status=404
    )

def server_error(request):
    return render(request, "misc/500.html", status=500)

@login_required
def add_comment(request, username, post_id):
    post = get_object_or_404(Post, author__username=username, id=post_id)
    form = CommentForm(request.POST or None)
    if form.is_valid():
        comment = form.save(commit=False)
        comment.author = request.user
        comment.post = post
        comment.save()
    return redirect('posts:post_view', username, post_id)

@login_required
def follow_index(request):
    post_list = Post.objects.filter(author__following__user=request.user)
    paginator = Paginator(post_list, COUNT_POSTS)
    page_number = request.GET.get('page')
    page = paginator.get_page(page_number)
    return render(
        request,
        "posts/follow.html",
        {'page': page, 'paginator': paginator}
    )

@login_required
def profile_follow(request, username):
    author = get_object_or_404(User, username=username)
    if author != request.user:
        Follow.objects.get_or_create(user=request.user, author=author)
    return redirect('posts:profile', username=username)

@login_required
def profile_unfollow(request, username):
    author = get_object_or_404(User, username=username)
    Follow.objects.filter(author=author, user=request.user).delete()
    return redirect('posts:profile', username=username)


import pygame
import sys

if __name__ == '__main__':
    pygame.init()
    running = True
    try:
        data = [int(line) for line in sys.stdin]
        size = width, height = data[0], data[1]
        screen = pygame.display.set_mode(size)
    except Exception:
        print('Неправильный формат ввода')
        running = False

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        pygame.draw.line(screen, (255, 255, 255), (0, 0), (width, height), width=5)
        pygame.draw.line(screen, (255, 255, 255), (0, height), (width, 0), width=5)
        pygame.display.flip()
    pygame.quit()


import cv2
import numpy as np
import argparse
import time
import find_boundary as bz
import os
import glob
def kmeans_seg(img, K):
    size = img.shape
    height = size[0]
    width = size[1]
    channel = size[2]

    imgPos = np.zeros(shape=(height, width, channel + 2))

    for i in range(height):
        for j in range(width):
            imgPos[i][j] = np.append(img[i][j], [i, j])

    Z = imgPos.reshape((-1, 5))

    # convert to np.float32
    Z = np.float32(Z)

    # define criteria, number of clusters(K) and apply kmeans()
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 1000, 0.1)
    # criteria = (10, 100, 1.0)

    ret, label, center = cv2.kmeans(Z, K, None, criteria, 20, cv2.KMEANS_RANDOM_CENTERS)

    # Now convert back into uint8, and make original image
    center = np.uint8(center)
    res = center[label.flatten(), 0:3]
    res2 = res.reshape((img.shape))

    mask = bz.find_bound(label, size)

    # mask.dtype = "uint8"

    # cv2.imshow('res2', res2)
    # cv2.imshow('mask',mask)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    return res2, mask

def seg(input_path,output_path, output_path2,K):
    start = time.time()
    img = cv2.imread(input_path)
    img_seg, img_binary = kmeans_seg(img, K)
    cv2.imwrite(output_path, img_seg)
    cv2.imwrite(output_path2, img_binary)
    end = time.time()
    print("Spend time: " + str(end - start))

def main():
    # Dir = '/home/tone/workspace/jupyter_lab/lab/Hanh/data/images/image_test'
    Desresult = '/home/buiduchanh/WorkSpace/Javis/Kmeans/result_Kmeans'
    Desresult_bound = '/home/buiduchanh/WorkSpace/Javis/Kmeans/result_bound'
    # imagelist = sorted(glob.glob('{}/*'.format(Dir)))
    listimage = [['/home/buiduchanh/Downloads/画像データ/61/6162/15100040/610000119/610005146.jpg', 'shadow'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/10500115/610000690/610032722.jpg', 'small_rust'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/10500115/610000690/610032743.jpg', 'pipe'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/15100090/610000143/610006427.jpg', 'large_rust'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/15100090/610000143/610006454.jpg', 'shadow'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/15100040/610000119/610005120.jpg', 'cable'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/15100190/610000688/610032632.jpg', 'tree'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/15100420/610000299/610014266.jpg', 'large_rust'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/10500115/610000004/610000203.jpg', 'high_contrast'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/10500180/610000033/610001218.jpg', 'medium_contrast'],
                 ['/home/buiduchanh/Downloads/画像データ/61/6162/15100390/610000263/610012394.jpg', 'low_contrast']]

    for input_path in listimage:
        print(input_path[0])
        basename = os.path.splitext(os.path.basename(input_path[0]))[0]
        # newname = basename + '_result' + '.jpg'
        newname = '{}_{}.jpg'.format(basename,input_path[1])
        output_path = os.path.join(Desresult,newname)
        output_path2 = os.path.join(Desresult_bound,newname)
        numberK = 3
        seg(input_path[0],output_path,output_path2,numberK)

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# author : puzzzzzzle
# email : 2359173906@qq.com
# desc : mng multi git repositories, only depends on python 3.5+

import concurrent.futures
import configparser
import argparse
import inspect
import logging
import functools
import multiprocessing
import os
import pathlib
import re
import subprocess
import time

# ---------- logger ----------

def create_cli_log(tag: str, format_str: str):
    # create logger
    tmp_log = logging.getLogger(tag)
    # create cli handle
    logger_handle = logging.StreamHandler()
    logger_handle.setLevel(LOG_LEVEL)
    # set formatter
    formatter = logging.Formatter(format_str)
    logger_handle.setFormatter(formatter)
    # add handle
    tmp_log.addHandler(logger_handle)
    return tmp_log

LOG_LEVEL = logging.INFO
logging.basicConfig(level=LOG_LEVEL)
logging.getLogger().handlers.clear()
cmd_logger = create_cli_log("cmd", '%(message)s')
# logger = create_cli_log("main", '|%(asctime)s|%(name)s|%(levelname)s|%(message)s')
logger = cmd_logger

# ---------- common cmd mng define ----------
def get_param_description(function, para_name):
    """
    get para's comment
    """
    docstring = function.__doc__
    if not docstring:
        return ""

    # regex for para
    pattern = rf":param\s*{para_name}\s*:\s*(.+)\s*"
    regex = re.compile(pattern, re.MULTILINE)
    match = regex.search(docstring)

    if match:
        param_desc = match.groups()
        return f"{param_desc[0]}"
    else:
        return ""

def build_args(sub_cmds, cls, run_func_name="run"):
    """
    build args for parser by function define
    """

    class MyHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
        def _format_args(self, action, default_metavar):
            return action.metavar

    parser = sub_cmds.add_parser(cls.cmd, description=cls.description,
                                 help=cls.help, formatter_class=MyHelpFormatter)

    run_func = getattr(cls, run_func_name)
    args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations = inspect.getfullargspec(run_func)
    default_arg_start = len(args)
    if defaults is not None:
        default_arg_start = len(args) - len(defaults)

    # add args
    normal_args = []
    default_args = {}
    for i in range(len(args)):
        if i == 0:
            continue
        arg = args[i]
        if i >= default_arg_start:
            default = defaults[i - default_arg_start]
            default_args[arg] = default
        else:
            normal_args.append(arg)
    # add positional requires args
    cls.normal_args = normal_args
    cls.default_args = default_args
    cls.annotations = annotations
    if len(normal_args) > 0:
        normal_args_help = ""
        metavar_str = ""
        for arg in normal_args:
            metavar_str += f"{arg} "
            t = str
            if arg in annotations:
                t = annotations[arg]
            comment = get_param_description(run_func, arg)
            if comment != "":
                comment = ":" + comment
            normal_args_help += f"[{arg}({t.__name__}){comment}] "
        parser.add_argument("args", metavar=metavar_str, type=str, nargs=len(normal_args),
                            help=normal_args_help)
    # add default args
    if len(default_args) > 0:
        for arg, value in default_args.items():
            if arg in annotations:
                t = annotations[arg]
            elif value is not None:
                t = type(value)
            else:
                t = str
            name = f"--{arg}"
            if len(arg) == 1:
                name = f"-{arg}"
            paras = {"type": t, "default": value}
            help_str = f"{get_param_description(run_func, arg)}"
            if t == bool:
                del paras["type"]
                if value:
                    help_str += f", default is set, add flags to set false"
                    paras["action"] = "store_false"
                else:
                    help_str += f", default is not set, add flags to set true"
                    paras["action"] = "store_true"

                paras["help"] = help_str
            else:
                paras["help"] = help_str

            parser.add_argument(name, **paras)

    parser.set_defaults(func=functools.partial(run_cmd, cls))
    pass

def run_cmd(cls, para):
    """
    execute cls
    """
    normal_args = cls.normal_args
    default_args = cls.default_args
    annotations = cls.annotations
    logger.debug(f"run {cls.__name__} {para}")
    # normal args
    if len(normal_args) > 0:
        args = list(para.args)
        assert len(args) == len(normal_args)
        for i in range(len(normal_args)):
            arg_name = normal_args[i]
            if arg_name in annotations:
                arg_type = annotations[arg_name]
                logger.debug(f"trans type {arg_name} -> {arg_type}; str value: {args[i]} ")
                args[i] = arg_type(args[i])
        args = tuple(args)
        logger.debug(f"position args {args}")
    else:
        args = ()
    # default args
    if len(default_args) > 0:
        dargs = dict(default_args)
        for key in default_args.keys():
            attr = getattr(para, key)
            logger.debug(f"get {key} {attr}")
            dargs[key] = attr
        logger.debug(f"default args {dargs}")
    else:
        dargs = {}
    cls.run_cmd(cls, *args, **dargs)
    pass

# ---------- repositories mng base define ----------
CONFIG_FILE_NAME = "Repositories.ini"

def cmd_main(args=None):
    """
    main args builder
    :return:
    """
    root = argparse.ArgumentParser(
        description=
        f"""
multi git repositories mng
""")
    root.set_defaults(func=lambda *args: root.print_help())

    sub_cmds = root.add_subparsers(help=f"supported cmds:")
    curr_module = inspect.getmodule(inspect.currentframe())
    for name, obj in inspect.getmembers(curr_module):
        if inspect.isclass(obj) and issubclass(obj, CmdBase) and name != "CmdBase":
            logger.debug(f"get one cmd {name}")
            build_args(sub_cmds, obj)

    args = root.parse_args(args)
    # execute
    args.func(args)

def find_file_in_parent_dir(start_path, file_name: str):
    """
    find file in curr or parent dir, return relative path
    """
    start_path = pathlib.Path(start_path).absolute()
    path = start_path
    assert path.is_dir()
    while True:
        logger.debug(f"find {path} {file_name}")
        f = path / file_name
        if f.exists() and f.is_file():
            result = start_path.relative_to(path)
            logger.debug(f"success find at {path} {result}")
            return result, path
        if path.parent == path:
            logger.debug(f"end find {path}")
            break
        path = path.parent.absolute()
    return None, None

def execute_cmd(cmd: str, force_log=False):
    start_time = time.time()

    def long_time_log(log_func, msg):
        if force_log or time.time() - start_time > 3:
            log_func(msg)

    process = subprocess.Popen(
        cmd,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        shell=True,
        text=True,
        bufsize=1
    )
    stdout_lines = []
    stderr_lines = []
    while process.poll() is None:
        # 从stdout输出读取内容
        stdout_line = process.stdout.readline()
        if stdout_line is not None:
            long_time_log(cmd_logger.info, stdout_line)
            stdout_lines.append(stdout_line)
        # 从stderr输出读取内容
        stderr_line = process.stderr.readline()
        if stderr_line:
            long_time_log(cmd_logger.error, stdout_line)
            stderr_lines.append(stdout_line)

    # 读取任何剩余的输出
    remaining_stdout, remaining_stderr = process.communicate()

    if remaining_stdout.strip():
        long_time_log(cmd_logger.info, remaining_stderr)
        stdout_lines.append(remaining_stderr)
    if remaining_stderr.strip():
        long_time_log(cmd_logger.error, remaining_stderr)
        stderr_lines.append(remaining_stderr)
    return process.wait(), stdout_lines, stderr_lines, cmd

def execute_cmd_in_rep_dir(cmd_obj, cmd_str, force_log=False):
    local_path = cmd_obj.value("local")
    curr_path = cmd_obj.base_path / local_path
    if not curr_path.exists():
        logger.info(f"project not cloned, ignore {cmd_obj.curr_name} {local_path}")
        return 0, [], [], cmd_str
    cmd = f'cd "{curr_path}" && {cmd_str}'
    logger.debug(f"will run -- {cmd} --")
    return execute_cmd(cmd, force_log)

def cmd_execute_worker(item, cls, conf, base_path, *args, **kwargs):
    global_conf = conf["__Global__"]
    cmd = cls(global_conf, conf[item], base_path, item)
    ret, info, err, cmd = cmd.run(*args, **kwargs)
    success = ret == 0
    header = "\n>>>>>>>>>>"
    if success:
        header += f"run success at {item}:"
    else:
        header += f"run fail at {item}:"
    body = ""
    if True or not success:
        body += f'\ncmd:{cmd}\n'
        for line in info:
            body += line
    if len(err) > 0:
        body += "err info:\n"
        for line in err:
            body += line
    body += "<<<<<<<<<<\n"

    if success:
        cmd_logger.debug(header + body)
    else:
        cmd_logger.error(header + body)
    return success, item

def create_and_run_cmd(cls, *args, **kwargs):
    curr_path = os.getcwd()
    curr_path = pathlib.Path(curr_path).absolute()

    # find config file
    relative_path, base_path = find_file_in_parent_dir(curr_path, CONFIG_FILE_NAME)
    assert relative_path is not None

    # load config file
    conf = configparser.ConfigParser()
    assert len(conf.read((base_path / CONFIG_FILE_NAME).absolute())) == 1

    # select needs
    need_exec = []
    for item in conf.sections():
        if item.title() == "__Global__":
            continue
        local_path = (base_path / conf[item]["local"]).absolute()
        if local_path == curr_path or local_path.is_relative_to(curr_path):
            logger.debug(f"add to exec {local_path}")
            need_exec.append(item)
        else:
            logger.debug(f"ignore {local_path}")

    # execute
    global_conf = conf["__Global__"]

    # for item in need_exec:
    #     run_item(item)
    jobs = cls.jobs_num
    if "jobs" in global_conf:
        jobs = int(global_conf["jobs"])
    cmd_logger.info(f"run with jobs {jobs}")
    assert jobs > 0
    curr_pool = concurrent.futures.ThreadPoolExecutor
    # curr_pool = concurrent.futures.ProcessPoolExecutor
    with curr_pool(max_workers=jobs) as executor:
        tasks = []
        for item in need_exec:
            fu = executor.submit(cmd_execute_worker, item, cls, conf, base_path, *args, **kwargs)
            tasks.append(fu)
        success_tasks = []
        fail_tasks = []
        for fu in concurrent.futures.as_completed(tasks):
            success, item = fu.result()
            if success:
                success_tasks.append(item)
            else:
                fail_tasks.append(item)
        info = f"total:{len(need_exec)} success:{len(success_tasks)} fail:{len(fail_tasks)}:{fail_tasks}"
        if len(fail_tasks) > 0:
            info += f" fail tasks:{fail_tasks}"
        cmd_logger.info(info)

class CmdBase:
    cmd = "CmdBase"
    description = "CmdBase desc"
    help = description
    jobs_num = multiprocessing.cpu_count()

    @staticmethod
    def run_cmd(cls, *args, **kwargs):
        return create_and_run_cmd(cls, *args, **kwargs)

    def __init__(self, global_conf, curr_conf, base_path, curr_name):
        self.global_conf = global_conf
        self.curr_conf = curr_conf
        self.base_path: pathlib.Path = base_path
        self.curr_name = curr_name
        pass

    def value_or_default(self, key: str, default=None) -> str:
        if key in self.curr_conf:
            return self.curr_conf[key]
        if key in self.global_conf:
            return self.global_conf[key]
        return default

    def value(self, key: str) -> str:
        if key in self.curr_conf:
            return self.curr_conf[key]
        if key in self.global_conf:
            return self.global_conf[key]
        raise KeyError(f"key {key} not exists")

    def run(self, *args, **kwargs):
        return 0, [], [], ""

# ---------- repositories mng  ----------

class TestCmd(CmdBase):
    cmd = "test"
    description = "test cmd args, just print input"
    help = description

    def run(self, arg1: int, arg2, arg3=1, arg4=2, arg5: int = None):
        """
        :param arg1  : arg1 desc str
        :param arg4  : arg4 desc str
        """
        cmd_logger.info(f"{arg1} {arg2} {arg3} {arg4} {arg5}")
        return 0, [], [], ""
        pass

class GitCloneCmd(CmdBase):
    cmd = "clone"
    description = "clone repositories in config"
    help = description

    def run(self):
        local_path = self.value("local")
        if (self.base_path / local_path).exists():
            cmd_logger.debug(f"ignore exists {self.curr_name} {local_path}")
            return 0, [], [], "ignore exists"
        recursive = self.value_or_default("recursive", "true")
        if recursive.strip(' ').upper() == 'TRUE':
            recursive_str = " --recursive "
        else:
            recursive_str = ""

        remote_path = self.value("remote")

        cmd = f'cd {self.base_path} && git clone {recursive_str} "{remote_path}" "{local_path}" '
        return execute_cmd(cmd)

class GitAnyCmd(CmdBase):
    cmd = "cmd"
    description = "run any cmd in each repository's dir"
    help = description

    def run(self, cmd: str):
        """
        :param cmd : any
        """
        return execute_cmd_in_rep_dir(self, cmd)
        pass

class GitUpdateCmd(CmdBase):
    cmd = "update"
    description = "update repositories in config"
    help = description

    def run(self, ignore_sub: bool = False):
        """
        :param ignore_sub : ignore update sub module
        """
        recursive_str = " --recurse-submodules"
        if ignore_sub:
            recursive_str = ""
        return execute_cmd_in_rep_dir(self, f'git pull {recursive_str}')
        pass

class GitCheckoutCmd(CmdBase):
    cmd = "checkout"
    description = "recursive update repositories in config"
    help = description

    def run(self, branch: str, r: bool = False):
        """
        :param branch : specified branch
        :param r : recurse submodule
        """
        #  git -c credential.helper= pull --recurse-submodules --progress origin better_game
        cmd = f'git checkout {branch} && git pull '
        if r:
            cmd += f' && git submodule foreach "git checkout {branch} && git pull"'
        return execute_cmd_in_rep_dir(self, cmd)
        pass

class GitStatusCmd(CmdBase):
    cmd = "status"
    description = "recursive update repositories in config"
    help = description
    jobs_num = 1

    def run(self, r: bool = False):
        """
        :param r : recurse submodule
        """
        #  git -c credential.helper= pull --recurse-submodules --progress origin better_game
        cmd = f'git status'
        if r:
            cmd += f' && git submodule foreach "git status"'
        cmd_logger.info(f"----------- git status at {self.curr_name} -----------")
        ret = execute_cmd_in_rep_dir(self, cmd, True)
        # cmd_logger.info(f"----------- git status end {self.curr_name} -----------\n")
        return ret

class GitConfUserCmd(CmdBase):
    cmd = "user"
    description = "set user's name and email"
    help = description

    def run(self, user_name: str, email: str, r: bool = False):
        """
        :param user_name : git user's name
        :param email : git user's email
        :param r : recurse submodule
        """
        set_one = f'git config user.name {user_name} && git config user.email {email}'
        cmd = set_one
        if r:
            cmd += f' && git submodule foreach "{set_one}"'
        cmd_logger.info(f"run at {self.curr_name} : {cmd}")
        ret = execute_cmd_in_rep_dir(self, cmd, True)
        return ret

if __name__ == '__main__':
    cmd_main()
    pass


n=int(input("Please enter a number: "))
count=0
for i in range (1,n):
	for j in range(2,n):
 		if i%j==0 and i!=j:
 			break
 		if j==n-1:
 			print (i)
 			count+=1
print("the count of numbers is -",count)


from Adafruit_MotorHAT import Adafruit_MotorHAT

class MotorController:
    direction_mapping = {
        "R": Adafruit_MotorHAT.RELEASE,
        "F": Adafruit_MotorHAT.FORWARD,
        "B": Adafruit_MotorHAT.BACKWARD}

    def __init__(self, num, motor_hat):
        self.motor = motor_hat.getMotor(num)
        self.motor.run(Adafruit_MotorHAT.RELEASE)
        self.motor.setSpeed(0)
        self.direction = 'R'
        self.speed = 0

    def update(self, direction, speed):
        if direction != self.direction:
            self.direction = direction
            direction_val = MotorController.direction_mapping.get(direction)
            if not direction_val:
                raise ValueError
            self.motor.run(direction_val)
        if speed != self.speed:
            self.speed = speed
            self.motor.setSpeed(speed)

    def stop(self):
        self.update('R', 0)


from gendiff.formatters.normalize import normalize_values

STATUS = {
    'unchanged': "  ",
    'added': "+ ",
    'removed': "- "
}

def stringify_val(value, depth: int) -> str:
    if not isinstance(value, dict):
        return value
    hold = ["{"]
    for key, val in value.items():
        hold.append(f"\n{'  ' * depth}  {key}: {stringify_val(val, depth + 2)}")
    hold.append(f"\n{'  ' * (depth - 1)}}}")
    return ''.join(hold)

def stringify_diff(diff: dict, depth=1) -> str:
    lst = []
    for k, v in diff.items():
        status = v['status']
        if status == 'nested':
            lst.append(f"{'  ' * depth}  {k}: {{\n")
            lst.append(f"{stringify_diff(v['value'], depth + 2)}")
            lst.append(f"{'  ' * (depth + 1)}}}\n")
        elif status == 'changed':
            lst.append(f"{'  ' * depth}- {k}: "
                       f"{stringify_val(v['old'], depth + 2)}\n")
            lst.append(f"{'  ' * depth}+ {k}: "
                       f"{stringify_val(v['new'], depth + 2)}\n")
        else:
            lst.append(f"{'  ' * depth}{STATUS[status]}{k}: "
                       f"{stringify_val(v['value'], depth + 2)}\n")
    res = ''.join(lst)
    return res

def format(diff: dict) -> str:
    diff = normalize_values(diff)
    return f"{{\n{stringify_diff(diff)}}}"


"""
В этом модуле лежат различные наборы представлений.

Разные view интернет-магазина: по товарам, заказам и т.д.
"""

from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.models import Group
from django.http import HttpResponse, HttpRequest, HttpResponseRedirect, JsonResponse
from timeit import default_timer
from django.core.cache import cache
from django.urls import reverse_lazy
from django.views.generic import TemplateView, ListView, DetailView, CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin, UserPassesTestMixin
from rest_framework.viewsets import ModelViewSet
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema, OpenApiResponse
import logging

from .forms import ProductForm, OrdersForm, GroupForm
from .mixins import LogoutIfNotStaffMixin
from .models import Product, Order, ProductImage
from django.views import View
from .serializers import ProductSerialiser, OrderSerialiser

logger = logging.getLogger(__name__)

@extend_schema(description="Product views CRUD")
class ProductViewSet(ModelViewSet):
    """
    Набор представлений для действий над Product
    Полный CRUD для сущностей товара
    """
    queryset = Product.objects.all()
    serializer_class = ProductSerialiser
    filter_backends = [
        SearchFilter,
        DjangoFilterBackend,
        OrderingFilter,
    ]
    search_fields = ["name", "description"]
    filterset_fields = [
        "name",
        "description",
        "price",
        "discount",
        "archived",
    ]
    ordering_fields = [
        "name",
        "price",
        "discount",
    ]

    @extend_schema(
        summary="Get one product by ID",
        description="Retrieves **product**, returns 404 if not found",
        responses={
            200: ProductSerialiser,
            404: OpenApiResponse(description="Empty response, product by id not found"),
        }
    )
    def retrieve(self, request, *args, **kwargs):
        return super().retrieve(*args, **kwargs)

class OrderViewSet(ModelViewSet):
    queryset = Order.objects.all()
    serializer_class = OrderSerialiser
    filter_backends = [
        SearchFilter,
        DjangoFilterBackend,
        OrderingFilter,
    ]
    search_fields = ["user", "products"]
    filterset_fields = [
        "delivery_address",
        "promocode",
        "created_at",
        "user",
        "products",
    ]
    ordering_fields = [
        "created_at",
        "user",
        "delivery_address",
    ]

class ShopIndexView(View):
    def get(self, request: HttpRequest) -> HttpResponse:
        products = [
            ('Laptop', 1999),
            ('Desktop', 2999),
            ('Smartphone', 999)
        ]
        context = {
            "time_running": default_timer(),
            "products": products,
            "items": 1,
        }
        return render(request, 'shopapp/shop-index.html', context=context)

class GroupsListView(View):
    def get(self, request: HttpRequest) -> HttpResponse:
        context = {
            "form": GroupForm(),
            "groups": Group.objects.prefetch_related('permissions').all(),
        }
        return render(request, 'shopapp/groups-list.html', context=context)

    def post(self, request: HttpRequest):
        form = GroupForm(request.POST)
        if form.is_valid():
            form.save()
        return redirect(request.path)

class ProductDetailsView(DetailView):
    template_name = "shopapp/product_details.html"
    # model = Product
    queryset = Product.objects.prefetch_related("images")
    context_object_name = "product"

    # def get(self, request: HttpRequest, pk: int) -> HttpResponse:
    #     product = get_object_or_404(Product, pk=pk)
    #     context = {
    #         "product": product,
    #     }
    #     return render(request, 'shopapp/products-details.html', context=context)

class ProductsListView(ListView):
    template_name = "shopapp/products-list.html"
    # model = Product
    context_object_name = "products"
    queryset = Product.objects.filter(archived=False)

# def products_list(request: HttpRequest):
#     context = {
#         "products": Product.objects.all(),
#     }
#     return render(request, 'shopapp/products-list.html', context=context)

class ProductCreateView(UserPassesTestMixin, CreateView):
    def test_func(self):
        # return self.request.user.groups.filter(name="secret-group").exists()
        return self.request.user.is_superuser

    model = Product
    fields = "name", "price", "description", "discount", "preview"
    success_url = reverse_lazy("shopapp:products_list")

# def create_product(request: HttpRequest) -> HttpResponse:
#     if request.method == "POST":
#         form = ProductForm(request.POST)
#         if form.is_valid():
#             # name = form.cleaned_data["name"]
#             # price = form.cleaned_data["price"]
#             form.save()
#             url = reverse("shopapp:products_list")
#             return redirect(url)
#     else:
#         form = ProductForm()
#     context = {
#         "form": form,
#     }
#     return render(request, "shopapp/create-product.html", context=context)

class ProductUpdateView(UpdateView):
    model = Product
    # fields = "name", "price", "description", "discount", "preview"
    form_class = ProductForm
    template_name_suffix = "_update_form"

    def get_success_url(self):
        return reverse(
            "shopapp:product_details",
            kwargs={"pk": self.object.pk},
        )

    def form_valid(self, form):
        response = super().form_valid(form)
        for image in form.files.getlist("images"):
            ProductImage.objects.create(product=self.object, image=image)
        return response

class ProductDeleteView(DeleteView):
    model = Product
    success_url = reverse_lazy("shopapp:products_list")

    def form_valid(self, form):
        success_url = self.get_success_url()
        self.object.archived = True
        self.object.save()
        return HttpResponseRedirect(success_url)

class OrdersListView(LoginRequiredMixin, ListView):
    queryset = (
        Order.objects
        .select_related("user")
        .prefetch_related("products")
    )

# def orders_list(request: HttpRequest):
#     context = {
#         "orders": Order.objects.select_related("user").prefetch_related("products").all(),
#     }
#     return render(request, 'shopapp/orders-list.html', context=context)

class OrderDetailView(PermissionRequiredMixin, DetailView):
    # permission_required = "view_order"
    permission_required = "shopapp.view_order"
    queryset = (
        Order.objects
        .select_related("user")
        .prefetch_related("products")
    )

class OrderCreateView(CreateView):
    model = Order
    fields = "user", "products", "promocode", "delivery_address"
    success_url = reverse_lazy("shopapp:order_list")
    logger.info(f'Создан заказ {fields}')

# def create_order(request: HttpRequest) -> HttpResponse:
#     if request.method == "POST":
#         form = OrdersForm(request.POST)
#         if form.is_valid():
#             form.save()
#             url = reverse("shopapp:order_list")
#             return redirect(url)
#     else:
#         form = OrdersForm()
#     context = {
#         "form": form,
#     }
#     return render(request, "shopapp/create-order.html", context=context)

class OrderUpdateView(UpdateView):
    model = Order
    fields = "user", "products"
    template_name_suffix = "_update_form"

    def get_success_url(self):
        return reverse(
            "shopapp:order_details",
            kwargs={"pk": self.object.pk},
        )

class OrderDeleteView(DeleteView):
    model = Order
    success_url = reverse_lazy("shopapp:order_list")

class ProductsDataExportView(View):
    def get(self, request: HttpRequest) -> JsonResponse:
        products = Product.objects.order_by("pk").all()
        products_data = [
            {
                "pk": product.pk,
                "name": product.name,
                "price": product.price,
                "archived": product.archived,
            }
            for product in products
        ]
        return JsonResponse({"products": products_data})

class OrderDataExportView(PermissionRequiredMixin, LogoutIfNotStaffMixin, View):
    permission_required = 'is_staff'

    def get(self, request: HttpRequest) -> JsonResponse:
        orders = Order.objects.order_by("pk").all()
        orders_data = [
            {
                "user": order.user.pk,
                "products": order.products.pk,
                "pk": order.pk,
                "promocode": order.promocode,
                "delivery_address": order.delivery_address,
            }
            for order in orders
        ]
        return JsonResponse({"orders": orders_data})


num1 = float(input("Enter First Number: "))
asmd = str(input("Enter +,-,x,/: "))
num2 = float(input("Enter Second Number: "))
add = num1 + num2
subtract = num1 - num2
multiply = num1 * num2
divided = num1 / num2
if asmd == "+" :
     print(add)
elif asmd == "-" :
     print(subtract)
elif asmd == "x" :
     print(multiply)
elif asmd == "/" :
     print(divided)
else :
     print("Invalid str")


import time
'''
Author: me
'''
cc = 7
charlist = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
            'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
print("Questo programma cripta del testo sueguendo una logicas fissa")

def crypt(cc, charlist):
    text = str(input("Inserisci il testo da criptare: "))
    print("Ecco il testo criptato: ", end='')
    for i in text:
        index = 0
        i.lower()
        if not i in charlist:
            print(i, end='')
        else:
            for x in charlist:
                if i == x:
                    print(charlist[index + cc], end='')
                else:
                    index += 1
                    while cc + index >= len(charlist):
                        cc -= 26
        cc += 3

def decrypt(cc, charlist):
    text = str(input("Inserisci il testo da decriptare: "))
    print("Ecco il testo decriptato: ", end='')
    for i in text:
        index = 0
        i.lower()
        if not i in charlist:
            print(i, end='')
        else:
            for x in charlist:
                if i == x:
                    while index - cc < 0:
                        index += 26
                    print(charlist[index - cc], end='')
                else:
                    index += 1
        cc += 3

def menu():
    print("Decidi cosa vuoi fare:", "\n", "1 - Cripta il testo",
          "\n", "2 - Decripta il testo", "\n", "3 - Spiegazione riguardo alla logica "
          "usata", "\n", "4 - Termina il programma")

def choice():
    c = str(input("Scelta: "))
    if c == '1':
        print('')
        crypt(cc, charlist)
        print('')
        print('')
        main()
    elif c == '2':
        print('')
        decrypt(cc, charlist)
        print('')
        print('')
        main()
    elif c == '3':
        print('')
        print("Non ho voglia di spiegare")
        print('')
        main()
    elif c == '4':
        print('')
        print("Il programma si sta chiudendo...")
        time.sleep(1.5)
    else:
        print("Scelta non valida, devi scegliere tra 1, 2, 3 e 4")
        choice()

def main():
    menu()
    choice()

main()


"""Methods using SyReNN to understand classification of a network on a plane.
"""
import numpy as np
from pysyrenn.frontend.network import Network
from pysyrenn.frontend.argmax_layer import ArgMaxLayer

from timeit import default_timer as timer

class PlanesClassifier:
    """Handles classifying a set of planes using SyReNN.
    """
    def __init__(self, network, planes, preimages=True):
        """Creates a new PlanesClassifier for the given @network and @planes.

        @planes should be a list of Numpy arrays with each one representing a
        V-representation polytope with (n_vertices, n_dims). If preimages=True
        is set, preimages of the endpoints of each classification region will
        be returned (otherwise, only the combinations will be).
        """
        self.network = network
        self.planes = planes
        self.preimages = preimages

        self.partially_computed = False
        self.transformed_planes = None
        self.timing = None

        self.computed = False
        self.classifications = None

    def partial_compute(
            self,
            include_post=True,
            compute_pre=False,
            fuse_classify=False,
            post_process=True,
            device= -1,
            dry_run=False):
        """Computes the relevant ExactLine and stores it for analysis.
        """
        if self.partially_computed:
            return

        self.transformed_planes = self.network.transform_planes(self.planes,
                                                                self.preimages,
                                                                include_post=include_post,
                                                                compute_pre=compute_pre,
                                                                fuse_classify=fuse_classify,
                                                                post_process=post_process,
                                                                device = device,
                                                                dry_run = dry_run)

        if dry_run:
            return

        if post_process:
            self.timing = [timing for _, timing in self.transformed_planes]
            self.transformed_planes = [plane for plane, _ in self.transformed_planes]

        self.partially_computed = True
        if fuse_classify and post_process:
            self.classifications = []
            for transformed_plane in self.transformed_planes:
                if include_post:
                    preimages = [preimage for preimage, _, _ in transformed_plane]
                    labels = [label for _, _, label in transformed_plane]
                else:
                    preimages = [preimage for preimage, _ in transformed_plane]
                    labels = [label for _, label in transformed_plane]
                self.classifications.append((preimages, labels))
            self.computed = True

    @classmethod
    def from_syrenn(cls, transformed_planes):
        """Constructs a partially-computed PlanesClassifier from ExactLines.
        """
        self = cls(None, None, None)
        self.transformed_planes = transformed_planes
        self.partially_computed = True
        return self

    def compute(self):
        """Returns the classification regions of network restricted to @planes.

        Returns a list with one tuple (pre_regions, corresponding_labels) for
        each plane in self.planes. pre_regions is a list of Numpy arrays, each
        one representing a VPolytope.

        In contrast to LinesClassifier, no attempt is made here to return the
        minimal set.
        """
        if self.computed:
            return self.classifications

        self.partial_compute()

        self.classifications = []
        classify_network = Network([ArgMaxLayer()])
        syrenn_server_time = 0
        post_compute_time = 0
        for upolytope in self.transformed_planes:
            pre_polytopes = []
            labels = []
            # First, we take each of the linear partitions and split them where
            # the ArgMax changes.
            postimages = [post for pre, post in upolytope]

            # start = timer()
            classified_posts = classify_network.transform_planes(
                postimages, compute_preimages=False, include_post=True)
            # syrenn_server_time += timer() - start

            start = timer()
            for vpolytope, classify_upolytope in zip(upolytope,
                                                     classified_posts):
                pre, post = vpolytope
                for combinations, classified_post in classify_upolytope:
                    pre_polytopes.append(np.matmul(combinations, pre))
                    mean_combination = np.mean(combinations, axis=0)

                    """
                    if (combinations.shape[0] != combinations.shape[1]):
                        print("\nclassified prepost:", post.shape, "\n", post)
                        print("\nclassified comb:", combinations.shape, "\n", combinations)
                        print("\nclassified post:", classified_post.shape, "\n", classified_post)

                        print("\nmean classified comb:", mean_combination.shape)
                        print(mean_combination)

                        print("\nmean classified comb * prepost:", np.matmul(mean_combination, post).shape)
                        print(np.matmul(mean_combination, post))
                        quit()
                    """

                    class_region_label = np.argmax(
                        np.matmul(mean_combination, post).flatten())
                    labels.append(class_region_label)
            self.classifications.append((pre_polytopes, labels))

            post_compute_time += timer() - start

        print("Post compute  time in classification: ", post_compute_time * 1000, "ms");
        # print("SyReNN Server time in classification: ", syrenn_server_time * 1000, "ms");

        self.computed = True
        return self.classifications


class NodoPilha:
    def __init__(self, dado=0, nodo_anterior=None):
        self.dado = dado
        self.anterior = nodo_anterior

    def __repr__(self):
        return '%s -> %s' % (self.dado, self.anterior)

class Pilha:
    def __init__(self):
        self.topo = None

    def __repr__(self):
        return "[" + str(self.topo) + "]"

    def insere(self, novo_dado):
        novo_nodo = NodoPilha(novo_dado)
        novo_nodo.anterior = self.topo
        self.topo = novo_nodo

    def remove(self):
        assert self.topo, "Impossível remover valor de pilha vazia."
        self.topo = self.topo.anterior

    def maiorElementoDaPilha(self, pilha):
        if not pilha.topo:
            return None

        maior = pilha.topo.dado
        nodo_atual = pilha.topo

        while nodo_atual:
            if nodo_atual.dado > maior:
                maior = nodo_atual.dado
            nodo_atual = nodo_atual.anterior

        return maior

    def imprimirNaOrdemInversa(self):
        nodo_atual = self.topo
        while nodo_atual:
            print(nodo_atual.dado, end=' -> ')
            nodo_atual = nodo_atual.anterior
        print("None")

    def compararIgualdadeDePilha(self, outra_pilha):
        nodo1 = self.topo
        nodo2 = outra_pilha.topo

        while nodo1 and nodo2:
            if nodo1.dado != nodo2.dado:
                print("Diferente")
                return False
            nodo1 = nodo1.anterior
            nodo2 = nodo2.anterior

        if nodo1 is None and nodo2 is None:
            print("Igual")
            return True
        else:
            print("Diferente")
            return False

    def tPilha(self, vetor):
        for numero in vetor:
            if numero % 2 == 0:
                self.insere(numero)
            else:
                numeroRetirado = self.topo.dado if self.topo else None
                if numeroRetirado is not None:
                    print(f"Retirado da pilha: {numeroRetirado}")

        while self.topo:
            numeroRetirado = self.topo.dado
            print(f"Retirado da pilha: {numeroRetirado}")
            self.remove()

    def tPilha2(self, outra_pilha, vetor):
        for numero in vetor:
            if numero > 0:
                self.insere(numero)
            elif numero < 0:
                outra_pilha.insere(numero)
            else:
                elemento_atual = self.topo.dado if self.topo else None
                elemento_outra_pilha = outra_pilha.topo.dado if outra_pilha.topo else None
                if elemento_atual is not None:
                    print(f"Retirado da pilha atual: {elemento_atual}")
                    self.remove()
                if elemento_outra_pilha is not None:
                    print(f"Retirado da outra pilha: {elemento_outra_pilha}")
                    outra_pilha.remove()

class TestePilha:
    pilha1 = Pilha()
    pilha1.insere(3)
    pilha1.insere(4)
    pilha1.insere(5)
    pilha1.insere(2)
    pilha1.insere(1)

    maior = pilha1.maiorElementoDaPilha(pilha1)
    print("Maior elemento na pilha:", maior)
    pilha1.imprimirNaOrdemInversa()

    pilha2 = Pilha()
    pilha2.insere(3)
    pilha2.insere(4)
    pilha2.insere(5)
    pilha2.insere(2)
    pilha2.insere(1)

    pilha3 = Pilha()
    pilha3.insere(1)

    pilha1.compararIgualdadeDePilha(pilha2)
    pilha1.compararIgualdadeDePilha(pilha3)

    vetor = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    pilhaT = Pilha()
    pilhaT.tPilha(vetor)

    vetor = [1, 2, 0, -3, -4, 0, 5, -6]
    minhaPilha = Pilha()
    outraPilha = Pilha()
    minhaPilha.tPilha2(outraPilha, vetor)

class PilhaCarros:
    def __init__(self):
        self.carros = []

    def estacionarCarro(self, placa):
        self.carros.append(placa)

    def verificarEstacionamento(self, placa):
        sequencia = []
        temCarro = False

        while self.carros:
            carro = self.carros.pop()
            sequencia.append(carro)

            if carro == placa:
                temCarro = True
                break

        if temCarro:
            print(f"O carro {placa} consegue sair. Retire nessa ordem: {sequencia}")
        else:
            print(f"O carro {placa} não foi encontrado na rua.")

pilhaCarros = PilhaCarros()

pilhaCarros.estacionarCarro("12345")
pilhaCarros.estacionarCarro("67890")
pilhaCarros.estacionarCarro("54321")

placaDesejada = "67890"
pilhaCarros.verificarEstacionamento(placaDesejada)


import math

def prime_factors(number):
    big_prime = 1

    if number % 2 == 0:
        big_prime = 2
    for oddNum in range(3, int(math.sqrt(number)) + 1, 2):
        if number % oddNum == 0:
            big_prime = oddNum
            number /= oddNum

    return big_prime

if __name__ == "__main__":
    print(prime_factors(600851475143))


from odoo import models, fields, api

class TimerMixin(models.AbstractModel):
    _name = 'timer.mixin'
    _description = 'Timer Mixin'
    # YTI Note: This mixin is supposed to be extended to
    # any models

    timer_start = fields.Datetime("Timer Start")
    timer_pause = fields.Datetime("Timer Last Pause")
    is_timer_running = fields.Boolean(compute="_compute_timer")

    @api.depends('timer_start')
    def _compute_timer(self):
        for record in self:
            record.is_timer_running = bool(record.timer_start)

    def action_timer_start(self):
        """ Action start the timer.
            Start timer and search if another timer hasn't been launched.
            If yes, then stop the timer before launch this timer.
        """
        self.ensure_one()
        if not self.timer_start:
            self.write({'timer_start': fields.Datetime.now()})

    def action_timer_stop(self):
        """ Stop the timer and return the spent minutes since it started
            :return minutes_spent if the timer is started,
                    otherwise return False
        """
        self.ensure_one()
        if not self.timer_start:
            return False
        minutes_spent = self._get_minutes_spent()
        self.write({'timer_start': False, 'timer_pause': False})
        return minutes_spent

    def _get_minutes_spent(self):
        start_time = self.timer_start
        stop_time = fields.Datetime.now()
        # timer was either running or paused
        if self.timer_pause:
            start_time += (stop_time - self.timer_pause)
        return (stop_time - start_time).total_seconds() / 60

    def action_timer_pause(self):
        self.write({'timer_pause': fields.Datetime.now()})

    def action_timer_resume(self):
        new_start = self.timer_start + (fields.Datetime.now() - self.timer_pause)
        self.write({'timer_start': new_start, 'timer_pause': False})

    @api.model
    def get_server_time(self):
        """ Returns the server time.
            The timer widget needs the server time instead of the client time
            to avoid time desynchronization issues like the timer beginning at 0:00
            and not 23:59 and so on.
        """
        return fields.Datetime.now()


import unicodedata

def is_latin(word):
    for char in word:
        if unicodedata.name(char).startswith('LATIN'):
            return True
    return False

def is_cyrillic(word):
    for char in word:
        if unicodedata.name(char).startswith('CYRILLIC'):
            return True
    return False

artists_list = []

with open('uniq_artists.txt') as f:
    line = f.readline()
    while line:
        line_clean = line.split(':')[1].strip()
        # print(line_clean)
        line = f.readline()
        if len(line_clean) == 0:
            pass
        else:
            if is_latin(line_clean):
                # print(f"Latin {line_clean}")
                artists_list.append(line_clean)
            elif is_cyrillic(f"Cyrillic {line_clean}"):
                # print(f"Is cyrillic")
                artists_list.append(line_clean)
            else:
                print("I don't now")

with open('list_of_artists.txt', 'w') as df:
    df.writelines([word + ';' for word in artists_list])

# print(artists_list)


import math
import random
from collections import defaultdict
from copy import copy

import matplotlib.pyplot as plt
import uuid
import jsonpickle

from helpers import get_filename
from service_handling.dynamo_handling.emotion_randomization import get_emotion_ids_by_valence
from service_handling.dynamo_handling.get_bucket_contents import list_all_objects_in_bucket
from metadata.file_metadata import Metadata
from config import video_ids, valences
from service_handling.dynamo_handling.user_creation.plots import plot_emotion_distribution, \
    plot_video_id_distribution
from service_handling.dynamo_handling.user_creation.plots import plot_file_distribution

def get_random_subset_emotion(my_list):
    my_list = copy(my_list)
    subset_length = 11
    return random.sample(my_list, subset_length)

def get_custom_replication(my_list, total_length):
    ret = []

    my_list = copy(my_list)

    replications = math.ceil(total_length / len(my_list))

    for i in range(replications):
        random.shuffle(my_list)
        ret.extend(my_list)

    return ret[:total_length]

def get_objects_as_metadata(valence):
    ret = []

    meta_list = []
    s3_objects = list_all_objects_in_bucket()
    for obj in s3_objects:
        filename = get_filename(obj["Key"])
        meta = Metadata(filename)
        if meta.emotion_1_valence == valence or meta.emotion_1_valence == "neu":
            meta_list.append(meta)

    for i in range(8):
        random.shuffle(meta_list)
        ret.extend(meta_list)

    return ret

def set_items():
    user_pool = []

    for valence in valences:

        # e.g. positive or negative type
        user_type = []

        objects_metadata = get_objects_as_metadata(valence)
        emotions = get_emotion_ids_by_valence(valence)

        # 125 instances of each user_type
        for idx in range(125):
            added_filenames = set()

            print(idx)

            user = []

            random.shuffle(objects_metadata)

            emotions_subset = get_random_subset_emotion(emotions)
            emotion_pool = get_custom_replication(emotions_subset, total_length=132)
            video_pool = get_custom_replication(video_ids, total_length=132)

            rejects = 0

            # add items to the user while emotion pool is not exhausted
            while emotion_pool:
                item = random.choice(objects_metadata)

                while item.filename in added_filenames:
                    item = random.choice(objects_metadata)

                if item.emotion_1_id in emotion_pool and item.video_id in video_pool:

                    user.append({"item": copy(item),
                                 "emotions_id_subset": copy(emotions_subset)})

                    added_filenames.add(copy(item.filename))
                    objects_metadata.remove(item)
                    emotion_pool.remove(item.emotion_1_id)
                    video_pool.remove(item.video_id)

                else:
                    rejects += 1
                    if rejects > len(objects_metadata):
                        video_pool = get_custom_replication(video_ids, total_length=len(video_pool))

            user_type.append(user)

        user_pool.append(user_type)

    return user_pool

def main():
    user_pool = set_items()

    frozen = jsonpickle.encode(user_pool)

    # Writing to sample.json
    with open("user_pool.json", "w") as outfile:
        outfile.write(frozen)

if __name__ == "__main__":
    main()