#!/usr/bin/env python3

import argparse, os
import numpy as np
import xesmf as xe
from netCDF4 import Dataset
from config_tools import Config

class ConfigRegrid(Config):
    def __init__(self):
        # static config applied for each processing
        self.woa_grid_path = "OSTIA.nc"
        self.woa_lat_var = "lat"
        self.woa_lon_var = "lon"
        self.l4_grid_path = "L4SSS.nc"
        self.l4_lat_var = "lat"
        self.l4_lon_var = "lon"
        self.regridder_file_path = "xesmf_wts.nc"

def parseCommandLine():
    parser = argparse.ArgumentParser(description=("Generate regrid weight file by xesmf"))
    parser.add_argument("config_path", help=("config file path"))
    args = parser.parse_args()
    print(args)
    return args

def main(args):

    cfg = ConfigRegrid()
    cfg.read_cfg(args.config_path, "regrid2")

    # WOA18 latlon grids as output grids
    fn_grd_out = os.path.abspath(cfg.woa_grid_path)
    f = Dataset(fn_grd_out)
    lat1d_grd_out = f.variables[cfg.woa_lat_var][:]
    lon1d_grd_out = f.variables[cfg.woa_lon_var][:]
    f.close()

    print("lat1d_grd_out: shape, min, max=",lat1d_grd_out.shape, np.min(lat1d_grd_out), np.max(lat1d_grd_out))
    print("lon1d_grd_out: shape, min, max=",lon1d_grd_out.shape, np.min(lon1d_grd_out), np.max(lon1d_grd_out))

    # L4 latlon grids as input grids
    fn_grd_in = os.path.abspath(cfg.l4_grid_path)
    f = Dataset(fn_grd_in)
    lat1d_grd_in = f.variables[cfg.l4_lat_var][:]
    lon1d_grd_in = f.variables[cfg.l4_lon_var][:]
    f.close()

    print("lat1d_grd_in: shape, min, max=",lat1d_grd_in.shape, np.min(lat1d_grd_in), np.max(lat1d_grd_in))
    print("lon1d_grd_in: shape, min, max=",lon1d_grd_in.shape, np.min(lon1d_grd_in), np.max(lon1d_grd_in))

    # we only generate wts to WOA18 grids within the L4 grid range; otherwise, xesmf fails to work
    lat_max_allowed = lat1d_grd_out[lat1d_grd_out<lat1d_grd_in.max()][-1]
    idx_lat_max_allowed = np.where(lat1d_grd_out==lat_max_allowed)[0][0]

    lat_min_allowed = lat1d_grd_out[lat1d_grd_out>lat1d_grd_in.min()][0]
    idx_lat_min_allowed = np.where(lat1d_grd_out==lat_min_allowed)[0][0]

    print("min_WOA18_lat can be mapped from L4 ESA: idx_woa18, val_woa18=", idx_lat_min_allowed, lat1d_grd_out[idx_lat_min_allowed])
    print("max_WOA18_lat can be mapped from L4 ESA: idx_woa18, val_woa18=", idx_lat_max_allowed, lat1d_grd_out[idx_lat_max_allowed])

    # generate the regridder
    grd_in = {"lon": lon1d_grd_in, "lat": lat1d_grd_in}
    grd_out = {"lon": lon1d_grd_out, "lat": lat1d_grd_out[idx_lat_min_allowed:idx_lat_max_allowed+1]}
    interp_method = "bilinear"
    periodic = True
    regridder = xe.Regridder(grd_in, grd_out, interp_method, periodic=periodic)

    fn_regridder_out = os.path.abspath(cfg.regridder_file_path)
    print("write regrid info into the file: ", fn_regridder_out)
    regridder.filename = fn_regridder_out
    regridder.to_netcdf()

    print(regridder)

    return None

if __name__ == '__main__':
    args = parseCommandLine()
    main(args)


from src.bot import Bot

def main():
    bot = Bot()

    try:
        bot.run()
    finally:
        for db in bot.dbs.values():
            bot.loop.run_until_complete(db.close())

if __name__ == "__main__":
    main()


# main program for leetspeak translator

from leetdict import d
from prng import LCG

s = input()

idx = []
result = ""

for i in range(len(s)):
    if s[i] != ' ':
        idx = LCG(i, len(d[s[i]]))
        result += d[s[i].lower()][idx]
    else:
        result += ' '

print(result)


import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import os
import torchvision.datasets as datasets
import torchvision.transforms as transforms

class AlexNet(nn.Module):
    def __init__(self, num_classes=101):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
        self.classifier = nn.Sequential(
            nn.Dropout(),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x

def train(model, optimizer, criterion, train_loader, valid_loader, writer, num_epochs):

    # 将模型设置为训练模式
    model.train()

    # 定义最佳验证集准确率和最佳模型参数
    best_valid_acc = 0.0
    best_model_params = model.state_dict()

    for epoch in range(num_epochs):
        train_loss = 0.0
        train_acc = 0.0
        valid_loss = 0.0
        valid_acc = 0.0

        # 训练模型
        for inputs, labels in train_loader:
            inputs = inputs.to(device)
            labels = labels.to(device)

            optimizer.zero_grad()

            outputs = model(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            train_loss += loss.item() * inputs.size(0)
            _, preds = torch.max(outputs, 1)
            train_acc += torch.sum(preds == labels.data)

        # 在验证集上测试模型
        with torch.no_grad():
            model.eval()
            for inputs, labels in valid_loader:
                inputs = inputs.to(device)
                labels = labels.to(device)

                outputs = model(inputs)
                loss = criterion(outputs, labels)

                valid_loss += loss.item() * inputs.size(0)
                _, preds = torch.max(outputs, 1)
                valid_acc += torch.sum(preds == labels.data)

        # 计算平均损失和准确率
        train_loss /= len(train_loader.dataset)
        train_acc /= len(train_loader.dataset)
        valid_loss /= len(valid_loader.dataset)
        valid_acc /= len(valid_loader.dataset)

        # 记录训练和验证集的损失和准确率
        writer.add_scalar('train_loss', train_loss, epoch + 1)
        writer.add_scalar('train_acc', train_acc, epoch + 1)
        writer.add_scalar('valid_loss', valid_loss, epoch + 1)
        writer.add_scalar('valid_acc', valid_acc, epoch + 1)

        print('Epoch [{}/{}], Train Loss: {:.4f}, Train Acc: {:.4f}, Valid Loss: {:.4f}, Valid Acc: {:.4f}'
              .format(epoch+1, num_epochs, train_loss, train_acc, valid_loss, valid_acc))

        # 如果当前模型在验证集上的准确率更好，则保存模型参数
        if valid_acc > best_valid_acc:
            best_valid_acc = valid_acc
            best_model_params = model.state_dict()

    # 加载最佳模型参数
    model.load_state_dict(best_model_params)

    # 保存模型
    torch.save(model.state_dict(), 'alexnet.pth')

def test(test_loader, criterion, writer):
    new_model = AlexNet(num_classes=101)
    # 加载保存的模型参数
    checkpoint = torch.load('alexnet.pth')
    new_model.load_state_dict(checkpoint)

    # 设置模型为评估模式
    new_model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = new_model(data)
            test_loss += criterion(output, target).item()  # 将一批的损失相加
            pred = output.argmax(dim=1, keepdim=True)  # 找到概率最大的下标
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    test_accuracy = 100. * correct / len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset), test_accuracy))
    writer.add_scalar('Testing Loss', test_loss)
    writer.add_scalar('Testing Accuracy', test_accuracy)

def get_data_loaders(data_dir, batch_size):
    # 定义数据预处理方式，包括裁剪、缩放和标准化
    transform = transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                             std=[0.229, 0.224, 0.225])
    ])

    # 加载数据集
    full_dataset = datasets.ImageFolder(os.path.join(data_dir), transform=transform)

    # 将数据集按照数量划分为训练集、验证集和测试集
    num_samples = len(full_dataset)
    num_train = int(num_samples * 0.8)
    num_valid = int(num_samples * 0.1)
    num_test = num_samples - num_train - num_valid

    train_dataset, valid_dataset, test_dataset = torch.utils.data.random_split(
        full_dataset, [num_train, num_valid, num_test])
    print(len(train_dataset), len(valid_dataset), len(test_dataset))
    # 创建DataLoader对象
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
    valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=False, num_workers=4)
    test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=4)

    return train_loader, valid_loader, test_loader

if __name__ == '__main__':

    # 设置超参数
    num_epochs = 30
    batch_size = 64
    learning_rate = 0.0001

    # 定义tensorboard日志文件夹路径
    log_dir = 'runs/alexnet_caltech101'

    # 初始化tensorboard的SummaryWriter
    writer = SummaryWriter(log_dir=log_dir)

    # 获取数据加载器
    train_loader, valid_loader, test_loader = get_data_loaders('./caltech-101/101_ObjectCategories', batch_size)

    # 创建模型
    model = AlexNet(num_classes=101)

    # 将模型移动到GPU上进行训练
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model.to(device)

    # 定义损失函数和优化器
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

    # 训练模型
    train(model, optimizer, criterion, train_loader, valid_loader, writer, num_epochs)

    # 测试模型
    test(test_loader, criterion, writer)

    # 关闭tensorboard的SummaryWriter
    writer.close()


import PIL as p
from PIL import ImageTk
from tkinter import filedialog
import cv2
from pathlib import Path
from tkinter import *
import pandas as pd
import real_face_reco
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")

def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)

def scan_image():
    global path
    videoCaptureObject = cv2.VideoCapture(1)
    result = True
    while (result):
        ret, frame = videoCaptureObject.read()
        txt="Press q for capture image"
        cv2.putText(frame,txt,(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,255),2)

        cv2.imshow("Scan Image",frame)
        path="./employ_img/"+id.get()+".jpg"
        if (cv2.waitKey(1) & 0xFF == ord('q')):
            cv2.imwrite(path, frame)
            break

    videoCaptureObject.release()
    cv2.destroyAllWindows()

def submit():
    image=path
    id_val=id.get()
    name_val = name.get()
    email_val = email.get()
    new_row=pd.Series([id_val,name_val,email_val,image])
    df=pd.DataFrame([new_row])
    df.to_csv('./data/employData.csv', mode='a', header=False,index=False)

    print("The Id is : " + id_val)
    print("The Name is : " + name_val)
    print("The Email is : " + email_val)

    name.set("")
    email.set("")
    id.set("")

def button_4_fnc():
    videoCaptureObject = cv2.VideoCapture(1)
    result = True
    while (result):
        ret, frame = videoCaptureObject.read()
        txt="Press q for capture image"
        cv2.putText(frame,txt,(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,255),2)
        cv2.imshow("Scan Image", frame)
        if (cv2.waitKey(1) & 0xFF == ord('q')):
            videoCaptureObject.release()
            cv2.destroyAllWindows()
            break
    print(frame.shape)
    txt_name=real_face_reco.find_img(frame)

    updateData(id=txt_name,set_im=frame)

def updateData(name=None,id=None,email=None,set_im=None):
    df=pd.read_csv("./data/employData.csv")
    df['ID'].astype(str)
    var =df.loc[df['ID'].isin([id])]
    print(var)
    name=var["NAME"].values[0]
    email=var["EMAIL"].values[0]
    out_name.set(name)
    out_id.set(id)
    out_email.set(email)
    path=f"{(var['IMAGE'].values[0])}"
    set_im=cv2.imread(path)
    set_img(set_im)

def button_5_fnc():
    global res_img
    global  image_1,panelB
    path=filedialog.askopenfilename()
    if len(path)>0:
        image=cv2.imread(path)
        txt_name = real_face_reco.find_img(image)
        updateData(id=txt_name,set_im=image)

def set_img(image):
    global res_img
    global image_1, panelB
    image = cv2.resize(image, (500, 468))
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image = p.Image.fromarray(image)

    image = ImageTk.PhotoImage(image)
    res_img = image
    canvas.create_image(
        996.0,
        790.0,
        image=res_img
    )

def button_3_fncn():
    global path
    path = filedialog.askopenfilename()
    print(path)
    img=cv2.imread(path)
    path="./employ_img/"+id.get()+".jpg"
    if len(path)>0:

        cv2.imwrite(path,img)

