from django.shortcuts import render, HttpResponse, redirect
from django.contrib.auth.decorators import login_required
from dc_info import models
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from dc_info.views.commonality import CustomPaginator, add_cabinet_log
from dc_info.utils import handel_excel
import json
import os

# 前端获取机柜信息页面
def get_cabinet_info(request, dcname, idcname, *args, **kwargs):
    dc_obj = models.DcInfo.objects.all()
    customer_obj = models.Customer.objects.all()
    search_cabinet = request.GET.get('search_cabinet', None)  # 获取用户搜索的机柜信息
    current_page = request.GET.get('page', '1')  # 获取用户点击的页码
    filter = request.GET.get('filter', None)  # 获取过滤信息
    addcabinet = request.GET.get('addcabinet', None)  # 添加机柜的时候跳转此页码会传入此参数
    if search_cabinet:
        cabinet_obj = dc_obj.get(
            name=dcname).idcinfo_set.get(
            name=idcname).cabinet_set.filter(
            number__icontains=search_cabinet)
    else:
        if filter == 'all' or not filter:
            cabinet_obj = dc_obj.get(name=dcname).idcinfo_set.get(
                name=idcname).cabinet_set.all().order_by('number')  # 获取机柜信息
        else:
            filter = int(filter)
            cabinet_obj = dc_obj.get(
                name=dcname).idcinfo_set.get(
                name=idcname).cabinet_set.all().filter(
                customer=models.Customer.objects.get(
                    pk=filter)).order_by('number')
    if current_page == 'all':
        paginator = CustomPaginator(1, 11, cabinet_obj, cabinet_obj.count())
    else:
        paginator = CustomPaginator(current_page, 11, cabinet_obj, 20)
    try:
        data_list = paginator.page(current_page)  # 分页
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    return render(request,
                  'dc_info/cabinetinfo.html',
                  {"dc_obj": dc_obj,
                   'customer_obj': customer_obj,
                   'dcname': dcname,
                   'idcname': idcname,
                   'page_list': data_list,
                   'filter': filter,
                   'addcabinet': addcabinet})

# 添加机柜
def create_cabinet(request, dcname, idcname):
    dc_obj = models.DcInfo.objects.all()
    customer_obj = models.Customer.objects.all()
    erro = ''
    if request.method == 'GET':
        return render(request,
                      'dc_info/create_cabinet.html',
                      {"dc_obj": dc_obj,
                       'customer_obj': customer_obj,
                       'dcname': dcname,
                       'idcname': idcname,
                       'erro': erro})
    elif request.method == 'POST':
        a = ''
        cabinet_num = request.POST.get('number')
        open_date = request.POST.get('open_date')
        customer_id = int(request.POST.get('customer'))
        if models.Cabinet.objects.filter(
                number=cabinet_num,
                idc__name=idcname,
                idc__dc__name=dcname).count() != 0:
            erro = '%s机柜已经存在，无需重复添加' % cabinet_num
            return render(request,
                          'dc_info/create_cabinet.html',
                          {"dc_obj": dc_obj,
                           'customer_obj': customer_obj,
                           'dcname': dcname,
                           'idcname': idcname,
                           'erro': erro})
        else:
            idc = models.IDCInfo.objects.get(name=idcname, dc__name=dcname)
            customer = customer_obj.get(pk=customer_id)
            a = models.Cabinet.objects.create(
                idc=idc,
                number=cabinet_num,
                customer=customer,
                open_date=open_date)
            # 添加机柜操作日志
            add_cabinet_log(request, 1, a)
        return redirect('/cabinet/%s/%s/?addcabinet=%s' % (dcname, idcname, a))

# 删除机柜
def delete_cabinet(request):

    if request.method == 'POST':
        idlist = []
        delete_list = ''
        for i in request.POST.values():
            idlist.append(int(i))
        cabinet_queryset = models.Cabinet.objects.filter(pk__in=idlist)
        for a in cabinet_queryset:
            delete_list += '%s,' % a
            # 添加机柜删除日志
            add_cabinet_log(request, 0, a)
            a.delete()
        return HttpResponse(json.dumps(
            {'status': True, 'delete_list': delete_list, 'delete_id': idlist}))

# 批量导入机柜
def import_cabinet(request, dcname, idcname):
    dc_obj = models.DcInfo.objects.all()
    customer_obj = models.Customer.objects.all()
    if request.method == 'GET':
        return render(request,
                      'dc_info/import_cabinet.html',
                      {"dc_obj": dc_obj,
                       'customer_obj': customer_obj,
                       'dcname': dcname,
                       'idcname': idcname})
    elif request.method == 'POST':
        cabinet_files = request.FILES.get('cabinet_excel')
        info = {'status': False}
        if cabinet_files:
            file_suffix = os.path.splitext(cabinet_files.name)[1]
            if file_suffix in ('.xls', '.xlsx'):
                try:
                    info = handel_excel.handel_import_cabinet(
                        cabinet_files.file)  # 交给函数出来文件
                except IOError as e:
                    info['erro'] = '文件异常(%s)' % e
                else:
                    if info['status']:
                        info['date'] = []
                        for i in info['cabinet_objlist']:
                            a = models.Cabinet.objects.create(**i)
                            add_cabinet_log(request, 1, a)
                            info['date'].append(a)
            else:
                info['erro'] = '上传文件只能是 .xls 和 .xlsx 格式'
        return render(request,
                      'dc_info/import_cabinet.html',
                      {"dc_obj": dc_obj,
                       'customer_obj': customer_obj,
                       'dcname': dcname,
                       'idcname': idcname,
                       'info': info})

# 主页获取机柜操作日志
def customet_cabinet_log(request):
    current_page = request.GET.get('page', 1)
    cabinet_number = request.GET.get('cabinet_number')
    customer = request.GET.get('customer', None)
    cabinet_log_obj = models.CabinetLog.objects.all()
    context = {"filter": {}}
    if cabinet_number:
        if customer:
            context["filter"] = {
                'cabinet_number': cabinet_number,
                'customer': customer}
            cabinet_log_obj = cabinet_log_obj.filter(
                cabinet_number=cabinet_number,
                customer__name=customer).order_by('handle_date').reverse()
        else:
            context["filter"] = {'cabinet_number': cabinet_number}
            cabinet_log_obj = cabinet_log_obj.filter(
                cabinet_number=cabinet_number).order_by('handle_date').reverse()
    else:
        if customer:
            context["filter"] = {'customer': customer}
            cabinet_log_obj = cabinet_log_obj.filter(
                customer__name=customer).order_by('handle_date').reverse()
        else:
            cabinet_log_obj = cabinet_log_obj.order_by('handle_date').reverse()

    paginator = CustomPaginator(current_page, 5, cabinet_log_obj, 11)
    try:
        data_list = paginator.page(current_page)
    except PageNotAnInteger:
        data_list = paginator.page(1)
    except EmptyPage:
        data_list = paginator.page(paginator.num_pages)
    context['page_list'] = data_list
    return render(request, 'dc_info/customer_cabinet_log.html', context)


from nodoPrioridad import Prioridad

class listaPriori:
    def __init__(self):
        self.head=None

    def getHead(self):
        return self.head

    def agregaComponente(self,nodo):
        aux=self.head

        while(True):
            if self.head==None:
                self.head=nodo
                break
            elif aux.getSiguiente()==None:
                aux.setSiguiente(nodo)
                break
            else:
                aux=aux.getSiguiente()

    def pop(self):
        if self.head==None:
            print('lista Vacia')
        aux=self.head
        self.head=aux.getSiguiente()
        aux=None


"""This is the model that represents a file as a tile. These tiles can then be arranged to become a grid.
    Has all file information and grid painting info. This is effectively a file.
"""
from PyQt6 import QtCore, QtGui
from PyQt6.QtWidgets import  QGraphicsSceneMouseEvent, QGraphicsWidget, QGraphicsRectItem, QGraphicsItem
from PyQt6.QtCore import  Qt, QLine, QRectF, QEvent, QRunnable, pyqtSignal, QObject
from PyQt6.QtGui import  QColor, QBrush, QPainterPath, QPen
from queue import Queue

from models import hydrus_api

from controller.widgets.center_text_box_widget import CenterTextBox

class FileTile(QGraphicsItem):
    """Custom widget to reprsent a tile in the grid of images.

    Args:
        QGraphicsWidget (QGraphicsWidget): inheritence
    """

    tile_background_color = QColor(210, 210, 210)
    selected_background_color = QColor(179, 236, 248)
    highlight_tile = False
    ordered_tiles = None

    def __init__(self, file_metadata: {}, tile_width: int, tile_height: int, size_type: str):
        """Creates a new tile to display the file and all file information

        Args:
            file_metadata ({}}): file metadata to parse
            tile_width (int) : width of tile
            tile_height (int): heeight of tile
        """
        super().__init__()
        self.process_metadata(file_metadata)
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.size_type = size_type
        self.pivot_tile = False
        self.highlight_tile = False

        self.setFlag(QGraphicsWidget.GraphicsItemFlag.ItemIsSelectable)

        # split tile into image and label according to hard coded ratios here
        self.image_height = int(self.tile_height * .9)
        self.text_height = int(self.tile_height * .1)

        # build textbox child widget
        # calculate text to say
        size = self.size_bytes
        if self.size_type == "GB":
            size = size / (1024**3)
        if self.size_type == "MB":
            size = size / (1024**2)
        size = round(size, 2)
        self.calculated_size = size
        self.child_text_box = CenterTextBox(str(size) +" "+ self.size_type,
                    self.tile_width, self.text_height)
        self.child_text_box.setParentItem(self)
        self.child_text_box.setPos(0, self.tile_height-self.text_height)

        # get the thumbnail and build it preemptively
        pixmap = hydrus_api.get_file_thumbnail(self.file_id)
        self.scaled_pixmap = pixmap.scaled(
            tile_width,
            tile_height,
            Qt.AspectRatioMode.KeepAspectRatio
        )

    def paint(self, painter, option=None, widget=None):
        """Overloading of the QGraphicsWidget paint string. See original
        """
        # paint background
        if self.highlight_tile:
            color = self.selected_background_color
        else:
            color = self.tile_background_color

        painter.setBrush(QBrush(color))
        painter.drawRect(0, 0, self.tile_width, self.tile_height)

        # paint outline if selected
        if self.highlight_tile:
            painter.setBrush(Qt.BrushStyle.NoBrush)
            pen = QPen(Qt.GlobalColor.blue)
            pen.setWidth(5)
            pen.setJoinStyle(Qt.PenJoinStyle.MiterJoin)
            painter.setPen(pen)
            painter.drawRect(0, 0, self.tile_width, self.tile_height)

        # paint textbox again
        self.child_text_box.setParentItem(self)
        self.child_text_box.setPos(0, self.tile_height-self.text_height)
        self.child_text_box.update()

        x = (self.tile_width - self.scaled_pixmap.width()) / 2 # center of image at center of tile
        painter.drawPixmap(int(x), 1, self.scaled_pixmap)

    def mousePressEvent(self, event: QGraphicsSceneMouseEvent) -> None:
        """Overload original
        """
        modifier = event.modifiers()
        pivot_tile = None
        last_clicked_tile = None
        for tile in self.ordered_tiles:
            if modifier == Qt.KeyboardModifier.ShiftModifier:
                if tile.isSelected():  #find last clicked tile
                    pivot_index = self.ordered_tiles.index(tile)
                    last_clicked_tile = tile
                if tile.pivot_tile is True: # finds the prexisting pivot
                    pivot_tile = tile
                    pivot_index = self.ordered_tiles.index(tile)
            elif modifier == Qt.KeyboardModifier.NoModifier:
                #unhighlight all other tiles
                tile.highlight_tile = False
                tile.pivot_tile = False
                tile.update()
            elif modifier == Qt.KeyboardModifier.ControlModifier:
                if tile.pivot_tile is True: #clears any prexisting pivot since
                    # we are becoming the new one
                    tile.pivot_tile = False
            if tile.isSelected():
                tile.setSelected(False)
        self.setSelected(True)
        if pivot_tile is None:
            self.pivot_tile = True

        # handle control click for self
        if modifier == Qt.KeyboardModifier.ControlModifier and self.highlight_tile is True:
            self.highlight_tile = False
        elif modifier == Qt.KeyboardModifier.ControlModifier and self.highlight_tile is False:
            self.highlight_tile = True
            self.pivot_tile = True
        else:
            self.highlight_tile = True

        # handle shift click
        if modifier == Qt.KeyboardModifier.ShiftModifier and pivot_tile:
            pivot_index = self.ordered_tiles.index(pivot_tile)
            self_index = self.ordered_tiles.index(self)
            # if last_clicked_tile wasn't pivot, then we must dehighlight other tiles
            if pivot_tile is not last_clicked_tile and last_clicked_tile is not None:
                last_clicked_index = self.ordered_tiles.index(last_clicked_tile)
                for index, tile in enumerate(self.ordered_tiles):
                    if last_clicked_index <= index <= pivot_index or pivot_index <= index <= last_clicked_index:
                        tile.highlight_tile = False
                        tile.update()
            # highlight all new tiles from pivot to self
            for index, tile in enumerate(self.ordered_tiles):
                if self_index <= index <= pivot_index or pivot_index <= index <= self_index:
                    tile.highlight_tile = True
                    tile.update()

    def boundingRect(self):
        """Overloaded define bounding rect
        """
        return QRectF(0, 0, self.tile_width, self.tile_height)

    def set_ordered_tiles(self, tiles:list[QGraphicsItem]):
        self.ordered_tiles = tiles

    def process_metadata(self, file_metadata):
        self.file_id = file_metadata["file_id"]
        self.file_type, self.extension = file_metadata["mime"].split("/")
        self.size_bytes = file_metadata["size"]
        self.tags = file_metadata["tags"]
        self.ratings = file_metadata["ratings"]
        self.notes = file_metadata["notes"]
        self.unix_modified_time = file_metadata["time_modified_details"]["local"]

        self.storage_tags = {}
        for service_id in self.tags:
            self.storage_tags[service_id] = self.tags[service_id]["storage_tags"]

