#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time
# @Author  : Huix
# @File
# @Software: PyCharm

import os
import tkinter as tk
from tkinter import *  # 导入 Tkinter 库
from tkinter.filedialog import askdirectory
import multiprocessing
import threading
import platform
import getpass
from InstallApk import InstallApk
# from adbutils import devices

class DeviceManager():

    def __init__(self):
        try:
            cmd = 'adb connect 127.0.0.1:5555'  # 腾讯手游模拟器比较常用，所以写在程序里
            os.system(cmd)
        except EXCEPTION as e:
            print(e)

        self.root = Tk()
        self.root.geometry('1615x420')
        self.root.title("DeviceManager")
        self.user = getpass.getuser()
        platform_system = platform.system()
        if platform_system == "Windows":
            self.win_logcat_path = ("D:\\DeviceManager\\LogcatLog")
            self.logcat_path = StringVar()
            self.logcat_path.set(self.win_logcat_path)

            self.win_GCloudlog_path = ("D:\\DeviceManager\\GCloudSDKLog")
            self.GCloudlog_path=StringVar()
            self.GCloudlog_path.set(self.win_GCloudlog_path)

            self.win_Corelog_path = ("D:\\DeviceManager\\GCloudSDKLog")
            self.Corelog_path = StringVar()
            self.Corelog_path.set(self.win_Corelog_path)

            self.win_GVoicelog_path = ("D:\\DeviceManager\\GCloudSDKLog")
            self.GVoicelog_path = StringVar()
            self.GVoicelog_path.set(self.win_GVoicelog_path)

        else:
            self.mac_logcat_path = ("/Users/" + self.user + "/Downloads/LogcatLog")
            self.logcat_path = StringVar()
            self.logcat_path.set(self.mac_logcat_path)

            self.mac_GCloudlog_path = ("/Users/" + self.user + "/Downloads/GCloudSDKLog")
            self.GCloudlog_path=StringVar()
            self.GCloudlog_path.set(self.mac_GCloudlog_path)

            self.mac_Corelog_path = ("/Users/" + self.user + "/Downloads/GCloudSDKLog")
            self.Corelog_path = StringVar()
            self.Corelog_path.set(self.mac_Corelog_path)

            self.mac_GVoicelog_path = ("/Users/" + self.user + "/Downloads/GCloudSDKLog")
            self.GVoicelog_path = StringVar()
            self.GVoicelog_path.set(self.mac_GVoicelog_path)

        #连接模拟器
        self.init_port =IntVar()

        #手游助手模拟器  5555  第二个开始 5555+index
        self.init_port.set(5555)

        self.increase_num = IntVar()
        self.increase_num.set(1)
        self.apk_name = StringVar()
        self.apk_name.set("请选择一个Apk或输入apk完整路径")
        self.select_device_list =[]
        self.device_list = self.get_device_list()
        self.cb_list =[]
        self.pool = multiprocessing.Pool(processes=6)
        self.button_list=[]
        self.button_logcat_c_list = []
        self.button_logcat_log_list = []
        self.button_delete_GCloudlog_list=[]
        self.button_pull_GCloudlog_list=[]
        self.button_delete_Corelog_list = []
        self.button_pull_Corelog_list = []
        self.button_delete_GVoicelog_list = []
        self.button_pull_GVoicelog_list = []
        self.install_item_list = []
        self.uninstall_item_list = []

    def get_logcat_path(self):	#得到log存放路径
        return self.logcat_path.get()

    def get_GCloudlog_path(self):	#得到log存放路径
        return self.GCloudlog_path.get()

    def get_Corelog_path(self):	 #得到log存放路径
        return self.Corelog_path.get()

    def get_GVoicelog_path(self):	#得到log存放路径
        return self.GVoicelog_path.get()

    # def get_apk_path(self):	#得到apk更目录路径
    #     return self.apk_path

    def item_device_return(self):	#得到log存放路径
        self.device_list = StringVar()
        return self.device_list.get()

    def draw_log_path(self):
        label_logcat=tk.Label(self.root, text="Logcat日志保存外层路径:")
        label_logcat.grid(row=0,column=1,sticky='w')

        entry_logcat_path = Entry(self.root, width=45, textvariable=self.logcat_path)
        entry_logcat_path.grid(row=0,column=2,sticky='w')

        button_open_logcat_path = Button(self.root, text="打开", command=lambda: self.open_file(entry_logcat_path.get()))
        button_open_logcat_path.grid(row=0 ,column=4)

        label_log1 = tk.Label(self.root, text="GCloud日志保存外层路径:")
        label_log1.grid(row=1, column=1, sticky='w')

        entry_log_path1 = Entry(self.root, width=45, textvariable=self.GCloudlog_path)
        entry_log_path1.grid(row=1, column=2, sticky='w')

        button_open_log1 = Button(self.root, text="打开", command=lambda: self.open_file(entry_log_path1.get()))
        button_open_log1.grid(row=1, column=4)

        label_log2 = tk.Label(self.root, text="GCloudCore日志保存外层路径:")
        label_log2.grid(row=2, column=1, sticky='w')

        entry_log_path2 = Entry(self.root, width=45, textvariable=self.Corelog_path)
        entry_log_path2.grid(row=2, column=2, sticky='w')

        button_open_log2 = Button(self.root, text="打开", command=lambda: self.open_file(entry_log_path2.get()))
        button_open_log2.grid(row=2, column=4)

        label_log3 = tk.Label(self.root, text="GVoice日志保存外层路径:")
        label_log3.grid(row=3, column=1, sticky='w')

        entry_log_path3 = Entry(self.root, width=45, textvariable=self.GVoicelog_path)
        entry_log_path3.grid(row=3, column=2, sticky='w')

        button_open_log3 = Button(self.root, text="打开", command=lambda: self.open_file(entry_log_path3.get()))
        button_open_log3.grid(row=3, column=4)

        # 刷新adb
        button_refresh = Button(self.root, text="刷新adb", bg="LightSteelBlue", command=lambda: self.refresh_adb())
        button_refresh.grid(row=0, column=7)
        # 关闭adb
        button_close_adb = Button(self.root, text="关闭adb", bg="DarkGray",command=self.close_adb)
        button_close_adb.grid(row=0, column=9)

        # 连接模拟器
        button_connect_device = Button(self.root, text="连接模拟器", command=self.start_connect_device_thread)
        button_connect_device.grid(row=0, column=10)

        # 连接云真机
        button_connect_device = Button(self.root, text="连接云真机", command=self.start_connect_cloud_device_thread)
        button_connect_device.grid(row=0, column=11)

        # 过关闭adb停止抓logcat日志
        button_close_adb = Button(self.root, text="停止抓logcat日志", bg="DarkGray",command=self.close_adb)
        button_close_adb.grid(row=0, column=12)

    def draw_device_connect(self):
        label_device_start_port = tk.Label(self.root,text="起始端口:")
        label_device_start_port.grid(row=1,column=7,sticky='w')

        entry_device_start_port = Entry(self.root, width=5, textvariable=self.init_port)
        entry_device_start_port.grid(row=1,column=8,sticky='w')

        label_device_num = tk.Label(self.root, text="连接数量:")#模拟器多开时想要连接的数量
        label_device_num.grid(row=1, column=9, sticky='w')

        entry_device_num = Entry(self.root, width=5, textvariable=self.increase_num)
        entry_device_num.grid(row=1, column=10, sticky='w')

    def close_adb(self):
        print("关闭 adb")
        try:
            cmd = 'adb kill-server'
            os.system(cmd)
        except EXCEPTION as e:
            print(e)

    def refresh_adb(self, start_row=0):
        print("刷新adb")
        try:
            # cmd_kill_adb = 'adb kill-server'
            cmd_start_adb = 'adb start-server'
            cmd1 = 'adb devices'
            # cmd2 = 'adb connect 127.0.0.1:5555'  #解决如果先运行工具（脚本），再启动腾讯手游助手，刷新 adb 手游助手刷不出来的问题
            # os.popen(cmd_kill_adb)
            os.popen(cmd_start_adb)
            os.popen(cmd1)

            # os.popen(cmd2)
        except EXCEPTION as e:
            print(e)

        old_device_list = self.device_list   # 原来连接的设备
        new_device_list = self.get_device_list()  # ==>adb device
        #old-new 的差集用old_new表示
        old_new  = set(old_device_list)-set(new_device_list)
        for item in  (self.install_item_list):
            if item.device in list(old_new):
                item.destroy()

        #new-old 的差集用new_old表示
        new_old = set(new_device_list)-set(old_device_list)         # 原来的设备 a  新插入一台b   ==b
        start_draw_index =  len(set(old_device_list)&set(new_device_list))  # a—>len
        old_new_jiao = set(old_device_list)&set(new_device_list)
        cur_device = list(old_new_jiao) + list(new_old)
        # cur_device = list(reversed(cur_device1))
        result = set(new_device_list).issubset(set(cur_device))
        if result == True:
            for item1 in  (self.install_item_list):
                if item1.device in list(cur_device):
                    item1.destroy()
        self.draw_installer_item(cur_device,start_draw_index+1)    # ((b),1)
        self.device_list=new_device_list

    def connect_device(self,index):
        try:
            port =self.init_port.get()+index
            print(port)
            cmd = 'adb connect 127.0.0.1:'+ str(port)
            print(cmd)
            os.system(cmd)
        except:
            print("连接第%d个模拟器有问题" % index+1)

    def connect_cloud_device(self,index):
        try:
            port =self.init_port.get()+index
            print(port)
            cmd = 'adb connect 119.29.201.189:'+ str(port)
            print(cmd)
            os.system(cmd)
        except:
            print("连接第%d个云真机有问题" % index+1)

    def start_connect_device_thread(self):
        for i in range(self.increase_num.get()):
            t= threading.Thread(target=self.connect_device,args=(i,))
            t.start()

    def start_connect_cloud_device_thread(self):
        for i in range(self.increase_num.get()):
            t= threading.Thread(target=self.connect_cloud_device,args=(i,))
            t.start()

    # 选择Apk根目录
    # def draw_apk_path(self):
    #     def selectPath():
    #         path_ = askdirectory()
    #         path.set(path_)
    #     path = StringVar()
    #     self.apk_path = path
    #     self.apk_path = StringVar()
    #     self.apk_path.set("D:\\")
    #     label_apk_path = tk.Label(self.root, text="APK根目录:")
    #     label_apk_path.grid(row=3, column=1, sticky='w')
    #
    #     entry_apk_path = Entry(self.root, width=45, textvariable=self.apk_path)
    #     entry_apk_path.grid(row=3, column=2, sticky='w')
    #
    #     button_select_apkPath = Button(self.root, text="选择", command=selectPath)
    #     button_select_apkPath.grid(row=3, column=4)

    def get_device_list(*args, **kwargs):  #得到设备列表
        os.system("adb devices")
        res = os.popen("adb devices").readlines()
        device_list = [sub.split('\t')[0] for sub in res[1:-1]]
       # device_list = [sub for sub in res[1:-1]]
        return device_list

    def draw_installer_item(self,device_list,old_device_num=0):
        for index, device in enumerate(device_list):
            start_row=index + old_device_num + 2
            install_item=InstallApk(self.root,device,start_row,self)
            self.install_item_list.append(install_item)
            self.root.grid_columnconfigure((0,3,5), minsize=20)

    def draw_label_text(self):
        label_text1 = tk.Label(self.root, text="提示：点击[关闭adb]/[停止抓logcat日志]之后需要重新点击2次[刷新adb]",
                              foreground="Yellow",background="Gray",)
        label_text1.place(x=772,y=62)
        label_text2 = tk.Label(self.root, text="已知问题：点击[刷新adb]会偶现卡顿现象，导出的日志达到100M左右会卡顿",
                              foreground="Yellow",background="Gray",)
        label_text2.place(x=772,y=85.5)

    def mainloop(self):
        self.draw_log_path()
        self.draw_device_connect()
        # self.draw_apk_path()
        self.draw_installer_item(self.device_list)
        self.draw_label_text()
        self.root.mainloop()

    def open_file(self,path):  #打开文件
        print("path:",path)
        os.system("explorer "+path)


