from functions import *
from findError import find_collection_error
import matplotlib.pyplot as plt
from utils import human_format

while True:
    option_input = ''
    print("Choose a function type:")
    options = [
        ['linear', linear],
        ['exponential', exponential],
        ['sinusoidal', sinusoidal],
        ['absolute', absolute],
        ['ellipse', ellipse],
        ['upside down normal', upside_normal],
        ['quadratic', quadratic]
    ]
    for i, option in enumerate(options):
        print(f'{i}: {option[0]}')
    option_input = input()
    try:
        function_name = options[int(option_input)][0]
        chosen_function = options[int(option_input)][1]
        break
    except:
        print('try again.')

number_of_samples = int(input('Number of samples to be generated: '))

single_or_multiple = int(input('Single trial or series? (S: 0, M: 1): '))
if single_or_multiple == 0: # single trial
    sample_size = int(input('Sample size: '))
    find_collection_error(
        chosen_function,
        sample_size,
        number_of_samples,
        plot_graph=True)

else: # mutliple trials
    upper_limit = int(input('Upper limit n: '))+1
    list_of_err = []

    for i in range(1, upper_limit):
        list_of_err.append(
            find_collection_error(
                chosen_function,
                i,
                number_of_samples)
        )

        print(f'{i}/{upper_limit-1} completed...')

    for i, err in enumerate(list_of_err):
        print(f'n={i+1}: P={round(err * 100, 2)}%')

    x = [i for i in range(1,upper_limit)]
    y = [100 * j for j in list_of_err]

    plt.figure(figsize=(8, 5))
    plt.plot(x, y)
    plt.xlabel('n')
    plt.ylabel('% error')
    plt.title(f'% error based on n ({function_name}), {human_format(number_of_samples)} samples')
    plt.grid(True)
    plt.show()


import torch

class Lie:
    @classmethod
    def se3_exp_map(cls, log_transform: torch.Tensor, eps: float = 1e-4):
        """
        se3 -> SE3

        Args:
            log_transform: shape of (N, 6)
        Returns:
            transform: shape of (N, 4, 4)
        """
        assert (
            len(log_transform.shape) == 2 and log_transform.shape[-1] == 6
        ), "Input tensor shape has to be Nx6."
        N = log_transform.shape[0]

        log_trans, log_rot = log_transform.split(3, dim=-1)

        skews = cls.hat(log_rot)
        skews_square = torch.bmm(skews, skews)
        rot_angles = (log_rot**2).sum(-1).clamp(eps).sqrt()
        rot_angles_inv = 1.0 / rot_angles
        I = torch.eye(3).to(log_transform)[None]

        A = (rot_angles.sin() * rot_angles_inv)[:, None, None]
        B = ((1.0 - rot_angles.cos()) * (rot_angles_inv**2))[:, None, None]
        C = ((rot_angles - rot_angles.sin()) * (rot_angles_inv**3))[:, None, None]

        R = I + A * skews + B * skews_square
        V = I + B * skews + C * skews_square
        T = V @ log_trans[..., None]

        transform = torch.eye(4).to(log_transform).repeat(N, 1, 1)
        transform[..., :3, :4] = torch.cat([R, T], dim=-1)

        return transform

    @classmethod
    def so3_exp_map(cls, log_rotation: torch.Tensor, eps: float = 1e-4):
        """
        so3 -> SO3

        Args:
            log_rotation: shape of (N, 3)
        Returns:
            R: shape of (N, 3, 3)
        """
        assert (
            len(log_rotation.shape) == 2 and log_rotation.shape[-1] == 3
        ), "Input tensor shape has to be Nx3."

        skews = cls.hat(log_rotation)
        skews_square = torch.bmm(skews, skews)
        rot_angles = (log_rotation**2).sum(-1).clamp(eps).sqrt()
        rot_angles_inv = 1.0 / rot_angles
        I = torch.eye(3).to(log_rotation)[None]

        A = (rot_angles.sin() * rot_angles_inv)[:, None, None]
        B = ((1.0 - rot_angles.cos()) * (rot_angles_inv**2))[:, None, None]

        R = I + A * skews + B * skews_square

        return R

    @classmethod
    def se3_log_map(
        cls, transform: torch.Tensor, eps: float = 1e-4, cos_bound: float = 1e-4
    ):
        """
        SE3 -> se3

        Args:
            transform: shape of (N, 4, 4)
        Returns:
            : shape of (N, 6)
        """
        assert (
            len(transform.shape) == 3
            and transform.shape[1] == 4
            and transform.shape[2] == 4
        ), "Input tensor shape has to be Nx4x4."
        N = transform.shape[0]

        assert torch.allclose(
            transform[:, 3, :3], torch.zeros_like(transform[:, :3, 3])
        ), "All elements of `transform[:, :3, 3]` should be 0."

        R = transform[:, :3, :3]
        log_rot = cls.so3_log_map(R, eps=eps, cos_bound=cos_bound)

        T = transform[:, :3, 3]

        rot_angles = (log_rot**2).sum(-1).clamp(eps).sqrt()
        log_rot_hat = cls.hat(log_rot)
        log_rot_hat_square = torch.bmm(log_rot_hat, log_rot_hat)
        I = torch.eye(3).to(log_rot)[None]

        A = ((1 - torch.cos(rot_angles)) / (rot_angles**2))[:, None, None]
        B = ((rot_angles - torch.sin(rot_angles)) / (rot_angles**3))[:, None, None]

        V = I + A * log_rot_hat + B * log_rot_hat_square
        log_trans = torch.linalg.solve(V, T[:, :, None])[:, :, 0]

        return torch.cat([log_trans, log_rot], dim=1)

    @classmethod
    def so3_log_map(cls, R: torch.Tensor, eps: float = 0.0001, cos_bound: float = 1e-4):
        """
        SO3 -> so3

        Args:
            R: shape of (N, 3, 3)
        Returns:
            log_rotation: shape of (N, 3)
        """
        assert len(R.shape) == 3 and R.shape[1] == 3 and R.shape[2] == 3
        N = R.shape[0]

        rot_trace = R[:, 0, 0] + R[:, 1, 1] + R[:, 2, 2]
        assert not (
            (rot_trace < -1.0 - eps) + (rot_trace > 3.0 + eps)
        ).any(), "A matrix has trace outside valid range [-1-eps,3+eps]."

        phi_cos = (rot_trace - 1.0) * 0.5
        phi = torch.acos(phi_cos.clamp(-1 + cos_bound, 1 - cos_bound))
        phi_sin = torch.sin(phi)

        # We want to avoid a tiny denominator of phi_factor = phi / (2.0 * phi_sin).
        # Hence, for phi_sin.abs() <= 0.5 * eps, we approximate phi_factor with
        # 2nd order Taylor expansion: phi_factor = 0.5 + (1.0 / 12) * phi**2
        phi_factor = torch.empty_like(phi)
        ok_denom = phi_sin.abs() > (0.5 * eps)
        phi_factor[~ok_denom] = 0.5 + (phi[~ok_denom] ** 2) * (1.0 / 12)
        phi_factor[ok_denom] = phi[ok_denom] / (2.0 * phi_sin[ok_denom])

        log_rotation_hat = phi_factor[:, None, None] * (R - R.permute(0, 2, 1))

        log_rotation = cls.hat_inv(log_rotation_hat)

        return log_rotation

    @classmethod
    def hat(cls, v: torch.Tensor):
        assert len(v.shape) == 2 and v.shape[-1] == 3
        N, dim = v.shape

        h = torch.zeros((N, 3, 3), dtype=v.dtype, device=v.device)
        x, y, z = v.unbind(-1)
        h[:, 0, 1] = -z
        h[:, 0, 2] = y
        h[:, 1, 0] = z
        h[:, 1, 2] = -x
        h[:, 2, 0] = -y
        h[:, 2, 1] = x

        return h

    @classmethod
    def hat_inv(cls, h: torch.Tensor, hat_inv_skew_symmetric_tol: float = 1e-5):
        assert (
            len(h.shape) == 3 and h.shape[1] == 3 and h.shape[2] == 3
        ), "Input has to be a batch of 3x3 Tensors."

        ss_diff = torch.abs(h + h.permute(0, 2, 1)).max()
        assert (
            float(ss_diff) < hat_inv_skew_symmetric_tol
        ), "One of input matrices is not skew-symmetric."

        x = h[:, 2, 1]
        y = h[:, 0, 2]
        z = h[:, 1, 0]
        v = torch.stack((x, y, z), dim=1)

        return v

class ExtrinsicOptimizer(torch.nn.Module):
    def __init__(self, n_views):
        super().__init__()

        self.se3_refinement = torch.nn.Embedding(n_views, 6)
        torch.nn.init.zeros_(self.se3_refinement.weight)

    def forward(self, extrinsics: torch.Tensor, indices: torch.tensor):
        """
        Optimize the camera extrinsic of the given index.

        Args:
            extrinsics: torch.Tensor, RT matrix of shape (B, 4, 4).
            indices: torch.Tensor of shape (B, 1)
        """
        refinement = Lie.se3_exp_map(self.se3_refinement(indices))
        return refinement @ extrinsics


"""
########################################
Code Your lambda Program here
isspace = lambda
########################################
"""

def mystrip(strval):
    strip = ''
    for v in strval:
        if not isspace(v):
            strip += v
    return strip

strval = 'Python Programming\t Section 1\n'
ret = mystrip(strval)
print(ret)


test_book_data = """
#This is a comment
Title of book

  Tags: Tag1, tag2, abcd
  Total: 700
  Exam: !today+7

  Sections:

    date: !today+1
    0 [2-5]: 0-10

    date: !today+2
    1 [1,2]: 10-20

    date: !today+3
    1 [3-5]: 21-30

Title of second book

Title of third book
"""

from pagecounter import parser

def test_titles():

    parser_result = parser.parse(test_book_data)

    title_list = [
            'Title of book',
            'Title of second book',
            'Title of third book',
            ]

    assert(list(parser_result.keys()) == title_list)


# Assign two variables that store the following values:

# $ 34.99 - product price (float)

# 20 lbs - product weight (int)

# Using the f-string formatting style print to the console the following message:
# price: $34.99. weight:20 lbs.

product_price = float(34.99)
product_weight= int(20)
print(f"price: ${product_price}. weight:{product_weight} lbs.")


from collections import deque

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def bfs(self, root):
    queue = deque()

    if root:
        queue.append(root)

    level = 0

    while len(queue):
        print("level: ", level)
        for i in range(len(queue)):
            cur = queue.popLeft()
            print(cur.val)
            if cur.left:
                queue.append(cur.left)
            if cur.right:
                queue.append(cur.right)
        level += 1


import numpy as np
import math
import matplotlib.pyplot as plt
from visualizer import KalmanFilterVisualizer

def save_plots(real_position, measured_position, kalman_position, real_speed, kalman_speed, measured_error,
               kalman_error, times):
    plt.plot(times, real_position, label='Faktyczne położenie')
    plt.plot(times, measured_position, label='Zmierzone położenie')
    plt.plot(times, kalman_position, label='Estymowane położenie')
    plt.xlabel('czas (s)')
    plt.ylabel('położenie (m)')
    plt.legend()
    plt.title('Położenie')
    plt.savefig('positions.png')
    plt.clf()
    plt.plot(times[200:400], real_position[200:400], label='Faktyczne położenie')
    plt.plot(times[200:400], measured_position[200:400], label='Zmierzone położenie')
    plt.plot(times[200:400], kalman_position[200:400], label='Estymowane położenie')
    plt.legend()
    plt.xlabel('czas (s)')
    plt.ylabel('położenie (m)')
    plt.title('Położenie pomiędzy 2 a 4 sekundą ruchu')
    plt.savefig('positions24.png')
    plt.clf()

    plt.plot(times, real_speed, label='Faktyczna prędkość')
    plt.plot(times, kalman_speed, label='Estymowana prędkość')
    plt.xlabel('czas (s)')
    plt.ylabel('prędkość (m/s)')
    plt.legend()
    plt.title('Prędkość')
    plt.savefig('speed.png')
    plt.clf()
    plt.plot(times[200:400], real_speed[200:400], label='Faktyczna prędkość')
    plt.plot(times[200:400], kalman_speed[200:400], label='Estymowana prędkość')
    plt.legend()
    plt.xlabel('czas (s)')
    plt.ylabel('szybkość (m/s)')
    plt.title('Szybkość 2s-4s')
    plt.savefig('speed24.png')
    plt.clf()

    plt.plot(times, measured_error, label='Błąd odczytu położenia')
    plt.plot(times, kalman_error, label='Błąd estymacji położenia filtrem Kalmana')
    plt.xlabel('czas (s)')
    plt.ylabel('błąd (m)')
    plt.legend()
    plt.title('Przebieg błędu')
    plt.savefig('error.png')
    plt.clf()
    plt.plot(times[200:400], measured_error[200:400], label='Błąd odczytu położenia')
    plt.plot(times[200:400], kalman_error[200:400], label='Błąd estymacji położenia filtrem Kalmana')
    plt.legend()
    plt.xlabel('czas (s)')
    plt.ylabel('błąd (m)')
    plt.title('Przebieg błędu pomiędzy 2 a 4 sekundą ruchu')
    plt.savefig('error24.png')
    plt.clf()