class WorkerSignals(QObject):
    """Miniclass to allow signalling
    """
    finished = pyqtSignal()

class FileTileCreatorWorker(QRunnable):
    """FileTile worker to create filetiles without slowing applicaiton too much
    Args:
        QRunnable (_type_): overriden thread type
    """
    def __init__(self,
            file_metadata:{},
            tile_width:int,
            tile_height:int,
            file_queue:Queue,
            size_type:str) -> None:
        """Worker to thread the creation of file_tiles

        Args:
            file_metadata ({}): json metadata in dict format
            self.tile_width (int): width of the display tile
            self.tile_height (int): height of the display tile
            file_queue (file_queue): thread safe queue to put our complete objs in
            size_type (str): pass in size type from input
        """
        super().__init__()
        self.file_metadata = file_metadata
        self.tile_width = tile_width
        self.tile_height = tile_height
        self.file_queue = file_queue
        self.size_type = size_type
        self.signals = WorkerSignals()

    def run(self) -> None:
        """Overwrites thread run to instead put an filetile object with the given data
        """
        self.file_queue.put(
            FileTile(self.file_metadata,
                     self.tile_width,
                     self.tile_height,
                     self.size_type))
        self.signals.finished.emit()


from PyQt5 import QtWidgets, QtCore
import sys  # sys нужен для передачи argv в QApplication
import os  # Отсюда нам понадобятся методы для отображения содержимого директорий
import Error
import numpy as np
import math
import popara_wind
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
import fin
import matplotlib.dates as mdates
import datetime as dt
import csv

class AlignDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super(AlignDelegate, self).initStyleOption(option, index)
        option.displayAlignment = QtCore.Qt.AlignCenter

class Poparno(QtWidgets.QMainWindow, popara_wind.Ui_MainWindow):
    def __init__(self, mass_kriter, mass_alter, i, flag, DATA):
        # Это здесь нужно для доступа к переменным, методам
        # и т.д. в файле design.py
        super().__init__()
        self.setupUi(self)  # Это нужно для инициализации нашего дизайна
        # self.tableWidget.setHorizontalHeaderLabels(mass_alter)
        # self.tableWidget.setVerticalHeaderLabels(mass_alter)
        if i == -1:
            self.label.setText('')
            mass_alter, mass_kriter = mass_kriter, mass_alter
            DATA = []
        else:
            self.label.setText(mass_kriter[i])
        LEN = len(mass_alter)
        if LEN < 10:
            self.setGeometry(0, 0, LEN * 150 + 300, LEN * 70 + 60)
        else:
            self.setGeometry(0, 0, 9 * 180 + 300, 9 * 100 + 300)

        self.btn_next.clicked.connect(
            lambda: self.dalee(mass_kriter, mass_alter, i, flag, DATA))  # Выполнить функцию при нажатии кнопки
        self.btn_graf.setEnabled(False)
        self.btn_next.setEnabled(False)
        self.pushButton.setEnabled(False)
        self.tableWidget.setRowCount(LEN)
        self.tableWidget.setColumnCount(LEN)
        self.btn_graf.clicked.connect(lambda: self.make_graf_pie(mass_alter))
        self.pushButton.clicked.connect(lambda: self.make_graf_stolb(mass_alter))
        delegate = AlignDelegate(self.tableWidget)
        self.tableWidget.setItemDelegate(delegate)
        stylesheet = "::section{Background-color:rgb(176,196,222)}"
        self.tableWidget.horizontalHeader().setStyleSheet(stylesheet)
        self.tableWidget.verticalHeader().setStyleSheet(stylesheet)
        if i == -1:
            TEXT = 'Критерии: \n'
            self.label.setText('Попарная оценка критериев')
            if flag == 1:
                data = self.check_data(-1)
                for j in range(LEN):
                    for q in range(LEN):
                        item = QtWidgets.QTableWidgetItem(data[j][q])
                        self.tableWidget.setItem(j, q, item)

            else:
                data = np.eye(LEN)
                for j in range(LEN):
                    for q in range(LEN):
                        item = QtWidgets.QTableWidgetItem(str(int(data[j][q])))
                        self.tableWidget.setItem(j, q, item)

        else:
            TEXT = 'Альтернативы: \n'
        for q in range(len(mass_alter)):
            TEXT += str(q + 1) + ': ' + mass_alter[q] + '\n'
        self.textEdit.setText(TEXT)
        if flag == 0:
            data = np.eye(LEN)
            for j in range(LEN):
                for q in range(LEN):
                    item = QtWidgets.QTableWidgetItem(str(int(data[j][q])))
                    self.tableWidget.setItem(j, q, item)
        else:
            data = self.check_data(i)
            for j in range(LEN):
                for q in range(LEN):
                    item = QtWidgets.QTableWidgetItem(data[j][q])
                    self.tableWidget.setItem(j, q, item)
        self.btn_chek.clicked.connect(lambda: self.CHEK(LEN))

    def dalee(self, mass_kriter, mass_alter, i, flag, DATA):
        # print(len(mass_alter))
        data = self.lineEdit.text().split(' ')[4:4 + len(mass_alter)]
        # print(data)
        new_data = []
        for r in data:
            r = r[:-1]
            new_data.append(float(r))
        data = dict(zip(mass_alter, new_data))
        DATA.append(new_data)
        if i == -1:
            sorted_dict = {}
            sorted_keys = sorted(data, key=data.get)
            for w in sorted_keys:
                sorted_dict[w] = data[w]
            # print(sorted_dict)
            temp_mass = []
            for j in sorted_dict.keys():
                temp_mass.append(j)
            mass_alter = temp_mass
            # print(mass_alter)
            mass_alter, mass_kriter = mass_kriter, mass_alter
        global wind
        i += 1
        if i < len(mass_kriter):
            wind = Poparno(mass_kriter, mass_alter, i, flag, DATA)
            wind.show()
            self.close()
        else:
            alter = []
            krit = DATA[0]
            krit.sort()
            krit = np.array(krit)
            for k in range(1, len(DATA)):
                alter.append(DATA[k])
            alter = np.array(alter).T
            rez = alter.dot(krit[np.newaxis, :].T)
            print(rez)
            print(mass_alter)
            global wind2
            wind2 = fin.FIN(rez, mass_alter)
            wind2.show()
            self.close()

    def CHEK(self, LEN):
        data = []
        try:
            for j in range(LEN):
                data1 = []
                for q in range(LEN):
                    if self.tableWidget.item(j, q).text() == '':
                        Error.ERROR(5)
                        return 0
                    if '/' in self.tableWidget.item(j, q).text():
                        temp2 = self.tableWidget.item(j, q).text().split('/')
                        temp = int(temp2[0]) / int(temp2[1])

                    else:
                        temp = int(self.tableWidget.item(j, q).text())
                    if int(temp) == 0:
                        temp = 1 / int(self.tableWidget.item(q, j).text())
                        item = QtWidgets.QTableWidgetItem('1/' + self.tableWidget.item(q, j).text())
                        self.tableWidget.setItem(j, q, item)
                    try:
                        if int(self.tableWidget.item(j, q).text()) < 0:
                            Error.ERROR(5)
                            return 0
                    except:
                        pass
                    data1.append(temp)
                data.append(data1)
            delegate = AlignDelegate(self.tableWidget)
            self.tableWidget.setItemDelegate(delegate)
        except:
            Error.ERROR(5)
            return 0
        vector_prior, flag2, OS, IS = self.magic(data)
        if not flag2:
            Error.ERROR(4)
            self.lineEdit.setText('; ИС = ' + str(IS) + '; ОС = ' + str(OS) + ' < 0.1 => Матрица НЕ согласована!')

        else:
            text = "Значения весов удельных критериев: "
            for i in vector_prior:
                text += str(i) + ', '
            text = text.strip(', ')

            text += '; ИС = ' + str(IS) + '; ОС = ' + str(OS) + ' < 0.1 => Матрица согласована!'
            self.lineEdit.setText(text)
            self.btn_next.setEnabled(True)
            self.btn_graf.setEnabled(True)
            self.pushButton.setEnabled(True)
            self.btn_chek.setEnabled(False)

    def magic(self, data):
        vector_prior = []
        for i in data:
            pop = 1
            for j in i:
                pop *= j
            pop = math.pow(pop, 1 / len(i))
            vector_prior.append(pop)
        # print(vector_prior)
        # print(sum(vector_prior))
        vector_prior2 = []
        for i in range(len(vector_prior)):
            vector_prior2.append(vector_prior[i] / sum(vector_prior))
        vector_prior = vector_prior2
        data = np.array(data)
        vector_prior = np.array(vector_prior)
        vector_prior2 = data.dot(vector_prior)
        # print(vector_prior2)
        vector_prior2 /= vector_prior
        # print(vector_prior2)
        l_max = sum(vector_prior2) / len(vector_prior2)
        # print(l_max)
        IS = (l_max - len(vector_prior2)) / (len(vector_prior2) - 1)
        # print('IS = ' + str(IS))
        midSI = self.check_SI(len(vector_prior2))
        OS = IS / midSI
        # print('OS = ' + str(OS))
        if str(OS) == 'nan':
            OS = 0
        if OS < 0.1:
            return vector_prior, True, OS, IS
        else:
            return vector_prior, False, OS, IS

    def check_SI(self, n):
        Sl_soglas = {1: 0, 2: 0, 3: 0.58, 4: 0.9, 5: 1.12, 6: 1.24, 7: 1.32, 8: 1.40, 9: 1.45, 10: 1.49, 11: 1.5,
                     12: 1.48, 13: 1.56, 14: 1.57, 15: 1.59}
        return Sl_soglas[n]

    def make_graf_pie(self, mass_alter):
        data = self.lineEdit.text().split(' ')[4:4 + len(mass_alter)]
        upd_data = []
        for i in data:
            i = i[:-1]
            upd_data.append(float(i))

        dpi = 80
        fig = plt.figure(dpi=dpi, figsize=(1536 / dpi, 768 / dpi))
        mpl.rcParams.update({'font.size': 13})

        plt.title('Удельные веса.')

        xs = range(len(mass_alter))
        plt.pie(
            upd_data, radius=1.1, autopct='%.1f')
        plt.legend(
            bbox_to_anchor=(0.15, 0.25), labels=mass_alter)
        fig.show()

    def make_graf_stolb(self, mass_alter):
        data = self.lineEdit.text().split(' ')[4:4 + len(mass_alter)]
        upd_data = []
        for i in data:
            i = i[:-1]
            upd_data.append(float(i))

        frequencies = upd_data
        freq_series = pd.Series(frequencies)
        y_labels = range(1, len(mass_alter) + 1)
        # Plot the figure.
        plt.figure(figsize=(12, 8))
        ax = freq_series.plot(kind='barh')
        ax.set_title('Удельные веса')
        ax.set_xlim(0, max(upd_data) + 0.2)  # expand xlim to make labels easier to read
        ax.set_yticklabels(y_labels)

        rects = ax.patches

        # For each bar: Place a label
        for h, rect in enumerate(rects):
            # Get X and Y placement of label from rect.
            x_value = rect.get_width()
            y_value = rect.get_y() + rect.get_height() / 2

            # Number of points between bar and label. Change to your liking.
            space = 5
            # Vertical alignment for positive values
            ha = 'left'

            # If value of bar is negative: Place label left of bar
            if x_value < 0:
                # Invert space to place label to the left
                space *= -1
                # Horizontally align label at right
                ha = 'right'

            # Use X value as label and format number with one decimal place
            label = "{}".format(mass_alter[h])
            # Create annotation
            plt.annotate(
                label,  # Use `label` as label
                (x_value, y_value),  # Place label at end of the bar
                xytext=(space, 0),  # Horizontally shift label by `space`
                textcoords="offset points",  # Interpret `xytext` as offset in points
                va='center',  # Vertically center label
                ha=ha)  # Horizontally align label differently for
            # positive and negative values.
        plt.show()

    def check_data(self, i):
        if i == -1:
            data = np.array([['1', '0', '3', '0', '5', '5', '5', '7', '1'],
                             ['3', '1', '9', '1', '9', '9', '8', '9', '3'],
                             ['0', '0', '1', '0', '1', '2', '1', '2', '0'],
                             ['3', '1', '7', '1', '7', '9', '9', '8', '3'],
                             ['0', '0', '1', '0', '1', '1', '1', '2', '0'],
                             ['0', '0', '0', '0', '1', '1', '1', '2', '0'],
                             ['0', '0', '1', '0', '1', '1', '1', '2', '0'],
                             ['0', '0', '0', '0', '0', '0', '0', '1', '0'],
                             ['1', '0', '3', '0', '3', '5', '5', '7', '1']])
        elif i == 0:
            data = np.array([['1', '3', '1', '9', '3', '5'],
                             ['0', '1', '0', '6', '1', '3'],
                             ['1', '3', '1', '9', '3', '5'],
                             ['0', '0', '0', '1', '0', '0'],
                             ['0', '1', '0', '5', '1', '2'],
                             ['0', '0', '0', '3', '0', '1']])
        elif i == 1:
            data = np.array([['1', '0', '0', '0', '0', '0'],
                             ['5', '1', '1', '1', '1', '1'],
                             ['5', '1', '1', '1', '1', '1'],
                             ['5', '1', '1', '1', '1', '1'],
                             ['5', '1', '1', '1', '1', '1'],
                             ['5', '1', '1', '1', '1', '1']])
        elif i == 2:
            data = np.array([['1', '0', '3', '5', '7', '1'],
                             ['3', '1', '7', '8', '9', '3'],
                             ['0', '0', '1', '2', '5', '0'],
                             ['0', '0', '0', '1', '1', '0'],
                             ['0', '0', '0', '1', '1', '0'],
                             ['1', '0', '2', '5', '7', '1']])
        elif i == 3:
            data = np.array([['1', '7', '0', '3', '2', '3'],
                             ['0', '1', '0', '0', '0', '0'],
                             ['3', '9', '1', '7', '3', '9'],
                             ['0', '3', '0', '1', '0', '1'],
                             ['0', '4', '0', '2', '1', '2'],
                             ['0', '2', '0', '1', '0', '1']])
        elif i == 4:
            data = np.array([['1', '0', '0', '0', '2', '0'],
                             ['2', '1', '0', '0', '3', '0'],
                             ['3', '2', '1', '0', '5', '0'],
                             ['7', '3', '5', '1', '9', '3'],
                             ['0', '0', '0', '0', '1', '0'],
                             ['6', '5', '2', '0', '7', '1']])
        elif i == 5:
            data = np.array([['1', '0', '0', '0', '1', '0'],
                             ['2', '1', '1', '0', '3', '0'],
                             ['2', '1', '1', '0', '2', '0'],
                             ['4', '2', '2', '1', '5', '1'],
                             ['1', '0', '0', '0', '1', '0'],
                             ['4', '2', '3', '1', '5', '1']])
        elif i == 6:
            data = np.array([['1', '0', '0', '0', '0', '0'],
                             ['2', '1', '0', '0', '0', '1'],
                             ['4', '2', '1', '0', '2', '2'],
                             ['5', '3', '2', '1', '2', '3'],
                             ['3', '2', '0', '0', '1', '1'],
                             ['2', '1', '0', '0', '1', '1']])
        elif i == 7:
            data = np.array([['1', '0', '0', '0', '1', '0'],
                             ['3', '1', '2', '0', '3', '0'],
                             ['2', '0', '1', '0', '2', '0'],
                             ['7', '3', '3', '1', '6', '2'],
                             ['1', '0', '0', '0', '1', '0'],
                             ['2', '2', '3', '0', '4', '1']])
        elif i == 8:
            data = np.array([['1', '0', '0', '0', '0', '0'],
                             ['2', '1', '2', '0', '0', '0'],
                             ['2', '0', '1', '0', '0', '0'],
                             ['4', '5', '5', '1', '3', '3'],
                             ['3', '3', '3', '0', '1', '1'],
                             ['3', '2', '4', '0', '1', '1']])
        else:
            data = np.eye(9)
        return data


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date  : 2019/2/21 14:24
# @Author: PythonVampire
# @email : vampire@ivamp.cn
# @File  : test_json.py
import json

