"""Tokenizing, tagging and parsing text with UDPipe.

"""
import warnings

from ufal import udpipe

WORD_ATTRS = (
    "id",
    "form",
    "lemma",
    "xpostag",
    "upostag",
    "feats",
    "head",
    "deprel",
    "deps",
    "misc",
)
MULTIWORDTOKEN_ATTRS = ("idFirst", "idLast", "form", "misc")
EMPTYNODE_ATTRS = (
    "id",
    "index",
    "form",
    "lemma",
    "upostag",
    "xpostag",
    "feats",
    "deps",
    "misc",
)
SENT_ATTRS = ("comments", "words", "multiwordTokens", "emptyNodes")
PPRINT_DIGEST = True

class UdpipeError(Exception):
    """An error which occurred in the :mod:`ufal.udpipe` C extension."""

class Model:
    """A UDPipe model for tagging and parsing text.

    :param model_path: Path to the pre-compiled UDPipe model to load.
    :type model_path: str or pathlib.Path

    """

    def __init__(self, model_path):
        self._model = udpipe.Model.load(str(model_path))
        if self._model is None:
            raise RuntimeError(f"Unable to load model from {model_path!r}!")
        self._default = self._model.DEFAULT

    def process(self, text, *, tag=True, parse=True, in_format=None, out_format=None):
        """Process input text, yielding sentences one by one.

        The text is always at least tokenized, and optionally morphologically
        tagged and syntactically parsed, depending on the values of the ``tag``
        and ``parse`` arguments.

        :param text: Text to process.
        :type text: str
        :param tag: Perform morphological tagging.
        :type tag: bool
        :param parse: Perform syntactic parsing.
        :type parse: bool
        :param in_format: Input format (cf. below for possible values).
        :type in_format: None or str
        :param out_format: Output format (cf. below for possible values).
        :type out_format: None or str

        The input text is a string in one of the following formats (specified
        by ``in_format``):

        - ``None``: freeform text, which will be sentence split and tokenized
          by UDPipe
        - ``"conllu"``: the CoNLL-U_ format
        - ``"horizontal"``: one sentence per line, word forms separated by
          spaces
        - ``"vertical"``: one word per line, empty lines denote sentence ends

        .. _CoNLL-U: https://universaldependencies.org/docs/format.html

        The output format is specified by ``out_format``:

        - ``None``: native :mod:`ufal.udpipe` objects, suitable for further
          manipulation in Python
        - ``"conllu"``, ``"horizontal"`` or ``"vertical"``: cf. above
        - ``"epe"``: the EPE (Extrinsic Parser Evaluation 2017) interchange
          format
        - ``"matxin"``: the Matxin XML format
        - ``"plaintext"``: reconstruct text with original spaces, discarding
          annotations

        New input and output formats may be added with new releases of UDPipe;
        for an up-to-date list, consult the `UDPipe API reference
        <http://ufal.mff.cuni.cz/udpipe/api-reference>`__.

        """
        if in_format is None:
            in_format = self._model.newTokenizer(self._default)
        else:
            in_format = udpipe.InputFormat.newInputFormat(in_format)
            if in_format is None:
                raise RuntimeError(f"Cannot create input format {in_format!r}.")

        if out_format is not None:
            out_format = udpipe.OutputFormat.newOutputFormat(out_format)
            if out_format is None:
                raise RuntimeError(f"Cannot create output format {out_format!r}.")

        in_format.setText(text)
        error = udpipe.ProcessingError()
        sent = udpipe.Sentence()
        while in_format.nextSentence(sent, error):
            if tag:
                self.tag(sent)
            if parse:
                self.parse(sent)
            if out_format is None:
                yield sent
            else:
                yield out_format.writeSentence(sent)
            sent = udpipe.Sentence()
        if error.occurred():
            raise UdpipeError(error.message)
        if out_format is not None:
            end = out_format.finishDocument()
            if end != "":
                yield end

    def tag(self, sent):
        """Perform morphological tagging on sentence.

        Modifies ``sent`` in place.

        :param sent: Sentence to tag.
        :type sent: ufal.udpipe.Sentence

        """
        # NOTE: like InputFormat.nextSentence, Model.tag and Model.parse accept
        # a ProcessingError argument. However, the udpipe_model.py example in
        # the UDPipe repo only passes the error argument to nextSentence,
        # probably on the assumption that input format errors are the only ones
        # which can be caused by users (and therefore will also routinely have
        # to be resolved by them). Other errors are bugs which should be fixed
        # by UDPipe maintainers, so they're ignored for simplicity's sake. For
        # the time being, we follow the same rationale here.
        self._model.tag(sent, self._default)

    def parse(self, sent):
        """Perform syntactic parsing on sentence.

        Modifies ``sent`` in place.

        :param sent: Sentence to parse.
        :type sent: ufal.udpipe.Sentence

        """
        self._model.parse(sent, self._default)

def load(corpus, in_format="conllu"):
    """Load corpus in input format.

    :param corpus: The data to load.
    :type corpus: str
    :param in_format: Cf. the documentation of :meth:`Model.process`.
    :type in_format: str
    :return: A generator of sentences (:class:`ufal.udpipe.Sentence`).

    """
    in_format = udpipe.InputFormat.newInputFormat(in_format)
    if in_format is None:
        raise RuntimeError(f"Cannot create input format {in_format!r}.")
    in_format.setText(corpus)
    error = udpipe.ProcessingError()
    sent = udpipe.Sentence()
    while in_format.nextSentence(sent, error):
        yield sent
        sent = udpipe.Sentence()
    if error.occurred():
        raise UdpipeError(error.message)

def dump(sent_or_sents, out_format="conllu"):
    """Dump sentence or sentences in output format.

    :param sent_or_sents: The data to dump.
    :type corpus: :class:`ufal.udpipe.Sentence`, or iterable thereof
    :param out_format: Cf. the documentation of :meth:`Model.process`.
    :type out_format: str
    :return: A generator of strings, corresponding to the serialized sentences.
        One final additional string may contain any closing markup, if required
        by the output format.

    """
    out_format = udpipe.OutputFormat.newOutputFormat(out_format)
    if out_format is None:
        raise RuntimeError(f"Cannot create output format {out_format!r}.")

    if isinstance(sent_or_sents, udpipe.Sentence):
        yield out_format.writeSentence(sent_or_sents)
    else:
        for sent in sent_or_sents:
            yield out_format.writeSentence(sent)
    end = out_format.finishDocument()
    if end != "":
        yield end

def _pprint_token(token, printer, cycle):
    cls_name = type(token).__name__
    if cycle:
        return printer.text(f"{cls_name}(...)")
    elif PPRINT_DIGEST and token.form == "<root>":
        return printer.text(f"{cls_name}(id={token.id}, <root>)")
    indent = len(cls_name) + 1
    with printer.group(indent, f"{cls_name}(", ")"):
        i = 0
        for attr in globals()[cls_name.upper() + "_ATTRS"]:
            val = getattr(token, attr)
            if not PPRINT_DIGEST or val != "" and val != -1:
                if i:
                    printer.text(",")
                    printer.breakable()
                printer.text(f"{attr}={val!r}")
                i += 1

def _pprint_sent(sent, printer, cycle):
    if cycle:
        return printer.text("Sentence(...)")
    with printer.group(2, "Sentence(", ")"):
        for i, attr in enumerate(SENT_ATTRS):
            seq = getattr(sent, attr)
            if PPRINT_DIGEST and seq.size() == 0:
                continue
            if i:
                printer.text(",")
            printer.breakable("")
            with printer.group(2, f"{attr}=[", "]"):
                printer.breakable("")
                for j, elem in enumerate(seq):
                    if j:
                        printer.text(",")
                        printer.breakable()
                    printer.pretty(elem)

def _pprint_seq(seq, printer, cycle):
    if cycle:
        return printer.text("[...]")
    # NOTE: The following is basically the same code as at the end of
    # _pprint_sent, minus a call to printer.breakable("") just after the with,
    # the indent width and the starting delimiter string of the group.
    # Unfortunately, I haven't yet figured out a way to adjust this depending
    # on whether _pprint_seq is called from _pprint_sent or not, so it will
    # have to stay duplicated for the time being.
    with printer.group(1, "[", "]"):
        for j, elem in enumerate(seq):
            if j:
                printer.text(",")
                printer.breakable()
            printer.pretty(elem)

def pprint(obj):
    """Pretty-print object.

    This is a convenience wrapper over :func:`IPython.lib.pretty.pprint` for
    easier importing.

    """
    try:
        from IPython.lib import pretty

        pretty.pprint(obj)
    except ImportError:
        warnings.warn("Please install the IPython package for pretty-printing to work.")

def pprint_config(*, digest=True):
    """Configure pretty-printing of :mod:`ufal.udpipe` objects.

    :param digest: Show only attributes with interesting values (other than
        ``''`` or ``-1``)
    :type digest: bool

    """
    global PPRINT_DIGEST
    PPRINT_DIGEST = digest

def _register_pprinters(formatter):
    formatter.for_type(udpipe.Word, _pprint_token)
    formatter.for_type(udpipe.MultiwordToken, _pprint_token)
    formatter.for_type(udpipe.EmptyNode, _pprint_token)
    formatter.for_type(udpipe.Sentence, _pprint_sent)
    formatter.for_type(udpipe.Comments, _pprint_seq)
    formatter.for_type(udpipe.Words, _pprint_seq)
    formatter.for_type(udpipe.MultiwordTokens, _pprint_seq)
    formatter.for_type(udpipe.EmptyNodes, _pprint_seq)

try:
    from IPython import get_ipython
    from IPython.lib import pretty

    _register_pprinters(pretty)
    _ipython = get_ipython()  # pylint: disable=invalid-name
    if _ipython is not None:
        _plain_formatter = _ipython.display_formatter.formatters["text/plain"]
        _register_pprinters(_plain_formatter)
    else:
        warnings.warn(
            "IPython session not found! Processed text will not be automatically pretty-printed, "
            "but you may still do so explicitly with the corpy.udpipe.pprint function."
        )
except ImportError:
    warnings.warn(
        "IPython package not found! Processed text will not be automatically pretty-printed, and "
        "the corpy.udpipe.pprint function will not work."
    )


from jax._src.api import value_and_grad, vmap
from jax._src.numpy.lax_numpy import array
from jax.scipy.special import logsumexp
from jax.experimental import optimizers
from jax import random, jit
import jax.numpy as np

from torch.utils.data.dataloader import DataLoader
from torchvision import datasets, transforms

import time

key = random.PRNGKey(1)
batch_size = 100

train_loader = DataLoader(
    datasets.MNIST(
        "./data", train=True, download=True,
        transform=transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize(
                  (0.1307,), (0.3081,)
            )
        ])
    ), batch_size=batch_size, shuffle=True
)

test_loader = DataLoader(
    datasets.MNIST(
        "./data", train=False, download=True,
        transform=transforms.Compose([
            transforms.ToTensor(),
            transforms.Normalize(
                  (0.1307,), (0.3081,)
            )
        ])
    ), batch_size=batch_size, shuffle=True
)

def initialize_mlp(sizes, key):
    keys = random.split(
        key, len(sizes)
    )

    def initialize_layer(m, n, key, scale=1e-2):
        w_key, b_key = random.split(key)
        return scale * random.normal(
            w_key, (n, m)
        ), scale * random.normal(
            b_key, (n,)
        )
    return [
        initialize_layer(m, n, k) for m, n, k in zip(
            sizes[:-1], sizes[1:], keys
        )
    ]

layer_sizes = [784, 512, 512, 10]

params = initialize_mlp(
    layer_sizes, key
)

def forward_pass(params, in_array):
    """
    forward pass
    """
    def relu_layer(params, x):
        def ReLU(x):
            return np.maximum(0, x)
        return ReLU(np.dot(params[0], x) + params[1])

    activations = in_array

    for w, b in params[:-1]:
        activations = relu_layer([w, b], activations)

    final_w, final_b = params[-1]
    logits = np.dot(
        final_w, activations
    ) + final_b

    return logits - logsumexp(logits)

batch_forward = vmap(
    forward_pass, in_axes=(None, 0), out_axes=0
)