def num_iters(T, h):
    return int(math.ceil(T/h))

def simulate(velocity_list, T, kp, ki, kd):
    timestep = 0.01
    iters = num_iters(T, timestep)
    iter_change = round(iters / len(velocity_list))
    last_velocity_index = 0

    u_max = 4
    accelnoise = 0.06
    x0 = np.array([[0], [0]])
    A = np.array([[1, timestep], [0, 1]])
    B = np.array([[1/2 * (timestep ** 2)], [timestep]])
    C = np.array([[1, 0]])
    measnoise = 3

    v_zadane = velocity_list[last_velocity_index]

    Sz = measnoise ** 2
    Sw = accelnoise ** 2 * np.array([[timestep ** 4 / 4, timestep ** 3 / 2], [timestep ** 3 / 2, timestep ** 2]])
    P = Sw

    errors = np.zeros(iters)
    errorSum = errors[0] * timestep
    u_val = np.zeros(iters)

    xhat = x0
    state_history = np.zeros((iters, 2, 1))
    kalman_history = np.zeros((iters, 2, 1))
    state_history[0] = x0
    kalman_history[0] = xhat
    measurement_history = np.zeros(iters)
    for i in range(iters - 1):
        error = v_zadane - xhat[1]
        errorSum += (error * timestep)
        u = kp * error + ki * errorSum
        if(u > u_max):
            u = u_max
        errors[i + 1] = error
        u_val[i + 1] = u

        if i % iter_change == 0 and i != 0 :
            last_velocity_index += 1
            v_zadane = velocity_list[last_velocity_index]

        process_noise = accelnoise * np.array([[1/2 * (timestep**2) * np.random.normal()], [timestep * np.random.normal()]])
        x = A@(state_history[i]) + B*u + process_noise
        measure_noise = np.random.normal() * measnoise
        y = C @ x + measure_noise

        xhat = A @ xhat + B * u
        inn = y - C @ xhat
        s = C @ P @ C.T + Sz
        K = A @ P @ C.T @ np.linalg.inv(s)
        xhat = xhat + K @ inn
        P = A @ P @ A.T - A @ P @ C.T @ np.linalg.inv(s) @ C @ P @ A.T + Sw
        kalman_history[i+1] = xhat
        state_history[i+1] = x
        measurement_history[i+1] = y

    return state_history, measurement_history, np.arange(0, T, timestep), kalman_history, errors, u_val

def test_statistically():
    errors_test = np.zeros((1000, 10000))
    errors_test_kalman = np.zeros((1000, 10000))
    for i in range(1000):
        print(i)
        history, measurement_history, times, kalman, _, _ = simulate([10, 20, 30, 10], 100, 1, 0.1, 0)
        errors = measurement_history - np.squeeze(history[:, 0, :])
        error_after = np.squeeze(kalman[:, 0, :]) - np.squeeze(history[:, 0, :])
        errors_test[i] = errors
        errors_test_kalman[i] = error_after

    errors_avg = np.average(np.abs(errors_test))
    errors_kalman_avg = np.average(np.abs(errors_test_kalman))

    errors_std_dev = np.std(errors_test)
    errors_kalman_std_dev = np.std(errors_test_kalman)
    return errors_avg, errors_std_dev, errors_kalman_avg, errors_kalman_std_dev

if __name__ == '__main__':
    # test_statistically()

    history, measurement_history, times, kalman, _, _ = simulate([10, 20, 30, 10], 100, 1, 0.1, 0)
    errors = measurement_history - np.squeeze(history[:, 0, :])
    error_after = np.squeeze(kalman[:, 0, :]) - np.squeeze(history[:, 0, :])

    save_plots(history[:, 0, :], measurement_history, kalman[:, 0, :], history[:, 1, :], kalman[:, 1, :],
               errors, error_after, times)

    kalman_errors = error_after
    measured_errors = errors
    velocities = np.squeeze(history[:, 1, :])
    kalman_velocities = np.squeeze(kalman[:, 1, :])
    visualizer = KalmanFilterVisualizer(measured_errors, kalman_errors, velocities, kalman_velocities, 100)
    visualizer.run()


import yaml
import os

def make_yaml(dest):
    train_yaml = dict(
        train =f'{dest}/train',
        val =f'{dest}/val',
        test=f'{dest}/test',
        nc =1,
        names =['ship',]
    )

    with open(os.path.join(dest,'train.yaml'), 'w') as outfile:
        yaml.dump(train_yaml, outfile, default_flow_style=True)


# -*- coding: UTF-8 -*-
from sys import argv
import dask.dataframe as dd
import logging
from datetime import datetime
import time

try:
    data_argv = argv
except IndexError as e:
    logging.error("Run script must with parameter")
    print('Run script must with parameter')
    exit('1')
    raise e

VERSION = 16.0

# ОКРУЖЕНИЕ
PROD = True

if PROD:
    # Путь к файлу для обработки:
    path_to_file_Commercial = "D:\\Export\\DP\\Commercial\\"
    path_to_file_PnL = "D:\\Export\\DP\\PnL\\"
    path_to_file_Calendar_shift = "D:\\Export\\DP\\Calendar_shift\\"
    path_to_file_Efficiency = "D:\\Export\\DP\\Efficiency\\"
    #  main .log file
    path_to_log = "D:\\HyperLog\\DP\\pyConvert.log"
else:
    path_to_file_Commercial = "C:\\Users\\60001240\\Desktop\\DP\\Commercial\\"
    path_to_file_PnL = "C:\\Users\\60001240\\Desktop\\DP\\PnL\\"
    path_to_file_Calendar_shift = "C:\\Users\\60001240\\Desktop\\DP\\Calendar_shift\\"
    path_to_file_Efficiency = "C:\\Users\\60001240\\Desktop\\DP\\Efficiency\\"
    path_to_log = "pyConvert.log"

# Название файлов по выгрузки
#  Коммерческие показатели
list_name_Commercial = [
    "CE_Commercial_TSC_Day.txt",
    "CE_Commercial_CPC_Month.txt",
    "CE_Commercial_CPC_Day.txt",
    "CE_Commercial_NoCPC_Day.txt",
    "CE_Commercial_TSC_Month.txt",
    "CE_Commercial_NoCPC_Month.txt"
]
#  CЧёт эксплуатации
list_name_PnL = [
    "CE_PnL_CPC_Month.txt",
    "CE_PnL_NoCPC_Month.txt"
]
Calendar_shift = [
    "CE_Calendar_shift.txt"
]
# Эффективность
list_name_Efficiency = [
    "CE_Efficiency_Month.txt"
]

#  Лог
logging.basicConfig(filename=path_to_log, level=logging.INFO)

# Функция конвертирует данные и проверяет кол-во записей.
def main(filename, path):
    print(filename)
    today = datetime.now()
    start_job = time.time()
    # Проверка типа поля DATA -> INT в CE_Calendar_shift.
    if filename == "CE_Calendar_shift.txt":
        df = dd.read_csv(path + filename, delimiter=';', encoding='1251')
        # Конвертируем в INT
        df[df.columns[14]] = df[df.columns[14]].astype('int64')
        # Конвертируем в INT название столбца, чтобы не потерялось первое значение.
        df = df.rename(columns={df.columns[14]: int(float(df.columns[14]))})
        count_txt = df.shape[0].compute() + 1
        df.to_csv(path + filename.replace(".txt", ".csv"), sep=";", index=False, single_file=True)
    else:
        df = dd.read_csv(path + filename, delimiter=';', dtype=str)
        # count all  lines.
        count_txt = df.shape[0].compute() + 1
        df.to_csv(path + filename.replace(".txt", ".csv"), sep=";", index=False, single_file=True)
        # Путь к файлу
        df = dd.read_csv(path + filename, delimiter=';', dtype=str)
        # Убираю доп. ковычки
        df.to_csv(path + filename.replace(".txt", ".csv"), sep=";", index=False, single_file=True)
    '''Сверка по кол-ву: txt == csv'''
    df_new = dd.read_csv(path + filename, delimiter=';', dtype=str)
    count_csv = df_new.shape[0].compute() + 1
    if count_txt == count_csv:
        print(f' count_txt {count_txt}  == count_csv {count_csv}')
    else:
        print(f' count_txt {count_txt} <> count_csv {count_csv}')
        logging.error("count_csv != count_csv")
        return 1  # 1 не сработало.

    #  В ЛОГ
    total_string = format(round(time.time() - start_job, 2))
    now_string = today.strftime("%d/%m/%Y %H:%M:%S")
    output = now_string + ';' + total_string + ";" + filename.replace(".txt",
                                                                      ".csv") + ";" + str(
        count_csv)
    # Add line to pyConvert.log
    logging.info(output)
    print(filename.replace(".txt", ".csv"))
    del df
    del df_new
    return 0  # 0 - всё ОК.

if __name__ == '__main__':
    start_time = time.time()
    try:
        now = datetime.now()
        dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
        # Обрабатываем каждую папку отдельно:Commercial
        if data_argv[1] == 'Commercial':
            for file in list_name_Commercial:
                main(filename=file, path=path_to_file_Commercial)

        #  Обрабатываем каждую папку отдельно: PnL
        if data_argv[1] == 'PnL':
            for file in list_name_PnL:
                main(filename=file, path=path_to_file_PnL)

        # Календарный сдвиг
        if data_argv[1] == 'Calendar_shift':

            for file in Calendar_shift:
                main(filename=file, path=path_to_file_Calendar_shift)

                #  Обрабатываем каждую папку отдельно: Efficiency
        if data_argv[1] == 'Efficiency':
            for file in list_name_Efficiency:
                main(filename=file, path=path_to_file_Efficiency)

        if not data_argv[1] == 'Efficiency' and \
           not data_argv[1] == 'Calendar_shift' and \
           not data_argv[1] == 'PnL' and \
           not data_argv[1] == 'Commercial':
            logging.error(f'Wrong data_argv {data_argv}')
            print(f'Used to: https://github.com/nvetrov/DP ')
            print('-----------------------------')
            print(f'py .\main.py Commercial')
            print(f'py .\main.py PnL')
            print(f'py .\main.py Calendar_shift')
            print(f'py .\main.py Efficiency')
            print(f'-------------------------------------')
            exit('1')

    except EOFError as e:
        # print("Caught the EOF error.")
        logging.error("Caught the EOF error")
        raise e
    except IOError as e:
        logging.error("Caught the I/O error")
        raise e
    except IndexError as e:
        logging.error(f'Run script must with parameter')
        print('Run script must with parameter: ')
        exit('1')
        raise e


from typing import Union, Dict

import wikipediaapi

class Wikipedia:
    def __init__(self, query) -> None:
        wiki_wiki = wikipediaapi.Wikipedia("en")
        self.page_py = wiki_wiki.page(query)

    @property
    def get_information(self) -> Union[Dict, bool]:
        try:
            if self.page_py.exists():
                return {"title": self.page_py.title, "summary": self.page_py.summary[0:60]}
            else:
                return False
        except Exception as e:
            print(f"error: {e}")
            return False


lista_nome = []
lista_peso = []

while True:
    nome = str(input('Digite o nome: '))
    peso = float(input('Digite o peso: '))
    continuar = str(input('Deseja continuar: [S/N]: ')).strip().lower()[0]
    lista_nome.append(nome)
    lista_peso.append(peso)
    zipped = zip(lista_nome, lista_peso)
    lista_zipped = list(zipped)
    max_peso = max(lista_peso)
    min_peso = min(lista_peso)
    nome_max = []
    nome_min = []
    peso_max = []
    peso_min = []
    for n, p in lista_zipped:
        if p == max_peso:
            peso_max.append(p)
            nome_max.append(n)
        if p == min_peso:
            peso_min.append(p)
            nome_min.append(n)
    if continuar == 's':
        continue
    if continuar == 'n':
        break

