"""
Minesweeper problem

Read in stars and dots for mines and non-mines
Output mines and adjacent count
"""

import file_reader as fr
import file_writer as fw

class Problem2:

    def __init__(self, game_board):
        self.game_board = game_board
        self.rows = len(self.game_board)
        self.cols = len(self.game_board[0])-1
        self.top_pad = [0 for i in range(self.cols)]
        self.bottom_pad = [0 for i in range(self.cols)]
        self.game_space = [[] for i in range(self.rows)]
        self.output_data = [[] for i in range(self.rows)]
        self.return_string = ""

    #calculate adjacent count
    def surrouding_update(self, list_location, row, col):
        list_location[row-1][col-1] += 1
        list_location[row][col-1] += 1
        list_location[row+1][col-1] += 1
        list_location[row-1][col] += 1
        list_location[row+1][col] += 1
        list_location[row-1][col+1] += 1
        list_location[row][col+1] += 1
        list_location[row+1][col+1] += 1

    def process_gameboard(self, input_game):

        #convert strings to ints, use 88 as the sentinal for *
        for index, row in enumerate(input_game):
            for char in row:
                if char == "*":
                    self.game_space[index].append(88)
                elif char == ".":
                    self.game_space[index].append(0)
                else:
                    None

        #add padding for calculation
        self.game_space.insert(0,self.top_pad)
        self.game_space.append(self.bottom_pad)

        for k in range(len(self.game_space)):
            self.game_space[k].insert(0,0)
            self.game_space[k].insert(self.cols+2,0)

        #process the adjacent values
        for index, num_row in enumerate(self.game_space):
            for index2, num_val in enumerate(num_row):
                if num_val == 88:
                    self.surrouding_update(self.game_space, index, index2)

        #remove pads
        del self.game_space[0]
        del self.game_space[-1]
        for index, row in enumerate(self.game_space):
            del row[0]
            del row[-1]

        #loop through game space again to process into a string for file writing
        for index, num_row in enumerate(self.game_space):
            for index2, num_val in enumerate(num_row):
                if num_val == 88:
                    self.output_data[index].append("*")
                elif num_val == 0:
                    self.output_data[index].append("0")
                else:
                    self.output_data[index].append(str(num_val))

        for num_row in self.output_data:
            self.return_string += " ".join(num_row)
            self.return_string += "\n"

        return self.return_string

def execute_main():
    input_file = fr.FileReader("inputFile.txt")
    game_input = input_file.file_read_all_str_list()

    exe_problem2 = Problem2(game_input)
    answer = exe_problem2.process_gameboard(game_input)
    print(answer)
    output_file = fw.FileWriter("PyProblem2-Output.txt")
    output_file._file_write_all_str(answer)

if __name__ == "__main__":
    execute_main()


"""
Module with functions for interfacing with the frictionless framework.
"""

# Import Python standard libraries
from pathlib import Path
from typing import *
import logging

# Import 3rd-party libraries
import frictionless

def describe_resource(
    filename: Union[Path, str], validate=True
) -> frictionless.Resource:
    """
    Obtain the frictionless description of a resource (i.e., single table).

    Note that the function will by default also perform pre-resource
    validation, which can be disabled by setting the `validate` parameter.
    The validation will stop execution and show the error report if the
    resource is not valid.

    Parameters
    ----------
    filename : Union[Path,str]
        The path to the resource to describe.
    validate : bool, optional
        Whether to perform pre-resource validation, by default True.
    """

    if validate:
        # Validate the resource
        report = frictionless.validate(filename)
        if not report["valid"]:
            logging.error(report.to_summary())
            raise ValueError(
                "Resource is not valid, please see validation report above."
            )

    resource = frictionless.describe(filename)

    return resource


import os.path
os.chdir("C:\\Users\\slelenia\\Desktop\\vitWork")

def main():
    file = input("->" )
    while not os.path.isfile(file):
        print("invalid file name")
        a = os.listdir()
        print("the files in cwd are:",a)
        file = input("->" )

    lista = counter(file)
    return print(lista)

def counter(file):
    car ="abcdefghijklmnopqrstuvxywzABCDEFRGIJKLMNOPQRSTUVXYWZòàèéùì"
    caratteri = 0
    parole = 0
    righe = 0
    file=open(file,"r")

    for line in file:
        riga = line.split()
        parole += len(riga)
        righe += 1
        for i in riga:
            for j in i:
                if j in car: caratteri += 1

    lista = [caratteri,parole,righe]
    return lista

main()

file conta caratteri parole e righe di un file.py


from user_recognition import user_recognition
import datetime
from time import sleep
import cv2
from playsound import playsound
import RPi.GPIO as GPIO

alarmsound = "sound.mp3"
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(9, GPIO.OUT)

