import faiss
import numpy as np
from transformers import CLIPProcessor, CLIPModel
from PIL import Image
import torchvision.transforms as transforms
import torch
import matplotlib.pyplot as plt
from datasets import load_dataset
from IPython.display import display
from IPython.display import Image as IPyImage

# 加载数据集
dataset = load_dataset("rajuptvs/ecommerce_products_clip")
training_split = dataset["train"]

# 定义显示图像的函数

def display_images(images):
    fig, axes = plt.subplots(2, 5, figsize=(15, 6))
    axes = axes.ravel()

    for idx, img in enumerate(images):
        axes[idx].imshow(img)
        axes[idx].axis('off')

    plt.subplots_adjust(wspace=0.2, hspace=0.2)
    plt.show()

# 校验数据集， 获取数据集中的前10张图像并显示
images = [example["image"] for example in training_split.select(range(10))]
# display_images(images)

# 初始化 CLIP 模型
device = "cuda" if torch.cuda.is_available() else "cpu"
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device)
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")

# 获取图像的特征向量

def get_image_features(image):
    with torch.no_grad():
        inputs = processor(images=[image], return_tensors="pt", padding=True)
        inputs.to(device)
        features = model.get_image_features(**inputs)
    return features.cpu().numpy()

# 为数据集中的每个示例添加图像特征向量

def add_image_features(example):
    example["features"] = get_image_features(example["image"])
    return example

# 对数据集应用函数以添加图像特征向量
training_split = training_split.map(add_image_features)

# 构建特征矩阵并创建 Faiss 索引
features = [example["features"] for example in training_split]
features_matrix = np.vstack(features)
dimension = features_matrix.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(features_matrix.astype('float32'))

# 获取文本的特征向量

def get_text_features(text):
    with torch.no_grad():
        inputs = processor(text=[text], return_tensors="pt", padding=True)
        inputs.to(device)
        features = model.get_text_features(**inputs)
    return features.cpu().numpy()

# 显示搜索结果
def display_search_results(results):
    fig, axes = plt.subplots(1, len(results), figsize=(15, 5))
    axes = axes.ravel()

    for idx, result in enumerate(results):
        axes[idx].imshow(result["image"])
        axes[idx].set_title(f"Distance: {result['distance']:.2f}")
        axes[idx].axis('off')

    plt.subplots_adjust(wspace=0.2, hspace=0.2)
    plt.show()

# 图片搜索
def search_image(image_path, top_k=5):
    # Load the image from the file
    image = Image.open(image_path).convert("RGB")

    # Get the image feature vector for the input image
    image_features = get_image_features(image)

    # Perform a search using the FAISS index
    distances, indices = index.search(image_features.astype("float32"), top_k)

    # Get the corresponding images and distances
    results = [
        {"image": training_split[i.item()]["image"],
         "distance": distances[0][j]}
        for j, i in enumerate(indices[0])
    ]

    return results

# 文字搜索

def search_text(query_text, top_k=5):
    # 获取输入查询文本的特征向量
    text_features = get_text_features(query_text)

    # 使用 Faiss 索引进行搜索
    distances, indices = index.search(text_features.astype("float32"), top_k)

    # 获取相应的图像和距离
    results = [
        {"image": training_split[i.item()]["image"],
         "distance": distances[0][j]}
        for j, i in enumerate(indices[0])
    ]

    return results

image_path = "./data/shirt.png"
query_text = "A red dress"

# 搜索示例
# results = search_image(image_path)
# display(IPyImage(filename=image_path, width=300, height=200))
# display_search_results(results)

results = search_text(query_text)
display_search_results(results)


### standard
import streamlit as st
from core.Page import Page
### custom
import core.stInfrastructure as infra
### Standard
import os
import base64
import numpy as np
import pandas as pd
import altair as alt

#####################
### main part
#####################

class Page1(Page):
    def __init__(self):
        super().__init__("Readings", "Zeroth Page", ['In mathematics, an automorphic number (sometimes referred to as a circular number) is a natural number in a given number base b whose square "ends" in the same digits as the number itself.','(see)["https://en.wikipedia.org/wiki/Automorphic_number"]'])

    def main(self):
        super().main()

        ### getting attribute
        pageDict=st.session_state[self.name]

        power=st.multiselect("Pick a power:",[x for x in range(1,10,1)])
        upto=st.radio("Pick range to check (up to):",[1000,10000,100000,1000000])
        plsmns=st.selectbox("Neighbours (+/-):",[x for x in range(0,10,1)])
        tallyList=[]
        if st.button("Get results!"):
            st.write("power ==",power)
            st.write("up to ==",upto)
            #tallyDict[power]={}
            for p in power:
                for y in range(plsmns*-1,plsmns+1,1):
                    #st.write("this is neighbour",y)
                    for x in range(0,upto,1):
                        if str(np.power(x,p))[-1*len(str(x))::]==str(x+y):
                            #st.write(x," : ",np.power(x,power),"...",y)
                            tallyList.append({'power':int(p),'neighbour':int(y),'n':int(x)})
                            #st.write(tallyList[-1])
        if len(tallyList)<1:
            st.stop()
        #st.write(tallyList)
        df_tally=pd.DataFrame(tallyList)
        df_tally_g=df_tally.groupby(["power","neighbour"]).count().reset_index()
        st.dataframe(df_tally_g)
        #df_tally_g=df_tally.groupby(["power","neighbour"]).count().reset_index()
        #st.dataframe(df_tally_g)
        myChart=alt.Chart(df_tally_g).mark_bar(size=20).encode(
                    x=alt.X('power:N'),
                    y=alt.Y('n'),
                    color='power:N',
                    column='neighbour:N',
                    tooltip=['power', 'neighbour', 'n']
        ).configure_legend(labelLimit= 0, symbolLimit=0)#.properties(width=800)
        st.altair_chart(myChart)


import cv2
import numpy as np
from numpy.random import uniform
from sys import exit
from os import listdir, mkdir
from os.path import join, exists, dirname, abspath

target = input('Select target ("r" for rotating, "t" for translating): ').lower()
if target != "r" and target != "t":
    exit("Bad input")
interval = input('Select one of the following ranges: (1: 150-249, 2: 250-349, 3: 350-449): ')
if interval != "1" and interval != "2" and interval != "3":
    exit("Bad input")
src_path = abspath(dirname(__file__))
directory = join(src_path, '..', '..', 'data', 'raw', target)
try:
    mkdir(directory)
except:
    pass

minimum = int(interval) * 100 + 50
maximum = int(interval) * 100 + 149

directory = join(directory, str(minimum) + '-' + str(maximum))
try:
    mkdir(directory)
except:
    pass

image_name = "data"
drawing = False
pt1_x , pt1_y = None , None
img = None
thickness = None

def draw(event, x, y, r1, r2):
    global pt1_x, pt1_y, drawing, img
    color = (255, 255, 255)
    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        pt1_x,pt1_y=x,y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        cv2.line(img,(pt1_x,pt1_y),(x,y),color=color,thickness=thickness)
    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            cv2.line(img,(pt1_x,pt1_y),(x,y),color=color,thickness=thickness)
            pt1_x,pt1_y=x,y
    elif event==cv2.EVENT_RBUTTONUP:
        itr = str(len(listdir(directory)))
        cv2.imwrite(join(directory, itr + '.png'), img)
        print(itr)
        new_image()
    elif event==cv2.EVENT_MBUTTONUP:
        new_image()

# draw white arrows on black background. ALWAYS

def new_image():
    global img, color, thickness
    thickness = 5 + round(uniform(0, 20))
    width = round(uniform(minimum, maximum))
    height = 100
    img = np.zeros((height,width,3), np.uint8)

new_image()
cv2.namedWindow(image_name)
cv2.setMouseCallback(image_name, draw)

while(1):
    cv2.imshow(image_name, img)
    if cv2.waitKey(1)&0xFF==27:
        break
cv2.destroyAllWindows()


from tools.qt import QtCore, QtWidgets, tr

from equipment.liquid_solid import Centrifuge
from UI import UI_corriente
from equipment import parents
from lib.corriente import Corriente, Solid
from lib import unidades
from tools import costIndex
from UI.widgets import Entrada_con_unidades

class UI_equipment(parents.UI_equip):
    """Diálogo de definición de tamices de sólidos"""
    def __init__(self, entrada=None, parent=None):
        """entrada: Parametro opcional de clase corriente que indica la corriente de entrada en kla tubería"""
        super(UI_equipment, self).__init__(Centrifuge, entrada=False, parent=parent)
        self.entrada=entrada

        #Pestaña entrada
        self.Entrada= UI_corriente.Ui_corriente(entrada)
        self.Entrada.Changed.connect(self.cambiar_entrada)
        self.tabWidget.insertTab(0, self.Entrada,tr("equipment", "Entrada", None))

        #Pestaña calculo
        gridLayout_Calculo = QtWidgets.QGridLayout(self.tabCalculo)

        #Pestaña costos
        gridLayout_Costos = QtWidgets.QGridLayout(self.tabCostos)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Tipo:", None)), 1, 1, 1, 1)
        self.tipo=QtWidgets.QComboBox()
        self.tipo.addItem(tr("equipment", "Proceso inorgánico", None))
        self.tipo.addItem(tr("equipment", "Proceso orgánico", None))
        self.tipo.currentIndexChanged.connect(self.mostrarSubclasificacion)
        self.tipo.currentIndexChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.tipo, 1, 2, 1, 1)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Material:", None)), 2, 1, 1, 1)
        self.materialInorganico=QtWidgets.QComboBox()
        self.materialInorganico.addItem(tr("equipment", "Acero al carbón", None))
        self.materialInorganico.addItem(tr("equipment", "Acero inoxidable 316", None))
        self.materialInorganico.addItem(tr("equipment", "Monel", None))
        self.materialInorganico.addItem(tr("equipment", "Níquel", None))
        self.materialInorganico.currentIndexChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.materialInorganico, 2, 2, 1, 1)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(20,20,QtWidgets.QSizePolicy.Policy.Fixed,QtWidgets.QSizePolicy.Policy.Fixed),3,0,1,2)
        self.materialOrganico=QtWidgets.QComboBox()
        self.materialOrganico.addItem(tr("equipment", "Acero al carbón", None))
        self.materialOrganico.addItem(tr("equipment", "Acero inoxidable 316", None))
        self.materialOrganico.addItem(tr("equipment", "Monel", None))
        self.materialOrganico.addItem(tr("equipment", "Níquel", None))
        self.materialOrganico.addItem(tr("equipment", "Hastelloy", None))
        self.materialOrganico.currentIndexChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.materialOrganico, 2, 2, 1, 1)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(10,10,QtWidgets.QSizePolicy.Policy.Fixed,QtWidgets.QSizePolicy.Policy.Fixed),3,0,1,6)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Caudal calculado:", None)), 4, 1, 1, 1)
        self.caudalcalculado=Entrada_con_unidades(unidades.MassFlow, readOnly=True, retornar=False)
        gridLayout_Costos.addWidget(self.caudalcalculado,4,2,1,1)
        gridLayout_Costos.addWidget(QtWidgets.QLabel(tr("equipment", "Caudal de diseño:", None)), 5, 1, 1, 1)
        self.caudaldiseno=Entrada_con_unidades(unidades.MassFlow)
        gridLayout_Costos.addWidget(self.caudaldiseno,5,2,1,1)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(10,10,QtWidgets.QSizePolicy.Policy.Fixed,QtWidgets.QSizePolicy.Policy.Fixed),6,0,1,6)

        self.Costos=costIndex.CostData(1.3, 2)
        self.Costos.valueChanged.connect(self.calcularCostos)
        gridLayout_Costos.addWidget(self.Costos,7,1,2,2)

        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(20,20,QtWidgets.QSizePolicy.Policy.Expanding,QtWidgets.QSizePolicy.Policy.Expanding),9,0,1,6)
        gridLayout_Costos.addItem(QtWidgets.QSpacerItem(20,20,QtWidgets.QSizePolicy.Policy.Expanding,QtWidgets.QSizePolicy.Policy.Expanding),11,0,1,6)
        self.groupBox_Costos = QtWidgets.QGroupBox(tr("equipment", "Costos calculados", None))
        gridLayout_Costos.addWidget(self.groupBox_Costos,10,0,1,6)
        gridLayout_5 = QtWidgets.QGridLayout(self.groupBox_Costos)
        gridLayout_5.addWidget(QtWidgets.QLabel(tr("equipment", "Coste Adquisición:", None)),0,1,1,1)
        self.C_adq=Entrada_con_unidades(unidades.Currency, retornar=False, readOnly=True)
        gridLayout_5.addWidget(self.C_adq,0,2,1,1)
        gridLayout_5.addWidget(QtWidgets.QLabel(tr("equipment", "Coste Instalación:", None)),1,1,1,1)
        self.C_inst=Entrada_con_unidades(unidades.Currency, retornar=False, readOnly=True)
        gridLayout_5.addWidget(self.C_inst,1,2,1,1)

        self.tabWidget.setCurrentIndex(0)
        self.mostrarSubclasificacion(0)

    def mostrarSubclasificacion(self, ind):
        self.materialInorganico.setVisible(not ind)
        self.materialOrganico.setVisible(ind)

    def cambiar_entrada(self, corriente):
        selfentrada=corriente
        self.calculo()

    def calculo(self):
        if self.todos_datos():

            self.rellenoSalida()

    def rellenoSalida(self):
        pass

    def todos_datos(self):
        pass

    def calcularCostos(self):
        if self.todos_datos():
            if self.tipo.currentIndex()==0:
                self.FireHeater.Coste(self.factorInstalacion.value(), 0, self.tipobox.currentIndex(), self.material.currentIndex())
            else:
                self.FireHeater.Coste(self.factorInstalacion.value(), 1, self.tipocilindrico.currentIndex(), self.material.currentIndex())
            self.C_adq.setValue(self.FireHeater.C_adq.config())
            self.C_inst.setValue(self.FireHeater.C_inst.config())

