from math import *

def nto(x):
    for i in range(2, isqrt(x)+1):
        if (x % i == 0):
            return False
    return x > 1

if __name__ == '__main__':
    n = int(input())
    if (nto(n)):
        print("YES")
    else:
        print("NO")


import numpy as np
from math import cos, acos, sqrt, exp, sin
from time import time, sleep

class PTZCamera_():
    def __init__(self, properties, map_size, grid_size,
                    Kv = 60, Ka = 5, Kp = 1, step = 0.1):

        self.grid_size = grid_size
        self.size = (int(map_size[0]/grid_size[0]), int(map_size[1]/grid_size[1]))
        self.id = properties['id']
        self.pos = properties['position']
        self.perspective = properties['perspective']/self.Norm(properties['perspective'])
        self.alpha = properties['AngleofView']/180*np.pi
        self.R = properties['range_limit']
        self.lamb = properties['lambda']
        self.color = properties['color']
        self.max_speed = properties['max_speed']
        self.sigma = properties['intensity']
        self.perspective_force = 0
        self.zoom_force = 0
        self.positional_force = np.array([0.,0.])
        self.targets = []
        self.FoV = np.zeros(self.size)
        self.global_event = np.zeros(self.size)
        self.global_event_plt = np.zeros(self.size)
        self.global_voronoi = np.zeros(self.size)
        self.local_Voronoi = []
        self.Kv = Kv
        self.Ka = Ka
        self.Kp = Kp
        self.step = step
        self.neighbors = []
        self.map_plt = np.zeros((self.size))
        self.intercept_quality = 0
        self.coverage_quality = 0
        self.last_pos = self.pos
        self.role = "Interceptor"

    def Update(self, targets, neighbors, centroid_tmp, geo_center_tmp):

        self.neighbors = neighbors
        self.targets = targets
        self.centroid = centroid_tmp
        self.geo_center = geo_center_tmp

        self.global_event = self.ComputeEventDensity(targets = self.targets)
        self.global_event_plt = ((self.global_event - self.global_event.min()) * (1/(self.global_event.max()
                                    - self.global_event.min()) * 255)).astype('uint8')

        self.FoV = np.zeros(self.size)
        self.UpdateFoV()

        # if self.role == "Tracker":
        #     self.UpdateGlobalVoronoi()
        # elif self.role == "Interceptor":
        #     self.UpdateSubGlobalVoronoi()

        self.UpdateLocalVoronoi()

        self.ComputeLocalCentroidal()
        self.UpdateOrientation()
        self.UpdateZoomLevel()

        self.UpdateRole()
        self.UpdatePosition()

        return

    def UpdateOrientation(self):

        self.perspective += self.perspective_force*self.step
        self.perspective /= self.Norm(self.perspective)

        return

    def UpdateZoomLevel(self):

        self.alpha += self.zoom_force*self.step

        return

    def UpdatePosition(self):

        # Tracker Control Law (Move to Sweetspot)

        if self.role == "Tracker":

            centroid_force = (self.centroid*self.grid_size - self.pos) * (1 - self.R*cos(self.alpha)
                                /self.Norm((self.centroid*self.grid_size - self.pos)[0]))
            rot = np.array([[cos(np.pi/2), -sin(np.pi/2)],
                        [sin(np.pi/2), cos(np.pi/2)]])
            v = rot@self.perspective.reshape(2,1)
            allign_force = ((self.geo_center*self.grid_size - self.pos)@v)*v

            self.positional_force = centroid_force[0]/2 + np.array([allign_force[0][0], allign_force[1][0]])/2

        # Interceptor Control Law (Move to Centroid)
        elif self.role == "Interceptor":

            self.positional_force = (self.centroid[0]*self.grid_size - self.pos)

        self.pos += self.Kp*self.positional_force*self.step

        return

    def UpdateGlobalVoronoi(self): # Not Finished
        return

    def UpdateSubGlobalVoronoi(self): # Not Finished
        return

    def UpdateFoV(self):

        range_max = (self.lamb + 1)/(self.lamb)*self.R
        quality_map = None
        quality_int_map = None
        intercept_map = np.zeros(self.FoV.shape)
        self.intercept_quality = 0

        for y_map in range(max(int((self.pos[1] - range_max)/self.grid_size[1]), 0),\
                            min(int((self.pos[1] + range_max)/self.grid_size[1]), self.size[1])):

            x_map = np.arange(max(int((self.pos[0] - range_max)/self.grid_size[0]), 0),\
                            min(int((self.pos[0] + range_max)/self.grid_size[0]), self.size[0]))

            q_per = self.ComputePerspectiveQuality(x_map*self.grid_size[0], y_map*self.grid_size[1])
            q_res = self.ComputeResolutionQuality(x_map*self.grid_size[0], y_map*self.grid_size[1])
            q_int = self.ComputeInterceptionQuality(x_map*self.grid_size[0], y_map*self.grid_size[1])

            quality = np.where((q_per > 0) & (q_res > 0), q_per*q_res, 0)
            q_int = np.where(q_int >= 0, q_int, 0)

            if quality_map is None:
                quality_map = quality
                quality_int_map = q_int

            else:
                quality_map = np.vstack((quality_map, quality))
                quality_int_map = np.vstack((quality_int_map, q_int))

        intercept_map[max(int((self.pos[1] - range_max)/self.grid_size[1]), 0):\
                                min(int((self.pos[1] + range_max)/self.grid_size[1]), self.size[0]),\
                                    max(int((self.pos[0] - range_max)/self.grid_size[0]), 0):\
                                        min(int((self.pos[0] + range_max)/self.grid_size[0]), self.size[0])]\
                                            = quality_int_map

        self.intercept_quality = np.sum(intercept_map*np.transpose(self.global_event))

        self.FoV[max(int((self.pos[1] - range_max)/self.grid_size[1]), 0):\
                    min(int((self.pos[1] + range_max)/self.grid_size[1]), self.size[0]),\
                        max(int((self.pos[0] - range_max)/self.grid_size[0]), 0):\
                            min(int((self.pos[0] + range_max)/self.grid_size[0]), self.size[0])]\
                                = quality_map

        return

    def UpdateLocalVoronoi(self):

        quality_map = self.FoV
        for neighbor in self.neighbors:
            quality_map = np.where((quality_map > neighbor.FoV), quality_map, 0)

        self.coverage_quality = np.sum(quality_map*np.transpose(self.global_event))
        self.local_voronoi = np.array(np.where((quality_map != 0) & (self.FoV != 0))) #np.where(self.FoV != 0)
        self.local_voronoi_map = np.where(((quality_map > 0.) & (self.FoV > 0.)), quality_map, 0)
        self.overlap = np.array(np.where((quality_map == 0) & (self.FoV != 0)))
        self.map_plt = np.array(np.where(quality_map != 0, self.id + 1, 0))

        return

    def UpdateRole(self):

        self.role = "Interceptor"

        for target in self.targets:
            pos = (np.asarray(target[0])/self.grid_size).astype(np.int64)

            if self.local_voronoi_map[pos[1]-1, pos[0]-1] > 0:
                self.role = "Tracker"
        # if self.coverage_quality >= self.intercept_quality:
        #     self.role = "Tracker"

        print(self.id, "=>", self.role, "=>", self.intercept_quality, "=>", self.coverage_quality)

        return

    def ComputeLocalCentroidal(self):

        rotational_force = np.array([0.,0.]).reshape(2,1)
        zoom_force = 0

        if len(self.local_voronoi[0]) > 0:
            mu_V = 0
            v_V_t = np.array([0, 0], dtype=np.float64)
            delta_V_t = 0

            # Control law for maximizing local resolution and perspective quality
            for i in range(len(self.local_voronoi[0])):
                x_map = self.local_voronoi[1][i]
                y_map = self.local_voronoi[0][i]

                x, y = x_map*self.grid_size[0], y_map*self.grid_size[1]
                x_p = np.array([x,y]) - self.pos
                norm = self.Norm(x_p)

                if norm == 0: continue

                mu_V += ((norm**self.lamb)*self.global_event[x_map,y_map] )/(self.R**self.lamb)
                v_V_t += ((x_p)/norm)*(cos(self.alpha) - \
                                ( ( self.lamb*norm )/((self.lamb+1)*self.R)))*\
                                    ( (norm**self.lamb)/(self.R**self.lamb) )*self.global_event[x_map,y_map]
                dist = (1 - (self.lamb*norm)/((self.lamb+1)*self.R))
                dist = dist if dist >= 0 else 0
                delta_V_t += (1 - (((x_p)@self.perspective.T))/norm)\
                                *dist*((norm**self.lamb)/(self.R**self.lamb))\
                                    *self.global_event[x_map,y_map]

            v_V = v_V_t/mu_V
            delta_V = delta_V_t/mu_V
            delta_V = delta_V if delta_V > 0 else 1e-10
            alpha_v = acos(1-sqrt(delta_V))
            alpha_v = alpha_v if alpha_v > 5/180*np.pi else 5/180*np.pi

            rotational_force += self.Kv*(np.eye(2) - np.dot(self.perspective[:,None],\
                                            self.perspective[None,:]))  @  (v_V.reshape(2,1))
            zoom_force -= self.Ka*(self.alpha - alpha_v)

        self.perspective_force = np.asarray([rotational_force[0][0], rotational_force[1][0]])
        self.zoom_force = zoom_force

        return

    def ComputePerspectiveQuality(self, x, y):

        x_p = np.array([x,y], dtype=object) - self.pos

        return (np.matmul(x_p,self.perspective.transpose())/np.linalg.norm(x_p)
            - np.cos(self.alpha))/(1 - np.cos(self.alpha))

    def ComputeResolutionQuality(self, x, y):

        x_p = np.array([x, y], dtype=object) - self.pos

        return (((np.linalg.norm(x_p)**self.lamb)*(self.R*np.cos(self.alpha)
            - self.lamb*( np.linalg.norm(x_p) - self.R*np.cos(self.alpha)) ))
                / (self.R**(self.lamb+1)))

    def ComputeInterceptionQuality(self, x, y):
        x_p = np.linalg.norm(np.array([x, y], dtype=object) - self.pos)
        quality = np.exp(-x_p**2/(2*self.sigma**2))*np.sign(1 - x_p)

        return quality

    def ComputeEventDensity(self, targets):

        x = np.arange(self.global_event.shape[0])*self.grid_size[0]
        event = np.zeros(self.global_event.shape)
        for y_map in range(0, self.global_event.shape[1]):
            y = y_map*self.grid_size[1]
            density = 0
            for i in range(len(targets)):
                density += targets[i][2]*np.exp(-targets[i][1]*np.linalg.norm(np.array([x,y], dtype=object)\
                                -np.array((targets[i][0][1],targets[i][0][0]))))
            event[:][y_map] = density

        return 0 + event

    def ComputeMaxCapacity(self): # Not Finished
        return

    def PublishInfo(self):
        pass

    def Norm(self, arr):

        sum = 0

        for i in range(len(arr)):
            sum += arr[i]**2

        return sqrt(sum)

    # self.positional_force[0] = np.sign((cos(self.alpha)/(self.R**self.lamb))*(self.pos[0] - centroid[0]*self.grid_size[0])\
    #                             * self.Norm(self.pos - centroid)**(self.lamb-2)*(self.lamb**2 - self.lamb)\
    #                             - (self.lamb/(self.R**(self.lamb+1)))*((self.lamb-1)*(self.pos[0] - centroid[0]*self.grid_size[0])\
    #                                 * self.Norm(self.pos-centroid*self.grid_size)**(self.lamb-3)))

    # self.positional_force[1] = np.sign((cos(self.alpha)/(self.R**self.lamb))*(self.pos[1] - centroid[1]*self.grid_size[0])\
    #                             * self.Norm(self.pos - centroid)**(self.lamb-2)*(self.lamb**2 - self.lamb)\
    #                             - (self.lamb/(self.R**(self.lamb+1)))*((self.lamb-1)*(self.pos[1] - centroid[1]*self.grid_size[0])\
    #                                 * self.Norm(self.pos-centroid*self.grid_size)**(self.lamb-3)))