def alarm(time, userName):
    alarmTime = [int(n) for n in time.split(":")]
    if 0 <= alarmTime[0] < 24 and 0 <= alarmTime[1] <= 60:
        alarmTimeInSecs = (alarmTime[0] * 3600) + (alarmTime[1] * 60)

        #get now time
        now = datetime.datetime.now()
        nowSecs = (now.hour * 3600) + (now.minute * 60) + now.second
        secondsUntillAlarm = alarmTimeInSecs - nowSecs
        if secondsUntillAlarm < 0:
            secondsUntillAlarm += 86400
        sleep(secondsUntillAlarm - 15)
        cam = cv2.VideoCapture(0)
        soundAlarm = True
        while soundAlarm:
            check, frame = cam.read()
            user_name = user_recognition("people.json", frame)
            if(user_name == userName):
                print("recognized")
                soundAlarm = False
            else:
                playsound(alarmsound)


# 모델 불러오기
# pip install tensorflow==2.9.1
from PIL import Image
import os, glob, numpy as np
import tensorflow as tf
import joblib
from tensorflow.python.keras.models import load_model, model_from_json

# model.json 파일 열기
class Cnn_Model():
    cnt = 0
    def __init__(self,img_path):
        # 객체를 여러번 불러올 필요는 없으므로 최초에 한번 만들 놓겠음
        if Cnn_Model.cnt == 0:
            json_file = open("static/saved_models/catdog_model.json", "r")
            loaded_model_json = json_file.read()
            json_file.close()
            # json파일로부터 model 로드하기
            Cnn_Model.loaded_model = model_from_json(loaded_model_json)
            # 로드한 model에 weight 로드하기
            Cnn_Model.loaded_model.load_weights("static/saved_models/model.h5")
            print("Loaded model from disk")
            Cnn_Model.loaded_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
            Cnn_Model.categories = joblib.load("static/saved_models/categories.pkl")
            Cnn_Model.cnt += 1
        self.origindir = img_path

    def cnn_model(self):
        x_test = []
        img = Image.open(self.origindir)
        img = img.convert("RGB")
        img = img.resize((64, 64))
        data = np.asarray(img)
        x_test.append(data)
        X = np.array(x_test)
        X = X.astype(float) / 255
        prediction = Cnn_Model.loaded_model.predict(X)
        pp = np.argmax(prediction)
        category = Cnn_Model.categories[pp]
        return category


import copy
from typing import Optional

import torch
import torch.nn as nn
from torch import Tensor

from .linear_attention import FullAttention, LinearAttention

def _get_clones(module, N):
    return nn.ModuleList([copy.deepcopy(module) for i in range(N)])

class MultiHeadAttention(nn.Module):
    def __init__(
        self,
        embed_dim,
        num_heads,
        dropout=0.0,
        bias=True,
        kdim=None,
        vdim=None,
        attention='linear',
    ):
        super(MultiHeadAttention, self).__init__()
        self.kdim = kdim if kdim is not None else embed_dim
        self.vdim = vdim if vdim is not None else embed_dim

        self.nhead = num_heads
        self.dropout = dropout
        self.head_dim = embed_dim // num_heads
        self.embed_dim = embed_dim
        assert (self.head_dim * num_heads == self.embed_dim
                ), 'embed_dim must be divisible by num_heads'

        # multi-head attention
        self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
        self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias)
        self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias)
        if attention == 'linear':
            self.attention = LinearAttention()
        else:
            self.attention = FullAttention()
        self.merge = nn.Linear(embed_dim, embed_dim, bias=False)

    def forward(self, q, k, v, q_mask=None, kv_mask=None):
        bs = q.size(0)
        # multi-head attention
        # [N, L, (H, D)]
        query = self.q_proj(q).view(bs, -1, self.nhead, self.head_dim)
        # [N, S, (H, D)]
        key = self.k_proj(k).view(bs, -1, self.nhead, self.head_dim)
        value = self.v_proj(v).view(bs, -1, self.nhead, self.head_dim)
        # [N, L, (H, D)]
        message = self.attention(query,
                                 key,
                                 value,
                                 q_mask=q_mask,
                                 kv_mask=kv_mask)
        # [N, L, C]
        message = self.merge(message.view(bs, -1, self.nhead * self.head_dim))

        return message