if __name__ == "__main__":
    import sys
    from lib.corriente import Corriente, Mezcla
    app = QtWidgets.QApplication(sys.argv)
    agua=Corriente(300, 1, 3600, Mezcla([62], [1]))
    dialogo = UI_equipment(agua)
    dialogo.show()
    sys.exit(app.exec())


# models.py
from django.db import models

class TimeSample(models.Model):
    ''' マイクロ秒を記録するために整数型フィールドのdatetime_microを設けます '''

datetime = models.DateTimeField()
datetime_micro = models.IntegerField(default=0)


# Import all the required modules/packages
from flask import request, url_for, redirect
import requests
from urllib.parse import parse_qsl
from config import getEnvConfig
from models import User, db
from flask_jwt_extended import create_access_token

#Load the env config
config = getEnvConfig()

'''
Index page of application
to route you to login page
'''
def index():
    return redirect(url_for('routeApp.login'))

'''
Login page of application
route you to gihub login
'''
def login():
    return redirect(config.GITHUB_AUTH_URI)

'''
Call back url from github provider
'''
def callback():
    try:
        #updating code from github to the github access token header
        config.GITHUB_ACCESS_TOKEN_HEADER.update({"code" : request.args.get("code")})
        #requesting access token from github using the code received
        response = requests.get('https://github.com/login/oauth/access_token',\
                                config.GITHUB_ACCESS_TOKEN_HEADER)

        #if success, use the access token to get the user details from github
        if response.status_code == 200:
            queryDict =  dict(parse_qsl(response.text))
            userResponse = requests.get(url = 'https://api.github.com/user',\
                                    headers = {"Authorization": "token {}".format(queryDict.get('access_token'))})

            #if user response is success, use the details to create user in our application
            if userResponse.status_code == 200:
                userData = userResponse.json()
                userObj = User.query.filter_by(github_id = userData.get('id')).first()
                if not userObj:
                    userObj = User(username = userData.get('login'), github_id = userData.get('id'),\
                                    is_active = True
                    )
                    db.session.add(userObj)
                    db.session.commit()
                '''generating jwt access token for the application and redirect to the client application
                with the access token'''
                access_token = create_access_token(identity = userObj.id)
                return redirect(config.LOGIN_SUCCESS_REDIRECT_URI+access_token)
            else:
                return {"message": "Error in fetching user form github!"}
        else:
            return {"message": "Error in github login!"}
    except Exception as e:
        return {"message":str(e)}


'''
题目描述:
给你一个二叉树，请你返回其按 层序遍历 得到的节点值。 （即逐层地，从左到右访问所有节点）。
'''

from typing import List
from Tree.TreeNode import TreeNode

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []

        ans = []
        queue = [root]

        while queue:
            cur_level_len = len(queue)
            cur_val = []
            for _ in range(cur_level_len):
                root = queue.pop(0)
                cur_val.append(root.val)

                if root.left:
                    queue.append(root.left)
                if root.right:
                    queue.append(root.right)
            ans.append(cur_val)

        return ans

102_二叉树的层序遍历.py


from PIL import Image
import matplotlib.pyplot as plt
import numpy as np

import torch
import torch.optim as optim
from torchvision import transforms, models

# get 'features' portion of VGG19
vgg = models.vgg19(pretrained=True).features

# freeze all VGG parameters since we're only optimizing the target image
for param in vgg.parameters():
    param.requires_grad_(False)

# move the model to GPU, if available
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
vgg.to(device)

def load_image(img_path, max_size=400, shape=None):
    '''
    Load in and transform an image, making sure image is <= 400 pixels in the
    x-y dims
    '''
    image = Image.open(img_path).convert('RGB')
    if max(image.size) > max_size:
        size = max_size
    else:
        size = max(image.size)

    if shape is not None:
        size = shape

    in_transform = transforms.Compose([transforms.Resize(size),
                                       transforms.ToTensor(),
                                       transforms.Normalize((0.485, 0.456, 0.406),
                                                            (0.229, 0.224, 0.225))])
    image = in_transform(image)[:3, :, :].unsqueeze(0)
    return image

# load in content and image design
content_image = load_image('images/content.jpg').to(device)
style_image = load_image('images/style.jpeg', shape=content_image.shape[-2:]).to(device)

def im_convert(tensor):
    '''
    Helper function for un-normalizing an image
    and converting it from Tensor to numpy for display that image
    '''
    image = tensor.to('cpu').clone().detach()
    image = image.numpy().squeeze()
    image = image.transpose(1, 2, 0)
    image = image * np.array((0.229, 0.224, 0.225))\
           + np.array((0.485, 0.456, 0.406))
    image = image.clip(0, 1)
    return image

#display the images
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))
ax1.imshow(im_convert(content_image))
ax2.imshow(im_convert(style_image))
print('Draw successfully')
# plt.show()

def get_features(image, model, layers=None):
    '''Run an image through a model and get the features for a set of layer.
    Default layers are for VGG net matching Gatys
    '''
    if layers is None:
        layers = {
            '0': 'conv1_1',
            '5': 'conv2_1',
            '10': 'conv3_1',
            '19': 'conv4_1',
            '21': 'conv4_2',
            '28': 'conv5_1'
        }
    features = {}
    tmp_image = image
    for name, layer in model._modules.items():
        tmp_image = layer(tmp_image)
        if name in layers:
            features[layers[name]] = tmp_image

    return features

def gram_matrix(tensor):
    '''
    Calculate gram matrix for a given tensor
    '''
    _, d, h, w = tensor.size()
    tensor = tensor.view(d, h*w)
    gram = torch.mm(tensor, tensor.t())

    return gram

content_features = get_features(content_image, vgg)
style_features = get_features(style_image, vgg)
style_grams = {layer: gram_matrix(style_features[layer])
              for layer in style_features}

# create a target by copying content image
target = content_image.clone().requires_grad_(True).to(device)

show_every = 100
optimizer = optim.Adam([target], lr=0.003)
steps = 2000

style_weights = {
    'conv1_1': 0.1,
    'conv2_1': 0.2,
    'conv3_1': 0.4,
    'conv4_1': 0.6,
    'conv4_2': 0.6,
    'conv5_1': 0.7
}

content_weight = 1
style_weight = 0.6

for i in range(1, steps + 1):
    print('Running Epoch', i)
    target_features = get_features(target, vgg)

    # content loss
    content_loss = torch.mean((target_features['conv4_2']
                               - content_features['conv4_2']) ** 2)

    # style loss
    style_loss = 0
    for layer in style_weights:
        target_feature = target_features[layer]
        target_gram = gram_matrix(target_feature)
        _, d, h, w = target_feature.shape
        style_gram = style_grams[layer]
        layer_style_loss = style_weights[layer] \
                           * torch.mean((target_gram - style_gram) ** 2)
        style_loss += layer_style_loss / (d * h * w)

    # total loss
    total_loss = content_weight * content_loss + style_weight * style_loss

    optimizer.zero_grad()
    total_loss.backward()
    optimizer.step()

    if i % show_every == 0:
        print('Total loss', total_loss.item())
        numpy_image = im_convert(target)
        plt.imshow(numpy_image)
        plt.savefig(f'image{i}.jpg')
        # plt.show()
        # im = Image.fromarray(numpy_image)
        # im.save(f'image{i}.jpg')


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

print('started...')

v = 10 # cm/s
delta_out = 1000

files = ['gouge_shear_2D_hertz_Lx5_50MPa_log.txt',
	'gouge_shear_2D_hooke_Lx5_50MPa_log.txt',
	'gouge_shear_3D_hertz_thinLy_Lx5_50MPa_log.txt']
dts = [8e-09,8e-09,2e-08]
labels = ['2D hertz','2D hooke','3D hertz (thin $\ell_y$)']
derivative_steps = 10

'''
files = ['gouge_shear_2D_hertz_Lx5_50MPa_log.txt',
	'gouge_shear_2D_hooke_Lx5_50MPa_log.txt']
dts = [8e-09,8e-09]
labels = ['2D hertz','2D hooke']
'''