print(f'O total de pessoas cadastradas foram {len(lista_nome)}.')
print(f'As pessoas com maior peso de chamam {nome_max} e pesam {peso_max[0]}kg cada uma.')
print(f'As pessoas com menor peso se chamam {nome_min} e pesam {peso_min[0]}kg cada uma.')


N, M = list(map(int, input().split()))
grazing = []
for i in range(M):
    grazing.append(list(map(int, input().split())))
grazing.sort()

def distance(mid):
    # number of cows in grazing area placed atleast mid distance
    cows = 0
    # position of previous

l = 0
r = 1000000
while(l+1 < r):
    mid = (l+r)//2
    if distance(mid):
        l = mid
    else:
        r = mid
print(l)


#!/usr/bin/env python3

import psycopg2
from faker import Faker
import random

USERS = 10

def populate(cur, conn):
    conn.autocommit = True
    cur.execute("drop table if exists users")
    cur.execute("drop table if exists addresses")
    conn.autocommit = False
    fake = Faker()
    def populate_users(cur, con):
        cur.execute("""
    CREATE TABLE IF NOT EXISTS users (
        id serial,
        name  varchar,
        dob DATE,
        primary key(id))
        """)
        con.commit()
        for _ in range(USERS):
            cursor.execute(f"""
            INSERT INTO users(name, dob) VALUES('{fake.name()}', '{fake.date_of_birth()}')
            """)
        conn.commit()
    def populate_addresses(cur, con):
        cur.execute("""
    CREATE TABLE IF NOT EXISTS addresses(
        id int,
        address varchar)
        """)
        conn.commit()
        fake = Faker()
        for i in range(USERS - 1):
            cursor.execute(f"""
            INSERT INTO addresses(id, address) VALUES('{i+1}', '{fake.address()}')
            """)
        # some users have more than one address
        for _ in range(3):
            cursor.execute(f"""
            INSERT INTO addresses(id, address) VALUES('{random.randint(1, USERS - 1)}', '{fake.address()}')
            """)
    populate_users(cur, conn)
    populate_addresses(cur, conn)

def printrecords(f):
    def wrapper(cursor):
        f(cursor)
        for i in cursor:
            print(i)
        print()
    return wrapper

@printrecords
def fetch(cursor):
    cursor.execute("""
    SELECT users.id, users.name, addresses.address  FROM users
    inner join addresses
    on users.id  = addresses.id
    order by users.id
    """)

@printrecords
def fetchjoin(cursor):
    cursor.execute("""
    SELECT users.id, users.name, addresses.address  FROM users
    left join addresses
    on users.id  = addresses.id
    order by users.id
    """)

@printrecords
def homeless(cursor):
    cursor.execute("""
    SELECT users.id, users.name FROM users
    where (select count(id) from  addresses where id = users.id) = 0
    """)

with psycopg2.connect(user = "dima",
                      database = "dima") as connection:
    with connection.cursor() as cursor:
        populate(cursor, connection)
        fetch(cursor)
        fetchjoin(cursor)
        homeless(cursor)


# coding=utf-8
import os
import glob
from biocluster.agent import Agent
from biocluster.tool import Tool
from biocluster.core.exceptions import OptionError
import unittest
__author__ = 'zjx'

class DownloadAgent(Agent):
    """
    Expression clustering analysis
    """
    def __init__(self, parent):
        super(DownloadAgent, self).__init__(parent)
        options = [
            {'name': 'id', 'type': 'string'},
            {'name': 'id_list', 'type': 'infile', 'format': 'ref_rna_v2.common'},
            # {'name': 'output', 'type': 'outfile', 'format': 'ref_rna_v2.dir'},
        ]
        self.add_option(options)

    def check_options(self):
        pass

    def set_resource(self):
        self._cpu = 1
        self._memory = "{}G".format('10')

    def end(self):
        super(DownloadAgent, self).end()

class DownloadTool(Tool):
    """
    Expression clustering analysis
    """
    def __init__(self, config):
        super(DownloadTool, self).__init__(config)
        software_dir = self.config.SOFTWARE_DIR
        self.python_path = 'miniconda2/bin/python'
        self.download_path = self.config.PACKAGE_DIR + '/prok_rna/download4ncbi.py'
        self.miniconda = software_dir + '/miniconda2/bin'
        self.set_environ(PATH=self.miniconda)

    def id_list(self):
        with open(os.path.join(self.work_dir, 'ID_list'), 'w') as i:
            i.write(self.option('id') + '\n')

    def download(self):
        cmd = '{} {}'.format(self.python_path, self.download_path)
        cmd += ' -ID_list {}'.format(os.path.join(self.work_dir, 'ID_list'))
        cmd += ' -output {}'.format(self.output_dir)
        cmd += ' -sorfware {}'.format(self.config.SOFTWARE_DIR)
        cmd_name = 'download4ncbi'
        command = self.add_command(cmd_name, cmd)
        command.run()
        self.wait()
        if command.return_code == 0:
            self.logger.info("{} Finished successfully".format(cmd_name))
        elif command.return_code is None:
            self.logger.warn("{} Failed and returned None, we will try it again.".format(cmd_name))
            command.rerun()
            self.wait()
            if command.return_code is 0:
                self.logger.info("{} Finished successfully".format(cmd_name))
            else:
                self.set_error("%s Failed. >>> %s", variables = (cmd_name, cmd), code = "35002902")
        else:
            self.set_error("%s Failed. >>> %s", variables = (cmd_name, cmd), code = "35002903")

    def check_filelist(self):   # added by zhangyitong on 20210903
        with open(os.path.join(self.work_dir, 'file.txt'), 'r') as f:
            genome_id, fna, gff, report = f.readline().strip().split('\t')
        if fna == '-':
            self.set_error('{}该物种ID下缺失fna文件。'.format(genome_id))
        elif gff == '-':
            self.set_error('{}该物种ID下缺失gff/gtf文件。'.format(genome_id))
        elif report == '-':
            self.set_error('{}该物种ID下缺失组装报告文件。'.format(genome_id))

    def set_output(self):
        pass

    def run(self):
        super(DownloadTool, self).run()
        self.id_list()
        self.download()
        self.check_filelist()
        self.set_output()
        self.end()

class TestFunction(unittest.TestCase):
    """
    This is test for the tool. Just run this script to do test.
    """
    def test(self):
        import random
        from mbio.workflows.single import SingleWorkflow
        from biocluster.wsheet import Sheet
        data = {
            "id": "download4ncbi" + str(random.randint(1, 10000)),
            "type": "tool",
            "name": "prok_rna.download4ncbi.download",
            "instant": False,
            "options": dict(
                id='GCF_004214875.1',
            )
           }
        wsheet = Sheet(data=data)
        wf = SingleWorkflow(wsheet)
        wf.run()

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


from setuptools import setup

with open("README.md", "r", encoding="utf-8") as f_p:
    long_description = f_p.read()

setup(
    name='psda',
    version='1.0.0',
    packages=['psda', 'psda.stats', 'psda.io_data', 'psda.process'],
    license='MIT LICENSE',
    author='Paweł Rajkiewicz',
    author_email='pr382959@students.mimuw.edu.pl',
    description='Polish School Data Analyser is a small package made as a final assignment'
                'in Data in Python course at MIMUW, Spring 20/21.',
    long_description=long_description,
    long_description_content_type="text/markdown",
    install_requires=[
        "pandas>=1.2.5",
        "numpy>=1.21",
        "xlrd>=2.0.1",
        "openpyxl>=3.0.7"
    ],
    python_requires='>=3.8'
)


import re
import threading
import time
from typing import Any, cast, Callable, Dict, Optional

# Dependencies of salesforce.dbapi on Django are minimalized.
# The biggest challenges are django.conf.settings, django.db.connections and django.test.

try:
    settings = None  # type: Any
    from django.conf import settings
except ImportError:
    # mock for some tests without a real Django
    import importlib
    import os

    settings = importlib.import_module(os.environ['DJANGO_SETTINGS_MODULE'])

    if not getattr(settings, 'SF_CAN_RUN_WITHOUT_DJANGO', False):
        raise

def get_max_retries() -> int:
    """Get the maximal number of requests retries

    The maximal number of retries for timeouts in requests to Force.com API.
    Can be set dynamically
    None: use defaults from settings.REQUESTS_MAX_RETRIES (default 1)
    0: no retry
    1: one retry
    """
    return getattr(settings, 'REQUESTS_MAX_RETRIES', 1)  # type: ignore[no-any-return] # noqa

def get_thread_connections() -> Dict[Optional[str], Any]:
    if not hasattr(thread_loc, 'connections'):
        thread_loc.connections = {}
    return cast(Dict[Optional[str], Any], thread_loc.connections)

class TimeStatistics:

    def __init__(self, expiration: float = 300) -> None:
        self.expiration = expiration
        self.data = {}  # type: Dict[str, float]

    def update_callback(self, url: str, callback: Optional[Callable[[], Any]] = None) -> None:
        """Update the statistics for the domain"""
        domain = self.domain(url)
        last_req = self.data.get(domain, 0)
        t_new = time.time()
        do_call = (t_new - last_req > self.expiration)
        self.data[domain] = t_new
        if do_call and callback:
            callback()

    @staticmethod
    def domain(url: str) -> str:
        match = re.match(r'^(?:https|mock)://([^/]*)/?', url)
        assert match, "HOST must be including the protocol and :// like 'https://login.salesforce.com'"
        return match.groups()[0]

time_statistics = TimeStatistics(300)
thread_loc = threading.local()


#!/usr/bin/env python
"""
Demo microservice that records player events.
"""
import os
from optparse import OptionParser
from flask import request
from flask_api import FlaskAPI, exceptions
from cassandra.cluster import Cluster
from structures import DynamicActionArray
from util import parse_timesamp, parse_action, cassandra_insert
import settings

parser = OptionParser()
parser.add_option("-p", "--port", dest="port",
                  default=settings.LOCAL_SERVER_PORT,
                  help="Port to listen on", type="int")
parser.add_option("-l", "--listen", dest="listen",
                  default=settings.LOCAL_SERVER_IP,
                  help="Address to listen on", type="string")

# FlaskAPI has an eye candy browser view
app = FlaskAPI(__name__)
data = DynamicActionArray(settings.ACTION_ARRAY_INIT_SIZE,
                          settings.ACTION_GROW_FACTOR,
                          settings.SCORE_VALUES)

# Cassandra startup
if settings.CASSANDRA_SUPPORT:
    cluster = Cluster(settings.CASSANDRA_CLUSTER_IPS)
    session = cluster.connect(settings.CASSANDRA_KEYSPACE)

@app.route('/', methods=['GET'])
def server_status():
    """
    Display server status!
    """
    return {'description': 'Stats Microservice',
            'records': data.length,
            'load': os.getloadavg()}

@app.route('/user/<int:uid>/', methods=['GET', 'POST'])
def user_stats(uid):
    """
    Insert and query user events.
    """
    if request.method == 'POST':
        try:
            timestamp = parse_timesamp(request.data.get('timestamp', ''))
            action = parse_action(request.data.get('action', ''), min_action=1,
                                  max_action=len(settings.SCORE_VALUES))
            data.append(uid, action, timestamp)
            if settings.CASSANDRA_SUPPORT:
                cassandra_insert(session, uid, action, timestamp)
            return {'message': 'ok'}
        except Exception as ex:
            raise exceptions.ParseError(
                detail='{}: {}'.format(ex.__class__.__name__, ex.message))

    if request.method == 'GET':
        try:
            start = parse_timesamp(request.args.get('start', ''))
            end = parse_timesamp(request.args.get('end', ''))
            return data.query(uid, start, end)
        except Exception as ex:
            raise exceptions.ParseError(
                detail='{}: {}'.format(ex.__class__.__name__, ex.message))

if __name__ == '__main__':
    app.debug = settings.LOCAL_SERVER_DEBUG
    (options, args) = parser.parse_args()
    app.run(host=options.listen, port=options.port)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import webbrowser
import urllib
from urllib.parse import quote
import re

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = "192.168.224.171" if s.getsockname()[0] != "192.168.224.171" else "localhost"
s.close()