def one_hot(x, k, dtype=np.float32):
    """
    docstring
    """
    return np.array(
        x[:, None] == np.arange(k), dtype
    )

def loss(params, in_array, targets):

    preds = batch_forward(
        params, in_array
    )

    return -np.sum(preds * targets)

num_classes = 10

def accuracy(params, data_loader):
    acc_total = 0

    for batch_idx, (data, target) in enumerate(data_loader):
        images = np.array(data).reshape(
            data.size(0), 28*28
        )
        targets = one_hot(
            np.array(target), num_classes
        )

        target_class = np.argmax(
            targets, axis=1
        )

        predicted_class = np.argmax(
            batch_forward(params, images), axis=1
        )

        acc_total += np.sum(
            predicted_class == target_class
        )

    return acc_total/len(data_loader.dataset)

step_size = 1e-3
opt_init, opt_update, get_params = optimizers.adam(step_size)
opt_state = opt_init(params)

@jit
def update(params, x, y, opt_state):
    """
    Compute the gradient for batch and update the params
    """
    value, grads = value_and_grad(loss)(params, x, y)
    opt_state = opt_update(
        0, grads, opt_state
    )

    return get_params(
        opt_state
    ), opt_state, value

num_epochs = 10

def run_mnist_training_loop(num_epochs, opt_state, net_type="MLP"):
    """
    traing loop
    """
    log_acc_train, log_acc_test, train_loss = [], [], []

    params = get_params(opt_state)

    train_acc = accuracy(params, train_loader)
    test_acc = accuracy(params, test_loader)
    log_acc_train.append(train_acc)
    log_acc_test.append(test_acc)

    for epoch in range(num_epochs):
        start_time = time.time()

        for batch_idx, (data, target) in enumerate(train_loader):
            if net_type == "MLP":
                x = np.array(data).reshape(
                    data.size(0), 28*28
                )

            y = one_hot(
                np.array(target), num_classes
            )

            params, opt_state, loss = update(
                params, x, y, opt_state
            )

            train_loss.append(loss)

        epoch_time = time.time() - start_time
        train_acc = accuracy(params, train_loader)
        test_acc = accuracy(params, test_loader)
        log_acc_train.append(train_acc)
        log_acc_test.append(test_acc)
        print("Epoch {} | T: {:0.2f} | Train A: {:0.3f} | Test A: {:0.3f}".format(
            epoch+1, epoch_time, train_acc, test_acc))
    return train_loss, log_acc_train, log_acc_test

train_loss, train_log, test_log = run_mnist_training_loop(
    num_epochs, opt_state, net_type="CNP"
)


# sql db management stuff
# https://www.sqlitetutorial.net

from sqlite3 import connect
from os.path import exists
from src.logger import Logger
from src.exception import TableExistError, DBConnectionFailedError, JSONDecodeError

log = Logger('SQLog')

try:
    with open('./config.json', 'r') as f:
        CONFIG:dict = __import__('json').load(f)
except (JSONDecodeError, FileNotFoundError):
    log.warning('failed to load config file')

# update loglist
try: log.remove_loglist(*CONFIG.get('log')['remove'])
except NameError: log.warning('couldn\'t update the loglist')

class DB:
    def __init__(self, path:str) -> None:
        self.path = path

        try:
            self.conn = connect(path)
            self.curser = self.conn.cursor()
            log.info(f'connected to db: {path}')
        except Exception as e:
            log.critical(f'Failed to connect to DB: {e.__str__()}')
            raise DBConnectionFailedError

    def create_db(db_path:str, ask:bool = False, question:str|None = None) -> bool:
        """Create new db file. Returns True if new DB was created and only returns False if creation was aborted by the user."""
        if ask:
            if question is None: question = 'Do you want to create a new database?'
            inp = input(f'{question} [y/n] ').lower()

            if inp == 'y':
                with open(db_path, 'w') as f:
                    f.close()
                log.info(f'created new db: {db_path}')
                return True
            else:
                return False
        else:
            with open(db_path, 'w') as f:
                f.close()
            log.info(f'created new db: {db_path}')
            return True

    def execute(self, sql:str, params:tuple=()) -> tuple|None:
        """Execute sql code."""
        try:
            log.debug(f'execute on db: {self.path}: {sql}')
            out = tuple(self.curser.execute(sql, params))
            if len(out) > 0: return out
            else: return None

        except Exception as e:
            log.error(f'error while executing sql on db: {self.path}: {e.__str__()}')
            raise e

    def create_table(self, name:str, columns:tuple|list) -> None:
        """
        Create new table in db.\n
        example: columns=["id integer PRIMARY KEY", ...]
        """
        try:
            if name not in tuple(self.list_tables()):
                code = f'CREATE TABLE IF NOT EXISTS {name} ({", ".join(columns)});'
                self.execute(code)
                self.commit()
                log.info(f'created new table: {name} in db: {self.path}')
            else:
                log.critical(f'table already exist in db: {self.path}')
                raise TableExistError(name)
        except Exception as e:
            log.error(f'error while creating new table: {name} on db: {self.path}: {e.__str__()}')
            raise e

    def list_tables(self) -> tuple:
        """Returns a generator object of tables from db."""
        ex = self.execute('SELECT name FROM sqlite_master WHERE type="table";')
        return ex if ex is not None else ('')

    def commit(self) -> None:
        """Commit executed code to db."""
        self.conn.commit()

    def close(self) -> None:
        """Close connection to DB."""
        try:
            self.commit() # just for safety
            self.conn.close()
            log.info(f'connection to db: {self.path} closed')
        except Exception as e:
            log.error(f'error while closing connection to db: {self.path}: {e.__str__()}')
            raise e

    def insert(self, table:str, data:dict) -> None:
        """Insert data into table."""
        try:
            log.debug(f'insert data into db: {self.path}: table: {table}')
            q = ', '.join(f"{'? '*len(data)}".split())
            code = f"INSERT INTO {table} ({', '.join([key for key in data])}) VALUES ({q});"
            self.execute(code, tuple(val for _, val in data.items()))
            self.commit()
        except Exception as e:
            log.error(f'error while inserting data into table: {table} in db: {self.path}: {e.__str__()}')
            raise e

    def select(self, table:str, columns:str|tuple|list, where:str='', params:tuple=()) -> tuple|None:
        """
        Retrieve data from db.
        example: where='WHERE uid = ...'
        """
        try:
            log.debug(f'get {columns} from db: {self.path}: table: {table}')
            code = f'SELECT {", ".join(columns) if type(columns) != str else columns} FROM {table} {where};'
            return self.execute(code, params)
        except Exception as e:
            log.error(f'error while retrieving data from table: {table} from db: {self.path}: {e.__str__()}')
            raise e

    def delete(self, table:str, where:str, params:tuple=()) -> None:
        """
        Delete row in table where $where matches.
        example: where='WHERE uid = ...'
        """
        try:
            log.debug(f'delete row in table: {table} where: {where}')
            self.execute(f'DELETE FROM {table} {where};', params)
            self.commit()
        except Exception as e:
            log.error(f'error while deleting row in table: {table} in db: {self.path}: {e.__str__()}')
            raise e

    def update(self, table:str, data:dict, where:str, params:tuple=()) -> None:
        """
        Update columns in table where $where matches.
        example: where='WHERE uid = ...'
        """
        try:
            log.debug(f'update row in table: {table} where: {where}')
            data = ', '.join((f'{key} = "{value}"' for key, value in data.items()))
            self.execute(f'UPDATE {table} SET {data} {where};', params)
            self.commit()
        except Exception as e:
            log.error(f'error while updating row in table: {table} in db: {self.path}: {e.__str__()}')
            raise e


#!/usr/bin/python
'''
author: Christian M
'''
import cv2
import numpy as np
import logging
from services.Base import *

class Webcam(Base):

    def __init__(self, serviceRunner):
        super(Webcam, self).__init__()
        self.logger = logging.getLogger(__name__)
        self.serviceRunner = serviceRunner
        self.config = self.defaultConfig()
        self.image = None

    def defaultConfig(self):
        return {"x": 0, "y": 0, "Interval": 1, "resx": 640, "resy": 480, "device": 0}

    def init(self):
        self.capture = cv2.VideoCapture(self.config['device'])
        if not self.capture.isOpened():
            self.logger.error("Could not open camera ", self.config['device'])
            img = np.zeros((self.config["resy"], self.config["resx"], 3), np.uint8)
            img += np.array([0,255,0], np.uint8)
            cv2.putText(img, 'No image, device %d'%(self.config["device"]), (10,self.config["resy"]/2), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0),1)
            self.image = img[:,::-1,:] #will be displayed mirrored
        else:
            self.capture.set(3,self.config["resx"])
            self.capture.set(4,self.config["resy"])

            ret, self.image = self.capture.read()

    def update(self):
        if self.capture.isOpened():
            ret, self.image = self.capture.read()
            self.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)

    def currentImage(self):
        return self.image


from django.conf.urls import url, include
from rest_framework import routers
from rest_framework.routers import DefaultRouter

from . import views

app_name = 'api'
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
# ^ begin $ end,+ several decimal long pattern
urlpatterns = [
    url(r'^itemslist/$', views.TodoListItems.as_view(), name='itemslist'),
url(r'^postslist/$', views.PostsList.as_view(), name='postslist'),
url(r'^placeslist/$', views.PlacesList.as_view(), name='placeslist'),
url(r'^profileslist/$', views.ProfileUserLists.as_view(), name='profileslist'),
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]


import tkinter as tk
import tkinter.ttk as ttk
from tkinter import messagebox
from datetime import date

# Variable para almacenar los datos de las ventas
datos_ventas = []

def guardar_venta():
    cliente = entry_cliente.get()
    producto = entry_producto.get()
    cantidad = entry_cantidad.get()

    if cliente == "" or producto == "" or cantidad == "":
        messagebox.showerror("Error", "Por favor, completa todos los campos.")
    else:
        # Aquí puedes agregar la lógica para guardar la venta en la base de datos
        messagebox.showinfo("Registro de Ventas", "Venta registrada correctamente.")
        entry_cliente.delete(0, tk.END)
        entry_producto.delete(0, tk.END)
        entry_cantidad.delete(0, tk.END)

        # Añadir los datos de la venta a la lista
        datos_venta = (producto, cantidad, "...", "...", "...")
        datos_ventas.append(datos_venta)

        # Actualizar el cuadro grande con los nuevos datos
        actualizar_cuadro_grande()

def actualizar_cuadro_grande():
    # Eliminar todas las etiquetas del cuadro grande
    for widget in cuadro_grande.winfo_children():
        widget.destroy()

    # Encabezados de la tabla
    encabezados = ["Producto", "Cantidad", "Precio", "Descuento", "Precio Total"]
    for col, encabezado in enumerate(encabezados):
        label_encabezado = tk.Label(cuadro_grande, text=encabezado, font=fuente_entry, anchor="w", width=15, bg="white", padx=5)
        label_encabezado.grid(row=0, column=col)
        if col > 0:
            separator = ttk.Separator(cuadro_grande, orient="vertical")
            separator.grid(row=0, column=col, sticky="ns")

    # Datos de las ventas
    for i, datos_venta in enumerate(datos_ventas):
        producto_valor = tk.Label(cuadro_grande, text=datos_venta[0], font=fuente_entry, anchor="w", width=20)
        producto_valor.grid(row=i+1, column=0)
        cantidad_valor = tk.Label(cuadro_grande, text=datos_venta[1], font=fuente_entry, anchor="w", width=10)
        cantidad_valor.grid(row=i+1, column=1)
        precio_valor = tk.Label(cuadro_grande, text=datos_venta[2], font=fuente_entry, anchor="w", width=10)
        precio_valor.grid(row=i+1, column=2)
        descuento_valor = tk.Label(cuadro_grande, text=datos_venta[3], font=fuente_entry, anchor="w", width=10)
        descuento_valor.grid(row=i+1, column=3)
        precio_total_valor = tk.Label(cuadro_grande, text=datos_venta[4], font=fuente_entry, anchor="w", width=10)
        precio_total_valor.grid(row=i+1, column=4)

# Crear la ventana de registro de ventas
ventana_registro_ventas = tk.Tk()
ventana_registro_ventas.title("Registro de Ventas")
ventana_registro_ventas.geometry("600x400")