class EncoderLayer(nn.Module):
    def __init__(self, d_model, nhead, attention='linear'):
        super(EncoderLayer, self).__init__()

        self.dim = d_model // nhead
        self.nhead = nhead

        # multi-head attention
        self.q_proj = nn.Linear(d_model, d_model, bias=False)
        self.k_proj = nn.Linear(d_model, d_model, bias=False)
        self.v_proj = nn.Linear(d_model, d_model, bias=False)
        if attention == 'linear':
            self.attention = LinearAttention()
        else:
            self.attention = FullAttention()
        self.merge = nn.Linear(d_model, d_model, bias=False)

        # feed-forward network
        self.mlp = nn.Sequential(
            nn.Linear(d_model, d_model * 2, bias=False),
            nn.GELU(),
            nn.Linear(d_model * 2, d_model, bias=False),
        )

        # norm and dropout
        self.pre_norm_q = nn.LayerNorm(d_model)
        self.pre_norm_kv = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)

    def forward(self,
                x,
                source,
                x_mask=None,
                source_mask=None,
                x_pos=None,
                s_pos=None):
        """
        Args:
            x (torch.Tensor): [N, L, C]
            source (torch.Tensor): [N, S, C]
            x_mask (torch.Tensor): [N, L] (optional)
            source_mask (torch.Tensor): [N, S] (optional)
        """
        # pdb.set_trace()
        bs = x.size(0)
        query = self.pre_norm_q(x)
        key = self.pre_norm_kv(source)
        value = self.pre_norm_kv(source)
        if x_pos is not None:
            query = query + x_pos
            key = key + s_pos
            value = value + s_pos

        # multi-head attention
        query = self.q_proj(query).view(bs, -1, self.nhead, self.dim)
        key = self.k_proj(key).view(bs, -1, self.nhead, self.dim)
        value = self.v_proj(value).view(bs, -1, self.nhead, self.dim)
        message = self.attention(query,
                                 key,
                                 value,
                                 q_mask=x_mask,
                                 kv_mask=source_mask)
        message = self.merge(message.view(bs, -1, self.nhead * self.dim))

        # feed-forward network
        x = x + message
        message2 = self.mlp(self.norm2(x))
        return x + message2

class LocalFeatureTransformer(nn.Module):
    """A Local Feature Transformer module."""
    def __init__(self, d_model=512, nhead=8):
        super(LocalFeatureTransformer, self).__init__()

        self.d_model = d_model
        self.nhead = nhead
        self.layer_names = ['self', 'cross'] * 4
        encoder_layer = EncoderLayer(d_model, nhead, 'linear')
        self.layers = nn.ModuleList([
            copy.deepcopy(encoder_layer) for _ in range(len(self.layer_names))
        ])
        self._reset_parameters()

    def _reset_parameters(self):
        for p in self.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)

    def forward(self, feat0, feat1, mask0=None, mask1=None):
        """
        Args:
            feat0 (torch.Tensor): [N, L, C]
            feat1 (torch.Tensor): [N, S, C]
            mask0 (torch.Tensor): [N, L] (optional)
            mask1 (torch.Tensor): [N, S] (optional)
        """

        assert self.d_model == feat0.size(
            2), 'the feature number of src and transformer must be equal'

        for layer, name in zip(self.layers, self.layer_names):
            if name == 'self':
                feat0 = layer(feat0, feat0, mask0, mask0)
                feat1 = layer(feat1, feat1, mask1, mask1)
            elif name == 'cross':
                src0, src1 = feat1, feat0
                feat0 = layer(feat0, src0, mask0, mask1)
                feat1 = layer(feat1, src1, mask1, mask0)
            else:
                raise KeyError
        return feat0, feat1

class DecoderLayer(nn.Module):
    def __init__(self, d_model, nhead, dropout=0.1, attention='linear'):
        super(DecoderLayer, self).__init__()

        self.dim = d_model // nhead
        self.nhead = nhead

        # multi-head attention
        self.q_proj = nn.Linear(d_model, d_model, bias=False)
        self.k_proj = nn.Linear(d_model, d_model, bias=False)
        self.v_proj = nn.Linear(d_model, d_model, bias=False)
        self.self_attn = MultiHeadAttention(d_model, nhead)
        self.multihead_attn = MultiHeadAttention(d_model, nhead)
        self.merge = nn.Linear(d_model, d_model, bias=False)
        self.dropout1 = nn.Dropout(dropout)
        self.dropout2 = nn.Dropout(dropout)
        self.dropout3 = nn.Dropout(dropout)

        # feed-forward network
        self.mlp = nn.Sequential(
            nn.Linear(d_model, d_model * 2, bias=False),
            nn.ReLU(True),
            nn.Linear(d_model * 2, d_model, bias=False),
        )

        # norm and dropout
        # self.pre_norm_q = nn.LayerNorm(d_model)
        # self.pre_norm_kv = nn.LayerNorm(d_model)
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.norm3 = nn.LayerNorm(d_model)

    def with_pos_embed(self, tensor, pos: Optional[Tensor]):
        return tensor if pos is None else tensor + pos

    def forward(self,
                tgt,
                memory,
                tgt_mask=None,
                memory_mask=None,
                tgt_pos=None,
                m_pos=None):
        """
        Args:
            tgt (torch.Tensor): [N, L, C]
            memory (torch.Tensor): [N, S, C]
            tgt_mask (torch.Tensor): [N, L] (optional)
            memory_mask (torch.Tensor): [N, S] (optional)
        """
        tgt2 = self.norm1(tgt)
        q = k = self.with_pos_embed(tgt2, tgt_pos)
        tgt2 = self.self_attn(q, k, v=tgt2, q_mask=tgt_mask, kv_mask=tgt_mask)
        tgt = tgt + self.dropout1(tgt2)
        tgt2 = self.norm2(tgt)
        tgt2 = self.multihead_attn(
            q=self.with_pos_embed(tgt2, tgt_pos),
            k=self.with_pos_embed(memory, m_pos),
            v=memory,
            q_mask=tgt_mask,
            kv_mask=memory_mask,
        )
        tgt = tgt + self.dropout2(tgt2)
        tgt2 = self.norm3(tgt)
        tgt2 = self.mlp(tgt2)
        tgt = tgt + tgt2

        return tgt