from storage_abstract import Storage

class Store(Storage):
    def __init__(self):
        self._items = {}          # {title: qnt}
        self._capacity = 100

    @property
    def items(self):
        return self._items

    @property
    def capacity(self):
        return self._capacity

    @capacity.setter
    def capacity(self, new_qnt):
        if new_qnt >= 0:
            self._capacity = new_qnt
        else:
            self._capacity = 0

    def add(self, title, qnt):
        """Увеличивает запас items с учетом лимита capacity"""
        self.check_qnt(qnt)
        if self.capacity == 0:
            raise Exception(f"We cannot add {title}: there is no empty space in Store.")

        elif qnt < self.capacity and title in self.items.keys():
            self.items[title] = qnt + self.items.get(title)

        elif qnt < self.capacity and title not in self.items.keys():
            self.items[title] = qnt

        elif qnt >= self.capacity and title in self.items.keys():
            self.items[title] = self.capacity + self.items.get(title)

        else:
            self.items[title] = self.capacity
        self.get_free_space("add", qnt)

    def remove(self, title, qnt):
        """Уменьшает запас items, но не ниже 0"""
        self.check_qnt(qnt)
        amount = self.items.get(title, None)
        if amount is not None:
            if qnt >= self.items.get(title):
                self.items[title] = 0
                del self._items[title]
            else:
                self.items[title] -= qnt
        else:
            raise Exception(f"There is no {title} in Store")
        self.get_free_space("remove", qnt)

    def get_free_space(self, flag, qnt):
        """Возвращает количество свободных мест (capacity)"""
        if flag == "add":
            self.capacity = self.capacity - qnt
        else:
            self.capacity = self.capacity + qnt

    def get_items(self):
        """Возвращает содержание склада в словаре {товар: количество} (items)"""
        return self.items

    def get_unique_items_count(self):
        """Возвращает количество уникальных товаров (items.keys)"""
        return len(self.items.keys())

    def check_qnt(self, qnt):
        """Проверяет введённое число"""
        if qnt <= 0:
            raise ValueError("Please, use only positive numbers greater than 0")
        try:
            int(qnt)
        except ValueError:
            print(type(qnt))
            raise TypeError("Please, use only numbers")


from unittest import mock

import pytest
import torch
import matplotlib.pyplot as plt

from src.datasets import BaseDataset
from src.utils import MultiLevelTimer

class TmpData(BaseDataset):
    def __init__(self, n, **kwargs):
        self.n = range(n)
        super().__init__(**kwargs)

    def __len__(self):
        return len(self.n)

    def load(self, item, x, y, meta):
        x['item'] = self.n[item]
        return x, y, meta

    def augment(self, x, y, meta):
        x['item'] *= 100
        meta['augs'] = 'helloworld'
        return x, y, meta

    def show(self, x, y, meta, axs=None): ...

class TestBaseDataset:
    def test_base(self):
        """Test that we have the expected functions."""
        with pytest.raises(TypeError):
            _ = BaseDataset()

        assert hasattr(BaseDataset, '__repr__'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, '__len__'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, '__getitem__'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, 'load'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, 'collate_fn'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, 'augment'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, 'to_torch'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, 'create_axs'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, 'show'), "Missing attribute from base dataset."
        assert hasattr(BaseDataset, 'play'), "Missing attribute from base dataset."

        dataset = TmpData(10)
        assert hasattr(dataset, 'logger'), "Missing logger in dataset."
        assert dataset.logger.name == 'BaseDataset.TmpData', "Incorrect logger name."

    def test_timer(self):
        """Test that timing can be enabled/disabled."""
        dataset = TmpData(10, log_time=True)
        x, y, meta = dataset[0]
        assert isinstance(dataset.timer, MultiLevelTimer), "Incorrect timer class."
        assert 'data_timer' in meta, "Missing timing information in meta."

        dataset = TmpData(10, log_time=False)
        x, y, meta = dataset[0]
        assert not isinstance(dataset.timer, MultiLevelTimer), "Incorrect timer class."
        assert 'data_timer' not in meta, "Unexpected timing information in meta."

    def test_augment(self):
        """Test that augmentations can be enabled/disabled."""
        dataset = TmpData(10, use_aug=True)
        x, y, meta = dataset[5]
        assert x['item'] == 500, "Augmentation not correctly applied."
        assert 'augs' in meta, "Missing augmentations information in meta."
        assert meta['augs'] == 'helloworld', "Augmentation not correctly applied."

        dataset = TmpData(10, use_aug=False)
        x, y, meta = dataset[5]
        assert x['item'] == 5, "Unexpected augmentation applied."
        assert 'augs' not in meta, "Unexpected augmentation information in meta."

        x2, y2, meta2 = BaseDataset.augment(dataset, x, y, meta)
        assert x2 == x, "Incorrect default augmentation"
        assert y2 == y, "Incorrect default augmentation"
        assert meta2 == meta, "Incorrect default augmentation"

    def test_as_torch(self):
        """Test that conversion to torch can be enabled/disabled."""
        dataset = TmpData(10, as_torch=True)
        x, y, meta = dataset[0]
        assert isinstance(x['item'], torch.Tensor), "Incorrect conversion to torch."
        assert isinstance(meta['items'], str), "Unexpected meta conversion to torch."

        dataset = TmpData(10, as_torch=False)
        x, y, meta = dataset[0]
        assert isinstance(x['item'], int), "Unexpected conversion to torch."
        assert isinstance(meta['items'], str), "Unexpected meta conversion to torch."

    def test_retry(self):
        """Test that exception retrying can be enabled/disabled."""

        # Dummy dataset
        class TmpData2(TmpData):
            def load(self, item, x, y, meta):
                if item % 2 == 0: raise ValueError  # Fail on even items.
                return super().load(item, x, y, meta)

        with pytest.raises(ValueError):  # By default shouldn't retry
            _ = TmpData2(10)[2]

        class TmpData3(TmpData2, retry_exc=Exception): pass
        x, y, meta = TmpData3(10)[2]
        assert x['item'] != 2, "Error retrying all exceptions."

        class TmpData3(TmpData2, retry_exc=ValueError): pass
        x, y, meta = TmpData3(10)[2]
        assert x['item'] != 2, "Error retrying on a specific exception."

    @pytest.mark.skip(reason="Creates multiple windows on PyCharm")
    def test_play(self):
        """Test dataset playing iterates correctly and sets window sizes."""
        dataset = TmpData(5, as_torch=True)
        with pytest.raises(ValueError):  # Should work only with non-torch data.
            dataset.play()

        dataset = TmpData(5, as_torch=False)
        dataset.show = mock.Mock()  # Allow for call count
        dataset.play()
        assert dataset.show.call_count == 5, "Incorrect number of calls to show."
        plt.close()

    @pytest.mark.skip(reason="Images are same size on PyCharm")
    def test_fullscreen(self):
        TmpData(5, as_torch=False).play()
        size1 = plt.get_current_fig_manager().canvas.get_width_height()
        plt.close()

        TmpData(5, as_torch=False).play(fullscreen=True)
        size2 = plt.get_current_fig_manager().canvas.get_width_height()
        plt.close()
        assert size1 != size2, "Error setting figure to fullscreen."

    def test_dataset_collate(self):
        """Test that we can collate data by default correctly."""
        class TmpData2(TmpData, retry_exc=ValueError):
            def load(self, item, x, y, meta):
                if item % 2 == 0: raise ValueError  # Fail on even items.
                return super().load(item, x, y, meta)

            def augment(self, x, y, meta):
                return super().augment(x, y, meta) if torch.rand(1) < 0.5 else (x, y, meta)

        dataset = TmpData2(10, as_torch=True, use_aug=True)
        batch_size = 4
        loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=4, collate_fn=dataset.collate_fn)
        x, y, meta = next(iter(loader))

        assert isinstance(x['item'], torch.Tensor),  "Incorrect conversion to torch."
        assert x['item'].shape == (batch_size,),  "Incorrect item batch size."
        assert x['item'][0] != 0,  "Incorrect retry on error."

        assert 'items' in meta, "Missing items in meta."
        assert len(meta['items']) == batch_size, "Incorrect items batch size."
        assert isinstance(meta['items'][0], str), "Incorrect items type."

        assert 'data_timer' in meta, "Missing data_timer in meta."
        assert len(meta['data_timer']) == batch_size, "Incorrect data_timer batch size."
        assert isinstance(meta['data_timer'][0], MultiLevelTimer), "Incorrect items type."

        assert 'errors' in meta, "Missing errors in meta."
        assert len(meta['errors']) == batch_size, "Incorrect errors batch size."
        assert isinstance(meta['errors'][0], str), "Incorrect errors type."

        assert 'augs' in meta, "Missing augmentations in meta."
        assert len(meta['augs']) == batch_size, "Incorrect augmentations batch size."
        assert isinstance(meta['augs'][0], str), "Incorrect augmentations type."


import sys
def f(nums):
    min1=[float("inf")]*4
    max1=[float("-inf")]*4
    if len(nums)<3:
        return 1
    if len(nums)<6:
        a=float("-inf")
        for index in range(len(nums)):
            for index1 in range(index+1,len(nums)):
                for index2 in range(index1+1,len(nums)):
                    b=nums[index]*nums[index1]*nums[index2]
                    a=b if b>a else a
        print(a)
    else:
        for item in nums:
            for i in range(0,3):
                if item<min1[i]:
                    min1=(min1[0:i]+[item]+min1[i:])[0:3]
                    break
            for i in range(0,3):
                if item>max1[i]:
                    max1=(max1[0:i]+[item]+max1[i:])[0:3]
                    break
        print(min1)
        print(max1)
        nums=min1+max1
        a=1
        for index in range(len(nums)):
            for index1 in range(index+1,len(nums)):
                for index2 in range(index1+1,len(nums)):
                    b=nums[index]*nums[index1]*nums[index2]
                    a=b if b>a else a
        return a
try:
    count=0
    while True:
        line = sys.stdin.readline().strip()
        if count%2==0:
            count+=1
            continue
        else:
            if line == '':
                break
            lines = list(map(int,line.split()))
            count+=1
            print(f(lines))
except:
    pass

offer/判断字符串是不是为二叉搜索树的一个路径.py

判断字符串是不是为二叉搜索树的一个路径.py


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

from morp.compat import *
from morp.interface.sqs import SQS
from . import _InterfaceTest

class InterfaceTest(_InterfaceTest):
    interface_class = SQS

    def test_send_recv_aws_encryption(self):
        config = self.get_config(KmsMasterKeyId="alias/aws/sqs")
        inter = self.get_interface(config)
        name = self.get_name()

        fields1 = inter.send(name, self.get_fields())
        fields2 = inter.recv(name)
        self.assertEqualFields(fields1, fields2)

        inter.ack(name, fields2)

    def test_get_attrs(self):
        inter = self.get_interface()
        attrs = inter.get_attrs(KmsMasterKeyId="foo-bar", KmsDataKeyReusePeriodSeconds=3600)
        self.assertTrue("KmsMasterKeyId" in attrs)