class Malzeme:
    def __init__(self, ad, stok_miktarı, son_bakım_tarihi):
        # Malzeme özelliklerini tanımlayan constructor
        self.ad = ad  # Malzeme adı
        self.stok_miktarı = stok_miktarı  # Malzeme stok miktarı
        self.son_bakım_tarihi = son_bakım_tarihi  # Malzeme son bakım tarihi

    def stok_kontrol(self):
        # Stok miktarını kontrol eder ve duruma göre uyarı verir.
        if self.stok_miktarı <= 0:
            print(f"{self.ad} malzemesinin stok miktarı tükenmiştir. Yeniden sipariş verilmelidir.")
        elif self.stok_miktarı < 10:
            print(f"{self.ad} malzemesinin stok miktarı azalmıştır. Yeniden sipariş verilmesi gerekebilir.")
        else:
            print(f"{self.ad} malzemesinin stok miktarı normal seviyededir.")

    def bakım_kontrol(self):
        # Son bakım tarihini kontrol eder ve gerekirse bakım uyarısı verir.
        if self.son_bakım_tarihi < "2023-01-01":
            print(f"{self.ad} malzemesinin son bakım tarihi geçmiştir. Bakım yapılmalıdır.")
        else:
            print(f"{self.ad} malzemesinin bakımı güncel.")

def main():
    malzeme_listesi = []
#Malzeme bilgisi ekleme ve kodun devam edip etmediğini anlayan şart ifadesi vardır.
    while True:
        print("\nMalzeme Bilgisi Ekle")
        ad = input("Malzeme Adı: ")
        stok_miktarı = int(input("Stok Miktarı: "))
        son_bakım_tarihi = input("Son Bakım Tarihi (YYYY-MM-DD): ")

        malzeme = Malzeme(ad, stok_miktarı, son_bakım_tarihi)
        malzeme_listesi.append(malzeme)

        devam_et = input("Başka malzeme eklemek ister misiniz? (E/H): ")
        if devam_et.lower() != "e":
            break

    print("\nMalzeme Bilgileri ve Kontrolleri")
    for malzeme in malzeme_listesi:
        print(f"Malzeme Adı: {malzeme.ad}")
        malzeme.stok_kontrol()
        malzeme.bakım_kontrol()