class TransformerDecoder(nn.Module):
    def __init__(self, decoder_layer, num_layers, norm=None):
        super().__init__()
        self.layers = _get_clones(decoder_layer, num_layers)
        self.num_layers = num_layers
        self.norm = norm

    def forward(self,
                tgt,
                memory,
                tgt_mask=None,
                memory_mask=None,
                tgt_pos=None,
                m_pos=None):
        output = tgt
        for layer in self.layers:
            output = layer(
                output,
                memory,
                tgt_mask=tgt_mask,
                memory_mask=memory_mask,
                tgt_pos=tgt_pos,
                m_pos=m_pos,
            )
        if self.norm is not None:
            output = self.norm(output)
        return output

class QueryTransformer(nn.Module):
    def __init__(self,
                 d_model=256,
                 nhead=8,
                 num_layers=4,
                 attention_mode='linear'):
        super(QueryTransformer, self).__init__()

        self.encoder_layer_names = ['self', 'cross'] * (num_layers)
        encoder_layer = EncoderLayer(d_model, nhead, attention=attention_mode)
        self.encoder = _get_clones(encoder_layer,
                                   len(self.encoder_layer_names))
        decoder_later = DecoderLayer(
            d_model,
            nhead,
            dropout=0.1,
        )
        self.decoder = TransformerDecoder(decoder_later, num_layers=2)

        self._reset_parameters()

    def _reset_parameters(self):
        for p in self.parameters():
            if p.dim() > 1:
                nn.init.xavier_uniform_(p)

    def forward(
        self,
        feat0,
        feat1,
        query_embed0,
        query_embed1,
        pos0,
        pos1,
        mask0=None,
        mask1=None,
    ):
        """
        Args:
            feat0:  [bs, c, h0, w0]
            feat1:
            query_embed0: [num_queries, c]
            query_embed1:
            pos0:
            pos1:
            mask0:
            mask1:
        Returns:
        """
        # pdb.set_trace()
        bs, c, h0, ww = feat0.shape
        feat0 = feat0.flatten(2).permute(0, 2, 1)
        feat1 = feat1.flatten(2).permute(0, 2, 1)
        if mask0 is not None:
            mask0 = mask0.flatten(1)
        if mask1 is not None:
            mask1 = mask1.flatten(1)
        pos0 = pos0.flatten(2).permute(0, 2, 1)
        pos1 = pos1.flatten(2).permute(0, 2, 1)
        query_embed0 = query_embed0.unsqueeze(0).repeat(bs, 1, 1)
        query_embed1 = query_embed1.unsqueeze(0).repeat(bs, 1, 1)

        for layer, name in zip(self.encoder, self.encoder_layer_names):
            if name == 'self':
                feat0 = layer(feat0, feat0, mask0, mask0, pos0, pos0)
                feat1 = layer(feat1, feat1, mask1, mask1, pos1, pos1)
            elif name == 'cross':
                src0, src1 = feat1, feat0
                feat0 = layer(feat0, src0, mask0, mask1, pos0, pos1)
                feat1 = layer(feat1, src1, mask1, mask0, pos1, pos0)
            else:
                raise KeyError

        # pdb.set_trace()
        tgt0 = torch.zeros_like(query_embed0)
        memory0 = feat0
        hs0 = self.decoder(
            tgt0,
            memory0,
            tgt_mask=None,
            memory_mask=mask0,
            tgt_pos=query_embed0,
            m_pos=pos0,
        )

        tgt1 = torch.zeros_like(query_embed1)
        memory1 = feat1
        hs1 = self.decoder(
            tgt1,
            memory1,
            tgt_mask=None,
            memory_mask=mask1,
            tgt_pos=query_embed1,
            m_pos=pos1,
        )
        # [bs, num_q, c]
        return hs0, hs1, memory0, memory1