# Configurar estilos
fuente_titulo = ("Arial", 24, "bold")
fuente_label = ("Arial", 14)
fuente_entry = ("Arial", 14)
fuente_boton = ("Arial", 14)

# Título del registro de ventas
titulo = tk.Label(ventana_registro_ventas, text="Registro de Ventas", font=fuente_titulo)
titulo.pack(pady=20)

# Contenedor para el formulario
contenedor_formulario = tk.Frame(ventana_registro_ventas)

# Label y Entry para el campo Cliente
label_cliente = tk.Label(contenedor_formulario, text="Cliente:", font=fuente_label)
label_cliente.grid(row=0, column=0, padx=10, pady=10, sticky="e")
entry_cliente = tk.Entry(contenedor_formulario, font=fuente_entry)
entry_cliente.grid(row=0, column=1, padx=10, pady=10)

# Label y Entry para el campo Producto
label_producto = tk.Label(contenedor_formulario, text="Producto:", font=fuente_label)
label_producto.grid(row=1, column=0, padx=10, pady=10, sticky="e")
entry_producto = tk.Entry(contenedor_formulario, font=fuente_entry)
entry_producto.grid(row=1, column=1, padx=10, pady=10)

# Label y Entry para el campo Cantidad
label_cantidad = tk.Label(contenedor_formulario, text="Cantidad:", font=fuente_label)
label_cantidad.grid(row=2, column=0, padx=10, pady=10, sticky="e")
entry_cantidad = tk.Entry(contenedor_formulario, font=fuente_entry)
entry_cantidad.grid(row=2, column=1, padx=10, pady=10)

# Label para la fecha
fecha_actual = date.today().strftime("%d/%m/%Y")
label_fecha = tk.Label(contenedor_formulario, text="Fecha:", font=fuente_label)
label_fecha.grid(row=3, column=0, padx=10, pady=10, sticky="e")
label_fecha_valor = tk.Label(contenedor_formulario, text=fecha_actual, font=fuente_entry)
label_fecha_valor.grid(row=3, column=1, padx=10, pady=10, sticky="w")

# Botón para guardar la venta
boton_registrar = tk.Button(contenedor_formulario, text="Registrar", font=fuente_boton, bg="#4CAF50", fg="white", command=guardar_venta)
boton_registrar.grid(row=4, column=0, padx=10, pady=10, sticky="w")

# Botón para cancelar
boton_cancelar = tk.Button(contenedor_formulario, text="Cancelar", font=fuente_boton, bg="#FF0000", fg="white", command=ventana_registro_ventas.quit)
boton_cancelar.grid(row=4, column=1, padx=10, pady=10, sticky="e")

# Agregar el contenedor del formulario a la ventana principal
contenedor_formulario.pack()

# Cuadro grande
cuadro_grande = tk.Frame(ventana_registro_ventas, bg="white", relief="solid", borderwidth=1)
cuadro_grande.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)

# Encabezados de la tabla
encabezados = ["Producto", "Cantidad", "Precio", "Descuento", "Precio Total"]
for col, encabezado in enumerate(encabezados):
    label_encabezado = tk.Label(cuadro_grande, text=encabezado, font=fuente_entry, anchor="w", width=15, bg="white", padx=5)
    label_encabezado.grid(row=0, column=col)
    if col > 0:
        separator = ttk.Separator(cuadro_grande, orient="vertical")
        separator.grid(row=0, column=col, sticky="ns")

# Ejecutar la aplicación
ventana_registro_ventas.mainloop()


# Imports
from hashes import *
from tkinter import *
from tkinter import filedialog
from tkinter import simpledialog
from tkinter.filedialog import asksaveasfile

# Class
class call5dia(simpledialog.Dialog):

    def __init__(self, parent, title=None, text=None):
        self.data = text
        simpledialog.Dialog.__init__(self, parent, title=title)

    def body(self, parent):
        self.text = Text(self, width=40, height=4)
        self.text.pack(fill="both", expand=True)

        self.text.insert("1.0", self.data)

        return self.text

# Callbacks
def call1():
    global inp
    inp = filedialog.askopenfilename(initialdir = "~",title = "Select file",filetypes = ((
        ('Text Document', '*.txt'),
        ('Python Files', '*.py'), ('All Files', '*.*'))))
    file = open(inp, 'r')
    l = file.readlines()
    inp = ''
    for index in l:
        inp += index
    main.destroy()
    return inp
def call2():
    def temp(a):
        global inp
        inp = a.get("1.0", "end-1c")
        main2.destroy()
    global inp
    main.destroy()
    main2 = Tk()
    main2.geometry('1280x720')
    main2.title('Decryptor')
    main2.config(background='#666666')
    l = Label(
        main2,
        background='#272727',
        foreground='#ffffff',
        text='What do you want to decrypt?',
        font=("Arial", 15)
    )
    inp = Text(
        main2,
        height = 10000,
        width =  10000,
        background = "#272727",
        foreground = "#ffffff",
        borderwidth=0,
        font=("Arial", 15),
        insertbackground="#ffffff"
    )
    but3 = Button(
        main2,
        background='#373737',
        foreground='#ffffff',
        activebackground='#878787',
        activeforeground='#ffffff',
        font=('Arial', 12),
        text='Decrypt',
        borderwidth=0,
        command=lambda: temp(inp)
    )
    l.pack(side=TOP)
    but3.pack(fill=Y,side=BOTTOM)
    inp.pack()
    main2.mainloop()
def call3():
    def temp(a):
        global inp
        inp = a.get("1.0", "end-1c")
        main3.destroy()
    global inp
    main3 = Tk()
    main3.geometry('1280x720')
    main3.title('Decryptor')
    main3.config(background='#666666')
    l1 = Label(
        main3,
        background='#272727',
        foreground='#ffffff',
        text='Please type in a valid encryption key',
        font=("Arial", 15)
    )
    inp = Text(
        main3,
        height = 10000,
        width =  10000,
        background = "#272727",
        foreground = "#ffffff",
        borderwidth=0,
        font=("Arial", 15),
        insertbackground="#ffffff"
    )
    but4 = Button(
        main3,
        background='#373737',
        foreground='#ffffff',
        activebackground='#878787',
        activeforeground='#ffffff',
        font=('Arial', 12),
        text='Decrypt',
        borderwidth=0,
        command=lambda: temp(inp)
    )
    l1.pack(side=TOP)
    but4.pack(fill=Y,side=BOTTOM)
    inp.pack()
    main3.mainloop()
def call4(op):
    type = [('Text Document', '*.txt'), ('Python Files', '*.py'), ('All Files', '*.*')]
    temp = asksaveasfile(filetypes = type, defaultextension = type)
    temp.write(op)
    quit()
def call5(op):
    call5dia(main4, title="Output", text=op)
    quit()
# Decrypt From File Or Not.
## Tkinter
main = Tk()
main.geometry('325x75')
main.title('Decryptor')
main.config(background='#272727')
## Config
label = Label(
    main,
    background='#272727',
    foreground='#ffffff',
    text='Do you want to decrypt a text file?',
    font=("Arial", 15)
    ).pack()
but1 = Button(
    main,
    background='#373737',
    foreground='#ffffff',
    activebackground='#878787',
    activeforeground='#ffffff',
    font=('Arial', 12),
    text='Yes',
    borderwidth=0,
    command=lambda: call1()
).pack(ipadx=30, side=LEFT,padx=10)
but2 = Button(
    main,
    background='#373737',
    foreground='#ffffff',
    activebackground='#878787',
    activeforeground='#ffffff',
    font=('Arial', 12),
    text='No',
    borderwidth=0,
    command=lambda: call2(),
).pack(ipadx=30, side=RIGHT,padx=10)
## Running
main.mainloop()

# Error Checking
if inp[-1] == '\n' or inp[-1] == ' ':
    inp = inp[:-1]
if len(inp) >= 5:
    b = inp[-3:]
    c = inp[-4]
    inp = inp[:-4]
    op = ''
    while b != 'ymc' or c not in 'abcdefghijklmno':
        call3()
        if len(inp) >= 5:
            b = inp[-3:]
            c = inp[-4]
            inp = inp[:-4]
            op = ''
        else:
            continue
else:
    while b != 'ymc' or c not in 'abcdefghijklmno':
        call3()
        if len(inp) >= 5:
            b = inp[-3:]
            c = inp[-4]
            inp = inp[:-4]
            op = ''
        else:
            continue
if c in 'abcde':
    hash = lvl1(a=c)
elif c in 'fghij':
    hash = lvl2(a=c)
elif c in 'klmno':
    hash = lvl3(a=c)

# Decrypting
for var in inp:
    op += hash[var]

# Saving Output
## Tkinter
main4 = Tk()
main4.geometry('425x75')
main4.title('Encrpyptor')
main4.config(background='#272727')
## Config
l2 = Label(
    main4,
    background='#272727',
    foreground='#ffffff',
    text='Do you want to save the output to a text file?',
    font=("Arial", 15)
    ).pack()
but1 = Button(
    main4,
    background='#373737',
    foreground='#ffffff',
    activebackground='#878787',
    activeforeground='#ffffff',
    font=('Arial', 12),
    text='Yes',
    borderwidth=0,
    command=lambda: call4(op)
).pack(ipadx=30, side=LEFT,padx=10)
but2 = Button(
    main4,
    background='#373737',
    foreground='#ffffff',
    activebackground='#878787',
    activeforeground='#ffffff',
    font=('Arial', 12),
    text='No',
    borderwidth=0,
    command=lambda: call5(op),
).pack(ipadx=30, side=RIGHT,padx=10)
## Running
main4.mainloop()


import requests
import json
from os import path
import asyncio
import time

def emitRequest(url):
  # retry if "Too many request (429)"
  while True:
    r = requests.get(url)
    if r.status_code == 200:
      return r
    elif r.status_code == 429 or r.status_code == 502:
      time.sleep(1)
    else:
      raise Exception(r.status_code, url)

def getRouteStop(co):
    # define output name
    ROUTE_LIST = 'routeList.'+co+'.json'
    STOP_LIST = 'stopList.'+co+'.json'

    # load route list and stop list if exist
    routeList = {}
    if path.isfile(ROUTE_LIST):
        return
    else:
        # load routes
        r = emitRequest('https://rt.data.gov.hk/v2/transport/nlb/route.php?action=list')
        routeList = []
        for route in r.json()['routes']:
            routeList.append({
                "id": route['routeId'],
                "route": route['routeNo'],
                "bound": "O",
                "orig_en": route['routeName_e'].split(' > ')[0],
                "orig_tc": route['routeName_c'].split(' > ')[0],
                "dest_en": route['routeName_e'].split(' > ')[1],
                "dest_tc": route['routeName_c'].split(' > ')[1],
                "service_type": str(1 + route['overnightRoute'] * 2 + route['specialRoute'] *4),
                "stops": [],
                "co": ["nlb"]
            })

    _stops = []
    stopList = {}
    if path.isfile(STOP_LIST):
        with open(STOP_LIST) as f:
            stopList = json.load(f)

    def getRouteStop(routeId):
        r = emitRequest('https://rt.data.gov.hk/v2/transport/nlb/stop.php?action=list&routeId='+routeId)
        try:
            return r.json()['stops']
        except Exception as err:
            print(r)
            raise err

    async def getRouteStopList ():
        loop = asyncio.get_event_loop()
        futures = [loop.run_in_executor(None, getRouteStop, route['id']) for route in routeList]
        ret = []
        for future in futures:
            ret.append(await future)
        for route, stops in zip(routeList, ret):
            stopIds = []
            fares = []
            faresHoliday = []
            for stop in stops:
                if stop['stopId'] not in stopList:
                    stopList[stop['stopId']] = {
                        'stop': stop['stopId'],
                        'name_en': stop['stopName_e'],
                        'name_tc': stop['stopName_c'],
                        'lat': stop['latitude'],
                        'long': stop['longitude']
                    }
                stopIds.append(stop['stopId'])
                fares.append(stop['fare'])
                faresHoliday.append(stop['fareHoliday'])
            route['stops'] = stopIds
            route['fares'] = fares[0:-1]
            route['faresHoliday'] = faresHoliday[0:-1]
        return routeList

    loop = asyncio.get_event_loop()
    routeList = loop.run_until_complete(getRouteStopList())

    with open(ROUTE_LIST, 'w') as f:
        f.write(json.dumps(routeList, ensure_ascii=False))
    with open(STOP_LIST, 'w') as f:
        f.write(json.dumps(stopList, ensure_ascii=False))