def mysearch(z):
    s = 'http://go.mail.ru/search?fm=1&q='+quote(z)
    doc = urllib.request.urlopen(s).read().decode('cp1251',errors='ignore')
    o=re.compile('"url":"(.*?)"')
    l=o.findall(doc)
    sp=[]
    for x in l:
        if((x.rfind('youtube')==-1) and(x.rfind('yandex')==-1) and(x.rfind('mail.ru')==-1) and(x.rfind('.jpg')==-1) and(x.rfind('.png')==-1) and(x.rfind('.gif')==-1)):
            sp.append(x)
    sp = dict(zip(sp, sp)).values()
    sp1=[]
    for x in sp: sp1.append(x)
    return sp1

def __ShutDown__():
	os.system('shutdown -s')
def __YTOpen__():
	webbrowser.open("http://youtube.com")
	return 1
def __VKOpen__():
	webbrowser.open("http://vk.com")
	return 1
def __cinema__():
	try :
		with urllib.request.urlopen("http://"+main.ip+"/api/other.php?desktop") as url:
			data = json.loads(url.read().decode())
	except BaseException:
		print("except")
		return "0"
	else:
		return data["plus"]

	webbrowser.open(mysearch('смотреть+онлайн+фильм+железний человек 1')[1])
	return 1


import numpy as np
import matplotlib.pyplot as plt

def relative_error(x0, x): return np.abs(x0-x)/np.abs(x0)

eps=np.finfo(np.double).eps
print("Машинная точность:", eps)

print(1 < np.inf)

def plot_error(x0,err):
    mask=np.logical_and(err>0,err<np.inf)
    plt.loglog(x0[mask],err[mask],".k")
    plt.loglog(x0,[eps]*len(err),"--r") # машинная точность для сравнения
    plt.xlabel("$Значение\;аргумента$")
    plt.ylabel("$Относительная\;погрешность$")
    plt.show()

def f_sqrt_sqr(x, n=52):
    for k in range(n): x=np.sqrt(x)
    for k in range(n): x=x*x
    return x

def my_sqrt_sqr(x, n = 10):
    for k in range(n):
        x = np.exp(2 * np.log(x))
        x = np.exp(0.5 * np.log(x))
    return x

x0=np.logspace(-4,4,100)
x = my_sqrt_sqr(x0)
err = relative_error(x0, x)
plot_error(x0, err)


class Solution(object):
    def merge(self, nums1, m, nums2, n):
        """
        :type nums1: List[int]
        :type m: int
        :type nums2: List[int]
        :type n: int
        :rtype: None Do not return anything, modify nums1 in-place instead.
        """
        i, j = 0, 0
        while i < len(nums1) and j < len(nums2):

            print(f"i: {i}, {nums1[i]}, j: {j} {nums2[j]}")
            if nums1[i] <= nums2[j]:
                # siply go to the next number in the first array
                i += 1
            else:
                nums1.insert(i, nums2[j])
                nums1.pop()
                j += 1
                i += 1

        while j < len(nums2):
            nums1[i] = nums2[j]
            i += 1
            j += 1

nums1 = [1, 2, 3, 0, 0, 0]
nums2 = [2, 5, 6]
m = 3
n = 3
obj = Solution()
result = obj.merge(nums1, m, nums2, n)
print(result)
# Output: [1, 2, 2, 3, 5, 6]


from __future__ import absolute_import

from flytekit.common.notifications import PagerDuty
from flytekit.common.schedules import CronSchedule
from flytekit.common.types.primitives import String, Integer, Boolean
from flytekit.models.core.execution import WorkflowExecutionPhase
from flytekit.sdk.tasks import (
    python_task,
    inputs,
    outputs,
)
from flytekit.sdk.types import Types
from flytekit.sdk.workflow import workflow_class, Input, Output

PAGE_ON_FAILURE_IN_PRODUCTION = PagerDuty(
    phases=[WorkflowExecutionPhase.FAILED, WorkflowExecutionPhase.TIMED_OUT],
    recipients_email=["testservice-low-urgency@lyft.pagerduty.com"],
)

TEST_CRON_SCHEDULE = CronSchedule("0/15 * * * ? *")

@inputs(list_of_nums=[Types.Integer])
@outputs(are_num_odd=[Types.Boolean])
@python_task(cache_version='1')
def find_odd_numbers(wf_params, list_of_nums, are_num_odd):
    if wf_params and wf_params.logging:
        wf_params.logging.info("Running find_odd_nums python task")
    output_list = []
    for num in list_of_nums:
        b = num % 2 == 1
        output_list.append(b)
        if wf_params and wf_params.logging:
            wf_params.logging.info("Number {} is odd? {}".format(num, b))
    are_num_odd.set(output_list)

@workflow_class()
class OnePythonTaskWF(object):
    odd_nums_task = find_odd_numbers(list_of_nums=[2, 3, 4, 7])
    task_output = odd_nums_task.outputs.are_num_odd

onePythonTaskLP = OnePythonTaskWF.create_launch_plan(schedule=TEST_CRON_SCHEDULE,
                                                     notifications=[PAGE_ON_FAILURE_IN_PRODUCTION])

@inputs(list_of_nums=[Types.Integer], demo_string=Types.String)
@outputs(are_num_odd=[Types.Boolean], altered_string=Types.String)
@python_task(cache_version='1')
def find_odd_numbers_with_string(wf_params, list_of_nums, demo_string, are_num_odd, altered_string):
    if wf_params and wf_params.logging:
        wf_params.logging.info("Running find_odd_nums python task")
    output_list = []
    for num in list_of_nums:
        b = num % 2 == 1
        output_list.append(b)
        if wf_params and wf_params.logging:
            wf_params.logging.info("Number {} is odd? {}".format(num, b))
    are_num_odd.set(output_list)
    altered_string.set(demo_string + '_changed')

@workflow_class()
class WorkflowWithIO(object):
    a = Input(Types.Integer, default=10, help="Test integer input with default")
    b = Input(Types.String, required=True, help="Test string with no default")
    odd_nums_task = find_odd_numbers_with_string(list_of_nums=[2, 3, 4, 7], demo_string=b)
    task_output = Output(odd_nums_task.outputs.are_num_odd, sdk_type=[Boolean])
    output_a = Output(a, sdk_type=Integer)  # pass through output
    output_b = Output(odd_nums_task.outputs.altered_string, sdk_type=String)


import random as rd
import hangman_art as ha
import hangman_words as hw
from replit import clear

print(ha.logo)
word_list = hw.word_list
stages = ha.stages
chosen_word = rd.choice(word_list)
chosen_word_len = len(chosen_word)

# Blank display
print(chosen_word)
display = []
for bar in range(chosen_word_len):
    display.append("_")
print(f"{' '.join(display)}")

end_of_game = False
lives = 6
while not end_of_game:
    user_guess = input("\nGuess a letter: ").lower()
    clear()
    if user_guess in display:
        print(f"\n{user_guess}, You've already tried this one! Try Another One :(")
    for letter in range(chosen_word_len):
        if user_guess == chosen_word[letter]:
            display[letter] = user_guess

    if "_" not in display:
        print("\n\t You've Won :) \n")
        end_of_game = True
        break

    elif user_guess not in chosen_word:
        print(f"\n{user_guess}, doesn't fits! Try Another One :(")
        lives -= 1
        print(f"{stages[lives]}")
        if lives == 0:
            print("\n\t You Lose :( \n")
            print(f"Word: {chosen_word}")
            end_of_game = True
            break

    print(f"{' '.join(display)}")


from .cryptomath import divceil

class Poly1305(object):

    """Poly1305 authenticator"""

    P = 0x3fffffffffffffffffffffffffffffffb # 2^130-5

    @staticmethod
    def le_bytes_to_num(data):
        """Convert a number from little endian byte format"""
        ret = 0
        for i in range(len(data) - 1, -1, -1):
            ret <<= 8
            ret += data[i]
        return ret

    @staticmethod
    def num_to_16_le_bytes(num):
        """Convert number to 16 bytes in little endian format"""
        ret = [0]*16
        for i, _ in enumerate(ret):
            ret[i] = num & 0xff
            num >>= 8
        return bytearray(ret)

    def __init__(self, key):
        """Set the authenticator key"""
        if len(key) != 32:
            raise ValueError("Key must be 256 bit long")
        self.acc = 0
        self.r = self.le_bytes_to_num(key[0:16])
        self.r &= 0x0ffffffc0ffffffc0ffffffc0fffffff
        self.s = self.le_bytes_to_num(key[16:32])

    def create_tag(self, data):
        """Calculate authentication tag for data"""
        for i in range(0, divceil(len(data), 16)):
            n = self.le_bytes_to_num(data[i*16:(i+1)*16] + b'\x01')
            self.acc += n
            self.acc = (self.r * self.acc) % self.P
        self.acc += self.s
        return self.num_to_16_le_bytes(self.acc)


filename = input("Enter the file name: ")

vowels = ["a", "e", "i", "o", "u"]
count = 0

with open(filename, "r") as file:
    for line in file:
        words = line.split()
        for word in words:
            if word[0].lower() in vowels:
                count += 1

print(f"Number of words that start with a vowel: {count}")


# A number, a, is a power of b if it is divisible by b and a/b is a power of b.
# Write a function called is_power that takes parameters a and b and
# returns True if a is a power of b.

def isp(a,b):
    if a%b==0 and isp(a/b,b):
        return True
    elif a/b==b:
        return True
    else:
        return False

x = 4
y = 2
print(isp(x, y))


import tkinter as tk
from tkinter import *
import phonenumbers

from phonenumbers import geodata, geocoder, carrier

root = tk.Tk()
root.geometry('300x400')
root.title('phone number tracker')

# code for clearing the textarea and entry_box
def clear():
    ent_1.delete(0, END)
    tex_area1.delete(1.0, END)

def check():
    ch = phonenumbers.parse(ent_1, 'EN')
    p = (geocoder.description_for_number(ch, 'eo'))
    print(len(p))
    service_name = phonenumbers.parse(ent_1, 'we')
    tex_area1.get(carrier.name_for_number(service_name, 'ru'))

lab_1 = Label(root, text='ENTER THE PHONE NUMBER(+...) ', bg='red', fg='white')
lab_1.place(x=44, y=10)

# entry for inputing the phone number
ent_1 = Entry(root)
ent_1.place(x=55, y=40)

# text_area for showing the information required
tex_area1 = Text(root, height=10, width=20)
tex_area1.place(x=55, y=125)

lab_1 = Label(root, text='THE INFORMATION WILL BE DISPLAY BELOW: ', bg='red', fg='white')
lab_1.place(x=44, y=100)

# CLEAR BUTTON
cle_1 = Button(root, text='clear', bg='blue', fg='whitesmoke', command=clear)
cle_1.place(x=44, y=310)

# exit BUTTON
exit_1 = Button(root, text='Exit', bg='blue', fg='whitesmoke')
exit_1.place(x=84, y=310)

# Check BUTTON
chk_1 = Button(root, text='Check', bg='blue', fg='whitesmoke', command=check)
chk_1.place(x=124, y=310)

root.mainloop()


import os
import semver
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.python.ops.gen_batch_ops import batch

def get_metadata(project_id):
    output_dir = os.path.join('.', 'output', project_id)
    image_mode = 'unknown'
    if project_id == 'mnist' or project_id == 'fashion_mnist':
        image_mode = 'greyscale'
    if project_id == 'pokemon':
        image_mode = 'rgb'
    return {
        'img_output_dir': os.path.join(output_dir, 'images'),
        'ckpt_output_dir': os.path.join(output_dir, 'checkpoints'),
        'image_mode': image_mode,
        'batch_size': 64
    }

def check_gpu(logger):
    os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
    os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
    gpus = tf.config.list_physical_devices('GPU')
    logger.info('Found Tensorflow with version ' + str(tf.__version__))
    logger.info('Found GPU: ' + str(len(gpus)))
    logger.info('Check GPU done.')

def create_directory_if_not_exist(directory_name):
    if not os.path.exists(directory_name):
        os.makedirs(directory_name)

def restore_previous_checkpoint(ckpt, ckpt_manager, ckpt_location, logger):
    if semver.compare(str(tf.__version__), "2.2.0") >= 0:
        ckpt_manager.restore_or_initialize()
    else:
        if os.path.exists(ckpt_location) and len(ckpt_manager.checkpoints) > 0:
            ckpt.restore(ckpt_manager.latest_checkpoint)
        else:
            logger.info('Checkpoint location not found. Skip.')
    logger.info('Restore checkpoint done.')