#Kodu çalıştırır.
if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This collection is used to execute commands for spatialMOS."""

import os
import logging
import json
from pathlib import Path
from datetime import datetime, timedelta
import requests
from invoke import task
from . import inv_logging
from . import inv_docker
from . import inv_node
from . import inv_rsync
from . import util

def archive_folder(c, folder):
    """The *.tar.gz are created with tar. The folder must be specified e.g. zamg."""
    inv_logging.task(archive_folder.__name__)
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "archive_folder",
        "--folder",
        folder,
    ]
    inv_docker.run_py_container(c, cmd)

@task
def archive_folder__gefs_avgspr_forecast_p05(c):
    """created a tar file from the folder gefs_avgspr_forecast_p05"""
    archive_folder(c, "gefs_avgspr_forecast_p05")
    util.write_statusfile_and_success_logging(
        archive_folder__gefs_avgspr_forecast_p05.__name__
    )

@task
def archive_folder__lwd(c):
    """created a tar file from the folder lwd"""
    archive_folder(c, "lwd")
    util.write_statusfile_and_success_logging(archive_folder__lwd.__name__)

@task
def archive_folder__measurements(c):
    """created a tar file from the folder measurements"""
    archive_folder(c, "measurements")
    inv_logging.success(archive_folder__measurements.__name__)

@task
def archive_folder__suedtirol(c):
    """created a tar file from the folder suedtirol"""
    archive_folder(c, "suedtirol")
    inv_logging.success(archive_folder__suedtirol.__name__)

@task
def archive_folder__zamg(c):
    """created a tar file from the folder lwd"""
    archive_folder(c, "zamg")
    util.write_statusfile_and_success_logging(archive_folder__zamg.__name__)

@task
def combine_gamlss_climatology(c, parameter):
    """Combine climatologies for spatialmos"""
    inv_logging.task(combine_gamlss_climatology.__name__)
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "combine_gamlss_climatology",
        "--parameter",
        parameter,
    ]
    inv_docker.run_py_container(c, cmd)

@task
def combine_data(c, folder):
    """Combine downloaded data for a folder."""
    inv_logging.task(combine_data.__name__)
    cmd = ["python", "./run_script.py", "--script", "combine_data", "--folder", folder]
    inv_docker.run_py_container(c, cmd)

@task
def combine_measurements(c):
    """Combine measurements in the ./data/measurements folder."""
    inv_logging.task(combine_measurements.__name__)
    cmd = ["python", "./run_script.py", "--script", "combine_measurements"]
    inv_docker.run_py_container(c, cmd)

@task
def combine_predictions__tmp_2m(c):
    """combine tmp_2m predictions"""
    inv_logging.task(combine_predictions__tmp_2m.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "combine_predictions",
        "--date",
        date,
        "--parameter",
        "tmp_2m",
    ]
    inv_docker.run_py_container(c, cmd)
    util.write_statusfile_and_success_logging(combine_predictions__tmp_2m.__name__)

@task
def combine_predictions__rh_2m(c):
    """combine rh_2m predictions"""
    inv_logging.task(combine_predictions__rh_2m.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "combine_predictions",
        "--date",
        date,
        "--parameter",
        "rh_2m",
    ]
    inv_docker.run_py_container(c, cmd)
    util.write_statusfile_and_success_logging(combine_predictions__rh_2m.__name__)

@task
def deploy(c):
    """Everything you need to deploy"""
    inv_logging.task(deploy.__name__)
    util.check_upstream(c)
    inv_node.build(c)
    inv_rsync.push(c, "sourcefiles")
    inv_rsync.push(c, "staticfiles")
    inv_logging.success(deploy.__name__)

@task
def get_gefs(c, date, resolution, modeltype, parameter):
    """Download data gefs files."""
    inv_logging.task(get_gefs.__name__)
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "get_gefs_forecasts",
        "--date",
        date,
        "--resolution",
        resolution,
        "--modeltype",
        modeltype,
        "--parameter",
        parameter,
    ]
    inv_docker.run_py_container(c, cmd)
    inv_logging.success(get_gefs.__name__)

@task
def get_gefs_forecasts__tmp_2m_avg(c):
    """Download forcasts for tmp_2m mean"""
    inv_logging.task(get_gefs_forecasts__tmp_2m_avg.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="avg", parameter="tmp_2m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__tmp_2m_avg.__name__)

@task
def get_gefs_forecasts__tmp_2m_spr(c):
    """Download forcasts for tmp_2m spread"""
    inv_logging.task(get_gefs_forecasts__tmp_2m_spr.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="spr", parameter="tmp_2m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__tmp_2m_spr.__name__)

@task
def get_gefs_forecasts__rh_2m_avg(c):
    """Download forcasts for rh_2m mean"""
    inv_logging.task(get_gefs_forecasts__rh_2m_avg.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="avg", parameter="rh_2m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__rh_2m_avg.__name__)

@task
def get_gefs_forecasts__rh_2m_spr(c):
    """Download forcasts for rh_2m spread"""
    inv_logging.task(get_gefs_forecasts__rh_2m_spr.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="spr", parameter="rh_2m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__rh_2m_spr.__name__)

@task
def get_gefs_forecasts__ugrd_10m_avg(c):
    """Download forcasts for ugrd_10 mean"""
    inv_logging.task(get_gefs_forecasts__ugrd_10m_avg.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="avg", parameter="ugrd_10m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__ugrd_10m_avg.__name__)

@task
def get_gefs_forecasts__ugrd_10m_spr(c):
    """Download forcasts for ugrd_10 spread"""
    inv_logging.task(get_gefs_forecasts__ugrd_10m_spr.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="spr", parameter="ugrd_10m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__ugrd_10m_spr.__name__)

@task
def get_gefs_forecasts__vgrd_10m_avg(c):
    """Download forcasts for wind_10m mean"""
    inv_logging.task(get_gefs_forecasts__vgrd_10m_avg.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="avg", parameter="vgrd_10m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__vgrd_10m_avg.__name__)

@task
def get_gefs_forecasts__vgrd_10m_spr(c):
    """Download forcasts for wind_10m spread"""
    inv_logging.task(get_gefs_forecasts__vgrd_10m_spr.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    get_gefs(c, date=date, resolution="0.5", modeltype="spr", parameter="vgrd_10m")
    util.write_statusfile_and_success_logging(get_gefs_forecasts__vgrd_10m_spr.__name__)

@task
def pre_processing_gribfiles__tmp_2m(c):
    """combine tmp_2m gribfiles for predictions"""
    inv_logging.task(pre_processing_gribfiles__tmp_2m.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    pre_processing_gribfiles(c, date=date, resolution="0.5", parameter="tmp_2m")
    util.write_statusfile_and_success_logging(pre_processing_gribfiles__tmp_2m.__name__)

@task
def pre_processing_gribfiles__rh_2m(c):
    """combine rh_2m gribfiles for predictions"""
    inv_logging.task(pre_processing_gribfiles__rh_2m.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    pre_processing_gribfiles(c, date=date, resolution="0.5", parameter="rh_2m")
    util.write_statusfile_and_success_logging(pre_processing_gribfiles__rh_2m.__name__)

@task
def pre_processing_gribfiles__ugrd_10m(c):
    """combine ugrd_10m gribfiles for predictions"""
    inv_logging.task(pre_processing_gribfiles__ugrd_10m.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    pre_processing_gribfiles(c, date=date, resolution="0.5", parameter="ugrd_10m")
    util.write_statusfile_and_success_logging(
        pre_processing_gribfiles__ugrd_10m.__name__
    )

@task
def pre_processing_gribfiles__vgrd_10m(c):
    """combine ugrd_10m gribfiles for predictions"""
    inv_logging.task(pre_processing_gribfiles__vgrd_10m.__name__)
    date = datetime.now().strftime("%Y-%m-%d")
    pre_processing_gribfiles(c, date=date, resolution="0.5", parameter="vgrd_10m")
    util.write_statusfile_and_success_logging(
        pre_processing_gribfiles__vgrd_10m.__name__
    )

@task
def pre_processing_gamlss_crch_climatologies(c, parameter):
    """Create climatologies for further processing in R with gamlss."""
    inv_logging.task(pre_processing_gamlss_crch_climatologies.__name__)
    cmd = [
        "python",
        "./spatialmos/pre_processing_gamlss_crch_climatologies.py",
        "--parameter",
        parameter,
    ]
    inv_docker.run_py_container(c, cmd)
    inv_logging.success(pre_processing_gamlss_crch_climatologies.__name__)

@task
def pre_processing_gribfiles(c, date, resolution, parameter):
    """Create the csv file and the jsonfile from the available gribfiles."""
    inv_logging.task(pre_processing_gribfiles.__name__)
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "pre_processing_prediction",
        "--date",
        date,
        "--resolution",
        resolution,
        "--parameter",
        parameter,
    ]
    inv_docker.run_py_container(c, cmd)
    inv_logging.success(pre_processing_gribfiles.__name__)

@task
def prediction__rh_2m(c):
    """Create the predictions and the spatialMOS plots for rh_2m."""
    inv_logging.task(prediction__rh_2m.__name__)
    c.run("rm -rf ./data/media/rh_2m/*")
    date = datetime.now().strftime("%Y-%m-%d")
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "prediction",
        "--date",
        date,
        "--resolution",
        "0.5",
        "--parameter",
        "rh_2m",
    ]
    inv_docker.run_py_container(c, cmd)
    util.write_statusfile_and_success_logging(prediction__rh_2m.__name__)

@task
def prediction__tmp_2m(c):
    """Create the predictions and the spatialMOS plots for tmp_2m."""
    inv_logging.task(prediction__tmp_2m.__name__)
    c.run("rm -rf ./data/media/tmp_2m/*")
    date = datetime.now().strftime("%Y-%m-%d")
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "prediction",
        "--date",
        date,
        "--resolution",
        "0.5",
        "--parameter",
        "tmp_2m",
    ]
    inv_docker.run_py_container(c, cmd)
    util.write_statusfile_and_success_logging(prediction__tmp_2m.__name__)

@task
def get_suedtirol(c, begindate, enddate):
    """Download data from South Tyrol."""
    inv_logging.task(get_suedtirol.__name__)
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "get_suedtirol_data",
        "--begindate",
        begindate,
        "--enddate",
        enddate,
    ]
    inv_docker.run_py_container(c, cmd)
    util.write_statusfile_and_success_logging(get_suedtirol.__name__)

@task
def get_lwd(c):
    """Download data from lwd tirol"""
    inv_logging.task(get_lwd.__name__)
    cmd = ["python", "./run_script.py", "--script", "get_lwd_data"]
    inv_docker.run_py_container(c, cmd)
    util.write_statusfile_and_success_logging(get_lwd.__name__)

@task
def get_zamg(c):
    """Download data from zamg webpage."""
    inv_logging.task(get_zamg.__name__)
    cmd = ["python", "./run_script.py", "--script", "get_zamg_data"]
    inv_docker.run_py_container(c, cmd)
    util.write_statusfile_and_success_logging(get_zamg.__name__)

@task
def init_topography(c):
    """Create shapefiles for spatialMOS"""
    inv_logging.task(init_topography.__name__)
    cmd = ["Rscript", "./r_spatialmos/init_shapefiles.R"]
    inv_docker.run_r_base(c, cmd)

    cmd = ["python", "./run_script.py", "--script", "pre_processing_topography"]
    inv_docker.run_py_container(c, cmd)

    # Download Shapefile and unzip it
    if not os.path.exists("./data/get_available_data/gadm/gadm36_AUT_shp"):
        req_gadm36_zip_file = (
            "https://biogeo.ucdavis.edu/data/gadm3.6/shp/gadm36_AUT_shp.zip"
        )
        gadm36_zip_file = "./data/get_available_data/gadm/gadm36_AUT_shp.zip"
        req_shapefile = requests.get(req_gadm36_zip_file, stream=True)
        if req_shapefile.status_code == 200:
            with open(gadm36_zip_file, mode="wb") as f:
                for chunk in req_shapefile.iter_content(chunk_size=128):
                    f.write(chunk)
            logging.info("The shapefile '%s' has been downloaded.", req_gadm36_zip_file)
            c.run(
                f"unzip {gadm36_zip_file} -d ./data/get_available_data/gadm/gadm36_AUT_shp"
            )
        else:
            raise RuntimeError(
                f"There was a problem with the download of the shapefile '{req_gadm36_zip_file}'"
            )

    inv_logging.success(init_topography.__name__)

@task
def install(c):
    """A task for quick installation of spatialMOS"""
    inv_logging.task(install.__name__)
    util.create_folders(c)
    inv_docker.rebuild(c)
    inv_node.yarn(c, "")
    inv_node.build(c)
    inv_logging.success(install.__name__)

@task
def interpolate_gribfiles(c, parameter):
    """GEFS Reforecasts are bilinear interpolated at station locations."""
    inv_logging.task(interpolate_gribfiles.__name__)
    cmd = [
        "python",
        "./run_script.py",
        "--script",
        "interpolate_gribfiles",
        "--parameter",
        parameter,
    ]
    inv_docker.run_py_container(c, cmd)
    inv_logging.success(interpolate_gribfiles.__name__)

@task
def merge_statusfiles(c):  # pylint: disable=W0613
    """Merge statusfiles"""
    statusfiles_path = Path("./data/spool/statusfiles/")
    statusfiles = []
    for file in sorted(statusfiles_path.glob("*.json")):
        logging.info("The file %s will be added to the systemstatus file.", file)
        with (open(file, mode="r", encoding="UTF-8")) as f:
            status = json.load(f)
            status["failed"] = datetime.now() > datetime.strptime(
                status["taskMaxAgeTime"], "%Y-%m-%dT%H:%M:%S"
            )
        statusfiles.append(status)

    settings = util.read_settings()
    systemchecks_done = sorted([c["taskName"] for c in statusfiles])
    systemchecks_available = [
        check
        for check in sorted(settings["systemChecks"].keys())
        if check != merge_statusfiles.__name__
    ]
    systemchecks_missing = [
        check for check in systemchecks_available if check not in systemchecks_done
    ]

    if len(systemchecks_missing) == 0:
        status_complete = True
        logging.info("All available checks from the 'settings.json' file are checked.")
    else:
        status_complete = False
        for check in systemchecks_missing:
            logging.error("The check '%s' is missing", check)

    status = {
        "taskName": merge_statusfiles.__name__,
        "taskFinishedTime": datetime.now().strftime("%Y-%m-%dT%H:%M:%S"),
        "taskMaxAgeTime": (
            datetime.now()
            + timedelta(
                minutes=int(settings["systemChecks"][merge_statusfiles.__name__])
            )
        ).strftime("%Y-%m-%dT%H:%M:%S"),
        "maxAge": int(settings["systemChecks"][merge_statusfiles.__name__]),
        "complete": status_complete,
        "failed": False,
    }
    statusfiles.append(status)
    statusfiles = sorted(statusfiles, key=lambda x: x["taskName"], reverse=False)

    merge_statusfile = Path("./data/media/systemstatus.json")
    with open(merge_statusfile, "w", encoding="utf-8") as f:
        json.dump(statusfiles, f)
    logging.info("The merged status file %s has been written.", merge_statusfile)
    inv_logging.success(merge_statusfiles.__name__)

@task
def r_gamlss_crch_model(c, validation, parameter):
    """Create the required spatial climatologies."""
    inv_logging.task(r_gamlss_crch_model.__name__)
    cmd = [
        "Rscript",
        "./r_spatialmos/gamlss_crch_model.R",
        "--validation",
        validation,
        "--parameter",
        parameter,
    ]
    inv_docker.run_r_base(c, cmd)
    inv_logging.success(r_gamlss_crch_model.__name__)

@task
def r_spatial_climatologies_nwp(c, begin, end, parameter):
    """Create daily climatologies for the NWP."""
    inv_logging.task(r_spatial_climatologies_nwp.__name__)
    cmd = [
        "Rscript",
        "./r_spatialmos/spatial_climatologies_nwp.R",
        "--begin",
        begin,
        "--end",
        end,
        "--parameter",
        parameter,
    ]
    inv_docker.run_r_base(c, cmd)
    inv_logging.success(r_spatial_climatologies_nwp.__name__)

@task
def r_spatial_climatologies_obs(c, begin, end, parameter):
    """Create daily climatologies for the observations."""
    inv_logging.task(r_spatial_climatologies_obs.__name__)
    cmd = [
        "Rscript",
        "./r_spatialmos/spatial_climatologies_observations.R",
        "--begin",
        begin,
        "--end",
        end,
        "--parameter",
        parameter,
    ]
    inv_docker.run_r_base(c, cmd)
    inv_logging.success(r_spatial_climatologies_obs.__name__)

@task
def remove_old_climatologies(c):  # pylint: disable=W0613
    """Climatologies older than 3 days are deleted"""
    inv_logging.task(remove_old_climatologies.__name__)
    days = range(1, datetime.now().timetuple().tm_yday - 2)
    folders = [
        "./data/spatialmos_climatology/gam/rh_2m/climate_spatialmos",
        "./data/spatialmos_climatology/gam/rh_2m/climate_spatialmos_nwp",
        "./data/spatialmos_climatology/gam/tmp_2m/climate_spatialmos",
        "./data/spatialmos_climatology/gam/tmp_2m/climate_spatialmos_nwp",
    ]
    for folder in folders:
        for day in days:
            for file in Path(folder).glob(f"yday_{day:03d}*.csv"):
                logging.info("File '%s' will be removed", file)
                os.unlink(file)
    util.write_statusfile_and_success_logging(remove_old_climatologies.__name__)

@task
def untar_folder(c, folder):
    """The *.tar.gz untared with tar. The fileprefix must be specified e.g. zamg."""
    inv_logging.task(untar_folder.__name__)
    cmd = ["python", "./run_script.py", "--script", "untar_folder", "--folder", folder]
    inv_docker.run_py_container(c, cmd)
    inv_logging.success(untar_folder.__name__)


import json

def rw_json():
    # create data
    data = {
        'name': 'ACME',
        'shares': 100,
        'price': 542.23
    }

    # print json.dumps
    print ( json.dumps(data) )
    print ( json.dumps(data, indent=4) )

    # write json file using json.dumpS
        # get data
    json_str = json.dumps( data )
    print ( json_str )
        # write data into json file using json.dump
    with open( 'data.json', 'w', encoding='utf-8' ) as wf:
        json.dump( data, wf )
        # read data from file
    with open( 'data.json', 'r', encoding='utf-8' ) as rf:
        rData = json.load(rf)
        print ( rData )

if __name__ == '__main__':
    rw_json()


from zendesk import ZendeskClient
import csv
import attributes
import json
import time

def map_agent_skills():
    attribute_values = attributes.get_attribute_values()
    mapping = []
    with open('agent_product_mapping.csv') as f:
        rows = csv.reader(f)
        next(rows)
        for row in rows:
            mapping.append(
                {
                    "id":int(row[0]),
                    "name":row[1],
                    "email":row[2],
                    "skills":[attributes.get_attribute_value_id(attribute_values,skill) for skill in row[3].split(',')]
                }
            )
    json.dump(mapping, open("mapping.json","w+"))

def create_skills():
    map_agent_skills()
    mapping = json.load(open("mapping.json"))
    zd = ZendeskClient()
    errors=[]
    for agent in mapping:
        payload = {"attribute_value_ids":[skill['id'] for skill in agent['skills']]}
        result = zd.post(f'/routing/agents/{agent["id"]}/instance_values.json',json = payload)
        if result.status_code != 200:
            errors.append(agent)
        print(agent['name'],result)
    json.dump(errors, open("errors.json","w+"))

if __name__ == "__main__":
    create_skills()


#!/usr/bin/env python

import rospy
from nav_msgs.msg import Odometry
from tf.transformations import euler_from_quaternion

class DumpOdom:

  def __init__(self):

    # Node subscribers
    self.sub = rospy.Subscriber('odom', Odometry, self.odomCb)

  def odomCb(self, msg):
    quat = msg.pose.pose.orientation
    orientation_list = [quat.x, quat.y, quat.z, quat.w]
    (roll, pitch, yaw) = euler_from_quaternion (orientation_list)

    print(str(rospy.get_time()) + '\t' +
        #str(rospy.Time.now()) + '\t' +
        str(msg.pose.pose.position.x) + '\t' +
        str(msg.pose.pose.position.y) + '\t' + str(yaw) + '\t' +
        str(msg.twist.twist.linear.x) + '\t' +
        str(msg.twist.twist.angular.z))

if __name__ == '__main__':
  rospy.init_node('dump_odom')
  do = DumpOdom()
  rospy.spin()


import os
import json
import time
import requests
import operator
import traceback
from functools import reduce

###################################################
# tg_key = '1683239661:AAFcEH4HMuUj1pI4KnJleRZ9tt3gkv8kttU'
m = []
n = []

###################################################

if "TG_KEY" in os.environ:
    tg_key = os.environ["TG_KEY"]

if not tg_key:
    print(f'''【通知参数】 is empty,DTask is over.''')
    exit()

###################################################

# 处理数据
def getCode(tg_key):
    global d
    url = f'https://api.telegram.org/bot{tg_key}/getUpdates'
    try:
        resp = requests.get(url).json()
        # print(resp)
        for i in resp['result']:
            if not (i['message']['text'].rfind('/jdfruit')):
                try:
                    with open('jdfruit_code.txt', 'a+') as f:
                        f.write(i['message']['text'].split(' ')[1])
                        f.write('\n')
                except IndexError:
                    pass
                continue

        time.sleep(10)
        with open('jdfruit_code.txt') as f:
            for line1 in f.readlines():
                line1 = line1.replace('\n', '')
                m.append(line1)
            for line2 in m:
                line2 = line2.split('&')
                n.append(line2)
        d = list(set(reduce(operator.add, n)))
        loadCode(d)

    except:
        print(traceback.format_exc())
        return

# 上传数据
def loadCode(d):
    # data = func()
    for line in d:
        with open('fruit.txt','a') as f:
            f.write(line + '\n')

def run():
    getCode(tg_key)

if __name__ == '__main__':
    run()


#!/usr/bin/env python
# This little transformation makes the dataset a lot smaller
# but the classifier still takes absolute ages to fit it.

from pyblique import get_data
from sklearn.decomposition import PCA
import numpy as np

# Shrink the isolet dataset by means of PCA.
# 600+ attributes -> 10 attributes
isolet = get_data("Data/isolet.data")
pca = PCA(n_components=10)
transformed = pca.fit_transform(isolet[:, :-1])
labels = isolet[:, -1]
labels = np.reshape(labels, (labels.shape[0], 1))
result = np.concatenate((transformed, labels), axis=1)
np.savetxt("Data/isolet_compressed.data", result, delimiter=",")


#!/usr/bin/env python3

import numpy as np
import rospy
import tf

from core.interfaces import ObjectDetector

# Broadcasts T as the transform from from_frame to to_frame
def show_pose(T,frame_from,frame_to):
    tf_broad.sendTransform(
        tf.transformations.translation_from_matrix(T),
        tf.transformations.quaternion_from_matrix(T),
        rospy.Time.now(),
        frame_from,
        frame_to
    )

if __name__ == "__main__":

    np.set_printoptions(precision=4,suppress=True)

    rospy.init_node("detector_test")
    tf_broad  = tf.TransformBroadcaster()

    detector = ObjectDetector()

    r = rospy.Rate(10) # Hz
    while not rospy.is_shutdown():
        r.sleep()
        detections = detector.get_detections()
        print(len(detections),'tags detected')

        detections.sort(key=lambda y: y[0])
        mult = {}
        for tag in detections:
            (name, pose) = tag
            if name in mult:
                mult[name].append(pose)
            else:
                mult[name] = [pose]
        for (name, Ts) in mult.items():
            for i, T in enumerate(Ts):
                frame = name+"_"+str(i)
                show_pose(T,frame,'camera')


import random, math, decimal
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
from reportlab.lib.styles import ParagraphStyle
from reportlab.lib.colors import black, getAllNamedColors
from reportlab.lib.enums import TA_LEFT
from reportlab.platypus import Paragraph

dimensions = {"stack_width": 3.15 * cm, "label_width": 3.15 * cm, "margin": 0.21 * cm, "red_line_width": 0.1575 * cm,
              "red_line_skip": 0.105 * cm, "label_skip": 0.21 * cm, "scale_skip": 0.21 * cm, "legend_skip": 0.21 * cm,
              "scale_label_skip": 0.21 * cm}
"""Dictionary with all skips and lengths that can be changed even at runtime.

    - ``stack_width``: the width of the stack diagram without any labels
    - ``label_width``: the width of the labels at both sides of the stack
    - ``margin``: the margin at a for edges around the whole diagram, excluding a
        possible red rim
    - ``red_line_width``: the width of the red rim
    - ``red_line_skip``: the distance between the red rim and the border of the PDF
    - ``label_skip``: the distance of the labels and the stack
    - ``scale_skip``: the vertical distance between the scale and the stack below
    - ``legend_skip``: the vertical distance between the legend and the stack above
    - ``scale_label_skip``: the distance between the scale bar and the scale label