times = []
velocities = []
for file, dt in zip(files,dts):
	sim_data = np.loadtxt(file)
	sim_length = len(sim_data)
	# x position array of the center of mass of the sheared (bottom) block
	sheared_block_x = np.array(sim_data[0:sim_length,8])
	# caluculate the instantaneous derivative as a function of time
	############
	time_window = derivative_steps*dt*delta_out
	velocity = []
	for i, j in zip(range(0, sheared_block_x.size-derivative_steps, derivative_steps),
		range(derivative_steps, sheared_block_x.size, derivative_steps)):
		instantaneous_velocity = (sheared_block_x[j]-sheared_block_x[i])/time_window
		velocity.append(instantaneous_velocity)
	print(min(np.abs(velocity)))
	# time array with centered derivative increments
	time = np.arange(
		0, sheared_block_x.size-derivative_steps, derivative_steps) + derivative_steps/2
	# convert time to mega seconds
	print('max velocity: '+str(np.max(velocity)))
	times.append(time/1e6)
	velocities.append(np.array(velocity)*100)

plt.rc('font', family='serif', serif = "cmr10", size=20)
plt.rcParams['mathtext.fontset']='cm'
plt.figure(figsize=(10,6))
matplotlib.rcParams['axes.unicode_minus'] = False

for x, y, label in zip(times, velocities, labels):
	avg_string = '$<V_{plate}>$='+str(round(np.mean(y),4))+' cm/s'
	std_string = '$\sigma$='+str(round(np.std(y),4))+' cm/s'
	plt.errorbar(x=x, y=y, linewidth=1, fmt='', label=label+': '+avg_string+', '+std_string)
#plt.errorbar(x=(sim_data[lines_until_step-1,0]-sim_data[0,0]
#	)*v*dt, y=0.29, yerr=0.05,linewidth=3)

plt.legend(loc='lower right', fontsize=20)
plt.xlabel('time (s)\n')
plt.ylabel('\nshearing plate velocity (cm/s)')
plt.title('$V_{slide}=10$ cm/s, varying contact law\n')
plt.tight_layout(pad=0)
plt.grid(linestyle='--')
plt.ylim(bottom=0)
#plt.xscale('log')
plt.show()


#### 일반 게시글의 댓글 컨트롤러

from datetime import datetime

from flask import Blueprint, url_for, request, render_template, g, flash
from werkzeug.utils import redirect

from flo import db
from flo.form import CommentForm
from flo.models.board_model import Board, Comment
from flo.views.auth_view import login_required

bp = Blueprint('comment', __name__, url_prefix='/comment')

# 댓글 작성하기
@bp.route('/write/<int:board_idx>', methods=('POST',))
@login_required                                         # 로그인 검증
def write(board_idx):
    try:
        form = CommentForm()
        board = Board.query.get(board_idx)
        content = request.form['content']

        # 댓글 낸용, 작성 시간, 작성자 정보
        if form.validate_on_submit():
            content = request.form['content']
            comment = Comment(content=content, write_t=datetime.now(), user=g.user)

            board.comment_set.append(comment)
            db.session.commit()

            return redirect(url_for('board.detail', board_idx=board_idx))

        if board is None:
            raise ValueError("게시글을 찾을 수 없습니다")

        return render_template('board/board_detail.html', board=board, form=form)

    except ValueError as e:
        return board_error(e)

# 댓굴 삭제
@bp.route('/delete/<int:comment_idx>')
@login_required
def delete(comment_idx):
    try:
        comment = Comment.query.get(comment_idx)
        board_idx = comment.board.idx

        # 댓글은 작성자만 삭제 가능
        if g.user != comment.user:
            flash('삭제권한이 없습니다')
        else:
            db.session.delete(comment)
            db.session.commit()

        return redirect(url_for('board.detail', board_idx=board_idx))

    except ValueError as e:
        return board_error(e)

@bp.errorhandler(ValueError)
def board_error(e):
    return render_template('errors/404.html'), 404


from typing import List

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

def zigzag(root: Node) -> List[int]:

    if not root:
        return []
    ans = []

    que = []
    left_to_right = True
    que.append(root)

    while que:
        a = []
        r = len(que)
        for i in range(r):
            node = que.pop(0)

            a.append(node.val)

            if node.left:
                que.append(node.left)
            if node.right:
                que.append(node.right)
        if not left_to_right:
            a.reverse()
        ans.append(a)
        a = None
        left_to_right = not left_to_right

    return ans

root = Node(20)
root.left = Node(8)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left = Node(10)
root.left.right.right = Node(14)
root.right = Node(22)
root.right.right = Node(25)

'''
   20
  /  \
 8    22
/ \     \
4  12   25
   /\
 10  14

'''

an = zigzag(root)
print(f'zigzag traversal is  {an}')


import cv2
from simple_facerec import SimpleFacerec
import seial as serial

# Encode faces from a folder
sfr = SimpleFacerec()
sfr.load_encoding_images("images/")

# Load Camera
cap = cv2.VideoCapture(0)

face = []
last_face = []
while True:
    ret, frame = cap.read()

    # Detect Faces
    face_locations, face_names = sfr.detect_known_faces(frame)
    if face_names is None : #or len(face_names) == 0
        pass
    else:

        if len(face_names) != 0 and 'Unknown' not in face_names:
            print('0' + str(face_names))
            serial.open()
        elif 'Unknown' in face_names and last_face != face_names:
            print('1' + str(face_names))
            serial.close()
        elif len(face_names) == 0 and last_face != face_names:
            print('2' + str(face_names))
            serial.close()
        last_face = face_names
        print(face_names)
        # if face_names in face:
        #     pass
        # else:
        #     serial.open()
        #     face.append(face_names)

    #print(face_names)
    for face_loc, name in zip(face_locations, face_names):
        y1, x2, y2, x1 = face_loc[0], face_loc[1], face_loc[2], face_loc[3]

        cv2.putText(frame, name,(x1, y1 - 10), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 200), 2)
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 200), 4)

    cv2.imshow("Frame", frame)

    key = cv2.waitKey(1)
    if key == 'q':
        break

cap.release()
cv2.destroyAllWindows()


"""
Unofficial implementation of Copy-Paste for semantic segmentation
"""

#conda activate mmdet
from PIL import Image
#import imgviz
#pip install imgviz
import cv2
#conda install opencv
import argparse
import os
import numpy as np
#import tqdm
#conda install tqdm

import tensorflow.compat.v1 as tf
from third_party.deeplab.core import feature_extractor
from core import preprocess_utils

def random_flip_horizontal(mask, img, p=0.5):
    if np.random.random() < p:
        img = img[:, ::-1, :]
        mask = mask[:, ::-1]
    return mask, img

def img_add(img_src, img_main, mask_src):
    if len(img_main.shape) == 3:
        h, w, c = img_main.shape
    elif len(img_main.shape) == 2:
        h, w = img_main.shape
    mask = np.asarray(mask_src[:,:,0], dtype=np.uint8)
    sub_img01 = cv2.add(img_src, np.zeros(np.shape(img_src), dtype=np.uint8), mask=mask)
    mask_02 = cv2.resize(mask, (w, h), interpolation=cv2.INTER_NEAREST)
    #size of output in cv2.resize() is defined as (w,h)
    mask_02 = np.asarray(mask_02, dtype=np.uint8)
    sub_img02 = cv2.add(img_main, np.zeros(np.shape(img_main), dtype=np.uint8),
                        mask=mask_02)

    if len(sub_img01.shape) == 2:
        sub_img01 = np.expand_dims(sub_img01, axis=2)
    if len(sub_img02.shape) == 2:
        sub_img02 = np.expand_dims(sub_img02, axis=2)

    sub_img01 = cv2.resize(sub_img01, (img_main.shape[1], img_main.shape[0]),
               interpolation=cv2.INTER_NEAREST)
    if len(sub_img01.shape) == 2:
        sub_img01 = np.expand_dims(sub_img01, axis=2)

    img_main = img_main - sub_img02 + sub_img01
    #img_main = img_main - sub_img02 + cv2.resize(sub_img01, (img_main.shape[1], img_main.shape[0]),
    #                                             interpolation=cv2.INTER_NEAREST)
    return img_main

def rescale_src(mask_src, img_src, h, w):
    #rescale and paste randomly
    if len(mask_src.shape) == 3:
        h_src, w_src, c = mask_src.shape
    elif len(mask_src.shape) == 2:
        h_src, w_src = mask_src.shape
    max_reshape_ratio = min(h / h_src, w / w_src)
    rescale_ratio = np.random.uniform(0.2, max_reshape_ratio)

    # reshape src img and mask
    rescale_h, rescale_w = int(h_src * rescale_ratio), int(w_src * rescale_ratio)
    mask_src = cv2.resize(mask_src, (rescale_w, rescale_h),
                          interpolation=cv2.INTER_NEAREST)
    mask_src = np.expand_dims(mask_src, axis=2)
    # mask_src = mask_src.resize((rescale_w, rescale_h), Image.NEAREST)
    img_src = cv2.resize(img_src, (rescale_w, rescale_h),
                         interpolation=cv2.INTER_LINEAR)

    # set paste coord
    py = int(np.random.random() * (h - rescale_h))
    px = int(np.random.random() * (w - rescale_w))

    # paste src img and mask to a zeros background
    img_pad = np.zeros((h, w, 3), dtype=np.uint8)
    mask_pad = np.zeros((h, w, 1), dtype=np.uint8)
    img_pad[py:int(py + h_src * rescale_ratio), px:int(px + w_src * rescale_ratio), :] = img_src
    mask_pad[py:int(py + h_src * rescale_ratio), px:int(px + w_src * rescale_ratio)] = mask_src

    return mask_pad, img_pad

def Large_Scale_Jittering(mask, img, min_scale=0.1, max_scale=2.0):
    rescale_ratio = np.random.uniform(min_scale, max_scale)
    h, w, _ = img.shape

    #h = int(h)
    #w = int(w)
    # rescale
    h_new, w_new = int(h * rescale_ratio), int(w * rescale_ratio)

    #img, mask = preprocess_utils.randomly_scale_image_and_label(img, mask, rescale_ratio)
    img = cv2.resize(img, (w_new, h_new), interpolation=cv2.INTER_LINEAR)
    mask = cv2.resize(mask, (w_new, h_new), interpolation=cv2.INTER_NEAREST)
    mask = np.expand_dims(mask, axis=2)
    # mask = mask.resize((w_new, h_new), Image.NEAREST)
    # crop or padding
    x, y = int(np.random.uniform(0, abs(w_new - w))), int(np.random.uniform(0, abs(h_new - h)))

    ##mask: Label with shape [height, width, 1].
    if rescale_ratio <= 1.0:  # padding
        img_pad = np.ones((h, w, 3), dtype=np.uint8) * 168
        #RGB(168,168,168) is grey
        mask_pad = np.zeros((h, w, 1), dtype=np.uint8)
        #
        #img_pad = np.ones((h, w, 3), dtype=np.float32) * 168
        #mask_pad = np.zeros((h, w, 1), dtype=np.int32)
        #img_pad = tf.cast(img_pad, tf.float32)
        #mask_pad = tf.cast(mask_pad, tf.int32)

        #print(h_new, w_new)

        img_pad[y:y+h_new, x:x+w_new, :] = img
        mask_pad[y:y+h_new, x:x+w_new, :] = mask

        return mask_pad, img_pad
    else:  # crop
        img_crop = img[y:y+h, x:x+w, :]
        mask_crop = mask[y:y+h, x:x+w, :]
        #print(img_crop.dtype)
        #print(mask_crop.dtype)
        return mask_crop, img_crop