class ChannelAttention(nn.Module):
    def __init__(self, in_planes, ratio=16):
        super(ChannelAttention, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.max_pool = nn.AdaptiveMaxPool2d(1)

        self.fc = nn.Sequential(
            nn.Conv2d(in_planes, in_planes // 16, 1, bias=False),
            nn.ReLU(inplace=False),
            nn.Conv2d(in_planes // 16, in_planes, 1, bias=False),
        )
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avg_out = self.fc(self.avg_pool(x))
        max_out = self.fc(self.max_pool(x))
        out = avg_out + max_out
        return self.sigmoid(out)

class SpatialAttention(nn.Module):
    def __init__(self, kernel_size=7):
        super(SpatialAttention, self).__init__()

        self.conv1 = nn.Conv2d(2,
                               1,
                               kernel_size,
                               padding=kernel_size // 2,
                               bias=False)
        self.sigmoid = nn.Sigmoid()

    def forward(self, x):
        avg_out = torch.mean(x, dim=1, keepdim=True)
        max_out, _ = torch.max(x, dim=1, keepdim=True)
        x = torch.cat([avg_out, max_out], dim=1)
        x = self.conv1(x)
        return self.sigmoid(x)


CONFIG = {

    "host" : "http://localhost:8080",
    "request" : {
        "method" : "POST",
        "data" : {
            "url": "https://sample-videos.com/img/Sample-jpg-image-50kb.jpg",
            "width": 10,
            "height": 10,
            "n": 30000
        },
        "headers" : {"Content-Type": "application/json"},
        "path" : "/function/'thumbnailer'"
    },
    "containerId" : "25aafb119ae1",
    "monitoring_window": 3,
    "app_sla": 0.4,
    "wait_time_min": 1,
    "wait_time_max": 1,
    "spawn_rate": 1,
    "end" : 100,
    "generator" : {
        "class" : "RampGen",
        "params" : {
            "slope": 1,
            "steady" : 50,
            "initial" : 1
        }
    },
    "controller" : {
        "class" : "StaticController",
        "params" : {
            "period" : 1,
            "init_cores" : 2,
            "min_cores" : 0.1,
            "max_cores" : 8
        }
    }
}

EXP_NAME = __file__.split("/")[-1].split(".")[0]

from base_experiment import *
setup(EXP_NAME, CONFIG)


from django.conf import settings
import datetime, os

def create_log(message):
    current_date = datetime.datetime.now()
    log_path = "{}/storages/logs".format(settings.BASE_DIR)
    log_filename = f"logs-{current_date.year}-{current_date.month:02d}-{current_date.day:02d}.txt"

    with open("{}/{}".format(log_path, log_filename), "a+") as log_file:
        log_file.write(f"{current_date} - {message}\n")

def remove_image(filepath):
    if os.path.isfile(filepath) and os.path.exists(filepath):
        os.remove(filepath)


import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import spacy
from googletrans import Translator
import re
import threading

# Ladda spaCy-modellen för engelska
nlp = spacy.load("en_core_web_sm")

def translate_srt(file_path, output_path, dest_lang='sv', progress_callback=None):
    translator = Translator()
    with open(file_path, 'r', encoding='utf-8') as file:
        contents = file.readlines()

    total_lines = len(contents)
    translated_contents = []
    for index, line in enumerate(contents):
        if re.match(r'\d\d:\d\d:\d\d', line) or re.match(r'\d+', line):
            translated_contents.append(line)
        else:
            if line.strip() != "":
                # Använd spaCy för att hitta namn i texten
                doc = nlp(line)
                names = [ent.text for ent in doc.ents if ent.label_ == 'PERSON']

                # Ersätt namn med placeholders
                temp_line = line
                for name in names:
                    temp_line = temp_line.replace(name, f'{{{names.index(name)}}}')

                # Översätt texten
                translated_line = translator.translate(temp_line, dest=dest_lang).text

                # Återställ namnen från placeholders
                for name in names:
                    translated_line = translated_line.replace(f'{{{names.index(name)}}}', name)

                translated_contents.append(translated_line + '\n')
            else:
                translated_contents.append('\n')

        # Uppdatera progressbaren
        if progress_callback:
            progress_callback(index + 1, total_lines)

    # Spara den översatta filen
    with open(output_path, 'w', encoding='utf-8') as file:
        file.writelines(translated_contents)

    return output_path

def update_progressbar(progress, total):
    progress_var.set(progress)
    progress_bar['maximum'] = total
    percent = f"{(progress / total) * 100:.1f}%"
    progress_label.config(text=percent)
    root.update_idletasks()

def translate_thread(file_path, output_path):
    try:
        translated_path = translate_srt(file_path, output_path, progress_callback=update_progressbar)
        messagebox.showinfo("Translation Complete", f"Translated file saved as: {translated_path}")
    except Exception as e:
        messagebox.showerror("Translation Failed", str(e))
    finally:
        progress_var.set(0)

def open_file():
    file_path = filedialog.askopenfilename(filetypes=[("SRT files", "*.srt")])
    if file_path:
        output_path = filedialog.asksaveasfilename(defaultextension=".srt", filetypes=[("SRT files", "*.srt")])
        if output_path:
            threading.Thread(target=translate_thread, args=(file_path, output_path), daemon=True).start()

def create_gui():
    global root, progress_var, progress_bar, progress_label
    root = tk.Tk()
    root.title("SRT Translator")

    open_button = tk.Button(root, text="Open SRT File", command=open_file)
    open_button.pack(side=tk.TOP, pady=10)

    progress_var = tk.DoubleVar()
    progress_bar = ttk.Progressbar(root, variable=progress_var, length=200)
    progress_bar.pack(side=tk.TOP, pady=10)

    progress_label = tk.Label(root, text="0%")
    progress_label.pack(side=tk.TOP, pady=5)

    root.mainloop()

if __name__ == "__main__":
    create_gui()


from tkinter import *

num = -1

def clicked():
    global num
    if (num == -1):
        num += 1
    else:
        num-=1

    res = "Привет{}".format(txt.get())
    res = res + str(num)

    try:
        error =res + str(num)
    except Exception as ex:
        res = str(ex)
        print("LOOOOOOOOOL: ", ex)
    finally:
        res = res + "\nЭто будет всегда выведено"

    label.configure(text=res)
    txt.configure(state=listState.get(num))

window = Tk()
listState = {-1 : 'disabled', 0 : 'readonly'}
window.title ("Добро пожаловать!")
label = Label(window, text="Ахах,ЧЫЖЫК", font=("Times New Roman", 24), bg="yellow", fg="blue")
lbl = Label(window, text="Ахах, ЧВК ЧИЖИК", font=("Times New Roman", 24), bg="yellow", fg="blue")
label.grid(column=0, row=0)
lbl.grid(column=0, row=1)
txt = Entry(window, width=10, state=listState.get(num))
txt.grid(column=2, row=0)
btn=Button(window, text="Не нажинать!", command=clicked)
btn.grid(column=1,row=0)
window.geometry('640x480')
window.mainloop()

Самочки/2/Таня/1питон.py


import torch
import torch.nn as nn
import torch.optim as optim
import random
import numpy as np

from typing import Callable

from .models import MLPnet, loadModel, saveModel, loadModel_from_dict

class DQNAgent:
    def __init__(self, state_size, num_actions, network_layers, learning_rate=0.001, discount_factor=0.99, epsilon=1.0, epsilon_decay=0.999, epsilon_min=0.01, batch_size=32, memory_capacity=10000, debug=False):
        self.state_size = state_size
        self.num_actions = num_actions
        self.network_layers = network_layers
        self.learning_rate = learning_rate
        self.discount_factor = discount_factor
        self.epsilon = epsilon
        self.epsilon_decay = epsilon_decay
        self.epsilon_min = epsilon_min
        self.batch_size = batch_size
        self.memory_capacity = memory_capacity
        self.memory = []
        self.model = MLPnet(state_size, *network_layers, num_actions)
        self.target_model = MLPnet(state_size, *network_layers, num_actions)
        self.target_model.load_state_dict(self.model.state_dict())
        self.debug=debug

        self.optimizer = optim.Adam(self.model.parameters(), lr=self.learning_rate)
        # self.optimizer = optim.RMSprop(self.model.parameters(), lr=10*self.learning_rate)
        self.criterion = nn.MSELoss()

        # <DEBUG>
        if self.debug:
            self.W = torch.tensor(np.loadtxt('flowmat.txt'), dtype=torch.float32)
        # </DEBUG>

    def choose_action(self, state, deterministic=False):
        if deterministic or np.random.uniform(0, 1)>=self.epsilon:
            # Exploit: choose the action with maximum Q-value for the current state
            state_tensor = torch.tensor(state, dtype=torch.float).unsqueeze(0)
            with torch.no_grad():
                q_values = self.model(state_tensor)
                action = torch.argmax(q_values).item()

            # <DEBUG>
            if self.debug:
                action = np.argsort((state_tensor.squeeze() @ self.W).numpy())[-1]
            # </DEBUG>
        else:
            # Explore: choose a random action
            action = random.randint(0, self.num_actions - 1)
        return action

    def remember(self, state, action, reward, next_state, done):
        self.memory.append((state, action, reward, next_state, done))
        if len(self.memory) > self.memory_capacity:
            self.memory.pop(0)

    def replay_supervised(self, target_fun: Callable[[np.ndarray], np.ndarray]):
        if len(self.memory) < self.batch_size:
            return

        batch = random.sample(self.memory, self.batch_size)
        state_batch, action_batch, reward_batch, next_state_batch, done_batch = zip(*batch)

        state_batch = torch.tensor(np.array(state_batch), dtype=torch.float)

        q_values = self.model(state_batch)

        # This comes from the target function (supervised learning)
        _, targets = torch.max(target_fun(state_batch), dim=1)

        criterion = torch.nn.CrossEntropyLoss()
        loss = criterion(q_values, targets)

        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

    def replay(self):
        # print("in replay")
        if len(self.memory) < self.batch_size:
            return

        batch = random.sample(self.memory, self.batch_size)
        state_batch, action_batch, reward_batch, next_state_batch, done_batch = zip(*batch)

        # state_batch=torch.stack(state_batch)
        # next_state_batch=torch.stack(next_state_batch)

        state_batch = torch.tensor(np.array(state_batch), dtype=torch.float)
        action_batch = torch.tensor(action_batch, dtype=torch.long)
        reward_batch = torch.tensor(reward_batch, dtype=torch.float)
        next_state_batch = torch.tensor(np.array(next_state_batch), dtype=torch.float)
        done_batch = torch.tensor(done_batch, dtype=torch.float)

        # <test>
        next_q_values = self.model(next_state_batch)
        next_q_values_target = self.target_model(next_state_batch)
        _, best_next_actions = torch.max(next_q_values, dim=1)
        max_next_q_values_target = next_q_values_target.gather(1, best_next_actions.unsqueeze(1)).squeeze(1)
        targets = reward_batch + self.discount_factor * max_next_q_values_target * (1.0 - done_batch)
        # </test>

        # # This comes from the predictive model itself
        # next_q_values = self.target_model(next_state_batch)
        # max_next_q_values, _ = torch.max(next_q_values, dim=1)
        # targets = reward_batch + self.discount_factor * max_next_q_values * (1.0 - done_batch)

        # targets = reward_batch + self.discount_factor * max_next_q_values
        q_values = self.model(state_batch)
        q_values = q_values.gather(1, action_batch.unsqueeze(1)).squeeze(1)

        loss = self.criterion(q_values, targets)

        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

    def update_target_model(self):
        self.target_model.load_state_dict(self.model.state_dict())

    def decay_epsilon(self):
        if self.epsilon > self.epsilon_min:
            self.epsilon *= self.epsilon_decay
            self.epsilon = max(self.epsilon, self.epsilon_min)

    def load_from_file(self, fname):
        self.model = loadModel(fname)
        self.target_model = loadModel(fname)
        # self.target_model.load_state_dict(self.model.state_dict())

    def load_from_dict(self, state_dict):
        self.model = loadModel_from_dict(state_dict)
        self.target_model = loadModel_from_dict(state_dict)
        # self.target_model.load_state_dict(self.model.state_dict())

    def save_to_file(self, fname):
        saveModel(self.model, fname)


import numpy as np
from tqdm.auto import trange
import os
import pickle

DIR = os.getcwd()

class NeuralNetwork:
    def __init__(self, sizes, train=False):
        """
        :param sizes: list
            A list of integers used to determine the sizes of the input, hidden, and output layers.
            ex: [784, 128, 10] : Will initialize a 128x784 matrix of weights and a 128x1 matrix of biases.
                                 Also, it will initialize a 10x128 matrix of weights and a 10x1 matrix of biases.
        :param train: boolean, optional
            When this flag is true it will randomize the biases and weights even if it can load model from disk
        """
        self.sizes = sizes
        self.learning_rate = 0.01
        self.nodes = {}
        self.error_nodes = {}
        self.trained = False

        # set biases and weights to random number if not able to load model from disk
        if train or self.load() is False:
            self.biases = self.initialize_bias()
            self.weights = self.initialize_weights()
        else:
            self.trained = True

    @staticmethod
    def sigmoid(x):
        return 1 / (1 + np.exp(-x))

    @staticmethod
    def squared_error_cost(prediction, target, derivative=False):
        if derivative:
            return 2 * (prediction - target)
        return (prediction - target) ** 2

    def activation(self, inputs, weights, bias):
        """
        Calculates the next layer by using the dot product, it multiplies the weights matrix by the inputs matrix
        connecting them to the neurons in the next layer. Next it adds the bias vector using matrix addition. Lastly,
        it applies the sigmoid function to the layer.

        :param inputs: numpy.ndarray
        :param weights: numpy.ndarray
        :param bias: numpy.ndarray
        :return: numpy.ndarray
        """
        return self.sigmoid(np.dot(weights, inputs) + bias)

    def sigmoid_derivative(self, x):
        """
        return self.sigmoid(x) * (1 - self.sigmoid(x)) - actual sigmoid derivative

        since sigmoid is already applied to x in forward_pass() we do not apply sigmoid to x again

        :param x: numpy.ndarray
        :return: numpy.ndarray
        """
        return x * (1 - x)

    def initialize_weights(self):
        """
        Initializes random matrices that will be used as weights. Each weight matrix is added to dictionary with the
        corresponding index as its key.

        :return: dict
        """
        weights = {}
        for i in range(1, len(self.sizes)):
            weights[i-1] = np.random.randn(self.sizes[i], self.sizes[i-1]) * np.sqrt(1. / self.sizes[i])
        return weights

    def initialize_bias(self):
        """
        Initializes random matrices that will be used as biases. Each bias matrix is added to dictionary with the
        corresponding index as its key.

        :return: dict
        """
        bias = {}
        for i in range(1, len(self.sizes)):
            bias[i-1] = np.random.randn(self.sizes[i], 1) * np.sqrt(1. / self.sizes[i])
        return bias

    def save(self):
        """
        save weights and biases to disk in '/model' folder
        """
        try:
            with open(DIR + '/model/weights.pickle', 'wb') as handle:
                pickle.dump(self.weights, handle)

            with open(DIR + '/model/bias.pickle', 'wb') as handle:
                pickle.dump(self.biases, handle)
        except FileNotFoundError as e:
            print('ERROR: Could not save files successfully: ' + e)

    def load(self):
        """
        Loads weights and biases from disk

        :return: Boolean
        """
        try:
            with open(DIR + '/model/weights.pickle', 'rb') as handle:
                self.weights = pickle.load(handle)

            with open(DIR + '/model/bias.pickle', 'rb') as handle:
                self.biases = pickle.load(handle)
        except IOError:
            return False

        return True

    def forward_pass(self, image):
        """
        Calculates every layer and stores it in self.nodes dictionary

        :param image: numpy.ndarray
        :return: numpy.ndarray
            This is the output layer
        """
        self.nodes[0] = layer = image.reshape((28, 28)).reshape(28 ** 2, 1)  # convert image to 784x1 matrix

        for i in range(len(self.weights)):
            layer = self.activation(layer, self.weights[i], self.biases[i])
            self.nodes[i+1] = layer

        return layer

    def predict_image(self, image):
        """
        Predicts the handwritten digit that's in the image

        :param image: numpy.ndarray
        :return: numpy.int64
        """
        return np.argmax(self.forward_pass(image), axis=0)[0]

    def update_parameters_iter(self, target):
        """
        Updates weights and biases like update_parameters() but for n amount of hidden layers
        todo: correctly update weights and biases!

        :param target: numpy.ndarray
        """
        index = len(self.weights) - 1
        self.weights[index] += self.learning_rate * (target - self.nodes[index+1]).dot(self.nodes[index].T)
        self.biases[index] += self.learning_rate * (target - self.nodes[index + 1]).sum()

        for i in range(len(self.weights)-2, -1, -1):
            gradient = self.weights[i+1].T.dot(2*(self.error_nodes[i+2] - self.nodes[i+2])) * self.sigmoid_derivative(self.nodes[i+1])
            self.weights[i] += self.learning_rate * gradient.dot(self.nodes[i].T)
            self.biases[i] += self.learning_rate * gradient

    def update_parameters(self, target):
        """
        Updates weights and biases

        :param target: numpy.ndarray
        """
        self.weights[2] += self.learning_rate * (target - self.nodes[3]).dot(self.nodes[2].T)
        self.biases[2] += self.learning_rate * (target - self.nodes[3]).sum()

        gradient = self.weights[2].T.dot(target - self.nodes[3]) * self.sigmoid_derivative(self.nodes[2])
        self.weights[1] += self.learning_rate * gradient.dot(self.nodes[1].T)
        self.biases[1] += self.learning_rate * gradient

        gradient = self.weights[1].T.dot(self.error_nodes[2]) * self.sigmoid_derivative(self.nodes[1])
        self.weights[0] += self.learning_rate * gradient.dot(self.nodes[0].T)
        self.biases[0] += self.learning_rate * gradient

    def backpropagation(self, prediction, target):
        """
        This is the backpropagation algorithm, for calculating the updates
        of the neural network's parameters.

        :param prediction: numpy.ndarray
        :param target: numpy.ndarray
        """
        self.error_nodes[len(self.weights)] = layer = self.squared_error_cost(prediction, target)

        for i in range(len(self.weights)-1, -1, -1):
            layer = np.dot(self.weights[i].T, layer)
            self.error_nodes[i] = layer

        self.update_parameters(target)

    def train(self, data, labels, epochs=5):
        """
        Trains model by using the corresponding data and label. The method expects Label[i] to be the label of data[i]

        :param data: numpy.ndarray
        :param labels: numpy.ndarray
        :param epochs: int, optional
        """
        for epoch in range(epochs):
            for i in trange(len(data), desc=str(epoch) + '/' + str(epochs)):
                prediction = self.forward_pass(data[i])

                # initialize a 10 by 1 matrix of the desired output
                target = np.zeros([10, 1], dtype=int)
                target[labels[i]] = 1

                self.backpropagation(prediction, target)


while True:
    a = int(input('\nDeseja ver a tabuada de outro número? '))
    if a < 0:
        break

    print(f'\n---Contemple a tabuada de {a}---')
    for i in range(1, 11):
        print(f'{a} x {i} = {i * a}')

print('Fim da execução do Programa Tabuada. Muito obrigado.')


import random

def play_roulette():
    total_slots = 37
    red_probability   = (18 / total_slots) * 100
    black_probability = (18 / total_slots) * 100
    green_probability = (1 / total_slots) * 100

    possible_outcomes = ["red", "black", "green"]
    probabilities = [red_probability, black_probability, green_probability]

    outcome = random.choices(
        possible_outcomes,
        weights=probabilities,
        k=1
    )[0]

    return outcome

def perform_simulation(n_times=1000, choice="red"):
    results = { "red": 0, "black": 0, "green": 0 }

    for i in range(n_times):
        outcome = play_roulette()
        results[outcome] += 1

    win_percentage = results[choice] / n_times

    return results, win_percentage

if __name__ == "__main__":
    results, win_percentage = perform_simulation(n_times=1000000,
                                                 choice="red")

    print(results)
    print(win_percentage)