def generate_img(gen, gen_input, epoch, sample_size, img_output_dir, visualize):
    preds = gen(gen_input)
    fig = plt.figure(figsize=(sample_size, 1))
    fig, axs = plt.subplots(sample_size, sample_size)
    for i in range(sample_size):
        for j in range(sample_size):
            visualize(preds, axs[i, j], i * sample_size + j)
    save_loc = os.path.join(img_output_dir, 'epoch_{0}'.format(epoch+1))
    create_directory_if_not_exist(save_loc)
    plt.margins(0, 0)
    plt.savefig(os.path.join(save_loc, 'sample.png'))
    plt.close('all')

def discriminator_loss(real, fake):
    real_loss = tf.losses.BinaryCrossentropy(
        from_logits=True)(tf.ones_like(real), real)
    fake_loss = tf.losses.BinaryCrossentropy(
        from_logits=True)(tf.zeros_like(fake), fake)
    return real_loss + fake_loss

def generator_loss(fake):
    return tf.losses.BinaryCrossentropy(from_logits=True)(tf.ones_like(fake), fake)

@tf.function
def train_step(imgs, gen, dis, gen_opt, dis_opt, batch_size, gen_input_generator):
    gen_input = gen_input_generator.next(batch_size)
    with tf.GradientTape() as gen_tape, tf.GradientTape() as dis_tape:
        gen_imgs = gen(gen_input)
        real_out = dis(imgs)
        fake_out = dis(gen_imgs)
        gen_loss = generator_loss(fake_out)
        dis_loss = discriminator_loss(real_out, fake_out)
    gen_grads = gen_tape.gradient(gen_loss, gen.trainable_variables)
    dis_grads = dis_tape.gradient(dis_loss, dis.trainable_variables)
    gen_opt.apply_gradients(zip(gen_grads, gen.trainable_variables))
    dis_opt.apply_gradients(zip(dis_grads, dis.trainable_variables))

def train(dataset, gen, dis, gen_opt, dis_opt, logger,
          epochs, start_epoch, interval, sample_size,
          batch_size, train_per_epoch, visualize,
          project_metadata, gen_input_generator):
    ckpt_output_dir = project_metadata['ckpt_output_dir']
    create_directory_if_not_exist(ckpt_output_dir)
    checkpoint = tf.train.Checkpoint(generator_optimizer=gen_opt,
                                     discriminator_optimizer=dis_opt,
                                     generator=gen,
                                     discriminator=dis)
    manager = tf.train.CheckpointManager(
        checkpoint, ckpt_output_dir, max_to_keep=3)
    restore_previous_checkpoint(checkpoint, manager, ckpt_output_dir, logger)
    max_epoch = start_epoch + epochs
    for e in range(start_epoch, max_epoch):
        step_cnt = 0
        for batch in dataset:
            if step_cnt % 25 == 0:
                logger.info(
                    'Epoch {0}/{1}: step {2}'.format(e, max_epoch, step_cnt))
            train_step(
                imgs=batch,
                gen=gen,
                dis=dis,
                gen_opt=gen_opt,
                dis_opt=dis_opt,
                batch_size=batch_size,
                gen_input_generator=gen_input_generator)
            step_cnt += 1
            if step_cnt > train_per_epoch:
                break
        if (e + 1) % interval == 0:
            generate_img(
                gen=gen,
                gen_input=gen_input_generator.next(sample_size**2),
                epoch=e,
                sample_size=sample_size,
                img_output_dir=project_metadata['img_output_dir'],
                visualize=visualize)
            manager.save()
    logger.info('Done')


import pathlib
import pickle
from struct import unpack
from typing import BinaryIO, List, Optional, Tuple, cast
from sklearn import cluster
import pandas as pd
import sys
import numpy as np
import scipy.sparse

def _read_little_endian_crec(file: BinaryIO
                             ) -> Optional[Tuple[int, int, float]]:
    le_int = file.read(16)
    # https://docs.python.org/3/library/struct.html#format-strings
    if len(le_int) == 0:
        return None
    crec = cast(Tuple[int, int, float], unpack('<iid', le_int))
    return crec

def load(cooccurrence_file_content: BinaryIO) -> scipy.sparse.coo_matrix:

    row: List[int] = []
    column: List[int] = []
    data: List[float] = []
    while (cooccurrence_file_content.readable()):
        crec = _read_little_endian_crec(cooccurrence_file_content)
        if crec is None:
            break
        row.append(crec[0])
        column.append(crec[1])
        data.append(crec[2])
    result = scipy.sparse.coo_matrix((data, (row, column)), dtype=np.float64)
    return result

def save_top_nodes(nodelist, filename):
    top_nodes = []
    for j in range(10):  # Pick ten nodes from each cluster, only one should be used. The others are back-up in case the selected node is filtered out (in case of multiple selection strategies)
        for i in range(n_clusters):
            if j < len(np.where(nodelist == i)[0]):
                index = np.where(nodelist == i)[0][j]
                # now match this index to node value:
                raw_value = dict.get(index)
                value = int(raw_value.strip('<').strip('>'))
                top_nodes.append((value,j))  # top_nodes should be of the form [(9677, 1), (2523, 1), ...]
    sys.stdout = original_stdout
    with open(filename, "wb") as fp:  # Pickling
        sys.stdout = fp
        pickle.dump(top_nodes, fp)
        sys.stdout = original_stdout # Reset the standard output to its original value
    return top_nodes

def save_diff_nodes(nodelist, filename):
    diff_nodes = []
    for k in range(10):
        # make a dictionary that contains the cluster label and the frequency of that label
        dict_freq = {}  # key is element, value is frequency
        for i in range(len(nodelist)):
            if nodelist[i] in dict_freq:
                freq = dict_freq[nodelist[i]]
                freq += 1
                dict_freq[nodelist[i]] = freq
            else:
                dict_freq.update({nodelist[i]: 1})
        counter = 0
        while counter < n_clusters:
            highest_value = max(dict_freq, key=dict_freq.get) # pick cluster with highest frequence
            indexes = np.where(nodelist == highest_value)[0]  # use all indexes in that cluster
            if len(indexes) > n_clusters:
                for j in range(n_clusters):  # only select as many anchors as needed
                    raw_value = dict.get(indexes[j])
                    value = int(raw_value.strip('<').strip('>')) # convert indexes to nodes
                    diff_nodes.append((value, k))
            else:
                for index in indexes:
                    raw_value = dict.get(index)
                    value = int(raw_value.strip('<').strip('>'))
                    diff_nodes.append((value, k))  # top_nodes should be of the form [(9677, 1), (2523, 1), ...]
            del dict_freq[highest_value]
            counter += len(indexes)

    with open(filename, "wb") as fp:  # Pickling
        sys.stdout = fp
        pickle.dump(diff_nodes, fp)
        sys.stdout = original_stdout # Reset the standard output to its original value
    return diff_nodes

def create_index_dict():
    dict = {}   #key is index, value is node name
    index = 0
    lines = open("/home/diependaal/KGlove/testInput/wn18rr.nt").readlines()   # Input file containing the knowledge graph triples
    for line in lines:
        line = line.split(' ')
        if line[0] not in dict.values():
            dict.update({index: line[0]})
            index += 1
        if line[2] not in dict.values():
            dict.update({index: line[2]})
            index += 1
    #print(dict)
    return dict

if __name__ == "__main__":
    original_stdout = sys.stdout # Save a reference to the original standard output
    p = pathlib.Path("/home/diependaal/KGlove/output/glove_input_file-testInput_wn18rr_nt-no_literals-forwardWeigher_UniformWeigher-alpha_0.69999999999999996-eps_1.0000000000000001e-05-onlyEntities_no-edges_yes.bin")
    with open(p, 'rb') as file:
        m = load(file)

    array = m.tocsc()
    n_clusters = 500
        # wn18rr has 500 anchor nodes
        # fbb15k237 has 1000 anchor nodes
    dict = create_index_dict()

    # K-means clustering
    k_means = cluster.KMeans(n_clusters=n_clusters)
    clusterlabelslist = k_means.fit_predict(array)    # use fit_predict
    save_top_nodes(clusterlabelslist, "/home/diependaal/KGlove/wn-k-means-500")
    save_diff_nodes(clusterlabelslist, "/home/diependaal/KGlove/wn-diff-k-means-500")

    #Agglomerative clustering, does not take sparse graph.
    array = array.toarray()
    agglomerative = cluster.AgglomerativeClustering(n_clusters=n_clusters, linkage="single")
    clusterlabelslist = agglomerative.fit_predict(array)
    save_top_nodes(clusterlabelslist, "/home/diependaal/KGlove/wn-agglo-500")
    Ssave_diff_nodes(clusterlabelslist, "/home/diependaal/KGlove/wn-diff-agglo-500")


from typing import List

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        l, r, res = 0, len(nums)-1, []
        while l <= r:
            left, right = nums[l]**2, nums[r]**2
            if left > right:
                res.append(left)
                l += 1
            else:
                res.append(right)
                r -= 1
        return res[::-1]

SquidGame/Day8/977. Squares of a Sorted Array.py


# import the necessary packages
#from imutils.video import VideoStream
from imutils.video import FPS
import time
import argparse
import imutils
import cv2
import numpy as np

# open a pointer to the video file
print("[INFO] opening video stream...")
stream = cv2.VideoCapture(0)

# wait 2 seconds for the camera to warm up
time.sleep(2.0)
fps = FPS().start()

# initialize averaged frame
(grabbed,frame) = stream.read()
avgframe = np.float32(frame)

# loop over frames from the video stream
while True:
	# grab the frame from the stream
	(grabbed, frame) = stream.read()

	# if the frame was not grabbed, then break out
	if not grabbed:
		break

	# show the grabbed frame
	cv2.imshow("Live Video", frame)

	key = cv2.waitKey(1) & 0xFF

	# if the `q` key was pressed, break from the loop
	if key == 27:
		break

	# update the FPS counter
	fps.update()

 	# accumulate logic
 	# the alpha parameter (float 0-1) controls how fast the accumulator forgets earlier frames (lower = longer memory)
	cv2.accumulateWeighted(frame, avgframe, 0.02)
	avgframeres = cv2.convertScaleAbs(avgframe)

	# show the averaged frame
	cv2.imshow("Averaged Video", avgframeres)

# stop the timer and display FPS information
fps.stop()
print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))

# do a bit of cleanup
stream.release()
cv2.destroyAllWindows()


# Faça um Programa que peça 2 números inteiros e um número real. Calcule e mostre:
# o produto do dobro do primeiro com metade do segundo .
# a soma do triplo do primeiro com o terceiro.
# o terceiro elevado ao cubo.

numero1 = int(input("Entre com o primeiro numero:"))
numero2 = int(input("Entre com o segundo numero:"))
numero3 = float(input("Entre com o terceiro numero:"))

produto_dobro = ((numero1 * 2) * (numero2 % 2))
soma_triplo = ((numero1 * 3) + numero3)
elevado_cubo = (numero3 ** 3)

print("O produto do dobro:", produto_dobro)
print("A soma do triplo:", soma_triplo)
print("O terceiro elevado ao cubo:", round(elevado_cubo))


# coding=utf-8
from django.db import transaction
from django.shortcuts import render, redirect

from datetime import datetime
# Create your views here.
from df_cart.models import CartInfo
from df_user.models import UserInfo
from models import *

def order_list(request):
    uid=request.session.get('uid')
    user=UserInfo.objects.get(pk=uid)

    dict=request.POST
    cids=dict.getlist('cid')
    cart_list=CartInfo.objects.filter(pk__in=cids)
    context={'title':'订单页面','cart_list':cart_list,'user':user}
    return render(request, 'df_order/order_list.html',context)

@transaction.atomic
def handle(request):

    sid=transaction.savepoint()

    try:
        dict=request.POST
        cids=dict.getlist('cid')
        addr=dict.get('addr')
        uid=request.session.get('uid')
        '''
        创建订单主表对象
        判断商品库存是否足够
        便历购物车信息　创建订单祥表对象
        将商品数量减少
        '''
        order=OrderInfo()
        order.oid='%s%d'%(datetime.now().strftime('%Y%m%d%H%M%S'),uid)
        order.user_id=uid
        order.ototal=0
        order.oaddress=addr
        order.save()

        total=0
        cartlist=CartInfo.objects.filter(pk__in=cids)
        for cart in cartlist:
            if cart.count>cart.goods.gkucun:
                # 库存不足　放弃购买　回滚
                transaction.savepoint_rollback(sid)
                return redirect('/cart/')
            else:
                #　库存足够　创建订单祥表
                detail=OrderDetailInfo()
                detail.goods=cart.goods
                detail.price=cart.goods.gprice
                detail.count=cart.count
                detail.order=order
                detail.save()

                #计算商品总价
                total+=detail.price*detail.count
                #修改库存数量
                goods=cart.goods
                goods.gkucun-=cart.count
                goods.save()
                #删除购物车
                cart.delete()

        #保存总价
        order.ototal=total
        order.save()
        #购买成功
        transaction.savepoint_commit(sid)
        return redirect('/user/order/')
    except:
        transaction.savepoint_rollback(sid)
        return redirect('/cart/')