def copy_paste(mask_src, img_src, mask_main, img_main, lsj=True):

    mask_src, img_src = random_flip_horizontal(mask_src, img_src)
    mask_main, img_main = random_flip_horizontal(mask_main, img_main)

    # LSJ， Large_Scale_Jittering
    if lsj:
        mask_src, img_src = Large_Scale_Jittering(mask_src, img_src)
        mask_main, img_main = Large_Scale_Jittering(mask_main, img_main)
    else:
        # rescale mask_src/img_src to less than mask_main/img_main's size
        h, w, _ = img_main.shape
        mask_src, img_src = rescale_src(mask_src, img_src, h, w)

    img = img_add(img_src, img_main, mask_src)
    mask = img_add(mask_src, mask_main, mask_src)

    return mask, img


import telebot
import random
viclist = ['Молодец','Поздраляю','Умничка','Везунчик','Вы стеклодув','Любитель стекла','Каратель викторин']
funlist = ['Почему стекольные заводы всегда заняты? Потому что им всегда есть что гранить!',
           'Что скажет стеколомойщик, когда его спросят, как дела на заводе? Нам все в руки!',
           'Почему стекольные заводы никогда не скучают? Потому что у них всегда есть окна к похвале!',
           'Какой стекольный завод самый занятой? Тот, где люди в очереди стоят, чтобы разбить окно!',
           'Почему на стекольных заводах всегда тихо? Потому что стеклографии не звучат громко!',
           'Как называют завод, где производят бутылки? Стекловкусообразие!',
           'Что произойдет, если стекольщик на заводе долго не спит? Он начнет видеть окна возле каждого предмета!',
           'Как стекольные заводы поднимают настройку своих работников? Им показывают прозрачные слайды!',
           'Зачем стекольным заводам экстрасенсы? Чтобы заранее видеть, сколько окон им нужно производить!',
           'Когда на стекольных заводах наступает новый год, они празднуют разбитием бутылок и украшением окон!',
           "Почему стекольный завод всегда приносит прибыль? Потому что они всегда имеют чашку успеха!",
            "Какой самый популярный подарок на свадьбу стекольщикам? Очевидно, стеклянные сюрпризы!",
            "Зачем стеклоход ходит вокруг стекольного завода? Он ищет свою прозрачную любовь!",
            "Почему стеклодувы такие хорошие рассказчики? Потому что они всегда говорят правду в глаза!",
            "Как называют танцы на стекле? Стеклянные шары!",
            "Какой фильм любят смотреть на стекольных заводах? Стекло (Glass)!",
            "Почему стекло всегда спокойное? Потому что оно никогда не теряет своего хладнокровия!"
]

from telebot import types
qvestmode = False
bot = telebot.TeleBot('6478889497:AAGb_tVDuN3Y5dlMGsTwXqdXykAU1JnsW8I')
def SetOff(bool):
    bool = False
def SetOn(bool):
    bool = True
@bot.message_handler(commands=['start','s'])
def main(message):
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("👋 Поздороваться")
    btn2 = types.KeyboardButton("❓ Задать вопрос")
    markup.add(btn1, btn2)
    bot.send_message(message.chat.id,f'Привет, {message.from_user.first_name}, Я чат бот ажур стиль, ты можешь увидеть снизу экрана,кнопки, нажимайте на них чтобы задавать вопросы и многое другое)',reply_markup=markup)
@bot.message_handler(content_types=['text'])
def func(message):
    if message.text == "👋 Поздороваться":
        bot.send_message(message.chat.id, text="Привет! Я чат бот ажур стиль, ты можешь увидеть снизу экрана кнопки, нажимайте на них чтобы задавать вопросы и многое другое)")
    elif message.text == "❓ Задать вопрос":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        btn1 = types.KeyboardButton("Викторина 💎")
        btn2 = types.KeyboardButton("Что я могу 🤖")
        btn3 = types.KeyboardButton("Обо Всем 🌃")
        btn4 = types.KeyboardButton("Шутки про стеклозавод 🤡")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(btn1, btn2, btn3,btn4, back)
        bot.send_message(message.chat.id, text="Задай мне вопрос", reply_markup=markup)

    elif message.text == "Шутки про стеклозавод 🤡":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Еще Одну Шутку!")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, back)
        bot.send_message(message.chat.id, "Окей вот и шутка:\n" + ''+funlist[random.randrange(0,16)]+"", reply_markup=markup,parse_mode='html')

    elif message.text == "Еще Одну Шутку!":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Еще Одну Шутку!")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, back)
        bot.send_message(message.chat.id, "Окей вот и шутка:\n" + '' + funlist[random.randrange(0, 16)] + "",
                         reply_markup=markup, parse_mode='html')

    elif message.text == "Викторина 💎":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Бутылки стеклянные")
        button2 = types.KeyboardButton("Банки стеклянные")
        button3 = types.KeyboardButton("Любые")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id,"Привет , {0.first_name}! \nРад видеть тебя в викторине!\nИтак, не будем же ждать, к первому вопросу.".format(message.from_user, bot.get_me()))
        bot.send_message(message.chat.id, "Вопрос №1:\nЧто принимаем?",reply_markup=markup)
    elif message.text == "Любые" :
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Банки стеклянные":
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Бутылки стеклянные":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Хрусталь целая")
        button2 = types.KeyboardButton("Хрусталь битая")
        button3 = types.KeyboardButton("Любые из предложенных")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)] + ', следующий вопрос №2!')
        bot.send_message(message.chat.id, 'Что из этого мы также принимаем!',reply_markup=markup)
    elif message.text == "Любые из предложенных" :
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Хрусталь битая":
        bot.send_message(message.chat.id,'Неправильно, попробуй еще раз!')
    elif message.text == "Хрусталь целая":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Синие и прозрачные стеклянные")
        button2 = types.KeyboardButton("Пластиковые,стеклянные")
        button3 = types.KeyboardButton("Железные и стеклянные")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №3!')
        bot.send_message(message.chat.id, 'какие бутылки принимаем?', reply_markup=markup)
    elif message.text == "Железные и стеклянные":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "Пластиковые,стеклянные":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "Синие и прозрачные стеклянные":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Нисколько, даром")
        button2 = types.KeyboardButton("мало")
        button3 = types.KeyboardButton("много всего")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №4!')
        bot.send_message(message.chat.id, 'Сколько платят за сдачу стекла?', reply_markup=markup)
    elif message.text == "мало":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "много всего":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "Что я могу 🤖":
        bot.send_message(message.chat.id, text="Я - чат бот Ажур Стиль могу все что вы попросите!\nНапример если хотите я могу вам рассказать про стекло и когда были первые очки, если интересно тогда переходи в вопросы и выбери пункт обо всем! И узнай много вестей")

    elif message.text == "Нисколько, даром":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("мячи")
        button2 = types.KeyboardButton("деревянные игрушки")
        button3 = types.KeyboardButton("елочные игрушки")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №5!')
        bot.send_message(message.chat.id, 'Что изготавливают из бутылочного стекла?', reply_markup=markup)

    elif message.text == "мячи":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "деревянные игрушки":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "елочные игрушки":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("785")
        button2 = types.KeyboardButton("1088")
        button3 = types.KeyboardButton("2137")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)] + ', следующий вопрос №6!')
        bot.send_message(message.chat.id, 'При какой температуре плавится жидкое стекло?', reply_markup=markup)

    elif message.text == "785":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "2137":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "1088":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("красный")
        button2 = types.KeyboardButton("голубой")
        button3 = types.KeyboardButton("синий")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button2, button1, button3, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №7!')
        bot.send_message(message.chat.id, 'Какой цвет самого дорогого стекла?', reply_markup=markup)

    elif message.text == "голубой":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "синий":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "красный":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("1451г")
        button2 = types.KeyboardButton("1673г")
        button3 = types.KeyboardButton("1342г")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button3, button2, button1, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №8!')
        bot.send_message(message.chat.id, 'Когда изобрели очки для коррекции зрения?', reply_markup=markup)

    elif message.text == "1673г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "1342г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "1451г":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("1876г")
        button2 = types.KeyboardButton("2004г")
        button3 = types.KeyboardButton("1903г")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button3, button2, button1, back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+', следующий вопрос №9!')
        bot.send_message(message.chat.id, 'когда было изобретено Небьющееся стекло?', reply_markup=markup)
    elif message.text == "2004г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "1876г":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")

    elif message.text == "1903г":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("металлы")
        button2 = types.KeyboardButton("краски")
        button3 = types.KeyboardButton("красители")
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button3, button2, button1, back)
        bot.send_message(message.chat.id, 'Итак! Это последний вопрос викторины')
        bot.send_message(message.chat.id, 'что используют для окраски стекла?', reply_markup=markup)
    elif message.text == "краски":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "красители":
        bot.send_message(message.chat.id, text="Неправильно, попробуй еще раз!")
    elif message.text == "металлы":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        back = types.KeyboardButton("Вернуться в главное меню")
        markup.add(back)
        bot.send_message(message.chat.id, viclist[random.randrange(0,6)]+'! Вы прошли эту викторину о стекле !', reply_markup=markup)

    elif message.text == "Обо Всем 🌃":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        back = types.KeyboardButton("Вернуться в главное меню")
        btn1 = types.KeyboardButton("Что принимают стекольные фабрики?")
        btn2 = types.KeyboardButton("Что изготавливают стекольные фабрики?")
        btn3 = types.KeyboardButton("Когда изобрели?")
        markup.add(btn1,btn2,btn3,back)
        bot.send_message(message.chat.id, text="Здесь вы можете узнать все и ответы на викторину в том числе!",parse_mode='html',reply_markup=markup)

    elif message.text == "Когда изобрели?":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Обо Всем 🌃")
        button2 = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2)
        bot.send_message(message.chat.id, text="О первых очках коррекции зрения: В 1451 году в Германии Nikolaus Kuzanski наладил производство вогнутых линз"
                                               ", которые имели тонкий центр линзы и толстый край и использовались для коррекции близорукости. "
                                               "Первые оправы для очков Первые оправы для очков изготавливались из дерева, свинца или меди.\n\nНебьющееся стекло "
                                               "было изобретено случайно. В 1903 году французский химик Эдуард Бенедиктус нечаянно уронил колбу, заполненную"
                                               "нитроцеллюлозой. Стекло треснуло, но не разлетелось на мелкие кусочки.\n\nТак как ученые считают эти находки древнейшими, "
                                               "то на вопрос, когда появилось стекло, они отвечают – около 12 тысяч лет назад. Именно столько лет насчитывает существование "
                                               "голубых и зеленых украшений из числа египетских археологических находок.\nОтвечая на вопрос, откуда появилось стекло, ученые сделали вывод, что это "
                                               "произошло примерно 55 веков назад, на территории Древнего Египта и Месопотамии. Первыми предметами из стекла были небольшие шарики правильной формы", reply_markup=markup)
    elif message.text == "Что изготавливают стекольные фабрики?":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Обо Всем 🌃")
        button2 = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2)
        bot.send_message(message.chat.id, text="\nОснову стекольной промышленности в России представляют пять крупных заводов, специализирующихся "
                                               "на производстве листового стекла. На их долю приходится более 90% всего выпускаемого в стране объема. \n\n"
                                               "Листовое стекло производится из кварцевого песка, кальцинированной соды, доломита и различных примесей. \n\n"
                                               "Продукция заводов востребована в строительстве, машиностроении, производстве мебели, торгового и медицинского"
                                               "оборудования, бытовой техники. Статистика отрасли показывает ежегодный рост производства в пределах 15%. \n\nНовым "
                                               "перспективным направлением стекольной промышленности, в котором занято свыше 50 профильных предприятий, называют "
                                               "промышленную переработку, включающую в себя изготовление стеклопакетов, закаливание и армирование стекла, производство "
                                               "триплекса. \n\nСтекольные заводы реализуют готовую продукцию следующих типов: стекло листовое, закаленное, матовое, цветное, "
                                               "узорчатое, армированное, многослойное, огнеупорное, а также стеклопакеты и стеклянные блоки "
                                               "\n\nСтекольные фабрики изготавливают елочные игрушки, многие украшение, посуду, дверные стекла и очень большое количество "
                                               "товаров на заказ!", reply_markup=markup)
    elif message.text == "Что принимают стекольные фабрики?":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("Обо Всем 🌃")
        button2 = types.KeyboardButton("Вернуться в главное меню")
        markup.add(button1, button2)
        bot.send_message(message.chat.id,
                         text="\n\nПереработкой стекла занимаются стеклоперерабатывающие заводы. В отличие от переработки пластика, эта система налажена и успешно работает уже долгие годы. \n\nВ стране работают десятки предприятий, которые перерабатывают стекло и превращают его в новые изделия. Поэтому дело за каждым – сдавать стекло на переработку довольно просто. \n\nНайти ближайший пункт приёма стеклотары в своём городе можно здесь."
"\n\nВ контейнеры для вторсырья или пункты приёма стеклотары можно отнести бутылки от напитков, банки из-под консервов или детского питания, а также различные пузырьки. Тара может быть прозрачная, зелёная или коричневая."
"\n\nНа переработку можно сдать и листовое стекло, которое осталось при замене окон. Однако его принимают только в компании «Стеклобой»: листовое стекло надо оставить у контейнера."
"\n\nПрежде чем сдать стекло, его надо ополоснуть от остатков содержимого и снять с тары крышку. Этикетку отрывать не нужно.Так-же можно сдавать целую хрусталь в наши Стеклозаводы!"
"\n\nПри этом вместе со стеклом нельзя сдавать на переработку:"
"\n\nкерамическую и стеклянную посуду (бокалы, стаканы, кружки, тарелки);\nочки или линзы;\nавтомобильное стекло;\nкрышки от сковородок и кастрюль;\nлампочки;\nзеркала;"
"\nхрусталь.", reply_markup=markup)

    elif message.text == "Вернуться в главное меню":
        markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
        button1 = types.KeyboardButton("👋 Поздороваться")
        button2 = types.KeyboardButton("❓ Задать вопрос")
        markup.add(button1, button2)
        bot.send_message(message.chat.id, text="Вы вернулись в главное меню", reply_markup=markup)
    else:
        bot.send_message(message.chat.id, text="На такую комманду я не запрограммирован..")