my_dict = {"img": "hjaksdgbasjkbdnasjkn"}
my_json = json.dumps(my_dict)
print(type(my_json))
print(my_json)


import os
from datetime import datetime

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities

from pages import Pages
from utilities.environments.common import CommonEnvironment

def take_screenshot(context):
    now = datetime.now().strftime('%Y-%m-%d-%H-%M-')
    scenario = context.scenario.name.replace(' ', '-')
    step = context.step.name.replace(' ', '-')
    filename = f'{os.getcwd()}/screenshots/{now}-{scenario}:{step}.png'
    context.driver.save_screenshot(filename)

def create_webdriver():
    driver = webdriver.Remote(command_executor='http://localhost:4444/wd/hub',
                              desired_capabilities=DesiredCapabilities.CHROME)
    driver.set_window_size(os.getenv('SCREEN_WIDTH'), os.getenv('SCREEN_HEIGHT'))
    return driver

class WebEnvironment(CommonEnvironment):
    def before_scenario(self, context, scenario):
        super().before_scenario(context, scenario)
        context.base_e2e_url = os.getenv('E2E_URL')
        context.logger.info(f'Base E2E URL is: {context.base_e2e_url}')
        context.logger.info('Starting browser')
        context.driver = create_webdriver()
        context.pages = Pages(context)

    def after_scenario(self, context, scenario):
        super().after_scenario(context, scenario)
        context.logger.info('Closing browser')
        context.driver.quit()

    def after_step(self, context, step):
        super().after_step(context, step)
        if step.status == 'failed':
            take_screenshot(context)


import numpy as np
import matplotlib.pyplot as plt
#对每一个样本，更新一次W，并同时返回误差
def linear_pre(W,X1,Y):
    learn_rate = 0.16
    Result = X1.dot(W.T)
    if Result >0:
        Ypre = 1
    else:
        Ypre = 0
    Wnew = W + learn_rate*(Y-Ypre)*X1
    error = Y - Ypre
    return Wnew,error

np.random.seed(12)

num_observations = 500

x1 = np.random.multivariate_normal([0,0],[[1,.75],[.75,1]],num_observations)
x2 = np.random.multivariate_normal([1,4],[[1,.75],[.75,1]],num_observations)

X = np.vstack((x1,x2)).astype(np.float32)
Y = np.hstack((np.zeros(num_observations),np.ones(num_observations)))

X1 = np.hstack((X,np.ones([2*num_observations,1])))
W = np.random.randn(1,3)

error_sum = 0
gamma = 0.00001
#这里想加上那个误差范围的判断，但一开始误差都是0，所以就设定让它在500次之后再生效了，
#你们有好的写法就改一下
for i in range(len(X1)):
    W,error = linear_pre(W, X1[i], Y[i])
    error_sum += error
    if (error_sum/(i+1) < gamma)&(i>500):
        break

f1=plt.figure(1)

plt.scatter(X[0:500,0],X[0:500,1],c = 'red')
plt.scatter(X[500:,0],X[500:,1],c ='green')

x_line = np.linspace(-3,3,1000)
y_line = -((W[0,0]*x_line+W[0,2])/W[0,1])

plt.plot(x_line,y_line,color = 'black')

plt.show()


from PyQt5 import QtCore, QtGui
from PyQt5.QtWidgets import QWidget, QDialog, QTableWidgetItem
from ui_mainscreen import Ui_MainScreen
from ui_wearabledialog import Ui_WearableDialog
from ui_zonedialog import Ui_ZoneDialog
from ui_devicedialog import Ui_DeviceDialog
from ui_configdialog import Ui_ConfigDialog
from ui_pausechangedialog import Ui_PauseChangeDialog
from ui_confirmdialog import Ui_ConfirmDialog
from drew_util import *
from constants import *