# Method-1 Using Stack

def isValid(s):
    length = len(s)
    stack = []
    for i in range(length):
        if s[i] == '[' or s[i] == '{' or s[i] == '(':
            stack.append(s[i])
        elif s[i] == ']' or s[i] == '}' or s[i] == ')':
            if stack:
                if s[i] == ')' and stack[-1] == '(' or s[i] == '}' and stack[-1] == '{' or s[i] == ']' and stack[-1] == '[':
                    stack.pop()
                else:
                    stack.append(s[i])
            else:
                stack.append(s[i])
    return len(stack) == 0

# Time Complexity : O(n)
# Space Complexity : O(n)


import pygame
import control
pygame.font.init()
menuFont = pygame.font.SysFont("monospace",62)

class menu:
    ###holds all the data for a single menu state instance
    def __init__(self,name,buttons,butCol=(255,255,255),txtCol=(255,255,0)):
        self.name = name
        self.buttons = buttons
        self.butCol = butCol
        self.txtCol = txtCol
        self.title = title(self.name)

    def draw(self,screen,offX=0,offY=0):
        if self.title:
            self.title.draw(screen,self.txtCol,[offX,offY])
        for but in self.buttons:
            but.draw(screen,self.txtCol,[offX,offY])

class title:
    def __init__(self,text,x=-125,y=-400):
        self.text = text
        self.location = [x,y]

    def draw(self,screen,txtColour,offset):
        label = menuFont.render(self.text,1,txtColour)
        screen.blit(label,(screen.get_width()/2 + self.location[0] + offset[0],screen.get_height()/2 + self.location[1] + offset[1]))

class button:
    def __init__(self,text,x,y,colour=(255,255,255),rect=None):
        self.text = text
        self.location = [x,y]
        self.colour = colour
        self.dimensions = menuFont.size(self.text)
    def draw(self,screen,txtColour,offset):
        label = menuFont.render(self.text,1,txtColour)
        self.rect = pygame.draw.rect(screen,self.colour,(screen.get_width()/2 + self.location[0] + offset[0],screen.get_height()/2 + self.location[1] + offset[1],self.dimensions[0],self.dimensions[1]))
        screen.blit(label,(screen.get_width()/2 + self.location[0] + offset[0],screen.get_height()/2 + self.location[1] + offset[1]))

menuList = {
    "pause" : menu("Pause", (
        #       Name        X       Y
        button("Resume",    -125,   -275),
        button("Options",   -125,   -100),
        button("Quit",      -125,   75)
        )),
    "options" : menu("Options", (
        button("Test",      -125, 0),
        button("Back",      -125,   75)
        ))
    }


# Report functions
file_name = "game_stat.txt"

def count_games(file_name):
    with open(file_name, 'r') as f:
        return len(f.readlines())

def decide(file_name, year):
    with open(file_name, 'r') as f:
        for line in f.readlines():
            line = line.split("\t")
            if line[2] == str(year):
                return True
        return False

def get_latest(file_name):
    latest_game_info = [0, ""]
    with open(file_name, 'r') as f:
        for line in f.readlines():
            line = line.split("\t")
            if int(line[2]) > latest_game_info[0]:
                latest_game_info[0] = int(line[2])
                latest_game_info[1] = line[0]
    return latest_game_info[1]

def count_by_genre(file_name, genre):
    count = 0
    with open(file_name, 'r') as f:
        for line in f.readlines():
            line = line.split("\t")
            if line[3] == genre:
                count += 1
    return count

def get_line_number_by_title(file_name, title):
    counter = 1
    with open(file_name, 'r') as f:
        for line in f.readlines():
            line = line.split("\t")
            if line[0] == title:
                return counter
            counter += 1

def sort_abc(file_name):
    titles = []
    with open(file_name, 'r') as f:
        for line in f.readlines():
            line = line.split("\t")
            titles.append(line[0])
    titles.sort()
    return titles


import pandas as pd

def tweet_precossess(tweets):
    """
    Splits user and their tweet into two columns of a dataframe.

    Args:
        tweets dataframe containing 1 column. Each cell values pattern : '@user_id : tweet'
    Returns:
        dataframe with 2 columns:
             1.'user_id'(str) of tweet
             2.'tweet_content' (str)
    """

    #get all user_ids in a list
    user_id = [tweets['Tweets'][i].split(":",1)[0] for i in range(len(tweets['Tweets']))]

    #get all tweets in a list
    tweet_content = [tweets['Tweets'][i].split(":",1)[1] for i in range(len(tweets['Tweets']))]

    #convert all user_ids list and their tweets into columns of a dataframe.
    df = pd.DataFrame({"user_id":user_id, "tweet_content": tweet_content})

    return df


import cx_Oracle
import time

def test_network_speed(connection_string, sql):
    try:
        connection = cx_Oracle.connect(connection_string)
        cursor = connection.cursor()

        start_time = time.time()
        cursor.execute(sql)
        data = cursor.fetchall()
        end_time = time.time()

        cursor.close()
        connection.close()

        elapsed_time = end_time - start_time
        return True, elapsed_time
    except Exception as e:
        return False, str(e)

if __name__ == "__main__":
    # 替换为您的数据库连接字符串和要执行的SELECT语句
    connection_string = "udms/admin@192.168.1.15:1521/demodb"
    sql = "SELECT * FROM (SELECT * FROM defect_region) WHERE ROWNUM <= 100000"

    success, elapsed_time = test_network_speed(connection_string, sql)

    if success:
        print(f"查询成功！执行时间：{elapsed_time:.4f} 秒")
    else:
        print(f"查询失败：{elapsed_time}")

    sql = "SELECT * FROM (SELECT * FROM edc_raw) WHERE ROWNUM <= 100000"

    success, elapsed_time = test_network_speed(connection_string, sql)

    if success:
        print(f"查询成功！执行时间：{elapsed_time:.4f} 秒")
    else:
        print(f"查询失败：{elapsed_time}")


#ecncoding=utf-8
import jieba.posseg as pseg
def doParse(question):
	sq = pseg.cut(question)
	result = []
	for w in sq:
		result.append((w.word, w.flag))
	sepaStr = ""
	for inner_item in result:
		sepaStr += (inner_item[0] + " " + str(inner_item[1]) + ", ")

	return sepaStr


from django.test import TestCase
from django.contrib.auth.models import User
from navsite.models import Category
from .models import Product, ProductTranslation, Image

class ProductModelTest(TestCase):

    def setUp(self):
        self.user = User.objects.create(username='testuser')
        self.category = Category.objects.create(name='TestCategory')

        self.product = Product.objects.create(
            user=self.user,
            category=self.category,
            stock=10,
            available=True,
            price=99.99,
            public=True
        )

    def test_product_creation(self):
        self.assertEqual(self.product.user, self.user)
        self.assertEqual(self.product.category, self.category)
        self.assertEqual(self.product.stock, 10)
        self.assertEqual(self.product.available, True)
        self.assertEqual(self.product.price, 99.99)
        self.assertEqual(self.product.public, True)

    def test_product_translation_creation(self):
        product_translation = ProductTranslation.objects.create(
            master=self.product,
            language_code='en',
            title='Test Product',
            slug='test-product',
            keywords='test, product',
            short_description='A test product.',
            description='This is a test product for demonstration purposes.'
        )

        self.assertEqual(product_translation.master, self.product)
        self.assertEqual(product_translation.language_code, 'en')
        self.assertEqual(product_translation.title, 'Test Product')
        self.assertEqual(product_translation.slug, 'test-product')
        self.assertEqual(product_translation.keywords, 'test, product')
        self.assertEqual(product_translation.short_description, 'A test product.')
        self.assertEqual(product_translation.description, 'This is a test product for demonstration purposes.')

    def test_image_creation(self):
        image = Image.objects.create(
            product=self.product,
            image='images/products/1/test.jpg'
        )

        self.assertEqual(image.product, self.product)
        self.assertEqual(image.image, 'images/products/1/test.jpg')


def particionado(lista, menor, mayor):
    pivote = lista[menor]
    izq = menor + 1
    der = mayor

    while True:
        while izq <= der and lista[izq] <= pivote:
            izq += 1
        while izq <= der and lista[der] >= pivote:
            der -= 1
        if der < izq:
            break
        else:
            lista[izq], lista[der] = lista[der], lista[izq]

    lista[menor], lista[der] = lista[der], lista[menor]

    return der

def quicksort(lista, menor, mayor):
    if menor < mayor:
        pivote = particionado(lista,menor,mayor)
        quicksort(lista, menor, pivote - 1)
        quicksort(lista, pivote + 1, mayor)

lista = [30,45,50,5,25,10,20,35,40,15]
print(lista)
quicksort(lista, 0, len(lista)-1)
print(lista)


#import FaceLandmarksExtractor

import numpy as np
import dlib
import torch
import keras
from keras import backend as K
from keras import layers as KL
import math
import os
import time
import code

#channels_first BatchNorm2D https://github.com/keras-team/keras/issues/10648

class TorchBatchNorm2D(keras.engine.Layer):
    def __init__(self, axis=-1, momentum=0.99, epsilon=1e-3, **kwargs):
        super(TorchBatchNorm2D, self).__init__(**kwargs)
        self.supports_masking = True
        self.axis = axis
        self.momentum = momentum
        self.epsilon = epsilon

    def build(self, input_shape):
        dim = input_shape[self.axis]
        if dim is None:
            raise ValueError('Axis ' + str(self.axis) + ' of '
                             'input tensor should have a defined dimension '
                             'but the layer received an input with shape ' +
                             str(input_shape) + '.')
        shape = (dim,)
        self.gamma = self.add_weight(shape=shape, name='gamma', initializer='ones', regularizer=None, constraint=None)
        self.beta = self.add_weight(shape=shape, name='beta', initializer='zeros', regularizer=None, constraint=None)
        self.moving_mean = self.add_weight(shape=shape, name='moving_mean', initializer='zeros', trainable=False)
        self.moving_variance = self.add_weight(shape=shape, name='moving_variance', initializer='ones', trainable=False)
        self.built = True

    def call(self, inputs, training=None):
        input_shape = K.int_shape(inputs)

        broadcast_shape = [1] * len(input_shape)
        broadcast_shape[self.axis] = input_shape[self.axis]

        broadcast_moving_mean = K.reshape(self.moving_mean, broadcast_shape)
        broadcast_moving_variance = K.reshape(self.moving_variance, broadcast_shape)
        broadcast_gamma = K.reshape(self.gamma, broadcast_shape)
        broadcast_beta = K.reshape(self.beta, broadcast_shape)
        invstd = K.ones (shape=broadcast_shape, dtype='float32') / K.sqrt(broadcast_moving_variance + K.constant(self.epsilon, dtype='float32'))

        return (inputs - broadcast_moving_mean) * invstd * broadcast_gamma + broadcast_beta

    def get_config(self):
        config = { 'axis': self.axis, 'momentum': self.momentum, 'epsilon': self.epsilon }
        base_config = super(TorchBatchNorm2D, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

def t2kw_conv2d (src):
    if src.bias is not None:
        return [ np.moveaxis(src.weight.data.cpu().numpy(), [0,1,2,3], [3,2,0,1]), src.bias.data.cpu().numpy() ]
    else:
        return [ np.moveaxis(src.weight.data.cpu().numpy(), [0,1,2,3], [3,2,0,1])]

def t2kw_bn2d(src):
    return [ src.weight.data.cpu().numpy(), src.bias.data.cpu().numpy(), src.running_mean.cpu().numpy(), src.running_var.cpu().numpy() ]

import face_alignment
fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D,enable_cuda=False,enable_cudnn=False,use_cnn_face_detector=True).face_alignemnt_net
fa.eval()

