# -*- coding=utf-8 -*-

from PIL import Image
import argparse

#cmd命令行输入参数处理
parser = argparse.ArgumentParser()

parser.add_argument('file')    #输入文件
parser.add_argument('-o', '--output')   #输出文件
parser.add_argument('--width', type = int, default = 80)    #输出字符画宽
parser.add_argument('--height', type = int, default = 80)    #输出字符画高

#获取参数
args = parser.parse_args()

IMG = args.file    #输入的图片文件路径
WIDTH = args.width    #输出字符画的宽度
HEIGHT = args.height    #输出字符画的高度
OUTPUT = args.output    #输出字符画的路径

#创建一个不重复的字符列表，灰度值小（暗）的用列表开头的符号，灰度值大（亮）的用列表末尾的符号。
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")

# 将256灰度映射到70个字符上
def get_char(r,g,b,alpha = 256):
    """RGB值转灰度值再转字符"""
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)    #灰度值转换公式

    unit = (256.0 + 1)/length
    return ascii_char[int(gray/unit)]    #返回一个列表中的字符

if __name__ == '__main__':

    im = Image.open(IMG)
    im = im.resize((WIDTH,HEIGHT), Image.NEAREST)    #Image.NEAREST表示输出低质量图片

    txt = ""

    for i in range(HEIGHT):
        for j in range(WIDTH):
            txt += get_char(*im.getpixel((j,i)))    #im.getpixel((j,i))获取得到坐标RGB像素值，返回一个元组
        txt += '\n'

    print(txt)

    #字符画输出到文件
    if OUTPUT:
        with open(OUTPUT,'w') as f:
            f.write(txt)    #如果执行时配置了输出文件，将打开文件将 txt 输出到文件
    else:
        with open("G:\python\output.txt",'w') as f:
            f.write(txt)

项目一：图片转字符画/ascii.py


# Faça um Algoritmo que leia 5 valores e escreva no final a soma dos valores positivos e a média dos negativos.

def main():
    a = 0
    cont = 0
    contneg = 0
    somaneg = 0
    soma = 0
    for cont in range (0, 5, 1):
        a = int(input())
        if a>=0:
            soma = soma+a
        else:
            contneg = contneg+1
            somaneg = somaneg+a
            media = somaneg/contneg
    print(soma, media)
    return 0

if __name__ == "__main__":
    main()


from dependent.core.utils.config import DPConfig
from dependent.text2sql import Text2SQL

import tqdm
import torch

import logging
logger = logging.getLogger(__name__)

from golden_eval_examples import examples

# Set up configurations

### Training algorithm configuration
# 'task': choose training algorithm, e.g., supervised fine-tuning (SFT)

algorithm_config = {
    'task': 'SFT'
}

### Model configuration
# 'id': the link of the model on huggingface
# 'model_class': the class of the model on huggingface
# 'torch_dtype': the model storage type, e.g., fp16, bf16
# 'device_map': select the device to run the model, e.g., 'auto', 'cuda:0'
# 'trust_remote_code": an argument from the huggingface API

model_config = {
    'id': 'codellama/CodeLlama-7b-hf',
    #'gpt2', #"vilsonrodrigues/falcon-7b-instruct-sharded",
    'model_class': 'AutoModelForCausalLM', #'GPT2LMHeadModel', #'AutoModelForCausalLM',
    "torch_dtype": torch.bfloat16,
    'device_map': 'auto',
    "trust_remote_code": True,
}

### Quantization configuration
# The arguments are required by the `bitsandbytes` library

quantization_config = {
    'load_in_4bit': True,
    'bnb_4bit_quant_type': "nf4",
    'bnb_4bit_use_double_quant': True,
    'bnb_4bit_compute_dtype': torch.float16
}

### LORA configuration
# The arguments are required by the `peft` library

lora_config = {
    'r': 8,
    'lora_alpha': 32,
    'target_modules': ["query_key_value"],
    'lora_dropout' : 0.05,
    'bias': "none",
    'task_type': "CAUSAL_LM"
}

### Tokenization configuration
# 'id': the link of the model on huggingface
# 'tokenizer_class': the class of the tokenizer on huggingface
# other arguments: refer to the huggingface tokenizer API

tokenizer_config = {
    'id': "codellama/CodeLlama-7b-hf",
    #'gpt2', #"vilsonrodrigues/falcon-7b-instruct-sharded",
    'tokenizer_class': 'AutoTokenizer',
    #'GPT2Tokenizer',
    'padding_side': 'left',
    'padding_token': 'eos_token',
    'eos_token': 'eos_token',
    'max_length': 512,
}

### Pipeline configuration
# 'eos_token_id': the token id of the string that marks the end of the text,
# 'pad_token_id': the token id of the string that pads the string to the max length

pipeline_config = {
    'eos_token_id': 'eos_token_id',
    'pad_token_id': 'eos_token_id'
}
### Optimizer configuration
# So far not configured because Huggingface trainer does not provide freedom in configuring the optimizer
# Will have more freedom in configuration if using Mosaic, Zero, ...

optimizer_config = {}

### Trainer configuration
# 'name': the name of the training library, e.g. huggingface, mosaic, ...
# 'epoch': the number of epochs for training
# other arugments: refer to the training library's API

train_config = {
    'name': 'huggingface',
    'epochs': 10,
    'per_device_train_batch_size': 1,
    'gradient_accumulation_steps': 4,
    'max_steps': 200,
    'learning_rate': 2e-4,
    'fp16': True,
    'logging_steps': 1,
    'output_dir': 'outputs',
    'optim': "paged_adamw_8bit"
}

### Dataset configuration
# 'dataset': the name of the dataset. Need local support. Currently only support spider, cosql, and sparc
# 'num_workers': the number of workers for preprocessing the dataset. An argument required by pyarrow.Dataset API.
# `num_splits': number of splits in the dataset for k-fold cross validation
# `columns`: the columns to keep in the training set
# 'type': the data type of the training set

data_config = {
    'dataset': ['spider'],
    'num_workers': 8,
    'num_splits': 1,
    'columns': ['input_ids', 'attention_mask', 'label'],
    'type': torch
}

### Dependent configuration
# 'algorithm': the algorithm configuration
# 'llm': the ensemble of the model, tokenizer, quantization, and pipeline configurations
# 'train': the trainer configuration
# 'data': the data configuration

dependent_config = {
    'algorithm': algorithm_config,
    'llm': {
        'model': model_config,
        'tokenizer': tokenizer_config,
        #'quantization': quantization_config,
        'pipeline': pipeline_config,
        #'lora': lora_config
    },
    'train': train_config,
    'data': data_config
}

log_interval = 10
eval_interval = 100

# Create the trainig pipeline configuration
text2sql_config = DPConfig.from_dict(dependent_config)

# Create a training pipeline
agent = Text2SQL.from_config(text2sql_config)

# Run the training pipeline for certain epochs
for i in tqdm.tqdm(range(1, agent.config.train.epochs)):
    # Evaluate the model with example
    for example in examples:
        print(agent.pipeline(example))
    # Run fine-tuning for one epoch
    train_info = agent.run(episodes = 1)

    # Record training info
    if i % log_interval == 0:
        for k, v in train_info.items():
            logger.info(f'training/{k}', v, i)

# Evaluate the model with example
for example in examples:
    print(agent.pipeline(example))


# 394. Decode String

# Reference
# https://leetcode.com/problems/decode-string/discuss/1400105/98-faster-oror-With-and-without-Stack-oror-Cleane-and-Concise

class Solution:
    def decodeString(self, s: str) -> str:
        res, num = "", 0
        stack = []
        for l in s:
            if l.isdigit():
                num = num * 10 + int(l)
            elif l == "[":
                stack.append(res)
                stack.append(num)
                res = ""
                num = 0
            elif l == "]":
                pnum = stack.pop()
                pstr = stack.pop()
                res = pstr + pnum*res
            else:
                res += l
        return res


def StackCalc(inp):
    """
    This function gets a string (e.g. "9 4 2 + 7 -") and does the calculations
    as if it was a stack calculater (for the ex above: 7-(2+4)=1.)
    This function returns the top of the stack (for the ex above: 1 because the stack is [9 1]).
    """
    inp = inp.split()
    leng = len(inp)
    st = [' '] * leng
    top = 0

    print("input:", inp)
    print("top:", top, ", st:", st)

    if leng == 0: return 0

    for c in inp:
        if c in ['+', '-', '*', '/']:
            st[top-2] = str(eval(st[top-1] + c + st[top-2]))
            st[top-1] = ' '
            top -= 1
        else:
            st[top] = c
            top += 1
        print("top:", top, ", st:", st)

    return float(st[top-1])

def Tests_StackCalc():  # Tests for the function StackCalc
    test1 = "5 6 - 7 +" # 7+(6-5) = 8
    print("result:", StackCalc(test1), "\n")

    test2 = "3 2 4 5 6 - 7 +" # 7+(6-5) = 8  # numbers 3,2,4 are ignored
    print("result:", StackCalc(test2), "\n")

    test3 = "2 3 + 7 - 1 -" # 1-(7-(3+2)) = -1
    print("result:", StackCalc(test3), "\n")

    test4 = "2 3 + 7 - 1 - -1 * 4 * 2 /" # 2/(4*(-1*(1-(7-(3+2))))) = 0.5
    print("result:", StackCalc(test4), "\n")


"""
Templates for reporting
=========================

Some methods for concat html string.
"""

__all__ = [
    "group_template"
]

group_html = """

Group %s Finished

%d tasks total, %d successful, %d failed.

Successful:

        %s

Exception:

        %s

"""