def appendDFToCSV_void(df, csvFilePath, sep=","):
    import os
    if not os.path.isfile(csvFilePath):
        df.to_csv(csvFilePath, mode='a', index=False, sep=sep)
    elif len(df.columns) != len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns):
        raise Exception("Columns do not match!! Dataframe has " + str(len(df.columns)) + " columns. CSV file has " + str(len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns)) + " columns.")
    elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all():
        raise Exception("Columns and column order of dataframe and csv file do not match!!")
    else:
        df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False)

window = Tk()

window.geometry("1860x1024")
window.configure(bg = "#FFFCB7")

name=StringVar()
email=StringVar()
id=StringVar()
out_id=StringVar()
out_name=StringVar()
out_email=StringVar()

canvas = Canvas(
    window,
    bg = "#FFFCB7",
    height = 1024,
    width = 1860,
    bd = 0,
    highlightthickness = 0,
    relief = "ridge"
)

canvas.place(x = 0, y = 0)
canvas.create_rectangle(
    1.1368683772161603e-13,
    0.0,
    720.0000000000001,
    1024.0,
    fill="#FFFFFF",
    outline="")

canvas.create_text(
    13.0,
    31.0,
    anchor="nw",
    text="Pandoras Box",
    fill="#F63333",
    font=("Roboto Bold", 50 * -1),
    width=718.0
)

canvas.create_text(
    33.0,
    195.0,
    anchor="nw",
    text="Register:",
    fill="#000",
    font=("Roboto Bold", 50 * -1),
    width=233.0
)

canvas.create_text(
    1043.0,
    16.0,
    anchor="nw",
    text="Show Me Everything:",
    fill="#000",
    font=("Roboto Bold", 50 * -1),
    width=664.0
)

entry_image_1 = PhotoImage(
    file=relative_to_assets("entry_1.png")
)
entry_bg_1 = canvas.create_image(
    270.5,
    366.5,
    image=entry_image_1
)
entry_1 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = id, font=('calibre',15,'bold'),fg="#000000"
)
entry_1.place(
    x=53.0,
    y=322.0,
    width=435.0,
    height=87.0
)

entry_image_2 = PhotoImage(
    file=relative_to_assets("entry_2.png")
)
entry_bg_2 = canvas.create_image(
    1602.5,
    761.5,
    image=entry_image_2
)
entry_2 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = out_email, font=('calibre',15,'bold'),fg="#000000"
)
entry_2.place(
    x=1385.0,
    y=717.0,
    width=435.0,
    height=87.0
)

entry_image_3 = PhotoImage(
    file=relative_to_assets("entry_3.png")
)
entry_bg_3 = canvas.create_image(
    1612.5,
    949.5,
    image=entry_image_3
)
entry_3 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = out_id, font=('calibre',15,'bold'),fg="#000000"
)
entry_3.place(
    x=1395.0,
    y=905.0,
    width=435.0,
    height=87.0
)

entry_image_4 = PhotoImage(
    file=relative_to_assets("entry_4.png")
)
entry_bg_4 = canvas.create_image(
    1602.5,
    600.5,
    image=entry_image_4
)
entry_4 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = out_name, font=('calibre',15,'bold'),fg="#000000"
)
entry_4.place(
    x=1385.0,
    y=556.0,
    width=435.0,
    height=87.0
)

entry_image_5 = PhotoImage(
    file=relative_to_assets("entry_5.png")
)
entry_bg_5 = canvas.create_image(
    270.5,
    654.0,
    image=entry_image_5
)
entry_5 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = email, font=('calibre',15,'bold'),fg="#000000"
)
entry_5.place(
    x=53.0,
    y=609.5,
    width=435.0,
    height=87.0
)

entry_image_6 = PhotoImage(
    file=relative_to_assets("entry_6.png")
)
entry_bg_6 = canvas.create_image(
    270.5,
    511.5,
    image=entry_image_6
)
entry_6 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = name, font=('calibre',15,'bold'),fg="#000000"
)
entry_6.place(
    x=53.0,
    y=467.0,
    width=435.0,
    height=87.0
)

canvas.create_text(
    34.0,
    281.0,
    anchor="nw",
    text="Enter ID:",
    fill="#000",
    font=("Roboto Bold", 25 * -1),
    width=126.0
)

canvas.create_text(
    1544.0,
    486.0,
    anchor="nw",
    text="Name",
    fill="#000",
    font=("Roboto Bold", 35 * -1),
    width=138.0
)

canvas.create_text(
    1544.0,
    671.0,
    anchor="nw",
    text="Email",
    fill="#000",
    font=("Roboto Bold", 35 * -1),
    width=138.0
)

canvas.create_text(
    1544.0,
    837.0,
    anchor="nw",
    text="Id No",
    fill="#000",
    font=("Roboto Bold", 35 * -1),
    width=138.0
)

canvas.create_text(
    33.0,
    429.0,
    anchor="nw",
    text="Enter Name:",
    fill="#000",
    font=("Roboto Bold", 25 * -1),
    width=163.0
)

canvas.create_text(
    34.0,
    574.0,
    anchor="nw",
    text="Enter Email:",
    fill="#000",
    font=("Roboto Bold", 25 * -1),
    width=189.0
)

button_image_1 = PhotoImage(
    file=relative_to_assets("button_1.png"))
button_1 = Button(
    image=button_image_1,
    borderwidth=0,
    highlightthickness=0,
    command=scan_image,
    relief="flat"
)
button_1.place(
    x=34.0,
    y=762.0,
    width=280.0,
    height=65.0
)

button_image_2 = PhotoImage(
    file=relative_to_assets("button_2.png"))
button_2 = Button(
    image=button_image_2,
    borderwidth=0,
    highlightthickness=0,
    command=submit,
    relief="flat"
)
button_2.place(
    x=220.0,
    y=891.0,
    width=280.0,
    height=65.0
)

button_image_3 = PhotoImage(
    file=relative_to_assets("button_3.png"))
button_3 = Button(
    image=button_image_3,
    borderwidth=0,
    highlightthickness=0,
    command=button_3_fncn,
    relief="flat"
)
button_3.place(
    x=401.0,
    y=762.0,
    width=280.0,
    height=65.0
)

button_image_4 = PhotoImage(
    file=relative_to_assets("button_4.png"))
button_4 = Button(
    image=button_image_4,
    borderwidth=0,
    highlightthickness=0,
    command=button_4_fnc,
    relief="flat"
)
button_4.place(
    x=731.0,
    y=166.0,
    width=471.0,
    height=114.0
)

button_image_5 = PhotoImage(
    file=relative_to_assets("button_5.png"))
button_5 = Button(
    image=button_image_5,
    borderwidth=0,
    highlightthickness=0,
    command=button_5_fnc,
    relief="flat"
)
button_5.place(
    x=1379.0,
    y=166.0,
    width=471.0,
    height=114.0
)

canvas.create_text(
    763.0,
    313.0,
    anchor="nw",
    text="Employ Details:",
    fill="#000",
    font=("Roboto Bold", 40 * -1),
    width=315.0
)

image_image_1 = PhotoImage(
    file=relative_to_assets("image_1.png"))
image_1 = canvas.create_image(
    996.0,
    790.0,
    image=image_image_1
)

image_image_2 = PhotoImage(
    file=relative_to_assets("image_2.png"))
image_2 = canvas.create_image(
    996.0,
    518.0,
    image=image_image_2
)
window.resizable(False, False)
window.mainloop()


# -*- coding: utf-8 -*-
import io
import json
import os
import logging
import argparse

import numpy as np
import tensorflow as tf
from tensorflow_datasets.core.features.text import SubwordTextEncoder

from attention import AttentionWeightedAverage
from utils import encode_text_with_encoder, preprocess_text, add_model_argparse, numeric_label_to_text

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',
                    level=logging.INFO)

def main(FLAGS) -> None:
  logging.info(f"Loading model from {FLAGS.saved_model}")
  model: tf.keras.Model = tf.keras.models.load_model(
    FLAGS.saved_model,
    custom_objects={"AttentionWeightedAverage": AttentionWeightedAverage}
  )
  logging.info(f"Loading encoder from {FLAGS.saved_encoder}")
  encoder_filename: str = FLAGS.saved_encoder.replace(".subwords", '')
  encoder: SubwordTextEncoder = SubwordTextEncoder.load_from_file(encoder_filename)

  sentence: str = preprocess_text(FLAGS.sentence)
  model_input = encode_text_with_encoder(encoder=encoder,
                                         text=sentence,
                                         max_sequence_length=FLAGS.max_words)
  pred: np.ndarray = np.squeeze(model.predict(model_input.reshape(1, -1)))
  logging.debug(f"Predictions: {pred}")

  pred_class: str = numeric_label_to_text(np.round(pred))
  logging.info(f"Input sentence: {FLAGS.sentence}")
  logging.info(f"Classification is '{pred_class}' with a score of {pred}")

  if FLAGS.save_plots:
    logging.info("Visualising classification, saving to 'visualisations' dir")
    os.makedirs("visualisations", exist_ok=True)

    out_model = tf.keras.models.Model(inputs=model.input,
                                      outputs=(model.get_layer("attention").output[1],
                                               model.layers[-1].output))

    attention, posterior = out_model.predict(model_input.reshape(1, -1))

    with io.open(os.path.join("visualisations",
                              "neat_vision_single_string.json"),
                 "w",
                 encoding="utf-8") as m:
      tokens = [encoder.decode([idx]) for idx in encoder.encode(sentence)]
      nest_dict = dict(text=tokens,
                     label=int(np.round(pred)),
                     prediction=int(np.round(pred)),
                     # posterior=posterior[0].tolist(),
                     attention=attention[0].tolist(),
                     id=FLAGS.sentence[:16])
      json.dump([nest_dict], m)

    with io.open(os.path.join("visualisations",
                              "neat_vision_labels.json"),
                 "w",
                 encoding="utf-8") as m:
      json.dump({"0": {"name": "Negative", "desc": "Negative"},
                 "1": {"name": "Positive", "desc": "Positive"}},
                m)
  #   vis_model = tf.keras.models.Model(
  #     inputs=model.input,
  #     outputs=[layer.output for layer in model.layers])
  #
  #   feature_maps = vis_model.predict(model_input)
  #   layer_names_with_index: List[Tuple[int, str]] = [
  #     (index, layer.name)
  #     for index, layer in enumerate(model.layers)
  #     if "dropout" not in layer.name]
  #
  #   for i, layer_name in layer_names_with_index:
  #     save_feature_map(fig=visualise_feature_maps(feature_maps[i],
  #                                                 layer_name),
  #                      output_dir=FLAGS.plot_dir,
  #                      fname=f"{layer_name}.png")
  #
  #   # fig = visualise_feature_maps(feature_maps[1], layer_names_with_index[1][1])
  #   # fig.savefig(fname=os.path.join(FLAGS.plot_dir, "fmap1.png"))
  #
  #   cam_layer_with_index: Tuple[int, str] = [(i, name)
  #                for i, name in layer_names_with_index
  #                if "global_average_pooling" in name or "flatten" in name][-1]
  #   if cam_layer_with_index:
  #     logging.info(f"Class Activation Map Layer: {cam_layer_with_index[1]}")
  #     # We want the input to the layer
  #     cam_layer_with_index = cam_layer_with_index[0] - 1, cam_layer_with_index[1]
  #
  #     cam = get_cam(image_size=model_input.shape[1],
  #                   conv_out=feature_maps[cam_layer_with_index[0]],
  #                   pred_vec=pred,
  #                   all_amp_layer_weights=model.layers[-1].get_weights()[0],
  #                   filters=model.layers[cam_layer_with_index[0]].output.shape[-1])
  #     fig = plot_cam(model_input, cam)
  #     save_feature_map(fig, output_dir=FLAGS.plot_dir, fname=f"cam.png")
  #
  #   FLAGS.test_image.save(os.path.join(FLAGS.plot_dir, "input_image.png"))
  #   greyscale_image.save(os.path.join(FLAGS.plot_dir, "greyscale_input.png"))
  #   rescaled_image.save(os.path.join(FLAGS.plot_dir, "rescaled_model_input.png"))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser = add_model_argparse(parser)
  parser.add_argument(
    "sentence",
    default="",
    type=str,
    help="String sentence to classify"
  )
  parser.add_argument(
    "--save_plots",
    help="Save visualisations of this classification to "
         "'visualisations' directory",
    action="store_true")
  parser.add_argument(
    "--plot_dir",
    default="visualisations",
    type=str,
    help="Path to save visualisations to (dir)")

  FLAGS, unparsed = parser.parse_known_args()
  if unparsed:
    logging.warning("Unparsed arguments: {}".format(unparsed))

  logging.info("Arguments: {}".format(FLAGS))
  main(FLAGS)