class UiControl:
    def __init__(self, systemState):
        self.systemState = systemState
        self.currXmlId = [-1, -1, -1, -1]
        self.afterPauseTask = TASK_NONE

        self.iconPause = QtGui.QIcon("./images/pause.png")
        self.iconActivate = QtGui.QIcon("./images/play.png")
        self.iconWait = QtGui.QIcon("./images/wait.png")

        self.mainWindow = QWidget()
        self.mainUi = Ui_MainScreen()
        self.mainUi.setupUi(self.mainWindow)

        self.pauseChangeDialog = QDialog()
        self.pauseChangeDialog.setWindowFlags(QtCore.Qt.CustomizeWindowHint|QtCore.Qt.WindowTitleHint|QtCore.Qt.WindowStaysOnTopHint)
        self.pauseChangeDialogUi = Ui_PauseChangeDialog()
        self.pauseChangeDialogUi.setupUi(self.pauseChangeDialog)
        self.pauseChangeGif = QtGui.QMovie("./images/waiting.gif")
        self.pauseChangeGif.setScaledSize(QtCore.QSize(140, 140))
        self.pauseChangeDialogUi.labelGIF.setMovie(self.pauseChangeGif)
        self.pauseChangeThread = PauseChangeThread(self.systemState)
        self.showWhenPauseDone = None

        self.dropdownRefreshThread = DropdownRefreshThread(self.systemState)
        self.doRefresh = -1

        self.statusRefreshThread1 = StatusRefreshThread()
        self.statusRefreshThread2 = StatusRefreshThread()
        self.statuRefreshThreadSelect = False

        self.delTypeId = -1
        self.confirmDialog = QDialog()
        self.confirmDialog.setWindowFlags(QtCore.Qt.CustomizeWindowHint|QtCore.Qt.WindowTitleHint)
        self.confirmDialogUi = Ui_ConfirmDialog()
        self.confirmDialogUi.setupUi(self.confirmDialog)

        self.dialogs = []
        for i in range(NUM_DIALOGS):
            dialog = QDialog()
            dialog.setWindowFlags(QtCore.Qt.CustomizeWindowHint|QtCore.Qt.WindowTitleHint)
            self.dialogs.append(dialog)

        self.dialogUis = []
        self.dialogUis.append(Ui_WearableDialog())
        self.dialogUis.append(Ui_ZoneDialog())
        self.dialogUis.append(Ui_DeviceDialog())
        self.dialogUis.append(Ui_ConfigDialog())
        for i in range(NUM_DIALOGS):
            self.dialogUis[i].setupUi(self.dialogs[i])

        self.tables = [self.mainUi.tableWearable, self.mainUi.tableZone, self.mainUi.tableDevice, self.mainUi.tableConfig]
        self.zoTable = self.mainUi.tableZoneOccupation
        self.dsTable = self.mainUi.tableDeviceState

        self.buttonGroups = []
        self.buttonGroups.append([self.mainUi.buttonEditWearable, self.mainUi.buttonDeleteWearable, self.mainUi.buttonNewWearable])
        self.buttonGroups.append([self.mainUi.buttonEditZone, self.mainUi.buttonDeleteZone, self.mainUi.buttonNewZone])
        self.buttonGroups.append([self.mainUi.buttonEditDevice, self.mainUi.buttonDeleteDevice, self.mainUi.buttonNewDevice])
        self.buttonGroups.append([self.mainUi.buttonEditConfig, self.mainUi.buttonClearConfig])

        self.connectUiElements()

        # populate tables with current system info
        self.populateHardwareTables()
        self.createZoneOccupationTable()
        self.createDeviceStateTable()

        # populate device type dropdown
        dropdown = self.dialogUis[TID_D].dropdownType
        for deviceType in DEVICE_TYPES.keys():
            dropdown.addItem(DEVICE_TYPES[deviceType], deviceType)

        # set initial button enabled/disabled state, etc
        for i in range(4):
            self.selectionUpdate(i)

        # initially, system should be unpaused
        self.mainUi.labelPauseStatus.setText("<b>System Active<b>")
        self.mainUi.buttonPause.setIcon(self.iconPause)
        self.manuallyPaused = False

        # now that everything is set up, let the other threads start doing their thing
        self.systemState.setSystemPause(RESUME)

        # since we start in the status tab, we want to make sure it's updating when we begin
        self.statusRefresh()

        # let's go!
        self.mainWindow.show()

    def connectUiElements(self):
        # "New" buttons
        self.mainUi.buttonNewWearable.clicked.connect(lambda: self.editWearable(True))
        self.mainUi.buttonNewZone.clicked.connect(lambda: self.editZone(True))
        self.mainUi.buttonNewDevice.clicked.connect(lambda: self.editDevice(True))

        # "Edit" buttons
        self.mainUi.buttonEditWearable.clicked.connect(lambda: self.editWearable(False))
        self.mainUi.buttonEditZone.clicked.connect(lambda: self.editZone(False))
        self.mainUi.buttonEditDevice.clicked.connect(lambda: self.editDevice(False))
        self.mainUi.buttonEditConfig.clicked.connect(lambda: self.editConfig())

        # "Delete" buttons
        self.mainUi.buttonDeleteWearable.clicked.connect(lambda: self.confirmDeletion(TID_W))
        self.mainUi.buttonDeleteZone.clicked.connect(lambda: self.confirmDeletion(TID_Z))
        self.mainUi.buttonDeleteDevice.clicked.connect(lambda: self.confirmDeletion(TID_D))
        self.mainUi.buttonClearConfig.clicked.connect(lambda: self.beginTaskWithPause(TASK_CLEAR_CONFIG))

        # deletion confirmation buttons
        self.confirmDialogUi.buttonNo.clicked.connect(lambda: self.confirmDialog.hide())
        self.confirmDialogUi.buttonYes.clicked.connect(lambda: self.beginTaskWithPause(TASK_DELETE_TABLE_ENTRY))

        # dialog "Cancel" buttons
        self.dialogUis[TID_W].buttonCancel.clicked.connect(lambda: self.cancelHardwareDialog(TID_W))
        self.dialogUis[TID_Z].buttonCancel.clicked.connect(lambda: self.cancelHardwareDialog(TID_Z))
        self.dialogUis[TID_D].buttonCancel.clicked.connect(lambda: self.cancelHardwareDialog(TID_D))
        self.dialogUis[TID_C].buttonCancel.clicked.connect(lambda: self.cancelHardwareDialog(TID_C))

        # dialog "Save" buttons
        self.dialogUis[TID_W].buttonSave.clicked.connect(lambda: self.saveWearable())
        self.dialogUis[TID_Z].buttonSave.clicked.connect(lambda: self.saveZone())
        self.dialogUis[TID_D].buttonSave.clicked.connect(lambda: self.saveDevice())
        self.dialogUis[TID_C].buttonSave.clicked.connect(lambda: self.saveConfig())

        # dialog "Refresh List" buttons
        self.dialogUis[TID_W].buttonRefresh.clicked.connect(lambda: self.refreshWearableDropdown())
        self.dialogUis[TID_Z].buttonRefresh.clicked.connect(lambda: self.initiateDropdownRefresh(TID_Z))
        self.dialogUis[TID_D].buttonRefresh.clicked.connect(lambda: self.initiateDropdownRefresh(TID_D))

        # enable/disable buttons when table selection changes, etc
        self.tables[TID_W].itemSelectionChanged.connect(lambda: self.selectionUpdate(TID_W))
        self.tables[TID_Z].itemSelectionChanged.connect(lambda: self.selectionUpdate(TID_Z))
        self.tables[TID_D].itemSelectionChanged.connect(lambda: self.selectionUpdate(TID_D))
        self.tables[TID_C].itemSelectionChanged.connect(lambda: self.selectionUpdate(TID_C))

        # manual system pause/resume button
        self.mainUi.buttonPause.clicked.connect(lambda: self.beginPauseChange((not self.systemState.systemIsPaused), True))
        self.pauseChangeThread.doneSignal.connect(lambda: self.finishPauseChange())

        self.dropdownRefreshThread.doneSignal.connect(lambda: self.finishDropdownRefresh())

        self.statusRefreshThread1.refreshSignal.connect(lambda: self.statusRefresh())
        self.statusRefreshThread2.refreshSignal.connect(lambda: self.statusRefresh())

        # link values of zone threshold slider & spinner
        spinner = self.dialogUis[TID_Z].spinnerThreshold
        slider = self.dialogUis[TID_Z].sliderThreshold
        spinner.valueChanged.connect(lambda: slider.setValue(spinner.value()))
        slider.valueChanged.connect(lambda: spinner.setValue(slider.value()))

        #
        tabs = self.mainUi.tabWidget
        tabs.currentChanged.connect(lambda: self.tabChange(tabs.currentIndex()))

    def tabChange(self, tabNum):
        if (tabNum == TAB_STAT):
            self.statusRefresh()
        elif (tabNum == TAB_SYS):
            self.createConfigTable()
        # other cases -> do nothing

    def beginPauseChange(self, desiredAction, isManualChange):
        if (desiredAction == self.systemState.systemIsPaused):
            return False # system is already in the desired state

        # manual changes are initiated by pressing the pause/resume button
        # automatic changes are initiated when editing any part of the system
        if (isManualChange):
            self.manuallyPaused = (desiredAction == PAUSE)

        if (desiredAction == PAUSE):
            waitText = "Pausing System..."
        else:
            waitText = "Resuming System... "
        self.mainUi.labelPauseStatus.setText(waitText)
        self.mainUi.buttonPause.setIcon(self.iconWait)

        self.pauseChangeDialog.setWindowTitle(waitText)
        self.pauseChangeGif.start()
        self.pauseChangeDialog.show()

        self.pauseChangeThread.setAction(desiredAction)
        self.pauseChangeThread.start()

        return True

    def finishPauseChange(self):
        if (self.systemState.systemIsPaused):
            doneText = "<b>System Paused</b>"
            newIcon = self.iconActivate
        else:
            doneText = "<b>System Active<b>"
            newIcon = self.iconPause

        self.mainUi.buttonPause.setIcon(newIcon)
        self.mainUi.labelPauseStatus.setText(doneText)

        self.pauseChangeGif.stop()
        self.pauseChangeDialog.hide()

        if (self.showWhenPauseDone != None):
            self.showWhenPauseDone.show()
            self.showWhenPauseDone = None

        if (self.doRefresh != -1):
            self.initiateDropdownRefresh(self.doRefresh)

        self.doRefresh = -1

        self.executeTask()

    def statusRefresh(self):
        # update each row (zone) in zone occupation table
        for row in range(self.zoTable.rowCount()):
            items = [self.zoTable.item(row, 0), self.zoTable.item(row, 1)]
            zone = self.systemState.getHardwareObjectByXmlId(TID_Z, items[0].data(5))
            self.updateZoneOccupationTableRow(zone, items)

        # update each row (zone) in zone occupation table
        for row in range(self.dsTable.rowCount()):
            items = [self.dsTable.item(row, 0), self.dsTable.item(row, 1)]
            device = self.systemState.getHardwareObjectByXmlId(TID_D, items[0].data(5))
            self.updateDeviceStateTableRow(device, items)

        # if still in status tab, need to keep refreshing
        if (self.mainUi.tabWidget.currentIndex() == TAB_STAT):
            # alternate between two refresh threads so signal emits don't "overlap"
            if (self.statuRefreshThreadSelect):
                self.statusRefreshThread1.start()
            else:
                self.statusRefreshThread2.start()
            self.statuRefreshThreadSelect = (not self.statuRefreshThreadSelect)

    def editWearable(self, isNew, isAfterPause=False):
        self.showWhenPauseDone = self.dialogs[TID_W]
        self.beginPauseChange(PAUSE, False)
        self.dialogUis[TID_W].labelInvalidName.setVisible(False)
        self.dialogUis[TID_W].labelInvalidWearable.setVisible(False)
        self.newFlag = isNew
        if (isNew):
            wearable = self.systemState.newWearable()
            self.currXmlId[TID_W] = wearable.xmlId
        else:
            wearable = self.systemState.getHardwareObjectByXmlId(TID_W, self.currXmlId[TID_W])
        self.dialogUis[TID_W].inputName.setText(wearable.name)
        self.refreshWearableDropdown()

    def editZone(self, isNew):
        self.showWhenPauseDone = self.dialogs[TID_Z]
        self.doRefresh = TID_Z
        pauseNeeded = self.beginPauseChange(PAUSE, False)
        if (not pauseNeeded):
            self.doRefresh = -1
            self.initiateDropdownRefresh(TID_Z)
        self.dialogUis[TID_Z].labelInvalidName.setVisible(False)
        self.dialogUis[TID_Z].labelInvalidModule.setVisible(False)
        self.newFlag = isNew
        if (isNew):
            zone = self.systemState.newZone()
            self.currXmlId[TID_Z] = zone.xmlId
        else:
            zone = self.systemState.getHardwareObjectByXmlId(TID_Z, self.currXmlId[TID_Z])
        self.dialogUis[TID_Z].inputName.setText(zone.name)
        self.dialogUis[TID_Z].spinnerThreshold.setValue(zone.threshold)
        if (not pauseNeeded):
            self.dialogs[TID_Z].show()

    def editDevice(self, isNew):
        self.showWhenPauseDone = self.dialogs[TID_D]
        self.doRefresh = TID_D
        pauseNeeded = self.beginPauseChange(PAUSE, False)
        if (not pauseNeeded):
            self.doRefresh = -1
            self.initiateDropdownRefresh(TID_D)
        self.dialogUis[TID_D].labelInvalidName.setVisible(False)
        self.dialogUis[TID_D].labelInvalidDevice.setVisible(False)
        self.newFlag = isNew
        if (isNew):
            device = self.systemState.newDevice()
            self.currXmlId[TID_D] = device.xmlId
        else:
            device = self.systemState.getHardwareObjectByXmlId(TID_D, self.currXmlId[TID_D])
        self.dialogUis[TID_D].inputName.setText(device.name)
        if (not pauseNeeded):
            self.dialogs[TID_D].show()

    def editConfig(self):
        self.showWhenPauseDone = self.dialogs[TID_C]
        self.beginPauseChange(PAUSE, False)
        self.dialogUis[TID_C].labelInvalidZone.setVisible(False)
        device = self.systemState.getHardwareObjectByXmlId(TID_D, self.currXmlId[TID_C])
        self.dialogUis[TID_C].labelConfig.setText("Configuration for \"" + device.name + "\"")
        self.populateConfigDropdowns(device)

    def cancelHardwareDialog(self, typeId):
        if (typeId != TID_C):
            if (self.newFlag):
                self.systemState.deleteHardwareObject(typeId, self.currXmlId[typeId])
            self.selectionUpdate(typeId)

        if (not self.manuallyPaused):
            self.beginPauseChange(RESUME, False)
        self.dialogs[typeId].hide()

    def saveWearable(self):
        givenName = (self.dialogUis[TID_W].inputName.text()).strip()
        if (self.systemState.nameInUse(TID_W, givenName, self.currXmlId[TID_W])):
            self.dialogUis[TID_W].labelInvalidName.setVisible(True)
            return
        else:
            self.dialogUis[TID_W].labelInvalidName.setVisible(False)

        selectedHwId = self.dialogUis[TID_W].dropdownWearable.currentData()
        if (selectedHwId == -1):
            self.dialogUis[TID_W].labelInvalidWearable.setVisible(True)
            return
        else:
            self.dialogUis[TID_W].labelInvalidWearable.setVisible(False)

        wearable = self.systemState.getHardwareObjectByXmlId(TID_W, self.currXmlId[TID_W])
        wearable.name = givenName
        wearable.hwId = selectedHwId
        self.updateWearableTable(wearable, self.newFlag)
        self.selectionUpdate(TID_W)
        if (not self.manuallyPaused):
            self.beginPauseChange(RESUME, False)
        self.dialogs[TID_W].hide()

    def saveZone(self):
        # disallow duplicate names
        givenName = (self.dialogUis[TID_Z].inputName.text()).strip()
        if (self.systemState.nameInUse(TID_Z, givenName, self.currXmlId[TID_Z])):
            self.dialogUis[TID_Z].labelInvalidName.setVisible(True)
            return
        else:
            self.dialogUis[TID_Z].labelInvalidName.setVisible(False)

        # disallow invalid hardware IDs
        selectedHwId = self.dialogUis[TID_Z].dropdownModule.currentData()
        if (selectedHwId == -1):
            self.dialogUis[TID_Z].labelInvalidModule.setVisible(True)
            return
        else:
            self.dialogUis[TID_Z].labelInvalidModule.setVisible(False)

        # input validated -- do the save operation
        zone = self.systemState.getHardwareObjectByXmlId(TID_Z, self.currXmlId[TID_Z])
        zone.name = givenName
        zone.hwId = selectedHwId
        zone.threshold = self.dialogUis[TID_Z].spinnerThreshold.value()
        self.updateZoneTable(zone, self.newFlag)
        self.selectionUpdate(TID_Z)

        # update zone occupation table in status tab
        if (self.newFlag):
            self.updateZoneOccupationTableRow(zone)
        else:
            for row in range(self.zoTable.rowCount()):
                if (self.zoTable.item(row, 0).data(5) == zone.xmlId):
                    items = [self.zoTable.item(row, 0), self.zoTable.item(row, 1)]
                    self.updateZoneOccupationTableRow(zone, items)
                    break

        self.updateDeviceStateTableRow
        if (not self.manuallyPaused):
            self.beginPauseChange(RESUME, False)
        self.dialogs[TID_Z].hide()

    def saveDevice(self):
        # disallow duplicate names
        givenName = (self.dialogUis[TID_D].inputName.text()).strip()
        if (self.systemState.nameInUse(TID_D, givenName, self.currXmlId[TID_D])):
            self.dialogUis[TID_D].labelInvalidName.setVisible(True)
            return
        else:
            self.dialogUis[TID_D].labelInvalidName.setVisible(False)

        # disallow invalid hardware IDs
        (selectedHwId, selectedListName) = self.dialogUis[TID_D].dropdownDevice.currentData()
        if (selectedHwId == 'INVALID'):
            self.dialogUis[TID_D].labelInvalidDevice.setVisible(True)
            return
        else:
            self.dialogUis[TID_D].labelInvalidDevice.setVisible(False)

        # input validated -- do the save operation
        device = self.systemState.getHardwareObjectByXmlId(TID_D, self.currXmlId[TID_D])
        device.name = givenName
        device.hwId = selectedHwId
        device.listName = selectedListName
        device.devType = self.dialogUis[TID_D].dropdownType.currentData()
        self.updateDeviceTable(device, self.newFlag)
        self.selectionUpdate(TID_D)

        # update device state table in status tab
        if (self.newFlag):
            self.updateDeviceStateTableRow(device)
        else:
            for row in range(self.dsTable.rowCount()):
                if (self.dsTable.item(row, 0).data(5) == device.xmlId):
                    items = [self.dsTable.item(row, 0), self.dsTable.item(row, 1)]
                    self.updateDeviceStateTableRow(device, items)
                    break

        if (not self.manuallyPaused):
            self.beginPauseChange(RESUME, False)
        self.dialogs[TID_D].hide()

    def saveConfig(self):
        configUi = self.dialogUis[TID_C]
        selectedZone = configUi.dropdownZone.currentData()
        if (selectedZone == -1):
            self.dialogUis[TID_C].labelInvalidZone.setVisible(True)
            return
        else:
            self.dialogUis[TID_C].labelInvalidZone.setVisible(False)

        device = self.systemState.getHardwareObjectByXmlId(TID_D, self.currXmlId[TID_C])
        device.zone = selectedZone
        device.enter = configUi.dropdownEntryAction.currentData()
        device.exit = configUi.dropdownExitAction.currentData()
        self.updateConfigTableEntry(device)
        self.selectionUpdate(TID_C)
        if (not self.manuallyPaused):
            self.beginPauseChange(RESUME, False)
        self.dialogs[TID_C].hide()

    def confirmDeletion(self, typeId):
        self.delTypeId = typeId
        hwObj = self.systemState.getHardwareObjectByXmlId(typeId, self.currXmlId[typeId])
        text = DEL_STR + HW_STR_DICT[typeId] + " \"" + hwObj.name + "\"?"
        self.confirmDialogUi.labelAreYouSure.setText(text)
        self.confirmDialogUi.labelWarning.setVisible(typeId == TID_Z)
        self.confirmDialog.show()

    def beginTaskWithPause(self, taskId):
        self.afterPauseTask = taskId
        ret = self.beginPauseChange(PAUSE, False)
        if (not ret):
            self.executeTask()

    def executeTask(self):
        task = self.afterPauseTask
        self.afterPauseTask = TASK_NONE

        if (task == TASK_NONE):
            return
        elif (task == TASK_CLEAR_CONFIG):
            self.clearConfig()
        elif (task == TASK_DELETE_TABLE_ENTRY):
            self.deleteTableEntry(self.delTypeId)

    def deleteTableEntry(self, typeId):
        xmlId = self.currXmlId[typeId]
        self.systemState.deleteHardwareObject(typeId, xmlId)
        self.tables[typeId].removeRow(self.tables[typeId].currentRow())
        self.removeFromStatusTable(typeId, xmlId)
        if (not self.manuallyPaused):
            self.beginPauseChange(RESUME, False)
        self.confirmDialog.hide()

    def clearConfig(self):
        device = self.systemState.getHardwareObjectByXmlId(TID_D, self.currXmlId[TID_C])
        device.zone = -1
        device.enter = 0
        device.exit = 0
        self.updateConfigTableEntry(device)
        if (not self.manuallyPaused):
            self.beginPauseChange(RESUME, False)

    def selectionUpdate(self, tableIdx):
        items = self.tables[tableIdx].selectedItems()
        if (len(items) > 0):
            self.currXmlId[tableIdx] = items[0].data(5)
        else:
            self.currXmlId[tableIdx] = -1
        shouldEnable = ( len(self.tables[tableIdx].selectedIndexes()) != 0)
        buttons = self.buttonGroups[tableIdx]
        for i in range(2): # only update edit & delete buttons
            buttons[i].setEnabled(shouldEnable)

    def refreshWearableDropdown(self):
        hwIdList = self.systemState.discoverHardware(TID_W)
        dropdown = self.dialogUis[TID_W].dropdownWearable
        dropdown.clear()

        for hwId in hwIdList:
            dropdown.addItem(str(hwId), hwId)

        if (not self.newFlag): # add and select current hwId if editing existing wearable
            wearable = self.systemState.getHardwareObjectByXmlId(TID_W, self.currXmlId[TID_W])
            dropdown.insertItem(0, str(wearable.hwId), int(wearable.hwId))
            dropdown.setCurrentIndex(0)
        elif (len(hwIdList) == 0):
            dropdown.addItem("[no unassigned wearables detected]", -1)

    def initiateDropdownRefresh(self, typeId):
        if (typeId == TID_Z):
            titleText = "Searching for Zone Modules..."
        else: # typeId = TID_D
            titleText = "Searching for Devices..."
        self.pauseChangeDialog.setWindowTitle(titleText)
        self.dropdownRefreshThread.setTypeId(typeId)
        self.dropdownRefreshThread.start()
        self.pauseChangeGif.start()
        self.pauseChangeDialog.show()

    def finishDropdownRefresh(self):
        if (self.dropdownRefreshThread.typeId == TID_Z):
            self.refreshZoneModuleDropdown()
        else: # typeId == TID_D
            self.refreshDeviceDropdown()

        self.pauseChangeGif.stop()
        self.pauseChangeDialog.hide()

    def refreshZoneModuleDropdown(self):
        hwIdList = self.dropdownRefreshThread.hwIdList
        dropdown = self.dialogUis[TID_Z].dropdownModule
        dropdown.clear()

        for hwId in hwIdList:
            dropdown.addItem(str(hwId), hwId)

        if (not self.newFlag): # add and select current hwId if editing existing zone
            zone = self.systemState.getHardwareObjectByXmlId(TID_Z, self.currXmlId[TID_Z])
            dropdown.insertItem(0, str(zone.hwId), int(zone.hwId))
            dropdown.setCurrentIndex(0)
        elif (len(hwIdList) == 0):
            dropdown.addItem("[no unassigned modules detected]", -1)

    def refreshDeviceDropdown(self):
        hwTupleList = self.dropdownRefreshThread.hwIdList
        dropdown = self.dialogUis[TID_D].dropdownDevice
        dropdown.clear()

        for (hwId, listName) in hwTupleList:
            dropdown.addItem(hwId + " - " + listName, (hwId, listName))

        # add and select current hwId if editing existing zone
        if (not self.newFlag):
            device = self.systemState.getHardwareObjectByXmlId(TID_D, self.currXmlId[TID_D])
            dropdown.insertItem(0, device.hwId + " - " + device.listName, (device.hwId, device.listName))
            dropdown.setCurrentIndex(0)
        elif (len(hwTupleList) == 0):
            dropdown.addItem("[no unassigned devices detected]", 'INVALID')

    def populateConfigDropdowns(self, device):
        configUi = self.dialogUis[TID_C]
        dropdown = configUi.dropdownZone
        dropdown.clear()

        for zone in self.systemState.dicts[TID_Z].values():
            dropdown.addItem(zone.name, zone.xmlId)
            if (zone.xmlId == device.zone):
                dropdown.setCurrentIndex(dropdown.count()-1)

        if (dropdown.count() == 0):
            dropdown.addItem("[no zones exist]", -1)

        actions = DEVICE_ACTIONS[device.devType]
        dropdown = configUi.dropdownEntryAction
        dropdown.clear()
        dropdown2 = configUi.dropdownExitAction
        dropdown2.clear()

        for actionId in DEVICE_ACTIONS[device.devType].keys():
            dropdown.addItem(actions[actionId], actionId)
            if (actionId == device.enter):
                dropdown.setCurrentIndex(dropdown.count()-1)
            dropdown2.addItem(actions[actionId], actionId)
            if (actionId == device.exit):
                dropdown2.setCurrentIndex(dropdown2.count()-1)

    def populateHardwareTables(self):
        for wearable in self.systemState.dicts[TID_W].values():
            self.updateWearableTable(wearable, True)

        for zone in self.systemState.dicts[TID_Z].values():
            self.updateZoneTable(zone, True)

        for device in self.systemState.dicts[TID_D].values():
            self.updateDeviceTable(device, True)

    def updateWearableTable(self, wearable, isNew):
        if (isNew):
            self.tables[TID_W].insertRow(0)
            # "Name" item with xmlId data
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(wearable.name)
            item.setData(5, wearable.xmlId)
            self.tables[TID_W].setItem(0, 0, item)
            # "Wearable ID" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(str(wearable.hwId))
            self.tables[TID_W].setItem(0, 1, item)
        else:
            items = self.tables[TID_W].selectedItems()
            items[0].setText(wearable.name)
            items[1].setText(str(wearable.hwId))

    def updateZoneTable(self, zone, isNew):
        if (isNew):
            self.tables[TID_Z].insertRow(0)
            # "Name" item with xmlId data
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(zone.name)
            item.setData(5, zone.xmlId)
            self.tables[TID_Z].setItem(0, 0, item)
            # "Module ID" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(str(zone.hwId))
            self.tables[TID_Z].setItem(0, 1, item)
            # "Threshold" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(str(zone.threshold))
            self.tables[TID_Z].setItem(0, 2, item)
        else:
            items = self.tables[TID_Z].selectedItems()
            items[0].setText(zone.name)
            items[1].setText(str(zone.hwId))
            items[2].setText(str(zone.threshold))

    def updateDeviceTable(self, device, isNew):
        if (isNew):
            self.tables[TID_D].insertRow(0)
            # "Name" item with xmlId data
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(device.name)
            item.setData(5, device.xmlId)
            self.tables[TID_D].setItem(0, 0, item)
            # "Bluetooth Address" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(device.hwId)
            self.tables[TID_D].setItem(0, 1, item)
            # "Type" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(DEVICE_TYPES[device.devType])
            self.tables[TID_D].setItem(0, 2, item)
        else:
            items = self.tables[TID_D].selectedItems()
            items[0].setText(device.name)
            items[2].setText(device.hwId)
            items[2].setText(DEVICE_TYPES[device.devType])

    def createConfigTable(self):
        configTable = self.tables[TID_C]
        configTable.clearContents()
        for i in range(configTable.rowCount()):
            configTable.removeRow(0)
        for device in self.systemState.dicts[TID_D].values():
            configTable.insertRow(0)
            # "Device" item with xmlId data
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(device.name)
            item.setData(5, device.xmlId)
            configTable.setItem(0, 0, item)
            # "Containing Zone" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            if (device.zone == -1):
                text = "[unassigned]"
            else:
                text = self.systemState.dicts[TID_Z][device.zone].name
            item.setText(text)
            item.setData(5, device.zone)
            configTable.setItem(0, 1, item)
            # "Entry Action" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(DEVICE_ACTIONS[device.devType][device.enter])
            configTable.setItem(0, 2, item)
            # "Exit Action" item
            item = QTableWidgetItem()
            item.setTextAlignment(ITEM_ALIGN_FLAGS)
            item.setFlags(ITEM_INTERACT_FLAGS)
            item.setText(DEVICE_ACTIONS[device.devType][device.exit])
            configTable.setItem(0, 3, item)

    def updateConfigTableEntry(self, device):
        items = self.tables[TID_C].selectedItems()
        if (device.zone == -1):
            text = "[unassigned]"
        else:
            text = self.systemState.dicts[TID_Z][device.zone].name
        items[1].setText(text)
        items[1].setData(5, device.zone)
        items[2].setText(DEVICE_ACTIONS[device.devType][device.enter])
        items[3].setText(DEVICE_ACTIONS[device.devType][device.exit])

    def createZoneOccupationTable(self):
        for zone in self.systemState.dicts[TID_Z].values():
            self.updateZoneOccupationTableRow(zone)

    def updateZoneOccupationTableRow(self, zone, tableItems=None):
        if (tableItems == None):
            tableItems = []
            for i in range(2):
                item = QTableWidgetItem()
                item.setTextAlignment(ITEM_ALIGN_FLAGS)
                item.setFlags(ITEM_INTERACT_FLAGS)
                tableItems.append(item)
            self.zoTable.insertRow(0)
            self.zoTable.setItem(0, 0, tableItems[0])
            self.zoTable.setItem(0, 1, tableItems[1])

        tableItems[0].setText(zone.name)
        tableItems[0].setData(5, zone.xmlId)

        wearablesPresent = ""
        firstOneFlag = True
        signalDataList = zone.wearablesInZone.items()

        counter = 0
        for wearbleId, signalData in signalDataList:
            wearable = self.systemState.getHardwareObjectByHwId(TID_W, wearbleId)
            if (not signalData.isInZone):
                continue
            counter += 1
            if (firstOneFlag):
                firstOneFlag = False
            else:
                wearablesPresent = wearablesPresent + ", "
            wearablesPresent = wearablesPresent + wearable.name

        if (counter == 0):
            wearablesPresent = "[none]"

        tableItems[1].setText(wearablesPresent)

    def createDeviceStateTable(self):
        for device in self.systemState.dicts[TID_D].values():
            self.updateDeviceStateTableRow(device)

    def updateDeviceStateTableRow(self, device, tableItems=None):
        if (tableItems == None):
            tableItems = []
            for i in range(2):
                item = QTableWidgetItem()
                item.setTextAlignment(ITEM_ALIGN_FLAGS)
                item.setFlags(ITEM_INTERACT_FLAGS)
                tableItems.append(item)
            self.dsTable.insertRow(0)
            self.dsTable.setItem(0, 0, tableItems[0])
            self.dsTable.setItem(0, 1, tableItems[1])

        tableItems[0].setText(device.name)
        tableItems[0].setData(5, device.xmlId)
        tableItems[1].setText(DEVICE_STATES[device.devType][device.state])

    def removeFromStatusTable(self, typeId, xmlId):
        if (typeId != TID_Z and typeId != TID_D):
            return
        else:
            if (typeId == TID_Z):
                table = self.zoTable
            else: # typeId == TID_D
                table = self.dsTable

            for row in range(table.rowCount()):
                if ((table.item(row, 0)).data(5) == xmlId):
                    table.removeRow(row)
                    return