from enum import Enum
from flask import Flask
from flask_restplus import Api, Resource, fields, reqparse

app = Flask(__name__)
api = Api(app)

# Перечисление для выбора поля сортировки
class SortingField(Enum):
    NAME = 'name'  # Для сортировки по имени
    AGE = 'age'    # Для сортировки по возрасту
    GROUP = 'group'  # Для сортировки по группе

# Перечисление для порядка сортировки
class SortOrder(Enum):
    ASC = 'asc'    # Порядок сортировки по возрастанию
    DESC = 'desc'  # Порядок сортировки по убыванию

class SubjectGrade:
    def __init__(self, subject, grade):
        self.subject = subject
        self.grade = grade

    def to_dict(self):
        return {'subject': self.subject, 'grade': self.grade}

class Student:
    # Счетчик добавленных студентов, используется для идентификаторов
    student_id_counter = 0

    def __init__(self, name, age, group, year_of_study):
        Student.student_id_counter += 1
        self.uid = Student.student_id_counter
        self.name = name
        self.age = age
        self.group = group
        self.year_of_study = year_of_study
        self.subjects_grades = []

    def add_subject_grade(self, subject, grade):
        subject_grade = SubjectGrade(subject, grade)
        self.subjects_grades.append(subject_grade)

    def to_dict(self, include_uid=True):
        student_dict = {'name': self.name, 'age': self.age,
                        'group': self.group, 'year_of_study': self.year_of_study}
        if include_uid:
            student_dict['uid'] = self.uid
        student_dict['subjects_grades'] = [sg.to_dict() for sg in self.subjects_grades]
        return student_dict

# Сортировка студентов
def sort_students(students, field: SortingField, sort_order: SortOrder):
    if field == SortingField.NAME:
        students.sort(key=lambda x: x.name, reverse=(sort_order == SortOrder.DESC))
    elif field == SortingField.AGE:
        students.sort(key=lambda x: x.age, reverse=(sort_order == SortOrder.DESC))
    elif field == SortingField.GROUP:
        students.sort(key=lambda x: x.group, reverse=(sort_order == SortOrder.DESC))

    return students

# Получение статистики по студентам
def get_subject_statistics(students):
    subject_statistics = {}

    for student in students:
        for subject_grade in student.subjects_grades:
            subject = subject_grade.subject
            grade = subject_grade.grade

            if subject not in subject_statistics:
                subject_statistics[subject] = {'grades': [grade], 'count': 1, 'average_grade': grade}
            else:
                subject_statistics[subject]['grades'].append(grade)
                subject_statistics[subject]['count'] += 1
                subject_statistics[subject]['average_grade'] = sum(subject_statistics[subject]['grades']) / len(subject_statistics[subject]['grades'])

    return subject_statistics

# Пример данных о студентах
students_data = [
    Student('Иванов Иван Иванович', 19, 'ИТ22-1', 4),
    Student('Сидоров Петр Петрович', 20, 'ИТ22-1', 4),
    Student('Петрова Анна Владимировна', 21, 'ИТ22-2', 3),
    Student('Смирнов Алексей Дмитриевич', 22, 'ИТ22-2', 3),
    Student('Козлова Екатерина Сергеевна', 20, 'ИТ22-1', 4)
]

# Добавим оценки по предметам (пятибалльная шкала) для каждого студента
students_data[0].add_subject_grade('Программирование', 4)
students_data[0].add_subject_grade('Базы данных', 5)
students_data[0].add_subject_grade('Веб-разработка', 3)

students_data[1].add_subject_grade('Программирование', 5)
students_data[1].add_subject_grade('Базы данных', 4)
students_data[1].add_subject_grade('Веб-разработка', 4)

students_data[2].add_subject_grade('Программирование', 3)
students_data[2].add_subject_grade('Веб-разработка', 4)

students_data[3].add_subject_grade('Программирование', 4)
students_data[3].add_subject_grade('Базы данных', 3)
students_data[3].add_subject_grade('Веб-разработка', 5)

students_data[4].add_subject_grade('Программирование', 5)
students_data[4].add_subject_grade('Базы данных', 4)
students_data[4].add_subject_grade('Веб-разработка', 5)

# Модели API
subject_grade_model = api.model('SubjectGrade', {
    'subject': fields.String(required=True, description='Название предмета'),
    'grade': fields.Integer(required=True, description='Оценка')
})

student_model = api.model('Student', {
    'uid': fields.Integer(readonly=True, description='Идентификатор студента'),
    'name': fields.String(required=True, description='Имя студента'),
    'age': fields.Integer(required=True, description='Возраст студента'),
    'group': fields.String(required=True, description='Группа студента'),
    'year_of_study': fields.Integer(required=True, description='Год обучения студента'),
    'subjects_grades': fields.List(fields.Nested(subject_grade_model), description='Список оценок по предметам')
})

students_list = api.model('StudentsList', {
    'count': fields.Integer(required=True, description='Количество студентов'),
    'items': fields.List(fields.Nested(student_model), required=True, description='Список студентов')
})

subject_statistics_model = api.model('SubjectStatistics', {
        'subject': fields.String(description='Название предмета'),
        'count': fields.Integer(description='Количество студентов, изучающих предмет'),
        'average_grade': fields.Float(description='Средняя оценка по предмету')
    })

overall_statistics_model = api.model('OverallStatistic', {
    'average_age': fields.Float(description='Средний возраст'),
    'student_count': fields.Integer(description='Количество студентов'),
    'subject_statistics': fields.List(fields.Nested(subject_statistics_model), description='Статистика по каждому предмету')
})

# Парсер параметров сортировки
parser = reqparse.RequestParser()
parser.add_argument('sort_by', type=SortingField, help='Сортировка по имени, возрасту или группе')
parser.add_argument('sort_order', type=SortOrder, help='Порядок сортировки: asc или desc')

students_ns = api.namespace('students', description='Операции со студентами')

@students_ns.route('/students')
class StudentsResource(Resource):
    @students_ns.doc('Список всех студентов')
    @students_ns.expect(parser)
    @students_ns.marshal_with(students_list)
    def get(self):
        """
        Список всех студентов.
        """
        args = parser.parse_args()
        sort_by = args.get('sort_by', None)
        sort_order = args.get('sort_order', None)

        sorted_students = sort_students(students_data.copy(), sort_by, sort_order)
        student_list = [student.to_dict() for student in sorted_students]
        return {'count': len(student_list), 'items': student_list}

    @students_ns.doc('Добавление нового студента')
    @students_ns.expect(student_model)
    @students_ns.marshal_with(student_model)
    def post(self):
        """
        Добавление нового студента.
        """
        new_student_data = api.payload
        new_student = Student(
            name=new_student_data['name'],
            age=new_student_data['age'],
            group=new_student_data['group'],
            year_of_study=new_student_data['year_of_study']
        )

        if 'subjects_grades' in new_student_data:
            for subject_grade_data in new_student_data['subjects_grades']:
                new_student.add_subject_grade(subject_grade_data['subject'], subject_grade_data['grade'])

        students_data.append(new_student)
        return new_student.to_dict()

@students_ns.route('/students/<int:id>')
class StudentResource(Resource):
    @students_ns.doc('Получение студента')
    @students_ns.marshal_with(student_model)
    def get(self, id):
        """
        Получение студента по идентификатору.
        """
        for student in students_data:
            if student.uid == id:
                return student.to_dict()

        api.abort(404, message=f"Студент с идентификатором {id} не найден")

    @students_ns.doc('Обновление данных студента')
    @students_ns.expect(student_model)
    @students_ns.marshal_with(student_model)
    def patch(self, id):
        """
        Обновление данных студента по идентификатору.
        """
        update_data = api.payload
        for student in students_data:
            if student.uid == id:
                # Обновление информации о студенте
                for field, value in update_data.items():
                    setattr(student, field, value)

                return student.to_dict()

        api.abort(404, message=f"Студент с идентификатором {id} не найден")

    @students_ns.doc('Удаление студента')
    @students_ns.response(204, 'Студент удален')
    def delete(self, id):
        """
        Удаление студента по идентификатору.
        """
        global students_data
        students_data = [student for student in students_data if student.uid != id]
        return '', 204

    @students_ns.route('/students/<int:id>/grades')
    class StudentGradesResource(Resource):
        @students_ns.doc('Получение оценок студента')
        @students_ns.marshal_with(subject_grade_model, as_list=True)
        def get(self, id):
            """
            Получение оценок студента.
            """

            for student in students_data:
                if student.uid == id:
                    return [sg.to_dict() for sg in student.subjects_grades]

            api.abort(404, message=f"Студент с идентификатором {id} не найден")

        @students_ns.doc('Добавление оценок студенту')
        @students_ns.expect(subject_grade_model)
        @students_ns.marshal_with(subject_grade_model)
        def post(self, id):
            """
            Добавление оценок студенту.
            """

            for student in students_data:
                if student.uid == id:
                    student.add_subject_grade(api.payload['subject'], api.payload['grade'])
                    return student.subjects_grades[-1].to_dict()

            api.abort(404, message=f"Студент с идентификатором {id} не найден")

@students_ns.route('/statistics')
class OverallStatisticsResource(Resource):
    @students_ns.doc('Получение общей статистики по всем студентам')
    @students_ns.marshal_with(overall_statistics_model)
    def get(self):
        """
        Получение общей статистики по всем студентам.
        """
        if not students_data:
            api.abort(404, message="Студенты не найдены")

        # Расчет среднего возраста для всех студентов
        average_age = sum(student.age for student in students_data) / len(students_data)

        # Получение статистики по предметам
        subject_statistics = get_subject_statistics(students_data)

        return {
            'average_age': average_age,
            'student_count': len(students_data),
            'subject_statistics': [{'subject': subject, **stats} for subject, stats in subject_statistics.items()]
        }

if __name__ == '__main__':
    app.run(debug=True)