def KerasConvBlock(in_planes, out_planes, input, srctorch):
    out1 = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d(srctorch.bn1) )(input)
    out1 = KL.Activation( keras.backend.relu ) (out1)
    out1 = KL.ZeroPadding2D(padding=(1, 1), data_format='channels_first')(out1)
    out1 = KL.convolutional.Conv2D( int(out_planes/2), kernel_size=3, strides=1, data_format='channels_first', padding='valid', use_bias = False, weights=t2kw_conv2d(srctorch.conv1) ) (out1)

    out2 = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d(srctorch.bn2) )(out1)
    out2 = KL.Activation( keras.backend.relu ) (out2)
    out2 = KL.ZeroPadding2D(padding=(1, 1), data_format='channels_first')(out2)
    out2 = KL.convolutional.Conv2D( int(out_planes/4), kernel_size=3, strides=1, data_format='channels_first', padding='valid', use_bias = False, weights=t2kw_conv2d(srctorch.conv2) ) (out2)

    out3 = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d(srctorch.bn3) )(out2)
    out3 = KL.Activation( keras.backend.relu ) (out3)
    out3 = KL.ZeroPadding2D(padding=(1, 1), data_format='channels_first')(out3)
    out3 = KL.convolutional.Conv2D( int(out_planes/4), kernel_size=3, strides=1, data_format='channels_first', padding='valid', use_bias = False, weights=t2kw_conv2d(srctorch.conv3) ) (out3)

    out3 = KL.Concatenate(axis=1)([out1, out2, out3])

    if in_planes != out_planes:
        downsample = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d(srctorch.downsample[0]) )(input)
        downsample = KL.Activation( keras.backend.relu ) (downsample)
        downsample = KL.convolutional.Conv2D( out_planes, kernel_size=1, strides=1, data_format='channels_first', padding='valid', use_bias = False, weights=t2kw_conv2d(srctorch.downsample[2]) ) (downsample)
        out3 = KL.add ( [out3, downsample] )
    else:
        out3 = KL.add ( [out3, input] )

    return out3

def KerasHourGlass (depth, input, srctorch):

    up1 = KerasConvBlock(256, 256, input, srctorch._modules['b1_%d' % (depth)])

    low1 = KL.AveragePooling2D (pool_size=2, strides=2, data_format='channels_first', padding='valid' )(input)
    low1 = KerasConvBlock (256, 256, low1, srctorch._modules['b2_%d' % (depth)])

    if depth > 1:
        low2 = KerasHourGlass (depth-1, low1, srctorch)
    else:
        low2 = KerasConvBlock(256, 256, low1, srctorch._modules['b2_plus_%d' % (depth)])

    low3 = KerasConvBlock(256, 256, low2, srctorch._modules['b3_%d' % (depth)])

    up2 = KL.UpSampling2D(size=2, data_format='channels_first') (low3)
    return KL.add ( [up1, up2] )

model_path = os.path.join( r'D:\DFLBuild\test\2DFAN-4.h5' )
if os.path.exists (model_path):
    t = time.time()
    model = keras.models.load_model (model_path, custom_objects={'TorchBatchNorm2D': TorchBatchNorm2D} )
    print ('load takes = %f' %( time.time() - t ) )
else:
    _input = keras.layers.Input ( shape=(3, 256,256) )
    x = KL.ZeroPadding2D(padding=(3, 3), data_format='channels_first')(_input)
    x = KL.convolutional.Conv2D( 64, kernel_size=7, strides=2, data_format='channels_first', padding='valid', weights=t2kw_conv2d(fa.conv1) ) (x)

    x = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d(fa.bn1) )(x)
    x = KL.Activation( keras.backend.relu ) (x)

    x = KerasConvBlock (64, 128, x, fa.conv2)
    x = KL.AveragePooling2D (pool_size=2, strides=2, data_format='channels_first', padding='valid' ) (x)
    x = KerasConvBlock (128, 128, x, fa.conv3)
    x = KerasConvBlock (128, 256, x, fa.conv4)

    outputs = []
    previous = x
    for i in range(4):
        ll = KerasHourGlass (4, previous, fa._modules['m%d' % (i) ])
        ll = KerasConvBlock (256,256, ll, fa._modules['top_m_%d' % (i)])

        ll = KL.convolutional.Conv2D(256, kernel_size=1, strides=1, data_format='channels_first', padding='valid', weights=t2kw_conv2d( fa._modules['conv_last%d' % (i)] ) ) (ll)
        ll = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d( fa._modules['bn_end%d' % (i)] ) )(ll)
        ll = KL.Activation( keras.backend.relu ) (ll)

        tmp_out = KL.convolutional.Conv2D(68, kernel_size=1, strides=1, data_format='channels_first', padding='valid', weights=t2kw_conv2d( fa._modules['l%d' % (i)] ) ) (ll)
        outputs.append(tmp_out)
        if i < 4 - 1:
            ll = KL.convolutional.Conv2D(256, kernel_size=1, strides=1, data_format='channels_first', padding='valid', weights=t2kw_conv2d( fa._modules['bl%d' % (i)] ) ) (ll)
            previous = KL.add ( [previous, ll, KL.convolutional.Conv2D(256, kernel_size=1, strides=1, data_format='channels_first', padding='valid', weights=t2kw_conv2d( fa._modules['al%d' % (i)] ) ) (tmp_out) ] )

    model = keras.models.Model (_input, outputs)
    model.compile ( loss='mse', optimizer='adam' )
    model.save (model_path)
    model.save_weights ( os.path.join( os.path.dirname(__file__) , 'weights.h5') )

    model_short = keras.models.Model (_input, outputs[0])
    model_short.compile ( loss='mse', optimizer='adam' )
    model_short.save ( os.path.join( os.path.dirname(__file__) , "2DFAN-4_light.h5" ) )
    model_short.save_weights ( os.path.join( os.path.dirname(__file__) , '_light_weights.h5') )

def transform(point, center, scale, resolution, invert=False):
    _pt = torch.ones(3)
    _pt[0] = point[0]
    _pt[1] = point[1]

    h = 200.0 * scale
    t = torch.eye(3)
    t[0, 0] = resolution / h
    t[1, 1] = resolution / h
    t[0, 2] = resolution * (-center[0] / h + 0.5)
    t[1, 2] = resolution * (-center[1] / h + 0.5)

    if invert:
        t = torch.inverse(t)

    new_point = (torch.matmul(t, _pt))[0:2]

    return new_point.int()

def get_preds_fromhm(hm, center=None, scale=None):
    max, idx = torch.max(  hm.view(hm.size(0), hm.size(1), hm.size(2) * hm.size(3)), 2)
    idx += 1
    preds = idx.view(idx.size(0), idx.size(1), 1).repeat(1, 1, 2).float()
    preds[..., 0].apply_(lambda x: (x - 1) % hm.size(3) + 1)
    preds[..., 1].add_(-1).div_(hm.size(2)).floor_().add_(1)

    for i in range(preds.size(0)):
        for j in range(preds.size(1)):
            hm_ = hm[i, j, :]
            pX, pY = int(preds[i, j, 0]) - 1, int(preds[i, j, 1]) - 1
            if pX > 0 and pX < 63 and pY > 0 and pY < 63:
                diff = torch.FloatTensor(
                    [hm_[pY, pX + 1] - hm_[pY, pX - 1],
                     hm_[pY + 1, pX] - hm_[pY - 1, pX]])
                preds[i, j].add_(diff.sign_().mul_(.25))

    preds.add_(-.5)

    preds_orig = torch.zeros(preds.size())
    if center is not None and scale is not None:
        for i in range(hm.size(0)):
            for j in range(hm.size(1)):
                preds_orig[i, j] = transform(
                    preds[i, j], center, scale, hm.size(2), True)

    return preds, preds_orig

def get_preds_fromhm2(a, center=None, scale=None):
    b = a.reshape ( (a.shape[0], a.shape[1]*a.shape[2]) )
    c = b.argmax(1).reshape ( (a.shape[0], 1) ).repeat(2, axis=1).astype(np.float)
    c[:,0] %= a.shape[2]
    c[:,1] = np.apply_along_axis ( lambda x: np.floor(x / a.shape[2]), 0, c[:,1] )

    for i in range(a.shape[0]):
        pX, pY = int(c[i,0]), int(c[i,1])
        if pX > 0 and pX < 63 and pY > 0 and pY < 63:
            diff = np.array ( [a[i,pY,pX+1]-a[i,pY,pX-1], a[i,pY+1,pX]-a[i,pY-1,pX]] )
            c[i] += np.sign(diff)*0.25

    c += 0.5
    result = np.empty ( (a.shape[0],2), dtype=np.int )
    if center is not None and scale is not None:
        for i in range(a.shape[0]):
            pt = np.array ( [c[i][0], c[i][1], 1.0] )
            h = 200.0 * scale
            m = np.eye(3)
            m[0,0] = a.shape[2] / h
            m[1,1] = a.shape[2] / h
            m[0,2] = a.shape[2] * ( -center[0] / h + 0.5 )
            m[1,2] = a.shape[2] * ( -center[1] / h + 0.5 )
            m = np.linalg.inv(m)
            result[i] = np.matmul (m, pt)[0:2].astype( np.int )
    return result

rnd_data = np.random.rand (3, 256,256).astype(np.float32)
#rnd_data = np.random.random_integers (2, size=(3, 256,256)).astype(np.float32)
#rnd_data = np.array ( [[[1]*256]*256]*3 , dtype=np.float32 )
input_data = np.array ([rnd_data])

fa_out_tensor = fa( torch.autograd.Variable( torch.from_numpy(input_data), volatile=True) )[-1].data.cpu()
fa_out = fa_out_tensor.numpy()

t = time.time()
m_out = model.predict ( input_data )[-1]
print ('predict takes = %f' %( time.time() - t ) )
t = time.time()

#fa_base_out = fa_base(torch.autograd.Variable( torch.from_numpy(input_data), volatile=True))[0].data.cpu().numpy()

print ( 'shapes = %s , %s , equal == %s ' % (fa_out.shape, m_out.shape, (fa_out.shape == m_out.shape) ) )
print ( 'allclose == %s' %  ( np.allclose(fa_out, m_out) ) )
print ( 'total abs diff outputs = %f' % ( np.sum ( np.abs(np.ndarray.flatten(fa_out-m_out))) ))

###
d = dlib.rectangle(156,364,424,765)

center = torch.FloatTensor(
                    [d.right() - (d.right() - d.left()) / 2.0, d.bottom() -
                     (d.bottom() - d.top()) / 2.0])
center[1] = center[1] - (d.bottom() - d.top()) * 0.12
scale = (d.right() - d.left() + d.bottom() - d.top()) / 195.0
pts, pts_img = get_preds_fromhm (fa_out_tensor, center, scale)
pts_img = pts_img.view(68, 2).numpy()

###

m_pts_img = get_preds_fromhm2 (m_out[0], center, scale)

print ('pts1 == pts2 == %s' % ( np.array_equal(pts_img, m_pts_img) ) )
import code
code.interact(local=dict(globals(), **locals()))

#print ( np.array_equal (fa_out, m_out) ) #>>> False
#code.interact(local=dict(globals(), **locals()))

#code.interact(local=locals())

#code.interact(local=locals())

###
#fa.conv1.weight = torch.nn.Parameter( torch.from_numpy ( np.array( [[[[1.0]*7]*7]*3]*64, dtype=np.float32) ) )
#fa.conv1.bias = torch.nn.Parameter( torch.from_numpy ( np.array( [1.0]*64, dtype=np.float32 ) ) )
#model.layers[2].set_weights( [ np.array( [[[[1.0]*64]*3]*7]*7, dtype=np.float32), np.array( [1.0]*64, dtype=np.float32 ) ] )

#b = np.array( [1.0]*64, dtype=np.float32 )
#b = np.random.rand (64).astype(np.float32)
#w = np.array( [[[[1.0]*7]*7]*3]*64, dtype=np.float32)
#w = np.random.rand (64, 3, 7, 7).astype(np.float32)
#s = w #fa_base.conv1.weight.data.cpu().numpy() #64x3x7x7
#d = np.moveaxis(s, [0,1,2,3], [3,2,0,1] )

#fa.conv1.weight = torch.nn.Parameter( torch.from_numpy ( w ) )
#fa.conv1.bias = torch.nn.Parameter( torch.from_numpy ( b ) )
#model.layers[2].set_weights( [np.transpose(w), b] )
#model.layers[2].set_weights( [d, b] )
'''
for i in range(0,64):
    for j in range(0,128):
        b = np.array_equal (fa_out[i,j], m_out[i,j])
        if b == False:
            print ( '%d %d == False' %(i,j) ) #>>> False
'''