class PauseChangeThread(QtCore.QThread):
    doneSignal = QtCore.pyqtSignal()
    action = RESUME
    isDone = False

    def __init__(self, systemState):
        super().__init__()
        self.systemState = systemState

    def setAction(self, action):
        self.action = action

    def run(self):
        self.isDone = False
        self.systemState.setSystemPause(self.action)
        self.doneSignal.emit()
        self.isDone = True

class DropdownRefreshThread(QtCore.QThread):
    doneSignal = QtCore.pyqtSignal()
    typeId = -1
    hwIdList = None

    def __init__(self, systemState):
        super().__init__()
        self.systemState = systemState

    def setTypeId(self, typeId):
        self.typeId = typeId

    def run(self):
        self.hwIdList = self.systemState.discoverHardware(self.typeId)
        self.doneSignal.emit()

class StatusRefreshThread(QtCore.QThread):
    refreshSignal = QtCore.pyqtSignal()

    def run(self):
        time.sleep(0.25)
        self.refreshSignal.emit()


def main():
    valuesArray = []
    sizeArray = int(input("Digite a quantidade de valores que deseja digitar: "))
    for size in range(sizeArray):
        valuesArray.append(int(input("Digite o %dº valor: " % (size + 1))))
    print(valuesArray)

if __name__ == '__main__':
    main()