"""empty message

Revision ID: c3880377ac48
Revises: 8dc5999a5c74
Create Date: 2020-02-04 15:44:28.982771

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c3880377ac48'
down_revision = '8dc5999a5c74'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('Artist', sa.Column('type', sa.String(length=120), nullable=True))
    op.add_column('Shows', sa.Column('type', sa.String(length=120), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('Shows', 'type')
    op.drop_column('Artist', 'type')
    # ### end Alembic commands ###


import os
import numpy as np
from Bio import SeqIO
import logging
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder

def import_epigenetic_dataset(files_path, cell_line, perc=1.0):
    if cell_line not in ["GM12878", "HelaS3", "HepG2", "K562"]:
        raise ValueError("Illegal cell line.")

    epigenetic_data_path = "{}/{}_200bp_Data.txt".format(files_path, cell_line)
    if not os.path.exists(epigenetic_data_path):
        raise FileNotFoundError("file {} not found".format(epigenetic_data_path))

    labels_path = "{}/{}_200bp_Classes.txt".format(files_path, cell_line)
    if not os.path.exists(labels_path):
        raise FileNotFoundError("file {} not found".format(labels_path))

    logging.debug("Importing epigenetic data of {} cell line".format(cell_line))
    epigenetic_data = np.loadtxt(epigenetic_data_path)

    with open(labels_path, "r") as f:
        labels = np.array([line.strip() for line in f.readlines()])

    X, y = subsample_data(epigenetic_data, labels, perc=perc)

    return X, y

def import_sequence_dataset(files_path, cell_line, perc=1.0):
    if cell_line not in ["GM12878", "HelaS3", "HepG2", "K562"]:
        raise ValueError("Illegal cell line.")

    seqeences_path = "{}/{}.fa".format(files_path, cell_line)
    if not os.path.exists(seqeences_path):
        raise FileNotFoundError("file {} not found".format(seqeences_path))

    labels_path = "{}/{}_200bp_Classes.txt".format(files_path, cell_line)
    if not os.path.exists(labels_path):
        raise FileNotFoundError("file {} not found".format(labels_path))

    logging.debug("Importing sequence data of {} cell line".format(cell_line))
    ltrdict = {'a': [1, 0, 0, 0, 0], 'c': [0, 1, 0, 0, 0],
               'g': [0, 0, 1, 0, 0], 't': [0, 0, 0, 1, 0],
               'n': [0, 0, 0, 0, 1]}
    with open(seqeences_path) as f:
        fasta_sequences = SeqIO.parse(f, 'fasta')
        sequences_data = np.array([np.array([ltrdict[x]
                                             for x in (str(fasta.seq)).lower()]) for fasta in fasta_sequences])

    with open(labels_path, "r") as f:
        labels = np.array([line.strip() for line in f.readlines()])

    X, y = subsample_data(sequences_data, labels, perc=perc)

    return X, y

def subsample_data(X, y, perc=1.0):
    if not 0.0 <= perc <= 1.0:
        raise ValueError("Illegal Percentage")

    if perc == 1.0:
        return X, y
    else:
        n = len(X)
        indices = np.random.choice(np.arange(0, n), int(n*perc))
        return X[indices], y[indices]

def get_data(experiment, files_path, cell_line, perc):
    d = {'bayesianMLP': import_epigenetic_dataset,
         'bayesianCNN': import_sequence_dataset,
         'fixedCNN': import_sequence_dataset}

    return d[experiment](files_path, cell_line, perc)

def split(X, y, random_state=42, test_perc=0.3, proportions=None, mode='u'):
    if mode not in ['u', 'fb', 'b']:
        raise ValueError("Illegal mode value")

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_perc, random_state=random_state)

    if mode != 'u':
        X_train, y_train = downsample_data(X_train, y_train, max_size_given=3000)

    if mode == 'fb':
        X_test, y_test = resampling_with_proportion(X_test, y_test, proportions)

    return X_train, X_test, y_train, y_test

def filter_by_tasks(X, y, task):
    if len(task) != 2:
        raise ValueError("Illegal task dimension")

    new_y = [(i, t["name"]) for t in task for i, label in enumerate(y) if label in t["labels"]]
    res = [[i for i, j in new_y],
           [j for i, j in new_y]]
    indices, y = np.array(res[0]), np.array(res[1])
    X = X[indices]

    return X, y

# TODO: probably useless
# def split_2(X, y, random_state=42, proportions=None, mode='u'):
#     if mode not in ['u', 'fb', 'b']:
#         raise ValueError("Illegal mode value")
#
#     splitters_dict = {'u': unbalanced_splitting,
#                       'fb': full_balanced_splitting,
#                       'b': balanced_splitting}
#     splitter = splitters_dict[mode]
#
#     if proportions:
#         return splitter(X, y, random_state=random_state, proportions=proportions)
#     else:
#         return splitter(X, y, random_state=random_state)

# TODO: add constant for 7
# TODO: testing!!!
# def full_balanced_splitting(X, y, test_perc=0.3, random_state=42, proportions=np.array([1, 1, 1, 2, 2, 1, 10])):
#     if len(proportions) >= 7:
#         raise ValueError("proportion length must be maximum 7 (number of classes)")
#
#     X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_perc, random_state=random_state)
#     X_train, y_train = downsample_data(X_train, y_train, max_size_given=3000)
#     X_test, y_test = resampling_with_proportion(X_test, y_test, proportions)
#
#     return X_train, X_test, y_train, y_test
#
#
# def balanced_splitting(X, y, test_perc=0.3, random_state=42):
#     X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_perc, random_state=random_state)
#     X_train, y_train = downsample_data(X_train, y_train, max_size_given=3000)
#
#     return X_train, X_test, y_train, y_test
#
#
# def unbalanced_splitting(X, y, test_perc=0.3, random_state=42):
#     return train_test_split(X, y, test_size=test_perc, random_state=random_state)

# TODO: fixing replace in sampling
def get_indices(indices, sample_sizes, n_classes, replace=False):
    indices_range = np.arange(len(indices))
    indices_all = np.concatenate([np.random.choice(indices_range[indices == i],
                                                   size=sample_sizes[i], replace=replace) for i in range(n_classes)])

    return indices_all

def downsample_data(data, classes, max_size_given):
    if max_size_given < 0:
        raise ValueError("max_size_given must be greater than 0")
    u, indices = np.unique(classes, return_inverse=True)
    num_u = len(u)
    sample_sizes = np.bincount(indices)

    size_min = np.amin(sample_sizes)

    if size_min < max_size_given:
        max_size_given = size_min
    sample_sizes[sample_sizes > max_size_given] = max_size_given

    indices_all = get_indices(indices, sample_sizes, num_u)
    data = data[indices_all, :]
    classes = classes[indices_all]

    return data, classes

def resampling_with_proportion(data, classes, proportions):
    u, indices = np.unique(classes, return_inverse=True)
    num_u = len(u)

    if num_u != len(proportions):
        raise ValueError("Proportions length doesn't match with number of classes")

    index_max_prop = np.argmax(proportions)
    sizes = np.bincount(indices)
    sample_sizes = [int(round(sizes[index_max_prop] * (prop / proportions[index_max_prop]))) for prop in proportions]

    indices_all = get_indices(indices, sample_sizes, num_u, replace=True)
    data = data[indices_all, :]
    classes = classes[indices_all]

    return data, classes

def encoding_labels(y):
    encoder = LabelEncoder()
    encoder.fit(y)
    y = encoder.transform(y)
    return y


import cv2 as cv
import numpy as np

def video():
    capture = cv.VideoCapture(0)
    while(True):
        ret ,frame = capture.read()
        frame = cv.flip(frame,1)
        if ret == False:
            break
        hsv = cv.cvtColor(frame,cv.COLOR_BGR2HSV)
        lower_hsv = np.array([0, 43, 46])
        upper_hsv = np.array([10, 255, 255])
        mask = cv.inRange(hsv,lowerb=lower_hsv,upperb=upper_hsv)
        cv.imshow("video",frame)
        cv.imshow("mask",mask)
        c = cv.waitKey(50)
        if c == 27:
            cv.destroyAllWindows()
            break

video()


from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

from apitools.base.py import list_pager
from googlecloudsdk.api_lib.container.vmware import client
from googlecloudsdk.api_lib.container.vmware import update_mask
from googlecloudsdk.command_lib.container.vmware import flags

class ClustersClient(client.ClientBase):
  """Client for clusters in gkeonprem vmware API."""

  def __init__(self, **kwargs):
    super(ClustersClient, self).__init__(**kwargs)
    self._service = self._client.projects_locations_vmwareClusters

  def List(self, args):
    """Lists Clusters in the GKE On-Prem VMware API."""
    list_req = (
        self._messages.GkeonpremProjectsLocationsVmwareClustersListRequest(
            parent=self._location_ref(args).RelativeName()))

    return list_pager.YieldFromList(
        self._service,
        list_req,
        field='vmwareClusters',
        batch_size=flags.Get(args, 'page_size'),
        limit=flags.Get(args, 'limit'),
        batch_size_attribute='pageSize')

  def Enroll(self, args):
    """Enrolls a VMware cluster to Anthos."""
    kwargs = {
        'adminClusterMembership': self._admin_cluster_membership_name(args),
        'vmwareClusterId': self._user_cluster_id(args),
        'localName': flags.Get(args, 'local_name'),
    }
    enroll_vmware_cluster_request = self._messages.EnrollVmwareClusterRequest(
        **kwargs)
    req = self._messages.GkeonpremProjectsLocationsVmwareClustersEnrollRequest(
        parent=self._user_cluster_parent(args),
        enrollVmwareClusterRequest=enroll_vmware_cluster_request,
    )
    return self._service.Enroll(req)

  def Unenroll(self, args):
    """Unenrolls an Anthos cluster on VMware."""
    kwargs = {
        'name': self._user_cluster_name(args),
        'force': flags.Get(args, 'force'),
    }
    req = (
        self._messages.GkeonpremProjectsLocationsVmwareClustersUnenrollRequest(
            **kwargs))
    return self._service.Unenroll(req)

  def Delete(self, args):
    """Deletes an Anthos cluster on VMware."""
    kwargs = {
        'name': self._user_cluster_name(args),
        'allowMissing': flags.Get(args, 'allow_missing'),
        'validateOnly': flags.Get(args, 'validate_only'),
        'force': flags.Get(args, 'force'),
    }
    req = self._messages.GkeonpremProjectsLocationsVmwareClustersDeleteRequest(
        **kwargs)
    return self._service.Delete(req)

  def Create(self, args):
    """Creates an Anthos cluster on VMware."""
    kwargs = {
        'parent': self._user_cluster_parent(args),
        'validateOnly': flags.Get(args, 'validate_only'),
        'vmwareCluster': self._vmware_cluster(args),
        'vmwareClusterId': self._user_cluster_id(args),
    }
    req = self._messages.GkeonpremProjectsLocationsVmwareClustersCreateRequest(
        **kwargs)
    return self._service.Create(req)

  def Update(self, args):
    kwargs = {
        'name':
            self._user_cluster_name(args),
        'allowMissing':
            args.allow_missing,
        'updateMask':
            update_mask.get_update_mask(
                args, update_mask.VMWARE_CLUSTER_ARGS_TO_UPDATE_MASKS),
        'validateOnly':
            args.validate_only,
        'vmwareCluster':
            self._vmware_cluster(args),
    }
    req = self._messages.GkeonpremProjectsLocationsVmwareClustersPatchRequest(
        **kwargs)
    return self._service.Patch(req)

  def _vmware_cluster(self, args):
    """Constructs proto message VmwareCluster."""
    kwargs = {
        'name': self._user_cluster_name(args),
        'adminClusterMembership': self._admin_cluster_membership_name(args),
        'description': flags.Get(args, 'description'),
        'onPremVersion': flags.Get(args, 'version'),
        'networkConfig': self._vmware_network_config(args),
        'loadBalancer': self._vmware_load_balancer_config(args),
    }
    if any(kwargs.values()):
      return self._messages.VmwareCluster(**kwargs)
    return None

  def _vmware_network_config(self, args):
    """Constructs proto message VmwareNetworkConfig."""
    kwargs = {
        'serviceAddressCidrBlocks':
            flags.Get(args, 'service_address_cidr_blocks'),
        'podAddressCidrBlocks':
            flags.Get(args, 'pod_address_cidr_blocks'),
    }
    if any(kwargs.values()):
      return self._messages.VmwareNetworkConfig(**kwargs)
    return None

  def _vmware_load_balancer_config(self, args):
    """Constructs proto message VmwareLoadBalancerConfig."""
    kwargs = {
        'f5Config': self._vmware_f5_big_ip_config(args),
        'metalLbConfig': self._vmware_metal_lb_config(args),
        'vipConfig': self._vmware_vip_config(args),
    }
    if any(kwargs.values()):
      return self._messages.VmwareLoadBalancerConfig(**kwargs)
    return None

  def _vmware_vip_config(self, args):
    """Constructs proto message VmwareVipConfig."""
    kwargs = {
        'controlPlaneVip': flags.Get(args, 'control_plane_vip'),
        'ingressVip': flags.Get(args, 'ingress_vip'),
    }
    if any(kwargs.values()):
      return self._messages.VmwareVipConfig(**kwargs)
    return None

  def _vmware_f5_big_ip_config(self, args):
    """Constructs proto message VmwareF5BigIpConfig."""
    kwargs = {
        'address': flags.Get(args, 'f5_config_address'),
        'partition': flags.Get(args, 'f5_config_partition'),
        'snatPool': flags.Get(args, 'f5_config_snat_pool'),
    }
    if any(kwargs.values()):
      return self._messages.VmwareF5BigIpConfig(**kwargs)
    return None

  def _vmware_metal_lb_config(self, args):
    """Constructs proto message VmwareMetalLbConfig."""
    kwargs = {
        'addressPools': self._address_pools(args),
    }
    if any(kwargs.values()):
      return self._messages.VmwareMetalLbConfig(**kwargs)
    return None

  def _address_pools(self, args):
    """Constructs proto message field address_pools."""
    address_pools = []
    address_pool_flag_value = flags.Get(args, 'metal_lb_config_address_pools')
    if address_pool_flag_value:
      for address_pool in address_pool_flag_value:
        address_pools.append(self._vmware_address_pool(address_pool))
    return address_pools

  def _vmware_address_pool(self, address_pool_args):
    """Constructs proto message VmwareAddressPool."""
    kwargs = {
        'addresses': address_pool_args.get('addresses', []),
        'avoidBuggyIps': address_pool_args.get('avoid_buggy_ips', False),
        'manualAssign': address_pool_args.get('manual_assign', False),
        'pool': address_pool_args.get('pool', ''),
    }
    if any(kwargs.values()):
      return self._messages.VmwareAddressPool(**kwargs)
    return None


import matplotlib.dates as mdates
import mplcursors
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg

spline = False
labels = {}

class MlpTimelineCanvas(FigureCanvasQTAgg):
    '''
    Класс холста Qt для помещения рисунка Matplotlib
    '''

    def __init__(self, fig):
        FigureCanvasQTAgg.__init__(self, fig)
        self.setMinimumSize(200, 200)
        self.labels = {}

def prepare_canvas(layout=None):
    '''
    Функция для инициализации рисунка Matplotlib и его размещения в виджете Qt
    '''
    # Подготовка рисунка и осей
    fig, axes = plot_single_empty_graph()
    # Получение экземпляра класса холста с размещенным рисунком
    canvas = MlpTimelineCanvas(fig)
    # Добавление виджета холста с рисунком в размещение
    layout.addWidget(canvas)
    return canvas

def plot_single_empty_graph():
    '''
    Функция для подготовки рисунка с пустыми осями и предварительного их оформления, без задания данных
    '''
    fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(10, 7), dpi=85, facecolor='white', frameon=True,
                             edgecolor='black', linewidth=1)
    fig.subplots_adjust(wspace=0.4, hspace=0.6, left=0.15, right=0.85, top=0.9, bottom=0.1)
    axes.grid(True, c='lightgrey', alpha=0.5)
    axes.set_xlabel('Дата статьи', fontsize=8)
    axes.set_ylabel('Частота', fontsize=8)
    return fig, axes

def func(t, A, h, T, phi):
    return A * np.exp(-h * t) * np.sin(2 * np.pi / T * t + phi)

def plot_draw_lines(data, canvas):
    ax = canvas.figure.get_children()[1]
    ax.cla()
    global labels
    labels = {}
    lines = {}
    for key, item in data.items():
        color = '#%02x%02x%02x' % (item[0][0], item[0][1], item[0][2])
        x = mdates.date2num(item[1])
        y = np.array(item[2])
        coeffs = np.polyfit(x, y, 5)
        poly_eqn = np.poly1d(coeffs)
        y_hat = np.array([a - 0.005 if a > 0.005 else a for a in poly_eqn(x)])
        xx = np.linspace(x.min(), x.max(), len(x))
        lines[key] = item[3]
        if spline:
            ax.plot(xx, y_hat, c=color, label=key + '_line')
            ax.fill_between(xx, y_hat, y2=0, color=color, alpha=0.2)
        else:
            ax.plot(item[1], y_hat, c=color, label=key + '_line')
            ax.fill_between(item[1], y_hat, color=color, alpha=0.2)
        pl = ax.plot(item[1], y, 'ro', c=color, label=key)

    labels = lines
    mplcursors.cursor(ax).connect("add", get_plot_label)
    canvas.draw()

def get_plot_label(sel):
    if sel.target.index == int(sel.target.index) and sel.artist.get_label() in labels:
        text = labels[sel.artist.get_label()][sel.target.index]
        # перенос по строкам в анотации графика
        size = 100
        end = ''
        parts = []
        for i in range(0, len(text), size):
            part = end + text[i:i + size]
            end = ''
            last_space = part.rindex(' ')
            if last_space > 0:
                end = part[last_space + 1:]
                part = part[:last_space + 1]
            parts.append(part)
        sel.annotation.set_text('\n'.join(parts))
    else:
        sel.annotation.set_visible(False)


#@PydevCodeAnalysisIgnore
"""add_water_level_attr