getRouteStop('nlb')


while True:
    try:
        x1, y1, x2, y2, vi, r1 , r2 = map(int,input().split())

        d = (((x2 - x1) ** 2) + ((y2 - y1) ** 2)) ** (1/2)

        distotal = d + (vi * 1.5)

        rtotal = r1 + r2

        if distotal <= rtotal:
            print('Y')
        else:
            print('N')
    except EOFError:
        break


from os import listdir
from os.path import join
from pprint import pprint

import calendar
from docx.api import Document
from docx.api import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from pprint import pprint

def prev_month_docxs(path_to_old_docxs):
    # searchs for prev month docx files, returning paths to them as a list
    path = path_to_old_docxs
    docx_files_list = [
        join(path, f) for f in listdir(path) if f.endswith(".docx")
    ]
    return docx_files_list

def table_column_header_keys(sample_docx):
    # reads keys from table column headers, which later will be
    # keys in data dictionary
    keys = []
    header_table = Document(sample_docx).tables[0]
    header_cells = header_table.row_cells(0)
    for i, cell in enumerate(header_cells):
        keys.append(cell.text)
    return keys

def data_dict(docxs_list, keys_list):
    """
    Stores .docx data into python dict
    1) reading data from MS docx files
    2) parsing them into dictionary
    3) data structure:
    data['PLAYER NAME'] = {'INNER KEY 1': INNER VALUE 1,
                          'INNER KEY 2': INNER VALUE 2, etc.}
    """

    data = {}
    for file in docxs_list:
        document = Document(file)
        table = document.tables[0]
        empty_keys = 0
        repetitions = 1
        key = '*'
        for i, row in enumerate(table.rows[1:]):
            text = [cell.text for cell in row.cells]
            if text[1] == '':
                empty_keys += 1
                key = 'ZZ' + str(empty_keys)
            elif text[1] == key[:-1]:
                repetitions += 1
                key = text[1] + str(repetitions)
            else:
                repetitions = 1
                key = text[1] + str(repetitions)
            name_dict = dict(zip(keys_list, text))
            data[key] = name_dict
    return data

def get_days(year, month, day, nw_days):
    # returning list of the calendar days based on given week day
    # excluding not working days when tennis courts are closed
    day = day_to_num(day)
    # day is:[0-Monday,1-Tuesday,2-Wednesday,3-Thursday
    #        [4-Friday,5-Saturday,6-Sunday]
    c = calendar.Calendar()
    r =  [date for date, _day in c.itermonthdays2(year, month) \
        if date != 0 and _day == day and date not in nw_days]
    return str(r).strip('[]')

def day_to_num(day):
    # changes input from data dictionary
    # basicly changes word to it's number representation
    days = ['PONIEDZIAŁEK', 'WTOREK', 'ŚRODA', \
        'CZWARTEK', 'PIĄTEK', 'SOBOTA', 'NIEDZIELA']
    for c, v in enumerate(days):
        if v == day:
            return c

def add_new(data, minor_data_keys, week_day, hour, name, year, month):
    # adding new player to data dictionary
    for i in range(1, 4):
        player_vals = ['', name, week_day, hour,
                        calendar_days_fill(year, month, week_day),
                        '', '']
        player_data = dict(zip(minor_data_keys, player_vals))
        data[name + str(i)] = player_data

def del_existing(data, data_key):
    # deletes existing data key, key must be present in a data dictionary
    for i in range(1, 4):
        del data[data_key + str(i)]

def switch_data_key(data, old_data_key, new_data_key):
    # changes old data key name to the new one
    for i in range(1, 4):
        data[new_data_key + str(i)] = data.pop(old_data_key + str(i))