import scipy.io as sio
import numpy as np
from openpyxl import Workbook

import fields

def load_diseases_to_array():
    f = open(fields.diseases_txt)
    d_list = []
    while True:
        line = f.readline().splitlines()
        if not line:
            break
        d_list.append(line[0])
    return d_list

def load_microbe_to_array():
    f = open(fields.microbes_txt)
    m_list = []
    while True:
        line = f.readline().splitlines()
        if not line:
            break
        m_list.append(line[0])
    return m_list

def load_mat_array():
    res_mat = sio.loadmat(fields.result_mat)
    return np.array(res_mat['S'])

if __name__ == '__main__':
    diseases = load_diseases_to_array()
    microbes = load_microbe_to_array()
    display_mat = dict()
    mat = load_mat_array()
    b = mat.size
    c = b
    for i in range(0, mat.shape[0]-1):
        for j in range(0, mat.shape[1]-1):
            name_i = diseases[i]
            name_j = microbes[j]
            # if name_i not in display_mat:
            #     display_mat[name_i] = dict()
            display_mat[(name_i, name_j)] = mat[i][j]
    sorted_dict = sorted(display_mat.items(), key=lambda item: item[1], reverse=True)

    wb = Workbook()  # 创建一个工作簿

    ws = wb.active  # 获取工作的激活工作表

    ws.cell(column=1, row=1, value='Disease')
    ws.cell(column=2, row=1, value='Microbe')
    ws.cell(column=3, row=1, value='Sim')
    for row in range(2, len(sorted_dict)):
        item = sorted_dict[row]
        ws.cell(column=1, row=row, value=item[0][0])
        ws.cell(column=2, row=row, value=item[0][1])
        ws.cell(column=3, row=row, value=item[1])
    wb.save('res.xls')


from sys import exit
import random
import pygame
import numpy as np

class SnakeBlock():
    def __init__(self, x, y, game_window, map_size, block_size, id):
        self.id = id
        self.size = 0
        self.x = x
        self.y = y
        self.game_window = game_window
        self.map_size = map_size
        self.block_size = block_size

    def draw(self):
        pygame.draw.rect(self.game_window, (255, 255, 255),
                         (self.x, self.y, self.block_size, self.block_size), 0)