Revision ID: 0bbe624e28b8
Revises: 65a56457757f
Create Date: 2020-12-18 11:58:29.886532

"""
from alembic import op
from sqlalchemy.orm.session import Session
import sqlalchemy as sa

# revision identifiers, used by Alembic.
from yasmine.app.enums.xml_node import XmlNodeEnum
from yasmine.app.models import XmlNodeAttrModel, XmlNodeAttrWidgetModel, XmlNodeModel, XmlNodeAttrRelationModel

revision = '0bbe624e28b8'
down_revision = '65a56457757f'
branch_labels = None
depends_on = None

def upgrade():
    bind = op.get_bind()
    session = Session(bind=bind)
    float_field = session\
        .query(XmlNodeAttrWidgetModel)\
        .filter(XmlNodeAttrWidgetModel.name == 'yasmine-float-field')\
        .first()
    water_level = XmlNodeAttrModel(name='water_level', widget=float_field, index=100)

    station = session.query(XmlNodeModel).get(XmlNodeEnum.STATION)
    station.attrs.append(XmlNodeAttrRelationModel(attr=water_level))

    channel = session.query(XmlNodeModel).get(XmlNodeEnum.CHANNEL)
    channel.attrs.append(XmlNodeAttrRelationModel(attr=water_level))

    session.commit()

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###


T = int(input())

for Test in range(T):
    N = int(input())
    k, r, c = 0, 0, 0

    matric = []

    for row in range(N):
        tmp = list(map(int, input().split()))
        tmp_set = set(tmp)
        k += tmp[row]
        if len(tmp_set) != N: r +=1
        matric.append(tmp)
    for column in range(N):
        tmp = set()
        for row in range(N):
            if matric[row][column] in tmp:
                c+=1
                break
            tmp.add(matric[row][column])

    print("Case #{}: {} {} {}".format(Test+1, k, r, c))


import json_wrapper

f = open("/Users/maomaoyu/Downloads/e-learning/HKUSTx/hkustx-2016-09-11/HKUSTx-COMP102.1x-2T2015-prod.mongo")
of1 = open('/Users/maomaoyu/Downloads/e-learning/HKUSTx/hkustx-2016-09-11/commentthread.txt', 'w')
of2 = open('/Users/maomaoyu/Downloads/e-learning/HKUSTx/hkustx-2016-09-11/comment.txt', 'w')
line = f.readline()
# types = []
comment_text = []
commentthread_text = []
while line:
    obj = json_wrapper.loads(line)
    # print(obj['_type'])
    # threadtype
    if obj['_type'] == "CommentThread":
        commentthread_text = [obj['_id']['$oid'], obj['votes']['up_count'], obj['votes']['down_count'],
                              obj['votes']['count'], obj['votes']['point'], obj['thread_type'], obj['comment_count'],
                              obj['title'], obj['body'], obj['updated_at']['$date'], obj['created_at']['$date'],
                              obj['last_activity_at']['$date']]
        # for i in range(0, len(commentthread_text)):
        #     commentthread_text[i] = str(commentthread_text[i])
        commentthread_text = [str(x) for x in commentthread_text]
        output = '\t'.join(commentthread_text)
        output = output.replace('\n', '\\n')
        output += '\n'
        of1.write(output)

    if obj['_type'] == "Comment":
        comment_text = [obj['comment_thread_id']['$oid'], obj['votes']['up_count'], obj['votes']['down_count'],
                              obj['votes']['count'], obj['votes']['point'],
                              obj['body'], obj['updated_at']['$date'], obj['created_at']['$date']]
        comment_text = [str(x) for x in comment_text]
        output = '\t'.join(comment_text)
        output = output.replace('\n', '\\n')
        output += '\n'
        of2.write(output)

    line = f.readline()
f.close()
of1.close()
of2.close()


import time
import traceback
# import pyttsx3

import utils.constants as Constants
from actuators.actuator import Actuator

import logging
logger = logging.getLogger("mqtt-nao-interface.actuators.speech.tts")

class TextToSpeech(Actuator):
    """ Text to speech actuator. Processes direcctives that indicate what to say and how. """
    def __init__(self, nao_interface, id, mqtt_topic, qi_app, virtual=False):
        super(TextToSpeech, self).__init__(nao_interface, id, mqtt_topic, [Constants.NAO_SERVICE_TTS], qi_app, virtual)
        self.services[Constants.NAO_SERVICE_TTS].setLanguage("English")
        self.default_volume = 0.9
        self.default_speed = 90
        self.is_first_tts = True

    def actuate(self, directive_list):
        for directive in directive_list:
            splitted_directive = directive.split(Constants.STRING_SEPARATOR)
            logger.info(str(splitted_directive))
            if splitted_directive[0] == "say":
                try:
                    logger.debug("Setting is_speaking to True")
                    self.nao_interface.is_speaking = True
                    if self.nao_interface.is_listening:  # if I start saying something while audio is being captured, then I set to discard such a thing later
                        self.nao_interface.services["SpeechRecognizer"].stopListening(erase_detected=True)

                    sentence = str(splitted_directive[1])

                    """ Cleaning the sentence by replacing some stuff that cannot be said out loud (the list of things could be expanded) """
                    sentence = sentence.replace(":D", "")

                    volume = None
                    if splitted_directive[2] == "volume":
                        volume = round(float(splitted_directive[3])/100.0,2)
                    speed = None
                    if splitted_directive[4] == "speed":
                        speed = float(splitted_directive[5])
                    shape = None
                    if splitted_directive[6] == "tone":
                        shape = float(splitted_directive[7])
                    emotion = None
                    if len(splitted_directive)>8 and splitted_directive[7] == "emotion":
                        emotion = splitted_directive[8]

                    logger.info("-> "+str(sentence))
                    self.say(str(sentence), emotion, speed, shape, volume)

                    self.nao_interface.is_speaking = False
                    logger.debug("Setting is_speaking to False")

                except Exception:
                    logger.warning(traceback.format_exc())
                    logger.warning("Could not perform directive ", splitted_directive)
                    self.nao_interface.is_speaking = False
                    pass

    def say(self, sentence, emotion, speed, shape, volume):
        if not volume is None:
            logger.info("-> setting volume to " + str(volume))
            self.services[Constants.NAO_SERVICE_TTS].setVolume(volume)
        else:
            self.services[Constants.NAO_SERVICE_TTS].setVolume(self.default_volume)

        sub_sentences = sentence.split(".")
        for ss in sub_sentences:
            if (not emotion is None) and (emotion == "joy"):
                ss = "\\style=playful\\ " + ss
            if (not speed is None):
                ss = "\\rspd="+str(int(speed))+"\\"+ss
            if (not shape is None):
                ss = "\\vct="+str(int(shape))+"\\"+ss

            logger.info("---> " + str(ss))

            id = self.services[Constants.NAO_SERVICE_TTS].pCall("say", str(ss))
            self.services[Constants.NAO_SERVICE_TTS].wait(id)

        logger.debug("Finished saying sentences")


from .apibase import APIError, APIBase, APIResponse

FIELDS = {
	'ROSTER'		: 'members',
	'MEMBERS'		: 'members',
	'ACHIEVEMENTS'	: 'achievements',}

class GuildProfile(APIBase):
	_path = '/guild/%(realm)s/%(name)s'
	_params = 'fields=%(fields)s'

	@staticmethod
	def _ResolveField(field):
		if field in FIELDS:
			return FIELDS[field]
		elif field in ('all', 'ALL'):
			return ','.join(set(FIELDS.values())) # Only take unique field tags
		else:
			return field

	def QueryGuild(self, realm, name, fields = None, raw = False, region = None):
		if fields:
			if not isinstance(fields, str):
				fields = ','.join(list(map(GuildProfile._ResolveField, fields)))
		else:
			fields = ''
		if not region:
			region = self.region

		query = self.StartQuery(region = region)
		query.SetParams(realm = self._ToSlug(realm), name = name, fields = fields)

		data = query.GetData(raw)

		if raw:
			return data

		return GuildResponse(data)

class GuildResponse(APIResponse):
	pass


import numpy as np
import tensorflow as tf
import requests

# Beispieldaten zum Lernen (Außentemp/Vorlauf)  (noch einen zweiten graden ausdenken, für raum temp und anhand dessen 3satz)
train_data = np.array([[20,21,0.25], [10,21,0.4375], [0,21,0.5874], [-10,21,0.7125], [-20,21,0.85], [-30,21,1],
                       [20,23,0.15], [10,23,0.33], [0,23,0.47], [-10,23,0.61], [-20,23,0.75], [-30,23,0.9],
                       [20,25,0.05], [10,25,0.23], [0,25,0.37], [-10,25,0.51], [-20,25,0.65], [-30,25,0.8]], dtype=float)  #zum zurückrechnen /0,8 /100
# train_data = np.array([[20,20], [10,35], [0,50], [-10,65], [-20,80], [-30,95]], dtype=float)

# Eingang und Ausgang festlegen
x_train = train_data[:, :2]  # Außentemperatur
y_train = train_data[:, 2]   # Kesseltemp

# Benutzerdefinierte Initialisierungsfunktion (gewichtung zufälig zwischen -1 und 1)
def custom_initializer(shape, dtype=None):
    return tf.constant_initializer(minval = -1, maxval = 1)(shape, dtype)

# Modell erstellen
model = tf.keras.Sequential([
    tf.keras.layers.Dense(units=80, input_shape=[2], activation='relu'),
    tf.keras.layers.Dense(units=80, activation='relu'),
    tf.keras.layers.Dense(units=1, activation='sigmoid')
])

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

# Modell trainieren
model.fit(x_train, y_train, epochs=700)

temperature_celsius = 12
raumTemp = 21

rechnung = np.array([[temperature_celsius,raumTemp]], dtype=float)
ergebnis = model.predict(rechnung)
print("wertergebnis =")
print(ergebnis)

#gehen davon aus, das 80 grad kessel 100% ist
ergebnis = ergebnis * 100  # Mit 100 multiplizieren
ergebnis = ergebnis * 0.8  # Mit 0,8 multiplizieren

print("Ergebnis nach den Berechnungen:", ergebnis)

# API-Anfrage senden
url = "https://api.openweathermap.org/data/2.5/forecast"
params = {
    "q": "Krefeld",
    "appid": "e344fc9861dff7289176537e2060d323"
}

response = requests.get(url, params=params)

# JSON-Daten abrufen
data = response.json()

# Heutiges Datum im Format "YYYY-MM-DD"
heutiges_datum = data['list'][0]['dt_txt'][:10]

# Temperaturen für den heutigen Tag speichern
temperaturen = []

for eintrag in data['list']:
    datum_und_zeit = eintrag['dt_txt']
    temperatur_in_kelvin = eintrag['main']['temp']

    if datum_und_zeit.startswith(heutiges_datum):
        temperatur_in_celsius = temperatur_in_kelvin - 273.15
        temperaturen.append({
            'Uhrzeit': datum_und_zeit[11:],
            'Temperatur_in_Celsius': temperatur_in_celsius
        })

# Ergebnisse anzeigen
for eintrag in temperaturen:
    print(f"Uhrzeit: {eintrag['Uhrzeit']}, Temperatur (Celsius): {eintrag['Temperatur_in_Celsius']:.2f} °C")

# strg + shift + p


from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

b1 = KeyboardButton('/Найти_работника')
b2 = KeyboardButton('/Сделать_выборку_сотрудников_по_должности')
b3 = KeyboardButton('/Сделать_выборку_сотрудников_по_зарплате')
b4 = KeyboardButton('/Добавить_сотрудника')
b5 = KeyboardButton('/Удалить_сотрудника')
b6 = KeyboardButton('/Обновить_данные_сотрудника')
b7 = KeyboardButton('/Экспортировать_данные_в_формате_json')
b8 = KeyboardButton('/Экспортировать_данные_в_формате_csv')
b9 = KeyboardButton('/Закончить_работу_и_сохранить_изменения')
kb_client = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
kb_client.add(b1).add(b2).add(b3).add(b4).add(b5).add(b6).add(b7).add(b8).add(b9)

b10 = KeyboardButton('/id')
b11 = KeyboardButton('/Имя_и_Фамилия')
b12 = KeyboardButton('/Вернуться_в_предыдущее_меню')
kb_client1 = ReplyKeyboardMarkup(resize_keyboard=True)
kb_client1.add(b10, b11).add(b12)

b0 = KeyboardButton('/start')
kb_client0 = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
kb_client0.add(b0)


import os
from pathlib import Path
from shutil import copyfile

from deepclustering.manager import ConfigManger, yaml_load
from deepclustering.model import Model, to_Apex
from deepclustering.utils import fix_all_seed

from main import get_dataloader

DATA_PATH = Path(".data")
from analyze import AnalyzeInference

def get_config(checkpoint_path):
    DEFAULT_CONFIG = None
    assert "mnist" in checkpoint_path.lower() or "cifar" in checkpoint_path.lower() or "svhn" in checkpoint_path.lower()
    if "mnist" in checkpoint_path.lower():
        DEFAULT_CONFIG = os.path.join(checkpoint_path, "config_MNIST.yaml")
    if "cifar" in checkpoint_path.lower():
        DEFAULT_CONFIG = os.path.join(checkpoint_path, "config_CIFAR.yaml")
    if "svhn" in checkpoint_path.lower():
        DEFAULT_CONFIG = os.path.join(checkpoint_path, "config_SVHN.yaml")
    assert DEFAULT_CONFIG
    assert Path(checkpoint_path, "config.yaml").exists()
    copyfile(os.path.join(checkpoint_path, "config.yaml"), DEFAULT_CONFIG)
    assert Path(DEFAULT_CONFIG).exists() and Path(DEFAULT_CONFIG).is_file()
    config = yaml_load(DEFAULT_CONFIG)
    return config, DEFAULT_CONFIG

if __name__ == '__main__':
    # interface: python analyze_main checkpoint_path=runs/07_15_benchmark/strong/cifar_2/iicgeo
    DEFAULT_CONFIG = None
    checkpoint_path = ConfigManger(DEFAULT_CONFIG_PATH=DEFAULT_CONFIG, verbose=True, integrality_check=True).config[
        "checkpoint_path"]
    merged_config, DEFAULT_CONFIG = get_config(checkpoint_path)
    # correct save_dir and checkpoint_dir
    merged_config["Trainer"]["save_dir"] = checkpoint_path
    merged_config["Trainer"]["checkpoint_path"] = checkpoint_path
    merged_config["Trainer"]["max_epoch"] = 300

    # for reproducibility
    fix_all_seed(merged_config.get("Seed", 0))

    # get train loaders and validation loader
    train_loader_A, train_loader_B, val_loader = get_dataloader(merged_config, DEFAULT_CONFIG)

    # create model:
    model = Model(
        arch_dict=merged_config["Arch"],
        optim_dict=merged_config["Optim"],
        scheduler_dict=merged_config["Scheduler"],
    )
    # if use automatic precision mixture training
    model = to_Apex(model, opt_level=None, verbosity=0)
    AnalyzeInference.RUN_PATH = ""

    clusteringTrainer = AnalyzeInference(
        model=model,
        train_loader_A=train_loader_A,
        train_loader_B=train_loader_B,
        val_loader=val_loader,
        config=merged_config,
        **merged_config["Trainer"]
    )
    """ for feature extraction and retraining
    if "mnist" in DEFAULT_CONFIG.lower() or "svhn" in DEFAULT_CONFIG.lower():
        # for mnist (VGG styple network): `trunk`, `trunk.features[N]`, etc.
        clusteringTrainer.linear_retraining("head_B.heads[0]", lr=1e-4)
        clusteringTrainer.linear_retraining("trunk", lr=1e-4)
        clusteringTrainer.linear_retraining("trunk.features[11]", lr=1e-4)
        clusteringTrainer.linear_retraining("trunk.features[7]", lr=1e-4)
        clusteringTrainer.linear_retraining("trunk.features[3]", lr=1e-4)

    elif "cifar" in DEFAULT_CONFIG.lower():
        # for cifar (resnet style network):
        # `head_B.heads[0] with feature size 10`,
        # `trunk.avgpool with feature size 512`,
        # `trunk.layer4 with feature size 512, 3, 3`, etc...
        for i in range(5):
            try:
                clusteringTrainer.linear_retraining(f"head_B.heads[{i}]", lr=1e-4)
            except Exception as e:
                continue

        clusteringTrainer.linear_retraining("trunk", lr=1e-4)
        clusteringTrainer.linear_retraining("trunk.layer4", lr=1e-4)
        clusteringTrainer.linear_retraining("trunk.layer3", lr=1e-4)
        clusteringTrainer.linear_retraining("trunk.layer2", lr=1e-4)
    else:
        raise NotImplementedError("Only support mnist, cifar, and svhn.")
    """
    # supervised training part.
    # clusteringTrainer.supervised_training(use_pretrain=True, lr=1e-4, data_aug=True)
    # clusteringTrainer.supervised_training(use_pretrain=False, lr=1e-3, data_aug=True)
    # clusteringTrainer.supervised_training(use_pretrain=True, lr=1e-4, data_aug=False)
    # clusteringTrainer.supervised_training(use_pretrain=False, lr=1e-3, data_aug=False)
    # """

    # for t in (100, 20, 10, 1):
    #     clusteringTrainer.save_plot(temporature=t)

    # clusteringTrainer.draw_tsne(500)
    # clusteringTrainer.writer.close()

    clusteringTrainer.draw_IMSAT_table(num_samples=30)