'''
input = -2.7966828
gamma = 0.7640695571899414
beta = 0.22801123559474945
moving_mean = 0.12693816423416138
moving_variance = 0.10409101098775864
epsilon = 0.0 #0.00001

print ( gamma * (input - moving_mean) / math.sqrt(moving_variance + epsilon) + beta )
print ( (input - moving_mean) * (1.0 / math.sqrt(moving_variance) + epsilon)*gamma + beta   )
'''
#code.interact(local=dict(globals(), **locals()))
'''
conv_64_128 = x
conv_64_128 = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d(fa.conv2.bn1) )(conv_64_128)
conv_64_128 = KL.Activation( keras.backend.relu ) (conv_64_128)
conv_64_128 = KL.ZeroPadding2D(padding=(1, 1), data_format='channels_first')(conv_64_128)
conv_64_128 = KL.convolutional.Conv2D( 64, kernel_size=3, strides=1, data_format='channels_first', padding='valid', use_bias = False, weights=t2kw_conv2d(fa.conv2.conv1) ) (conv_64_128)
conv_64_128 = TorchBatchNorm2D(axis=1,  momentum=0.1, epsilon=1e-05, weights=t2kw_bn2d(fa.conv2.bn2) )(conv_64_128)
conv_64_128 = KL.Activation( keras.backend.relu ) (conv_64_128)
'''
#
#
#keras result = gamma * (input - moving_mean) / sqrt(moving_variance + epsilon) + beta
#
# (input - mean / scale_factor) / sqrt(var / scale_factor + eps)
#
#input = -3.0322433
#
#gamma = 0.1859646
#beta = -0.17041835
#moving_mean = -3.0345056
#moving_variance = 8.773307
#epsilon = 0.00001
#
#result = - 0.17027631
#
# fa result = 1.930317


import cv2
import imutils
import numpy as np
from PIL import Image as PilImage
from PIL.ExifTags import TAGS

class Image:
    """
    Encapsulation of routines to an image. Internally, the
    image is stored as a numpy.ndarray.

    Arguments
    ---------
    filename: str, optional
        if given, the image referenced by the filename is loaded from disc
    """

    def __init__(self, filename=None):
        self._raw = None
        if filename:
            self.load(filename)
        self.contours = []

    def __getitem__(self, index):
        return self._raw[index]

    @property
    def height(self):
        if self._raw is None:
            raise ValueError("Cannot read height from undefined image")
        return self._raw.shape[0]

    @property
    def width(self):
        if self._raw is None:
            raise ValueError("Cannot read width from undefined image")
        return self._raw.shape[1]

    def crop_by_contour(self, index=0, inplace=False):
        """
        Crop the image about the bounding box of a contour.

        The contours need to be created first with the ``find_contours`` routine.

        Arguments
        ---------
        index: int, optional
            the index of the contour to use
        inplace: bool, optional
            if True, the image is cropped and returned, otherwise a new image is returned

        Returns
        -------
        Image:
            the cropped image
        """
        if index < 0 or index >= len(self.contours):
            raise IndexError(f"The given contour index ({index}) is out of range")

        x, y, w, h = cv2.boundingRect(self.contours[index])
        cropped = self._raw[y : y + h, x : x + w]  # noqa

        if inplace:
            self._raw = cropped
            return self

        new_image = Image()
        new_image._raw = cropped
        return new_image

    def draw_contours(self, color, inplace=False):
        """
        Draw around each contour of the image

        The contours need to be created first with the ``find_contours`` routine.

        Arguments
        ---------
        color: tuple
            the RGB color of the boundary
        inplace: bool, optional
            if True, the image is modified and returned, otherwise a new image is returned

        Returns
        -------
        Image:
            the modified image
        """
        raw = self._raw.copy()
        for contour in self.contours:
            cv2.drawContours(raw, [contour], -1, color, 2)

        if inplace:
            self._raw = raw
            return self

        new_image = Image()
        new_image._raw = raw
        return new_image

    def find_contours(self, threshold):
        """
        Find all contours of the image by first converting it
        to gray-scale and then applying a color threshold.

        Arguments
        ---------
        threshold: int
            any pixel above the threshold is counted as foreground, otherwise background
        """
        gray_img = cv2.cvtColor(self._raw, cv2.COLOR_BGR2GRAY)
        blurred_img = cv2.GaussianBlur(gray_img, (5, 5), 0)
        thresh_img = cv2.threshold(blurred_img, threshold, 255, cv2.THRESH_BINARY)[1]

        cnts = cv2.findContours(
            thresh_img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
        )
        self.contours = sorted(
            imutils.grab_contours(cnts), key=cv2.contourArea, reverse=True
        )

    def load(self, filename, auto_orient=True):
        """
        Load an image from file

        Arguments
        ---------
        filename: str
            the path to the file
        auto_orient: bool, optional
            if True, orient the image according to the meta data (if available)
        """
        pil_image = PilImage.open(filename)
        if auto_orient:
            self._orient_pil_image(pil_image)
        self._raw = np.array(pil_image)
        if len(self._raw.shape) == 3 and self._raw.shape[2] >= 3:
            self._raw = cv2.cvtColor(self._raw, cv2.COLOR_BGR2RGB)

    def save(self, filename, jpg_quality=None):
        """
        Save image to disc

        Arguments
        ---------
        filename: str
            the path to the file
        jpg_quality: int, optional
            an value between 1 and 100 indicating the JPG quality
        """
        params = []
        if jpg_quality:
            params = [int(cv2.IMWRITE_JPEG_QUALITY), jpg_quality]
        cv2.imwrite(filename, self._raw, params)

    @staticmethod
    def _find_exif_value(pil_image, field):
        exif = pil_image._getexif()
        if not exif:
            return 1

        for key, value in exif.items():
            if TAGS.get(key) == field:
                return value
        return 1

    @staticmethod
    def _orient_pil_image(pil_image):
        orientation = Image._find_exif_value(pil_image, "Orientation")
        rotation_angle = {3: 180, 6: 270, 8: 90}.get(orientation, 0)
        if rotation_angle:
            pil_image = pil_image.rotate(rotation_angle, expand=False)


import numpy as np

a = np.array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]]
)

indices = np.array([[False, False, True],
                    [False, False, False],
                    [True, True, False]]
)

print(a[indices])
# [3 7 8]

print('\nListing 3-17')
## Data: popular Instagram accounts (millions followers)
inst = np.array([[232, "@instagram"],
                 [133, "@selenagomez"],
                 [59, "@victoriassecret"],
                 [120, "@cristiano"],
                 [111, "@beyonce"],
                 [76, "@nike"]]
)

## One-liner
superstars = inst[inst[:,0].astype(float) >100, 1]

## Results
print(superstars)


import sys
from torch import autocast
import os
import pandas as pd
import gzip
import os
import csv
from sentence_transformers import  util, InputExample
import pandas as pd
import sys
from diffusers import StableDiffusionPipeline
import os
import numpy as np

rank = int(sys.argv[1])
world_size = 8
os.environ["CUDA_VISIBLE_DEVICES"] = str(rank)
print(f'rank {rank} of {world_size}')

sts_dataset_path = os.path.join('/data/Datasets', 'stsbenchmark.tsv.gz')
if not os.path.exists(sts_dataset_path):
    util.http_get('https://sbert.net/datasets/stsbenchmark.tsv.gz', sts_dataset_path)

train_samples = []
dev_samples = []
test_samples = []
with gzip.open(sts_dataset_path, 'rt', encoding='utf8') as fIn:
    reader = csv.DictReader(fIn, delimiter='\t', quoting=csv.QUOTE_NONE)
    for row in reader:
        score = float(row['score']) / 5.0  # Normalize score to range 0 ... 1
        sentence1 = row['sentence1']
        sentence2 = row['sentence2']
        #inp_example = InputExample(texts=[row['sentence1'], row['sentence2']], label=score)
        if row['split'] == 'dev':
            dev_samples.append([score, sentence1, sentence2])
        elif row['split'] == 'test':
            test_samples.append([score, sentence1, sentence2])
        else:
            train_samples.append([score, sentence1, sentence2])

model_id = "CompVis/stable-diffusion-v1-4"
device = f"cuda"
pipe = StableDiffusionPipeline.from_pretrained(model_id, use_auth_token=True)
pipe = pipe.to(device)

for i in range(len(test_samples)):
    if i % world_size==rank:
        score, sentence1, sentence2 = test_samples[i]
        print(f'{i}/{len(test_samples)}({int(i/len(test_samples)*100)}%)\t{score}\t{sentence1} | {sentence2}')
        for repeat in range(5):
            with autocast("cuda"):
                image_sentence1 = pipe(sentence1, guidance_scale=7.5)["sample"][0]
                while np.sum(np.array(image_sentence1))==0:
                    print(f'regenerating {sentence1}')
                    image_sentence1 = pipe(sentence1, guidance_scale=7.5)["sample"][0]

                image_sentence2 = pipe(sentence2, guidance_scale=7.5)["sample"][0]
                while np.sum(np.array(image_sentence2))==0:
                    print(f'regenerating {sentence2}')
                    image_sentence2 = pipe(sentence2, guidance_scale=7.5)["sample"][0]

            image_sentence1.save(f'/data/Datasets/rendered_sts/test/{sentence1.replace("/","-")}-{repeat}.png')
            image_sentence2.save(f'/data/Datasets/rendered_sts/test/{sentence2.replace("/","-")}-{repeat}.png')


from django.urls import path

from .views import *

app_name = 'api'

urlpatterns = [
    path('login/', ObtainAuthToken.as_view(), name = 'login'),
    path('getall/', McpmasterlistAPI.as_view(), name = 'getall'),
    path('mcpdata/', McpDataAPI.as_view(), name = 'mcpdata'),
    path('createuser/', RegisterUserAPI.as_view(), name = 'createuser'),
]


'''
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964,
  "year": 2020
}

# print(thisdict)
# print(thisdict.keys())
# print(thisdict.values())
print(thisdict.items())

thisdict["model"] = "bently"

print(thisdict.items())

for a in thisdict.keys():
    print(a, thisdict[a])
'''

'''
team1 = {"name":{1:"Lee", 2:"Kim", 3:"YOO"}, "age":{1:20, 2:30, 3:25}, \
    "job":{1:"singer", 2:"student", 3:"teacher"}}

print(team1["name"][3])

thisset = {True, "Lee" ,30, "camera"}

if False in thisset :
    print("True")
else:
    print("nono")

for i in thisset :
    print(i)
'''
# [문제]
# 파티에 참석한 사람들의 명단이 세트 A와 B에 각각 저장되어 있다.
# 2개 파티에 모두 참석한 사람들의 명단을 출력하려면 어떻게 해야 할까?

# [출력 결과]
# 2개의 파티에 모두 참석한 사람은 다음과 같습니다.
# {'Park'}

from os import lstat

data = '''내 속엔 내가 너무도 많아 당신의 쉴 곳 없네
내 속엔 헛된바램들로 당신의 편할 곳 없네
내 속엔 내가 어쩔 수 없는 어둠 당신의 쉴 자리를 뺏고
내 속엔 내가 이길 수 없는 슬픔 무성한 가시나무숲같네
바람만 불면 그 메마른가지 서로 부대끼며 울어대고
쉴곳을 찾아 지쳐 날아온 어린새들도 가시에 찔려 날아가고
바람만 불면 외롭고 또 괴로워 슬픈 노래를 부르던 날이 많았는데
내 속엔 내가 너무도 많아서 당신의 쉴 곳 없네
바람만 불면 그 메마른가지 서로 부대끼며 울어대고
쉴곳을 찾아 지쳐 날아온 어린새들도 가시에 찔려 날아가고
바람만 불면 외롭고 또 괴로워 슬픈 노래를 부르던 날이 많았는데
내 속엔 내가 너무도 많아서 당신의 쉴 곳 없네'''

# a = (set(data))
# b = {}
# for i in a:
#     num1 = data.count(i)
#     b.update({i:num1})
# print(b)

# c = set(data.split(" "))
# d = {}
# for j in c:
#     if j.count("\n")!=0:
#         continue
#     else:
#         num2 = data.count(j)
#         d.update({j:num2})
# print(d)

lst = []
for p in [1,2,3]:
    print(p)

[lst.append(p+10) for p in [1,2,3,4]]
print(lst)

new = [x for x in range(10) if x<5]
print(new)

this = [True, "Lee" ,30, "camera"]
[print(x) for x in this]

newthis = ["hello" for x in this]
print(newthis)

[print(x) if x!='Lee' else 30 for x in this]