from math import log
from operator import itemgetter
import re
import pandas as pd

def createDataSet():
	mydata = ""
	with open('D:/ML-Practicles/Decision-Tree/lenses.txt') as f:
		mydata = re.split(r'\n',f.read())

	mydata.remove('')
	final = ""
	final_list = []

	for i in range(len(mydata)):
		final = mydata[i]
		final_list.append((re.findall(r'[\d]',final)))

	labels = ['Age', 'Spectacle_Prescription', 'astigmatic', 'Tear_Rate', 'Lenses']

	return final_list,labels

def majoritycnt(classList):
	classCount = {}

	for vote in classList:

		if vote not in classCount.keys():
			classCount[vote] = 1

		else:
			classCount[vote] += 1

	sortedClassCount = sorted(classCount.items(), key=itemgetter(1), reverse=True)
	return sortedClassCount[0][0]

def calcshannonEnt(dataset):
	d = {}
	length = len(dataset)
	shannon_ent = 0
	for feature in dataset:
		label = feature[-1]

		if label not in d.keys():
			d[label] = 1
		else:
			d[label] += 1

	for k in d.keys():
		prob = float(d[k] / length)
		shannon_ent -= prob * log(prob,2)

	return shannon_ent

def splitdataset(dataset, axis, value):
	a = list()
	for feature in dataset:
		if feature[axis] == value:
			reducevect = feature[:axis]
			reducevect.extend(feature[axis+1:])
			a.append(reducevect)

	return a

def selectbestFeature(dataset):
	old_entropy = calcshannonEnt(dataset)
	best_feature = -1
	best_info_gain = 0.0
	num_feature = len(dataset[0]) - 1

	for i in range(num_feature):
		example = []
		for feature in dataset:
			example.append(feature[i])
		unique_val = set(example)
		new_entropy = 0.0

		for value in unique_val:
			sub_dataset = splitdataset(dataset, i, value)
			prob = float(len(sub_dataset)) / float(len(dataset))
			new_entropy += prob * calcshannonEnt(sub_dataset)

		info_gain = old_entropy - new_entropy

		if info_gain > best_info_gain:
			best_info_gain = info_gain
			best_feature = i

	return best_feature

def createTree(dataset, labels_test):
	classList = []
	for i in dataset:
		classList.append(i[-1])

	if classList.count(classList[0]) == len(dataset):
		return classList[0]

	if len(dataset[0]) == 1:
		return majoritycnt(classList)

	bestFeature = selectbestFeature(dataset)
	bestFeatureLabel = labels[bestFeature]

	myTree = {bestFeatureLabel:{}}
	del(labels_test[bestFeature])

	featValues = []
	for f in dataset:
		featValues.append(f[bestFeature])

	uniqueValues = set(featValues)

	for value in uniqueValues:
		subLabels = labels_test[:]
		myTree[bestFeatureLabel][value] = createTree(splitdataset(dataset, bestFeature, value), subLabels)

	return myTree

#test using tree for classification
def classify(myTree, labels, testVec):
	featLabel = ""
	for k in myTree.keys():
		featLabel = k
		break

	second_dir = myTree[featLabel]
	feature = labels.index(featLabel)
	value = testVec[feature]
	classLabel = ''

	for k in second_dir.keys():

		if value == int(k):
			if type(second_dir[k]).__name__ == 'dict':
				classLabel = classify(second_dir[k], labels, testVec)
			else:
				classLabel = second_dir[k]
	return classLabel

dataset, labels = createDataSet()
myTree = createTree(dataset, labels)

answer = classify(myTree, ['Age', 'Spectacle_Prescription', 'astigmatic', 'Tear_Rate', 'Lenses'], [3,1,1,1])
if answer == "3":
	print("hard lense")

if answer == "2":
	print("no lense")

if answer == "1":
	print("soft lense")


class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # for index,  num in enumerate(nums):
        #     other_num = target - num
        #     if other_num in nums[index+1:]:
        #         return [index, len(nums)-1-nums[::-1].index(other_num)]
        hash_map = {}
        for index, num in enumerate(nums):
            hash_map[num] = index
        for index, num in enumerate(nums):
            other_num = target - num
            # print(other_num)
            if other_num in hash_map and index != hash_map[other_num]:
                return [index, hash_map[other_num]]


# import discord
from discord.ext import commands, tasks

class DbHandler(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.fired_ready = False

    @commands.Cog.listener()
    async def on_ready(self):
        if self.fired_ready:
            return
        self.fired_ready = True
        async for data in self.bot.db.guild_data.find():
            self.bot.guild_data[data["guild_id"]] = data["data"]
        async for data in self.bot.db.channel_data.find():
            self.bot.channel_data[data["channel_id"]] = data["data"]
        self.update_db.start()
        await self.update_db()

    @tasks.loop(minutes=10)
    async def update_db(self):
        for guild, data in self.bot.guild_data.items():
            await self.bot.db.guild_data.update_one(
                {
                    "guild_id": guild,
                },
                {"$set": {"guild_id": guild, "data": data}},
                upsert=True,
            )

        for channel, data in self.bot.channel_data.items():
            await self.bot.db.channel_data.update_one(
                {
                    "channel_id": channel,
                },
                {"$set": {"channel_id": channel, "data": data}},
                upsert=True,
            )

    def cog_unload(self):
        self.update_db.stop()

def setup(bot):
    bot.add_cog(DbHandler(bot))


from gcsa.event import Event
from gcsa.google_calendar import GoogleCalendar
import gcsa

import yaml

config = yaml.load(open("settings.yaml", "r"), Loader=yaml.FullLoader)

calendar_id = config["calendar_id"]

gc = GoogleCalendar(
    calendar_id,
    credentials_path="credentials.json",
    token_path="token.pickle",
)

gc.add_event(
    Event(
        summary="Test event",
        start=gcsa.utils.to_datetime("2021-01-01 00:00:00"),
        end=gcsa.utils.to_datetime("2021-01-01 01:00:00"),
    )
)


import tensorflow as tf
tf.compat.v1.set_random_seed(66)

x = [1,2,3]
y = [3,5,7]

x_train = tf.placeholder(tf.float32, shape = [None])
y_train = tf.placeholder(tf.float32, shape = [None])
x_test = tf.placeholder(tf.float32, shape = [None])

w = tf.Variable([0.3])
b = tf.Variable([1.0])

hypothesis = x * w + b

loss = tf.reduce_mean(tf.square(hypothesis - y))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.17)
train = optimizer.minimize(loss)

# #3-2. 훈련
# sess = tf.compat.v1.Session()
# sess.run(tf.global_variables_initializer())

# #2.
# sess = tf.compat.v1.Session()
# sess.run(tf.compat.v1.global_variables_initializer())
# # bbb = 변수.eval(session = sess)

#3.
sess = tf.compat.v1.InteractiveSession()
sess.run(tf.compat.v1.global_variables_initializer())

for step in range(101):
    # sess.run(train)
    _, loss_val, w_val, b_val = sess.run([train, loss, w, b],
                                feed_dict={x_train : [1,2,3], y_train : [3,5,7]})
    if step % 1 == 0:
        # print(step, sess.run(loss), sess.run(w), sess.run(b))
        print(step, loss_val, w_val, b_val)

#4. 평가, 예측
test = x_test * w + b

#1.
# print(sess.run(test ,feed_dict = {x_test:[6,7,8]}))

#2.
# ccc = test.eval(session = sess, feed_dict = {x_test:[6,7,8]})
# print('ccc :', ccc)

#3.
print(test.eval(feed_dict = {x_test:[6,7,8]}))
# print(ddd)?
sess.close()


#!/usr/bin/env python3
# -*- coding:UTF-8

""" 使用管道进行进程间通信

读端-写端,类似与socket端口
每个端口即可以读入又可以写入
"""

import multiprocessing

def consumer(pipe):
    read_p, write_p = pipe
    write_p.close() # 关闭管道的写端
    while True:
        try:
            item = read_p.recv()
        except EOFError:
            break
        print(item)
    print('Consumer done')

def producer(seq,write_p):
    for item in seq:
        write_p.send(item)

if __name__ == '__main__':
    (read_p, write_p) = multiprocessing.Pipe()

    #消费者
    cons_p = multiprocessing.Process(target=consumer, args=((read_p, write_p),))
    cons_p.start()

    #关闭父进程的读端
    read_p.close()

    seq = range(100)
    producer(seq, write_p)

    # 生产完成，关闭生产者的写端
    # 否则，会在消费者的recv处阻塞挂起,important
    write_p.close()

    #等待消费者结束
    cons_p.join()
    print('Main process over')


from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl

SAMPLE_URL = "http://py4e-data.dr-chuck.net/comments_42.html"
ACTUAL_URL = "http://py4e-data.dr-chuck.net/comments_1511082.html"

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

# url = SAMPLE_URL
# url = ACTUAL_URL
url = input('Enter - ')
html = urlopen(url, context=ctx).read()
soup = BeautifulSoup(html, "html.parser")
total = 0

# Retrieve all of the anchor tags
tags = soup('span')
for tag in tags:
  raw_num = tag.contents[0]
  try:
    num = int(raw_num)
  except:
    continue
  total += num

print(total)


import random

def get_word():
    words=["lion", "umbrella", "window", "computer", "glass", "juice", "chair", "desktop","laptop", "dog", "cat", "lemon", "cabel", "mirror", "hat"]
    return random.choice(words).upper()

def check(word,guesses,guess):
    status=""
    matches=0
    for letter in word:
        if letter in guesses:
            status=status + letter
        else:
            status=status +'_'
        if letter==guess:
            matches=matches + 1
    if matches>1:
        print("Yes! the word contains",matches,"'" + guess + "'" +"s")
    elif matches==1:
        print("Yes!the word contain the letter" + guess + "'")
    else:
        print("sorry ,the word does not contain the leter:- "+ guess +"'")
    return status

def main():
    word=get_word()
    guesses=[]
    gussed=False
    limit=0

    print("the word contains",len(word),"letters")
    while not gussed:
        guess=input("please enter one letter or a {}-letter word.".format(len(word))).upper()
        if guess in guesses:
            print("you already guessed"+ guess + '"')
        elif len(guess)==len(word):
            guesses.append(guess)
            if guess==word:
                gussed=True
            else:
                print("sorry,that is incorrect.")
        elif len(guess)==1:
            guesses.append(guess)
            result=check(word,guesses,guess)
            if result==word:
                gussed=True

            else:
                print(result)
        else:
            print("Invalid entry")
    print("Yes ,the word is ",word + "!you got it in",len(guesses),"tries")
main()


def tail(f, n):
    assert n >= 0
    pos, lines = n+1, []
    while len(lines) <= n:
        try:
            f.seek(-pos, 2)
        except IOError:
            f.seek(0)
            break
        finally:
            lines = list(f)
        pos *= 2
    return lines[-n:]


#!python3
# dialogTable.py - 标准对话框使用示例

from tkinter import *
from tkinter.messagebox import askokcancel, askquestion, showerror
from tkinter.filedialog import askopenfilename
from tkinter.colorchooser import askcolor
from tkinter.simpledialog import askfloat

class Quitter(Frame):
    """
    验证退出请求的Quit按钮；封装成类，可复用、连接其它GUI实例
    """
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack()
        widget = Button(self, text='Quit', command=self.quit)
        widget.pack(side=LEFT, expand=YES, fill=BOTH)

    def quit(self):
        ans = askokcancel('Verify exit', 'Really quit?')        # 返回True或False
        if ans:
            Frame.quit(self)

demos = {'Open': askopenfilename,
         'Color': askcolor,             # 返回表示所选颜色的数据结构或元组(None,None)
         'Query': lambda: askquestion('warning', 'You typed "rm*"\nConfirm?'),  # 返回字符串'Yes'或'No'
         'Error': lambda: showerror('Error!', 'He is dead,Jack'),
         'Input': lambda: askfloat('Entry', 'Enter credit card number')}        # 返回浮点数字对象或None