from ts3tools import ts3tools

# plugin name (must be unique!)
name = 'test2'
base = None

# setup - initial plugin load
def setup(ts3base):
    global base
    base = ts3base

    # register plugin function as callback
    #base.register_callback(name, 'ts3.loop', test)

def test(values):
    global base
    base.send_receive('sendtextmessage targetmode=2 target=1 msg=' + ts3tools.escape_text('nope'))
    base.execute_callback(name + '.test', {})


# -*- coding: utf-8 -*-
# coding:utf-8
import os
import sys

device_id = sys.argv[1]

key = os.popen("adb devices -l").read()

for line in os.popen("adb -s " + device_id + " shell ps").read().splitlines():
    if line.find("com.android.commands.monkey") >= 0:
        os.popen("adb -s " + device_id + " shell kill " + line.split()[1])


import sympy
from random import randint
import base64
import io

from sympy import *
from numpy import *
import matplotlib.pyplot as plt
from sympy.parsing.sympy_parser import parse_expr

from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

plt.switch_backend('agg')

x, y = sympy.symbols('x y')

def Graficacion(fx):
    y = fx
    x = linspace(-5,5,100)
    y = eval(y)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.spines['left'].set_position('zero')
    ax.spines['right'].set_color('none')
    ax.spines['bottom'].set_position('zero')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.yaxis.set_ticks_position('left')

    plt.grid(alpha=.4,linestyle='--')

    plt.title("Funcion F(x): " + fx)

    plt.xlim(-8, 8)
    plt.ylim(-8, 8)

    plt.plot(x,y,'g')

    # Convert plot to PNG image
    pngImage = io.BytesIO()
    FigureCanvas(fig).print_png(pngImage)

    # Encode PNG image to base64 string
    pngImageB64String = "data:image/png;base64,"
    pngImageB64String += base64.b64encode(pngImage.getvalue()).decode('utf8')

    return pngImageB64String