bot.polling(none_stop=True)


""" Required file for using this repository as a PIP dependency.
This is not a development enviornment setup script, it should NOT be run manually.
Add to your requirements.txt a line like:
    git+https://github.com/taikedz/dedupe@main
"""

# For help adjusting this file, see
# https://setuptools.pypa.io/en/latest/userguide/quickstart.html

from glob import glob
import os
import setuptools
import sys
import re

# ===================
# Configuration of setup

# Track the version in a file in your lib
# Ensure it has a "get_version()" method returning the version string
import dedupe as MYLIB

REPO_URL="https://github.com/taikedz/dedupe"

# Short description
DESCRIPTION = "Deduplicator for file trees"

# Short-name for library (used in paths, etc)
LIB_NAME = "dedupe"

# Ownership details ...
OWNER = "TaiKedz"
AUTHOR_NAME = "Tai Kedzierski"
AUTHOR_EMAIL = "dch.tai/G-MAIL"

# Any executable script files
SCRIPT_FILES = ['bin/dedupe', 'bin/dd-merge', 'bin/dd-flatten']

# Files to include during installation
CONFIG_GLOBS = ["config/*.yaml"]

# Packages (top-level dirs with a __init__.py file inside them)
#   to exclude during installation
EXCLUDE_GLOBS = ["tests"]

# note - in python2 , platform is "linux2" :-(
# Add a "requirements.{os_string}.txt" to add support for it
# e.g. "requirements.linux.txt"
SUPPORTED_OS_LIST = ("win32", "linux")

MIN_PYTHON_VERSION = "3.6"

# Load this file's content as the long-description
DESCRIPTION_FILE = "ABOUT.md"
LONG_DESCRIPTION_TYPE = "text/markdown"

CLASSIFIERS = [
    "Programming Language :: Python :: 3",
    "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)",
    "Operating System :: POSIX :: Linux",
    "Operating System :: Microsoft :: Windows",
    ]

# / END OF CONFIG AREA
# ----------------------------------------------------

# ===========
# Helpers

with open(DESCRIPTION_FILE) as fh:
    LONG_DESCRIPTION = fh.read()

def uncomment_file(path:str):
    """ Read a file, ignore all blank or comment lines, return each line as an individual list item
    """
    with open(path) as fh:
        return [L.strip() for L in fh.readlines() if not re.match("^\\s*(#.*)?$", L.strip())]

def get_all_files(globs):
    all_files = []
    for pat in globs:
        all_files.extend(glob(pat))
    return all_files

# ============
# Load requirements

# Sometimes, the lib requires a specific platform to _work_
if sys.platform not in SUPPORTED_OS_LIST:
    print("WARNING - platform {} cannot install some dependencies.".format(sys.platform))
    print( "          You can still develop with {},".format(LIB_NAME))
    print( "          but your project will not run locally on this machine.")

# Anywhere this package installed, use content from requirements.txt always ...
reqtxt_list = []
if os.path.exists("requirements.txt"):
    reqtxt_list.extend(uncomment_file("requirements.txt"))

# Add special support for some OSes - e.g. deployment environments, dev environments ...
for os_string in SUPPORTED_OS_LIST:
    if sys.platform == os_string:
        req_file = "requirements.{}.txt".format(os_string)

        if os.path.isfile(req_file):
            print("--- Selecting {} dependencies ---".format(os_string))
            extras = uncomment_file(req_file)
            reqtxt_list.extend(extras)

# ==============
# Active setup routine

setuptools.setup(
    name=LIB_NAME,
    version=MYLIB.version.get_version(),

    author=AUTHOR_NAME,
    author_email=AUTHOR_EMAIL,

    description=DESCRIPTION,
    long_description=LONG_DESCRIPTION,
    long_description_content_type=LONG_DESCRIPTION_TYPE,

    url=REPO_URL,

    scripts=get_all_files(SCRIPT_FILES),

    project_urls={
        "Bug Tracker": f"{REPO_URL}/issues",
    },
    classifiers=CLASSIFIERS,
    package_dir={LIB_NAME: LIB_NAME},
    python_requires=">=".format(MIN_PYTHON_VERSION),
    install_requires=reqtxt_list,

    packages=setuptools.find_packages(exclude=get_all_files(EXCLUDE_GLOBS)),

    # Installs to f"{sys.prefix}/{dirname}" where 'dirname' is the first memebr of each tuple
    data_files=[('{}/config'.format(LIB_NAME), get_all_files(CONFIG_GLOBS))]
)


from keras.models import Sequential
from keras.layers import Dense
from keras.utils import plot_model
import numpy as np

# fix random seed for reproducibility
np.random.seed(8)

# 1. load pima indians dataset
dataset = np.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]

# 2. create model
## 8 - 12 - 8 - 1
model = Sequential()
model.add(Dense(units=12, input_dim=8, activation='relu'))
model.add(Dense(units=8, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))

plot_model(model, to_file='model.png', show_shapes=True)

# 3. Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# 4. Fit the model
model.fit(X, Y, epochs=150)

# 5. evaluate the model
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

# 5-2 calculate predictions
predictions = model.predict(X)
# round predictions
rounded = [int(round(x[0])) for x in predictions]
print(rounded)


"""
Project goal 1: Fred way
"""
from collections import namedtuple
from datetime import datetime
from functools import partial

def transform_headers(headers):
    """Processing headers from file"""
    column_names = [
        header.replace(' ', '_').lower()
        for header in headers
    ]
    return column_names

def read_data():
    """
    A generator that return each row in data file
    :return:
    """
    global file_name
    with open(file_name) as f:
        next(f)
        yield from f

def column_parsers():
    """
    Create the column parser which instructs how to
    validate each cell on a row
    """
    return (
        parse_int,
        parse_string,
        lambda x: parse_string(x, default=''),
        partial(parse_string, default=''),
        parse_date,
        parse_int,
        lambda x: parse_string(x, default=''),
        parse_string,
        lambda x: parse_string(x, default='')
    )

def parse_row(raw_row, *, default=None):
    """
    This function:
        - Validate each cell on a row based on the definition
        in column_parser
        - Turn each row into a Ticket instance if valid
        - Otherwise, return the default
    :param raw_row:
    :param default:
    :return:
    """

    fields = raw_row.strip('\n').split(',')
    # Use generator here for lazy evaluation
    processed_row = [func(field)
                     for func, field in zip(column_parser, fields)]

    # Evaluate if all cell is not None, also means valid
    if all(item is not None for item in processed_row):
        return Ticket(*processed_row)
    else:
        return default

def parse_data():
    """
    This generator:
        - Read the data row by row
        - Validate each cell on a row
        - Only if valid, yield it as a Ticket instance
    :return:
    """
    for row in read_data():
        parsed = parse_row(row)
        if parsed:
            yield parsed

# Utils functions
def parse_int(value, *, default=None):
    """
    Parse the value into integer type
    otherwise, replace it with None
    """
    try:
        return int(value)
    except ValueError:
        return default

def parse_date(value, *, default=None):
    """
    Parse the value into date type
    otherwise, replace it with None
    """
    date_format = '%m/%d/%Y'
    try:
        return datetime.strptime(value, date_format).date()
    except ValueError:
        return default

def parse_string(value, *, default=None):
    """
    Parse the value into string type
    otherwise, replace it with None
    """
    try:
        cleaned = value.strip()
        if not cleaned:
            return default
        else:
            return cleaned
    except ValueError:
        return default

file_name = 'nyc_parking_tickets_extract.csv'

with open(file_name) as f:
    sample_headers = next(f).strip('\n').split(',')
    raw_data = next(f)

Ticket = namedtuple(
    'Ticket',
    transform_headers(sample_headers)
)

column_parser = column_parsers()

parsed_rows = parse_data()
for _ in range(5):
    print(next(parsed_rows))


import numpy as np
import pygame as pg

import projectile
import settings as st
from weapon import Weapon