def docx_fill(old_docxs, save_path, data):
    sorted_data = sorted(data.keys())
    sliced_data = [sorted_data[i * 24:(i + 1) * 24] for i in range((len(sorted_data) + 24 - 1) // 24)]
    key_order = ['LP', 'NAZWISKO', 'DZIEŃ TYGODNIA',
                 'GODZINA', 'DNI KALENDARZOWE', 'NALEŻNOŚĆ\nZA GODZINĘ',
                  'LUTY' + 7 * ' ' + 'UWAGI', 'PŁATNOŚĆ']
    current_lp = 1
    wait = 0
    for c, v in enumerate(sorted_data):
        print(v)
        data[v]['LP'] = str(current_lp)
        wait += 1
        if wait == 3:
            current_lp += 1
            wait = 0
    for slicee in sliced_data:
        first_letter = slicee[0][0]
        last_letter = slicee[-1][0]
        document = Document(old_docxs[0])
        sample_table = document.tables[0]
        padding_letters = set()
        for i, row in enumerate(sample_table.rows[1:]):
            padding_letters.add(data[slicee[i]]['NAZWISKO'][:1])
            for j, cell in enumerate(row.cells):
                cell.text = data[slicee[i]][key_order[j]]
                #cell.paragraphs[0].style = document.styles['Normal']
        paragraphs = document.paragraphs
        paragraphs[0].text = '  -  '.join(sorted(list(padding_letters)))
        doc_name = 'REZERWACJE STAŁE  ' + '-'.join(sorted(padding_letters)) + '.docx'
        document.save(join(save_path, doc_name))

def main(path_to_old_docxs, save_path, year, month, nw_days):

    """
    def main(path_to_old_docxs, save_path, year, month, nw_days)
    *path_to_old_docxs - path to old .docx files folder
    *save_path - path to new .docx files folder(produced by this script)
    *year - 4 digits like 2020, *month - 1-12 (1==Jan)
    *nw_days - not working days in given *month for eg. [1, 6]
    """

    old_docx_paths = prev_month_docxs(path_to_old_docxs)
    # inner_keys finds and stores table coulmn header keys needed for data_dictionary
    inner_keys = table_column_header_keys(old_docx_paths[0])
    # data variable stores nested dictionary in which players data are stored
    data = data_dict(old_docx_paths, inner_keys)

    for i in data.keys():
        data[i]['DNI KALENDARZOWE'] = get_days(year, month, data[i]['DZIEŃ TYGODNIA'], nw_days)

    docx_fill(old_docx_paths, save_path, data)
    pprint(data)

if __name__ == '__main__':
    main(
        path_to_old_docxs=R'C:\Users\danie\Desktop\mail\merging docx tables\old',
        save_path='C://Users//danie//Desktop//mail//merging docx tables//new//',
        year=2020,
        month=3,
        nw_days=[],
)


from django.conf.urls import include, url
from rest_framework.routers import DefaultRouter
from rest_framework.schemas import get_schema_view
from . import rest

router = DefaultRouter()
router.register(r"simple", rest.SimpleViewSet)
router.register(r"users", rest.UserViewSet)
schema_view = get_schema_view("Test safetydance_django API")

urlpatterns = [
    url(r"^api/", include(router.urls), name="api"),
    url(r"^api/schema", schema_view, name="api-schema"),
    url(
        r"^api/rest-framework/auth",
        include("rest_framework.urls", namespace="rest_framework"),
    ),
]


import pandas as pd
import pickle
import numpy as np

model = open(
    'C:/Users/Kalpagam/udemy_bootcamp/ml_projects/anomaly_detection/trained_model.pkl', 'rb')
trained_model = pickle.load(model)

x_test = input("Enter a current reading ")

x_test = np.asarray(x_test).reshape(-1, 1)

result = trained_model.predict(x_test)

if (result == [1]):
    print("Anomaly")
else:
    print("No Anomaly")


import logging
import os
import sys
import time
from http import HTTPStatus

import requests
import telegram
from dotenv import load_dotenv

from exceptions import HttpResponseError, ParseError

load_dotenv()

TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
PRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN')
TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')

RETRY_PERIOD = 600
ENDPOINT = 'https://practicum.yandex.ru/api/user_api/homework_statuses/'
HEADERS = {'Authorization': f'OAuth {PRACTICUM_TOKEN}'}

HOMEWORK_VERDICTS = {
    'approved': 'Работа проверена: ревьюеру всё понравилось. Ура!',
    'reviewing': 'Работа взята на проверку ревьюером.',
    'rejected': 'Работа проверена: у ревьюера есть замечания.'
}

def check_tokens():
    """Проверка наличия переменных окружения."""
    return all([
        PRACTICUM_TOKEN,
        TELEGRAM_TOKEN,
        TELEGRAM_CHAT_ID
    ])

def get_api_answer(timestamp):
    """Создание get-запроса к API."""
    RESPONSE = {
        'url': ENDPOINT,
        'headers': HEADERS,
        'params': {"from_date": timestamp},
    }
    try:
        response = requests.get(**RESPONSE)
        if response.status_code != HTTPStatus.OK:
            message = (f'Параметры запроса: {response.url}',
                       f'Статус ответа API: {response.status_code}',
                       f'Контент ответа: {response.text}',)
            raise HttpResponseError(message)

    except Exception as error:
        message = f'Эндпоинт {ENDPOINT}, недоступен! Ошибка: {error}.'
        raise HttpResponseError(message)

    return response.json()

def check_response(response):
    """Проверка ответа API на наличие нужных ключей и типов данных."""
    logging.info('Проверка ответа API')

    if not isinstance(response, dict):
        message = 'Ответ API не являтеся словарем!'
        raise TypeError(message)

    if 'homeworks' not in response and 'current_date' not in response:
        message = 'Нет нужного ключа в ответе API!'
        raise KeyError(message)

    homeworks = response.get('homeworks')

    if not isinstance(homeworks, list):
        message = 'Формат данных по ключу "homeworks", не является списком!'
        raise TypeError(message)

    return homeworks

def parse_status(homework):
    """
    Парсим статус домашней работы.
    Содержащий один из вердиктов словаря HOMEWORK_VERDICTS.
    """
    homework_name = homework.get('homework_name')

    if 'homework_name' not in homework:
        message = 'В ответе API нет ключа "homework_name".'
        raise ParseError(message)

    status_work = homework.get('status')

    if 'status' not in homework:
        message = 'В ответе API отсутстует ключ "status".'
        raise ParseError(message)

    verdict = HOMEWORK_VERDICTS.get(status_work)

    if status_work not in HOMEWORK_VERDICTS:
        message = f'Неизвестный статус домашней работы: {status_work}'
        raise KeyError(message)

    return f'Изменился статус проверки работы "{homework_name}". {verdict}'

def send_message(bot, message):
    """Отправка сообщения в Telegram."""
    try:
        bot.send_message(
            chat_id=TELEGRAM_CHAT_ID,
            text=message,
        )
        logging.debug(f'Сообщение - "{message}", отправлено успешно')

    except telegram.error.TelegramError as error:
        message = f'Не удалось отправить сообщение из-за ошибки {error}'
        logging.error(message)
        raise AssertionError(message)

def main():
    """Основная логика работы бота."""
    if not check_tokens():
        logging.critical(
            'Отсутствуют переменные окружения',
            'Прогрмма принудительно остановлена!'
        )
        exit()

    bot = telegram.Bot(token=TELEGRAM_TOKEN)
    timestamp = int(time.time())
    old_status_homework = ''
    old_exception = ''

    while True:

        try:
            response_get_api = get_api_answer(timestamp)
            timestamp = response_get_api.get('current_date')
            homeworks = check_response(response_get_api)

            if not homeworks:
                message = 'Нет домашних работ'
                logging.debug(message)

            new_status_homework = parse_status(homeworks[0])

            if new_status_homework != old_status_homework:
                message = new_status_homework
                send_message(bot, message)
                old_status_homework = new_status_homework

        except Exception as error:
            message = f'Сбой в работе программы: {error}'
            logging.error(error.__context__)
            new_exception = message
            if new_exception != old_exception:
                send_message(bot, message)
                old_exception = new_exception

        finally:
            time.sleep(RETRY_PERIOD)

if __name__ == '__main__':
    logging.basicConfig(
        level=logging.DEBUG,
        format='%(asctime)s, %(levelname)s, %(message)s, %(name)s',
        stream=sys.stdout
    )
    main()


import boto3

import config

database = boto3.resource(
    'dynamodb',
    endpoint_url = config.USER_STORAGE_URL,
    region_name = 'ru-central1',
    aws_access_key_id = config.AWS_PUBLIC_KEY,
    aws_secret_access_key = config.AWS_SECRET_KEY
)

forecast = database.Table('ИМЯ ВАШЕЙ ТАБЛИЦЫ')


import random
import time
import tkinter as tk

def start_game():
    global lst,goal_list,replay_list,m
    m = 0
    lst, goal_list = creat_lst()
    replay_list.append(lst.copy())
    # root.bind("<Left>", left)
    # root.bind("<Right>", right)
    # root.bind("<Up>", north)
    # root.bind("<Down>", south)
    output_lst()

def game_clear():
    global lst
    global goal_list
    if lst == goal_list:
        result = tk.Toplevel()
        label_result = tk.Label(result, text='game clear\ncongratulation!!',
                                bg='white', font=('Arial', 14),
                                width=18, height=6)
        label_result.grid()
        button_replay = tk.Button(result, text = 'review',
                                  bg='white', font = ('Arial', 14),
                                  width=18, height=2,command = replay_function)
        button_replay.grid()

def replay_function():
    replay_window = tk.Toplevel()
    replay_window.geometry("450x420")
    replay_window.resizable(False, False)
    frm_1 = tk.Frame(replay_window, width=450, height=420, bg='#87CEEB').grid(rowspan=6, columnspan=3)
    for a in range(m):
        replay_window.after(500,output_replay_lst(a,replay_window))
        replay_window.update()

def label_result():
    label_result = tk.Label(root_result, text='game clear', bg='white', font=('Arial', 14),
                            width=12, height=5)
    label_result.grid()

def label_move_num():
    move = tk.Label(root,text='步数:',font=('宋体', 24),bg ='white')
    move.place(x = 455,y = 16)
    move_num = tk.Label(root,text=m,font=('宋体', 24),bg ='white',width = 5)
    move_num.place(x = 540,y =16)

def button_start():
    button_start = tk.Button(root, text='开始游戏',
                             bg='white', font=('宋体', 18),
                             width=12, height=5, command=start_game)
    button_start.place(x = 455,y = 285, width=190, height=60)

def button_goal_list():
    button_goal_list = tk.Button(root, text='目标位置',
                             bg='white', font=('宋体', 18),
                             width=12, height=5, command=output_goal_list)
    button_goal_list.place(x=455, y=355, width=190, height=60)

def button_left():
    button_left = tk.Button(root, text='move_left',
                            bg='white', font=('Arial', 11),
                            width=12, height=5, command=lambda: left(lst))
    button_left.grid(row=4, column=0)

def button_right():
    button_left = tk.Button(root, text='move_right',
                            bg='white', font=('Arial', 11),
                            width=12, height=5, command=lambda: right(lst))
    button_left.grid(row=4, column=2)

def button_up():
    button_left = tk.Button(root, text='move_up',
                            bg='white', font=('Arial', 11),
                            width=12, height=5, command=lambda: north(lst))
    button_left.grid(row=3, column=1)

def button_down():
    button_left = tk.Button(root, text='move_down',
                            bg='white', font=('Arial', 11),
                            width=12, height=5, command=lambda: south(lst))
    button_left.grid(row=4, column=1)

def replay_up(replay_window):
    global m
    if m == 0:
        output_replay_lst(replay_window)
    else:
        m -=1
        output_replay_lst(replay_window)

def replay_down(replay_window):
    global m
    if m == len(replay_list)-1:
        output_replay_lst(replay_window)
    else:
        m +=1
        output_replay_lst(replay_window)

def replay_m(input,replay_window):
    global m
    m = int(input)
    output_replay_lst(replay_window)

def output_replay_lst(a,replay_window):
    j = -2
    for i in range(9):
        if (i % 3 == 0):
            j += 2
        label1 = tk.Label(replay_window, text=replay_list[a][i],
                          bg='#F8F8FF', font=('Arial', 20),
                          width=6, height=3)
        label1.grid(row=j, column=(i % 3), rowspan=2, padx=4, pady=4, sticky='n,e,w,s')

def output_lst():
    j = -2
    for i in range(9):
        if (i % 3 == 0):
            j += 2
        label1 = tk.Label(root, text=lst[i],
                          bg='#F8F8FF', font=('Arial', 20),
                          width=6, height=3)
        label1.grid(row=j, column=(i % 3), rowspan=2, padx=4, pady=4, sticky='n,e,w,s')
    root.update()

def output_goal_list():
    goal_list_tk = tk.Toplevel()
    goal_list_tk.title('目标位置')
    goal_list_tk.geometry("450x420")
    frm_1 = tk.Frame(goal_list_tk, width=450, height=420, bg='#87CEEB').grid(rowspan=6, columnspan=3)
    j = -2
    for i in range(9):
        if (i % 3 == 0):
            j += 2
        label2 = tk.Label(goal_list_tk, text=goal_list[i],
                          bg='#F8F8FF', font=('Arial', 20),
                          width=6, height=3)
        label2.grid(row=j, column=(i % 3), rowspan=2, padx=4, pady=4, sticky='n,e,w,s')

def inversion_number(lst):
    n = 0
    for i in range(1,9):
        if lst[i] == 0:
            continue
        for j in range(i):
            if lst[j] > lst[i]:
                n += 1
    return n

def can_start(lst, goal_list):
    return inversion_number(lst) % 2 == inversion_number(goal_list) % 2

def creat_lst():
    lst = [i for i in range(0, 9)]
    goal_list = [i for i in range(0, 9)]
    random.shuffle(lst)
    random.shuffle(goal_list)
    while (can_start(lst, goal_list) != 1):
        random.shuffle(goal_list)
    return lst,goal_list

def move_bind():
    root.bind("<Left>", left)
    root.bind("<Right>", right)
    root.bind("<Up>", north)
    root.bind("<Down>", south)

def move_none():
    root.bind("<Left>", None)
    root.bind("<Right>", None)
    root.bind("<Up>", None)
    root.bind("<Down>", None)

def north(event):
    global m
    n = lst.index(0)
    if (n <3):
        output_lst()
    else:
        lst[n] = lst[n - 3]
        lst[n - 3] = 0
        m += 1
        replay_list.append(lst.copy())
    label_move_num()
    output_lst()
    game_clear()

def south(event):
    global m
    n = lst.index(0)
    if (n >5):
        output_lst()
    else:
        lst[n] = lst[n + 3]
        lst[n + 3] = 0
        m += 1
        replay_list.append(lst.copy())
    label_move_num()
    output_lst()
    game_clear()

def left(event):
    global m
    n = lst.index(0)
    if(n in [0, 3, 6]):
        output_lst()
    else:
        lst[n] = lst[n - 1]
        lst[n - 1] = 0
        m +=1
        replay_list.append(lst.copy())
    label_move_num()
    output_lst()
    game_clear()

def right(event):
    global m
    n = lst.index(0)
    if(n in [2, 5, 8]):
        output_lst()
    else:
        lst[n] = lst[n + 1]
        lst[n + 1] = 0
        m += 1
        replay_list.append(lst.copy())
    label_move_num()
    output_lst()
    game_clear()

def move():
    move_none()
    while(lst != goal_list and v.get() == 2):
        ch = random.randint(1,4)
        if ch == 1:
            north(lst)
        elif ch == 2:
            south(lst)
        elif ch == 3:
            left(lst)
        elif ch == 4:
            right(lst)
        time.sleep(0.3)

if __name__ == '__main__':

    root = tk.Tk()
    root.title('八数码游戏')

    root.geometry("650x420")
    root.resizable(False, False)

    frm_1 = tk.Frame(root, width=450, height=420, bg='#87CEEB').grid(rowspan=6, columnspan=3)
    frm_2 = tk.Frame(root, width=200, height=70, bg='#F8F8FF').grid(row=0, column=3)
    frm_3 = tk.LabelFrame(root, width=200, height=210, bg='#E0FFFF', text='游戏模式',font = 18).grid(row=1, column=3, rowspan=3)
    frm_4 = tk.Frame(root, width=200, height=140, bg='#7FFFD4').grid(row=4, column=3, rowspan=2)

    m = 0
    replay_list = []

    lst = [i for i in range(9)]
    lst[1] = 0
    lst[0] = 1
    goal_list = [i for i in range(9)]
    output_lst()

    button_start()
    button_goal_list()

    label_move_num()

    move_way = [('人工移动',1),
                ('随机移动',2),
                ('智能移动',3)]
    v = tk.IntVar()
    v .set(1)
    tk.Radiobutton(root, text = '人工移动', variable = v, value = 1,
                   bg='#E0FFFF', width=18, height=2, font=35, anchor='w', command = move_bind()).place(x = 460 ,y = 90)
    tk.Radiobutton(root, text = '随机移动', variable = v, value = 2,
                   bg='#E0FFFF', width=18, height=2, font=35, anchor='w', command = move).place(x = 460 ,y = 155)
    tk.Radiobutton(root, text = '智能移动', variable = v, value = 3,
                   bg='#E0FFFF', width=18, height=2, font=35, anchor='w').place(x = 460 ,y = 220)
    root.mainloop()

第2学期/【第24课】探秘人工智能/八数码_游戏.py


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from mpl_toolkits.mplot3d import Axes3D
import pandas as pd

# warmup_exercise:
def warmup_exercise():
    """ Return a 5x5 identity matrix. """
    return np.eye(5)

# Linear Regression with One Variable
def load_data(fileLocation, featureColumns, responseColumns):
    """ Given a file location, this provides a pandas DataFrame of the data.

    featureColumns and responseColumns are lists of indices corresponding to those data series,
    with the convention that the returned data is from left to right, features and then responses. """
    return pd.read_csv(fileLocation, usecols=featureColumns + responseColumns, header=None)

def plot_scatter(data):
    """ Generates a scatter plot of the provided data. Returns the axes for further plotting ability. """

    data.columns = ['city_population', 'profit']
    axes = data.plot(x='city_population', y='profit', kind='scatter')
    axes.set_xlim(left=data['city_population'].min() - 1)
    axes.set_xlabel('Population of city in 10,000s')
    axes.set_ylabel('Profit in $10,000s')
    return axes

def compute_cost(features, response, theta):
    """ Computes the least square error cost function value. """

    # in this case we know that the last variable is the response, so we ignore it
    cost = np.dot(features, theta) # h_theta(x_i)
    cost -= response # - y_i
    cost *= cost # square it
    cost = cost.sum() / (2 * len(features)) # summation, then divide by 2m
    return cost

def compute_dCost_dTheta(features, response, theta):
    """ Helper function that calculates dJ/dTheta, evaluated at theta. """

    # notice that this will be similar to the general cost function
    cost = np.dot(features, theta) # h_theta(x_i)
    cost -= response # - y_i
    cost = np.broadcast_to(cost, (len(features.columns), len(cost))).T * features # elementwise mult by the remainder of derivative
    cost = np.sum(cost, axis=0) / len(features)
    return cost.values

def execute_gradient_descent(data, learningRate=0.01, maxIters=2000, theta=None, addInterceptFeature=True):
    """ Returns the parameter vector Theta of len(data.columns) + 1 that minimizes least
    squares error loss.

    addInterceptFeature - if True, adds a feature column of 1's corresponding to the Theta_0 parameter
    theta - option to initialize Theta to specific values.
    learningRate - algorithm learning rate parameter
    maxIters - number of iterations after which the algorithm automatically terminates """

    # initialize theta if not given
    if theta is None:
        interceptLength = 0 if addInterceptFeature else -1
        theta = np.zeros(len(data.columns) + interceptLength)

    # insert intercept feature
    data.insert(0, 'intercept', 1)

    # print initial cost, and set up a cost tracking list
    cost = compute_cost(data.iloc[:,:-1], data.iloc[:,-1], theta)
    costProgression = [cost]
    print('Current _cost: {0}'.format(cost))

    for i in range(maxIters):

        theta -= learningRate * compute_dCost_dTheta(data.iloc[:,:-1], data.iloc[:,-1], theta) # dCost_dTheta is a 2-vector

        cost = compute_cost(data.iloc[:,:-1], data.iloc[:,-1], theta)
        costProgression.append(cost)
        print('Current cost: {0}'.format(cost))

    # remove the dummy intercept variable from data, else our scatter plots will be messed up
    data.drop('intercept', axis=1, inplace=True)
    return theta, pd.DataFrame(costProgression)

def plot_fitted_regression(data, fittedTheta):
    """ Plots the fitted regression line on a previous scatter plot. """

    scatter = plot_scatter(data)

    x = np.arange(data['city_population'].min(), data['city_population'].max(), .1) # recall the name of our columns
    scatter.plot(x, fittedTheta[0] + fittedTheta[1] * x)

    scatter.legend(['Training data', 'Linear Regression'])
    return

def predict(observationVector, theta):
    """ Given a fitted theta and observation vector, we can make a regression prediction.
    We assume observationVector and theta are lists. """

    observationVector.insert(0, 1) # add the intercept value
    return sum([observationVector[i] * theta[i] for i in range(len(theta))])

def plot_cost_curves(data):
    """ Plots 3d and contour curves of the cost function in parameter space. This helps us
    visualize the dynamics of the gradient descent algorithm. """

    # initialize our parameter space
    thetaZeroValues = np.linspace(-10, 10, 100)
    thetaOneValues = np.linspace(-1, 4, 100)
    costValues = np.zeros((100, 100))

    # we are going to need to insert the intercept column again
    data.insert(0, 'intercept', 1)

    # get the fuction values over parameter space
    for i in range(100):
        for j in range(100):
            costValues[i,j] = compute_cost(data.iloc[:,:-1], data.iloc[:,-1], [thetaZeroValues[i], thetaOneValues[j]])

    # drop intercept
    data.drop('intercept', axis=1, inplace=True)

    # convert to 3d friendly meshgrid
    thetaZeroValues, thetaOneValues = np.meshgrid(thetaZeroValues, thetaOneValues)

    # time to plot, first the surface and then the contour
    fig = plt.figure(figsize=(15,10))

    # surface plot
    surfax = fig.add_subplot(1, 2, 1, projection='3d')
    surfax.plot_surface(thetaZeroValues, thetaOneValues, costValues.T)

    # contour plot
    contax = fig.add_subplot(1, 2, 2)
    contax.contour(thetaZeroValues, thetaOneValues, costValues.T, 17) # seventeen contour lines for clarity
    contax.set_ylabel('Theta One')
    contax.set_xlabel('Theta Zero')
    return

def required_main():
    """ Main function for required exercises """

    loc = r"C:\Users\ashamlian\Downloads\machine-learning-ex1\ex1\ex1data1.txt"
    foodTruckData = load_data(loc, [0], [1])
    plot_scatter(foodTruckData)

    fittedTheta, _ = execute_gradient_descent(foodTruckData, theta=[0,0])

    print('For a town of {0} people, we expect profits of {1} * $10,000'.format(35000, predict([3.5], fittedTheta)))
    print('For a town of {0} people, we expect profits of {1} * $10,000'.format(70000, predict([7], fittedTheta)))

    plot_fitted_regression(foodTruckData, fittedTheta)
    plot_cost_curves(foodTruckData)
    return

# Optional Exercises
def normalize_features(data):
    """ Apply standardization to the dataset. Pandas makes this very simple """

    data.columns = ['sq_ft', 'bedrooms', 'price']
    tmp = data[['sq_ft', 'bedrooms']]
    tmp = tmp.sub(tmp.mean()).div(tmp.std())
    return pd.concat([tmp, data['price']], axis=1)

def plot_convergence(costProgression, learningRate):
    """ Constructs a plot that demonstrates the convergence rate for a given learning rate. """

    x = np.arange(1, len(costProgression)+1)

    fig, ax = plt.subplots(1, 1, 1)
    ax.plot(x, costProgression)
    ax.set_xlabel('Number of iterations')
    ax.set_ylabel('J(Theta)')
    fig.title('Convergence rate for learning rate alpha = {0}'.format(learningRate))
    return

def plot_convergences(costProgressions, learningRates):
    """ Constructs a plot that compares convergence rates to respective learning rates. """

    learningRates = [str(alpha) for alpha in learningRates] # convert to string for column names
    costProgressions.columns = learningRates
    axes = costProgressions.plot()
    axes.legend(learningRates)
    return

def calculate_normal_equation(data):
    """ Use the analytical method to calculate the optimal parameter vector. """

    # split data for legibility and insert the intercept
    features = data.iloc[:, :-1]
    features.insert(0, 'intercept', 1)
    response = data.iloc[:, -1]

    # compute the normal equation
    # this is kinda like using *= or += but for matrices instead
    theta = np.linalg.pinv(np.dot(features.T, features))
    theta = np.dot(theta, features.T)
    theta = np.dot(theta, response)
    return theta

def optional_main():
    """ Main function for optional exercises."""

    loc = r"C:\Users\ashamlian\Downloads\machine-learning-ex1\ex1\ex1data2.txt"
    housingData = load_data(loc, [0,1], [2])

    normedHousingData = normalize_features(housingData)

    # get a range of alphas and find the cost evolutions for them
    testedLearningRates = [1, 0.3, .1, .03, .01, .003, .001]
    associatedCosts = []

    for alpha in testedLearningRates:

        _, costProgression = execute_gradient_descent(normedHousingData, learningRate=alpha, maxIters=100)
        associatedCosts.append(costProgression)

    associatedCosts = pd.concat(associatedCosts, axis=1) # now we have one nice pandas dataframe
    plot_convergences(associatedCosts, testedLearningRates) # notice the resulting scale of the plot, still HUGE

    # we are going to predict the price of a 1650 sq. ft, 3 bedroom house
    # let's take the theta of the best of the learning rates: 1.0
    # but don't forget that we have to normalize the prediction for this model
    newHouse = [1650, 3]
    normedNewHouse = [-0.4412732002552997, 0.22367546144324044] # i did this manually, using the training mean() and std()
    fittedTheta, _ = execute_gradient_descent(normedHousingData, learningRate=1) # maxiters defaults to 2000
    print('For a 1650 square foot, 3 bedroom house, the predicted price is: {0}'.format(predict(normedNewHouse, fittedTheta)))

    # and compare it to that of the normal equation
    fittedTheta = calculate_normal_equation(housingData)
    print('For a 1650 square foot, 3 bedroom house, the predicted price is: {0}'.format(predict(newHouse, fittedTheta)))

    return

if __name__ == '__main__':

    required_main()
    optional_main()


# My modules
import json_manager

import os, sys, random
from typing import Optional
import discord
from discord import app_commands
import aiocron

settings = json_manager.ReadFile(os.getcwd() + '/settings.json')
adminIds = settings['adminIds']
online_presence = settings['online-presence']

class MyClient(discord.Client):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(intents=intents)
        self.synced = False

    async def on_ready(self):
        if(not self.synced):
            await tree.sync()
            self.synced = True

            await changePresence()
            aiocron.crontab('0 */1 * * *', func=changePresence, start=True)
            print(f'Logged in as {client.user} (ID: {client.user.id}) \n------')

client = MyClient(intents=discord.Intents.default())
tree = app_commands.CommandTree(client)

#/- FUNCTIONS
async def changePresence():
    await client.change_presence(activity= discord.Game(online_presence[random.randint(0, len(online_presence) - 1)]));

@tree.command()
async def clear_all(interaction: discord.Interaction):
    """Clears all existing text from this channel"""
    await interaction.response.send_message(f'Clearing all chat...', ephemeral= True)
    await interaction.channel.purge()

@tree.command()
@app_commands.rename(amountToDelete = 'number')
@app_commands.describe(amountToDelete = 'Amount of messages to delete in this channel')
async def clear(interaction: discord.Interaction, amountToDelete: int):
    """Clears x amount of messages from this channel"""
    await interaction.response.send_message(f'Clearing {amountToDelete} message(s)...', ephemeral= True)

    msgs = []
    async for msg in interaction.channel.history(limit= amountToDelete):
        msgs.append(msg);

    await interaction.channel.delete_messages(msgs)

@tree.command()
@app_commands.rename(user = 'user')
@app_commands.describe(user = 'The selected user')
async def clear_user(interaction: discord.Interaction, user: discord.User):
    """Deletes all messages from a given user"""
    await interaction.response.send_message(f'Clearing all messages by {user}...', ephemeral= True)
    msgs = []
    async for msg in interaction.channel.history():
        if(msg.author.id != user.id): continue
        msgs.append(msg);
    await interaction.channel.delete_messages(msgs)

@tree.command(name="shutdown", description="Shuts the bot down")
async def self(interaction: discord.Interaction):
    if(not (interaction.user.id in adminIds)): # Stops anyone but the admins to turn shut off the bot.
        await interaction.response.send_message(f'You do not have permission to run that command!', ephemeral= True)
        return

    print(f'{interaction.user} has shutdown the bot!')
    await interaction.response.send_message(f'Shutting down...', ephemeral= True)
    sys.exit(0)

token = open('token.txt', 'r')
client.run(token.read())
token.close()


import os
import codecs
import re

def year_from_root(root_url):
    return int(root_url[-4:])

def index_files():
    findable_files = []

    for root, _, files in os.walk("./Past Papers"):
        if len(files) == 0:
            continue

        year = year_from_root(root)

        for file in files:
            file_name, exam_extention = os.path.splitext(file)
            if exam_extention == ".pdf_txt":
                findable_files.append(
                    (file_name, year, os.path.join(root, file)))

    return findable_files

# https://stackoverflow.com/questions/3862010/is-there-a-generator-version-of-string-split-in-python
# generator object for iterating over words in a string.
def word_iter(text):
    return (x.group(0) for x in re.finditer(r"\S+", text))

def matching_elements(token, val):
    return sum(1 if token[i] == val[i] else 0 for i in range(len(val)))

# Because the thing that read images->text might occasionally incorrectly read a letter
# we're gonna say if you match all but 1 characters from token2 against
# token1 then that's a match
def lossy_compare(token, word):
    threshold = max(len(token) - 1, 1)
    for i in range(0, max(1, len(word) - len(token) + 1)):
        matches = matching_elements(token, word[i:i + len(token)])
        if matches >= threshold:
            return True
    return False

def search_exam_paper(pages, tokens):
    results = {}
    for page_number, page in enumerate(pages, 2):
        if page.isspace():
            continue

        matches = 0
        for word in word_iter(page):
            for token in tokens:
                if lossy_compare(token, word):
                    matches += 1
                    break  # we can only match 1 token.

        if matches > 0:
            results["Page Number:" + str(page_number)] = matches
    return results

def search(files, query):
    query_token = query.split(' ')

    results = {}

    for file_name, year, url in files:
        with codecs.open(url, 'r', encoding="utf-8") as file:
            pages = file.read().split(":::::")

            matches = search_exam_paper(pages, query_token)

            if len(matches) == 0:
                continue

            if year not in results.keys():
                results[year] = {}

            results[year][file_name] = matches

    return results

# sure rank_years and rank_papers share alot of logic
# but i'm too tired to think of a clean way to merge their logic

def rank_years(matches):
    years = {}

    for year, papers in matches.items():
        frequency = 0

        for page_freq in papers.values():
            frequency += sum(freq for freq in page_freq.values())

        years[year] = frequency

    return sorted(years, key=lambda k: years[k], reverse=True)

def rank_papers(papers):
    p_freqs = {}

    for paper_name, pages in papers.items():
        p_freqs[paper_name] = sum(freq for freq in pages.values())

    return sorted(p_freqs, key=lambda k: p_freqs[k], reverse=True)

def output_matches(matches):
    ranked_years = rank_years(matches)
    print("- Top Matches:")

    for year in ranked_years:
        papers = rank_papers(matches[year])

        print("--- Year: %d" % year)
        for paper in papers:
            print("----- Paper: %s" % paper)
            for page in matches[year][paper]:
                print("------- %s" % page)

def run_search_loop():
    searchable_files = index_files()
    while True:
        query = input('Query > ')

        if query in ["quit", "exit"]:
            break

        if len(query) < 2:
            print("length of query must be >= 2")
            continue

        matches = search(searchable_files, query)

        if len(matches) == 0:
            print("No Matches found for query %s" % query)
            continue

        output_matches(matches)

if __name__ == "__main__":
    if not os.path.exists("./Past Papers"):
        print("Cannot find Past Papers directory")
    else:
        run_search_loop()


#-*- coding:utf-8 –*-

# chinese.py

import sqlite3, sys

def insert(a, b, c, d, e ):
	conn = sqlite3.connect('sayHello.db')
	c = conn.cursor()
	c.execute("INSERT INTO COMPANY (姓名,学号,性别,年龄,学院) \
                 VALUES ('%s', '%s', '%s', '%s', '%s' )" % (a, b, c, d, e));
	conn.commit()
	c = conn.cursor()
	cursor = c.execute("SELECT 姓名,学号,性别,年龄,学院  from COMPANY")
	values= cursor.fetchall()
	for row in values:
		print ("姓名 = "+str(row[0]))
		print ("学号= "+str(row[1]))
		print ("性别= "+str(row[2]))
		print ("年龄= "+str(row[3]))
		print ("学院 = "+str(row[4])), "\n";
	return "Operation done successfully";

if '__main__' == __name__:
	if 6 == len(sys.argv):
		args = sys.argv
		insert(args[1], args[2], args[3], args[4], args[5])


import cmd

# RUNNABLE_SHELL = '/bin/zsh'
# GIMP_EXECUTE = '/Applications/GIMP-2.10.app/Contents/MacOS/GIMP'
# GEGL_EXECUTE = '/usr/local/bin/gegl'
cmd.SetEnvConf('/bin/zsh', '/Applications/GIMP-2.10.app/Contents/MacOS/GIMP', '/usr/local/bin/gegl')

inf = '/Users/zhujiafeng/SIAT/gimp_test/origin.jpg'
of = '/Users/zhujiafeng/SIAT/gimp_test/gegimp_fu_test_now.jpg'

cmds = cmd.CmdSet(inf, of)
cmds.append(cmd.Cmd_gimp_color_balance(preserve_lum=True, yellow_blue=100))
cmds.append(cmd.Cmd_gegl_saturation(scale=1.0))
cmds.append(cmd.Cmd_gegl_color_temperature(original_temperature=5000.0, intended_temperature=5000.0))
cmds.exec()


class Solution(object):
    def isToeplitzMatrix(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: bool
        """
        m = len(matrix)
        if m == 0:
            return True
        n = len(matrix[0])
        if n == 0:
            return True
        for i in xrange(n):
            if self.check(matrix, 0, i, matrix[0][i]) == False:
                return False

        for j in xrange(1, m):
            if self.check(matrix, j, 0, matrix[j][0]) == False:
                return False
        return True

    def check(self, matrix, x, y, target):
        while x < len(matrix) and y < len(matrix[0]):
            if matrix[x][y] != target:
                return False
            x += 1
            y += 1
        return True


#!/usr/bin/env python3

import os
import argparse
import gc
import matplotlib.pyplot as plt
from matplotlib import animation
from tqdm.auto import tqdm
from typing import Optional, Tuple
from numpy.typing import NDArray
import numpy as np
from dataclasses import dataclass

# =============================================================

"""
Simple N-body simulation in Python
Based on Newton's Law of Gravity
"""

def parse_args():
    # script arguments
    parser = argparse.ArgumentParser(description="N-body Script",
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument(
        "-sv", "--save-video",
        action="store_true",
        help="To save a video of the simulation running"
    )

    config = vars(parser.parse_args())

    return config

# -----------------------------------------------------------

def get_accel(pos: NDArray, mass: NDArray, G: float, soft: float):
    """
    Calculating the acceleration on each particle
    ---------------------------
    Arguments:
    ---------------------------
    pos  : N x 3 matrix of positions of the N particles
    mass : N x 1 vector of masses of the N particles
    G    : Newton's gravitational constant
    soft : length at which to stop calculating the force
           and replacing it with a small value, since Newton's
           gravity becomes infinite as distance between 2 point
           particles tends to zero. Also called softening length.
    ---------------------------
    Returns:
    ---------------------------
    accel: N x 3 matrix of accelerations for the N particles
    """

    # positions of all the particles
    x, y, z = pos[:, 0:1], pos[:, 1:2], pos[:, 2:3]

    # pairwise particle separations: r_j - r_i
    dx, dy, dz = (x.T - x), (y.T - y), (z.T - z)

    print(dx.shape)
    # r^-3 for the pairwise particle separations
    inv_r3 = (dx ** 2 + dy ** 2 + dz ** 2 + soft ** 2)
    inv_r3[inv_r3 > 0] = inv_r3[inv_r3 > 0] ** (-1.5)
    # accelerations of the N particles
    ax = G * (dx * inv_r3) @ mass
    ay = G * (dy * inv_r3) @ mass
    az = G * (dz * inv_r3) @ mass
    # @ represents matrix multiplication

    # stack the accelerations
    accel = np.hstack((ax, ay, az))
    return accel

# --------------------------------------------------------

def get_E(pos: NDArray, vel: NDArray, mass: NDArray, G: float):
    """
    Get K.E. and P.E. of the simulation
    ---------------------------
    Arguments:
    ---------------------------
    pos  : N x 3 matrix of positions of the N particles
    vel  : N x 3 matrix of velocities of the N particles
    mass : N x 1 vector of masses of the N particles
    G    : Newton's gravitational constant
    ---------------------------
    Returns:
    ---------------------------
    KE   : Kinetic Energy of the System
    PE   : Potential Energy of the System
    """

    # Kinetic Energy of the system
    KE = 0.5 * np.sum(np.sum(mass * vel ** 2))

    # Potential Energy of the system
    # positions of all the particles
    x, y, z = pos[:, 0:1], pos[:, 1:2], pos[:, 2:3]

    # pairwise particle separations: r_j - r_i
    dx, dy, dz = (x.T - x), (y.T - y), (z.T - z)

    # r^-1 for all pairwise particle separations
    inv_r = np.sqrt(dx ** 2 + dy ** 2 + dz ** 2)
    inv_r[inv_r > 0] = 1 / inv_r[inv_r > 0]

    # we sum only over the upper triangle of the matrix
    # to count each pairwise interaction only once
    PE = G * np.sum(
        np.sum(
            np.triu(-(mass * mass.T) * inv_r, 1)
        )
    )

    return KE, PE

# --------------------------------------------------------

@dataclass
class NBody:
    N: int
    G: float
    soft: float
    mass: NDArray
    pos: NDArray
    vel: NDArray

# --------------------------------------------------------

def live_plot_nbody(
        particle_positions: NDArray,
        t_end: float,
        t_all: NDArray,
        KE_save: NDArray,
        PE_save: NDArray,
        fig_attrs: Tuple[plt.Figure, plt.GridSpec, plt.Axes, plt.Axes],
        sample_dir: Optional[str] = None,
        save_video: bool = False,
) -> None:
    if save_video and sample_dir is not None and not os.path.isdir(sample_dir):
        os.makedirs(sample_dir)

    fig, _grid, ax1, ax2 = fig_attrs

    ax1.set(
        xlabel="$x$", ylabel="$y$", xlim=(-2, 2), ylim=(-2, 2),
        xticks=[-2, -1, 0, 1, 2], yticks=[-2, -1, 0, 1, 2],
        aspect='equal',
    )

    ax2.set(
        xlabel="Time", ylabel="Energy",
        xlim=(0, t_end), ylim=(min(KE_save.min(), PE_save.min()),
                               max(KE_save.max(), PE_save.max())),
    )

    lines = ax1.plot([], [], "o", markersize=5, zorder=3)
    lines2 = ax1.plot([], [], "o", markersize=1, alpha=0.5)
    line_ke, = ax2.plot([], [], label="K.E.")
    line_pe, = ax2.plot([], [], label="P.E.")
    ax2.legend(fontsize=6, framealpha=0.5)

    t_all = np.array(t_all)

    def init():
        lines[0].set_data([], [])
        lines2[0].set_data([], [])
        line_ke.set_data([], [])
        line_pe.set_data([], [])
        return lines + [line_ke, line_pe]

    def animate(i):
        pos = particle_positions[:, :, i]
        lines[0].set_data(pos[:, 0], pos[:, 1])
        trails = np.array([i - 50, i - 40, i - 30, i - 20, i - 10, 0])
        trail_len = np.max(trails[np.where(trails >= 0)])
        xx = particle_positions[:, 0, trail_len:(i + 1)]
        yy = particle_positions[:, 1, trail_len:(i + 1)]
        lines2[0].set_data(xx, yy)
        line_ke.set_data(t_all[:i], KE_save[:i])
        line_pe.set_data(t_all[:i], PE_save[:i])
        return lines + [line_ke, line_pe]

    anim = animation.FuncAnimation(fig, animate, init_func=init,
                                   frames=len(t_all),
                                   blit=True)

    if save_video:
        anim.save(f"{sample_dir}/nbody.mp4", writer="ffmpeg", fps=60)

    plt.show()

# --------------------------------------------------------

def run_simulation(nbody: NBody, t_end: float, dt: float):
    """
    Runs the simulation for a specified duration.
    ---------------------------
    Arguments:
    ---------------------------
    nbody     : Nbody class object
    t_end     : Duration of simulation
    dt        : time step for simulation
    ---------------------------
    Returns:
    ---------------------------
    Saves particle positions, velocities, energies at a specified frequency
    """

    # set up arrays to store data
    N_iter = int(np.ceil(t_end / dt))
    pos_save = np.zeros((nbody.N, 3, N_iter + 1))
    KE_save = np.zeros(N_iter + 1)
    PE_save = np.zeros(N_iter + 1)
    time = np.zeros(N_iter + 1)

    # get initial acceleration and energies
    accel = get_accel(nbody.pos, nbody.mass, nbody.G, nbody.soft)
    KE, PE = get_E(nbody.pos, nbody.vel, nbody.mass, nbody.G)

    # save initial conditions
    pos_save[:, :, 0] = nbody.pos
    # vel_save[:,:,0] = nbody.vel
    KE_save[0] = KE
    PE_save[0] = PE

    # initialize time
    t = 0.0
    i = 0

    with tqdm(total=N_iter) as pbar:
        while i < N_iter:
            # update positions
            nbody.pos = nbody.pos + (nbody.vel * dt) + (0.5 * accel * dt ** 2)

            # find new acceleration
            accel_new = get_accel(nbody.pos, nbody.mass, nbody.G, nbody.soft)

            # update velocities
            nbody.vel = nbody.vel + 0.5 * (accel + accel_new) * dt

            pos_save[:, :, i + 1] = nbody.pos
            # vel_save[:,:,i+1] = nbody.vel
            KE, PE = get_E(nbody.pos, nbody.vel, nbody.mass, nbody.G)
            KE_save[i + 1] = KE
            PE_save[i + 1] = PE
            time[i + 1] = t

            # update acceleration
            accel = accel_new

            # update time
            t += dt
            i += 1

            # update progress bar
            pbar.update(1)

    # return saved data
    return pos_save, KE_save, PE_save, time

# --------------------------------------------------------

def main():
    config = parse_args()
    save_video = config["save_video"]

    N = 100  # Number of particles
    t_end = 10.  # Time at which the sim ends
    dt = 0.01  # Timestep
    soft = 0.1  # softening length
    G = 1.  # Newton's gravitational constant

    rng = np.random.default_rng(seed=42)
    mass = 20. * np.ones((N, 1)) / N  # total mass of the N particles
    pos = rng.standard_normal((N, 3))  # random positions
    vel = rng.standard_normal((N, 3))

    nbody = NBody(N, G, soft, mass, pos, vel)

    pos, KE_save, PE_save, t_all = run_simulation(nbody, t_end, dt)

    fig = plt.figure(figsize=(4, 6), dpi=100)
    grid = plt.GridSpec(3, 1, wspace=0, hspace=0.7)
    ax1 = plt.subplot(grid[0:2, 0])
    ax2 = plt.subplot(grid[2, 0])

    fig_attrs = (fig, grid, ax1, ax2)

    live_plot_nbody(
        particle_positions=pos,
        t_end=t_end,
        t_all=t_all,
        KE_save=KE_save,
        PE_save=PE_save,
        fig_attrs=fig_attrs,
        sample_dir='./data',
        save_video=save_video,
    )

# --------------------------------------------------------

if __name__ == "__main__":
    main()
    gc.collect()


#Entrada e saída de dados

nome = input ("Texto que será mostrado pro usuário")
print ('texto')

#Variáveis - Servem pra armazenar valores

n_clientes = 150
cliente01 = "Tiago"
saldoCliente = 1.500

#Tipos de dados
##Str

nome = "Textos ou String"
nome2 = 'Textos ou Strings'

##Int

valor = 150

##Float

valor2 = 15.000

##Bool

bool01 = True
bool02 = False

##Operadores

###Operadores Aritméticos

#Soma

10 + 20

#Subtração

150 - 149

#Divisão

150 / 300

#Multiplicação

150 * 399

#Divisão Inteira

150 // 5

#Resto da Divisão

150 % 5

##### Review #####

#Variaveis

var=1 #Int
var2='String' #Str
var3=3.6 #Float
var4=True #Bool

#Entrada e saída de dados

nome = input('Qual é o seu nome')
print(150)
print(14.5)
print('Teste')

#Tipos de dados

#Operadores

#Aritmético

n1 = 5
n2 = 10

n1 + n2 #Soma
n2 - n1 #Subtração
n1 * n2 #Multiplicação
n1 / n2 #Divisão
n1 // n2 #Divisão Inteira
#Atribuição

n1 = 100
n1 += 100
n1 -= 100
n1 *= 100
n1 /= 100
n1 //= 100
n1 %= 100
n1 **= 100

#Comparação

n1 == n2
n1 != n2
n1 > n2
n1 < n2

#Strings - Conjunto de caracteres


"""fire URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
from login import views
from login import user, messages, device, video

user_patterns = [
    path('login/', user.login_controller),
    path('check_login/', user.check_is_login_and_get_username_controller),
    path('info/', user.get_user_info_controller)
]
message_patterns = [
    path('', messages.messages),
    path('info/', messages.get_message_info_controller),
    path('approve', messages.approve_message_controller),
]

device_patterns = [
    path('', device.device_controller),
    path('all/', device.get_all_device_controller)
]

video_patterns = [
    path('', video.videos_controller)
]

api_patterns = [
    path('user/', include(user_patterns)),
    path('messages/', include(message_patterns)),
    path('devices/', include(device_patterns)),
    path('videos/', include(video_patterns)),
]
urlpatterns = [
    path('admin/', admin.site.urls),
    path('messages/', views.MessageAmount),
    path('warning/true/', views.dealTrue),
    path('warning/false/', views.dealFalse),
    path('warning/', views.warning),
    path('login/', views.login),
    path('monitor/', views.monitor),
    path('overview/', views.overview),
    path('logout/', views.logout),
    path('data', views.DealData),
    path('conf/', views.conf),
    path('wechat', views.wechat),
    path('user_config', views.getUserConf),
    path('', TemplateView.as_view(template_name='index.html')),
    path('api/', include(api_patterns))
]


# -*- coding: cp1251 -*-
import tkinter as tk
from tkinter import ttk
from tkinter.scrolledtext import ScrolledText
import numpy as np
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

def create():
    global swarm
    global velocity
    global pbest_pos
    global pbest_value
    global gbest_pos
    global gbest_value
    global k
    global bounds
    global dim
    global mystat
    mystat = []
    ax.clear()
    canvas.draw()
    dim = int(mutant_entry.get())
    k_entry.delete(0, tk.END)
    k_entry.insert(0, 0)
    k = 0
    bounds = np.array([int(minn_entry.get()) * dim, int(maxx_entry.get()) * dim])
    swarm = np.random.uniform(bounds[0], bounds[1], (int(chromoval_entry.get()), dim))
    velocity = np.zeros((int(chromoval_entry.get()), dim))
    pbest_pos = swarm.copy()
    pbest_value = np.array([np.inf] * int(chromoval_entry.get()))
    gbest_pos = np.zeros(dim)
    gbest_value = np.inf

def draw_graph(points):
    ax.clear()
    x = [point[0] for point in points]
    y = [point[1] for point in points]
    ax.scatter(x, y)
    canvas.draw()

def function(x):
    return 8*x[0]**2+4*x[0]*x[1]+5*x[1]**2

def main():
    global swarm
    global velocity
    global pbest_pos
    global pbest_value
    global gbest_pos
    global gbest_value
    global k
    global bounds
    global mystat
    gener_val = int(generations_var.get())
    chromo_val = int(chromoval_entry.get())
    k += gener_val
    k_entry.delete(0, tk.END)
    k_entry.insert(0, k)
    w = float(inercia_entry.get())
    c1 = c2 = float(speed_entry.get())
    for i in range(gener_val):
        f = np.array([function(x) for x in swarm])

        mask = f < pbest_value
        pbest_value[mask] = f[mask]
        pbest_pos[mask] = swarm[mask]

        mask = pbest_value < gbest_value
        if np.any(mask):
            gbest_value = np.min(pbest_value)
            gbest_pos = pbest_pos[np.argmin(pbest_value)]
        if gbest_value < 80 :
            mystat.append(gbest_value)

        r1 = np.random.rand(chromo_val, dim)
        r2 = np.random.rand(chromo_val, dim)
        velocity = w * velocity + c1 * r1 * (pbest_pos - swarm) + c2 * r2 * (gbest_pos - swarm)
        swarm = swarm + velocity

        swarm = np.clip(swarm, bounds[0], bounds[1])

        swarm = np.where(swarm < bounds[0], bounds[0], swarm)
        swarm = np.where(swarm > bounds[1], bounds[1], swarm)
    draw_graph(swarm)
    output_text2.delete(1.0, tk.END)
    output_text2.insert(tk.END, "№, Значение в лучшей точке, Лучшая точка \n")
    for i in range(chromo_val):
        line = "{} , {}, {}".format(i,pbest_value[i].round(4), pbest_pos[i].round(4)) + "\n"
        output_text2.insert(tk.END, line)

    resx = "Minimum found: {}".format(gbest_pos.round(6))
    resy = "Minimum value: {}".format(gbest_value.round(6))
    output_text1.insert("1.0", resx + "\n")
    output_text1.insert("1.0", resy + "\n")
    output_text1.insert("1.0", "************************\n")
    print(k)
    if gbest_value <= 10**(-3):
        print("Найденный минимум", gbest_pos)
        print("Значение минимума", gbest_value)
        quit()

def delete():
    output_text1.delete("0.0", tk.END)
    ax.clear()
    canvas.draw()

root = tk.Tk()
root.title("Роевой алгоритм")
root.geometry("1200x800")

left_frame = ttk.Frame(root, padding=10)
right_frame = ttk.LabelFrame(root, padding=10, text="Особи")

root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)

left_frame.grid(row=0, column=0, sticky="nsew")
right_frame.grid(row=0, column=1, sticky="nsew")

frame1 = ttk.LabelFrame(left_frame, padding=10, text="Параметры")
frame11 = ttk.LabelFrame(left_frame, padding=10, text="Количество шагов")
frame2 = ttk.LabelFrame(left_frame, padding=10, text="Управление")
frame3 = ttk.LabelFrame(left_frame, padding=10, text="Результаты")
frame1.pack(side="top", fill="x", padx=5, pady=5)
frame11.pack(side="top", fill="x", padx=5, pady=5)
frame2.pack(side="top", fill="x", padx=5, pady=5)
frame3.pack(side="top", fill="both", expand=True, padx=5, pady=5)

combo_label = ttk.Label(frame1, text="Функция")
combo = ttk.Combobox(frame1, width="40")
combo['value'] = ("8*x[0]**2+4*x[0]*x[1]+5*x[1]**2",)
combo.current(0)

mutant_label = ttk.Label(frame1, text="Размерность")
mutant_entry = ttk.Spinbox(frame1, from_=0, to=10)
mutant_entry.insert(0, "2")
chromoval_label = ttk.Label(frame1, text="Количество особей")
chromoval_entry = ttk.Spinbox(frame1, from_=0, to=10000)
chromoval_entry.insert(0, "50")
minn_label = ttk.Label(frame1, text="Левая граница области поиска")
minn_entry = ttk.Spinbox(frame1, from_=-10000, to=10000)
minn_entry.insert(0, "-50")
maxx_label = ttk.Label(frame1, text="Правая граница области поиска")
maxx_entry = ttk.Spinbox(frame1, from_=-10000, to=10000)
maxx_entry.insert(0, "50")
inercia_label = ttk.Label(frame1, text="Итерационный вес")
inercia_entry = ttk.Spinbox(frame1, from_=-100, to=100)
inercia_entry.insert(0, "0.7")
speed_label = ttk.Label(frame1, text="Коэффициент ускорения")
speed_entry = ttk.Spinbox(frame1, from_=-100, to=100)
speed_entry.insert(0, "1.4")

combo_label.grid(row=0, column=0)
combo.grid(row=1, column=0)

mutant_label.grid(row=2, column=0, padx=0, pady=5)
mutant_entry.grid(row=2, column=1, padx=5, pady=5)

chromoval_label.grid(row=3, column=0, padx=0, pady=5)
chromoval_entry.grid(row=3, column=1, padx=5, pady=5)

minn_label.grid(row=4, column=0, padx=0, pady=5)
minn_entry.grid(row=4, column=1, padx=5, pady=5)

maxx_label.grid(row=5, column=0, padx=0, pady=5)
maxx_entry.grid(row=5, column=1, padx=5, pady=5)

inercia_label.grid(row=6, column=0, padx=0, pady=5)
inercia_entry.grid(row=6, column=1, padx=5, pady=5)

speed_label.grid(row=7, column=0, padx=0, pady=5)
speed_entry.grid(row=7, column=1, padx=5, pady=5)

generations_var = tk.IntVar()
spin = ttk.Spinbox(frame11, from_=10, to=1000, width=10, textvariable=generations_var)
radio_button0 = ttk.Radiobutton(frame11, text="1", variable=generations_var, value=1)
radio_button1 = ttk.Radiobutton(frame11, text="10", variable=generations_var, value=10)
radio_button2 = ttk.Radiobutton(frame11, text="100", variable=generations_var, value=100)
radio_button3 = ttk.Radiobutton(frame11, text="500", variable=generations_var, value=500)
radio_button0.grid(row=0, column=0, padx=1, pady=5)
radio_button1.grid(row=0, column=1, padx=1, pady=5)
radio_button2.grid(row=0, column=2, padx=1, pady=5)
radio_button3.grid(row=0, column=3, padx=1, pady=5)
spin.grid(row=0, column=4, padx=5, pady=5)

k = 0
create_button = ttk.Button(frame2, text="Создать особей", command=create)
calculate_button = ttk.Button(frame2, text="Посчитать шаги", command=main)
k_label = ttk.Label(frame2, text="Пройдено шагов:")
k_entry = ttk.Entry(frame2)
create_button.grid(row=2, column=0, padx=5, pady=5)
calculate_button.grid(row=2, column=1, padx=5, pady=5)
k_label.grid(row=3, column=0, padx=5, pady=5)
k_entry.grid(row=3, column=1, padx=5, pady=5)
output_text1 = ScrolledText(frame3, width=20, height=8)
output_text1.pack(side="top", fill="both", expand=True)
delbutton = ttk.Button(frame3, text="Очистить", command=delete)
delbutton.pack(side="bottom", fill="x")
output_text2 = ScrolledText(right_frame, width=50, height=20)
output_text2.pack()

fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=right_frame)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

dim = 2
bounds = np.array([int(minn_entry.get()) * dim, int(maxx_entry.get()) * dim])
swarm = np.empty((int(chromoval_entry.get()), dim))
velocity = np.empty((int(chromoval_entry.get()), dim))
pbest_pos = swarm.copy()
pbest_value = np.array([np.inf] * int(chromoval_entry.get()))
gbest_pos = np.zeros(dim)
gbest_value = np.inf
generations_var.set(1)
mystat = []

root.mainloop()