"""
parameters = {"roughness": 3.15, "grid_points": 24}
"""Dictionary with further parameters that can be changed even at runtime.

    - ``roughness``: the roughness of the textured lines in bp
    - ``grid_points``: number of grid points used for the textured line
"""

single_label_style = ParagraphStyle("label", fontName="DejaVu", bulletFontName="DejaVu", fontSize=10.5)
legend_label_style = ParagraphStyle("label", fontName="DejaVu", bulletFontName="DejaVu",
                                    leftIndent=15.3, firstLineIndent=-15.3, spaceAfter=10.5, fontSize=10.5)

lineskip = single_label_style.leading
line_height = single_label_style.fontSize

def get_circled_number(number, largest_number):
    """Converts a number to a string using the nicest way possible.  If only
    numbers ≤ 10 occur in the diagram, the circled unicode numbers like “➉” are
    used.  Otherwise, a layout like “(10)” is used as a fallback.

    :param number: the number to be converted
    :param largest_number: the largest number which occurs in the diagram

    :type number: int
    :type largest_number: int

    :return:
      a nice-looking string representation of the number

    :rtype: str
    """
    if largest_number > 10:
        return "({0})".format(number)
    else:
        return "➀➁➂➃➄➅➆➇➈➉"[number - 1]

class Path:
    """Helper class for drawing the layer stack.  It is used in a late stage
    of drawing the diagram, when the PDF canvas is already prepared.  It helps
    to draw the outline of a single layer consisting of basic shapes like
    vertical lines or textured horizontal lines.  This way, the caller has
    complete flexibility, which is needed because the properties of a layer
    (structured, textured, collapsed) can be arbitrarily combinated.

    :ivar textured_points: the grid points for the textured line; it consists
      of (x, y) pairs of coordinates.  The y coordinate oscillates around zero.

    :ivar edge_indices: The indices within `textured_points` of the places
      where the vertical edges of the layer join the horizonal edges.  This is
      needed for structured layers: Here, we have two columns the horizontal
      edges of which lie somewhere in the middle of the layer.  This list
      consists of four elements, namely the left and right index of the left
      column, and the left and right index of the right column.

    :ivar voffset: The vertical coordinate of the lower edge of the layer.
      ``voffset`` + ``height`` = ``accumulated_height``.

    :type textured_points: list of (float, float)
    :type edge_indices: list of int
    :type voffset: float
    """

    def __init__(self, canvas, segment, height, accumulated_height, textured, bottom_layer, fill_color=None):
        """
        :param canvas: the PDF canvas object
        :param segment: The layer segment to be drawn.  It may be ``"whole"``,
            ``"left"``, or ``"right"``.  The latter two are used for structured
            samples to draw the two columns they consist of.
        :param height: height of the layer
        :param accumulated_height: height of the layer measured from the very
            bottom of the stack
        :param textured: whether the layer is textured
        :param bottom_layer: the next non-structured layer below the current one
        :param fill_color: the color of the filling; if not given, just the outline
            is drawn

        :type canvas: canvas.Canvas
        :type segment: str
        :type height: float
        :type accumulated_height: float
        :type textured: bool
        :type bottom_layer: `Layer`
        :type fill_color: str
        """
        self.canvas, self.segment, self.height, self.accumulated_height, self.fill_color = \
            canvas, segment, height, accumulated_height, fill_color

        random.seed(1)
        self.textured_points = [(dimensions["stack_width"] / parameters["grid_points"] * i,
                                 random.uniform(-parameters["roughness"], parameters["roughness"]))
                                for i in range(parameters["grid_points"] + 1)]
        self.edge_indices = [int(round(x * parameters["grid_points"])) for x in [1/8, 3/8, 5/8, 7/8]]

        self.voffset = 0 if fill_color or not bottom_layer else bottom_layer.accumulated_height
        bottom_textured = bottom_layer and bottom_layer.textured
        self.p = canvas.beginPath()
        if segment == "whole":
            self.bottom_left = (0,
                                0 if fill_color else self.voffset + (self.textured_points[0][1] if bottom_textured else 0))
            self.top_left = (self.bottom_left[0], (self.textured_points[0][1] if textured else 0) + accumulated_height)
            self.bottom_right = (dimensions["stack_width"],
                                 0 if fill_color else self.voffset + (self.textured_points[-1][1] if bottom_textured else 0))
            self.top_right = (self.bottom_right[0], (self.textured_points[-1][1] if textured else 0) + accumulated_height)
        elif segment == "left":
            self.bottom_left = (self.textured_points[self.edge_indices[0]][0], 0 if fill_color else
                                self.voffset + (self.textured_points[self.edge_indices[0]][1] if bottom_textured else 0))
            self.top_left = (self.bottom_left[0],
                             (self.textured_points[self.edge_indices[0]][1] if textured else 0) + accumulated_height)
            self.bottom_right = (self.textured_points[self.edge_indices[1]][0], 0 if fill_color else
                                 self.voffset + (self.textured_points[self.edge_indices[1]][1] if bottom_textured else 0))
            self.top_right = (self.bottom_right[0],
                              (self.textured_points[self.edge_indices[1]][1] if textured else 0) + accumulated_height)
        else:
            self.bottom_left = (self.textured_points[self.edge_indices[2]][0], 0 if fill_color else
                                self.voffset + (self.textured_points[self.edge_indices[2]][1] if bottom_textured else 0))
            self.top_left = (self.bottom_left[0],
                             (self.textured_points[self.edge_indices[2]][1] if textured else 0) + accumulated_height)
            self.bottom_right = (self.textured_points[self.edge_indices[3]][0], 0 if fill_color else
                                 self.voffset + (self.textured_points[self.edge_indices[3]][1] if bottom_textured else 0))
            self.top_right = (self.bottom_right[0],
                              (self.textured_points[self.edge_indices[3]][1] if textured else 0) + accumulated_height)
        self.p.moveTo(*self.bottom_left)

    def draw_vertical_line(self, direction):
        """Draws a vertical line of the layer (segment).

        :param direction: the direction the line should be drawn; may be
            ``"up"`` or ``"down"``

        :type direction: str
        """
        if direction == "up":
            self.p.lineTo(*self.top_left)
        else:
            self.p.lineTo(*self.bottom_right)

    def draw_horizontal_line(self, direction):
        """Draws a straight horizontal line of the layer (segment).

        :param direction: the direction the line should be drawn; may be
            ``"right"`` or ``"left"``

        :type direction: str
        """
        if direction == "right":
            self.p.lineTo(*self.top_right)
        else:
            self.p.lineTo(*self.bottom_left)

    def draw_textured_line(self, direction):
        """Draws a textured (= jagged) horizontal line of the layer (segment).

        :param direction: the direction the line should be drawn; may be
            ``"right"`` or ``"left"``

        :type direction: str
        """
        if direction == "right":
            if self.segment == "left":
                points = [(x, self.accumulated_height + offset)
                          for x, offset in self.textured_points[self.edge_indices[0] + 1:self.edge_indices[1] + 1]]
            elif self.segment == "right":
                points = [(x, self.accumulated_height + offset)
                          for x, offset in self.textured_points[self.edge_indices[2] + 1:self.edge_indices[3] + 1]]
            else:
                points = [(x, self.accumulated_height + offset) for x, offset in self.textured_points[1:]]
        else:
            if self.segment == "left":
                points = [(x, offset + self.voffset)
                          for x, offset in self.textured_points[self.edge_indices[1] - 1:self.edge_indices[0] - 1:-1]]
            elif self.segment == "right":
                points = [(x, offset + self.voffset)
                          for x, offset in self.textured_points[self.edge_indices[3] - 1:self.edge_indices[2] - 1:-1]]
            else:
                points = [(x, offset + self.voffset) for x, offset in self.textured_points[-2::-1]]
        for x, y in points:
            self.p.lineTo(x, y)

    def draw_collapsed_line(self, direction):
        """Draws an interrupted vertical line of the layer (segment) in order
        to denote a collapsed layer.

        :param direction: the direction the line should be drawn; may be
            ``"up"`` or ``"down"``

        :type direction: str
        """
        gap = 3
        protusion = 3
        mid_edge = self.accumulated_height - self.height / 2
        if direction == "up":
            x = self.top_left[0]
            y = mid_edge - gap / 2
            self.p.lineTo(x, y)
            self.p.moveTo(x + protusion, y + protusion)
            self.p.lineTo(x - protusion, y - protusion)
            self.p.moveTo(x, y)
            y = mid_edge + gap / 2
            self.p.moveTo(x, y)
            self.p.moveTo(x + protusion, y + protusion)
            self.p.lineTo(x - protusion, y - protusion)
            self.p.moveTo(x, y)
            self.p.lineTo(*self.top_left)
        else:
            x = self.bottom_right[0]
            y = mid_edge + gap / 2
            self.p.lineTo(x, y)
            self.p.moveTo(x - protusion, y - protusion)
            self.p.lineTo(x + protusion, y + protusion)
            self.p.moveTo(x, y)
            y = mid_edge - gap / 2
            self.p.moveTo(x, y)
            self.p.moveTo(x - protusion, y - protusion)
            self.p.lineTo(x + protusion, y + protusion)
            self.p.moveTo(x, y)
            self.p.lineTo(*self.bottom_right)

    def draw(self):
        """Actually draws the filled or outlined path on the canvas.
        """
        if self.fill_color:
            self.canvas.setFillColor(getAllNamedColors()[self.fill_color])
            self.canvas.drawPath(self.p, fill=True, stroke=False)
        else:
            self.canvas.drawPath(self.p, fill=False, stroke=True)

class Layer:
    """Class which holds one layer of a stack.

    :ivar name: the name or label of the layer

    :ivar nm: The thickness of the layer in nm.  This should be negative
      (e.g. −1) for mere treatments like an HF dip.

    :ivar color: the color name of the layer; it must be a color name known to
      ReportLab

    :ivar structured: whether the layer is not completely covering but
      structured

    :ivar textured: whether the top surface of the layer is textured by e.g. an
      etching process

    :ivar verified: whether the accuracy of the data of this layer has been
      verified my a human

    :ivar label: the typeset label of the label

    :ivar label_height: the height of the label

    :ivar one_liner: whether the typeset label consists of only a single line

    :ivar collapsed: whether the layer should be displayed collapsed (i.e. with
      broken vertical edges) because it would be too thick otherwise

    :ivar height: the height of the printed layer

    :ivar accumulated_height: the height of the printed layer measured from the
      common baseline at the very bottom of the stack

    :ivar bottom_layer: the next layer below this one which is not structured,
      i.e. covers the whole width; this is the layer the current one grows on;
      if it is ``None``, the current layer “grows” on the very bottom of the
      stack.

    :type name: str
    :type nm: float
    :type color: str
    :type structured: bool
    :type textured: bool
    :type verified: bool
    :type label: Paragraph
    :type label_height: float
    :type one_liner: bool
    :type collapsed: bool
    :type height: float
    :type accumulated_height: float
    :type bottom_layer: `Layer`
    """

    def __init__(self, informal_layer):
        """
        :param informal_layer: the informal layer object from the database

        :type informal_layer: `institute.models.InformalLayer`
        """
        self.nm, self.color, self.structured, self.textured, self.verified, self.collapsed = \
            float(informal_layer.thickness), informal_layer.color, informal_layer.structured, \
            informal_layer.textured, informal_layer.verified, informal_layer.always_collapsed or None
        if informal_layer.classification and informal_layer.doping:
            name = informal_layer.get_doping_display() + "-" + informal_layer.get_classification_display()
        else:
            name = informal_layer.get_classification_display()
        if name:
            if informal_layer.comments:
                name += ", " + informal_layer.comments
        else:
            name = informal_layer.comments
        if informal_layer.thickness_reliable and informal_layer.thickness >= 0:
            name = "{0} ({1})".format(name, self.format_thickness(informal_layer.thickness))
        if not self.verified:
            name = """{0} ??""".format(name)
        self.name = name
        self.label = self.label_height = self.one_liner = self.height = self.accumulated_height = self.bottom_layer = None

    @staticmethod
    def format_thickness(nm):
        """Create a pretty-printed version of the thickness value including a
        unit of measument.

        :param nm: The thickness of the layer in nm.  This should be negative
            (e.g. −1) for mere treatments like an HF dip.  Note that it is not
            a float but a decimal value.

        :type nm: decimal.Decimal

        :return:
          the pretty-printed version of the thickness including the unit

        :rtype: str
        """
        if nm >= decimal.Decimal("1e6"):
            value = nm / decimal.Decimal("1e6")
            unit = "mm"
        elif nm >= decimal.Decimal("1e3"):
            value = nm / decimal.Decimal("1e3")
            unit = "µm"
        else:
            value = nm
            unit = "nm"
        value = str(value)
        if "." in value:
            value = value.rstrip("0")
            if value.endswith("."):
                value = value[:-1]
        return "{0} {1}".format(value, unit)

    def draw(self, canvas):
        """Draw this layer on the PDF canvas.  It draws both the outline and
        the filling.

        :param canvas: the PDF canvas object

        :type canvas: canvas.Canvas
        """
        def draw_column(column):
            path = Path(canvas, column, self.height, self.accumulated_height, self.textured, self.bottom_layer, self.color)
            path.draw_vertical_line("up")
            if self.textured:
                path.draw_textured_line("right")
            else:
                path.draw_horizontal_line("right")
            path.draw_vertical_line("down")
            path.draw_horizontal_line("left")
            path.draw()

            path = Path(canvas, column, self.height, self.accumulated_height, self.textured, self.bottom_layer)
            if self.collapsed:
                path.draw_collapsed_line("up")
            else:
                path.draw_vertical_line("up")
            if self.textured:
                path.draw_textured_line("right")
            else:
                path.draw_horizontal_line("right")
            if self.collapsed:
                path.draw_collapsed_line("down")
            else:
                path.draw_vertical_line("down")
            if self.bottom_layer and self.bottom_layer.textured:
                path.draw_textured_line("left")
            else:
                path.draw_horizontal_line("left")
            path.draw()
        if self.structured:
            draw_column("left")
            draw_column("right")
        else:
            draw_column("whole")

class Scale:
    """Class which holds the scale of the diagram.  This covers two tasks:
    First, to draw the scale at the top of the diagram, and secondly, to
    convert lengths given in nm to bp.

    :ivar scale: the scale factor of the diagram

    :ivar magnitude: the order of magnitude of the scale bar

    :ivar factor: the factor of the scale bar.  The height of the scale bar in
      nm is

      .. math::

          \\text{factor} \\cdot 10^{\\text{magnitude}}

    :ivar scale_height: the height of the scale bar in bp

    :type scale: float
    :type magnitude: int
    :type factor: int
    :type scale_height: float
    """

    def __init__(self, layers):
        """Find the optimal scaling for the diagram.

        :param layers: all layers of the stack

        :type layers: list of `Layer`

        :return:
          The scaling in bp/nm, the height of the scale bar in bp, the factor of
          the scale bar, and its magnitude.  The height of the scale bar in nm is

          .. math::

              \\text{factor} \\cdot 10^{\\text{magnitude}}

        :rtype: float, float, int, int
        """
        thicknesses = [layer.nm for layer in layers if layer.nm > 0]
        thicknesses.sort(reverse=True)
        if thicknesses:
            self.scale = 2 * 10**(1/10) * lineskip / thicknesses[len(thicknesses) // 2]
        else:
            self.scale = 2 * 10**(1/10) * lineskip / 1000
        # In order to snap the scale to discrete values
        self.scale = 10 ** (round(math.log10(self.scale) * 5) / 5)

        self.magnitude = 1
        while self.magnitude < 9:
            for self.factor in [1, 2, 5]:
                self.scale_height = self.scale * 10**self.magnitude * self.factor
                if self.scale_height > 0.735 * cm:
                    break
            else:
                self.magnitude += 1
                continue
            break

    def draw(self, canvas):
        """Draws the scale bar and its label on the PDF canvas.  Note that you
        must select the position of the scale by calling ``canvas.translate``
        before.

        :param canvas: the PDF canvas to be used

        :type canvas: canvas.Canvas
        """
        protusion = 2
        canvas.line(0, 0, 0, self.scale_height)
        canvas.line(-protusion, 0, protusion, 0)
        canvas.line(-protusion, self.scale_height, protusion, self.scale_height)
        scale_label = str(self.factor) + \
            [None, "0 nm", "00 nm", " µm", "0 µm", "00 µm", " mm", "0 mm", "00 mm"][self.magnitude]
        canvas.drawString(dimensions["scale_label_skip"], self.scale_height / 2 - line_height / 2, scale_label)

    def __call__(self, length):
        """Converts from nm to bp.

        :param length: the length in nm

        :type nm: float

        :return:
          the length in bp

        :rtype: float
        """
        return self.scale * length

def build_stack(layers, scale):
    """Pre-calculate the layout of the stack and its labels.  Nothing is
    actually drawn here.  Instead, this routine calculates the layer heights on
    the canvas, as well as the label dimensions.  Both is used to calculate the
    total size of the diagram and to position the labels.  (*Then* it is
    possible to actuall create the ``Canvas`` object and to draw on it.  But
    this is not done here.)

    :param layers: the layers to be drawn, in the chronological order of their
        making
    :param scale: the scale of the diagram

    :type layers: list of `Layer`
    :type scale: `Scale`

    :return:
      the height of the printed stack

    :rtype: float
    """
    total_height = 0
    for i, layer in enumerate(layers):
        layer.height = scale(layer.nm) if layer.nm > 0 else 0
        if layer.collapsed is None:
            layer.collapsed = layer.height > 10 * lineskip
        if layer.collapsed:
            layer.height = 2 * lineskip
        layer.label = Paragraph(layer.name, single_label_style)
        __, layer.label_height = layer.label.wrap(dimensions["label_width"], 10 * lineskip)
        layer.one_liner = len(layer.label.blPara.lines) == 1
        if i == 0:
            layer.bottom_layer = None
        elif layer.structured:
            layer.bottom_layer = layers[i - 1]
        else:
            j = i - 1
            while layers[j].structured or layers[j].nm < 0:
                j -= 1
                if j < 0:
                    layer.bottom_layer = None
                    break
            else:
                layer.bottom_layer = layers[j]
        total_height += layer.height
        layer.accumulated_height = total_height
    return total_height

class Label:
    """Class for labels of layers.

    :cvar needs_left_row: whether the space left to the stack must be used for
      labels, too; it is ``True`` iff at least one label is placed to the left
      of the stack

    :ivar text: the content of the label

    :ivar voffset: the vertical distance between the bottom of the stack
      diagram and the centre of the label

    :ivar right_row: see constructor

    :type needs_left_row: bool
    :type text: str
    :type voffset: float
    :type right_row: bool
    """
    needs_left_row = False

    def __init__(self, layer, right_row):
        """
        :param layer: the layer of this label
        :param right_row: whether the label should be placed to the right of the
            stack; if ``False``, it is positioned to the left

        :type layer: `Layer`
        :type right_row: bool
        """
        self.text, self.voffset, self.right_row = layer.name, layer.accumulated_height - layer.height / 2, right_row
        if not right_row:
            Label.needs_left_row = True

    def print_label(self, canvas):
        """Draws the label on the canvas.

        :param canvas: the PDF canvas to be used

        :type canvas: `Canvas`
        """
        if self.needs_left_row:
            hoffset = dimensions["label_width"] + dimensions["stack_width"] + 2 * dimensions["label_skip"] \
                if self.right_row else 0
        else:
            hoffset = dimensions["stack_width"] + dimensions["label_skip"] if self.right_row else 0
        if not self.right_row:
            self.text = """<para alignment="right">{0}</para>""".format(self.text)
        paragraph = Paragraph(self.text, single_label_style)
        __, height = paragraph.wrap(dimensions["label_width"], 10 * lineskip)
        paragraph.drawOn(canvas, hoffset, self.voffset - height / 2)

class NumberedLabel(Label):
    """Class for labels which consists of (circled) numbers because the actual
    label(s) are too big to be printed next to the layer(s).  This may have a
    from–to form like “➁–➄” or may be a single number like “➆”.

    :cvar largest_number: the largest number that occurs in the diagram.  It is
      needed because if it exceeds 10, the circled numbers from Unicode aren't
      sufficient anymore (Unicode contains only 1–10).  Thus, we have to
      fallback to parentheses then for *all* numbers: (1), (2), etc.

    :ivar lower: see constructor

    :ivar upper: see constructor

    :ivar voffset: see constructor

    :ivar right_row: see constructor

    :type largest_number: int
    :type lower: int
    :type upper: int
    :type voffset: float
    :type right_row: bool
    """
    largest_number = 0

    def __init__(self, lower, upper, voffset, right_row):
        """
        :param lower: the lower boundary of the numbers interval
        :param upper: the upper boundary of the numbers interval; thus, if this
            label contains only one number, ``upper`` − ``lower`` = 1
        :param voffset: the vertical distance between the bottom of the stack
            diagram and the centre of the label
        :param right_row: whether the label should be placed to the right of the
            stack; if ``False``, it is positioned to the left

        :type lower: int
        :type upper: int
        :type voffset: float
        :type right_row: bool
        """
        self.lower, self.upper, self.voffset, self.right_row = lower, upper, voffset, right_row
        NumberedLabel.largest_number = max(NumberedLabel.largest_number, upper - 1)
        if not right_row:
            Label.needs_left_row = True

    def print_label(self, canvas):
        if self.upper - self.lower == 1:
            self.text = get_circled_number(self.lower, self.largest_number)
        elif self.upper - self.lower == 2:
            self.text = ", ".join(get_circled_number(number, self.largest_number)
                                   for number in range(self.lower, self.upper))
        else:
            self.text = "{0}–{1}".format(get_circled_number(self.lower, self.largest_number),
                                          get_circled_number(self.upper - 1, self.largest_number))
        super().print_label(canvas)

def place_labels(layers):
    """Finds the best places for all labels.  Additionally, move labels for
    which there is not enough free space to the legend.

    :param layers: the layers to be drawn

    :type layers: list of `Layer`

    :return:
      all labels, all labels intended to be displaced to the legend

    :rtype: list of `Label`, list of str
    """
    labels = []
    displaced_labels = []
    i = 0
    while i < len(layers):
        layer = layers[i]
        if layer.height >= layer.label_height:
            labels.append(Label(layer, right_row=True))
        else:
            j = i + 1
            collective_height = layer.height
            while j < len(layers) and layers[j].height < line_height:
                collective_height += layers[j].height
                j += 1
            if j - i == 1 and layer.one_liner:
                labels.append(Label(layer, right_row=j == len(layers)))
            else:
                current_delayed_number = len(displaced_labels) + 1
                right_row = collective_height >= line_height
                voffset = layers[j - 1].accumulated_height - collective_height / 2
                labels.append(
                    NumberedLabel(current_delayed_number, current_delayed_number + j - i, voffset, right_row))
                displaced_labels.extend(layer.name for layer in layers[i:j])
            i = j - 1
        i += 1
    return labels, displaced_labels

def build_legend(displaced_labels, width):
    """Creates the legend without actually drawing it.

    :param displaced_labels: all labels intended to be displaced to the legend
    :param width: the width of the printed legend

    :type displaced_labels: list of str
    :type width: float

    :return:
      All items of the legend as ReportLab paragraphs, the height of the
      printed legend

    :rtype: list of Paragraph, float
    """
    legend = []
    for i, label in enumerate(displaced_labels):
        number = i + 1
        legend.append(
            Paragraph("""<bullet>{0}</bullet>{1}""".format(get_circled_number(number, NumberedLabel.largest_number), label),
                      legend_label_style))
    total_height = 0
    for item in legend:
        total_height += item.wrap(width, 100 * lineskip)[1]
    if legend:
        total_height += (len(legend) - 1) * 0.3 * lineskip
    return legend, total_height

def generate_diagram(filepath, layers, title, subject):
    """Generates the stack diagram and writes it to a PDF file.

    :param filepath: the path to the PDF file that should be written
    :param layers: the layers of the stack in chronological order
    :param title: the title of the PDF file
    :param subject: the subject of the PDF file

    :type filepath: str
    :type layers: list of `Layer`
    :type title: str
    :type subject: str
    """
    scale = Scale(layers)
    stack_height = build_stack(layers, scale)
    labels, displaced_labels = place_labels(layers)
    total_margin = dimensions["margin"]
    full_label_width = dimensions["label_skip"] + dimensions["label_width"]
    width = dimensions["stack_width"] + 2 * total_margin + full_label_width
    if Label.needs_left_row:
        width += full_label_width
    legend, legend_height = build_legend(displaced_labels, width)
    height = scale.scale_height + stack_height + legend_height + 2 * total_margin + dimensions["scale_skip"]
    if legend:
        height += dimensions["legend_skip"]
    verified = all(layer.verified for layer in layers)
    if not verified:
        red_line_space = dimensions["red_line_skip"] + dimensions["red_line_width"]
        width += 2 * red_line_space
        height += 2 * red_line_space
        total_margin += red_line_space

    c = canvas.Canvas(filepath, pagesize=(width, height), pageCompression=True)
    c.setAuthor("JuliaBase samples database")
    c.setTitle(title)
    c.setSubject(subject)
    c.setLineJoin(1)
    c.setLineCap(1)

    if not verified:
        red_line_position = dimensions["red_line_width"] / 2 + dimensions["red_line_skip"]
        c.saveState()
        c.setStrokeColor(getAllNamedColors()["red"])
        c.setLineWidth(dimensions["red_line_width"])
        c.rect(red_line_position, red_line_position, width - 2 * red_line_position, height - 2 * red_line_position)
        c.restoreState()
    c.translate(total_margin, total_margin)
    yoffset = 0
    for item in reversed(legend):
        item.drawOn(c, 0, yoffset)
        yoffset += item.height + 0.3 * lineskip
    if legend:
        c.translate(0, legend_height + dimensions["legend_skip"])
    for label in labels:
        label.print_label(c)
    c.saveState()
    if Label.needs_left_row:
        c.translate(full_label_width, 0)
    layers = [layer for layer in reversed(layers) if layer.nm >= 0]
    for i, layer in enumerate(layers):
        layer.draw(c)
    c.restoreState()
    c.translate(full_label_width if Label.needs_left_row else 0, stack_height + dimensions["scale_skip"])
    scale.draw(c)
    c.showPage()
    c.save()

if __name__ == "__main__":
    layers = [Layer("Glas", 2e3, "lightblue", textured=True),
              Layer("Eine wirklich wunderschöne αβγ-Schicht", 1e2,
                    "red", textured=True, verified=True),
              Layer("i", decimal.Decimal("999"), "orange", structured=True, textured=True, thickness_reliable=True),
              Layer("s", -1, "blue", textured=True),
              Layer("s", -1, "blue", textured=True),
              Layer("s", -1, "blue", textured=True),
              Layer("HF", -1, "blue", textured=True),
              Layer("n", 2e2, "green", textured=True),
              ]
    layers = [Layer("Glas", decimal.Decimal("1.1e6"), "lightblue", thickness_reliable=True, verified=True),
              Layer("ZnO", decimal.Decimal("800"), "lightgrey", thickness_reliable=True, verified=True),
              Layer("n", decimal.Decimal("25"), "green", thickness_reliable=True, verified=True),
              Layer("i", decimal.Decimal("150"), "orange", thickness_reliable=True, verified=True),
              Layer("p", decimal.Decimal("80"), "red", thickness_reliable=True, verified=True),
              Layer("HF", decimal.Decimal("-1"), "blue", thickness_reliable=True, verified=True),
              Layer("ZnO", decimal.Decimal("120"), "lightgrey", thickness_reliable=True, verified=True, structured=True),
              Layer("Silber", decimal.Decimal("700"), "grey", thickness_reliable=True, verified=True, structured=True,
                    collapsed=True),
              ]
    generate_diagram("test.pdf", layers, "10-TB-testsample", "Layer stack of 10-TB-testsample")


# n 皇后问题 研究的是如何将 n 个皇后放置在 n×n 的棋盘上，并且使皇后彼此之间不能相互攻击。
#
# 给你一个整数 n ，返回所有不同的 n 皇后问题 的解决方案。
#
# 每一种解法包含一个不同的 n 皇后问题 的棋子放置方案，该方案中 'Q' 和 '.' 分别代表了皇后和空位。
#
# 输入：n = 4
# 输出：[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
# 解释：如上图所示，4 皇后问题存在两个不同的解法。
# 示例 2：
#
# 输入：n = 1
# 输出：[["Q"]]

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        # 皇后会在所在行列正负对角线进行攻击
        # 所以决定了每行只有一个皇后
        # 再使用集合 对列， 正对角线 x+y 负对角线x-y 进行判断
        def generateMap():
            Map = list()
            for i in range(n):
                # queen[i] 表示 第i行的皇后的位置
                # print(queen)
                row[queen[i]] = 'Q'
                Map.append(''.join(row))
                row[queen[i]] = '.'
            return Map

        def backtarck(row):
            if row == n:
                Map = generateMap()
                ans.append(Map)
            # 列的遍历，皇后放哪一列
            for i in range(n):
                if i in columns or (row + i) in dial1 or (row - i) in dial2:
                    continue
                queen[row] = i
                columns.add(i)
                dial1.add(row + i)
                dial2.add(row - i)
                backtarck(row + 1)
                columns.remove(i)
                dial1.remove(row + i)
                dial2.remove(row - i)

        ans = list()
        columns, dial1, dial2 = set(), set(), set()
        queen = [-1] * n
        row = ['.'] * n
        backtarck(0)
        return ans


# -*- coding: utf-8 -*-
"""
Created on Fri Dec 26 10:21:46 2014
Project	:Python-Project
Version	:0.0.1
@author	:macrobull (http://github.com/macrobull)

"""

import os, sys

f=open('Chars', 'r')
ESCAPE = f.readline().split()[1:]
#print(ESCAPE)

cCnt = {}
mapper = {}
for l in f:
	info = l.split()
	for alias in info[1:]:
		mapper[alias] = info[0]
	cCnt[info[0]] = 0

f.close()

#print(mapper)

os.popen('rm "' + sys.argv[2] + '/"*')

for dirpath, dirnames, filenames in os.walk(sys.argv[1]):
	for ff in filenames:
		fn, ext = os.path.splitext(ff)
		for es in ESCAPE:
			fn = fn.replace(es, ' ')

		match = 0
		char = None
		for tag in fn.split():
			if tag in mapper:
				c = mapper[tag]
				if char != c:
					match += 1
					char = c

		if match == 1:
			os.popen("ln -s '"+dirpath + os.sep + ff+"' '"
				+ sys.argv[2] + os.sep + char + '.' +str(cCnt[char]) +
				ext + "'")
			cCnt[char] += 1

#sys.argv[1]
#sys.argv[2]


from django.db import models
from django.utils.translation import gettext_lazy as _

class Car(models.Model):
    owner = models.ForeignKey("users.Driver", on_delete=models.CASCADE, related_name="cars", verbose_name=_("Владелец"))
    brand = models.CharField(_("Марка"), max_length=100)
    released_at = models.DateTimeField(_("Дата выпуска"))

    class Meta:
        verbose_name = _("Автомобиль")
        verbose_name_plural = _("Автомобили")

    def __str__(self):
        return f""

class Order(models.Model):
    NEW = 10
    PROCESSING = 20
    DONE = 30
    CANCELED = 40

    STATUS_OPTIONS = (
        (NEW, _("Новый")),
        (PROCESSING, _("В обработке")),
        (DONE, _("Выполнен")),
        (CANCELED, _("Отменён")),
    )
    status = models.IntegerField(_("Статус"), choices=STATUS_OPTIONS, default=NEW)

    client = models.ForeignKey("users.User", on_delete=models.SET_NULL, related_name="orders", null=True,
                               verbose_name=_("Клиент"))
    driver = models.ForeignKey("users.Driver", on_delete=models.SET_NULL, related_name="orders", null=True,
                               verbose_name=_("Водитель"))
    car = models.ForeignKey("main.Car", on_delete=models.SET_NULL, related_name="orders", null=True,
                            verbose_name=_("Автомобиль"))
    address = models.CharField(_("Адресс пункта назначения"), max_length=100)

    client_comment = models.TextField(_("Комментарий клиента"), blank=True, null=True)
    driver_comment = models.TextField(_("Комментарий водителя"), blank=True, null=True)

    created_at = models.DateTimeField(_("Время создания"), auto_now_add=True)
    updated_at = models.DateTimeField(_("Время обновления"), auto_now=True)

    class Meta:
        ordering = ("-created_at",)
        verbose_name = _("Заказ")
        verbose_name_plural = _("Заказы")

    def __str__(self):
        return f"Заказ #{self.pk}"


#이진 탐색 = 탐색 범위를 절반씩 줄여 나가면서 찾는다
#장점 = 빠르다 / 실제로 쓰인다
#단점 = 정렬이 되어 있어야 한다. / 만들기 어렵다

# 핵심 로직
# 중간 인덱스 값을 구해서 반씩 나눠가며 탐색

arr = [1,2,3,5,6,7,8,9,10,11]

def bisearch(arr,num):

    start = 0
    end = len(arr) -1

    midindex = len(arr) // 2
    indexv = arr[midindex]
    if indexv == num:
        return midindex
    elif indexv < num:
        start = midindex +1
    elif indexv > num:
        end = midindex -1

    return -1


class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        used1 = [[False] * 9 for _ in range(9)]
        used2 = [[False] * 9 for _ in range(9)]
        used3 = [[False] * 9 for _ in range(9)]

        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] != '.':
                    num = int(board[i][j]) - 1
                    k = i // 3 * 3 + j // 3
                    if used1[i][num] or used2[j][num] or used3[k][num]:
                        return False
                    used1[i][num] = used2[j][num] = used3[k][num] = True

        return True


# coding : utf-8
def main():
    N = int(input())
    S = str(input())

    j = 0
    for i, s in enumerate(S):
        if s == str(1):
            j = i
            break

    if (j + 1) % 2 == 0:
        print("Aoki")
    else:
        print("Takahashi")

main()


#作者：刘畅
#功能：HMM（隐马尔可夫模型）分词
#计算后接字标签最有可能出现的概率
from collections import Counter
from math import log

hmm_model = {i:Counter() for i in 'sbme'}

with open('dict.txt',encoding='utf-8') as f:
    for line in f:
        lines=line.split(' ')
        if len(lines[0]) == 1:
            hmm_model['s'][lines[0]] +=int(lines[1])
        else:
            hmm_model['b'][lines[0][0]] +=int(lines[1])
            hmm_model['e'][lines[0][-1]] += int(lines[1])
            for m in lines[0][1:-1]:
                hmm_model['m'][m] += int(lines[1])
print(hmm_model)
log_total = {i:log(sum(hmm_model[i].values())) for i in 'sbme'}
print(log_total)

trans={'ss': 0.3,'sb': 0.7,'bm': 0.3,'be': 0.7,
       'mm': 0.3,'me': 0.7,'es': 0.3,'eb': 0.7}

trans = {i:log(j) for i,j in trans.items()}

def viterbi(nodes):#nodes表示需要分词的句子中所有字的标签情况
    paths = nodes[0]#第一个字的sbme标签情况
    for l in range(1, len(nodes)):  # l表示句子中的每个字对应的偏移量
        paths_ = paths
        paths = {}
        for i in nodes[l]:
            nows = {}
            for j in paths_:
                if j[-1]+i in trans:#当前字标签和后接字标签的组合能够出现时计算出现概率。
                    nows[j+i] = paths_[j] + nodes[l][i] + trans[j[-1]+i]
            k = max(nows.values())
            paths[list(nows.keys())[list(nows.values()).index(k)]] = k#将概率最大（最有可能出现的词计算胡来）
    return list(paths.keys())[list(paths.values()).index(max(paths.values()))]# return paths.keys()[paths.values()]#.index(max(paths.values()))]

def hmm_cut(s):
    nodes = [{i:log(j[t]+1)-log_total[i] for i,j in hmm_model.items()}for t in s]
    tags = viterbi(nodes)
    print(tags)
    words = [s[0]]
    for i in range(1,len(s)):
        if tags[i] in ['b','s']:
            words.append(s[i])
        else:
            words[-1] +=s[i]
    return words

if __name__ == '__main__':
    print(hmm_cut('结婚的和尚未结婚的'))


numer = 1

while numer <= 200:
    licz = 0
    i = 2

    while i <= numer//2:
        if numer % i == 0:
            licz = licz + 1
        i =  i + 1

    if licz == 0 and numer != 1:
        print(numer, end= " " )

    numer = numer + 1


class Solution:
    # 22.26% 71.31%
    def arrayChange(self, nums: List[int], operations: List[List[int]]) -> List[int]:
        coords = {num: i for i, num in enumerate(nums)}
        for old, new in operations:
            nums[coords[old]] = new
            coords[new] = coords[old]
        return nums

    def arrayChange_best_speed(self, nums: List[int], operations: List[List[int]]) -> List[int]:
        dic = {num: i for i, num in enumerate(nums)}
        for s, e in operations:
            i = dic[s]
            nums[i] = e
            dic[e] = i
            del dic[s]
        return nums

    def arrayChange_2nd_best_speed(self, nums: List[int], operations: List[List[int]]) -> List[int]:
        index = {val: i for i, val in enumerate(nums)}
        for old, new in operations:
            x = index[old]
            nums[x] = new
            index[new] = x
        return nums

    def arrayChange_best_memory(self, nums: List[int], operations: List[List[int]]) -> List[int]:
        hashmap = {}
        while operations:
            cad = operations.pop()
            if cad[1] in hashmap:
                hashmap[cad[0]] = hashmap[cad[1]]
            else:
                hashmap[cad[0]] = cad[1]
        for i in range(len(nums)):
            cad = nums[i]
            if cad in hashmap:
                nums[i] = hashmap[cad]
        return nums

2200 - 2299/2295 - Replace Elements in an Array/2295 - Replace Elements in an Array.py


from vehiculo_espacial.models import VehiculoNoTripulado
from dtos.nave_no_tripulada_dto import NaveNoTripuladaDTO

class NaveNoTripuladaMapper:
  def nave_no_tripulada_dto_to_model(nave_dto: NaveNoTripuladaDTO):
    nave= VehiculoNoTripulado(None,nave_dto.get_nombre(),nave_dto.get_tipo_propulsion(),nave_dto.get_capacidad_transporte(),
    nave_dto.get_peso(),nave_dto.get_empuje())
    return nave

  def model_to_nave_no_tripulada_dto(self, nave: VehiculoNoTripulado):
    nave_dto= NaveNoTripuladaDTO(nave.nombre,nave.tipo_propulsion,nave.capacidad_transporte,
    nave.peso,nave.empuje)
    return nave_dto

  def form_to_nave_no_tripulada_dto(input):
    nave_dto= NaveNoTripuladaDTO(None,input['name'][0],input['tipo_propulsion'][0],input['capacidad'][0],
    input['peso'][0],input['empuje'][0])
    return nave_dto


# -*- coding: utf-8 -*-

import sys
import os
import re
from operator import itemgetter
from ipwww_common import translation, AddMenuEntry, OpenURL, \
                         CheckLogin, CreateBaseDirectory

import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import random
import json

ADDON = xbmcaddon.Addon(id='plugin.video.iplayerwww')

def GetAtoZPage(page_url, just_episodes=False):
    """   Generic Radio page scraper.   """

    pDialog = xbmcgui.DialogProgressBG()
    pDialog.create(translation(30319))

    html = OpenURL(page_url)

    total_pages = 1
    current_page = 1
    page_range = list(range(1))
    paginate = re.search(r'<ol.+?class="pagination.*?
',html)
    next_page = 1
    if paginate:
        if int(ADDON.getSetting('radio_paginate_episodes')) == 0:
            current_page_match = re.search(r'page=(\d*)', page_url)
            if current_page_match:
                current_page = int(current_page_match.group(1))
            page_range = list(range(current_page, current_page+1))
            next_page_match = re.search(r'
', paginate.group(0))
            if next_page_match:
                page_base_url = next_page_match.group(1)
                next_page = int(next_page_match.group(2))
            else:
                next_page = current_page
            page_range = list(range(current_page, current_page+1))
        else:
            pages = re.findall(r'<li.+?class="pagination__page.*?
',paginate.group(0))
            if pages:
                last = pages[-1]
                last_page = re.search(r' current_page:
            page_url = 'http://www.bbc.co.uk' + page_base_url + str(page)
            html = OpenURL(page_url)

        masthead_title = ''
        masthead_title_match = re.search(r'<div.+?id="programmes-main-content".*?(.+?)', html)
        if masthead_title_match:
            masthead_title = masthead_title_match.group(1)
        else:
            alternative_masthead_title_match = re.search(r'
.*?([^<]+?)', html, re.M | re.S)
            if alternative_masthead_title_match:
                masthead_title = alternative_masthead_title_match.group(1)

        list_item_num = 1

        programmes = html.split('
')
        for programme in programmes:

            if not re.search(r'programme--radio', programme):
                continue

            series_id = ''
            series_id_match = re.search(r'data-lazylink-inc="/programmes/(.+?)/episodes/player.inc"', programme)
            if series_id_match:
                series_id = series_id_match.group(1)

            programme_id = ''
            programme_id_match = re.search(r'data-pid="(.+?)"', programme)
            if programme_id_match:
                programme_id = programme_id_match.group(1)

            name = ''
            name_match = re.search(r'(.+?)', programme)
            if name_match:
                name = name_match.group(1)
            else:
                alternative_name_match = re.search(r'<meta property="name" content="([^"]+?)"', programme)
                if alternative_name_match:
                    name = alternative_name_match.group(1)

            image = ''
            image_match = re.search(r'<meta property="image" content="(.+?)" />', programme)
            if image_match:
                image = image_match.group(1)

            synopsis = ''
            synopsis_match = re.search(r'(.+?)<\/span>', programme)
            if synopsis_match:
                synopsis = synopsis_match.group(1)

            station = ''
            station_match = re.search(r'<p class="programme__service.+?(.+?)<\/strong>.*?<\/p>', programme)
            if station_match:
                station = station_match.group(1).strip()

            series_title = "[B]%s - %s[/B]" % (station, name)
            if just_episodes:
                title = "[B]%s[/B] - %s" % (masthead_title, name)
            else:
                title = "[B]%s[/B] - %s" % (station, name)

            if series_id:
                AddMenuEntry(series_title, series_id, 131, image, synopsis, '')
            elif programme_id: #TODO maybe they are not always mutually exclusive
                url = "http://www.bbc.co.uk/radio/play/%s" % programme_id
                CheckAutoplay(title, url, image, ' ', '')

            percent = int(100*(page+list_item_num/len(programmes))/total_pages)
            pDialog.update(percent,translation(30319),name)

            list_item_num += 1

        percent = int(100*page/total_pages)
        pDialog.update(percent,translation(30319))

    if int(ADDON.getSetting('radio_paginate_episodes')) == 0:
        if current_page < next_page:
            page_url = 'http://www.bbc.co.uk' + page_base_url + str(next_page)
            AddMenuEntry(" [COLOR ffffa500]%s >>[/COLOR]" % translation(30320), page_url, 138, '', '', '')

    #BUG: this should sort by original order but it doesn't (see http://trac.kodi.tv/ticket/10252)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_VIDEO_TITLE)

    pDialog.close()

def GetPage(page_url, just_episodes=False):
    """   Generic Radio page scraper.   """

    pDialog = xbmcgui.DialogProgressBG()
    pDialog.create(translation(30319))

    html = OpenURL(page_url)

    total_pages = 1
    current_page = 1
    page_range = list(range(1))
    paginate = re.search(r'<ol.+?class="pagination.*?
',html)
    next_page = 1
    if paginate:
        if int(ADDON.getSetting('radio_paginate_episodes')) == 0:
            current_page_match = re.search(r'page=(\d*)', page_url)
            if current_page_match:
                current_page = int(current_page_match.group(1))
            page_range = list(range(current_page, current_page+1))
            next_page_match = re.search(r'
', paginate.group(0))
            if next_page_match:
                page_base_url = next_page_match.group(1)
                next_page = int(next_page_match.group(2))
            else:
                next_page = current_page
            page_range = list(range(current_page, current_page+1))
        else:
            pages = re.findall(r'<li.+?class="pagination__page.*?
',paginate.group(0))
            if pages:
                last = pages[-1]
                last_page = re.search(r' current_page:
            page_url = 'http://www.bbc.co.uk' + page_base_url + str(page)
            html = OpenURL(page_url)

        masthead_title = ''
        masthead_title_match = re.search(r'<div.+?id="programmes-main-content".*?(.+?)', html)
        if masthead_title_match:
            masthead_title = masthead_title_match.group(1)
        else:
            alternative_masthead_title_match = re.search(r'
.*?([^<]+?)', html, re.M | re.S)
            if alternative_masthead_title_match:
                masthead_title = alternative_masthead_title_match.group(1)

        list_item_num = 1
        data = ''
        data_match = re.findall(r'', html, re.DOTALL)
        if match:
            data = match.group(1)
            json_data = json.loads(data)
            # Note: Need to create list for backwards compatibility
            stream_id_st = [json_data['programmes']['current']['id']]
            # print json.dumps(json_data, indent=2, sort_keys=True)
    return stream_id_st

def CheckAutoplay(name, url, iconimage, plot, aired=None):
    if ADDON.getSetting('streams_autoplay') == 'true':
        AddMenuEntry(name, url, 212, iconimage, plot, '', aired=aired)
    else:
        AddMenuEntry(name, url, 132, iconimage, plot, '', aired=aired)


import numpy as np
import utils.CamLib as cl

def _get_coord(id_list, xyz):
    id_list = np.array(id_list).reshape([-1, 1])
    return np.mean(xyz[id_list], 0).squeeze()

def _get_origin(origin_def, xyz):
    """ Get location from an definition. """
    mode, definition = origin_def
    if mode == 'l':
        return _get_coord(definition, xyz)

    elif mode == 'g':
        return np.array(definition)

def _get_vec(axes_def, xyz):
    """ Get axis from an definition. """
    mode, definition = axes_def
    if mode == 'l':
        p = _get_coord(definition[0], xyz)
        c = _get_coord(definition[1], xyz)
        vec = c - p

    elif mode == 'g':
        vec = np.array(definition)

    else:
        raise NotImplementedError('Invalid mode.')

    return np.reshape(vec, [3])

def _norm(vec):
    """ L2 norm of a vector. """
    n = np.linalg.norm(vec, 2)
    if n < 1e-6:
        raise Exception('Small vector used for axis definition.')
    return vec/n

def _to_mat(x_axis, y_axis, z_axis, origin):
    R = np.stack([x_axis, y_axis, z_axis], 0)  # rotation matrix
    M = np.eye(4)
    M[:3, :3] = R
    M[:3, -1:] = -np.matmul(R, np.reshape(origin, [3, 1]))  # trans
    return M

def _my_cross(x=None, y=None, z=None):
    """ Calculate cross product without having to worry about getting the order and signs right. """
    if x is not None and y is not None:
        return np.cross(x, y)
    elif x is not None and z is not None:
        return np.cross(x, -z)
    elif y is not None and z is not None:
        return np.cross(y, z)
    else:
        raise NotImplementedError('This should never happen.')

def trafo_to_coord_frame(coord_def, xyz):
    """ Calculate the transformation matrix. """
    ori = coord_def['orientation']
    has_x = 'x' in ori.keys()
    has_y = 'y' in ori.keys()
    has_z = 'z' in ori.keys()
    assert sum([has_x, has_y, has_z]) == 2, 'You get to chose exactly two axes, no more, no less.'

    if has_x and has_y:
        x_vec = _norm(_get_vec(ori['x'], xyz))
        y_vec = _norm(_get_vec(ori['y'], xyz))
        z_vec = _my_cross(x=x_vec, y=y_vec)

        if ori['prio'] == 'x':
            y_vec = _my_cross(x=x_vec, z=z_vec)
        elif ori['prio'] == 'y':
            x_vec = _my_cross(y=y_vec, z=z_vec)
        else:
            raise NotImplementedError('This should never happen.')

    elif has_x and has_z:
        x_vec = _norm(_get_vec(ori['x'], xyz))
        z_vec = _norm(_get_vec(ori['z'], xyz))
        y_vec = _my_cross(x=x_vec, z=z_vec)

        if ori['prio'] == 'x':
            z_vec = _my_cross(x=x_vec, y=y_vec)
        elif ori['prio'] == 'z':
            x_vec = _my_cross(y=y_vec, z=z_vec)
        else:
            raise NotImplementedError('This should never happen.')

    elif has_y and has_z:
        y_vec = _norm(_get_vec(ori['y'], xyz))
        z_vec = _norm(_get_vec(ori['z'], xyz))
        x_vec = _my_cross(y=y_vec, z=z_vec)

        if ori['prio'] == 'y':
            z_vec = _my_cross(x=x_vec, y=y_vec)
        elif ori['prio'] == 'z':
            y_vec = _my_cross(x=x_vec, z=z_vec)
        else:
            raise NotImplementedError('This should never happen.')

    else:
        raise NotImplementedError('This should never happen.')

    origin = _get_origin(coord_def['origin'], xyz)
    M = _to_mat(x_vec, y_vec, z_vec, origin)
    xyz_local = cl.trafo_coords(xyz, M)
    return xyz_local

def calculate_angle(angle_def, xyz):
    """ Calculate angle in rad between two vectors. """
    vec1 = _norm(_get_vec(angle_def[0], xyz))
    vec2 = _norm(_get_vec(angle_def[1], xyz))
    return np.arccos(np.dot(vec1, vec2))


import numpy as np
import keras
import h5py
import pywt
import json

# DO NOT CHANGE (length of a single slot in seconds, car dependant):
TIME = 0.05

SEG_LEN = 10  # sec, length of sample (window)
WINDOW_SIZE = int(SEG_LEN / TIME)

class DataGenerator(keras.utils.Sequence):
    'Generates data for Keras'

    def __init__(self, list_ids, labels, targets, categories, binary, n_channels, type, sensor='clutch', batch_size=32, dim=WINDOW_SIZE):
        'Initialization'
        self.targets = targets
        self.dim = dim
        self.batch_size = batch_size
        self.labels = labels
        self.list_IDs = list_ids
        self.n_channels = n_channels
        self.on_epoch_end()
        self.list_of_sensors = []
        self.inp_names = []
        self.type = type
        self.binary = binary
        self.categories = categories

        if self.binary:
            self.n_classes = 2
        else:
            self.n_classes = len(targets)

        with open('label_dict.json', 'r') as f:
            self.label_dict_name = json.load(f)

        if self.n_channels == 1:
            if sensor!= "":
                self.list_of_sensors = [sensor]
            else:
                self.list_of_sensors = ['clutch']
            self.inp_names = ['inp1']
        else:
            self.list_of_sensors = ['clutch', 'gaspedal', 'rpm', 'speed']
            self.inp_names = ['inp0', 'inp1', 'inp2', 'inp3']

        print(
            "Created data generator with {0} number of channels, {1} targets, labels_dict of length {2}, number of "
            "classes {3}, list of ids with length {4}".format(self.n_channels, self.targets, len(self.labels),
                                                              self.n_classes, len(self.list_IDs)))

    def __len__(self):
        'Denotes the number of batches per epoch'
        return int(np.floor(len(self.list_IDs) / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]

        # Find list of IDs
        list_IDs_temp = [self.list_IDs[k] for k in indexes]

        # Generate data
        X, y = self.__data_generation(list_IDs_temp)

        return X, y

    def on_epoch_end(self):
        'Updates indexes after each epoch'
        self.indexes = np.arange(len(self.list_IDs))

    def reshape_helper(self, X):
        return X.reshape(X.shape[0], X.shape[1], 1)

    def __data_generation(self, list_IDs_temp):
        'Generates data containing batch_size samples'  # X : (n_samples, *dim, n_channels)
        # Initialization
        X = np.empty((self.batch_size, self.dim, self.n_channels))
        if self.n_classes == 2:
            y = np.empty(self.batch_size, dtype=int)
        else:
            y = np.empty((self.batch_size, self.n_classes), dtype=int)

        # Map labels to integers
        if self.binary:
            driver2id = dict((t, int(t in self.targets)) for t in set(self.categories))
        else:
            driver2id = dict(
                (t, keras.utils.to_categorical(i, num_classes=self.n_classes)) for i, t in enumerate(self.categories))

        if self.type == "train":
            h5f = h5py.File("sliced_data/dset1.h5", 'r')
        elif self.type == "test":
            h5f = h5py.File("sliced_data/dset2.h5", 'r')

        X_dict = {}
        for i, ID in enumerate(list_IDs_temp):
            # Store sample
            for sensor_, j in zip(self.list_of_sensors, range(self.n_channels)):
                x = h5f[sensor_][int(ID)]
                X[i, :, j] = x
            if self.binary:
                y[i] = driver2id[self.labels[str(ID)]]
            else:
                y[i] = np.array(driver2id[self.labels[str(ID)]])

        for inp, i in zip(self.inp_names, range(self.n_channels)):
            X_dict[inp] = self.reshape_helper(X[:, :, i])
        h5f.close()
        return X_dict, y


# 문제분석

# TLE.
# string = list(input())

# length = 1
# dic = {}
# while length <= len(string):
# 	for i in range(0, len(string)):
# 		if "".join(string[i:i+length]) not in dic:
# 			dic["".join(string[i:i+length])] = 1
# 	length += 1

# print(len(dic))

string = input()
length = 1

cnt = 0
arr = set()
while length <= len(string):
	for i in range(0, len(string)):
		arr.add(string[i:i+length])
	# 서로 다른 문자열이고
	length += 1

# set table 을 썼어야 하는 문제이구만
print(len(arr))

python-algo/data_structure/서로 다른 부분 문자열의 개수.py

서로 다른 부분 문자열의 개수.py


import customtkinter as ctk

from components.Clusters import KubeClusters
from components.StatusBar import StatusBar
from kubectl.config_read import getKubeConfigDetails
from menus.MenuMain import MainMenu

ctk.set_appearance_mode("System")
ctk.set_default_color_theme("dark-blue")
appWidth, appHeight = 900, 800

class App(ctk.CTk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.title("Kubectl Config Manager")
        self.geometry(f"{appWidth}x{appHeight}")

        MainMenu(self)

        self.clusterFrame = ctk.CTkFrame(self)
        self.KubeClusters = KubeClusters(self.clusterFrame, self)
        self.clusterFrame.pack(side='top', fill='both', expand=True)

        self.statusFrame  = ctk.CTkFrame(self)
        self.StatusBar    = StatusBar(self.statusFrame)
        self.statusFrame.pack(side='bottom', fill='both', expand=True)

    def generateResults(self, event=None):
        self.StatusBar.setAction(f'generateResults - event:{event}')
        print(f'generateResults - event:{event}')

    def set_kube_details(self, kube_config_details):
        self.KubeClusters.setValues(kube_config_details)

    def reset_app(self):
        print('Reloading all settings')
        #app.quit()

    def shutdown_app(self):
        print('Shutting down 1')
        app.quit()

# ----------------------------------------------------
if __name__ == "__main__":
    kube_config = getKubeConfigDetails()

    app = App()
    app.set_kube_details(kube_config)

    # trap the close event to kill the matplotlib agent
    app.protocol('WM_DELETE_WINDOW', app.shutdown_app)

    app.mainloop()