class Snake():
    def __init__(self, game_window, x, y, map_size, block_size):
        self.game_window = game_window
        self.map_size = map_size
        self.block_size = block_size
        self.headX = x
        self.headY = y
        self.tailX = x
        self.tailY = y
        self.body = [SnakeBlock(self.headX, self.headY,
                                self.game_window, self.map_size, self.block_size, 1)]
        self.turns = []
        self.size = 1
        self.steps_between_foods = 0

    def move(self, dir, foodX, foodY):
        def food_dir(dir, foodX, foodY):
            if dir == 'up' and self.headY > foodY:
                return True
            if dir == 'down' and self.headY < foodY:
                return True
            if dir == 'left' and self.headX > foodX:
                return True
            if dir == 'right' and self.headX < foodX:
                return True
            return False
        self.steps_between_foods = self.steps_between_foods + 1
        eat = False
        snake_collide = False
        reward = 0
        if dir == "none":
            return (snake_collide, eat, reward)
        if dir == "up":
            self.headY = self.headY - self.block_size
        if dir == "down":
            self.headY = self.headY + self.block_size
        if dir == "right":
            self.headX = self.headX + self.block_size
        if dir == "left":
            self.headX = self.headX - self.block_size

        if self.headX == foodX and self.headY == foodY:
            self.body.append(SnakeBlock(self.body[self.size - 1].x, self.body[self.size - 1].y,
                                        self.game_window, self.map_size, self.block_size, self.size + 1))
            self.size += 1
            reward = 0.5
            eat = True
            self.steps_between_foods = 0
        else:
            if self.collide():
                snake_collide = True
                reward = -0.5
            else:
                if food_dir(dir, foodX, foodY):
                    reward = 0.1
                else:
                    pass
                    reward = -0.1

        for i in reversed(range(self.size)):
            if i == 0:
                self.body[0].x = self.headX
                self.body[0].y = self.headY
            else:
                self.body[i].x = self.body[i - 1].x
                self.body[i].y = self.body[i - 1].y
        return (snake_collide, eat, reward)

    def collide(self):
        collideFlag = False
        if self.headX < 0 or self.headX >= self.map_size[0] * self.block_size or \
                self.headY < 0 or self.headY >= self.map_size[1] * self.block_size:
            collideFlag = True

        for block1 in self.body:
            for block2 in self.body:
                if block1.id != block2.id:
                    if block1.x == block2.x and block1.y == block2.y:
                        collideFlag = True
        return collideFlag

    def draw(self):
        for block in self.body:
            block.draw()

    def getSnakePlaces(self):
        places = [[], []]
        for block in self.body:
            places[0].append(block.x)
            places[1].append(block.y)
        return places

class Food():
    def __init__(self, game_window, map_size, block_size):
        self.game_window = game_window
        self.map_size = map_size
        self.block_size = block_size
        self.x = 0
        self.y = 0

    def draw(self):
        pygame.draw.rect(self.game_window, (255, 0, 0),
                         (self.x, self.y, self.block_size, self.block_size), 0)

    def new(self, takenPlaces):
        self.x = random.randint(0, self.map_size[0] - 1) * self.block_size
        self.y = random.randint(0, self.map_size[1] - 1) * self.block_size
        while self.x in takenPlaces[0] and self.y in takenPlaces[1]:
            self.x = random.randint(0, self.map_size[0] - 1) * self.block_size
            self.y = random.randint(0, self.map_size[1] - 1) * self.block_size

class Map():
    def __init__(self, game_window, map_size, block_size):
        self.game_window = game_window
        self.map_size = map_size
        self.block_size = block_size
        self.food = Food(self.game_window, self.map_size, self.block_size)
        self.food.new([[], []])

    def draw(self):
        # draw grid

        x = 0
        y = 0

        for i in range(self.map_size[0]):
            x = x + self.block_size
            pygame.draw.line(self.game_window, (255, 255, 255),
                             (x, 0), (x, self.block_size * self.map_size[1]))

        for i in range(self.map_size[1]):
            y = y + self.block_size
            pygame.draw.line(self.game_window, (255, 255, 255),
                             (0, y), (self.block_size * self.map_size[0], y))
        # draw food
        self.food.draw()

    def newFood(self, takenPlaces):
        self.food.new(takenPlaces)