class Player(pg.sprite.Sprite):
    players = []

    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((st.TILES_WH // 1.5, st.TILES_WH // 1.5))
        self.color = np.array((5, 5, 5))
        self.image.fill(self.color)

        # treeImage = pg.image.load("images/therock.png")
        # treeImage = pg.transform.scale(treeImage, (st.TILES_WH // 1.5, st.TILES_WH // 1.5))
        # self.image.blit(treeImage, (0, 0))

        self.rect = self.image.get_rect()
        self.rect.center = st.WIDTH // 2, st.HEIGHT // 2

        # stats
        self.max_hp = 5
        self.hp = self.max_hp
        self.mana = 1
        self.strength = 1
        self.agility = 1
        self.vitality = 1
        self.attack_speed = st.TICK * 2

        self.running = 0, 0
        self.shoot_bool = False
        self.is_alive = True
        self.take_damage_countdown = 1
        self.make_damage_countdown = 1

        st.all_sprites.add(self)
        Player.players.append(self)

    def update(self):
        self.take_damage_countdown = max(self.take_damage_countdown - st.TICK * 5, 0)
        self.make_damage_countdown = max(self.make_damage_countdown - self.attack_speed, 0)

    def check_health(self):
        dh = max(self.hp / self.max_hp, 0.1)
        clr = np.array([(1-dh)*100, 0, 0])
        pg.draw.rect(self.image, clr+self.color, (0, 0, *self.rect.size), self.rect.width // 10)
        pos = self.rect.center
        self.rect = self.image.get_rect()
        self.rect.center = pos

    def take_damage(self, dmg):
        if self.take_damage_countdown:
            return

        self.hp = max(self.hp - dmg, 0)
        self.check_health()
        if self.hp == 0:
            self.is_alive = False

    def move(self, x, y):
        # preparations
        v = max(st.TILES_WH * 3 * st.TICK, 1)
        offset = st.TILES_WH // 10 // 1.5
        x, y = -x, -y

        # player's and board's pos
        left, top, right, bottom = *self.rect.topleft, *self.rect.bottomright
        b_left, b_top = st.positions[0]

        # positions and offset
        t_bt = (top - b_top) / st.TILES_WH
        b_bt = (bottom - b_top) / st.TILES_WH
        l_bl = (left - b_left) / st.TILES_WH
        r_bl = (right - b_left) / st.TILES_WH
        offset_tiles = offset / st.TILES_WH

        # hit wall? great, now go back, Monkey
        ox, oy = 0, 0
        if st.map_tiles[int(t_bt)][int(l_bl - offset_tiles)] == "02":
            ox += 1
        elif st.map_tiles[int(t_bt)][int(r_bl + offset_tiles)] == "02":
            ox -= 1
        elif st.map_tiles[int(b_bt)][int(l_bl - offset_tiles)] == "02":
            ox += 1
        elif st.map_tiles[int(b_bt)][int(r_bl + offset_tiles)] == "02":
            ox -= 1

        if st.map_tiles[int(t_bt - offset_tiles)][int(l_bl)] == "02":
            oy += 1
        elif st.map_tiles[int(b_bt + offset_tiles)][int(l_bl)] == "02":
            oy -= 1
        elif st.map_tiles[int(t_bt - offset_tiles)][int(r_bl)] == "02":
            oy += 1
        elif st.map_tiles[int(b_bt + offset_tiles)][int(r_bl)] == "02":
            oy -= 1

        # this is needed for not being pushed from wall
        # upd: now, it doesn't work with diagonal movement, because of square root of 2 divided by 2.
        # It's an irrational number. Also, maybe it's because of it being little bit smaller than my program can detect.
        rx, ry = (1 if x else 0), (1 if y else 0)
        # sum it all up
        st.positions += ((x - ox) * v * rx, (y - oy) * v * ry)

    def shoot(self):
        mouse_pos = pg.mouse.get_pos()
        speed = st.TILES_WH // 10
        x, y = (mouse_pos[0] - st.WIDTH // 2), (mouse_pos[1] - st.HEIGHT // 2)

        vx = x / abs(x ** 2 + y ** 2) ** 0.5 * speed
        vy = y / abs(x ** 2 + y ** 2) ** 0.5 * speed

        self.make_damage_countdown = 1
        projectile.Projectile("linear", (st.WIDTH // 2, st.HEIGHT // 2), (vx, vy),
                              st.TILES_WH * 5, self.strength)


import pandas as pd
import seaborn as sns
import skillsnetwork
import numpy as np
from networkx.drawing.tests.test_pylab import plt

df = pd.read_csv('data/Ames_Housing_Data.tsv', sep = '\t')

# This is recommended by the data set author to remove a few outliers
df = df.loc[df['Gr Liv Area'] <= 4000,:]
print("Number of rows in the data:", df.shape[0])
print("Number of columns in the data:", df.shape[1])
data = df.copy()

#One_hot encoding for dummy variables
one_hot_encode_cols = df.dtypes[df.dtypes == np.object]
one_hot_encode_cols = one_hot_encode_cols.index.tolist()

df = pd.get_dummies(df, columns = one_hot_encode_cols, drop_first=True)

#Log Transforming Skew Variables
mask = data.dtypes == np.float
float_cols = data.columns[mask]

skew_limit = 0.75
skew_vals = data[float_cols].skew()
skew_cols = (skew_vals
             .sort_values(ascending=False)
             .to_frame()
             .rename(columns={0:'Skew'})
             .query('abs(Skew) > {}'.format(skew_limit)))

#Let's draw a log graph
field = "BsmtFin SF 1"
fig, (ax_before, ax_after) = plt.subplots(1,2, figsize=(10,5))
df[field].hist(ax = ax_before)               # before the transformation
df[field].apply(np.log1p).hist(ax=ax_after) # after the tranformation

ax_before.set(title='before np.log1p', ylabel='frequency', xlabel='value')
ax_after.set(title='after np.log1p', ylabel='frequency', xlabel='value')
fig.suptitle('Field "{}"'.format(field));

IBM Machine Learning/1. Exploratory Data Analytics for ML/3W_Feature Engineering Demo/main.py


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

import cgi
import cgitb
import os
import sys

root = os.path.dirname(os.path.dirname(__file__))
sys.path.append(root)
from tools import utils

form   = cgi.FieldStorage()
rel_id = int(form.getvalue("id", -1))
name   = str(form.getvalue("name", ""))

show = utils.show
cgitb.enable()

PgConn    = utils.get_dbconn()
PgCursor  = PgConn.cursor()

if rel_id == -1 and name == "":
    utils.print_header("Show polygon")
    show("
%s
" % ("Show polygon"))
    show("<form method='GET' action=''>")
    show("%s" % "Id of relation")
    show("<input type='text' name='id' id='id'>")
    show("
")
    show("%s" % "Name of user polygon")
    show("<input type='text' name='name' id='name'>")
    show("<input type='submit'>")
    show("</form>")
    sys.exit(0)

utils.print_header("Show polygon")

if rel_id != -1:

    sql_list = """SELECT id, params, timestamp, ST_NPoints(geom) AS npoints,
                         ST_MaxDistance(geom, geom) AS length
                  FROM polygons WHERE id = %s
                  ORDER BY params"""
    PgCursor.execute(sql_list, (rel_id, ))

    osm_results = PgCursor.fetchall()

    if osm_results:
        show("
%s
" % ("List of available polygons for id = %d" % rel_id))

        show("
\n")
        show("
\n")
        show("    %s ▾	\n" % ("params"))
        show("    %s	\n" % ("timestamp"))
        show("    %s	\n" % ("NPoints"))
        show("    %s	\n" % ("Length"))
        show("    %s	\n" % ("WKT"))
        show("    %s	\n" % ("GeoJSON"))
        show("    %s	\n" % ("poly"))
        show("    %s	\n" % ("Image"))
        show("
\n")

        for res in osm_results:
            show("
\n")
            show("    " + str(res["params"]) + "	\n")
            show("    " + str(res["timestamp"]) + "	\n")
            show("    " + str(res["npoints"]) + "	\n")
            show("    " + str(res["length"]) + "	\n")
            show("    WKT	\n" % (rel_id, str(res["params"])))
            show("    GeoJSON	\n" % (rel_id, str(res["params"])))
            show("    poly	\n" % (rel_id, str(res["params"])))
            show("    image	\n" % (rel_id, str(res["params"])))
            show("
\n")

        show("
\n")

if name != "":

    sql_list = """SELECT name, timestamp, ST_NPoints(geom) AS npoints,
                         ST_MaxDistance(geom, geom) AS length
                  FROM polygons_user WHERE name LIKE %s
                  ORDER BY name"""
    PgCursor.execute(sql_list, (name, ))

    user_results = PgCursor.fetchall()

    if user_results:
        show("
%s
" % ("List of available user polygons for name = %s" % name))

        show("
\n")
        show("
\n")
        show("    %s	\n" % ("name"))
        show("    %s	\n" % ("timestamp"))
        show("    %s	\n" % ("NPoints"))
        show("    %s	\n" % ("Length"))
        show("    %s	\n" % ("WKT"))
        show("    %s	\n" % ("GeoJSON"))
        show("    %s	\n" % ("poly"))
        show("    %s	\n" % ("Image"))
        show("
\n")

        for res in user_results:
            n = str(res["name"])
            show("
\n")
            show("    " + n + "	\n")
            show("    " + str(res["timestamp"]) + "	\n")
            show("    " + str(res["npoints"]) + "	\n")
            show("    " + str(res["length"]) + "	\n")
            show("    WKT	\n" % (n))
            show("    GeoJSON	\n" % (n))
            show("    poly	\n" % (n))
            show("    image	\n" % (n))
            show("
\n")

        show("
\n")

if rel_id != -1 and name != "" and osm_results and user_results:

    show("
%s
" % ("Union of all osm/user polygons"))

    show("
\n")
    show("
\n")
    show("    params	\n")
    for u_res in user_results:
        show("    %s	\n" % (u_res["name"]))
    show("
\n")
    for o_res in osm_results:
        show("
\n")
        show("    " + str(o_res["params"]) + "	\n")
        for u_res in user_results:
            show("    ")
            show("WKT\n" % (rel_id, o_res["params"], u_res["name"]))
            show("GeoJSON\n" % (rel_id, o_res["params"], u_res["name"]))
            show("poly\n" % (rel_id, o_res["params"], u_res["name"]))
            show("image\n" % (rel_id, o_res["params"], u_res["name"]))
            show("    	")
        show("
\n")
    show("
\n")

if rel_id == -1 or name == "":
    show("

\n")
    show("
%s
" % ("Show polygon"))
    show("<form method='GET' action=''>")
    show("%s" % "Id of relation")
    if rel_id == -1:
        show("<input type='text' name='id' id='id'>")
    else:
        show("<input type='text' name='id' id='id' value='%d'>", rel_id)
    show("
")
    show("%s" % "Name of user polygon")
    show("<input type='text' name='name' id='name' value='%s'>" % name)
    show("<input type='submit'>")
    show("</form>")

###########################################################################
utils.print_tail()

PgConn.commit()
PgConn.close()


from os.path import join as pjoin
from typing import Optional

import torch

from tensordict.tensordict import TensorDict
from torchrl.envs import EnvBase

from rl4co.data.dataset import TensorDictDataset
from rl4co.data.utils import load_npz_to_tensordict
from rl4co.utils.pylogger import get_pylogger

log = get_pylogger(__name__)

class RL4COEnvBase(EnvBase):
    """Base class for RL4CO environments based on TorchRL EnvBase

    Args:
        data_dir: Root directory for the dataset
        train_file: Name of the training file
        val_file: Name of the validation file
        test_file: Name of the test file
        check_solution: Whether to check the validity of the solution at the end of the episode
        seed: Seed for the environment
        device: Device to use. Generally, no need to set as tensors are updated on the fly
    """

    batch_locked = False

    def __init__(
        self,
        *,
        data_dir: str = "data/",
        train_file: str = None,
        val_file: str = None,
        test_file: str = None,
        check_solution: bool = True,
        seed: int = None,
        device: str = "cpu",
        **kwargs,
    ):
        super().__init__(device=device, batch_size=[])
        self.data_dir = data_dir
        self.train_file = pjoin(data_dir, train_file) if train_file is not None else None
        self.val_file = pjoin(data_dir, val_file) if val_file is not None else None
        self.test_file = pjoin(data_dir, test_file) if test_file is not None else None
        self.check_solution = check_solution
        if seed is None:
            seed = torch.empty((), dtype=torch.int64).random_().item()
        self.set_seed(seed)

    def _step(self, td: TensorDict) -> TensorDict:
        """Step function to call at each step of the episode containing an action.
        Gives the next observation, reward, done
        """
        raise NotImplementedError

    def _reset(self, td: Optional[TensorDict] = None, batch_size=None) -> TensorDict:
        """Reset function to call at the beginning of each episode"""
        raise NotImplementedError

    def _make_spec(self, td_params: TensorDict = None):
        """Make the specifications of the environment (observation, action, reward, done)"""
        raise NotImplementedError

    def get_reward(self, td, actions) -> TensorDict:
        """Function to compute the reward. Can be called by the agent to compute the reward of the current state
        This is faster than calling step() and getting the reward from the returned TensorDict at each time for CO tasks
        """
        raise NotImplementedError

    def get_action_mask(self, td: TensorDict) -> torch.Tensor:
        """Function to compute the action mask (feasible actions) for the current state
        Action mask is 1 if the action is feasible, 0 otherwise
        """
        raise NotImplementedError

    def check_solution_validity(self, td, actions) -> TensorDict:
        """Function to check whether the solution is valid. Can be called by the agent to check the validity of the current state
        This is called with the full solution (i.e. all actions) at the end of the episode
        """
        raise NotImplementedError

    def dataset(self, batch_size=[], phase="train", filename=None):
        """Return a dataset of observations
        Generates the dataset if it does not exist, otherwise loads it from file
        """
        if filename is not None:
            log.info(f"Overriding dataset filename from {filename}")
        f = getattr(self, f"{phase}_file") if filename is None else filename
        if f is None:
            if phase != "train":
                log.warning(f"{phase}_file not set. Generating dataset instead")
            td = self.generate_data(batch_size)
        else:
            log.info(f"Loading {phase} dataset from {f}")
            if phase == "train":
                log.warning(
                    "Loading training dataset from file. This may not be desired in RL since "
                    "the dataset is fixed and the agent will not be able to explore new states"
                )
            try:
                td = self.load_data(f, batch_size)
            except FileNotFoundError:
                log.error(
                    f"Provided file name {f} not found. Make sure to provide a file in the right path first or "
                    f"unset {phase}_file to generate data automatically instead"
                )
                td = self.generate_data(batch_size)

        return TensorDictDataset(td)

    def generate_data(self, batch_size):
        """Dataset generation"""
        raise NotImplementedError

    def transform(self):
        """Used for converting TensorDict variables (such as with torch.cat) efficiently
        https://pytorch.org/rl/reference/generated/torchrl.envs.transforms.Transform.html
        By default, we do not need to transform the environment since we use specific embeddings
        """
        return self

    def render(self, *args, **kwargs):
        """Render the environment"""
        raise NotImplementedError

    @staticmethod
    def load_data(fpath, batch_size=[]):
        """Dataset loading from file"""
        return load_npz_to_tensordict(fpath)

    def _set_seed(self, seed: Optional[int]):
        """Set the seed for the environment"""
        rng = torch.manual_seed(seed)
        self.rng = rng

    def __getstate__(self):
        """Return the state of the environment. By default, we want to avoid pickling
        the random number generator directly as it is not allowed by `deepcopy`
        """
        state = self.__dict__.copy()
        state["rng"] = state["rng"].get_state()
        return state

    def __setstate__(self, state):
        """Set the state of the environment. By default, we want to avoid pickling
        the random number generator directly as it is not allowed by `deepcopy`
        """
        self.__dict__.update(state)
        self.rng = torch.manual_seed(0)
        self.rng.set_state(state["rng"])


import logging
import threading
import os
from typing import Callable, Iterable, List, Optional

from PyQt5 import QtCore, QtGui, QtWidgets

__all__ = ["LoggerWidget", "QueuedLoggerWidget"]

class Handler(logging.Handler):

    def __init__(self, callback: Callable) -> None:
        super().__init__()
        self.callback = callback

    def emit(self, record: logging.LogRecord) -> None:
        self.callback(record)

class LoggerWidget(QtWidgets.QTextEdit):

    MaximumEntries: int = 1024 * 1024
    """Maximum number of visible log entries."""

    received = QtCore.pyqtSignal(logging.LogRecord)
    """Received is emitted when a new log record is appended by a logger."""

    def __init__(self, parent: Optional[QtWidgets.QWidget] = None) -> None:
        super().__init__(parent)
        self.setReadOnly(True)
        self.document().setMaximumBlockCount(type(self).MaximumEntries)

        self.handler = Handler(self.received.emit)
        self.setLevel(logging.INFO)
        self.received.connect(self.appendRecord)

        self.recordFormats = {}

        errorFormat = QtGui.QTextCharFormat()
        errorFormat.setForeground(QtGui.QColor("red"))
        self.recordFormats[logging.ERROR] = errorFormat

        warningFormat = QtGui.QTextCharFormat()
        warningFormat.setForeground(QtGui.QColor("orange"))
        self.recordFormats[logging.WARNING] = warningFormat

        infoFormat = QtGui.QTextCharFormat()
        infoFormat.setForeground(QtGui.QColor())
        self.recordFormats[logging.INFO] = infoFormat

        debugFormat = QtGui.QTextCharFormat()
        debugFormat.setForeground(QtGui.QColor("grey"))
        self.recordFormats[logging.DEBUG] = debugFormat

    def setLevel(self, level: int) -> None:
        """Set log level of widget."""
        self.handler.setLevel(level)

    def addLogger(self, logger: logging.Logger) -> None:
        """Add logger to widget."""
        logger.addHandler(self.handler)

    def removeLogger(self, logger: logging.Logger) -> None:
        """Remove logger from widget."""
        logger.removeHandler(self.handler)

    def appendRecords(self, records: Iterable[logging.LogRecord]) -> None:
        """Append log records and auto scroll to bottom."""
        # Get current scrollbar position
        scrollbar = self.verticalScrollBar()
        position = scrollbar.value()
        # Lock to current position or to bottom
        lock = position + 1 >= scrollbar.maximum()
        # Append formatted log messages
        for record in records:
            text = self.formatRecord(record)
            textCharFormat = self.recordTextCharFormat(record)
            textCursor = QtGui.QTextCursor(self.document())
            textCursor.movePosition(QtGui.QTextCursor.End)
            # Insert newline except for first entry
            if not self.textCursor().atStart():
                textCursor.insertText(os.linesep)
            textCursor.insertText(text, textCharFormat)
        # Scroll to bottom
        if lock:
            scrollbar.setValue(scrollbar.maximum())
        else:
            scrollbar.setValue(position)

    def appendRecord(self, record: logging.LogRecord) -> None:
        """Append log record and auto scroll to bottom."""
        self.appendRecords([record])

    def recordTextCharFormat(self, record: logging.LogRecord) -> QtGui.QTextCharFormat:
        """Return text character format for record."""
        for level, textCharFormat in self.recordFormats.items():
            if record.levelno >= level:
                return textCharFormat
        return QtGui.QTextCharFormat()

    def showRecentRecords(self) -> None:
        scrollbar = self.verticalScrollBar()
        scrollbar.setValue(scrollbar.maximum())

    @classmethod
    def formatTime(cls, seconds: float) -> str:
        """Format timestamp for log record."""
        dt = QtCore.QDateTime.fromMSecsSinceEpoch(int(seconds * 1e3))
        return dt.toString("yyyy-MM-dd hh:mm:ss")

    @classmethod
    def formatRecord(cls, record: logging.LogRecord) -> str:
        """Format log record."""
        timestamp = cls.formatTime(record.created)
        return "{}\t{}\t{}".format(timestamp, record.levelname, record.message)

class RecordsQueue:

    def __init__(self) -> None:
        self.lock = threading.RLock()
        self.records: List[logging.LogRecord] = []

    def append(self, record: logging.LogRecord) -> None:
        with self.lock:
            self.records.append(record)

    def fetch(self) -> List[logging.LogRecord]:
        with self.lock:
            records = self.records[:]
            self.records.clear()
            return records

class QueuedLoggerWidget(LoggerWidget):

    def __init__(self, parent: Optional[QtWidgets.QWidget] = None) -> None:
        super().__init__(parent)

        self.recordsQueue = RecordsQueue()

        self.updateInterval = 250

        self.updateTimer = QtCore.QTimer(self)
        self.updateTimer.timeout.connect(self.applyQueuedRecords)
        self.updateTimer.start(self.updateInterval)

    def appendRecord(self, record: logging.LogRecord) -> None:
        """Append log record to queue."""
        self.recordsQueue.append(record)

    def applyQueuedRecords(self) -> None:
        """Append records from queue to log widget."""
        records = self.recordsQueue.fetch()
        if records:
            super().appendRecords(records)


# Import our python modules needed for NoSQL db (Mongo) and TKinter for the GUI
from flask import Flask, render_template, request, redirect
from tkinter import *
from tkinter import simpledialog
from pymongo import MongoClient
from pymongo.cursor import Cursor
from pymongo.server_api import ServerApi
import pprint
import io
import re
import sys

root = Tk()
root.title("Retail Inventory App - NoSQL DB - IUBH")
root.bell()

# Our sample database
store_data = [
    {"item": "Item 1 ", "price": 14.6, "quantity": 50, "category": "Category 1", "brand": "Brand Gaeger", "color": "Red", "size": "Small", "material": "Cotton"},
    {"item": "Item 2 🛍", "price": 70.2, "quantity": 30, "category": "Category 2", "brand": "Brand Umlaut", "color": "Blue", "size": "Medium", "material": "Polyester"}
]

# Connect to MongoDB
mongo_uri = 'mongodb://localhost:27017/'
client = MongoClient(mongo_uri)
db = client['Datastream_db']
collection = db['Data_collection']

# Set the Stable API version when creating a new client
client = MongoClient(mongo_uri, server_api=ServerApi('1'))

# Send a ping to confirm a successful connection
try:
    client.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)

# Insert the data into the collection
collection.insert_many(store_data)

# Define a list of auto-completion options
autocomplete_options = [
    'store_data',
    'collection.insert_one',
    'collection.insert_many',
    'collection.find',
    'collection.update_one',
    'collection.update_many',
    'collection.delete_one',
    'collection.delete_many',
    'collection.updateOne',
    'db.collection.updateOne',
    'db.command'
]

# Create text input box
text_input = Text(root, width=60, height=2)
text_input.grid(row=0, column=0, padx=5, pady=5)

# Create button to execute code
def execute_code(event=None):
    code = text_input.get("1.0", END)
    buf = io.StringIO()

    try:
        # Check if the code contains MongoDB commands
        if re.search(r'\b(db\.[\w\.]+)\b', code):
            # Execute MongoDB commands and print the results
            result = db.command(code.strip())
            pprint.pprint(result, stream=buf)
        else:
            # Redirect stdout to buffer and evaluate Python code
            sys.stdout = buf
            result = eval(code)
            sys.stdout = sys.__stdout__

            # Check if the result is a cursor object and print each document
            if isinstance(result, Cursor):
                result = [doc for doc in result]
                for doc in result:
                    pprint.pprint(doc, stream=buf)
            else:
                pprint.pprint(result, stream=buf)

        # Display the results in the display_box
        display_box.insert(END, buf.getvalue())
        display_box.insert(END, "Code executed successfully!\n")

    except Exception as e:
        # Display any errors in the display_box
        display_box.insert(END, str(e))

# Bind Shift+Enter key to execute_code function
text_input.bind('<Shift-Return>', execute_code)

execute_button = Button(root, text="Execute", command=execute_code)
execute_button.grid(row=0, column=1, padx=5, pady=5)

# Create clear button
def clear_display():
    display_box.delete('1.0', END)

clear_button = Button(root, text="Clear", command=clear_display)
clear_button.grid(row=0, column=2, padx=5, pady=5)

# Create display box
display_box = Text(root, width=80, height=40)
display_box.grid(row=1, column=0, columnspan=2, padx=5, pady=5)

# Create auto-complete function
def autocomplete(event):
    text = event.widget.get("1.0", "end-1c")
    if text:
        matches = [option for option in autocomplete_options if option.startswith(text)]
        if len(matches) == 1:
            event.widget.delete("1.0", "end")
            event.widget.insert("1.0", matches[0])
        elif len(matches) > 1:
            selection = simpledialog.askstring("Autocomplete", "Did you mean one of these?\n" + "\n".join(matches))
            if selection:
                event.widget.delete("1.0", "end")
                event.widget.insert("1.0", selection)

# Bind auto-complete function to text input box
text_input.bind("<Tab>", autocomplete)

root.mainloop()

def execute_code(event=None):
    code = text_input.get("1.0", END)
    buf = io.StringIO()

    try:
        # Check if the code contains MongoDB commands
        if re.search(r'\b(db\.[\w\.]+)\b', code):
            # Execute MongoDB commands and print the results
            result = db.command(code.strip())
            pprint.pprint(result, stream=buf)
        else:
            # Redirect stdout to buffer and evaluate Python code
            sys.stdout = buf
            result = eval(code)
            sys.stdout = sys.__stdout__

            # Check if the result is a cursor object and print each document
            if isinstance(result, Cursor):
                result = [doc for doc in result]
                for doc in result:
                    pprint.pprint(doc, stream=buf)
            else:
                pprint.pprint(result, stream=buf)

        # Display the results in the display_box
        display_box.insert(END, buf.getvalue())

    except Exception as e:
        # Display any errors in the display_box
        display_box.insert(END, str(e))


import copy
from typing import Union, List
from collections import OrderedDict

import numpy as np

import torch.nn as nn

def try_match_signature_to_torch_module(state_dict: OrderedDict) -> \
        Union[nn.Module, List, None]:
    """Matches a set of parameters to their corresponding torch layer."""
    params = state_dict.keys()

    # Characteristics of a batch normalization layer.
    if 'running_mean' in params or 'running_var' in params:
        return make_batchnorm(state_dict)

    # Check for Linear vs. Conv2d layers.
    if 'weight' in params:
        if len(state_dict['weight'].size()) == 2:
            return make_dense(state_dict)
        elif len(state_dict['weight'].size()) == 4:
            return make_conv(state_dict)

    # An unrecognized type of layer.
    return None

def make_conv(state_dict: OrderedDict) -> nn.Conv2d:
    out_planes, in_planes, kernel = state_dict['weight'].size()[0:3]
    use_bias = False
    if 'bias' in state_dict.keys():
        use_bias = True
    layer = nn.Conv2d(int(in_planes), int(out_planes),
                      kernel_size = (kernel, ) * 2, bias = use_bias)
    layer.load_state_dict(state_dict, strict = False)
    return layer

def make_dense(state_dict: OrderedDict) -> nn.Linear:
    out_planes, in_planes = state_dict['weight'].size()[:2]
    use_bias = False
    if 'bias' in state_dict.keys():
        use_bias = True
    layer = nn.Linear(int(in_planes), int(out_planes), bias = use_bias)
    layer.load_state_dict(state_dict)
    return layer

def make_batchnorm(state_dict: OrderedDict) -> nn.BatchNorm2d:
    layer = nn.BatchNorm2d(int(state_dict['weight'].size()[0]))
    layer.load_state_dict(state_dict, strict = False)
    return layer

def make_sequential(state_dict: OrderedDict) -> nn.Sequential:
    """Constructs an `nn.Sequential` module from the state dict."""
    layers = []
    state_keys = state_dict.keys()
    for layer_name in get_unique_layers(state_dict.keys()):
        corresponding_keys = get_corresponding_keys(layer_name, state_keys)
        layer_dict = construct_layer_dict(corresponding_keys, state_dict)
        maybe_layer = try_match_signature_to_torch_module(layer_dict)
        if maybe_layer is not None:
            if isinstance(maybe_layer, list):
                layers.extend(maybe_layer)
            layers.append(maybe_layer)
        else:
            layers.append(reconstruct_model(layer_dict))
    return nn.Sequential(*layers)

def copy_layer(module: nn.Module) -> nn.Module:
    """Copies an `nn.Module` whilst maintaining its parameters."""
    return copy.deepcopy(module)

def pop_prefix(string):
    """Returns a string with the prefix removed."""
    return '.'.join(string.split('.')[1:])

def has_sub_modules(key):
    """Returns whether a layer has any submodules."""
    return len(key.split('.')) != 1

def is_sequential(state_keys):
    """Returns whether the state dict is of a sequential model."""
    return all([i.split('.')[0].isdigit() for i in state_keys])

def is_prefixed_sequential(state_keys):
    """Returns whether the state dict is of a prefixed sequential model."""
    try:
        return all([i.split('.')[1].isdigit() for i in state_keys])
    except IndexError:
        return False

def get_unique_layers(state_keys):
    """Returns a list of unique layers given a set of state keys."""
    keys = [i.split('.')[0] for i in state_keys]
    indexes = np.unique(keys, return_index = True)[1]
    return [keys[idx] for idx in sorted(indexes)]

def get_sub_layers(state_keys):
    """Returns a list of all of the sub-layers in a set of state keys."""
    return [pop_prefix(key) for key in state_keys]

def get_corresponding_keys(key, state_keys):
    """Returns all keys in `state_keys` starting with `key`."""
    return [i for i in state_keys if i.split('.')[0] == key]

def construct_layer_dict(keys, state_dict) -> OrderedDict:
    """Construct a state dict for the layer (with the prefix removed)."""
    return OrderedDict([
        (pop_prefix(i[0]), i[1]) for i in state_dict.items() if i[0] in keys])

def reconstruct_model(state_dict):
    """Reconstructs a PyTorch `nn.Module` given a state dict.

    This method attempts to reconstruct the topology of a PyTorch model given
    only its state dict of weights, not the actual model itself. The returned
    model maintains the topology as provided in the state dict, but it is
    unable to account for any layers which do not have weights; for instance,
    activation or dropout layers do not appear in the new module.

    Parameters
    ----------
    state_dict : OrderedDict
        The state dict of a PyTorch model, in the format as returned by, for
        example, `<arbitrary model>.state_dict()`. This can also be a regular
        `dict`, but in order to maintain an accurate topology of the model it
        should be an `OrderedDict`.
    """
    # Get the keys of the state dict and all of the layers.
    state_keys = state_dict.keys()
    layers = get_unique_layers(state_keys)

    # Begin by checking whether we have received a sequential model.
    if is_sequential(state_dict):
        return make_sequential(state_dict)

    # Recursively construct each layer.
    module_layers = OrderedDict()
    for layer_name in layers:
        corresponding_keys = get_corresponding_keys(layer_name, state_keys)
        layer_dict = construct_layer_dict(corresponding_keys, state_dict)
        sub_layers = get_sub_layers(corresponding_keys)
        layer = None

        # If the module is sequential, then we need to repeat this procedure
        # for each of those layers and wrap the entire thing in a sequential model.
        if is_sequential(sub_layers):
            layer = make_sequential(layer_dict)

        # A custom case where there is a prefix followed by a sequential layer
        # naming format, e.g., `block.1...`, `block.2....`, etc.
        elif is_prefixed_sequential(sub_layers):
            prefix = sub_layers[0].split('.')[0]
            sub_dict = OrderedDict((pop_prefix(i[0]), i[1]) for i in layer_dict.items())
            seq_layer = make_sequential(sub_dict)
            layer = nn.Module()
            layer.add_module(prefix, seq_layer)

        # If `bn` is in the layer name, assume that it is a batch normalization
        # layer and use `nn.BatchNorm()` as the stand-in for the layer, unless
        # a custom layer is passed in the state dict.
        elif 'bn' in layer_name:
            if not is_sequential(sub_layers):
                layer = make_batchnorm(layer_dict)

        # If `conv` or `fc` is in the layer name, assume that it is either a `Conv2d`
        # layer or a `Linear` layers and check based on the actual model weights which
        # of the two it is, unless a user-passed argument is present.
        elif 'conv' in layer_name or 'fc' in layer_name:
            if not is_sequential(sub_layers):
                layer = try_match_signature_to_torch_module(layer_dict)

        # Otherwise, this is likely a custom module and we need to recursively
        # construct the module.
        else:
            mod = try_match_signature_to_torch_module(layer_dict)

            # If the result of `mod` is not None, then that means that
            # this method has almost certainly received the state dict
            # of an individual layer, so we can bypass the full `nn.Module`
            # construction here and just return the layer here.
            if mod is not None:
                return mod

            # Otherwise, keep attempting to construct recursive sub-layers
            # until we get to recognized layers. If no recognized layers are
            # found, then raise an error since that would be unsupported.
            sub_layer_dict = OrderedDict()
            for sub_layer in get_unique_layers(sub_layers):
                sub_layer_dict[sub_layer] = reconstruct_model(construct_layer_dict(
                    get_corresponding_keys(sub_layer, sub_layers), layer_dict))

            # Reconstruct a new `nn.Module` from the layer.
            layer = nn.Module()
            for name, mod in sub_layer_dict.items():
                layer.add_module(name, mod)

        # Update the layer dictionary.
        module_layers[layer_name] = layer

    # Reconstruct the `nn.Module` from the dictionary of layers.
    module = nn.Module()
    for name, mod in module_layers.items():
        module.add_module(name, mod)
    return module