def success_table(datas: list) -> str:
    ret = ["
",
           "
task id	train acc	val acc	",
           "data	load time	train time
"]
    for taskid, data in datas:
        ret.append("
%s	%s	%s	%s	%s	%s
" %
                   (taskid, data["train_acc"], data["val_acc"], data["data"], data["load_time"], data["train_time"]))
    ret.append("
")
    return "".join(ret)

def fail_table(datas: list) -> str:
    ret = ["
", "
task id	stage	message
"]
    for taskid, data in datas:
        ret.append("
%s	%s	%s
" % (taskid, data["stage"], data["message"]))
    ret.append("
")
    return "".join(ret)

def group_template(name: str, result: dict) -> str:
    """
    group report template html.

    :param name: group name
    :param result: group schedule result.
    :return: the html string.
    """
    global group_html
    success_datas = []
    fail_datas = []
    for k, v in result.items():
        if v["type"] == "success":
            success_datas.append((k, v["data"]))
        else:
            fail_datas.append((k, v["data"]))
    return group_html % (name, len(result), len(success_datas), len(fail_datas),
                         success_table(success_datas), fail_table(fail_datas))


import time
import webbrowser
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from tkinter import *
from tkinter.filedialog import askopenfile

print (">>> Discord Nitro Code Checker <<< ")
print (">>> Made by Atlas | Nulled.to <<< ")
webbrowser.open('https://www.nulled.to/user/1229709-atlas')

driver = webdriver.Chrome("C:/chromedriver.exe");
xPath = """//*[@id="app-mount"]/div[1]/div/div[2]/div/section/div/div[1]"""
count = 0
might = 0
attempts = 0

file = askopenfile(filetypes=[("Text files","*.txt")])
codes = file.readlines()

for code in codes:
	print(attempts)
	attempts += 1
	driver.get("http://discord.gift/" + code)
	time.sleep(2)
	try:
		texter = driver.find_element_by_xpath(xPath)
	except NoSuchElementException:
		print ("Might be Valid \n \n \n \n %s - @Atlas - \n \n \n \n" % code)
		might += 1
		continue
	if(texter.text == "Gift Code Invalid"):
		print("Might: %d | Invalid: %d" % (might, attempts))
time.sleep(3);
print("\n\tMight: %d \n\t Invalids: %d" % (might, attempts))
driver.close()
input('Finished')


# the following two lines are for front end user
import sys
sys.path.append("..")

import carla
import time
import datetime

from backend.intersection_settings_helper import write_intersection_settings, read_intersection_settings

from backend.carla_env import CARLA_ENV # self-written class that provides help functions
from backend.multiple_vehicle_control import VehicleControl
from backend.initial_intersection import  create_intersections, get_ego_spectator, get_ego_left_spectator
from backend.full_path_vehicle import LeadVehicleControl, FollowVehicleControl

from backend.intersection_definition import get_traffic_lights
from backend.intersection_backend import IntersectionBackend

def main():
    try:
        client = carla.Client("localhost",2000)
        client.set_timeout(10.0)
        world = client.load_world('Town05')
	# client.start_recorder("output.log", True)

        # set the weather
        weather = carla.WeatherParameters(
            cloudiness=10.0,
            precipitation=0.0,
            sun_altitude_angle=90.0)
        world.set_weather(weather)

        # set the spectator position for demo purpose
        spectator = world.get_spectator()
        spectator.set_transform(carla.Transform(carla.Location(x=-190, y=1.29, z=75.0), carla.Rotation(pitch=-88.0, yaw= -1.85, roll=1.595))) # top view of intersection

        env = CARLA_ENV(world)
        time.sleep(2) # sleep for 2 seconds, wait the initialization to finish

        # get traffic light list
        traffic_light_list = get_traffic_lights(world.get_actors())

        # get intersection list
        intersection_list = create_intersections(env, 4, traffic_light_list, navigation_speed = 10.0)

        # edit intersection
        # these should be done with the help of the front end gui
        init_intersection = intersection_list[0]
        normal_intersections = intersection_list[1:]
        init_intersection.add_ego_vehicle(safety_distance = 15.0, stop_choice = "abrupt", vehicle_color = '255,255,255')
        init_intersection.add_follow_vehicle(follow_distance = 20.0, stop_choice = "penetrate", penetrate_distance = 2.0)
        init_intersection.add_lead_vehicle(lead_distance = 20.0, stop_choice = "abrupt")
        init_intersection.add_vehicle(choice = "left", stop_choice = "abrupt", vehicle_color = '255,255,255')
        init_intersection.add_vehicle(choice = "right",command="left")

        # test edit settings
        name1 = init_intersection.add_vehicle(choice = "ahead",command="left")
        name2 = init_intersection.add_vehicle(choice = "ahead",command = "right")

        name1 = init_intersection.edit_vehicle_settings(name1, choice = "ahead", vehicle_color = '128,128,128')
        name2 = init_intersection.edit_vehicle_settings(name2, choice = "ahead", gap = 15.0, vehicle_color = '128,128,128')

        # get bounding box
        bb = init_intersection.get_vehicle_bounding_box(name1)
        print("bb.x = %f, bb.y = %f, bb.z = %f" % (bb.x, bb.y, bb.z))

        init_intersection.edit_traffic_light("subject")
        init_intersection.edit_traffic_light("left",red_start = 40.0,red_end = 60.0,yellow_start=30.0,yellow_end=40.0,green_start=0.0,green_end = 30.0)
        init_intersection.edit_traffic_light("right",red_start = 0.0,red_end = 10.0,yellow_start=10.0,yellow_end=20.0,green_start=20.0,green_end = 40.0)
        init_intersection.edit_traffic_light("ahead",red_start = 20.0,red_end = 40.0,yellow_start=10.0,yellow_end=20.0,green_start=0.0,green_end = 10.0)

        intersection_list[1].add_vehicle(choice = "ahead")
        intersection_list[1].add_vehicle(choice = "left",command="left")
        intersection_list[1].add_vehicle(choice = "right",command = "left")
        intersection_list[1].add_vehicle(choice = "right",command = "right")
        intersection_list[1]._shift_vehicles(-10, choice = "right",index = 0)
        #intersection_list[1].edit_traffic_light("left")

        intersection_list[2].add_vehicle(choice = "ahead")
        intersection_list[2].add_vehicle(choice = "left",command="left")
        intersection_list[2].add_vehicle(choice = "right",command = "left")
        intersection_list[2].add_vehicle(choice = "right",command = "right")
        #intersection_list[2].edit_traffic_light("right")

        intersection_list[3].add_vehicle(command = "left")
        intersection_list[3].add_vehicle()
        intersection_list[3].edit_traffic_light("ahead")

        # test import/export
        init_setting = init_intersection.export_settings()

        intersection_list[3].import_settings(init_setting)
        intersection_list[3].add_vehicle(command = "left")
        intersection_list[3].add_vehicle()
        third_setting = intersection_list[3].export_settings()

        write_intersection_settings("third_intersection_setting",third_setting)
        new_third_setting = read_intersection_settings('third_intersection_setting')

        intersection_list[2].import_settings(new_third_setting)

        IntersectionBackend(env,intersection_list)
    finally:
        time.sleep(10)
        env.destroy_actors()
	# client.stop_recorder()

    # with open('output_' + str(datetime.datetime.now()) +'.txt', 'w') as f:
        # sys.stdout = f # Change the standard output to the file we created.
        # print(client.show_recorder_file_info("output.log"))
        # Reset the standard output to its original value
        # print_to_file()
        # do some file parsing with f

if __name__ == '__main__':
    main()


# Dostep swobodny
# Demonstruje indeksowanie znakow

import random

word = "piotrek"
print("Wartosc zmiennej word to: ", word, "\n")

high = len(word)
low = -len(word)

for i in range(10):
    position = random.randrange(low, high)
    print("word[", position, "]\t", word[position])

input("\n\nAby zakonczyc program, nacisnij klawisz ENTER.")

Python Programming for the Absolute Beginner/r04/dostep_swobodny.py


import configparser

class Config():
    def __init__(self, file) -> None:
        self.configFile = file
        self.parser = configparser.ConfigParser(delimiters=('='), allow_no_value=True)

        self.parser.optionxform = str
        self.parser.read(self.configFile)
        self.data = list(self.load())
        self.backup = list(self.load())

    def load(self) -> tuple[list, list, list, dict]:
        self.parser.read(self.configFile)
        tracklist = {}

        try:
            sources = list(self.parser.get("TRACKED", "sources").split("|"))
            extensions = list(self.parser.get("TRACKED", "extensions").split("|"))
            destinations = list(self.parser.get("TRACKED", "destinations").split("|"))
        except configparser.NoOptionError:
            raise Exception("Cannot load configuration file. 'TRACKED' section is missing options")
        except configparser.NoSectionError:
            raise Exception("Cannot load configuration file. 'TRACKED' section is missing")
        except AttributeError:
            raise Exception("Cannot load configuration file. Invalid option in 'TRACKED' section")

        try:
            for key in self.parser["TRACKLIST"]:
                tracklist[key] = list(self.parser["TRACKLIST"][key].split("|"))
                if '' in tracklist[key]: tracklist[key] = []
        except KeyError as e:
            raise Exception(f"Cannot load configuration file. {str(e)} section is missing")

        return (sources if '' not in sources else [],
                extensions if '' not in extensions else [],
                destinations if '' not in destinations else [],
                tracklist if '' not in tracklist else {})

    def update(self, includeBackup = False) -> None:
        self.data = list(self.load())
        if includeBackup: self.backup = list(self.load())

    def hasChanged(self) -> bool:
        return False if self.data == self.backup else True

    def addKey(self, section, newKey) -> None:
        self.parser[section][newKey] = ""
        self.saveChanges()

    def deleteKey(self, section, oldKey) -> None:
        for key in self.parser[section]:
            if key == oldKey:
                self.parser.remove_option(section, key)
        self.saveChanges()

    def editKey(self, section, oldKey, newKey) -> None:
        for key in self.parser[section]:
            if key == oldKey:
                value = self.parser.get(section, key)
                self.parser.remove_option(section, key)
                self.parser[section][newKey] = value
        self.saveChanges()

    def saveChanges(self) -> None:
        with open(self.configFile, 'w') as configfile:
            self.parser.write(configfile)
        self.update()

    # THROWS NoOptionError, NoSectionError
    def add(self, section, key, value) -> None:
        if value != "":
            option = self.parser.get(section, key)
            newOption = f"{option}|{value}" if len(option) > 0 else f"{value}"

            if key == "destinations":
                self.addKey("TRACKLIST", value)

            self.parser.set(section, key, newOption)
            self.saveChanges()

    def edit(self, section, key, oldValue, newValue) -> None:
        option = self.parser.get(section, key)
        newOption = option.replace(oldValue, newValue)

        if key == "destinations":
            self.editKey("TRACKLIST", oldValue, newValue)
        elif key == "extensions":
            newOption = option.rsplit(".", 1)[0] + newValue

        self.parser.set(section, key, newOption)
        self.saveChanges()

    def delete(self, section, key, value) -> None:
        option = self.parser.get(section, key)
        if option.find(f"|{value}") != -1: valueToDelete = f"|{value}"
        elif option.find(f"{value}|") != -1: valueToDelete = f"{value}|"
        else: valueToDelete = f"{value}"
        newOption = option.replace(valueToDelete, "")

        if key == "destinations": self.deleteKey("TRACKLIST", value)
        if value == ".": newOption = option.rsplit("|.", 1)[0]

        self.parser.set(section, key, newOption)
        self.saveChanges()


# 设损失函数为（w+1)^2, 令w初值为5.反向传播就是求最优w，即求最小loss对应的w值
import tensorflow as tf
LEARNING_RATE_BASE = 0.1 #最初学习率
LEARNING_RATE_DECAY = 0.9 #学习衰减率
LEARNING_RATE_STEP = 1 #喂入多少轮BATCH_SIZE后， 更新一次学习率， 一般设为：总样本/BATCH_SIZE

global_step = tf.Variable(0, trainable=False) #运行轮数计数器，不被训练
learning_rate = tf.compat.v1.train.exponential_decay(LEARNING_RATE_BASE, global_step, LEARNING_RATE_STEP, LEARNING_RATE_DECAY, staircase=True)

w = tf.Variable(tf.constant(5, dtype=tf.float32))

loss = tf.square(w+1)
train_step = tf.compat.v1.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)

with tf.compat.v1.Session() as sess:
	init_op = tf.compat.v1.global_variables_initializer()
	sess.run(init_op)
	for i in range(40):
		sess.run(train_step)
		learning_rate_val =sess.run(learning_rate)
		global_step_val = sess.run(global_step)
		w_val = sess.run(w)
		loss_val = sess.run(loss)
		print("After %s steps: global_step is %f, learnng_rate is %f, w is %f, loss is %f." %(i, global_step_val, learning_rate_val, w_val, loss_val))


#!/usr/bin/env python
# coding: utf-8
"""
@author: magic
"""

from django.conf.urls import patterns, include, url
from blog.views import *

urlpatterns = patterns('',
    url(r'^post_list/$', post_list, name='post_list'),
	url(r'^post/(?P<pk>\d+)/$', post_detail, name="post_detail"),
	url(r'^post/new/$', post_new, name="post_new"),
	url(r'^post/(?P<pk>\d+)/edit/$', post_edit, name="post_edit"),
	url(r'^drafts/$', post_draft_list, name="post_draft_list"),
	url(r'^post/(?P<pk>[0-9]+)/publish/$', post_publish, name="post_publish"),
	url(r'^post/(?P<pk>\d+)/ remove/$', post_remove, name="post_remove"),
)


#!/usr/bin/env python

import os
import datetime
from jinja2 import Environment, FileSystemLoader

#TMPL_FILES = ['index.html', 'resources.html', 'schedule.html', 'papers.html']
TMPL_FILES = ['index.html','syllabus.html','policies.html','mentors.html','resources.html', 'faq.html', 'alumni.html','students.html','teacherassistants.html']
TMPL_DIR = os.path.realpath(os.path.join(os.path.dirname(__file__), '../templates'))
OUTPUT_PATH = os.path.realpath(os.path.join(TMPL_DIR, '../deploy'))

def get_page_name(tmpl_file_name):
    return os.path.splitext(tmpl_file_name)[0].lower()

def get_base_params():
    return {'last_modified': datetime.date.today()}

def generate(tmpl_base, tmpl_files, dest_path):
    env = Environment(loader=FileSystemLoader(tmpl_base))
    params = get_base_params()

    for tmpl_name in tmpl_files:
        tmpl = env.get_template(tmpl_name)
        out_file = os.path.join(dest_path, os.path.basename(tmpl_name))
        print('Generating: %s'%out_file)
        params['page_name'] = get_page_name(tmpl_name)
        open(out_file, 'wb').write(tmpl.render(**params))

if __name__=='__main__':
    generate(TMPL_DIR, TMPL_FILES, OUTPUT_PATH)


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

"""
Import all the basic stuff
"""

from plot_keras_history import show_history, plot_history
from tensorflow.keras.backend import square, mean
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard, ReduceLROnPlateau
from tensorflow.keras.optimizers import RMSprop, Adam
from tensorflow.keras.layers import Input, Dense, GRU, Embedding
from tensorflow.keras.models import Sequential
import matplotlib as mpl
import IPython.display
import IPython
from predlib import direction_to_angle, WindowGenerator, Model, RepeatBaseline
from gemlib import to_celsius
from matplotlib.collections import TriMesh
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import pandas as pd
import os
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime, timedelta

mpl.rcParams['figure.figsize'] = (8, 6)
mpl.rcParams['axes.grid'] = False

"""
Automatically retrieves the path of the lastest `Bresso_updated` weather-data file downloaded through `table_scraper.py`
"""

gemini_path = '/Users/matteocitterio/Documents/gemini-Project'
files = [i for i in os.listdir(gemini_path) if os.path.isfile(os.path.join(gemini_path, i)) and
         'Bresso_updated' in i]

path_name = (files[-1])

"""
Read file and drop NaNs
"""

df = pd.read_csv(path_name)
df.dropna(how='any', inplace=True)

"""
Convert wind direction into degrees
"""

Written_winds = ['North', 'South', 'East', 'West']
Shorter_winds = ['N', 'S', 'E', 'W']

df.Wind = df.Wind.replace(Written_winds, Shorter_winds)

wind_dirs = ['N', 'NNE', 'NNW', 'NW', 'NE', 'ENE', 'E', 'SE',
             'ESE', 'SSE', 'WNW', 'W', 'S', 'SW', 'SSW', 'WSW']
angle_list = [0, 22.5, 337.5, 315, 45, 67.5, 90, 135,
              112.5, 157.5, 295.5, 270, 180, 225, 202.5, 247.5]

df.Wind = direction_to_angle(df.Wind, wind_dirs, angle_list)

"""
Stripe measure units and convert everything into float numbers
"""

head_list = [
    'Temperature',
    'Humidity',
    'Dew Point',
    'Speed',
    'Gust',
    'Pressure',
    'Precip. Rate.',
    'Precip. Accum.',
    'Solar',
]

for header in head_list:
    df[header] = (df[header].str.split().str[0])
    df[header] = (df[header].astype(float))

"""
Let's do the vector transformation (wind speed, wind direction) -> (wind x, wind y), this will improve our
prediction
"""

wv = df.pop('Speed')

# Convert to radians.
wd_rad = df.pop('Wind')*np.pi / 180

# Calculate the wind x and y components.
df['Wx'] = wv*np.cos(wd_rad)
df['Wy'] = wv*np.sin(wd_rad)

"""
Let's cut the complete dataset eliminating the parts where no data are available, namely consider only from
30-10-2021 until today
"""

LastAvailableDay = datetime.strptime(
    df['Time'].str.split().str[2].unique()[-1], "%Y-%m-%d")
StartingDay = LastAvailableDay - timedelta(days=375-1)
print(StartingDay)

df = df[df['Time'].str.split().str[2] >= StartingDay.strftime("%Y-%m-%d")]

df['Temperature'] = to_celsius(df['Temperature'])

"""
We can now think that time is of course periodic and an a priori assumption could be considering weather as
something with the same period of the time of the Year + the time of the day + fluctuations.
We should then convert the time info into a periodic variable
"""

date_time = pd.to_datetime(df.pop('Time'), format='%I:%M %p %Y-%m-%d')
timestamp_s = date_time.map(pd.Timestamp.timestamp)

day = 24*60*60
year = (365.2425)*day
hour = 60 * 60

df['Day sin'] = np.sin(timestamp_s * (2 * np.pi / day))
df['Day cos'] = np.cos(timestamp_s * (2 * np.pi / day))
df['Year sin'] = np.sin(timestamp_s * (2 * np.pi / year))
df['Year cos'] = np.cos(timestamp_s * (2 * np.pi / year))

"""
Precipitation rate has only spikes and it is not as informative since it basically doesnt correlate with anything
we should drop it and keep in mind that the same fate could be shared by her sister, `Prep. Acc.`
"""

df.pop('Precip. Rate.')

"""
Since i need to test what i'im doing and to stress my architecture features I only consider the 2% of the
complete dataset which is something around a week
"""

# n = len(df)
# df = df[int(n*0.95):-1]

"""
Let's get the features and the data split: 70% training, 20% validation, 10% test
"""

column_indices = {name: i for i, name in enumerate(df.columns)}

n = len(df)
train_df = df[0:int(n*0.7)]
val_df = df[int(n*0.7):int(n*0.9)]
test_df = df[int(n*0.9):]

num_features = df.shape[1]
print('Num features:', num_features)

"""
Let's renormalize the dataset according to the train mean and std
"""

train_mean = train_df.mean()
train_std = train_df.std()

train_df = (train_df - train_mean) / train_std
val_df = (val_df - train_mean) / train_std
test_df = (test_df - train_mean) / train_std

"""
This is the core the class WindowGenerator which essentially carries out all the boring stuff we need to do in
order to create an eligible piece if training-val-test data.
"""

MAX_EPOCHS = 20

input_hours = 24
output_hours = 1

OUT_STEPS = 12 * output_hours
IN_STEPS = 12 * input_hours

prediction_labels = ['Temperature']
num_features_predicted = len(prediction_labels)
multi_window = WindowGenerator(input_width=IN_STEPS,
                               label_width=OUT_STEPS,
                               shift=OUT_STEPS,
                               train_df=train_df,
                               val_df=val_df,
                               test_df=test_df,
                               label_columns=prediction_labels,
                               batch_size=4)

# multi_window.plot()

inputs, labels=multi_window.example

# inputs, labels = multi_window.unshuffled_test.take(1)

x=[]
y_true=[]
y_pred_baseline=[]
y_pred_multi=[]
y_pred_lstm=[]
y_pred_dense=[]
y_pred_cnn=[]
y_pred_bidir=[]

model = Model(multi_window, train_std['Temperature'])

# model.repeat_baseline('repeat_baseline')
# model.compile_and_fit()

# model.performance()
# predictions_baseline=model.predict(inputs)
# print(predictions_baseline.shape)
# predictions_baseline=tf.reshape(predictions_baseline, (4,12,1))

print('Multi')
model.multi_linear(OUT_STEPS, num_features_predicted, model_name='multilinear', LoadModel=True)

model.performance()
predictions = model.predict(inputs)

# print('lstm')
# model.multi_lstm(OUT_STEPS, num_features_predicted,
#                  model_name='multi_lstm', LoadModel=True)

# model.performance()
# predictions_lstm = model.predict(inputs)
print('Bidir')
# model.bidirectional_lstm(OUT_STEPS, num_features_predicted,
#                          model_name='bidirectional_lstm', LoadModel=True)

# model.performance()
# predictions_bidir = model.predict(inputs)

print('Dense')
model.dense(OUT_STEPS, num_features_predicted,
                 model_name='dense', LoadModel=True)

model.performance()
predictions_dense = model.predict(inputs)

# print('cnn')
model.cnn(OUT_STEPS, num_features_predicted,
                 model_name='cnn', LoadModel=True)

model.performance()
predictions_cnn = model.predict(inputs)

# model.comparison_performances()

model.comparison_performances()

for i in range(0, 4):

    for j in range(0, multi_window.label_width):

        x.append((multi_window.label_indices + (OUT_STEPS * i))[j])
        y_true.append(((labels[i, :, multi_window.label_columns_indices.get(
            'Temperature', None)]*train_std[0])+train_mean[0])[j])
        y_pred_multi.append(((predictions[i, :, multi_window.label_columns_indices.get(
            'Temperature', None)]*train_std[0])+train_mean[0])[j])
        # y_pred_lstm.append(((predictions_lstm[i, :, multi_window.label_columns_indices.get(
        #     'Temperature', None)]*train_std[0])+train_mean[0])[j])
        y_pred_dense.append(((predictions_dense[i, :, multi_window.label_columns_indices.get(
            'Temperature', None)]*train_std[0])+train_mean[0])[j])
        # y_pred_bidir.append(((predictions_bidir[i, :, multi_window.label_columns_indices.get(
        #     'Temperature', None)]*train_std[0])+train_mean[0])[j])
        y_pred_cnn.append(((predictions_cnn[i, :, multi_window.label_columns_indices.get(
            'Temperature', None)]*train_std[0])+train_mean[0])[j])
        # y_pred_baseline.append(((predictions_baseline[i, :, 0]*train_std[0])+train_mean[0])[j])

plt.plot(x, y_true, '-', lw=3, label='labels')
plt.plot(x, y_pred_multi, ls='--',label='multi linear')
# plt.plot(x, y_pred_lstm, '--', label='lstm')
plt.plot(x, y_pred_dense, ls='--', label='dense')
plt.plot(x, y_pred_cnn, ls='--', label='cnn')
# plt.plot(x, y_pred_baseline, '--', label='repeat baseline')
# plt.plot(x, y_pred_bidir, '--', label='bidir')
plt.legend()
plt.show()


lista = []
posicaoMenor = []
posicaoMaior = []
maior = 0
menor = 0
for c in range(0, 5):
    lista.append(int(input(f'Digite um valor para a posição {c}: ')))
    if c == 0:
        maior = menor = lista[c]
        posicaoMenor.append(c)
        posicaoMaior.append(c)
    else:
        if lista[c] > maior:
            maior = lista[c]
            posicaoMaior.clear()
            posicaoMaior.append(c)
        elif lista[c] == maior:
            posicaoMaior.append(c)
        if lista[c] < menor:
            menor = lista[c]
            posicaoMenor.clear()
            posicaoMenor.append(c)
        elif lista[c] == menor:
            posicaoMenor.append(c)
print(f'Você digitou os valores: {lista}')
if len(posicaoMaior) > 1:
    print(f'O maior valor digitado foi o {maior} e ele se encontra nas posições ', end='')
    for valores in posicaoMaior:
        print(valores, end=' ')
    print()
else:
    print(f'O maior valor digitado foi o {maior} e ele se encontra na posição {posicaoMaior[0]}')
if len(posicaoMenor) > 1:
    print(f'O menor valor digitado foi o {menor} e ele se encontra nas posições ', end='')
    for valores in posicaoMenor:
        print(valores, end=' ')
else:
    print(f'O menor valor digitado foi o {menor} e ele se encontra na posição {posicaoMenor[0]}')


"""
An example demonstrating how to use custom reaction objects.

For benchmark purposes, an ignition test is run to compare simulation times.

Requires: cantera >= 3.0.0
Keywords: kinetics, benchmarking, user-defined model
"""

from timeit import default_timer
import numpy as np
from math import exp
import warnings

import cantera as ct

mech = 'gri30.yaml'
fuel = 'CH4'
gas0 = ct.Solution(mech)

species = gas0.species()
reactions = gas0.reactions()

# construct custom reactions: replace 2nd reaction with equivalent custom reaction
custom_reactions = [r for r in reactions]
custom_reactions[2] = ct.Reaction(
    equation='H2 + O <=> H + OH',
    rate=lambda T: 38.7 * T**2.7 * exp(-3150.15428/T))

gas1 = ct.Solution(thermo='ideal-gas', kinetics='gas',
                   species=species, reactions=custom_reactions)

# construct reactions based on ExtensibleRate: replace 2nd reaction with equivalent
# ExtensibleRate
@ct.extension(name="extensible-Arrhenius")
class ExtensibleArrhenius(ct.ExtensibleRate):
    def after_set_parameters(self, params, units):
        self.A = params["A"]
        self.b = params["b"]
        self.Ea_R = params["Ea_R"]

    def replace_eval(self, T):
        return self.A * T**self.b * exp(-self.Ea_R/T)

extensible_yaml = """
    equation: H2 + O <=> H + OH
    type: extensible-Arrhenius
    A: 38.7
    b: 2.7
    Ea_R: 3150.15428
    """

extensible_reactions = gas0.reactions()
extensible_reactions[2] = ct.Reaction.from_yaml(extensible_yaml, gas0)
gas2 = ct.Solution(thermo="ideal-gas", kinetics="gas",
                   species=species, reactions=extensible_reactions)

# construct test case - simulate ignition

def ignition(gas):
    # set up reactor
    gas.TP = 1000., 5 * ct.one_atm
    gas.set_equivalence_ratio(0.8, fuel, 'O2:1.0, N2:3.773')
    r = ct.IdealGasReactor(gas)
    net = ct.ReactorNet([r])
    net.rtol_sensitivity = 2.e-5

    # time reactor integration
    t1 = default_timer()
    net.advance(.5)
    t2 = default_timer()

    return 1000 * (t2 - t1)

# output results

repeat = 100
print("Average time of {} simulation runs for '{}' "
      "({})".format(repeat, mech, fuel))

sim0 = 0
for i in range(repeat):
    sim0 += ignition(gas0)
sim0 /= repeat
print('- New framework (YAML): '
      '{0:.2f} ms (T_final={1:.2f})'.format(sim0, gas0.T))

sim1 = 0
for i in range(repeat):
    sim1 += ignition(gas1)
sim1 /= repeat
print('- One Custom reaction: '
      '{0:.2f} ms (T_final={1:.2f}) ... '
      '{2:+.2f}%'.format(sim1, gas1.T, 100 * sim1 / sim0 - 100))

sim2 = 0
for i in range(repeat):
    sim2 += ignition(gas2)
sim2 /= repeat
print('- One Extensible reaction: '
      '{0:.2f} ms (T_final={1:.2f}) ... '
      '{2:+.2f}%'.format(sim2, gas2.T, 100 * sim2 / sim0 - 100))


from django.db import models
from .validator import validate_file_extension
from cloudinary_storage.storage import VideoMediaCloudinaryStorage

# Create your models here.

class Minister(models.Model):
    content_type = [
        ('song', 'song'),
        ('message', 'message'),
        ('presentation', 'presentation'),

    ]
    name = models.CharField(max_length=240, null=False, blank=False)
    publish = models.IntegerField(default=0)
    content = models.CharField(
        max_length=15,
        choices=content_type,
        default='presentation', )
    description = models.TextField(null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    picture = models.ImageField(upload_to='images/author/')
    times_played = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.name}'

class Events(models.Model):
    name = models.CharField(max_length=30)
    date_created = models.DateTimeField(auto_now_add=True, null=False, blank=False)
    times_played = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.name}'

class Content(models.Model):
    minister = models.ForeignKey(Minister, on_delete=models.CASCADE, related_name='minister')
    name = models.CharField(max_length=240, null=False, blank=False, unique=True)
    content = models.FileField(upload_to='content/audio', validators=[validate_file_extension],
                               storage=VideoMediaCloudinaryStorage, null=True, blank=True)
    image = models.ImageField(upload_to='content/images')
    # change to set to null for on delete
    tag = models.ForeignKey(Events, on_delete=models.PROTECT)
    description = models.TextField(null=True, blank=True)
    date_created = models.DateTimeField()
    times_played = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        minister__ = Minister.objects.get(id=self.minister.id)
        minister__.publish += 1
        minister__.save()
        return super().save(*args, **kwargs)

    @property
    def event_name(self):
        return f'{self.tag.name}'

    @property
    def minister_name(self):
        return f'{self.minister.name}'

    def __str__(self):
        return f'{self.name}'


""" Demo of parallel queries using ``gsqlite3``. """

from __future__ import print_function
import os
from functools import partial
from random import randint
from timeit import Timer
import gevent
import sqlite3
import gsqlite3

filename = os.path.join(os.path.dirname(__file__), 'demo.sqlite')
select_stmt = "SELECT * FROM example WHERE value >= ? AND value < ?"
num_rows_to_fetch = 100000

def populate(module, num_rows=1000000):
    con = module.connect(filename)
    con.execute("CREATE TABLE IF NOT EXISTS example (value)")
    (count,) = con.execute("SELECT count(1) FROM example").fetchone()
    if count < num_rows:
        num_rows -= count
        values = [(randint(1, 1000000),) for _ in range(num_rows)]
        print("Populating '{}' ...".format(filename))
        insert = "INSERT INTO example (value) VALUES (?)"
        con.executemany(insert, values)
        con.commit()
    con.close()

def query(module, lower, upper):
    con = module.connect(filename)
    cur = con.cursor()
    cur.execute(select_stmt, (lower, upper))
    cur.fetchmany(num_rows_to_fetch)
    con.close()

def query_using_greenlets(module):
    g1 = gevent.spawn(query, module, 10, 100)
    g2 = gevent.spawn(query, module, 100, 1000)
    g3 = gevent.spawn(query, module, 1000, 5000)
    gevent.joinall([g1, g2, g3])

def main():
    modules = [gsqlite3, sqlite3]
    # either module will work here
    populate(modules[0])
    for module in modules:
        time_query_using_module(module)
    os.unlink(filename)
    return None

def time_query_using_module(module):
    # This is largely copied verbatim from the 'timeit' module
    repeat = 3
    number = 10
    verbose = True
    precision = 3
    stmt = partial(query_using_greenlets, module)
    t = Timer(stmt)
    try:
        r = t.repeat(repeat, number)
    except:
        t.print_exc()
        return 1
    best = min(r)
    if verbose:
        print("raw times:", " ".join(["%.*g" % (precision, x) for x in r]))
    print("%s: %d loops," % (module.__name__, number))
    usec = best * 1e6 / number
    if usec < 1000:
        print("best of %d: %.*g usec per loop" % (repeat, precision, usec))
    else:
        msec = usec / 1000
        if msec < 1000:
            print("best of %d: %.*g msec per loop" % (repeat, precision, msec))
        else:
            sec = msec / 1000
            print("best of %d: %.*g sec per loop" % (repeat, precision, sec))

if __name__ == '__main__':
    main()


import requests
from bs4 import BeautifulSoup

url = "https://search.daum.net/search?w=tot&q=2019%EB%85%84%EC%98%81%ED%99%94%EC%88%9C%EC%9C%84&DA=MOR&rtmaxcoll=MOR"
res = requests.get(url)
res.raise_for_status()
soup = BeautifulSoup(res.text, "lxml") # 객체 생성

images = soup.find_all("img", attrs = {"class" : "thumb_img"})

for idx, image in enumerate(images) :
    image_res = requests.get(image["src"])
    image_res.raise_for_status() # 문제가 있을 경우

    with open("movie{}.jpg".format(idx+1), "wb") as f :
        f.write(image_res.content)

    if idx >=4 :  # 상위 5개 파일만 저장
        break

웹크롤링_영화이미지다운.py


import os

from config.celery import app

from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from . import tasks
from .models import File, CompressedFile
from .serializers import FileSerializer

class FileViewSet(viewsets.ModelViewSet):
    serializer_class = FileSerializer
    parser_classes = (MultiPartParser, FormParser)
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return File.objects.filter(creator=self.request.user).order_by("-created_at")

    def perform_create(self, serializer):
        serializer.save(creator=self.request.user)

    @action(detail=False)
    def compress(self, request, *args, **kwargs):
        last_compress = (
            CompressedFile.objects.filter(creator=request.user)
            .order_by("-updated_at")
            .first()
        )

        # Make sure the user only have a compressed file
        if last_compress:
            if last_compress.is_finish:
                return Response(
                    {
                        "message": "Already has a compressed file",
                        "url": last_compress.file.url,
                    },
                    status=status.HTTP_400_BAD_REQUEST,
                )

            return Response(
                {"message": "Processing the file"}, status=status.HTTP_400_BAD_REQUEST
            )

        result = tasks.compress_all_user_files.delay(request.user.id)
        CompressedFile(creator=request.user, task_id=result.id).save()
        return Response({"message": "start processing"}, status=status.HTTP_200_OK)

    @action(detail=False, url_path="compress/check")
    def check_compress(self, request, *args, **kwargs):
        last_compress = (
            CompressedFile.objects.filter(creator=request.user)
            .order_by("-updated_at")
            .first()
        )

        if last_compress:
            result = tasks.compress_all_user_files.AsyncResult(last_compress.task_id)

            if result.status == "SUCCESS":
                last_compress.is_finish = True
                last_compress.file = result.get()
                last_compress.save()
                return Response(
                    {"message": result.status, "url": last_compress.file.url},
                    status=status.HTTP_200_OK,
                )
            elif result.status == "FAILURE":
                last_compress.is_finish = True
                last_compress.save()
                return Response(
                    {"message": result.status},
                    status=status.HTTP_503_SERVICE_UNAVAILABLE,
                )

            return Response({"message": result.status}, status=status.HTTP_200_OK)
        else:
            return Response(
                {"message": "The compressed file doesn't exists."},
                status=status.HTTP_400_BAD_REQUEST,
            )

    @action(detail=False, url_path="compress/force")
    def force_compress(self, request, *args, **kwargs):
        last_compress = (
            CompressedFile.objects.filter(creator=request.user)
            .order_by("-updated_at")
            .first()
        )

        if last_compress:
            # remove the file
            if last_compress.is_finish:
                os.unlink(last_compress.file.path)
            else:
                # stop the process
                app.control.revoke(last_compress.task_id, terminate=True)
            last_compress.delete()

        result = tasks.compress_all_user_files.delay(request.user.id)
        CompressedFile(creator=request.user, task_id=result.id).save()
        return Response({"message": "start processing"}, status=status.HTTP_200_OK)


import os
import rospy
import actionlib
from std_msgs.msg import String
import random
from geometry_msgs.msg import Pose2D
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
from geometry_msgs.msg import Pose2D
from std_msgs.msg import String
from coordinator import *
from multi_run3 import *
import random
import math
from DVRP import *
random.seed(1) # 控制变量

renew_int=60
num_of_new=2
capacity=100

def order_init(coordinator, my_dvrp): # 订单初始化
    vacant=[] # 没有订单的任务点
    for i in list(coordinator.task_list.keys()):
        if coordinator.task_list[i]==0:
            vacant.append(i)
    new=random.sample(vacant,10) # 随机产生10个订单

    for i in new:
        coordinator.task_list[i]=random.randint(20,23) # 随机产生需求量

    my_dvrp.input_demand_and_car_num(coordinator.task_list,3,[],[]) # DVRP
    routes, tasks, robot=my_dvrp.cal_everything() # 得到机器人对应的任务与路径

    for i in range(len(routes)):
        coordinator.renew(routes[i],tasks[i],robot[i]) # 更新任务与路径

def order_generator(): # 产生新订单
    vacant=[]
    for i in list(coordinator.task_list.keys()):
        if coordinator.task_list[i]==0:
            vacant.append(i)
    new=random.sample(vacant,3) # 从没有订单的任务点产生新订单
    for i in new:
        coordinator.task_list[i]=random.randint(10,20) # 随机需求量

if __name__=='__main__':
    rospy.init_node('transportation', anonymous=True)
    my_dvrp=DVRP(16, capacity) # 初始化DVRP
    actionExecuter1 = ActionExec('robot1') #初始化机器人
    actionExecuter2 = ActionExec('robot2')
    actionExecuter3 = ActionExec('robot3')
    coordinator = PatrolCoordinator(availableRobots=['robot1', 'robot2', 'robot3']) # 初始化调度中心
    print('-------------round 0--------------')
    order_init(coordinator, my_dvrp) # 订单初始化

    rospy.sleep(renew_int)
    round=1
    while True: # 每隔一段时间产生新订单
        print(' ')
        print('-------------round '+str(round)+'--------------')
        print('We have finished altogether '+str(coordinator.finished)+' tasks now.')
        order_generator() # 产生新订单
        round+=1
        goal_list=[]
        name=['robot'+str(j+1) for j in range(3)]
        name_list=[]
        for i in name: # 找在做任务的机器人
            if len(coordinator.task[i])>1 and coordinator.task[i][0]!=(0,0):
                goal_list.append(coordinator.task[i][0])
                name_list.append(int(i[-1]))

        my_dvrp.input_demand_and_car_num(coordinator.task_list,3,goal_list,name_list) # DVRP
        routes, tasks, robot=my_dvrp.cal_everything() # 得到任务与路径

        task_num = 0 # 当前剩下多少任务
        for i in range(len(routes)):
            task_num += len(tasks[i]) - 1
            coordinator.renew(routes[i],tasks[i],robot[i]) # 更新任务与路径

        print('There are altogether '+str(task_num)+' tasks to finish now.')
        rospy.sleep(renew_int)


import unittest
import xtuml
import bridgepoint

class TestNavigation(unittest.TestCase):
    '''
    Test suite for xtuml navigate operations
    '''
    def setUp(self):
        self.m = bridgepoint.load_metamodel()

    def tearDown(self):
        del self.m

    def test_navigate_one(self):
        s_dt = self.m.select_any('S_DT',  xtuml.where_eq(Name='void'))
        pe_pe = xtuml.navigate_one(s_dt).PE_PE[8001](lambda inst: True)
        self.assertEqual(s_dt.DT_ID, pe_pe.Element_ID)

    def test_navigate_many(self):
        s_dt = self.m.select_many('S_DT')
        pe_pe = xtuml.navigate_many(s_dt).PE_PE[8001](lambda inst: True)
        self.assertEqual(len(s_dt), len(pe_pe))

    def test_navigate_suptype(self):
        s_dt = self.m.select_any('S_DT', xtuml.where_eq(Name='void'))
        s_cdt = xtuml.navigate_subtype(s_dt, 17)
        self.assertTrue(s_cdt)
        self.assertIsInstance(s_cdt, self.m.find_class('S_CDT'))

    def test_navigate_assoc(self):
        s_sys = self.m.new('S_SYS')
        g_eis = self.m.new('G_EIS')
        s_dt = self.m.select_any('S_DT', xtuml.where_eq(Name='void'))
        pe_pe = xtuml.navigate_one(s_dt).PE_PE[8001]()

        self.assertTrue(xtuml.relate(g_eis, s_sys, 9100))
        self.assertTrue(xtuml.relate(g_eis, pe_pe, 9100))

        self.assertTrue(xtuml.navigate_one(s_sys).G_EIS[9100].PE_PE[9100]())
        self.assertTrue(xtuml.navigate_one(pe_pe).G_EIS[9100].S_SYS[9100]())

        inst = xtuml.navigate_one(pe_pe).S_SYS[9100]()
        self.assertEqual(inst, s_sys)

    def test_navigate_none(self):
        self.assertIsNone(xtuml.navigate_one(None)())
        self.assertIsNone(xtuml.navigate_subtype(None, 0))
        self.assertEqual(len(xtuml.navigate_many(None)()), 0)

    def test_navigate_invalid_handle(self):
        self.assertRaises(xtuml.MetaException, xtuml.navigate_one, 50)

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


import random
import networkx as nx
import matplotlib.pyplot as plt

def simulate_influence_spread(
    graph: nx.Graph, *, initial_nodes: list[str] | str | None = None, steps: int = 500, probability: int = 0.5
) -> list[str]:
    if initial_nodes is None:
        initial_nodes = random.choice(list(graph.nodes()))
    if not isinstance(initial_nodes, list):
        initial_nodes = [initial_nodes]

    inicial_nodes = set(initial_nodes)
    influencing_nodes = set(initial_nodes)
    influenced_nodes = set()

    for _ in range(steps):
        new_influences = set()
        for node in influencing_nodes:
            for neighbor in graph.neighbors(node):
                if neighbor in influenced_nodes:
                    continue
                if random.random() < probability:
                    new_influences.add(neighbor)
        influenced_nodes.update(influencing_nodes)
        influencing_nodes = new_influences

        yield inicial_nodes, influencing_nodes, influenced_nodes

def main() -> None:
    graphs = []
    graphs.append(nx.les_miserables_graph())
    graphs.append(nx.read_adjlist('socfb-Penn94.txt'))
    print('Graphs loaded')

    for i, G in enumerate(graphs):
        for step, (inicial, influencing, influenced) in enumerate(simulate_influence_spread(G, steps=10)):
            plt.figure()
            node_colors = []
            for node in G.nodes():
                if node in influencing:
                    node_colors.append('red')
                elif node in inicial:
                    node_colors.append('orange')
                elif node in influenced:
                    node_colors.append('green')
                else:
                    node_colors.append('blue')
            nx.draw(
                G,
                pos=nx.spring_layout(G, seed=1),
                with_labels=True,
                font_size=5,
                node_color=node_colors,
            )
            plt.savefig(f"visualization_{i}/step_{step}.png")  # Saves the figure to a file
            plt.close()
            #plt.title(f"Step {step}")
            #plt.show()

if __name__ == '__main__':
    main()


# Дано целое число N (>1). Вывести наибольшее из целых чисел К,
# для которых сумма 1 + 2 + ... + К будет меньше или равна N, и саму эту сумму.
N = input("Введите целое число: ")
try:
    N = int(N)
    print("Удачно.")
except ValueError:
    print("Ошибка.")
K = 1
S = 1
while S <= N:
    K += 1
    S += K
    print("K = {0}, S = {1} ".format(K, S))
S -= K
K -= 1
print("K = {0}, S = {1}".format(K, S))


def solution(k):
    def is_odd(x):
        if x % 2 != 0:
            return True
        else:
            return False

    yellow_sum = 0
    red_sum = 0

    for i in range(1, k+1):
        if is_odd(i):
            yellow_sum += (i*i)
        else:
            red_sum += (i*i)

    difference = red_sum - yellow_sum

    return difference


import sqlite3
import json
import time
import datetime
from datetime import date
from datetime import timedelta

class Database:
    def __init__(self):
        pass

    def connectCursor(self):
        conn = sqlite3.connect("sassBot.db")
        cur = conn.cursor()
        return conn, cur

    # Confessions Table Methods
    def createConfessionsTable(self):
        conn,cur = self.connectCursor()
        cur.execute('''CREATE TABLE IF NOT EXISTS confessions
                (
                    confession_id INTEGER PRIMARY KEY,
                    confession TEXT,
                    confession_title TEXT,
                    review_status INTEGER,
                    reviewer_id INTEGER,
                    reviewer_name TEXT,
                    date_added INTEGER,
                    date_reviewed INTEGER
                )
            ''')
        conn.commit()
        cur.close()
        conn.close()

    def addConfession(self, confession:str, title:str) -> None:
        self.createConfessionsTable()
        conn,cur = self.connectCursor()
        rowVals = (confession, title, time.time())
        exeString = f'''INSERT INTO confessions (confession,confession_title, date_added) VALUES (?,?,?)'''
        cur.execute(exeString,rowVals)
        conn.commit()
        cur.close()
        conn.close()

    def getUnreviewedConfession(self):
        self.createConfessionsTable()
        confessionId = 0
        confession = ""
        title = ""
        conn,cur = self.connectCursor()
        exeString = '''SELECT confession_id, confession,confession_title FROM confessions WHERE date_reviewed IS NULL LIMIT 1'''
        cur.execute(exeString)
        values = cur.fetchall()
        if values:
            confessionId = values[0][0]
            confession = values[0][1]
            title = values[0][2]
        cur.close()
        conn.close()
        self.setConfessionDateReviewed(confessionId)
        return confessionId, confession, title

    def setConfessionDateReviewed(self, confessionId):
        self.createConfessionsTable()
        conn, cur = self.connectCursor()
        exeString = f'''UPDATE confessions SET date_reviewed={time.time()} WHERE confession_id={confessionId} '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def reviewConfession(self, confessionId: int, approveDeny: int, reviewerId: int, reviewerName: str):
        self.createConfessionsTable()
        conn, cur = self.connectCursor()
        values = (approveDeny, reviewerId, reviewerName, time.time(), confessionId)
        exeString = f'''UPDATE confessions SET review_status=?, reviewer_id=?, reviewer_name=?, date_reviewed=? WHERE confession_id=? '''
        cur.execute(exeString,values)
        conn.commit()
        cur.close()
        conn.close()

    def getUnfinishedReviews(self):
        self.createConfessionsTable()
        conn, cur = self.connectCursor()
        exeString = f'''SELECT confession_id, date_reviewed FROM confessions WHERE review_status IS NULL AND date_reviewed IS NOT NULL '''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value

    def resetConfessionDateReviewed(self, confessionId):
        self.createConfessionsTable()
        conn, cur = self.connectCursor()
        exeString = f'''UPDATE confessions SET date_reviewed=NULL WHERE confession_id={confessionId} '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def getAllUnreviewed(self):
        self.createConfessionsTable()
        conn,cur = self.connectCursor()
        exeString = '''SELECT confession_id, confession,confession_title FROM confessions WHERE date_reviewed IS NULL'''
        cur.execute(exeString)
        values = cur.fetchall()
        cur.close()
        conn.close()
        return values

    # Platform_Accounts Table Methods
    def getPlatformTempTitle(self,platform, accountName):
        self.checkAddTitleCols()
        title = ""
        titleTime = 0
        conn,cur = self.connectCursor()
        exeString = f'''SELECT temp_title, temp_title_time FROM platform_accounts WHERE platform_name='{platform}' AND account_name='{accountName}' '''
        cur.execute(exeString)
        values = cur.fetchall()
        if values:
            title = values[0][0]
            titleTime = values[0][1]
        cur.close()
        conn.close()
        return title, titleTime

    def getPlatformAccountNames(self,platform:str):
        conn,cur = self.connectCursor()
        names= []
        exeString = f'''SELECT account_name FROM platform_accounts WHERE platform_name='{platform}' '''
        if self.isExists(exeString):
            cur.execute(exeString)
            namesList = cur.fetchall()
            for name in namesList:
                names.append(name[0])
        cur.close()
        conn.close()
        return names

    def doesAccountExist(self,platform, accountName):
        isExistString = f'''SELECT temp_title, temp_title_time FROM platform_accounts WHERE platform_name='{platform}' AND account_name='{accountName}' '''
        accountExist = self.isExists(isExistString)
        return accountExist

    def addTempTitle(self,title: str, platform: str, accountName: str ) -> None:
        self.createPlatformAccountsTable()
        self.checkAddTitleCols()
        conn,cur = self.connectCursor()
        if self.doesAccountExist(platform, accountName):
            exeString = f'''UPDATE platform_accounts SET temp_title='{title}', temp_title_time={time.time()} WHERE platform_name='{platform}' AND account_name='{accountName}' '''
            cur.execute(exeString)
            conn.commit()
            cur.close()
            conn.close()
        else:
            print("given bad account or platform. can't update title")

    def checkAddTitleCols(self):
        isTitleExist = self.isColExist("platform_accounts","temp_title")
        if not isTitleExist:
            conn,cur = self.connectCursor()
            cur.execute('''ALTER TABLE platform_accounts ADD temp_title TEXT ''')
            cur.execute('''ALTER TABLE platform_accounts ADD temp_title_time REAL ''')
            conn.commit()
            cur.close()
            conn.close()

    def createPlatformAccountsTable(self) -> None:
        conn,cur = self.connectCursor()
        cur.execute('''CREATE TABLE IF NOT EXISTS platform_accounts
                (
                    account_name TEXT NOT NULL,
                    platform_name TEXT NOT NULL,
                    last_online_message REAL,
                    last_stream_start_time REAL,
                    last_stream_end_time REAL,
                    temp_title TEXT,
                    temp_title_time REAL,
                    PRIMARY KEY (account_name, platform_name),
                    FOREIGN KEY(platform_name) REFERENCES platforms(platform_name)
                )
            ''')
        conn.commit()
        cur.close()
        conn.close()

    def createNewPlatformAccount(self, accountName:str, platformName:str,lastOnlineMessage = 0, lastStreamStartTime = 0, lastStreamEndTime = 0) -> None:
        self.createPlatformAccountsTable()
        conn,cur = self.connectCursor()
        rowVals =(accountName, platformName, lastOnlineMessage, lastStreamStartTime, lastStreamEndTime)
        cur.execute('INSERT INTO platform_accounts (account_name, platform_name, last_online_message, last_stream_start_time, last_stream_end_time) VALUES (?,?,?,?,?)',rowVals)
        conn.commit()
        cur.close()
        conn.close()

    def getPlatformAccountsRowValues(self, platformName, accountName):
        self.createPlatformAccountsTable()
        conn,cur = self.connectCursor()
        exeString = f'''SELECT last_online_message,last_stream_start_time,last_stream_end_time FROM platform_accounts WHERE platform_name='{platformName}' AND account_name='{accountName}' '''
        if not self.isExists(exeString):
            self.createNewPlatformAccount(accountName, platformName)
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value[0][0],value[0][1],value[0][2]

    def updatePlatformAccountRowCol(self,platformName,accountName,col,newValue):
        self.createPlatformAccountsTable()
        conn,cur = self.connectCursor()
        exeString = f'''UPDATE platform_accounts SET {col}={newValue} WHERE platform_name='{platformName}' AND account_name='{accountName}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    # Platform Table Methods
    def setRerun(self, isRerun, platform):
        self.checkAddRerunCols()
        conn,cur = self.connectCursor()
        tFalse = 1 if isRerun else 0
        exeString = f'''UPDATE platforms SET rerun_playing={tFalse} WHERE platform_name='{platform}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def getRerun(self, platform):
        isRerun = 0
        self.checkAddRerunCols()
        conn, cur = self.connectCursor()
        exeString = f'''SELECT rerun_playing FROM platforms WHERE platform_name='{platform}' '''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        if value[0][0] != None:
            isRerun = value[0][0]
        return isRerun

    def updatePlatformRowCol(self,rowKey,col,newValue):
        conn,cur = self.connectCursor()
        exeString = f'''UPDATE platforms SET {col}={newValue} WHERE platform_name='{rowKey}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def getPlatformsRowCol(self, rowKey, col):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT {col} FROM platforms WHERE platform_name='{rowKey}' '''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value[0][0]

    def getPlatformsRowValues(self, platformName):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT last_online_message,last_stream_start_time,last_stream_end_time FROM platforms WHERE platform_name='{platformName}' '''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        isRerun = self.getRerun(platformName)
        return value[0][0],value[0][1],value[0][2], isRerun

    # Subathon Table Methods
    def startSubathon(self,epochTime):
        conn,cur = self.connectCursor()
        subTrue = 1
        exeString = f'''UPDATE subathon SET subathon={subTrue}, start_time={epochTime}  '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def endSubathon(self,epochTime):
        conn,cur = self.connectCursor()
        subFalse = 0
        exeString = f'''UPDATE subathon SET subathon={subFalse}, end_time={epochTime}  '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def getSubathonStatus(self):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT subathon,start_time,end_time FROM subathon'''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value[0]

    def getSubathonStatusClean(self):
        sub = self.getSubathonStatus()
        subathon = sub[0]
        subStart = sub[1]
        subEnd = sub[2]
        return subathon,subStart,subEnd

    def getSubathonLongest(self):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT longest_subathon FROM subathon'''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value[0][0]

    def getSubathonLongestTime(self):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT longest_subathon,longest_subathon_time FROM subathon'''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value[0][0],value[0][1]

    def setLongestSubathon(self,subathonLength,subathonStartTime):
        conn,cur = self.connectCursor()
        exeString = f'''UPDATE subathon SET longest_subathon={subathonLength},longest_subathon_time={subathonStartTime}  '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    # Stream Table Methods
    def setRerunAnnounce(self, isAnnounce):
        self.checkAddRerunCols()
        conn,cur = self.connectCursor()
        tFalse = 1 if isAnnounce else 0
        exeString = f'''UPDATE stream SET rerun_ping={tFalse}'''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def getRerunAnnounce(self):
        isRerun = 0
        self.checkAddRerunCols()
        conn, cur = self.connectCursor()
        exeString = f'''SELECT rerun_ping FROM stream '''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        if value[0][0] != None:
            isRerun = value[0][0]
        return isRerun

    def getStreamTableValues(self):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT last_online,last_offline,last_stream_length FROM stream'''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value[0][0],value[0][1],value[0][2]

    def setStreamLastOnline(self,lastOnline):
        conn,cur = self.connectCursor()
        exeString = f'''UPDATE stream SET last_online={lastOnline} '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def setStreamLastOffline(self,lastOffline):
        conn,cur = self.connectCursor()
        exeString = f'''UPDATE stream SET last_offline={lastOffline} '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def setStreamLastStreamLength(self,lastStreamLength):
        conn,cur = self.connectCursor()
        exeString = f'''UPDATE stream SET last_stream_length={lastStreamLength} '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def getTwImgStuff(self):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT tw_img_list,tw_img_queue, img_banned_list FROM stream'''
        cur.execute(exeString)
        value = cur.fetchall()
        if value[0][2] is None:
            bannedList = []
        else:
            bannedList = json.loads(value[0][2])
        if value[0][0] is None or value[0][1] is None:
            twImgList = []
            twImgQue =[]
        else:
            twImgList = json.loads(value[0][0])
            twImgQue = json.loads(value[0][1])
        cur.close()
        conn.close()
        return twImgList, twImgQue, bannedList

    def setBannedList(self, bannedList):
        conn,cur = self.connectCursor()
        bannedListDump = json.dumps(bannedList)
        exeString = f'''UPDATE stream SET img_banned_list='{bannedListDump}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def setTwImgList(self,twImgList):
        conn,cur = self.connectCursor()
        twImgListDump = json.dumps(twImgList)
        exeString = f'''UPDATE stream SET tw_img_list='{twImgListDump}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def setTwImgQueue(self,twImgQueue):
        conn,cur = self.connectCursor()
        twImgQueueDump = json.dumps(twImgQueue)
        exeString = f'''UPDATE stream SET tw_img_queue='{twImgQueueDump}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def setImgPin(self, epochTime: int, url: str) -> None:
        conn,cur = self.connectCursor()
        exeString = f'''UPDATE stream SET img_pin={epochTime}, img_pin_url='{url}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def getImgPin(self):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT img_pin, img_pin_url FROM stream '''
        cur.execute(exeString)
        value = cur.fetchall()
        cur.close()
        conn.close()
        return value[0][0],value[0][1]

    def getPing(self):
        conn,cur = self.connectCursor()
        exeString = f'''SELECT everyone_ping FROM stream '''
        cur.execute(exeString)
        value = cur.fetchall()
        ping = False
        if value[0][0]:
            ping = True
        cur.close()
        conn.close()
        return ping

    def setPing(self, ifPing: bool) -> None:
        conn,cur = self.connectCursor()
        ping = 1 if ifPing else 0
        exeString = f'''UPDATE stream SET everyone_ping={ping} '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    # User_Presence_Stats Table Methods
    def isPresDateExists(self, dataDate: date) -> bool:
        exeString = f'''SELECT user_presences FROM user_presence_stats WHERE date='{dataDate}' '''
        isExists = self.isExists(exeString)
        return isExists

    def getPresenceDay(self,dataDate: date) -> dict:
        conn,cur = self.connectCursor()
        presenceDict = {}
        exeString = f'''SELECT user_presences FROM user_presence_stats WHERE date='{dataDate}' '''
        if self.isExists(exeString):
            cur.execute(exeString)
            value = cur.fetchall()
            presenceDict = json.loads(value[0][0])
        elif str(dataDate) == str(date.today()):
            for i in range(144):
                hour = int(i/6)
                minute = i%6
                minute = minute * 10
                hourMinute = f'{hour}:{minute}'
                presenceDict[hourMinute] = 0
            self.setNewPresenceDay(date.today(),datetime.datetime.now().weekday(),presenceDict)
        cur.close()
        conn.close()
        return presenceDict

    def setPresenceDay(self, dataDate: date, presenceDict: dict) -> None:
        conn,cur = self.connectCursor()
        presenceDictDump = json.dumps(presenceDict)
        exeString = f'''UPDATE user_presence_stats SET user_presences='{presenceDictDump}' WHERE date = '{dataDate}' '''
        cur.execute(exeString)
        conn.commit()
        cur.close()
        conn.close()

    def setNewPresenceDay(self, dataDate: date, dataWeekDay: int, presenceDict: dict) -> None:
        conn,cur = self.connectCursor()
        presenceDictDump = json.dumps(presenceDict)
        rowVals =(dataDate, dataWeekDay, presenceDictDump)
        cur.execute('INSERT INTO user_presence_stats (date, week_day, user_presences) VALUES (?,?,?)',rowVals)
        conn.commit()
        cur.close()
        conn.close()

    def getLastWeeksDayPresenceData(self, dayDate: date) -> dict:
        conn,cur = self.connectCursor()
        previousWeekDayDate = dayDate - timedelta(days = 7)
        value = 0
        lastWeekPres = self.getPresenceDay(previousWeekDayDate)
        if lastWeekPres:
            value = lastWeekPres
        cur.close()
        conn.close()
        return value

    # Helper Functions
    def isExists(self,query: str) -> bool:
        conn,cur = self.connectCursor()
        exists = f"SELECT EXISTS({query})"
        isExists = False
        try:
            cur.execute(exists)
            value = cur.fetchall()
            isExists = value[0][0]
        except sqlite3.OperationalError:
            print("error when checking if col exists, perhaps no data yet")
        cur.close()
        conn.close()
        return isExists

    def isColExist(self,tableName, colName):
        isExist = False
        conn,cur = self.connectCursor()
        cur.execute(f'PRAGMA table_info({tableName})')
        retCols = cur.fetchall()
        for col in retCols:
            if colName in col:
                isExist = True
        cur.close()
        conn.close()
        return isExist

    def checkAddRerunCols(self):
        isTitleExist = self.isColExist("stream","rerun_ping")
        if not isTitleExist:
            conn,cur = self.connectCursor()
            cur.execute('''ALTER TABLE stream ADD rerun_ping INTEGER ''')
            cur.execute('''ALTER TABLE platforms ADD rerun_playing INTEGER ''')
            conn.commit()
            cur.close()
            conn.close()


#!/usr/bin/env python
import numpy as np
import sys
import cv2
import os
import pytesseract
from gtts import gTTS
from PIL import Image
from resizeimage import resizeimage
import time

cap = cv2.VideoCapture(-1)
sample=0;
error=0
#time.sleep(2)
new_height=0
while(cap.isOpened()):
#while(True):
    ret, img = cap.read()
    if ret:
        error=1
        gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        #adapt1 = cv2.adaptiveThreshold(gray,130,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY_INV,153,40)
        cv2.imshow('frame',img)
        #print(adapt1)
        cv2.imwrite('frame.png',img)
        cv2.waitKey(1)
        sample=sample+1
    if (sample == 2):
         sample =0;
        # resized_image=cv2.resize(img,(441,303))
         cv2.imwrite('fra12.png',img)
         #is_valid =resizeimage.resize_cover.validate(img,[200,100])
         #print(is_valid)
         #if is_valid:
         #    cover=resizeimage.resize_cover(img,[200,100])
         #    cover.save('fr.jpeg',image.format)
         break

cap.release()
if error ==0:
    print('Camera is interrupted\nPlease execute the script again')
    cv2.destroyAllWindows()
if error ==1:
   print('image is caputured')
im = Image.open("frame.png")

#text = pytesseract.image_to_boxes(im,lang = 'eng',config = '-psm 7',output_type='Output.STRING' )
#text = pytesseract.image_to_boxes(im,lang = 'eng',config = '-psm 7',nice=0,output_type='string' )
#temp = text.encode('utf-8')
#type(text)
##############espeak#####################
#lag = 'en'
#myobj = gTTS(text=text,lang=lag, slow =False)
#myobj.save("test.mp3")
#os.system("mpg321 test.mp3")
###########################################
#print(text)
cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
"""
Created on Sat Dec 12 17:10:15 2020

@author: Mitchell Bink, Max Kleinman en Sandro Offermans"""

from flask import Flask, render_template, request, Markup
import pandas as pd
import numpy as np
from scipy.integrate import odeint
from scipy import interpolate
import markdown2
import dateutil
import datetime
from os import environ

app = Flask(__name__)

def getValuesCountry(countryName):
    print(countryName)
    numberOfRow = 283
    data = pd.read_excel('data_countries_all_with_relatives_xls.xls', sheet_name = None)
    RegularData = pd.read_excel('regular_data_countries_xls.xls')
    listCumuCases = list(data[countryName]["Cumulative cases"].iloc[0:numberOfRow])
    listCumuDeaths = list(data[countryName]["Cumulative deaths"].iloc[0:numberOfRow])
    populationNumber = int(RegularData.loc[RegularData["ISO-3166"] == countryName]["Total population"])
    # densityNumber = int(RegularData.loc[RegularData["ISO-3166"] == countryName]["population density"])
    CasesPerTenThousand = list([round(number / (populationNumber / 10000),2) for number in listCumuCases])
    DeathsPerTenThousand = list([round(number / (populationNumber / 10000),2) for number in listCumuDeaths])

    listNewCases = list(data[countryName]["New Cases"].iloc[0:numberOfRow])
    listChangeCases = list(data[countryName]["Change of Cases"].iloc[0:numberOfRow])
    listNewDeaths = list(data[countryName]["New Deaths"].iloc[0:numberOfRow])
    listChangeDeaths = list(data[countryName]["Change of Deaths"].iloc[0:numberOfRow])
    listStringency = list(data[countryName]["Stringency"].iloc[0:numberOfRow])

    deathratio = []
    for i in range(len(listCumuCases)):
        if listCumuCases[i] != 0:
            dratio = (listCumuDeaths[i] /listCumuCases[i] * 100 )
            dratio = round(dratio, 2)
        else:
            dratio = 0
        deathratio.append(dratio)
    return ([list(listCumuCases),
             list(listCumuDeaths),
             list(CasesPerTenThousand),
             list(DeathsPerTenThousand),
             list(deathratio),
             list(listNewCases),
             list(listChangeCases),
             list(listNewDeaths),
             list(listChangeDeaths),
             list(listStringency)])

numbersNL = getValuesCountry('NLD')
numbersBE = getValuesCountry('BEL')
numbersALB = getValuesCountry('ALB')
numbersAND = getValuesCountry('AND')
numbersBLR = getValuesCountry('BLR')
numbersAUT = getValuesCountry('AUT')
numbersBIH  = getValuesCountry('BIH')
numbersBGR  = getValuesCountry('BGR')
numbersHRV  = getValuesCountry('HRV')
numbersGBR  = getValuesCountry('GBR')
numbersUKR  = getValuesCountry('UKR')
numbersCHE  = getValuesCountry('CHE')
numbersSWE  = getValuesCountry('SWE')
numbersESP  = getValuesCountry('ESP')
numbersSVN  = getValuesCountry('SVN')
numbersSVK  = getValuesCountry('SVK')
numbersSRB  = getValuesCountry('SRB')
numbersRUS  = getValuesCountry('RUS')
numbersROU  = getValuesCountry('ROU')
numbersPRT  = getValuesCountry('PRT')
numbersPOL  = getValuesCountry('POL')
numbersNOR  = getValuesCountry('NOR')
numbersMDA  = getValuesCountry('MDA')
numbersLUX  = getValuesCountry('LUX')
numbersLTU  = getValuesCountry('LTU')
numbersLVA  = getValuesCountry('LVA')
numbersITA  = getValuesCountry('ITA')
numbersIRL  = getValuesCountry('IRL')
numbersISL  = getValuesCountry('ISL')
numbersHUN  = getValuesCountry('HUN')
numbersGRC  = getValuesCountry('GRC')
numbersDEU  = getValuesCountry('DEU')
numbersFRA  = getValuesCountry('FRA')
numbersFIN  = getValuesCountry('FIN')
numbersEST  = getValuesCountry('EST')
numbersDNK  = getValuesCountry('DNK')
numbersCZE  = getValuesCountry('CZE')

@app.route('/', methods = ['GET'])
def index():
     return render_template(
         'index.html',
         meta_title = 'Dashboard covid-19 - Zuyd Hogeschool',
         meta_description = 'Compare the numbers of the countries',
         rel_canonical = '/',
         icon = 'https://dataintelligence.zuyd.nl/wp-content/uploads/2020/09/cropped-Penrose-driehoek-192x192.png',
         numbersNL = numbersNL,
         numbersBE = numbersBE,
         numbersALB = numbersALB,
         numbersAND = numbersAND,
         numbersBLR = numbersBLR,
         numbersAUT = numbersAUT,
         numbersBIH = numbersBIH,
         numbersBGR = numbersBGR,
         numbersHRV = numbersHRV,
         numbersGBR = numbersGBR,
         numbersUKR = numbersUKR,
         numbersCHE = numbersCHE,
         numbersSWE = numbersSWE,
         numbersESP = numbersESP,
         numbersSVN = numbersSVN,
         numbersSVK = numbersSVK,
         numbersSRB = numbersSRB,
         numbersRUS = numbersRUS,
         numbersROU = numbersROU,
         numbersPRT = numbersPRT,
         numbersPOL = numbersPOL,
         numbersNOR = numbersNOR,
         numbersMDA = numbersMDA,
         numbersLUX = numbersLUX,
         numbersLTU = numbersLTU,
         numbersLVA = numbersLVA,
         numbersITA = numbersITA,
         numbersIRL = numbersIRL,
         numbersISL = numbersISL,
         numbersHUN = numbersHUN,
         numbersGRC = numbersGRC,
         numbersDEU = numbersDEU,
         numbersFRA = numbersFRA,
         numbersFIN = numbersFIN,
         numbersEST = numbersEST,
         numbersDNK = numbersDNK,
         numbersCZE = numbersCZE)

@app.route('/project/doelstelling-project', methods = ['GET'])
def aanleiding():
    return render_template('doelstelling-project.html',
           meta_title = 'Doelstelling - Zuyd Hogeschool',
           meta_description = 'Doelstelling van het project',
           rel_canonical = '/project/doelstelling-project')

@app.route('/onderzoek/ontwikkeling-in-nederland', methods = ['GET'])
def Ontwikkeling_in_Nederland():
    marked_text = ''
    with open("README.md", encoding="utf8") as f:
        marked_text = markdown2.markdown(f.read(),extras=['fenced-code-blocks'])
    return render_template('ontwikkeling-in-nederland.html',
                           meta_title = "Ontwikkeling in Nederland",
                           meta_description = "Hoe heeft covid-19 zich ontwikkeld in Nederland ten opzichte van andere Europese landen?",
                           rel_canonical = "/onderzoek/ontwikkeling-in-nederland", md=Markup(marked_text))

@app.route('/project/lectoraat-data-intelligence', methods = ['GET'])
def lectoraat():
    return render_template('lectoraat.html',
           meta_title = 'Lectoraat Data Intelligence - Zuyd Hogeschool',
           meta_description = 'Algemene informatie over het Lectoraat Data Intelligence',
           rel_canonical = '/project/lectoraat-data-intelligence')

@app.route('/project/achtergrond-project', methods = ['GET'])
def opzet():
    return render_template('achtergrond-project.html',
           meta_title = 'Achtergrond - Zuyd Hogeschool',
           meta_description = 'De achtergrond over het project',
           rel_canonical = '/project/achtergrond-project')

@app.route('/overig/contact', methods = ['GET'])
def referenties():
    return render_template('contact.html',
           meta_title = 'Contact - Zuyd Hogeschool',
           meta_description = 'Contacteer het Lectoraat Data Intelligence',
           rel_canonical = '/overig/contact')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

def deriv(y, t, r0_y_interpolated, gamma, sigma, N, p_I_to_C, p_C_to_D, Beds):
    S, E, I, C, R, D = y

    def betaa(t):
        return I / (I + C) * (12 * p_I_to_C + 1/gamma * (1 - p_I_to_C)) + C / (I + C) * (
            min(Beds(t), C) / (min(Beds(t), C) + max(0, C-Beds(t))) * (p_C_to_D * 7.5 + (1 - p_C_to_D) * 6.5) +
            max(0, C-Beds(t)) / (min(Beds(t), C) + max(0, C-Beds(t))) * 1 * 1
        )

    def beta(t):
        try:
            return r0_y_interpolated[int(t)] / betaa(t) if not np.isnan(betaa(t)) else 0
        except:
            return r0_y_interpolated[-1] / betaa(t)

    dSdt = -beta(t) * I * S / N
    dEdt = beta(t) * I * S / N - sigma * E
    dIdt = sigma * E - 1/12.0 * p_I_to_C * I - gamma * (1 - p_I_to_C) * I
    dCdt = 1/12.0 * p_I_to_C * I - 1/7.5 * p_C_to_D * \
        min(Beds(t), C) - max(0, C-Beds(t)) - \
        (1 - p_C_to_D) * 1/6.5 * min(Beds(t), C)
    dRdt = gamma * (1 - p_I_to_C) * I + (1 - p_C_to_D) * \
        1/6.5 * min(Beds(t), C)
    dDdt = 1/7.5 * p_C_to_D * min(Beds(t), C) + max(0, C-Beds(t))
    return dSdt, dEdt, dIdt, dCdt, dRdt, dDdt

gamma = 1.0/9.0
sigma = 1.0/3.0

def logistic_R_0(t, R_0_start, k, x0, R_0_end):
    return (R_0_start-R_0_end) / (1 + np.exp(-k*(-t+x0))) + R_0_end

def Model(initial_cases, initial_date, N, beds_per_100k, R_0_start, k, x0, R_0_end, p_I_to_C, p_C_to_D, s, end_date, total_days, r0_y_interpolated=None):
    days = total_days
    def beta(t):
        return logistic_R_0(t, R_0_start, k, x0, R_0_end) * gamma

    def Beds(t):
        beds_0 = beds_per_100k / 100_000 * N
        return beds_0 + s*beds_0*t  # 0.003

    diff = int((np.datetime64("2020-01-01") - np.datetime64(initial_date)) / np.timedelta64(1, "D"))
    if diff > 0:
        r0_y_interpolated = [r0_y_interpolated[0] for _ in range(diff-1)] + r0_y_interpolated
    elif diff < 0:
        r0_y_interpolated = r0_y_interpolated[(-diff):]

    last_date = np.datetime64(initial_date) + np.timedelta64(days-1, "D")
    missing_days_r0 = int((last_date - np.datetime64(end_date)) / np.timedelta64(1, "D"))
    r0_y_interpolated += [r0_y_interpolated[-1] for _ in range(missing_days_r0+1)]

    y0 = N-initial_cases, initial_cases, 0.0, 0.0, 0.0, 0.0
    t = np.linspace(0, days, days)
    ret = odeint(deriv, y0, t, args=(r0_y_interpolated,
                                        gamma, sigma, N, p_I_to_C, p_C_to_D, Beds))
    S, E, I, C, R, D = ret.T
    R_0_over_time = r0_y_interpolated
    total_CFR = [0] + [100 * D[i] / sum(sigma*E[:i]) if sum(
        sigma*E[:i]) > 0 else 0 for i in range(1, len(t))]
    daily_CFR = [0] + [100 * ((D[i]-D[i-1]) / ((R[i]-R[i-1]) + (D[i]-D[i-1]))) if max(
        (R[i]-R[i-1]), (D[i]-D[i-1])) > 10 else 0 for i in range(1, len(t))]

    dates = []
    ax = pd.DataFrame(index=pd.date_range(start=(initial_date), periods=days))

    for item in ax.index:
        item = str(item)
        item = item.replace(' 00:00:00','').replace('-',', ')
        dates.append(item)

    return dates, list([round(s,3) for s in S]), list([round(e,3) for e in E]), list([round(i,3) for i in I]), list([round(c,3) for c in C]), list([round(r,3) for r in R]), list([round(d,3) for d in D]), R_0_over_time, list([round(total_cfr,3) for total_cfr in total_CFR]), list([round(daily_cfr,3) for daily_cfr in daily_CFR]), [Beds(i) for i in range(len(t))], end_date, total_days

def update_graph(initial_cases, initial_date, population, icu_beds, p_I_to_C, p_C_to_D, r0_data, r0_columns, range_x, end_date, total_days):

    last_initial_date, last_population, last_icu_beds, last_p_I_to_C, last_p_C_to_D = "2020-01-15", 1_000_000, 5.0, 5.0, 50.0
    if not (initial_date and population and icu_beds and p_I_to_C and p_C_to_D):
        initial_date, population, icu_beds, p_I_to_C, p_C_to_D = last_initial_date, last_population, last_icu_beds, last_p_I_to_C, last_p_C_to_D

    r0_data_y = [datapoint["R value"] if ((not np.isnan(datapoint["R value"])) and (datapoint["R value"] >= 0)) else 0 for datapoint in r0_data]
    f = interpolate.interp1d(range_x, r0_data_y, kind='linear')
    r0_x_dates = pd.date_range(start=np.datetime64(initial_date), end=np.datetime64(end_date), freq="D")
    r0_y_interpolated = f(np.linspace(0, len(range_x)-1, num=len(r0_x_dates))).tolist()

    dates, S, E, I, C, R, D, R_0_over_time, total_CFR, daily_CFR, B, date_end, days_total = Model(initial_cases, initial_date, population, icu_beds, 3.0, 0.01, 50, 2.3, float(p_I_to_C)/100, float(p_C_to_D)/100, 0.001,  end_date, total_days, r0_y_interpolated)

    return  (dates, S, E, I, C, R, D, R_0_over_time, total_CFR, daily_CFR, B, list([0] + [round(D[i]-D[i-1],3) for i in range(1, len(dates))]), list([0] + [max(0, round(C[i-1]-B[i-1],3)) for i in range(1, len(dates))]))

@app.route('/onderzoek/epidemic-calculator', methods =['POST','GET'])
def calc():
    if request.method == 'POST':
        form_population_range = request.form.get('population_range')
        form_ICU_beds_range = request.form.get('ICU_beds_range')
        form_Initial_cases_range = request.form.get('Initial_cases_range')
        form_p_symptoms_range = request.form.get('p_symptoms_range')
        form_p_dying_range = request.form.get('p_dying_range')
        form_start_date = request.form.get('start_date_picker')
        form_months = request.form.get('countofMonths')
        form_end_date = request.form.get('end_date_picker')
        form_days = request.form.get('valueOfDays')

        if (type(form_population_range) == type(None)):
            form_population_range = 17800000
        if (type(form_ICU_beds_range) == type(None)):
            form_ICU_beds_range = 10
        if (type(form_Initial_cases_range) == type(None)):
            form_Initial_cases_range = 1
        if (type(form_p_symptoms_range) == type(None)):
            form_p_symptoms_range = 5.0
        if (type(form_p_dying_range) == type(None)):
            form_p_dying_range = 5.0
        if (type(form_start_date) == type(None)):
            form_start_date = "2020-01-01"
        if (type(form_end_date) == type(None)):
            form_end_date = "2020-09-01"
        if (type(form_months) == type(None)):
            form_months = 9
        else:
            form_months = int(form_months)

        listOfRdata = []
        listOfRcolumns = []
        list_r_values = []
        a_month = dateutil.relativedelta.relativedelta(months=int(1))
        a_date = datetime.datetime.strptime(form_start_date, "%Y-%m-%d")
        for vals in range(form_months):
            tem_date = str(a_date)
            temp_r = 'r_value_' + str(vals)
            r_value = request.form.get(temp_r)
            listOfRdata.append({"Date": str(tem_date[0:10]), "R value": float(r_value)})
            listOfRcolumns.append({"Date": str(tem_date[0:10]), "R value": float(r_value)})
            list_r_values.append(r_value)
            a_date += a_month

        def getnums(s, e,i):
           return list(range(s, e,i))

        # Driver Code
        start, end, intval = 0, form_months,1
        x_range = getnums(start, end,intval)

        ax = update_graph(int(form_Initial_cases_range), str(form_start_date), int(form_population_range), int(form_ICU_beds_range), float(form_p_symptoms_range), float(form_p_dying_range), listOfRdata, listOfRcolumns, x_range, form_end_date, int(form_days))
        return render_template("epidemic-calculator.html",
               results = list(ax),
               default_values = [str(form_start_date), int(form_population_range), int(form_Initial_cases_range), int(form_ICU_beds_range), float(form_p_symptoms_range), float(form_p_dying_range), str(form_end_date), int(form_days), list_r_values],

        meta_title = 'Epidemic calculator - Zuyd Hogeschool',
        meta_description = 'Epidemic calculator',
        rel_canonical = '/onderzoek/epidemic-calculator')

    if request.method == 'GET':
        def getnums(s, e,i):
           return list(range(s, e,i))

        # Driver Code
        start, end, intval = 0, 9,1
        x_range = getnums(start, end,intval)
        ax = update_graph(1,"2020-01-01",17700000,10,5.0,5.0,[ {"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-02-01", "R value" : 2.9},{"Date" : "2020-03-01", "R value" : 2.5},{"Date" : "2020-04-01", "R value" : 0.8},{"Date" : "2020-05-01", "R value" : 1.1},{"Date" : "2020-06-01", "R value" : 2},{"Date" : "2020-07-01", "R value" : 2.1},{"Date" : "2020-08-01", "R value" : 2.2},{"Date" : "2020-09-01", "R value" : 2.3}],    [ {"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2},{"Date" : "2020-01-01", "R value" : 3.2}     ],x_range, "2020-09-01", 360)
        return render_template("epidemic-calculator.html",
               results = list(ax),
               default_values = ["2020-01-01", 17800000, 1, 10, 5.0, 5.0, "2020-09-01", 360, [3.2, 2.9,2.5,0.8,1.1,2,2.1,2.2,2.3]],
           meta_title = 'Epidemic calculator - Zuyd Hogeschool',
           meta_description = 'Epidemic calculator',
           rel_canonical = '/onderzoek/epidemic-calculator')

if __name__ == "__main__":
    HOST = environ.get('SERVER_HOST', 'localhost')
    try:
        PORT = int(environ.get('SERVER_PORT', '5555'))
    except ValueError:
        PORT = 5000
    app.run(HOST, PORT)


import tkinter as tk
from tkinter import messagebox
from pprint import pprint

import colors as c
import gameplay_logic as gp

class MyApp:
    """ Tkinter GUI object.

    Attributes:
        root - root of the app
        board_base - Matrix with integers values for logic/math operations.
        board_GUI - Matrix which holds as an element dict with Label and Frame tkinter objects to create GUI.

        score - An integer count for current gained score.

    """
    def __init__(self, root):
        """Inits MyApp with """
        self.root = root
        n = 4
        self.board_base = [[0 for i in range(n)] for j in range(n)]
        self.board_GUI = []

        self.score = tk.IntVar()
        self.make_score()
        self.make_board()

        gp.start_game(self.board_base)
        self.update_GUI()
        self.bind_movement()

    def make_score(self):
        """Display Score part of the GUI.

        Attributes:
            score_frame - Tkinter Frame object, sets placement of the score on the app view.
            score_label - Tkinter Label object displays current score value.

        """
        self.score_frame = tk.Frame(self.root)
        self.score_frame.place(relx=0.5, y=45, anchor="center")
        tk.Label(self.score_frame, text="Score", font=c.SCORE_FONT).grid(row=0)
        self.score_label = tk.Label(self.score_frame, text=str(0), font=c.SCORE_LABEL_FONT)
        self.score_label.grid(row=1)

    def make_board(self):
        """Display empty board part of the GUI and creates board_GUI.

        Attributes:
            grid_frame - Tkinter Frame object, sets placement of the board on the app view.
            cell_frame - Tkinter Frame object, sets placement of the cell on the board view.
            cell_number - Tkinter Label object, styles and displays number of the cell.
        """
        self.grid_frame = tk.Frame(self.root, bg=c.GRID_COLOR)
        self.grid_frame.grid(pady=(100, 0))
        for i in range(4):
            row = []
            for j in range(4):
                cell_frame = tk.Frame(self.grid_frame, bg=c.EMPTY_CELL_COLOR, width=140, height=140)
                cell_frame.grid(row=i, column=j, padx=5, pady=5)

                cell_number = tk.Label(self.grid_frame, bg=c.EMPTY_CELL_COLOR, anchor="center")
                cell_number.grid(row=i, column=j)

                cell_data = {"frame": cell_frame, "number": cell_number}
                row.append(cell_data)
            self.board_GUI.append(row)

    def update_GUI(self):
        """Updates GUI by actual board_base and score values."""
        numbers = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
        for i, row in enumerate(self.board_base):
            for j, val in enumerate(row):
                if val in numbers:
                    self.board_GUI[i][j]['frame'].config(bg=c.CELL_COLORS[val])
                    self.board_GUI[i][j]['number'].config(bg=c.CELL_COLORS[val], text=str(val), font=c.CELL_NUMBER_FONTS[val])
                else:
                    self.board_GUI[i][j]['frame'].config(bg=c.EMPTY_CELL_COLOR)
                    self.board_GUI[i][j]['number'].config(bg=c.EMPTY_CELL_COLOR, text="")
        self.score_label.config(text=self.score.get())

    def bind_movement(self):
        """Bind WSAD and ARROWS buttons for movements of the board."""
        self.root.bind("<Up>", self.movement_button_clicked)
        self.root.bind("<Down>", self.movement_button_clicked)
        self.root.bind("<Left>", self.movement_button_clicked)
        self.root.bind("<Right>", self.movement_button_clicked)
        self.root.bind("<w>", self.movement_button_clicked)
        self.root.bind("<s>", self.movement_button_clicked)
        self.root.bind("<a>", self.movement_button_clicked)
        self.root.bind("<d>", self.movement_button_clicked)

    def movement_button_clicked(self, evt):
        """Pulls out keyboard button name and uses it as a direction to perform board movement.

        Arguments:
            evt - Tkinter event raised after clicking binned keyboard button.
            keyboard_button - An string name of the keyboard button.
        """
        keyboard_button = evt.keysym
        self.move_board_elements(keyboard_button)

    def move_board_elements(self, direction):
        """Starts movement math/logic of the matrix in the given direction when performed updates score and board_base.

        At start the function checks if move in any direction is possible if
        not then game over occurs. The function sets mechanic that only after
        moving elements new elements can be spawned.

        Arguments:
            direction - An string name of the board movement direction.
            new_board_base - Matrix with integers values with its elements moved to the given direction.
            gained_score - An integer count of the new points scored.
        """
        to = {
            "Left": gp.move_elements_left(self.board_base),
            "a": gp.move_elements_left(self.board_base),
            "Right": gp.move_elements_right(self.board_base),
            "d": gp.move_elements_right(self.board_base),

            "Up": gp.move_elements_up(self.board_base),
            "w": gp.move_elements_up(self.board_base),
            "Down": gp.move_elements_down(self.board_base),
            "s": gp.move_elements_down(self.board_base),
        }

        if gp.game_over(self.board_base) == "END":
            messagebox.showinfo("Game Over", f"Yous score: {self.score.get()}")

        if self.board_base == to[direction][0]:
            return

        new_board_base, gained_score = to[direction]
        self.board_base = new_board_base
        self.board_base = gp.add_element(self.board_base)
        self.score.set(self.score.get() + gained_score)
        self.update_GUI()

    def __repr__(self):
        return f"{self.__class__.__name__}({self.board_base})"