def Newton(valor):

    fx = parse_expr(valor)

    resultados = []
    ER = 100
    ban = 0
    alerta = 0
    aleatorio = 2
    dx = sympy.diff(fx,x)

    while ER > 0:
        ban = ban + 1
        arriba = fx.subs(x,aleatorio)
        abajo = dx.subs(x,aleatorio)
        vx = round(aleatorio - float(arriba/abajo),4)

        if vx == 0:
            alerta = 1
            break
        else:
            VA = float((vx-aleatorio)/vx)
            VA = abs(round(VA,4))
            ER = round(VA * 100,4)

        if ban==1:
            resVX = vx
            resER = ER
        else:
            if ER < resER:
                resVX = vx
                resER = ER

        resultados.append(["Caso "+str(ban),vx,str(ER)+"%"])

        aleatorio = vx

        if ban > 20:
            break

    return resultados, alerta, resVX, resER


import z3
from miasm.ir.translators import Translator
from miasm.expression.expression import *

translator = Translator.to_language("z3")

values = [
    (42, 10, 4, 2),
    (-42, 10, -4, -2),
    (42, -10, -4, 2),
    (-42, -10, 4, -2)
]

for a, b, c, d in values:
    cst_a = ExprInt(a, 8)
    cst_b = ExprInt(b, 8)

    div_result = ExprInt(c, 8)
    div = ExprOp("sdiv", cst_a, cst_b)
    print("%d / %d == %d" % (a, b, div_result))
    solver = z3.Solver()
    print("%s == %s" %(div, div_result))
    eq1 = translator.from_expr(div) != translator.from_expr(div_result)
    solver.add(eq1)
    result = solver.check()
    assert result == z3.unsat

    mod_result = ExprInt(d, 8)
    print("%d %% %d == %d" % (a, b, mod_result))
    res2 = ExprOp("smod", cst_a, cst_b)
    solver = z3.Solver()
    print("%s == %s" %(res2, mod_result))
    eq2 = translator.from_expr(res2) != translator.from_expr(mod_result)
    solver.add(eq2)
    result = solver.check()
    assert result == z3.unsat


import wx
import wx.lib.throbber as  throb
import MatroxFramegrabber
import numpy as np

class wxSaviorTopPanel(wx.Panel):

    """Image acquisition control panel
    """

    def __init__(self,
                 parent,
                 matrox_frame_grabber_wx_event_generator,
                 local_savior_path = '.'):

        """
        """

        # default constructor using the parent window
        wx.Panel.__init__(self, parent, -1)

        self._matrox_frame_grabber_wx_event_generator = matrox_frame_grabber_wx_event_generator
        self._matrox_frame_grabber                    = matrox_frame_grabber_wx_event_generator.GetEventGenerator()
        self._matrox_frame_grabber_wx_event_generator.BindWXEvent("stats_ready", self._OnStatsUpdate)

        self.movie_number = 0

        # If we have a fixation GUI open, grab its reference
        if parent.fixQ is not None:
            self.fixQ = parent.fixQ

        # getting background and foreground colours from the parent panel
        self.SetBackgroundColour(parent.GetBackgroundColour())
        self.SetForegroundColour(parent.GetForegroundColour())

        # creating the sizer and defining control dimensions
        main_sizer             = wx.GridBagSizer(vgap = 10, hgap = 10)
        border                 = 0
        text_ctrl_width        = 40
        text_ctrl_height       = 15
        text_ctrl_size         = (text_ctrl_width, text_ctrl_height)

        # Defining the title font
        bold_font = self.GetFont()
        bold_font.SetWeight(wx.BOLD)
        bold_font.SetPointSize(bold_font.GetPointSize() + 2)
        self.SetFont(bold_font)

        ###################################################################
        #                      creating controls                          #
        ###################################################################

        # discard and image recording section #######################
        blank_icon                  = wx.Bitmap(local_savior_path + '/icons/blank icon.png',                 wx.BITMAP_TYPE_PNG)
        stop_icon                   = wx.Bitmap(local_savior_path + '/icons/Pause-Hot-icon 42.png',          wx.BITMAP_TYPE_PNG)
        live_icon                   = wx.Bitmap(local_savior_path + '/icons/play-normal-blue-bright 42.png', wx.BITMAP_TYPE_PNG)
        record_icon                 = wx.Bitmap(local_savior_path + '/icons/Record-Pressed-icon 42.png',     wx.BITMAP_TYPE_PNG)

        # creating the throbbers (initially in resting mode)
        self.mode_icons             = [stop_icon, live_icon, record_icon, blank_icon]
        throbber_delay              = 0.35
        self.current_mode_throbber = throb.Throbber(self, -1, self.mode_icons, frameDelay = throbber_delay)

        self.SetCurrentModeIcon('stop')

        # adding controls to the sizer
        main_sizer.Add(self.current_mode_throbber,
                       pos  = (0, 1),                               span   = (5, 1),
                       flag = wx.ALIGN_CENTER_VERTICAL|wx.ALL,      border = 0)

        label_acquisition_frame_rate_title = wx.StaticText(self, label = "Acquisition frame rate (FPS): ", style = wx.ALIGN_LEFT)
        self._acquisition_frame_rate_label = wx.StaticText(self, label = '0.0', style = wx.ALIGN_LEFT)

        self._video_writing_frame_rate_title   = wx.StaticText(self, label = "Writing frame rate (FPS): ")
        self._video_writing_rate_label   = wx.StaticText(self, label = '0.0')

        self._video_writing_frame_rate_title.Show(False)
        self._video_writing_rate_label.Show(False)
        self._video_number_label         = wx.StaticText(self, label = 'Not recording')
        self._video_frames_written_label = wx.StaticText(self, label = '0/0')

        self._video_frames_written_label.Show(False)

        main_sizer.Add(label_acquisition_frame_rate_title,
                       pos  = (1,  2),                    span   = (1, 1),
                       flag = wx.EXPAND | wx.ALL | wx.ALIGN_LEFT,                   border = border)
        main_sizer.Add(self._acquisition_frame_rate_label,
                       pos  = (1,  3),                    span   = (1, 1),
                       flag = wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, border = border)

        # size headers ####################################################
        self.temp_header_H               = wx.StaticText(self, label = "  H  ")
        self.temp_header_V               = wx.StaticText(self, label = "  V  ")

        # adding controls to the sizer
        main_sizer.Add(self.temp_header_H,
                       pos  = (1,  5),                              span   = (1, 1),
                       flag = wx.ALIGN_CENTER | wx.ALL, border = border)
        main_sizer.Add(self.temp_header_V,
                       pos  = (1,  6),                              span   = (1, 1),
                       flag = wx.ALIGN_CENTER | wx.ALL, border = border)

        # Image size in degrees  ##########################################
        label_text_imaging_fov_in_deg    = wx.StaticText(self, label = "Field of view (deg):")
        self.text_imaging_width_in_deg   = wx.StaticText(self, label = "2.0")
        self.text_imaging_width_in_deg.SetMinSize((text_ctrl_width, -1))
        label_imaging_x_in_deg           = wx.StaticText(self, label = "x")
        self.text_imaging_height_in_deg  = wx.StaticText(self, label = "2.0")

        # Frame size in pixels ############################################
        label_frame_size_in_pix          = wx.StaticText(self, label = "Image size (pix):")
        label_frame_size_in_pix.SetMinSize((2*text_ctrl_width, -1))
        self.text_frame_width_in_pix     = wx.StaticText(self, label = "     ")
        self.text_frame_width_in_pix.SetMinSize((text_ctrl_width, -1))
        label_frame_size_x               = wx.StaticText(self, label =  "x")
        self.text_frame_height_in_pix    = wx.StaticText(self, label = "     ")

        # adding controls to the sizer
        current_row = 2

        main_sizer.Add(self._video_writing_frame_rate_title,
                       pos  = (current_row,  2),                    span   = (1, 1),
                       flag = wx.EXPAND | wx.ALL| wx.ALIGN_LEFT,                   border = border)
        main_sizer.Add(self._video_writing_rate_label,
                       pos  = (current_row,  3),                    span   = (1, 1),
                       flag = wx.EXPAND | wx.ALIGN_LEFT| wx.ALL, border = border)

        main_sizer.Add(label_text_imaging_fov_in_deg,
                       pos  = (current_row,  4),                    span   = (1, 1),
                                          border = border)
        main_sizer.Add(self.text_imaging_width_in_deg,
                       pos  = (current_row,  5),                    span   = (1, 1),
                       border = border)
        main_sizer.Add(label_imaging_x_in_deg,
                       pos  = (current_row,  6),                    span   = (1, 1),
                       border = border)
        main_sizer.Add(self.text_imaging_height_in_deg,
                       pos  = (current_row, 7),                    span   = (1, 1),
                       border = border)

        current_row += 1
        main_sizer.Add(self._video_number_label,
                       pos  = (current_row,  2),                    span   = (1, 1),
                       flag = wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, border = border)

        main_sizer.Add(self._video_frames_written_label,
                       pos  = (current_row,  3),                    span   = (1, 1),
                       flag = wx.EXPAND | wx.ALIGN_LEFT | wx.ALL, border = border)

        main_sizer.Add(label_frame_size_in_pix,
                       pos  = (current_row,  4),                    span   = (1, 1),
                       border = border)
        main_sizer.Add(self.text_frame_width_in_pix,
                       pos  = (current_row,  5),                    span   = (1, 1),
                       border = border)
        main_sizer.Add(label_frame_size_x,
                       pos  = (current_row,  6),                    span   = (1, 1),
                       border = border)
        main_sizer.Add(self.text_frame_height_in_pix,
                       pos  = (current_row, 7),                    span   = (1, 1),
                       border = border)

        current_row += 1
        main_sizer.AddSizer((0,0),
                       pos  = (current_row, 10),                    span   = (1, 1),
                       flag = wx.EXPAND | wx.ALIGN_CENTER | wx.ALL, border = border)

        # making some columns and row growables
        #main_sizer.AddGrowableCol( 0, proportion = 1)
        main_sizer.AddGrowableCol( 2, proportion = .6)
        main_sizer.AddGrowableCol( 3, proportion = .4)
        # main_sizer.AddGrowableCol( 6, proportion = 2)
        # main_sizer.AddGrowableCol(12, proportion = 2)

        # Fitting the current panel to the needs of the sizer.
        self.SetSizerAndFit(main_sizer)

        # bind the onclose method
        wx.GetApp().GetTopWindow().Bind(wx.EVT_CLOSE, self.OnClose, wx.GetApp().GetTopWindow())
        self._main_sizer = main_sizer

        # end of constructor ##############################################

    def _OnStatsUpdate(self, event):

        matrox_frame_grabber =  self._matrox_frame_grabber_wx_event_generator.GetEventGenerator()

        if matrox_frame_grabber.GetCurrentState() == MatroxFramegrabber.RECORDING or\
            matrox_frame_grabber.GetCurrentState() == MatroxFramegrabber.PAUSED_RECORDING:

            self._video_writing_frame_rate_title.Show(True)
            self._video_writing_rate_label.Show(True)
            self._video_number_label.Show(True)
            self._video_frames_written_label.Show(True)
            self._main_sizer.Layout()
            avi_writing_frame_rate = matrox_frame_grabber.GetAVIWritingFrameRate()
            avi_writing_frame_rate = np.around(avi_writing_frame_rate, 2)

            avi_frames_written     = matrox_frame_grabber.GetCurrentAVIFrameNumber()
            avi_frames_to_write    = matrox_frame_grabber.GetNumberOfAVIFramesToWrite()

            self._video_writing_rate_label.SetLabel(str(avi_writing_frame_rate))

            saving_video_label   = "Saving movie # " + str(self.movie_number)
            frames_written_label = str(avi_frames_written) + '/' + str(avi_frames_to_write)

            self._video_number_label.SetLabel(saving_video_label)
            self._video_frames_written_label.SetLabel(frames_written_label)
        else:
            self._video_writing_frame_rate_title.Show(False)
            self._video_writing_rate_label.Show(False)
            self._video_number_label.Show(False)
            self._video_frames_written_label.Show(False)

        acquisition_rate = matrox_frame_grabber.GetAcquisitionFrameRate()
        display_rate     = matrox_frame_grabber.GetDisplayFrameRate()
        display_rate     = np.around(display_rate, 2)
        acquisition_rate     = np.around(acquisition_rate, 2)
        self._acquisition_frame_rate_label.SetLabel(str(acquisition_rate))

        self.Update()

        event.Skip()

    def OnClose(self, event):

        self.current_mode_throbber.Rest()
        event.Skip()

    def SetCurrentModeIcon(self, current_mode):

        """
        """

        if current_mode == 'live':
            # hiding the pause throbber
            self.current_mode_throbber.Stop()
            self.current_mode_throbber.SetSequence([1, 3])
            #self.current_mode_throbber.Start()

        elif current_mode == 'record':

            self.current_mode_throbber.Stop()
            self.current_mode_throbber.SetSequence([2, 3])
            #self.current_mode_throbber.Start()

        else:

            self.current_mode_throbber.Stop()
            self.current_mode_throbber.SetSequence([0, 0])

        # Force a repaint event
        self.Refresh()

    def ShowEyeTrackingIcon(self, boolean):
        ""
        ""
        pass
        #self.eye_tracking_icon.Show(boolean)

    def UpdateOpticalScannersAndImageSamplingDisplay(self,frame_width_in_deg,
                                                           frame_height_in_deg):

        """
        """

        frame_width_in_pix = self._matrox_frame_grabber.GetVideoWidth()
        frame_height_in_pix =  self._matrox_frame_grabber.GetVideoHeight()

        # getting sizes to guarantee alignment
        temp_size_left  = self.text_frame_width_in_pix.GetSize()
        temp_size_right = self.text_frame_height_in_pix.GetSize()

        # Frame size in pixels
        self.text_frame_width_in_pix.SetLabel(    str(frame_width_in_pix))
        self.text_frame_height_in_pix.SetLabel(   str(frame_height_in_pix))

        self.text_imaging_width_in_deg.SetLabel(  str(round(frame_width_in_deg,  2)))
        self.text_imaging_height_in_deg.SetLabel( str(round(frame_height_in_deg, 2)))

        # Update the fixation GUI as well
        if self.fixQ is not None:
            try:
                # 1 is for FOV changes
                self.fixQ.put( (1, round(frame_width_in_deg,  2),round(frame_height_in_deg,  2)),block=False, timeout=0 )
            except:
                pass

        # adjusting sizes
        self.text_frame_width_in_pix.SetSize(     temp_size_left)
        self.text_frame_height_in_pix.SetSize(    temp_size_right)
        self.text_imaging_width_in_deg.SetSize(   temp_size_left)
        self.text_imaging_height_in_deg.SetSize(  temp_size_right)

    def SetCurrentMovieNumber(self, movie_number):
        self.movie_number = movie_number