class Demo(Frame):
    """
    创建简单的按钮栏，实现 demos 中的功能
    """
    def __init__(self, parent=None, **options):
        Frame.__init__(self, parent, **options)
        self.pack()
        Label(self, text='Basic Demos').pack()
        for (key, value) in demos.items():
            Button(self, text=key, command=value).pack(fill=BOTH, side=TOP)
        Quitter(self).pack(side=TOP, fill=BOTH)

if __name__ == '__main__':
    Demo().mainloop()


import unittest
from Lesson_11_survey import survey

class TestSurvey(unittest.TestCase):

    def setUp(self):
        """создание опроаса"""
        question = 'the best language is? '
        self.mysurvey = survey(question)
        self.answers = ['python', 'c#', '1c', 'c++']

    def test_save_single_answer(self):
        self.mysurvey.save_answer(self.answers[0])
        self.assertIn(self.answers[0], self.mysurvey.answers)

    def test_save_all_answer(self):
        for each in self.answers:
            self.mysurvey.save_answer(each)
        for each in self.answers:
            self.assertIn(each, self.mysurvey.answers)

unittest.main()


# Released by rdb under the Unlicense (unlicense.org)
# Based on information from:
# https://www.kernel.org/doc/Documentation/input/joystick-api.txt

import os, struct, array
import fcntl
from fcntl import ioctl

# Iterate over the joystick devices.
print('Available devices:')

for fn in os.listdir('/dev/input'):
    if fn.startswith('js'):
        print('  /dev/input/%s' % fn)

# We'll store the states here.
axis_states = {}
button_states = {}

# Axis and button mapping are joystick-specific
# Joystick (DragonRise Inc.   Generic   USB  Joystick  ) has 7 axes (X, Y, Z, Rx, Ry, Hat0X, Hat0Y)
# and 12 buttons (Trigger, ThumbBtn, ThumbBtn2, TopBtn, TopBtn2, PinkieBtn, BaseBtn, BaseBtn2, BaseBtn3, BaseBtn4, BaseBtn5, BaseBtn6).

# Run jscal -q to see the address mappings. Current output:
# jscal -u 7,0,1,2,3,4,16,17,12,288,289,290,291,292,293,294,295,296,297,298,299 /dev/input/js0

axis_names = {
    0x00 : 'axis0', # Binary L/R axis for 4-way button
    0x01 : 'axis1', # right joystick analog input L/R
    0x02 : 'axis2', # right joystick analog input U/D
    0x03 : 'axis3', # Binary U/D axis for 4-way button
}

button_names = {

    0x120 : 'but0',  # Triangle AND right joystick up/down
    0x121 : 'but1',  # Circle AND right joystick left/right
    0x122 : 'but2',  # Cross AND right joystick up/down
    0x123 : 'but3',  # Square AND right joystick left/right
    0x124 : 'but4',  # L2
    0x125 : 'but5',  # R2
    0x126 : 'but6',  # L1
    0x127 : 'but7',  # R1
    0x128 : 'but8',  # select
    0x129 : 'but9',  # start
    0x130 : 'but10',
    0x131 : 'but11', # analog - sends no event output
}

axis_map = []
button_map = []

# Open the joystick device.
fn = '/dev/input/js0'
print('Opening %s...' % fn)
jsdev = open(fn, 'rb')

# set to non-blocking!!!
flag = fcntl.fcntl(jsdev, fcntl.F_GETFD)
fcntl.fcntl(jsdev, fcntl.F_SETFL, flag | os.O_NONBLOCK)

# Get the device name.

# Get number of axes and buttons.
buf = array.array('B', [0])
ioctl(jsdev, 0x80016a11, buf) # JSIOCGAXES
num_axes = buf[0]

buf = array.array('B', [0])
ioctl(jsdev, 0x80016a12, buf) # JSIOCGBUTTONS
num_buttons = buf[0]

# Get the axis map.
buf = array.array('B', [0] * 0x40)
ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP

for axis in buf[:num_axes]:
    axis_name = axis_names.get(axis, 'unknown(0x%02x)' % axis)
    axis_map.append(axis_name)
    axis_states[axis_name] = 0.0

# Get the button map.
buf = array.array('H', [0] * 200)
ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP

for btn in buf[:num_buttons]:
    btn_name = button_names.get(btn, 'unknown(0x%03x)' % btn)
    button_map.append(btn_name)
    button_states[btn_name] = 0

print('{:d} axes found '.format(num_axes))

print('{:d} buttons found '.format(num_buttons))

# Main control loop
# The following code is event-based. That means the values are ONLY updated on change.

# It might be more intuitive to update all buttons/axes in a continuous loop.

# how this works: every time something is pressed on the joystick, it logs an EVENT
# in the EVENT QUEUE
# We continuously read from the event queue. HOWEVER this means that if a value isn't changed,
# we don't see it in the queue.

# It MAY be possible to poll joystick values continuously (check joystick API and maybe evdev API?)
# but in the meantime we can write code that APPEARS continuous even though it is event-based

def main():
    running = True

    # Observe that axis map and button map contain the CURRENT STATE of each axis.

    while running:
        # To see a continuously updated list of the current values of all buttons and axes, uncomment the below

        # print current controller state:
        #for butt in button_map:
        #    print("{name} : {val} ".format(name=butt, val=button_states[butt]))

        #for ax in axis_map:
        #    print("{name} : {val} ".format(name=ax, val=axis_states[ax]))

        # Use current joystick state to control robot

        # Axis 2 is the only analog axis BUT can act as 2 axes by combining with buttons
        # Axis 2 can be controlled by:
        # L/R on left toggle
        # U/D on right toggle (this also toggles the states of buttons 0 or 2)

        # Example code:

        try:
            # read
            evbuf = jsdev.read(8)
            if evbuf:
                time, value, intype, number = struct.unpack('IhBB', evbuf)

                if intype & 0x01:
                    button = button_map[number]
                    if button:
                        button_states[button] = value

                if intype & 0x02:
                    axis = axis_map[number]
                    if axis:
                        fvalue = value / 32767.0
                        axis_states[axis] = fvalue

        except:
            pass

        # get value from axis 2
        diraxis = axis_map[2]
        ax2val = axis_states[diraxis]

        # check button states
        butt0 = button_map[0]
        butt2 = button_map[2]

        # There are several methods to determine which combination of button/axes has been set!
        # this is just one example

        if (button_states[butt0] or button_states[butt2]):
            # we should be moving forwards or backwards
            if ax2val > 0:
                print("Going backwards at {} ".format(ax2val))

            if ax2val < 0:
                print ("Going forwards at {} ".format(ax2val))

        else: # we should be turning left or right
            if ax2val < 0:
                print("Turning left at {} ".format(ax2val))
            elif ax2val > 0 :
                print("Turning right at {} ".format(ax2val))

        # Things to think about:
        # how can we change between turning on the spot and turning while moving forward or back?
        # what other controls might be useful?

if __name__ == '__main__':
  main()


import numpy as np
from scipy import signal
import sys

sys.path.insert(0, '../src')

from core import Sequential, MIMO_Wrapper
from dsp.modem import get_alphabet, Modulator
from dsp.frontend import Upsampler, SRRC_filter
from dsp.optical import CMA
from channels.mimo import Selective_Channel, AWGN
from analysers.scope import IQ_Scope
import matplotlib.pyplot as plt

def generate_H_list(N_tap, N_t, coef=0.3):
    """
    Generate a list of MIMO channel (one matrix by tap)
    """

    I_mat = np.eye(N_t)
    H_list = []
    for indice in range(N_tap):
        B = np.random.randn(N_t, N_t) + 1j*np.random.randn(N_t, N_t)
        H_temp = (coef**indice)*(I_mat + B)
        H_list.append(H_temp)

    return H_list

# parameters
type, M = "PSK", 4
N_t = 2
N_tap = 8
N = 100000
oversampling = 2
rolloff = 0.2
sigma2 = 0.001
nlim = [N-2000, N]

alphabet = get_alphabet(type, M)

# generate siso stream at transmitter side
tx_siso = Sequential([Modulator(alphabet), Upsampler(oversampling), SRRC_filter(rolloff, oversampling)])

# generate random channel
H_list = generate_H_list(N_tap, N_t)

# create chain
channel = Sequential([
            MIMO_Wrapper(tx_siso, N_t),
            Selective_Channel(H_list),
            AWGN(0.001),
            MIMO_Wrapper(IQ_Scope(num="scope1", nlim=nlim), N_t),
            CMA(10, alphabet, mu=0.0001, oversampling=oversampling),
            MIMO_Wrapper(IQ_Scope(num="scope2", nlim=nlim), N_t),
            ])

# simulate communication
S = np.random.randint(0, high=M, size=(2,N))
Y = channel(S)
plt.show()


# Start Your Code here

# Should have the following methods:
# Take a Ticket //
# Decrease the amount of tickets available by 1 //
# Decrease the amount of parking spaces available by 1 //
# Pay for parking
# Display an input that waits for an amount from the user and stores it as a variable
# If the payment variable is not empty (meaning the ticket has been paid) then dispay a message to the user that their ticket has been paid and they have 15 min to leave
# This should update the "current ticket" DICTIONARY key "paid" to True
# leave garage
# If the ticket has been paid, display a messsage of "Thank you, have a nice day!"
# If the ticket has not been paid, display an input prompt for payment
# Once paid, display message, "Thank you, have a nice day!"
# Update parking spaces LIST to increase by 1 (meaning add to the parking spaces LIST //
# tickets >> LIST     parking spaces >> LIST     current ticket >> DICTIONARY

class Garage:
    def __init__(self):
        self.tickets = 10
        self.spots = 10
        self.activeTicket = {"paid": False}

# car enters, takes ticket, one less ticket, one less spot

    def newTicket(self):
        print("Please remember to take your ticket and please enter the garage.")
        self.tickets -= 1
        print(f"There are {self.tickets} tickets available in this garage.")
        self.spots -= 1
        print(
            f"There are {self.spots} parking spaces available in this garage.")

# pay ticket

    def pay(self):
        while True:
            payment = int(input("Please insert $100 and type 100 to confirm."))
            if payment == 100:  # parking is 10 dollars
                print(
                    "Your payment has been accepted. You have 15 minutes to leave or payment will triple. You will be taken back to the main menu now.")
                self.activeTicket["paid"] = True
                break
            else:
                print("SHOW ME THE MONEY!")

# leave garage
    def exitGarage(self):
        if self.activeTicket["paid"] == True:
            print("Thank you, have a nice day!")
            self.tickets += 1
            print(
                f"There are {self.tickets} tickets available in this garage.")
            self.spots += 1
            print(
                f"There are {self.spots} parking spaces available in this garage.")
# if ticket has not been paid
        else:
            while True:
                exiting = int(input("You still owe $100. Insert $100 and type 100 to confirm."))
                if exiting == 100:
                    print("Thank you, have a nice day!")
                    break
                else:
                    print("You did not show me the money. You live here now.")

#run the code
def scenario():
    while True:
        new = int(input("\nPlease select from the following options:\n Select 1 to Print Ticket and Enter Garage\n Select 2 to Pay for Parking \n Select 3 to Leave Garage\n"))

        if new == 1:
            fellsPoint.newTicket()
        elif new == 2:
            fellsPoint.pay()
        elif new == 3:
            fellsPoint.exitGarage()
            break

#name it
fellsPoint = Garage()
scenario()


#entrada & processamento
for i in range(0, 5):
    peso = float(input(f'Peso da 1ª pessoa: '))
    if i == 0:
        maior = menor = peso
    else:
        if peso > maior:
            maior = peso
        if peso < menor:
            menor = peso

#saida
print(f'O maior peso lido foi de {maior:.2f}Kg')
print(f'O menor peso lido foi de {menor:.2f}Kg')


# ðŸ’¡ **Question 1**

# A permutation perm of n + 1 integers of all the integers in the range [0, n] can be represented as a string s of length n where:

# - s[i] == 'I' if perm[i] < perm[i + 1], and
# - s[i] == 'D' if perm[i] > perm[i + 1].

# Given a string s, reconstruct the permutation perm and return it. If there are multiple valid permutations perm, return **any of them**.

# **Example 1:**

# **Input:** s = "IDID"

# **Output:**

# [0,4,1,3,2]

# Solution