class SnakeGame():
    def __init__(self, map_size, block_size):
        self.block_size = block_size
        self.map_size = map_size
        self.width = map_size[0] * block_size
        self.height = map_size[0] * block_size
        self.score = 0
        self.state = np.zeros(12, dtype=int)

        pygame.init()
        self.game_window = pygame.display.set_mode(
            (self.width, self.height))

        self.board = Map(self.game_window, self.map_size, self.block_size)
        self.snake = Snake(self.game_window, self.width // 2,
                           self.height // 2, self.map_size, self.block_size)
        self.board.newFood(self.snake.getSnakePlaces())

        playFlag = True
        direction = "none"

    def move(self, dir):
        snake_collide, food_eaten, reward = self.snake.move(
            dir, self.board.food.x, self.board.food.y)

        if food_eaten:
            self.board.newFood(self.snake.getSnakePlaces())
            foodEaten = False
            self.score = self.score + 1

        # if collide
        if self.snake.steps_between_foods > 500:
            return (True, reward)
        return (snake_collide, reward)

    def draw_stats(self):
        x = self.width + 50
        y = (self.height // 4) * 3

        for i in range(3):
            x = x + self.block_size
            pygame.draw.line(self.game_window, (255, 255, 255),
                             (x, y), (x, y+self.block_size * 3))

        for i in range(4):
            y = y + self.block_size
            pygame.draw.line(self.game_window, (255, 255, 255),
                             (x - 4*self.block_size, y), (x, y))

    def draw(self):
        self.game_window.fill((0, 0, 0))
        # self.draw_stats()
        self.board.draw()
        self.snake.draw()
        pygame.display.update()
        pass

    def show_text(self, text, pos=(200, 200)):
        font = pygame.font.SysFont("comicsansms", 30)
        render = font.render("generation: " + text, True, (255, 255, 255))
        self.game_window.blit(render, pos)
        pygame.display.flip()

    def update_state(self):
        def blocked(pos):
            if pos[0] < 0 or pos[0] >= self.map_size[0] * self.block_size or \
                    pos[1] < 0 or pos[1] >= self.map_size[1] * self.block_size:
                return True
            for block in self.snake.body:
                if (block.x, block.y) == pos:
                    return True
            return False

        def head_new_pos(head_pos, dir):
            if dir == "up":
                return (head_pos[0], head_pos[1] - self.snake.block_size)
            if dir == "down":
                return (head_pos[0], head_pos[1] + self.snake.block_size)
            if dir == "right":
                return (head_pos[0] + self.snake.block_size, head_pos[1])
            if dir == "left":
                return (head_pos[0] - self.snake.block_size, head_pos[1])

        def get_food_state():
            food_state = np.zeros(4, dtype=int)

            if self.snake.headX > self.board.food.x:
                food_state[0] = 1
            if self.snake.headY > self.board.food.y:
                food_state[1] = 1
            if self.snake.headX < self.board.food.x:
                food_state[2] = 1
            if self.snake.headY < self.board.food.y:
                food_state[3] = 1

            # if self.snake.headX < self.board.food.x and self.snake.headY > self.board.food.y:
            #     food_state[0] = 1
            # if self.snake.headX == self.board.food.x and self.snake.headY > self.board.food.y:
            #     food_state[1] = 1
            # if self.snake.headX > self.board.food.x and self.snake.headY > self.board.food.y:
            #     food_state[2] = 1
            # if self.snake.headX < self.board.food.x and self.snake.headY == self.board.food.y:
            #     food_state[3] = 1
            # if self.snake.headX > self.board.food.x and self.snake.headY == self.board.food.y:
            #     food_state[4] = 1
            # if self.snake.headX < self.board.food.x and self.snake.headY < self.board.food.y:
            #     food_state[5] = 1
            # if self.snake.headX == self.board.food.x and self.snake.headY < self.board.food.y:
            #     food_state[6] = 1
            # if self.snake.headX > self.board.food.x and self.snake.headY < self.board.food.y:
            #     food_state[7] = 1
            return food_state

        def get_blocked_state():
            head_pos = (self.snake.headX, self.snake.headY)
            blocked_state = np.zeros(4, dtype=int)
            if blocked(head_new_pos(head_pos, "left")):
                blocked_state[0] = 1
            if blocked(head_new_pos(head_pos, "up")):
                blocked_state[1] = 1
            if blocked(head_new_pos(head_pos, "right")):
                blocked_state[2] = 1
            if blocked(head_new_pos(head_pos, "down")):
                blocked_state[3] = 1
            return blocked_state

        # food_pos = (self.board.food.x, self.board.food.y)
        # head_pos = (self.snake.headX, self.snake.headY)
        # neck_pos = (self.snake.body[-1].x, self.snake.body[-1].y)

        self.state = np.zeros(8, dtype=int)

        self.state[:4] = get_food_state()
        self.state[4:8] = get_blocked_state()

    def get_state(self):
        self.update_state()
        return self.state

def main():
    pygame.init()
    # parameters:
    block_size = 40
    map_size = (16, 16)
    playFlag = True
    direction = "none"
    clock = pygame.time.Clock()

    game = SnakeGame(map_size, block_size)

    while playFlag:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit(0)
            keys = pygame.key.get_pressed()

        if keys[pygame.K_UP]:
            direction = "up"
        if keys[pygame.K_DOWN]:
            direction = "down"
        if keys[pygame.K_RIGHT]:
            direction = "right"
        if keys[pygame.K_LEFT]:
            direction = "left"
        snake_collide, reward = game.move(direction)
        if snake_collide:
            playFlag = False
        print(reward)
        game.draw()
        clock.tick(8)

if __name__ == "__main__":
    main()


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

from beckett import clients, resources

class PeopleResource(resources.BaseResource):

    class Meta(resources.BaseResource.Meta):
        name = 'People'
        identifier = 'name'
        attributes = (
            'name',
            'slug',
            'another_thing',
        )
        methods = (
            'get',
        )

class BlogResource(resources.BaseResource):

    class Meta(resources.BaseResource.Meta):
        name = 'Blog'
        identifier = 'id'
        attributes = (
            'id',
            'title',
            'slug',
            'content',
        )
        methods = (
            'get',
            'post',
            'put',
            'patch',
            'delete',
        )
        pagination_key = 'objects'

    @classmethod
    def get_url(cls, url, uid, **kwargs):
        if kwargs.get('page'):
            return '{}?page={}'.format(
                url,
                kwargs.get('page')
            )
        if uid:
            return '{}/{}'.format(url, uid)
        else:
            return url

class PlainTestClient(clients.BaseClient):

    class Meta(clients.BaseClient.Meta):
        name = 'test_client'
        base_url = 'http://dev/api'
        resources = (
            PeopleResource,
        )

class BlogTestClient(clients.BaseClient):

    class Meta(clients.BaseClient.Meta):
        name = 'test_blog_client'
        base_url = 'http://dev/api'
        resources = (
            BlogResource,
        )

# Hypermedia fixtures

class HypermediaAuthorsResource(resources.HypermediaResource):

    class Meta(resources.HypermediaResource.Meta):
        name = 'Authors'
        resource_name = 'authors'
        base_url = 'http://dev/api'
        identifier = 'name'
        attributes = (
            'name',
            'title',
        )
        methods = (
            'get',
        )

class HypermediaBlogsResource(resources.HypermediaResource):

    class Meta(resources.HypermediaResource.Meta):
        name = 'Blogs'
        identifier = 'name'
        base_url = 'http://dev/api'
        attributes = (
            'name',
            'slug',
            'another_thing',
            'author',
        )
        methods = (
            'get',
        )

        related_resources = (
            HypermediaAuthorsResource,
        )

class HypermediaBlogTestClient(clients.BaseClient):

    class Meta(clients.BaseClient.Meta):
        name = 'test_hyper_blog_client'
        base_url = 'http://dev/api'
        resources = (
            HypermediaBlogsResource,
            HypermediaAuthorsResource,
        )

class NoDefaultsResource(resources.BaseResource):
    """
    A class without the following defaults set:
        - pagination_key
        - valid_status_codes

    It should still be able to use defaults for this
    """
    class Meta:
        name = 'Person'
        resource_name = 'people'
        identifier = 'url'
        attributes = (
            'name',
        )
        methods = (
            'get',
        )

class NoDefaultsClient(clients.BaseClient):

    class Meta(clients.BaseClient.Meta):
        name = 'no_defaults_test_client'
        base_url = 'http://dev/api'
        resources = (
            NoDefaultsResource,
        )

# Subresource tests

class AuthorSubResource(resources.SubResource):

    class Meta(resources.BaseResource.Meta):
        name = 'Author'
        identifier = 'name'
        attributes = (
            'name',
        )

class SubResourcePeopleResource(resources.BaseResource):

    class Meta(resources.BaseResource.Meta):
        name = 'People'
        identifier = 'name'
        attributes = (
            'slug',
            'another_thing',
        )
        methods = (
            'get',
        )
        subresources = {
            "author": AuthorSubResource
        }


from gofetch import template

from unittest import TestCase

class RenderTemplateTestCase(TestCase):

    SIMPLE_TEMPLATE = """
SELECT {{ fields }}
FROM {{ database_and_table }}
WHERE {{ condition }}
;"""

    SIMPLE_PARAM_DICT = {
        "fields": "*",
        "database_and_table": "test_db.test",
        "condition": "b > 1"
    }

    def test_render_string(self):
        EXPECTED = """
SELECT *
FROM test_db.test
WHERE b > 1
;"""
        result = template._render_string_template(self.SIMPLE_TEMPLATE, self.SIMPLE_PARAM_DICT)
        self.assertEquals(EXPECTED, result)

    def test_render_file(self):
        # 'simple_template.sql'
        self.fail("test not implemented")


def shift_n_letters(letter, n):
    shift_value = (ord(letter) - ord('a') + (n % 26)) % 26
    return chr(ord('a') + shift_value)

def rotate(letters, n):
    result = ''
    for letter in letters:
        if letter == ' ':
            result += letter
        else:
            result += shift_n_letters(letter, n)
    return result

print(rotate('sarah', 13))
print(rotate('fnenu', 13))
print(rotate('dave', 5))
print(rotate('ifaj', -5))
print(rotate(("zw pfli tfuv nfibj tfiivtkcp pfl jyflcu "
              "sv rscv kf ivru kyzj"), -17))


def solve(s):
    nums = list(map(int, s))
    ans, n = 0, len(nums)
    for i in range(len(nums)-1):
        l, r = i, i+1
        suml = sumr = 0
        while l >= 0 and r < n:
            suml += nums[l]
            sumr += nums[r]
            if suml == sumr and i-l+1 > ans:
                ans = i-l+1
            l -= 1
            r += 1
    return ans*2

for _ in range(int(input())):
    s = input()
    print(solve(s))

对称子字符串/对称子字符串.py


dictionary = {}
languages = {}

while True:
    line = input()
    if line == "exam finished":
        break
    command = line.split("-")
    if len(command) == 3:
        username, language, points = command[0], command[1], int(command[2])
        languages[language] = languages.get(language, 0) + 1
        if username in dictionary.keys():
            if points > dictionary[username]:
                dictionary[username] = points
        else:
            dictionary[username] = points
    else:
        dictionary[command[0]] = 0

print(f"Results:")
[print(f"{key} | {value}") for key, value in dictionary.items() if value != 0]

print(f"Submissions:")
[print(f"{some_language} - {number}") for some_language, number in languages.items()]

2. Python Fundamentals/7. Dictionaries - Exercise/12_SoftUni_exam_results.py


from aws_cdk import core
from cdk_deployment.main_stack import MainStack

# start cdk
app = core.App()

# retrieve the name of the branch and the ecr repo to pull from
ecr_repository_name = app.node.try_get_context("ecr_repository")
branch_name = app.node.try_get_context("branch")
account = app.node.try_get_context("account")
region = app.node.try_get_context("region")
if not branch_name or not ecr_repository_name or not account or not region:
    raise Exception("Branch, ECR repository, account and region are required")

print(
    f"Working on branch {branch_name} ",
    f"ECR repository {ecr_repository_name} ",
    f"account {account} ",
    f"region {region}",
)

# setup environment, ie account and region where to deploy
env_EU = core.Environment(account=account, region=region)

# create the stack
# csfe stands for CDK step function example
_ = MainStack(
    app,
    "csfeMainStack",
    stack_name=f"csfe-{branch_name}-main-stack",
    env=env_EU,
    ecr_repository_name=ecr_repository_name,
    branch_name=branch_name,
    account=account,
    region=region,
)

# synthesize the app into a cloud assembly, ie an ensamble of artifacts
# such as CloudFormation templates and assets that are needed to deploy
# this app into the AWS cloud.
app.synth()


#Делал в паре с Андреем Чебыровым
import random
import cmath as mt
print('Вариант №',len('Галай Роман Олегович')%5)
f=lambda x: mt.log(x)+(x+1)**3
def differ(func, x: float, epsilon: float):
    return (func(x + epsilon / 2.) - func(x - epsilon / 2.)) \
           / epsilon

def newton(func, x: float, epsilon: float):
    try:

        if ((differ(func, x, epsilon)) == 0.):
            return newton(func, (x + epsilon / 2 * (-1) ** (random.random())).real, epsilon)

        if abs((x - func(x) / (differ(func, x, epsilon)))- x) > epsilon:
            return newton((func, x - func(x) / (differ(func, x, epsilon))), epsilon)
        else:
            return (x - func(x) / (differ(func, x, epsilon)))
    except:
        return x

epsilon=float(input('Точность ввода: '))
approx=newton(f,1.,epsilon)
print(approx)


#! /usr/bin/env python

import rospy
from mavros_msgs.srv import CommandBool

ms_emergency = 'tello/emergency'

rospy.init_node("emergency_quit")

emergency_srv = rospy.ServiceProxy(ms_emergency, CommandBool)
resp = emergency_srv(True)
print("Emergency quit", resp.success, resp.result)


import logging
from nyuki import Nyuki, resource
from nyuki.capabilities import Response
from aiohttp_cors import ResourceOptions, setup as cors_setup

from webapp import Webapp
from data import DockerData

log = logging.getLogger(__name__)
WEBAPP_PATH = './webapp/'

class Mesh(Nyuki):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.webapp = Webapp(self.loop)
        self.data = DockerData(ignore=self.config['ignore'])

    async def setup(self):
        # Enable cors capabilities for the api routes
        self._enable_cors()

        # Start the webapp
        web_host = self.config['webapp']['host']
        web_port = self.config['webapp']['port']
        await self.webapp.build(WEBAPP_PATH, web_host, web_port)

    def _enable_cors(self):
        app = self.api._api._app
        cors = cors_setup(app, defaults={
            "*": ResourceOptions(
                allow_credentials=True,
                expose_headers="*",
                allow_headers="*",
            )
        })
        for route in self.api._api.router.routes():
            cors.add(route)

    @resource(endpoint='/containers', version='v1')
    class Containers:

        def get(self, request):
            return Response(self.data.containers)

    @resource(endpoint='/nodes', version='v1')
    class Nodes:

        def get(self, request):
            return Response(self.data.nodes())

    @resource(endpoint='/edges', version='v1')
    class Edges:

        def get(self, request):
            return Response(self.data.edges())

if __name__ == '__main__':
    nyuki = Mesh()
    nyuki.start()


# Method 1
from array import*

arr1 = array('i',[10,20,30,40,50])
arr1.remove(40)

for x in arr1:
    print(x)

# Method 2
import array as arr
number = arr.array('i',[10,20,30,90,40])
del number[2]
print(number)


# coding=utf-8
import sys
from PyQt5.QtWidgets import (QApplication, QWidget, QLineEdit, QLabel, QPushButton,
                             QRadioButton, QVBoxLayout, QGroupBox)

from fa_generator import FiniteAutomat
from expr_parser import Parser

class MainWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self._match_whole_mode = QRadioButton("Celé", self)
        self._match_whole_mode.setChecked(True)
        self._match_substring_mode = QRadioButton("Sub string", self)
        self._input = QLineEdit()
        self._input.setPlaceholderText("Kontrolovaný text")
        self._re_input = QLineEdit()
        self._re_input.setPlaceholderText("Regulární výraz")

        self._output = QLabel()
        self._check_button = QPushButton("Kontrola", self)

        layout = QVBoxLayout()
        layout.addWidget(self._match_whole_mode)
        layout.addWidget(self._match_substring_mode)
        layout.addWidget(self._re_input)
        layout.addWidget(self._input)
        layout.addWidget(self._output)
        layout.addWidget(self._check_button)

        self.setLayout(layout)

        self._check_button.clicked.connect(self.check)

    def check(self):
        try:
            p = Parser(self._re_input.text())
            ka = p.parse()
            if not ka:
                self._output.setText("Syntax error.")
                return

            dka = ka.dka()
            if self._match_whole_mode.isChecked():
                res = dka.eval(self._input.text(), FiniteAutomat.MatchMode.MATCH_WHOLE)
                if res:
                    self._output.setText("Shoda")
                else:
                    self._output.setText("Neshoda")
            elif self._match_substring_mode.isChecked():
                res = dka.eval(self._input.text(), FiniteAutomat.MatchMode.MATCH_SUB)
                if res is False:
                    self._output.setText("Řetězec nenalezen")
                else:
                    self._output.setText("Řetězec nalezen na pozici {}".format(res))
        except Exception as e:
            print(e)

"""app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec())"""

p = Parser("6\\da")

a = p.parse()
print(a.start)
print(a.end)
print(a._graph)
a = a.dka()
print(a._start_is_end)
print(a._graph)
print("starte")
a.eval("67a", FiniteAutomat.MatchMode.MATCH_WHOLE)


from django import forms
from django.utils import timezone

from menu.models import Menu
from .models import Order

class OrderForm(forms.ModelForm):
    """Form to create a new order"""

    def __init__(self, *args, **kwargs):
        self.item_selected = args[0].get("item_selected")
        self.menu = args[0].get("menu")
        self.customization = args[0].get("customization")
        super(OrderForm, self).__init__(*args, **kwargs)
        self.fields["customization"].required = False

    def unique_selection_validation(self):
        """Check that the user has not selected an option for this current menu (today)"""
        order = Order.objects.filter(
            ordered_by=self.instance.ordered_by, menu=self.menu
        )
        if order.exists():
            raise forms.ValidationError("User already chose an item for this menu")

    def time_validation(self):
        """Validation to check if request is before 11 am in current day"""
        menu_date = Menu.objects.get(pk=self.menu).date
        now = timezone.localtime(timezone.now())
        cut_off_time = timezone.localtime(timezone.now()).replace(
            hour=11, minute=0, second=0, microsecond=0
        )
        now_date = now.date()
        if menu_date < now_date:
            raise forms.ValidationError("This is a past menu")
        if now_date == menu_date and now > cut_off_time:
            raise forms.ValidationError("You are too late")

    def clean(self):
        """Verify that user have not created a new order and that he is on time"""
        try:
            self.unique_selection_validation()
            self.time_validation()
        except forms.ValidationError as errors:
            for error in errors:
                self.add_error(None, error)

    class Meta:
        model = Order
        fields = ["item_selected", "menu", "customization"]


__author__ = 'MACSAMI'

import unittest
from models.item import Item
from models.user import User
from models.bid import Bid

class TestItem(unittest.TestCase):
    def setUp(self):
        #init users
        self.user1 = User('John')
        self.user2 = User('Paul')
        #init bids
        self.bid1 = Bid(10, self.user1)
        self.bid2 = Bid(6, self.user2)
        #init items
        self.item1 = Item('Item1')
        self.item1.new_bid(self.bid1, self.bid2)
        self.item2 = Item('Item2')

    def test_init(self):
        self.assertEqual(self.item1.name, 'Item1', 'incorrect name for item')

    def test_new_bid(self):
        self.bid3 = Bid(12,self.user1)
        self.item2.new_bid(self.bid3)
        self.assertEqual(len(self.item2.bids), 1, 'invalid number of bids')

    def test_get_max_bid(self):
        self.assertEqual(self.item1.get_winning_bid().value, 10, 'incorrect max bid when not None')
        self.assertEqual(self.item2.get_winning_bid(), None, 'incorrect max bid when None')

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