###################################################################
#                           Test code                             #
###################################################################

class TestApp(wx.App):

    def __init__ (self):

        wx.App.__init__(self)

        # initializing the window
        test_frame       = wx.Frame(None,
                                    size  = (700, 250),
                                    title = 'wxSaviorImageAcquisitionPanel test')

        self.SetTopWindow(test_frame)
        sizer = wx.BoxSizer(wx.VERTICAL)

        # creating panel
        self.test_panel      = wxSaviorTopPanel(test_frame)

        self.test_panel.UpdateOpticalScannersAndImageSamplingDisplay(
                             frame_width_in_pix            = 800,
                             frame_height_in_pix           = 750,
                             frame_width_in_deg            = 1.8,
                             frame_height_in_deg           = 1.7)

        sizer.Add(self.test_panel, wx.GROW)

        live_button = wx.Button(test_frame, label = "Start Live")
        sizer.Add(live_button)
        live_button.Bind(wx.EVT_BUTTON, self.OnLive)

        record_button = wx.Button(test_frame, label = "Start Record")
        sizer.Add(record_button)
        record_button.Bind(wx.EVT_BUTTON, self.OnRecord)

        stop_button = wx.Button(test_frame, label = "Stop")
        sizer.Add(stop_button)
        stop_button.Bind(wx.EVT_BUTTON, self.OnStop)

        test_frame.SetSizer(sizer)
        test_frame.Show()

        # starting the main event loop
        self.MainLoop()

    def OnLive(self, event):
        self.test_panel.SetCurrentModeIcon('live')
        event.Skip()

    def OnRecord(self, event):
        self.test_panel.SetCurrentModeIcon('record')
        event.Skip()

    def OnStop(self, event):
        self.test_panel.SetCurrentModeIcon('stop')
        event.Skip()

if __name__ == '__main__':

    # initializing the application
    app              = TestApp()


from asyncio import Lock

from pyrogram import filters
from pyrogram.types import Message

from TechlockRobot import pbot as app
from TechlockRobot import arq
from TechlockRobot.utils.dbfunctions import get_trust_db, update_trust_db
from TechlockRobot.utils.filter_groups import trust_group

spam_db = {}

lock_access = Lock()

async def get_spam_data(message: Message, text: str):
    async with lock_access:
        c, m = message.chat.id, message.message_id
        if c not in spam_db:
            spam_db[c] = {}
        if m not in spam_db[c]:
            data = (await arq.nlp(text)).result[0]
            spam_db[c][m] = data
        return spam_db[c][m]

@app.on_message(
    (filters.text | filters.caption)
    & ~filters.me
    & ~filters.private,
    group=trust_group,
)
async def trust_watcher_func(_, message: Message):
    # Sleeping so that we can get cached data created by
    # spam.py with get_spam_data function
    if message.command:
        return
    if not message.from_user:
        return
    user_id = message.from_user.id
    text = message.text or message.caption
    text = text.strip()
    if not text:
        return
    if len(text) < 2:
        return
    data = await get_spam_data(message, text)
    if isinstance(data, str):
        return
    spam = data.spam
    await update_trust_db(user_id, spam)

async def get_spam_probability(user_id) -> list:
    data = await get_trust_db(user_id)
    if not data:
        return [0, 0]
    mean = lambda x: sum(x) / len(x)
    spam = [i for i in data]
    return [mean(spam), len(spam)]


# 10001st prime

from math import sqrt

is_prime = lambda n: [i for i in range(2, int(sqrt(n) + 1)) if n % i == 0] == []

counter = 1
index = 1
result = 0

while index <= 10002:
    if is_prime(counter):
        result = counter
        index += 1

    counter += 1

print(result)


import av
import av.container
import czeditor.util.avhelper

import numpy as np

from PySide6.QtCore import QFileInfo

# PyAV video reader with intelligent seeking.
class PyAVSeekableVideoReader:

    def __init__(self, filename):
        self._filename = filename
        self._container: av.container.InputContainer = av.open(
            QFileInfo(self._filename).canonicalFilePath())
        self._stream = self._container.streams.video[0]
        self._currentFrame = 0
        self.frame_rate = float(self._stream.average_rate)
        self._keyframes = []
        self._container.streams.video[0].thread_type = "AUTO"
        self._stream.codec_context.skip_frame = "NONKEY"
        for frame in self._container.decode(self._stream):
            self._keyframes.append(
                int(frame.pts*self._stream.time_base*self.frame_rate))
        self._stream.codec_context.skip_frame = "DEFAULT"
        self._container.seek(0)
        theframe = next(self._container.decode(
            self._stream)).to_ndarray(format="rgb24")
        self._cachedFrame = np.full(
            (theframe.shape[0], theframe.shape[1], 4), 255, dtype=np.uint8)
        self._cachedFrame[:, :, :3] = theframe

    def seekForward(self, frame: int):
        self._currentFrame = frame
        for decodedFrame in self._container.decode(self._stream):
            if not (int(decodedFrame.pts*self._stream.time_base*self.frame_rate) < frame):
                return decodedFrame
        else:
            return decodedFrame

    def seek(self, frame: int) -> av.VideoFrame:
        if (self._currentFrame == frame):
            return self._cachedFrame
        self._container.seek(
            int(frame/self._stream.time_base/self.frame_rate), stream=self._stream)
        return self.seekForward(frame)

    def __getitem__(self, frame: int):
        if (frame < self._currentFrame):
            self._cachedFrame[:, :, :3] = self.seek(
                frame).to_ndarray(format="rgb24")
        if (frame > self._currentFrame):
            for i in self._keyframes:
                if i < frame and i > self._currentFrame:
                    self._cachedFrame[:, :, :3] = self.seek(
                        frame).to_ndarray(format="rgb24")
                    break
                elif i > frame:
                    self._cachedFrame[:, :, :3] = self.seekForward(
                        frame).to_ndarray(format="rgb24")
                    break
            else:
                self._cachedFrame[:, :, :3] = self.seekForward(
                    frame).to_ndarray(format="rgb24")
        return self._cachedFrame

    def __len__(self):
        return self._stream.frames

    def close(self):
        self._container.close()

class PyAVAudioWriter:

    def __init__(self, nextsamples, filename):
        self._filename = filename
        self._samplefunction = nextsamples

    def writeaudio(self, samples):
        self._container = av.open(self._filename, "w")
        self._stream = self._container.add_stream("mp3", 48000)
        self._stream.channels = 1
        self._stream.sample_rate = 48000
        self._currentsample = 0
        while self._currentsample < samples:
            frame = av.AudioFrame.from_ndarray(np.ndarray.astype(
                self._samplefunction(), "<f8"), format="dbl", layout="mono")
            frame.sample_rate = 48000
            for packet in self._stream.encode(frame):
                self._container.mux(packet)
            self._currentsample += 512
        self._container.close()