def reconstruct_permutation(s):
    n = len(s)
    perm = [0] * (n + 1)
    low, high = 0, n

    for i in range(n):
        if s[i] == 'I':
            perm[i] = low
            low += 1
        else:
            perm[i] = high
            high -= 1

    perm[n] = low

    return perm

# ðŸ’¡ **Question 2**

# You are given an m x n integer matrix matrix with the following two properties:

# - Each row is sorted in non-decreasing order.
# - The first integer of each row is greater than the last integer of the previous row.

# Given an integer target, return true *if* target *is in* matrix *or* false *otherwise*.

# You must write a solution in O(log(m * n)) time complexity.

# Solution

def search_matrix(matrix, target):
    m, n = len(matrix), len(matrix[0])
    left, right = 0, m * n - 1

    while left <= right:
        mid = left + (right - left) // 2
        num = matrix[mid // n][mid % n]

        if num == target:
            return True
        elif num < target:
            left = mid + 1
        else:
            right = mid - 1

    return False

# ðŸ’¡ **Question 3**

# Given an array of integers arr, return *true if and only if it is a valid mountain array*.

# Recall that arr is a mountain array if and only if:

# - arr.length >= 3
# - There exists some i with 0 < i < arr.length - 1 such that:
#     - arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
#     - arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

def valid_mountain_array(arr):
    n = len(arr)
    if n < 3:
        return False

    i = 0
    while i < n - 1 and arr[i] < arr[i + 1]:
        i += 1

    if i == 0 or i == n - 1:
        return False

    while i < n - 1 and arr[i] > arr[i + 1]:
        i += 1

    return i == n - 1

# ðŸ’¡ **Question 4**

# Given a binary array nums, return *the maximum length of a contiguous subarray with an equal number of* 0 *and* 1.

# **Example 1:**

# **Input:** nums = [0,1]

# **Output:** 2

# **Explanation:**

# [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.

# Solution

def find_max_length(nums):
    count = 0
    max_length = 0
    count_map = {0: -1}  # Initial count of 0 is -1 to handle starting edge case

    for i, num in enumerate(nums):
        if num == 0:
            count -= 1
        else:
            count += 1

        if count in count_map:
            max_length = max(max_length, i - count_map[count])
        else:
            count_map[count] = i

    return max_length

# ðŸ’¡ **Question 5**

# The **product sum** of two equal-length arrays a and b is equal to the sum of a[i] * b[i] for all 0 <= i < a.length (**0-indexed**).

# - For example, if a = [1,2,3,4] and b = [5,2,3,1], the **product sum** would be 1*5 + 2*2 + 3*3 + 4*1 = 22.

# Given two arrays nums1 and nums2 of length n, return *the **minimum product sum** if you are allowed to **rearrange** the **order** of the elements in* nums1.

# **Example 1:**

# **Input:** nums1 = [5,3,4,2], nums2 = [4,2,2,5]

# **Output:** 40

# **Explanation:**

# We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40.

# Solution

def min_product_sum(nums1, nums2):
    nums1.sort()
    nums2.sort(reverse=True)

    min_product = 0

    for i in range(len(nums1)):
        min_product += nums1[i] * nums2[i]

    return min_product

# ðŸ’¡ **Question 6**

# An integer array original is transformed into a **doubled** array changed by appending **twice the value** of every element in original, and then randomly **shuffling** the resulting array.

# Given an array changed, return original *if* changed *is a **doubled** array. If* changed *is not a **doubled** array, return an empty array. The elements in* original *may be returned in **any** order*.

# **Example 1:**

# **Input:** changed = [1,3,4,2,6,8]

# **Output:** [1,3,4]

# **Explanation:** One possible original array could be [1,3,4]:

# - Twice the value of 1 is 1 * 2 = 2.
# - Twice the value of 3 is 3 * 2 = 6.
# - Twice the value of 4 is 4 * 2 = 8.

# Other original arrays could be [4,3,1] or [3,1,4].

# Solution

def find_original(changed):
    counter = {}

    for num in changed:
        if num not in counter:
            counter[num] = 0
        counter[num] += 1

    original = []

    for num in counter:
        if num * 2 not in counter or counter[num] != counter[num * 2]:
            return []

        original += [num] * counter[num]

    return original

# ðŸ’¡ **Question 7**

# Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

# **Example 1:**
# **Input:** n = 3

# **Output:** [[1,2,3],[8,9,4],[7,6,5]]

#Solution

def generate_matrix(n):
    matrix = [[0] * n for _ in range(n)]
    num = 1
    top, bottom, left, right = 0, n - 1, 0, n - 1

    while num <= n * n:
        for i in range(left, right + 1):
            matrix[top][i] = num
            num += 1
        top += 1

        for i in range(top, bottom + 1):
            matrix[i][right] = num
            num += 1
        right -= 1

        for i in range(right, left - 1, -1):
            matrix[bottom][i] = num
            num += 1
        bottom -= 1

        for i in range(bottom, top - 1, -1):
            matrix[i][left] = num
            num += 1
        left += 1

    return matrix

# ðŸ’¡ **Question 8**

# Given two [sparse matrices](https://en.wikipedia.org/wiki/Sparse_matrix) mat1 of size m x k and mat2 of size k x n, return the result of mat1 x mat2. You may assume that multiplication is always possible.

# **Example 1:**

def multiply_matrices(mat1, mat2):
    m, k = len(mat1), len(mat1[0])
    n = len(mat2[0])

    result = [[0] * n for _ in range(m)]

    for i in range(m):
        for j in range(n):
            for x in range(k):
                result[i][j] += mat1[i][x] * mat2[x][j]

    return result


##UTLILISE LE FILTRE DE CANNY
import time
from mpu9250_jmdev.registers import *
from mpu9250_jmdev.mpu_9250 import MPU9250
import VL53L0X

import picamera
import datetime

import numpy as np
from numpy import asarray
import matplotlib.pyplot as plt
from PIL import Image as img
import math as m
import cv2
#import cv2 as cv

def capture(name,x=3280, y=1845): #accède à la caméra, prend une capture et la sauvegarde sous le nom "name" : le "name doit inclure le formar .png ou jpg
    camera = picamera.PiCamera()
    camera.resolution = (x,y)
    camera.capture(name)
    imBrute = img.open(name)
    return (imBrute)

def traitementImageCanny(imBrute): #application du filtre de canny : Binarisation de l'image, application d'un filtre gradient pour détection de contours

    imTraitement = cv2.imread(imBrute.filename)  # Read image

    #Setting parameter values
    t_lower = 80  # Lower Threshold
    t_upper = 110  # Upper threshold

    # Applying the Canny Edge filter
    edge = cv2.Canny(imTraitement, t_lower, t_upper)
    imTraitee=img.fromarray(edge)
    imTraitee.show()
    return (imTraitee)

def constructionMatriceAccumulatrice(imTraitee,resolutionAngulaire = 1, resolutionDistance=1): #construction de la matrice accumulatrice pour la détection de droite
    theta = [k for k in range(0,int(180/resolutionAngulaire),1)]
    distanceMax=int((((3280/resolutionDistance)**2)+((1845/resolutionDistance)**2))**(1/2))+1 #longueur maximale de rho dnas le plan de hough, conditionné par la diagonale
    matriceAccumulatrice = np.zeros((int(180/resolutionAngulaire),distanceMax)) #matrice qui permettra le dessin du plan de hough
    coord= []
    for x in range(int(3280/resolutionDistance)) :
        for y in range(int(1845/resolutionDistance)):
            if imTraitee.getpixel((x*resolutionDistance,y*resolutionDistance))==255:
                coord.append((x*resolutionDistance,y*resolutionDistance))
    #récupéré les coordonnées des points d'intérêt

    for a in coord :
        for T in theta:
            T=T*resolutionAngulaire
            x=a[0]
            y=a[1]
            r=((x/resolutionDistance)*m.cos((T*2*m.pi)/360))+((y/resolutionDistance)*m.sin((T*2*m.pi)/360))
            matriceAccumulatrice[int(T/resolutionAngulaire)][int(r)] +=1
    return ([matriceAccumulatrice, imTraitee])

def reconstructionDroite(matriceAccumulatrice,imBrute,resolutionAngulaire,resolutionDistance, nbligne):
    largeurX = len(matriceAccumulatrice[0])
    longueurY = len(matriceAccumulatrice[0][0])
    planDeHough = img.new("L",size=(largeurX,longueurY))
    for x in range(largeurX):
        for y in range (longueurY):
            planDeHough.putpixel((x,y),int(matriceAccumulatrice[0][x,y]))
    planDeHough.save("plan_de_hough.jpg")
    #on montre le plan de hough
    plt.imshow(planDeHough,cmap="binary_r")
    plt.xlabel("theta")
    plt.ylabel("rho")
    plt.suptitle("plan de hough")
    plt.show()

    #recherche du max
    max_index = np.unravel_index(matriceAccumulatrice[0].argmax(), matriceAccumulatrice[0].shape) #trouve l'index d'un max de la matrice
    m=matriceAccumulatrice[0][max_index]
    listMax=[max_index]
    valeurmax=matriceAccumulatrice[0][max_index]
    matriceAccumulatrice[0][max_index]=0
    nb=1;
    while (nb<nbligne):
        max_index = np.unravel_index(matriceAccumulatrice[0].argmax(), matriceAccumulatrice[0].shape)
        while ((((max_index[0]-listMax[0][0])**2)+((max_index[1]-listMax[0][1])**2))**(1/2) <=20):
            matriceAccumulatrice[0][max_index]=0
            max_index = np.unravel_index(matriceAccumulatrice[0].argmax(), matriceAccumulatrice[0].shape)

        listMax.append(max_index)
        nb+=1

    print("index du max et valeur :",max_index,valeurmax)

    #coloriage des max
    for z in listMax:
        x=z[0]
        y=z[1]
        for i in range(-1,2):
            for j in range(-1,2):
                if x+i >=0 and y+j >=0 and x+i<largeurX and y+j <longueurY  :
                    planDeHough.putpixel((x+i,y+j),190)
    plt.imshow(planDeHough,cmap="binary_r")
    plt.xlabel("theta")
    plt.ylabel("rho")
    plt.suptitle("plan de hough avec repérage des max")
    plt.show()

    print("ci joint la liste des maximas globaux de la matrice accumulatrice :")
    print(listMax)

    distanceMax=int(((3280**2)+(1845**2))**(1/2)+1) #diagonale maximale
    print ("distance max = ", distanceMax)
    stockEquation=[]
    for w in range(len(listMax)):
        thetaL=listMax[w][0]*resolutionAngulaire
        rhoL=listMax[w][1]*resolutionDistance
        print("thetaL=",thetaL,"rhoL =",rhoL)
        while (rhoL>=distanceMax/2) :
            print(rhoL, "  avant")
            rhoL =rhoL - distanceMax
            print(rhoL, "  après")

        #equation de la forme ax + b
        if (thetaL!=0):
            a1=-np.cos(thetaL*2*np.pi/360)/np.sin(thetaL*2*np.pi/360)
            b1=rhoL/np.sin(thetaL*2*np.pi/360)
            x=[k for k in range(3280)]
            y=[((a1*x[k])+b1) for k in x]
            print ("équation trouvée : ","y = ",a1,"x + ",b1)
            stockEquation.append([x,y])
        else :
            x=[rhoL for k in range(3280)]
            y=[k for k in range(3280)]
            stockEquation.append([x,y])

        for k in range(len(x)):
            if y[k]>=0 and y[k]<1845:
                imBrute.putpixel((x[k],int(y[k])),150)
            if y[k]>=0 and y[k]+1<1845:
                imBrute.putpixel((x[k],int(y[k]+1)),150)
            if y[k]>=0 and y[k]-1<1845:
                imBrute.putpixel((x[k],int(y[k]-1)),150)
            if y[k]>=0 and y[k]<1845 and x[k]+1<3280:
                imBrute.putpixel((x[k]+1,int(y[k])),150)
            if y[k]>=0 and y[k]<1845 and x[k]-1>=0:
                imBrute.putpixel((x[k]-1,int(y[k])),150)

        #tracage du centre
        for u in range(-1,2):
            for i in range(-10,11):
                if 1640+u+i >= 0 and 1640 + u +i <3280 and 922+u+i>=0 and 922+u+i<1845:
                    imBrute.putpixel((1640+u+i,922+u),150)
                    imBrute.putpixel((1640+u,922+i+u),150)
    imBrute.show()

    return stockEquation

def Horizon(imageBrute,resolutionAngulaire,resolutionDistance, nbligne):
    stockEquation=reconstructionDroite(constructionMatriceAccumulatrice(traitementImageCanny(imageBrute),resolutionAngulaire,resolutionDistance),imageBrute,resolutionAngulaire,resolutionDistance, nbligne)
    return stockEquation

### cercle dont on connait le rayon

def coordCercleRayonEstime(a,b,rayonEstime,matrice,resolutionDistance, resolutionAngulaireCercleInter):#a et b coordonnnées réelles de son centre en pixels, resol détermine le nombre de points du cercle
    theta=0
    pasAngulaire=(2*m.pi)/resolutionAngulaireCercleInter
    while(theta<2*m.pi):
        x=int(rayonEstime*m.cos(theta)+a)
        y=int(rayonEstime*m.sin(theta)+b)
        theta+=pasAngulaire
        if ((x<3280) and (y<1845) and (x>=0) and (y>=0)):
            matrice[int(x/resolutionDistance)][int(y/resolutionDistance)]+=1

def constructionMatriceAccumulatriceCercleConnu(imTraitee,rayonEstime, resolutionAngulaire = 1, resolutionDistance=1, resolutionAngulaireCercleInter=32):

    matriceAccumulatriceCercleConnu = np.zeros((int(3280/resolutionAngulaire)+1,int(1845/resolutionDistance)+1)) #matrice qui permettra le dessin du plan de hough
    coord= [] #rassemble les points d'intérêt, i.e ceux qui sont un contour
    for x in range(int(3280/resolutionDistance)) :
        for y in range(int(1845/resolutionDistance)):
            if imTraitee.getpixel((x*resolutionDistance,y*resolutionDistance))==255:
                coordCercleRayonEstime(x*resolutionDistance,y*resolutionDistance,rayonEstime,matriceAccumulatriceCercleConnu,resolutionDistance,resolutionAngulaireCercleInter)
    #récupéré les coordonnées des points d'intérêt, en pixels de l'image, sans les considérations de résolution
    return matriceAccumulatriceCercleConnu

def reconstructionCercle(matriceAccumulatriceCercleConnu,imBrute,rayonEstime,resolutionAngulaire=1,resolutionDistance=1,resolutionAngulaireCercleInter=32):
    largeurX = len(matriceAccumulatriceCercleConnu)
    longueurY = len(matriceAccumulatriceCercleConnu[0])
    planDeHoughCercle = img.new("L",size=(largeurX,longueurY))
    for x in range(largeurX):
        for y in range (longueurY):
            planDeHoughCercle.putpixel((x,y),int(matriceAccumulatriceCercleConnu[x,y]))
    planDeHoughCercle.save("plan_de_hough.jpg")
    #on montre le plan de hough
    plt.imshow(planDeHoughCercle,cmap="binary_r")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.suptitle("plan de hough")
    plt.show()

    #recherche du max
    max_index = np.unravel_index(matriceAccumulatriceCercleConnu.argmax(), matriceAccumulatriceCercleConnu.shape) #trouve l'index d'un max de la matrice
    m=matriceAccumulatriceCercleConnu[max_index]
    matriceAccumulatriceCercleConnu[max_index]=0
    listMax=[max_index]
    print("index du max et valeur :",max_index,m)
    while (matriceAccumulatriceCercleConnu[np.unravel_index(matriceAccumulatriceCercleConnu.argmax(), matriceAccumulatriceCercleConnu.shape)]==m):
        listMax.append(np.unravel_index(matriceAccumulatriceCercleConnu.argmax(), matriceAccumulatriceCercleConnu.shape))
        matriceAccumulatriceCercleConnu[np.unravel_index(matriceAccumulatriceCercleConnu.argmax(), matriceAccumulatriceCercleConnu.shape)]=0

    #coloriage des max
    for z in listMax:
        x=z[0]
        y=z[1]
        for i in range(-2,3):
            for j in range(-2,3):
                if (x+i<int(3280/resolutionDistance)) and (x+i >0) and (y+i<int(1845/resolutionDistance)) and (y+i >0):
                    planDeHoughCercle.putpixel((x+i,y+j),210)
    plt.imshow(planDeHoughCercle,cmap="binary_r")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.suptitle("plan de hough avec repérage du max")
    plt.show()

    print("ci joint la liste des maximas globaux de la matrice accumulatrice :")
    print(listMax)
    aCentre=listMax[0][0]*resolutionDistance
    bCentre=listMax[0][1]*resolutionDistance

    print("aCentre=",aCentre,"bCentre =",bCentre)

    #determination des coordonnees du cercle determiné pour le tracer sur l'image brute
    theta=0
    coordCercle=[]
    pasAngulaire=(2*np.pi)/(resolutionAngulaireCercleInter*20) #le coef multiplicatif est là pour traçer plus de points du cercle
    while (theta<2*np.pi):
        coordCercle.append((int(rayonEstime*np.cos(theta)+aCentre),int(rayonEstime*np.sin(theta)+bCentre)))
        theta+=pasAngulaire

    print("quelques coordonnées du cercle et la longueur de la liste : ", len(coordCercle),"  ", coordCercle[0],"   ", coordCercle[-1])
    for c in coordCercle:
        for k in range(-3,4):
            for j in range(-3,4):
                if ((c[0]+k<3280) and (c[1]+j<1845) and (c[0]+k>=0) and (c[1]+j>=0)):
                    imBrute.putpixel((c[0]+k,c[1]+j),120)
    for k in range(-3,4):
            for j in range(-3,4):
                if ((aCentre+k<3280) and (bCentre+j<1845) and (aCentre+k>=0) and (bCentre+j>=0)):
                    imBrute.putpixel((aCentre+k,bCentre+j),120)
    plt.imshow(imBrute)
    plt.xlabel("x")
    plt.ylabel("y")
    plt.suptitle("image brute avec le cercle trouvé")
    plt.show()

def reconnaissanceCercleRayonConnu(imageBrute,rayonEstime,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter):
    reconstructionCercle(constructionMatriceAccumulatriceCercleConnu(traitementImageCanny(imageBrute), rayonEstime,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter),imageBrute, rayonEstime,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter)

###Cercle de rayon inconnu

def coordCercleRayonR(a,b,r,matrice,pasDeRayon,resolutionDistance, resolutionAngulaireCercleInter):#a et b coordonnnées réelles de son centre en pixels, resol détermine le nombre de points du cercle
    theta=0
    pasAngulaire=(2*m.pi)/resolutionAngulaireCercleInter
    while(theta<2*m.pi):
        x=int(r*m.cos(theta)+a)
        y=int(r*m.sin(theta)+b)
        theta+=pasAngulaire
        if ((x<3280) and (y<1845) and (x>=0) and (y>=0)):
            matrice[int(r/pasDeRayon)][int(x/resolutionDistance)][int(y/resolutionDistance)]+=50

def traitementImageCannyGradient(imBrute, stockEquation=[]):
    imTraitement = cv2.imread(imBrute.filename)  # Read image

    #Setting parameter values
    t_lower = 60  # Lower Threshold
    t_upper = 110  # Upper threshold

    # Applying the Canny Edge filter
    imTraitee = cv2.Canny(imTraitement, t_lower, t_upper)

    #effaçage des droites trouvées pour ne pas perturber la détection de cercle sur l'image NB de canny

    for k in range(len(stockEquation)):
        x=stockEquation[k][0]
        y=stockEquation[k][1]
        for l in range(len(x)):
            for i in range(-15,16):
                for j in range(-15,16):
                    if round(x[l])+i < 3280 and round(x[l])+i >=0:
                        if round(y[l])+j>=0 and round(y[l])+j <1845:
                            if imTraitee[round(y[l])+j][round(x[l])+i] >10:
                                imTraitee[round(y[l])+j][round(x[l])+i]=0

    apercu=img.fromarray(imTraitee)
    apercu.show()
    return (imTraitee)

def constructionMatriceAccumulatriceCercleInconnu(imTraitee,pasDeRayon=10, rayonMini=25 ,resolutionAngulaire = 1, resolutionDistance=1, resolutionAngulaireCercleInter=32):
    #matrices de convolution
    Gx=np.array(([-1,0,1],[-2,0,2],[-1,0,1]))
    Gy=np.array(([-1,-2,-1],[0,0,0],[1,2,1]))
    distanceMax=round(1845/2)
    #on considère que le rayon du cercle que l'on vera a un rayon minimal et un rayon maximal
    matriceAccumulatriceCercleInconnu=np.zeros((((distanceMax-rayonMini)//pasDeRayon)+2,round(1845/resolutionDistance)+2,round(3280/resolutionDistance)+1))
    CXY=[] #liste des coordonnées des points du cercle de la matrice accumulatrice
    for x in range(round(3280/resolutionDistance)) :
        for y in range(round(1845/resolutionDistance)):
            if imTraitee[y*resolutionDistance,x*resolutionDistance]==255:
                matriceAccumulatriceCercleInconnu[len(matriceAccumulatriceCercleInconnu)-1,y,x]=1
                CXY.append([[x,y]])#faux pixels
    for i in range(len(CXY)):
        x=CXY[i][0][0]*resolutionDistance #conversion en vrais pixels
        y=CXY[i][0][1]*resolutionDistance #conversion en vrais pixels
        if x>=1 and y>=1 and x<3279 and y<1844 :
            A=np.array(([imTraitee[y-1,x-1],imTraitee[y-1,x],imTraitee[y-1,x+1]],[imTraitee[y,x-1],imTraitee[y,x],imTraitee[y,x+1]],[imTraitee[y+1,x-1],imTraitee[y+1,x],imTraitee[y+1,x+1]])) #matrice 3x3 autour du point du cercle considéré
            CXY[i].append(m.atan2((((Gy*A).sum())/9),(((Gx*A).sum())/9)))
            for r in range(rayonMini,distanceMax,pasDeRayon):
                theta=CXY[i][1]*360/(2*np.pi)
                U=np.arange(theta-25,theta+25,1)
                x=CXY[i][0][0]
                y=CXY[i][0][1]
                for T in U:
                    a=round(r*m.cos(T*2*np.pi/360)+x)
                    b=round(r*m.sin(T*2*np.pi/360)+y)
                    if (a>=0) and (a<round(3280/resolutionDistance)) and (b>=0) and (b<round(1845/resolutionDistance)):
                        matriceAccumulatriceCercleInconnu[((r-rayonMini)//pasDeRayon),b,a]+=1
                    a=round(-r*m.cos(-T*2*np.pi/360)+x)
                    b=round(-r*m.sin(-T*2*np.pi/360)+y)
                    if (a>=0) and (a<round(3280/resolutionDistance)) and (b>=0) and (b<round(1845/resolutionDistance)):
                        matriceAccumulatriceCercleInconnu[((r-rayonMini)//pasDeRayon),b,a]+=1
    plt.imshow(matriceAccumulatriceCercleInconnu[len(matriceAccumulatriceCercleInconnu)-1])
    plt.show()
    return matriceAccumulatriceCercleInconnu

def reconstructionCercleInconnu(matriceAccumulatriceCercleInconnu,imBrute,pasDeRayon=10,rayonMini=25,resolutionAngulaire=1,resolutionDistance=1,resolutionAngulaireCercleInter=32):
    #recherche du max
    max_index = np.unravel_index(matriceAccumulatriceCercleInconnu.argmax(), matriceAccumulatriceCercleInconnu.shape) #trouve l'index d'un max de la matrice
    m=matriceAccumulatriceCercleInconnu[max_index]
    matriceAccumulatriceCercleInconnu[max_index]=0
    listMax=[max_index]
    print("index du max et valeur :",max_index,m)
    while (matriceAccumulatriceCercleInconnu[np.unravel_index(matriceAccumulatriceCercleInconnu.argmax(), matriceAccumulatriceCercleInconnu.shape)]==m):
        listMax.append(np.unravel_index(matriceAccumulatriceCercleInconnu.argmax(), matriceAccumulatriceCercleInconnu.shape))
        matriceAccumulatriceCercleInconnu[np.unravel_index(matriceAccumulatriceCercleInconnu.argmax(), matriceAccumulatriceCercleInconnu.shape)]=0
    print("longueur liste des maxima : ", len(listMax), "      coordonnées : ", listMax)

    bCentre=listMax[0][1]*resolutionDistance
    aCentre=listMax[0][2]*resolutionDistance
    rayon=((listMax[0][0]*pasDeRayon)+rayonMini)*resolutionDistance

    plt.imshow(matriceAccumulatriceCercleInconnu[listMax[0][0]])
    plt.show()

    for i in range(-3,4):
        for j in range(-3,4):
            imBrute.putpixel((int(aCentre)+i,int(bCentre)+j),180)

    print("aCentre=",aCentre,"   bCentre =",bCentre,"   rayon =",rayon)

    #determination des coordonnees du cercle determiné pour le tracer sur l'image brute
    theta=0
    coordCercle=[]
    pasAngulaire=(2*np.pi)/(resolutionAngulaireCercleInter*20) #le coef multiplicatif est là pour traçer plus de points du cercle
    while (theta<2*np.pi):
        coordCercle.append((int(rayon*np.cos(theta)+aCentre),int(rayon*np.sin(theta)+bCentre)))
        theta+=pasAngulaire

    for c in coordCercle:
        for k in range(-3,4):
            for j in range(-3,4):
                if ((c[0]+k<3280) and (c[1]+j<1845) and (c[0]+k>=0) and (c[1]+j>=0)):
                    imBrute.putpixel((c[0]+k,c[1]+j),120)
    for k in range(-3,4):
            for j in range(-3,4):
                if ((aCentre+k<3280) and (bCentre+j<1845) and (aCentre+k>=0) and (bCentre+j>=0)):
                    imBrute.putpixel((aCentre+k,bCentre+j),120)
    #centre du cercle
    for u in range(-1,2):
            for i in range(-10,11):
                if aCentre+u+i >= 0 and aCentre + u +i <3280 and bCentre+u+i>=0 and bCentre+u+i<1845:
                    imBrute.putpixel((aCentre+u+i,bCentre+u),150)
                    imBrute.putpixel((aCentre+u,bCentre+i+u),150)

    plt.imshow(imBrute)
    plt.xlabel("x")
    plt.ylabel("y")
    plt.suptitle("image brute avec le cercle trouvé")
    plt.show()
    return  [imBrute,aCentre,bCentre]

def reconnaissanceCercleRayonInconnu(imageBrute,pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter):
    reconstructionCercleInconnu(constructionMatriceAccumulatriceCercleInconnu(traitementImageCannyGradient(imageBrute), pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter),imageBrute, pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter)

def MatriceDistances (distance, angle=0, FOVX=62, FOVY=49, resol=20):
    matriceDist=np.zeros((2,int(1845/resol)+1,int(3280/resol) +1))
    for x in range(0,1640,resol):
        for y in range(0,922,resol):
            thetaX=(FOVX/2)*(x/1640)
            thetaY=(FOVY/2)*(y/922)
            dx=m.tan(thetaX*m.pi/180)*distance
            dy=m.tan(thetaY*m.pi/180)*distance
            matriceDist[0][(int(1845/(2*resol)))+int(y/resol)][(int(3280/(2*resol)))+int(x/resol)]=dx
            matriceDist[0][(int(1845/(2*resol)))+int(y/resol)][(int(3280/(2*resol)))-int(x/resol)]=dx
            matriceDist[0][(int(1845/(2*resol)))-int(y/resol)][(int(3280/(2*resol)))+int(x/resol)]=dx
            matriceDist[0][(int(1845/(2*resol)))-int(y/resol)][(int(3280/(2*resol)))-int(x/resol)]=dx
            matriceDist[1][(int(1845/(2*resol)))+int(y/resol)][(int(3280/(2*resol)))+int(x/resol)]=dy
            matriceDist[1][(int(1845/(2*resol)))+int(y/resol)][(int(3280/(2*resol)))-int(x/resol)]=dy
            matriceDist[1][(int(1845/(2*resol)))-int(y/resol)][(int(3280/(2*resol)))+int(x/resol)]=dy
            matriceDist[1][(int(1845/(2*resol)))-int(y/resol)][(int(3280/(2*resol)))-int(x/resol)]=dy
    return matriceDist

def total(imBrute,pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter, nblignes): #combine la détection de lignes et de cercle

    stockEquation=Horizon(imBrute,resolutionAngulaire,resolutionDistance,nblignes)
    [imBrute,aCentre,bCentre]=reconstructionCercleInconnu(constructionMatriceAccumulatriceCercleInconnu(traitementImageCannyGradient(imBrute, stockEquation), pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter),imBrute, pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter)
    distance=21
    A=MatriceDistances(distance)
    print("coordonnées par rapport au centre de l image (centre optique) : ", A[0][round(bCentre/20)][round(aCentre/20)], A[1][round(bCentre/20)][round(aCentre/20)])
#total(img.open("blablabla.jpg"),5,50,1,4,128,2)

def totalCam(nom,pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter, nblignes): #combine la prise de photo via caméra, l'utilisation des capteurs, et la détection de lignes et de cercle
    [imBrute,distance,angleHorizontal]=captureEcranData(nom)
    stockEquation=Horizon(imBrute,resolutionAngulaire,resolutionDistance,nblignes)
    [imBrute,aCentre,bCentre]=reconstructionCercleInconnu(constructionMatriceAccumulatriceCercleInconnu(traitementImageCannyGradient(imBrute, stockEquation), pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter),imBrute, pasDeRayon,rayonMini,resolutionAngulaire,resolutionDistance,resolutionAngulaireCercleInter)
    A=MatriceDistances(distance)
    print("coordonnées par rapport au centre de l image (centre optique) : ", A[0][round(bCentre/20)][round(aCentre/20)], A[1][round(bCentre/20)][round(aCentre/20)])

# def a(): #algorithme déjà proposé par uen bibliothère python : très rapide, mais très sensible au bruit, imprécis, non robuste, inexact, approximatif
    image = cv2.imread("cercle.jpg")
    image=cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)
    #th,image=cv2.threshold(image,90,255,cv2.THRESH_BINARY)
    th,image = cv2.threshold(image, 128,192,cv2.THRESH_OTSU)
    image = cv2.medianBlur(image,5)
    cv2.namedWindow("detected circles", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("detected circles", 300, 700)
    cv2.imshow('detected circles',image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cimg = cv2.cvtColor(image,cv2.COLOR_GRAY2BGR)
    circles = cv2.HoughCircles(image,cv2.HOUGH_GRADIENT,1,20, param1=50,param2=30,minRadius=10,maxRadius=500)
    circles = np.uint16(np.around(circles))
    for i in circles[0]:
        # draw the outer circle
        cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
        # draw the center of the circle
        cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

    cv2.namedWindow("detected circles", cv2.WINDOW_NORMAL)
    cv2.resizeWindow("detected circles", 300, 700)
    cv2.imshow('detected circles',cimg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    ### Concerne les capteurs de distance et gyromètre

### gyromètre
mpu = MPU9250(
    address_ak=AK8963_ADDRESS,
    address_mpu_master=MPU9050_ADDRESS_68, # Master has 0x68 Address
    address_mpu_slave=MPU9050_ADDRESS_68, # Slave has 0x68 Address
    bus=1,
    gfs=GFS_1000,
    afs=AFS_8G,
    mfs=AK8963_BIT_16,
    mode=AK8963_MODE_C100HZ)

mpu.configure() # Apply the settings to the registers.

def captureAngle(mpu=mpu):
    accelerationX = mpu.readAccelerometerMaster()[0]
    accelerationY = mpu.readAccelerometerMaster()[1]
    accelerationZ = mpu.readAccelerometerMaster()[2]
    pitch = 180 * m.atan (accelerationX/m.sqrt(accelerationY*accelerationY + accelerationZ*accelerationZ))/m.pi;
    print("angle : ", pitch)

    ### Capteur de distance

#Create a VL53L0X object

def captureDistance():
    tof = VL53L0X.VL53L0X(i2c_bus=1,i2c_address=0x29)

    tof.open()
    # Start ranging
    tof.start_ranging(VL53L0X.Vl53l0xAccuracyMode.BETTER)

    distance = tof.get_distance()
    if distance > 0:
        print("%d mm, %d cm, %d" % (distance, (distance/10),1))

    tof.stop_ranging()
    tof.close()
    return distance/10 #renvoie la valeur en centimètres

###capture d'écran + données !

def captureEcranData(name):
    imBrute = capture(name,x=3280, y=1845)
    angleHorizontal=captureAngle()
    distance=captureDistance()
    print("angleHorizontal = ", angleHorizontal, "    distance = ", distance )
    return [imBrute,distance,angleHorizontal]


import math
import re

# 자카드 유사도 문제
# 자카드 유사도 = 교집합 / 합집합
# 입력된 문자열을 2개씩 끊어 집합을 만든다  (ex: "testWord" -> "te", "es", "st", "tW", "Wo", "or", "rd")
# 문자 쌍에 알파벳 외의 다른것이 있다면 해당 쌍은 버린다 (ex: "asd2fg" -> "as", "sd", "fg")
# 문자는 대소문자를 구분하지 않는다
# 출력값은 0 ~ 1 의 실수임으로, 보기 쉽게 65536를 곱하고 소수는 버린다
# 교집합과 합집합 모두 공백일 경우 J(a, b) = 1로 정의한다
def solution(str1, str2):
    j1 = list()
    j2 = list()

    reg = re.compile(r'[A-Z]')
    str1 = str1.upper()
    str2 = str2.upper()

    for e in range(1, len(str1)):
        sr = str1[e - 1] + str1[e]
        if sr != ''.join([e.group() for e in re.finditer(reg, sr)]):
            continue
        j1.append(sr)
    for e in range(1, len(str2)):
        sr = str2[e - 1] + str2[e]
        if sr != ''.join([e.group() for e in re.finditer(reg, sr)]):
            continue
        j2.append(sr)

    temp = j1.copy()
    set_sum = j1.copy()

    for e in j2:
        if e not in temp:
            set_sum.append(e)
        else:
            temp.remove(e)

    inter = list()
    for e in j2:
        if e in j1:
            j1.remove(e)
            inter.append(e)

    if len(set_sum) == 0:
        answer = 1
    else:
        answer = len(inter) / len(set_sum)
    return math.floor(answer * 65536)


import os
import sys

def between(filetext, index):
	stage = 0
	buffer = ""
	for i in range(0, len(filetext)):
		if filetext[index+i] == ">" and stage == 0:
			stage = 1
		elif filetext[index+i] == "<" and stage == 1:
			break
		elif stage == 1:
			buffer += filetext[index+i]
	return buffer

def output_issues(text, file):
	stage = 0
	listing = []
	listing.append(int(file[10:14]))
	listing.append(int(file[10:12]))
	listing.append(int(file[12:14]))
	for i in range(0, len(text)):
		if text[i:i+10] == "<fileDesc " and stage == 0:
			stage = 1
		elif text[i:i+7] == "<title " and stage == 1:
			stage = 2
			listing.append(between(text, i+7))
		elif text[i:i+7] == "<editor" and stage == 2:
			listing.append("Lomas, G. A.")
			stage = 3
		elif text[i:i+7] == "<extent" and stage == 3:
			stage = 4
			listing.append(int(between(text, i+7)))
		elif text[i:i+7] == "<extent" and stage == 2:
			listing.append("None")
			stage = 4
			listing.append(int(between(text, i+7)))
		elif text[i:i+11] == "<sourceDesc" and stage == 4:
			stage = 5
		elif text[i:i+10] == "<publisher" and stage == 5:
			stage = 6
			listing.append(between(text, i+10))
		elif text[i:i+9] == "<pubPlace" and stage == 6:
			stage = 7
			listing.append(between(text, i+9))
		elif text[i:i+5] == "<date" and stage == 7:
			stage = 8
			listing.append(between(text, i+9))
		elif text[i:i+7] == "value=\"" and stage == 8:
			listing.append(int(text[i+7:i+11]))
			listing.append(int(text[i + 11:i + 13]))
	return listing

def list_to_str_issues(listing):
	buffer = "INSERT INTO issues (id, volume, issue, title, editor, pages, publisher, pubplace, date, year, month) VALUES ("
	for i in range(0, len(listing)-1):
		if type(listing[i]) == int:
			buffer += str(listing[i])
		else:
			buffer += "\"" + listing[i] + "\""
		buffer += ", "
	buffer += str(listing[-1]) + ")" + "\n"
	return buffer

def header_read(text, file, output):
	buffer = ""
	for i in range(0, len(text)):
		if text[i:i+4] == "<div1":
			buffer = text[0:i]
	output_list = output_issues(buffer, file)
	output_str = list_to_str_issues(output_list)
	output.write(output_str)

def issues_reader(files_list, path):
	issues_name = "SQL_issues.txt"
	issues_file = open(issues_name, "a")
	issues_file.truncate(0)
	for file in files_list:
		lol = open(path + "/" + file)
		if file[0:3] == "spe":
			file_text = lol.read()
			header_read(file_text, file, issues_file)

def main():
	path = os.getcwd() + "/journals"
	files_list = os.listdir(path)
	issues_reader(files_list, path)
	print("made it")

main()


import math
import pandas as pd
import numpy as np

import argparse

import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D

import matplotlib.pyplot as plt
from torch import norm

def main(args):
    df = pd.read_csv(args.filename)
    df["No"] = range(0, len(df.index))

    # calc K constant
    df["K"] = (
        np.sqrt(df["velocity_x"] ** 2 + df["velocity_y"] ** 2)
        * df["integration_time"]
        / (df["range"] * np.sqrt(df["delta_px"] ** 2 + df["delta_py"] ** 2))
    )

    # calc velocity magnitude
    df["velocity"] = np.sqrt(df["velocity_x"] ** 2 + df["velocity_y"] ** 2)

    # calc delta magnitude
    df["delta"] = np.sqrt(df["delta_px"] ** 2 + df["delta_py"] ** 2)

    # remove NaN and inf
    df = df.replace([np.inf, -np.inf], np.nan).dropna()

    # remove zero velocity
    df = df[df["velocity"] != 0]

    # remove zero delta
    df = df[df["delta"] != 0]

    # add histogram of K constant
    plt.hist(
        df[df["surface_quality"] > 230]["K"], bins=100, alpha=0.5, color="red", log=True
    )

    k_hist, k_bin_edges = np.histogram(df[df["surface_quality"] > 230]["K"], bins=100)
    k_classvalues = (k_bin_edges[:-1] + k_bin_edges[1:]) / 2

    k_list = np.array(list(zip(k_classvalues, k_hist)))
    # sort list by frequency
    k_list = k_list[k_list[:, 1].argsort()[::-1]]

    # print top 5 K constant
    print(f"Top 5 K constant: {k_list[:5]}")

    # determine K constant, use top 5 K constant, weighted by frequency
    k_constant = np.average(k_list[:5, 0], weights=k_list[:5, 1])
    print(f"K constant: {k_constant}")

    """
    # print mode
    k_modes = df[df["surface_quality"] > 230]["K"].mode()
    print(f"K modes: {k_modes}")

    # remove 0 from mode
    k_modes = k_modes[k_modes != 0]

    # determine K constant, use top 3 modes
    k_constant = k_modes.head(1).mean()
    print(f"K constant: {k_constant}")
    """

    plt.show()

    # show K constant
    plt.scatter(
        df[df["surface_quality"] > 230]["No"], df[df["surface_quality"] > 230]["K"]
    )
    plt.axhline(y=k_constant, color="r", linestyle="-")
    plt.show()

    # separate data to 16 bins based on surface quality
    # surface quality is an integer from 0 to 255
    # 255 is the best quality, 0 is the worst
    # 16 bins are created
    df_bins = []
    for i in range(16):
        df_bins.append(
            df[
                (df["surface_quality"] >= (i * 16))
                & (df["surface_quality"] < ((i + 1) * 16))
            ]
        )

    centerized_df_bins = []

    # centerize delta_px and delta_py
    for df_bin in df_bins:
        centerized_df_bins.append(
            df_bin.assign(
                delta_px=lambda x: x["delta_px"]
                - x["velocity_x"] * x["integration_time"] / x["range"] / k_constant,
                delta_py=lambda x: x["delta_py"]
                - x["velocity_y"] * x["integration_time"] / x["range"] / k_constant,
                delta=lambda x: x["delta"]
                - x["velocity"] * x["integration_time"] / x["range"] / k_constant,
                actual_delta_px=lambda x: x["velocity_x"]
                * x["integration_time"]
                / x["range"]
                / k_constant,
                actual_delta_py=lambda x: x["velocity_y"]
                * x["integration_time"]
                / x["range"]
                / k_constant,
            )
        )

        # drop NaN and inf
        centerized_df_bins[-1] = (
            centerized_df_bins[-1].replace([np.inf, -np.inf], np.nan).dropna()
        )

    # calculate covariance for each bin
    covs = []
    for df_bin in centerized_df_bins:
        covs.append(np.cov(df_bin["delta_px"], df_bin["delta_py"]))

    # plot 16 bins
    # add scatter plot of delta_px and delta_py, and histogram of delta_px and delta_py
    hist_axs = []
    fig, axs = plt.subplots(4, 4, figsize=(20, 20))
    for i in range(16):
        axs[i // 4, i % 4].scatter(
            centerized_df_bins[i]["delta_px"], centerized_df_bins[i]["delta_py"]
        )
        axs[i // 4, i % 4].set_title(
            f"surface_quality: {i*16} - {(i+1)*16}, \n cov: {covs[i]}, \n actual dpx: {centerized_df_bins[i]['actual_delta_px'].mean()}"
        )
        axs[i // 4, i % 4].set_xlabel("delta_px")
        axs[i // 4, i % 4].set_ylabel("delta_py")
        axs[i // 4, i % 4].set_xlim([-1, 1])
        axs[i // 4, i % 4].set_ylim([-1, 1])
        axs[i // 4, i % 4].grid()

        hist_axs.append(axs[i // 4, i % 4].twinx())

        hist_axs[i].hist(
            centerized_df_bins[i]["delta_px"], bins=20, alpha=0.5, color="red"
        )
        hist_axs[i].hist(
            centerized_df_bins[i]["delta_py"], bins=20, alpha=0.5, color="blue"
        )

    # add space between plots
    fig.tight_layout(pad=5.0)

    # show plot
    plt.show()

    fig, axs = plt.subplots(4, 4, figsize=(20, 20), subplot_kw={"projection": "3d"})

    # plot 3d histogram of delta, velocity, separated by surface quality
    for i in range(4):
        for j in range(4):
            ax = axs[i, j]

            # Create histogram bins
            delta_bins = np.linspace(-1.0, 1.0, 20)
            velocity_bins = np.linspace(0, 0.2, 20)

            df_bin = centerized_df_bins[i * 4 + j]

            # Create histogram
            hist, xedges, yedges = np.histogram2d(
                df_bin["delta"],
                df_bin["velocity"],
                bins=(delta_bins, velocity_bins),
            )
            # Normalize each velocity bin
            for k in range(hist.shape[1]):
                total = np.sum(hist[:, k])
                if total > 0:
                    hist[:, k] /= total

            # Construct arrays for the anchor positions of the bars.
            xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1], indexing="ij")
            xpos = xpos.flatten()
            ypos = ypos.flatten()
            zpos = 0

            # Construct arrays with the dimensions for the bars.
            dx = dy = 0.1
            dz = hist.flatten()

            ax.bar3d(xpos, ypos, zpos, dx, dy, dz, shade=True)
            ax.set_xlabel("delta")
            ax.set_ylabel("velocity")
            ax.set_zlabel("Frequency")

            # set z range
            ax.set_zlim([0, 1.0])

    plt.show()

    # plot 2d histogram of delta, velocity, separated by surface quality
    fig, axs = plt.subplots(4, 4, figsize=(20, 20))
    for i in range(4):
        for j in range(4):
            ax = axs[i, j]
            ax.set_title(
                f"surface_quality: {(i*4+j)*16} - {(i*4+j+1)*16}, \n cov: {covs[i*4+j]}, \n actual dpx: {centerized_df_bins[i*4+j]['actual_delta_px'].mean()}"
            )

            df_bin = centerized_df_bins[i * 4 + j]

            ax.hist2d(
                df_bin["delta"],
                df_bin["velocity"],
                bins=[25, 10],
                cmap="Blues",
                range=[[-1, 1], [0, 0.2]],
            )
            ax.set_xlabel("delta")
            ax.set_ylabel("velocity")
    fig.tight_layout(pad=5.0)
    plt.show()

if __name__ == "__main__":
    # get filename from command line
    parser = argparse.ArgumentParser(
        description="Calculate covariance of optical flow measurements."
    )
    parser.add_argument(
        "filename", type=str, help="CSV file containing optical flow measurements."
    )
    args = parser.parse_args()

    main(args)


import openpyxl

#1.엑셀파일 만들기
wb = openpyxl.Workbook()

#2.워크시크 만들기(워크시트 이름)
ws = wb.create_sheet('오징어게임')

#3.데이터 추가하기
ws['A1'] = '참가번호'
ws['B1'] = '성명'

ws['A2'] = '001'
ws['B2'] = '오일남'

#4.엑셀 저장하기(엑셀파일 이름)
#wb.save('참가자_data.xlsx') #경로를 따로 지정하지 않으면 현재 프로젝트 폴더에 생성됨
#현재 폴더(프로젝트 폴더 내부의 구분된 폴더)에 저장하고 싶다면 해당폴더의 경로를 앞에 붙여줌
wb.save(r'D:\Crawling_Python\02_파이썬엑셀다루기\참가자_data.xlsx')
#앞에 r을 추가하여 ''안의 문자를 모두 문자열로 취급하라는 뜻

02_파이썬엑셀다루기/01_엑셀만들기.py


import metazimmer.dogshowbase.core as dogfirst
from colassigner import Col, ColAssigner
from colassigner.meta_base import get_all_cols

from sscutils import ScruTable, TableFeaturesBase, register

class SexMatchIndex(ColAssigner):
    def __init__(self, dog_df) -> None:
        self.dog_df = dog_df

    def sex_1(self, df) -> Col[str]:
        return self._get_sex(df, dogfirst.SpotFeatures.dog_1.dog_id)

    def sex_2(self, df) -> Col[str]:
        return self._get_sex(df, dogfirst.SpotFeatures.dog_2.dog_id)

    def _get_sex(self, spot_df, spot_ind):
        return (
            self.dog_df[dogfirst.DogFeatures.sex]
            .reindex(spot_df[spot_ind].values)
            .values
        )

class SexMatchFeatures(TableFeaturesBase):
    count = int

sex_match_table = ScruTable(SexMatchFeatures, SexMatchIndex)

@register(
    dependencies=[
        dogfirst.spot_table,
        dogfirst.dog_table,
    ],
    outputs=[sex_match_table],
)
def calculate_sex_match():

    spot_df = dogfirst.spot_table.get_full_df()
    dog_df = dogfirst.dog_table.get_full_df()

    sm_df = (
        spot_df.assign(**{SexMatchFeatures.count: 1})
        .pipe(SexMatchIndex(dog_df))
        .groupby(get_all_cols(SexMatchIndex))[[SexMatchFeatures.count]]
        .sum()
    )

    sex_match_table.replace_all(sm_df)


import torch.nn as nn
import torch.nn.functional as F
from .block import TransformerBlock

class VanillaTransformer(nn.Module):
    def __init__(
        self,
        num_layers,
        embed_dim,
        hidden_dim,
        num_heads,
        causal=False,
        attn_dropout=0.0,
        ffn_dropout=0.0,
        attn_type="vanilla",
        ffn_type="vanilla",
        norm_type="ln",
        pre_norm=False,
        act_fun="gelu",
    ):
        super().__init__()
        self.layers = nn.ModuleList([])
        for _ in range(num_layers):
            self.layers.append(
                TransformerBlock(
                    embed_dim=embed_dim,
                    hidden_dim=hidden_dim,
                    num_heads=num_heads,
                    causal=causal,
                    attn_dropout=attn_dropout,
                    ffn_dropout=ffn_dropout,
                    attn_type=attn_type,
                    ffn_type=ffn_type,
                    norm_type=norm_type,
                    pre_norm=pre_norm,
                    act_fun=act_fun,
                )
            )

    def forward(self, x, y=None):
        for layer in self.layers:
            x = layer(x)

        return x