import os.path
import time
from selenium.webdriver.chrome.service import Service
import pandas as pd
from selenium import webdriver

driver = webdriver.Edge(service=Service(r'E:\WebDriver\msedgedriver.exe'))  # 这里浏览器驱动器的文件路径，我这里是edge最新的驱动器

# 根据给定的url地址，获取该页面的所有文章链接
def crawUrl(url):
    # try:
    driver.get(url)
    driver.refresh()
    # for i in range(1, 100):
    #
    #     # print('i===', i)
    #     element = driver.find_element_by_xpath('//*[@class="xpage-more-btn"]')
    #     driver.execute_script("arguments[0].click();", element)
    driver.execute_script('document.documentElement.scrollTop=100000')
    time.sleep(2)
    a = driver.find_elements_by_xpath('//a')  # 根据标签查找
    # except Exception:
    #     print('出现异常了')
    #     return None
    urls = []
    for floderurl in a:

            result = floderurl.get_attribute("href")
            urls.append(result)

    print("最终的uRL：", urls)
    return urls

# 根据给定的url链接获取到文本
def crawText(purl):
    text = ''
    try:
        driver.get(purl)
        text = driver.find_element_by_xpath('//*[@id="content"]/div[@class="post_body"]').text
    except Exception:
        return None
    print(text)

    return text

# 保存和加载数据
def save(lists):
    new = pd.DataFrame({
        '文本类别': lists['文本类别'],
        '文本内容': lists['文本内容']
    })
    if not os.path.exists('newdata.csv'):
        with open('newdata.csv') as f:
            pass
    old = pd.read_csv('newdata.csv', encoding='utf-8', engine='python')
    new = pd.concat([new, old])
    new.drop_duplicates(subset=['文本内容'], keep='first', inplace=True)
    new.to_csv('newdata.csv', index=None, encoding='utf-8')

def Transfrom(lists):
    label = []
    text = []
    for categ in lists:
        urls = lists[categ]
        for url in urls:
            temp = crawText(url)
            if temp is not None:
                label.append(categ)
                text.append(temp)
    dict = {
        '文本类别': label,
        '文本内容': text
    }
    return dict

    #  "政治": crawUrl('http://cpc.people.com.cn/')
    #    "军事": crawUrl('http://www.xinhuanet.com/milpro/'),

#   "军事": crawUrl('http://military.people.com.cn/'),
if __name__ == '__main__':
    lists = {
        '航空': crawUrl('https://news.163.com/air/'),

    }

    lists = Transfrom(lists)
    print(lists)
    save(lists)

    driver.quit()


# Freely inspired by https://github.com/tobibaum/metrabs_trt
# This script saves the BackBone from MetrABS with signature and exports the weight and bias of the heads as numpy

import tensorflow as tf
import numpy as np
import sys
import os

try:
    sys.path.append('modules/hpe/assets/metrabs/src')
    from backbones.efficientnet.effnetv2_model import *
    import backbones.efficientnet.effnetv2_utils as effnet_util
    import tfu
except ImportError as e:
    print("Clone https://github.com/isarandi/metrabs inside modules/hpe/assets first!")
    exit(-1)

if not os.path.exists('modules/hpe/modules/raws/metrabs_eff2l_y4'):
    print("Download weights from https://omnomnom.vision.rwth-aachen.de/data/metrabs/metrabs_eff2l_y4.zip")
    print("Or from model zoo https://github.com/isarandi/metrabs/blob/master/docs/MODELS.md")
    print("Extract them and put them into modules/hpe/modules/raws")
    exit(-1)

BATCH_SIZE = 5

# Input names
model_name = 'efficientnetv2-l'
model_folder = 'modules/hpe/modules/raws/metrabs_eff2l_y4'

# Output names
bbone_name = "modules/hpe/modules/signatured/bbone{}".format(BATCH_SIZE)
head_name = "modules/hpe/modules/numpy/head"

# Load model
model = tf.saved_model.load(model_folder)
mod_vars = model.crop_model.variables
name_shape = [['/'.join(v.name.split('/')[1:]), v.shape] for v in mod_vars if 'tpu' not in v.name]

####################
# EXTRACT BACKBONE #
####################
effnet_util.set_batchnorm(effnet_util.BatchNormalization)
tfu.set_data_format('NHWC')
tfu.set_dtype(tf.float32)

mod = get_model(model_name, include_top=False, pretrained=False, with_endpoints=False)
mod.set_weights(mod_vars[:-4])

@tf.function()
def my_predict(my_prediction_inputs, **kwargs):
    prediction = mod(my_prediction_inputs, training=False)
    return {"prediction": prediction}

my_signatures = my_predict.get_concrete_function(
    my_prediction_inputs=tf.TensorSpec([BATCH_SIZE, 256, 256, 3], dtype=tf.float32, name="images")
)

tf.saved_model.save(mod, bbone_name, signatures=my_signatures)

#################
# EXTRACT HEADS #
#################
np.save(head_name+'_weights.npy', model.crop_model.heatmap_heads.conv_final.variables.weights[0].numpy())
np.save(head_name+'_bias.npy', model.crop_model.heatmap_heads.conv_final.variables.weights[1].numpy())


All = int(input())

for q in range(0, All):
    string = input()
    length = len(string)

    stack=[]
    index=1
    for i in range(0, length):
        if string[i] == '(':
            stack.append(index)
            print(index,end=' ')
            index+=1

        elif string[i] == ')':
            print(stack.pop(), end=' ')
    print()


import re
from models import (
    Push,
    PushManager,
)
from util.exceptions import GatlinException
from providers.abc import Provider
from sqlalchemy.exc import IntegrityError
from config import logging

class PushRepo:

    @staticmethod
    def get(uuid):
        push = Push.query.filter_by(
            uuid=uuid
        ).one_or_none()
        if push is None:
            raise GatlinException("Push not exist", 404)
        return push

    @staticmethod
    def create(message, app_id):
        try:
            pm = PushManager.query.filter_by(
                uuid=app_id
            ).one_or_none()
            if pm is None:
                raise GatlinException("This app not exist", 404)
            push = Push(message, pm.id)
            return push.save()
        except Exception as e:
            raise GatlinException(e, 400)

    @staticmethod
    def get_message(message_id, app_id):

        try:
            push = PushManager.query.join(Push).filter(
                PushManager.uuid == app_id,
                Push.sent == False,
                Push.uuid == message_id
            ).one_or_none()
            if push is None:
                raise GatlinException("Message not exists", 404)
            if len(push.installation) == 0:
                raise GatlinException("No devices with this app", 200)
            return push.json
        except Exception as e:
            raise GatlinException(e, 400)

class PushManagerRepo:

    def __init__(self, provider):
        """
        Instantiate the provider
        """
        if isinstance(provider, Provider):
            self._provider = provider
        else:
            raise GatlinException("Invalid Provider", 400)

    @staticmethod
    def get(uuid):
        """
        Get a push manager
        """
        pmanager = PushManager.query.filter_by(
            uuid=uuid
        ).one_or_none()
        if pmanager is None:
            raise GatlinException("App not exist", 404)
        return pmanager

    @staticmethod
    def get_all():
        """
        Get all the push manager
        """
        return PushManager.query.all()

    def create(self, android_key):
        """
        Create a new push manager
        """
        try:
            sns_arn = self._provider.set_android_platform(android_key)
            push_manager = PushManager(android_key, self._provider.app_name, sns_arn)
            return push_manager.save()
        except GatlinException as exception:
            raise exception
        except IntegrityError:
            raise GatlinException("Error while saving the app", 400)

    def update(self, uuid, android_key):
        """
        Update the android key of the
        given push manager
        """
        try:
            pmanager = PushManager.query.filter_by(
                uuid=uuid
            ).one_or_none()
            if pmanager is None:
                raise GatlinException("App not exist", 404)
            self._provider.app_name = pmanager.app_name
            _ = self._provider.set_android_platform(android_key)
            pmanager.android_key = android_key
            return pmanager.save()
        except GatlinException as exception:
            raise exception

    def delete(self, uuid):
        """
        Remove a push manager
        """
        try:
            pmanager = PushManager.query.filter_by(
                uuid=uuid
            ).one_or_none()
            if pmanager is None:
                raise GatlinException("App not exist", 404)
            self._provider.delete_platform(pmanager.sns_arn)
            pmanager.delete()
        except GatlinException as exception:
            raise exception


"""
Data type conversion of different files
"""
import csv
import codecs
from itertools import islice
try:
    from openpyxl import load_workbook
except ModuleNotFoundError:
    raise ModuleNotFoundError("Please install the library. https://pypi.org/project/openpyxl/")

def csv_to_list(file=None, line=1):
    """
    Convert CSV file data to list
    :param file: Path to file
    :param line: Start line of read data
    :return:  list data

    @data(csv_to_list(/home/user/seldom/data.csv, line=1))
    def test_login(self, username, password):
        print(username)
        print(password)
    """
    if file is None:
        raise FileExistsError("Please specify the CSV file to convert.")

    table_data = []
    csv_data = csv.reader(codecs.open(file, 'r', 'utf_8_sig'))
    for line in islice(csv_data, line - 1, None):
        table_data.append(line)

    return table_data

def excel_to_list(file=None, sheet="Sheet1", line=1):
    """
    Convert CSV file data to list
    :param file: Path to file
    :param sheet: excel sheet, default name is Sheet1
    :param line: Start line of read data
    :return: list data

    @data(excel_to_list(/home/user/seldom/data.xlsx, sheet="Sheet1", line=1))
    def test_login(self, username, password):
        print(username)
        print(password)
    """
    if file is None:
        raise FileExistsError("Please specify the Excel file to convert.")

    excel_table = load_workbook(file)
    sheet = excel_table[sheet]

    table_data = []
    for line in sheet.iter_rows(line, sheet.max_row):
        line_data = []
        for field in line:
            line_data.append(field.value)
        table_data.append(line_data)

    return table_data


import context

import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
import torch.nn.functional as F

from experiments.args import *
from experiments.default import *
from experiments.data_loader import *
from experiments.construct import *
from gradeval.utils import *
from models.losses import *
from experiments.test import Test

import models

# from PIL import Image

def default_options():
    ROOT = "../"

    o = odict()
    #
    o.file = odict()
    o.file.root = ROOT
    o.file.dataset = odict()
    o.file.dataset.name = 'MNIST'
    o.file.dataset.path = ROOT + 'data/'
    o.file.dataset.class_name = MNIST_dataset
    o.file.dataset.construct_args = odict()
    #
    #
    o.file.base_dir = ROOT + 'runs/'
    o.file.cuda = True
    o.file.verbose = True
    o.file.log_dir = o.file.base_dir + 'test/'
    #
    o.create = odict()
    o.create.network = 'fc'
    o.create.n_layers = 2
    o.create.hidden_size = 100
    o.create.add_batch_norm = False

    o.methods = odict()
    o.methods.init_temp = 1.0
    o.methods.activation = 'tanh'
    #
    o.train = odict()
    o.train.method = 'standard'
    # o.train.method = 'sah'
    # o.train.method = 'score'
    # o.train.method = 'gumbel'
    o.train.epochs = 100
    o.train.batch_size = 64
    # o.train.lr = 0.03
    o.train.lr = None
    o.train.lr_estimate_epochs = 5
    # o.train.samples = 1 # depricated
    o.train.init_seed = 1
    o.train.data_seed = 1
    o.train.val_size = 0.1
    o.train.optimizer = 'sgd'
    o.train.momentum = 0.9
    o.train.Nesterov = True
    o.train.train_samples = 1
    o.train.stat_samples = 10
    o.train.stochastic = False
    #
    #
    o.test = odict()
    o.test.batch_size = 128
    o.test.samples = 1
    o.test.stat_samples = 10
    #
    o.train.lr = None
    o.train.lr_estimate_epochs = 5
    o.train.lr_estimate_trials = 10
    o.train.step_lr = 100
    #
    # #data = MNIST_dataset(o.file.dataset_path)
    # data = new_dataset(o.file.dataset)
    #
    #
    o.create.input_shape = None
    o.create.input_size = None
    o.create.n_classes = None
    #
    o.train.epoch = None
    #
    o.lock()
    return o

def save_config(o, name):
    save_object(o.file.log_dir + name + '.pkl', o)
    with open(o.file.log_dir + name + '.txt', 'w') as f:
        print(*(s + os.linesep for s in o.strings()), file=f)

def edit_on_load(o):
    if o.train.optimizer == 'Adam' and o.train.Adam is not None and o.train.Adam.amsgrad:
        o.train.optimizer = 'Amsgrad'
        # del o.train.Adam
    return o

def collect_options(root_dir, exclude={}, must_include={}):
    #
    subd = [os.path.join(root_dir, o) for o in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, o))]
    subd.sort()
    ALL = odict()
    for d, dir_name in reversed(list(enumerate(subd))):
        info_name = dir_name + '/o.pkl'
        if not os.path.exists(info_name):
            print('Skipping (not exists) {}'.format(dir_name))
            del subd[d]
            continue
        o = pickle.load(open(info_name, "rb"))
        params = ', '.join(o.strings())
        if any(word in params for word in exclude) or not all(word in params for word in must_include):
            print('Skipping (by exclude/must_include) {}'.format(dir_name))
            del subd[d]
            continue

        o = edit_on_load(o)
        ALL[dir_name + '/'] = o
    return ALL

def uncommon_important(o, common):
    uncommon = o - common
    del uncommon.file
    del uncommon.train.epochs
    del uncommon.train.epoch
    if uncommon.create:
        del uncommon.create.input_shape
        del uncommon.create.n_classes
    del uncommon.test
    if uncommon.train:
        del uncommon.train.samples
    del uncommon.code
    del uncommon.debug
    if uncommon.train:
        del uncommon.train.init
        if not uncommon.train.step_lr:
            del uncommon.train.step_lr
            del uncommon.train.lr_estimate_trials

    if uncommon.train and not uncommon.train.backtrack:
        del uncommon.train.backtrack
    return uncommon

def configure(base_dir, oo):
    force_path(base_dir)
    # collect options from existing directories
    fo = collect_options(base_dir)
    # find common
    common = odict.intersection(*oo, *fo.values())
    del common.train.method
    # update existing items
    for [dir, o] in fo.items():
        # find uncommon
        uncommon = uncommon_important(o, common)
        # update dir name, if nothing is running...
        new_dir = os.path.join(base_dir, str(uncommon)) + '/'
        # rename
        c = True
        if False:
            if dir != new_dir:
                c = query_yes_no(f'Rename:? \n    {dir}\n to {new_dir}\n', default="yes")
            if c:
                os.rename(dir, new_dir)
                o.file.log_dir = new_dir
                save_config(o, 'o')

    # add new items
    for o in oo:
        # find uncommon
        uncommon = uncommon_important(o, common)
        new_dir = os.path.join(base_dir, str(uncommon)) + '/'
        c = True
        # if os.path.exists(new_dir):
        #     c = query_yes_no(f'Path {dir} exists, overwrite config?'.format(), default="no")
        if c:
            force_path(new_dir)
            o.file.log_dir = new_dir
            save_config(o, 'o')
    # return full list of configs

    fo = collect_options(base_dir)
    return [*fo.values()]


#coding:utf-8

# Create your models here.

from django.db import models

# Create your models here.

class CaptchaCode(models.Model):

    code = models.CharField(verbose_name=u'验证码', max_length=100, default="")
    key = models.CharField(verbose_name=u'校验码', max_length=200, default="")
    create_time = models.DateTimeField(verbose_name=u'生成时间', auto_now_add=True)
    def __str__(self):
        return self.code

    class Meta:
        verbose_name = u'仓库管理'
        verbose_name_plural = verbose_name


# Surgeo accuracy analysis using collected demographic data
import numpy as np
import pandas as pd
import surgeo

# Tree plenish event demographic responses... pre-downloaded
df = pd.read_csv("/home/justinmiller/Documents/Data/tpEventDemographic.csv")

names = df[df.columns[2]].values
last_names = [name.split(" ")[-1] if name.split(" ")[-1] else name.split(" ")[-2] for name in names]

fsg = surgeo.SurnameModel()

fsg_results = fsg.get_probabilities(pd.Series(last_names))
print(str(len(fsg_results)) + " Total Entries")

df = pd.concat([df, fsg_results], axis = 1)

df = df.dropna(subset = ['white'])
print(str(len(df)) + " Usable Surnames")

pd.set_option('display.max_columns', None)
print(df)

# Mapping keys for comparison row by row
r = 5 # Column with race question
keys = np.unique(df[df.columns[r]]) # Race row
keyMap = {}
keyMap[keys[0]] = "api"
keyMap[keys[1]] = "black"
keyMap[keys[2]] = "hispanic"
keyMap[keys[3]] = "multiple"
keyMap[keys[6]] = "white"

# Looping through to find percent estimate of actual race
probList = np.array([])

for i in df.index:

    race = df[df.columns[r]][i]
    try:
        probability = df[keyMap[race]][i]
        probList = np.append(probList, probability)
    except:
        probList = np.append(probList, np.nan)
        print("The user answered: " + race)

# Adding problist back onto df
df = pd.concat([df, pd.DataFrame(probList, index = df.index)], axis = 1)
df.columns[-1] = "probability"


import pygame
from Properties.HIT_BOX import *
from Levels import CorentLevel

class MovableHitBox(HitBox):
    def __init__(self, data=None):
        # copy constractor ( type(data) == tpe(class) )
        if isinstance(data, MovableHitBox):
            # [win, x=0, y=0, width=1, height=1, color=(255, 0, 0)]
            HitBox.__init__(self, data)
            self.gravity = data.gravity
            self.moveSpeed = data.moveSpeed
            self.jumpSpeed = data.jumpSpeed
        # normal constractor, data will need to be in the shape of [hit_box, move_speed=0, jump_speed=0, gravity=0.1]
        else:
            HitBox.__init__(self, data[0])
            self.moveSpeed = data[1]
            self.jumpSpeed = data[2]
            self.gravity = data[3]

        # save object speed
        self.x_speed = 0
        self.y_speed = 0

        # hiting floors
        self.onObject = None
        self._t_fall = 0
        self._move = 0  # -1 Left, 1 Right, 0 noMove
        self._v0 = 0

        # vertical knock off
        self._isKnockOff = False
        self.deceleration_knockOff = 0
        self.v0_knockOff = 0
        self._t_knockOff = 0

    def update(self):
        self.x_speed = self._initiateMove() + self._initiateKnockOff()
        self.y_speed = self._initiateFalling()
        self.update_speed(self.x_speed, self.y_speed)

        # chack if object still stand on floor
        if self.onObject is not None:  # if object on floor
            self.y += 1
            if where_collide(self, self.onObject) != "down":
                self.onObject = None
                self._v0 = 0  # cliff falling speed
            self.y -= 1

        # hit a floor
        for floor in CorentLevel.corentFloors:
            if (where_collide(self, floor) == "down") and self.y_speed > 0:
                self.y = floor.y - self.height - 1
                self.onObject = floor
                self._v0 = 0
                self._t_fall = 0
                break

        # hit wall
        for wall in CorentLevel.corentWalls:
            colide = where_collide(self, wall)
            if colide == "right": # object move right, can only hit wall from the left
                self.x = wall.x - self.width - 1
            elif colide == "left": # object move left
                self.x = wall.x + wall.width + 1

        # hit solide object
        for solide in CorentLevel.corentSpecial:
            colide = where_collide(self, solide)
            if colide == "right": # object move right, can only hit wall from the left
                self.x = solide.x - self.width - 1
            elif colide == "left": # object move left
                self.x = solide.x + solide.width + 1
            elif colide == "down":
                self.y = solide.y - self.height -1
                self.onObject = solide
                self._v0 = 0
                self._t_fall = 0
            elif colide == "up":
                self.y = solide.y + solide.height + 1
                self._v0 = 0
                self._t_fall = 0

        # reset tageling
        self._move = 0

    def reset(self, x, y):
        HitBox.reset(self, x, y)
        # reset  speed
        self.x_speed = 0
        self.y_speed = 0
        # reset floor floors
        self.onObject = None
        self._t_fall = 0
        self._move = 0  # -1 Left, 1 Right, 0 noMove
        self._v0 = 0
        # reset knock off
        self._isKnockOff = False
        self.deceleration_knockOff = 0
        self.v0_knockOff = 0
        self._t_knockOff = 0

    def moveRight(self):
        self._move += 1

    def moveLeft(self):
        self._move += -1

    def idle(self):
        self._move += 0

    def _initiateMove(self):
        if self._move > 0:
            return self.moveSpeed
        elif self._move < 0:
            return -self.moveSpeed
        else:
            return 0

    def jump(self):
        if self.onObject is not None:
            self.onObject = None
            self._t_fall = 0
            self._v0 = -self.jumpSpeed

    def _initiateFalling(self):
        if self.onObject is not None:  # if on floor
            return 0
        else:  # if not, then fall
            self._t_fall += 1
            return self._v0 + self.gravity * (self._t_fall - 1)

    # data must be in diffrent Direction
    def knockOff(self, v0, deceleration):
        if (v0 * deceleration <= 0):
            # up date
            self.v0_knockOff = v0
            self._t_knockOff = 0
            self.deceleration_knockOff = deceleration
            self._isKnockOff = True
        else:
            print("knockoff effect got values that could broke the game")

    def _initiateKnockOff(self):
        if not self._isKnockOff:
            return 0
        # if the next step will change the direction of the movement
        elif ((self.v0_knockOff + self.deceleration_knockOff * (self._t_knockOff)) *
              (self.v0_knockOff + self.deceleration_knockOff * (self._t_knockOff + 1)) <= 0):
            self._isKnockOff = False
            self.v0_knockOff = 0
            self._t_knockOff = 0
            self.deceleration_knockOff = 0
            return 0
        # else, continue to deceleration
        else:
            self._t_knockOff += 1
            return self.v0_knockOff + self.deceleration_knockOff * (self._t_knockOff - 1)


from numpy import random, array, exp, dot, ndarray
import pickle

def sigmoid(x):
    # applying the sigmoid function
    return 1 / (1 + exp(-x))

def sigmoid_derivative(x):
    # computing derivative to the Sigmoid function
    return x * (1 - x)

def fill(l, length, null=0, reverse=False):
    if len(l) > length:
        if reverse:
            return l[len(l) - length :]
        else:
            return l[:length]
    else:
        for x in range(length - len(l)):
            if reverse:
                l = [null] + l
            else:
                if isinstance(l, str):
                    l += str(null)
                else:
                    l.append(null)
    return l

def process_value(x, bits_per_character=8):
    if type(x) == str:
        return [
            int(i)
            for i in "".join([format(ord(i), f"0{bits_per_character}b") for i in x])
        ]
    elif type(x) == int:
        return [int(i) for i in format(x, "b")]
    elif type(x) == list:
        return x
    elif type(x) == array:
        return x
    elif type(x) == ndarray:
        return x

def decode(data, bits_per_character=8):
    confidence = 0
    for i in data:
        if i < 0.5:
            confidence += 1 - i
        else:
            confidence += i
    confidence /= len(data)
    out = [round(x) for x in data]
    bytes = [
        out[x : x + bits_per_character] for x in range(0, len(out), bits_per_character)
    ]
    strbytes = ["".join([str(i) for i in x]) for x in bytes]
    chrs = [int(x, 2) for x in strbytes]
    string = ""
    for x in chrs:
        if x == 0:
            string += ""
        try:
            string += chr(x)
        except:
            string += ""
    return string, confidence

class NeuralNetwork:
    def __init__(
        self,
        input_length=4,
        output_length=1,
        bits_per_character=8,
        layers = 1,
        synaptic_weights=None,
        save_funct=None
    ):
        self.layers = layers
        self.input_length = input_length
        self.output_length = output_length
        self.bits_per_character = bits_per_character
        self.save_funct = save_funct
        if synaptic_weights == None:
            # seeding for random number generation
            random.seed(1)

            # converting weights to a 3 by 1 matrix with values from -1 to 1 and mean of 0
            self.synaptic_weights = [2 * random.random((input_length, output_length)) - 1] * layers
        else:
            self.synaptic_weights = array(synaptic_weights)
    def __del__(self):
        if self.save_funct:
            self.save_funct()
    def adjust(self, training_inputs, training_outputs):
        # siphon the training data via  the neuron
        output = self.think(training_inputs)

        # computing error rate for back-propagation
        error = training_outputs - output

        # performing weight adjustments
        for i in range(len(self.synaptic_weights)):
            x = output
            for _ in range(len(self.synaptic_weights) - i):
                x = sigmoid_derivative(output)
            adjustments = dot(training_inputs.T, error * x)

            self.synaptic_weights[i] += adjustments
        return output

    def train(self, training_inputs, training_outputs, training_iterations):
        training_inputs = array(
            [
                fill(process_value(inp, self.bits_per_character), self.input_length)
                for inp in training_inputs
            ]
        )
        training_outputs = array(
            [
                fill(process_value(out, self.bits_per_character), self.output_length)
                for out in training_outputs
            ]
        )
        # training the model to make accurate predictions while adjusting weights continually
        for iteration in range(training_iterations):
            # siphon the training data via  the neuron
            output = self.think(training_inputs)

            # computing error rate for back-propagation
            error = training_outputs - output

            # performing weight adjustments
            for i in range(len(self.synaptic_weights)):
                x = output
                for _ in range(len(self.synaptic_weights) - i):
                    x = sigmoid_derivative(output)
                adjustments = dot(training_inputs.T, error * x)

                self.synaptic_weights[i] += adjustments

    def think(self, inputs):
        # passing the inputs via the neuron to get output
        if type(inputs) != ndarray:
            inputs = fill(
                process_value(inputs, self.bits_per_character), self.input_length
            )
        inputs = array(inputs)
        x = inputs
        for i in range(len(self.synaptic_weights)):
            x = sigmoid(dot(inputs, self.synaptic_weights[i]))
        output = x
        return output

    def addInput(self, start=0):
        if start == None:
            start = sum([sum(x) for x in self.synaptic_weights.tolist()]) / len(
                self.synaptic_weights
            )
        for l in range(len(self.synaptic_weights)):
            self.synaptic_weights[l] = array(
                [[start] * self.output_length] + self.synaptic_weights[l].tolist()
            )
        self.input_length += 1

    def addOutput(self, start=0):
        if start == None:
            start = sum([sum(x) for x in self.synaptic_weights.tolist()]) / len(
                self.synaptic_weights
            )
        for l in range(len(self.synaptic_weights)):
            for i in range(len(self.synaptic_weights)):
                self.synaptic_weights[l][i] = array(self.synaptic_weights[l].tolist() + [start])
        self.output_length += 1

    def setInOut(self, inputs, outputs):
        if inputs > self.input_length:
            for i in range(inputs - self.input_length):
                self.addInput()
        elif inputs < self.input_length:
            for l in range(len(self.synaptic_weights)):
                self.synaptic_weights[l] = self.synaptic_weights[l][1:]
        if outputs > self.max_output_length:
            for i in range(inputs - self.max_output_length):
                self.addOutput()
        elif outputs < self.max_output_length:
            for l in range(len(self.synaptic_weights)):
                for i in range(len(self.synaptic_weights[l])):
                    self.synaptic_weights[l][i] = array(self.synaptic_weights[l].tolist()[:-1])
        self.input_length = inputs
        self.output_length = outputs

if __name__ == "__main__":
    x = NeuralNetwork(32, 32, 8, 2)
    x.train(
        [process_value("hi"), process_value("hey")],
        [process_value("hey"), process_value("hi")],
        20,
    )
    print(decode(x.think(process_value("hi"))))


# from lilab.multiview_scripts_dev.comm_functions import (
#       box2cs, get_max_preds, get_max_preds_gpu, transform_preds)
import numpy as np
import torch

def box2cs(box, image_size, keep_ratio=True):
    """Encode bbox(x,y,w,h) into (center, scale) without padding.

    Returns:
        tuple: A tuple containing center and scale.
    """
    x, y, w, h = box[:4]
    aspect_ratio = 1. * image_size[0] / image_size[1]
    center = np.zeros((2), dtype=np.float32)
    center[0] = x + w * 0.5
    center[1] = y + h * 0.5

    if keep_ratio:
        if w > aspect_ratio * h:
            h = w * 1.0 / aspect_ratio
        elif w < aspect_ratio * h:
            w = h * aspect_ratio
    scale = np.array([w * 1.0 / 200.0, h * 1.0 / 200.0], dtype=np.float32)
    return center, scale

def get_max_preds(heatmaps:np.ndarray):
    assert isinstance(heatmaps,
                      np.ndarray), ('heatmaps should be numpy.ndarray')
    assert heatmaps.ndim == 4, 'batch_images should be 4-ndim'

    N, K, _, W = heatmaps.shape
    heatmaps_reshaped = heatmaps.reshape((N, K, -1))
    idx = np.argmax(heatmaps_reshaped, 2).reshape((N, K, 1))
    maxvals = np.amax(heatmaps_reshaped, 2).reshape((N, K, 1))

    preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
    preds[:, :, 0] = preds[:, :, 0] % W
    preds[:, :, 1] = preds[:, :, 1] // W

    preds = np.where(np.tile(maxvals, (1, 1, 2)) > 0.0, preds, -1)
    return preds, maxvals

def get_max_preds_gpu(heatmaps:torch.Tensor):
    N, K, _, W = heatmaps.shape
    heatmaps_reshaped = heatmaps.reshape((N, K, -1))
    idx = torch.argmax(heatmaps_reshaped, 2).reshape((N, K, 1))
    maxvals = torch.amax(heatmaps_reshaped, 2).reshape((N, K, 1))
    idx = idx.cpu().numpy()
    maxvals = maxvals.cpu().numpy()

    preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
    preds[:, :, 0] = preds[:, :, 0] % W
    preds[:, :, 1] = preds[:, :, 1] // W

    return preds, maxvals

def non_max_suppression(heatmap:np.ndarray, num_peaks, w=5) -> np.ndarray:
    peaks = np.zeros((num_peaks, 3), dtype=np.float32)
    for i in range(num_peaks):
        max_index = np.argmax(heatmap)
        peak = np.unravel_index(max_index, heatmap.shape)
        peak_y, peak_x = peak
        peak_v = heatmap[peak_y, peak_x]
        peaks[i] = peak_x, peak_y, peak_v

        y_min = max(0, peak_y - w // 2)
        y_max = min(heatmap.shape[0], peak_y + w // 2 + 1)
        x_min = max(0, peak_x - w // 2)
        x_max = min(heatmap.shape[1], peak_x + w // 2 + 1)
        heatmap[y_min:y_max, x_min:x_max] = 0

    return peaks

def transform_preds(coords, center, scale, output_size, use_udp=False):
    assert coords.shape[-1] == 2
    assert len(center) == 2
    assert len(scale) == 2
    assert len(output_size) == 2
    scale = scale * 200.0
    output_size = np.array(output_size)
    if use_udp:
        preds = scale / (output_size - 1.0)
    else:
        scale_step = scale / output_size
    preds = coords * scale_step + center - scale * 0.5
    return preds


import sys
file = open(sys.argv[1],"r")
data = file.readlines()
banks = [int(i) for i in data[0].split()]
amountOfBanks = len(banks)

visited = dict()
steps = 0
visited[str(banks)] = steps

while (True):
    topValue = max(banks)
    maxIndex = banks.index(topValue)
    banks[maxIndex] = 0

    for i in xrange(0,topValue):
        banks[(maxIndex + 1 + i) % amountOfBanks] += 1

    steps += 1
    if( str(banks) in visited):
        break
    else:
        visited[str(banks)] = steps

print("total steps",steps)
print("cycle",steps - visited[str(banks)])


import json
from Parametres import labels_list, butlabels_list, mainmenu_list, file_name
from Interface import gen_Frames, MainMenu
from Functions import *
from MenuFunctions import *

# Создание главного окна
root = Tk()
root.title("Task-manager")
root.resizable(False, False)
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
w = w//2
h = h//2
w = w - 330
h = h - 290
root.geometry('660x580+{}+{}'.format(w, h))
# Добавление виджетов
frame1 = gen_Frames([labels_list[0]] + butlabels_list[0:4], root)
frame2 = gen_Frames([labels_list[1]] + butlabels_list[4:8], root)
frame1.configurate((lambda: adding(root, frame1), lambda: deleting(frame1), lambda: ending(frame1, frame2),
                    lambda: informate(root, frame1)))
frame2.configurate((lambda: returning(frame2, frame1), lambda: deleting(frame2), lambda: changing(root, frame2),
                    lambda: informate(root, frame2)))
menu = MainMenu(root, mainmenu_list,
                (lambda: export_results(frame2), lambda: categs(root, frame1, frame2),
                 lambda: clear_all(frame1.box_frame, frame2.box_frame)))
# Восстановление предыдущей сессии
file = open(file_name, "r", encoding='utf-8')
database = json.load(file)
file.close()
restore(database, frame1.box_frame, frame2.box_frame)
root.mainloop()
# Запись состояния сессиии
file = open(file_name, "w")
transformed_categs = {}
for categ in categories.keys():
    transformed_categs[categ] = list(map(lambda x: x.to_str(), categories[categ]))
database = {"unfinished": list(map(lambda x: x.to_str(), frame1.box_frame.box_data)),
            "finished": list(map(lambda x: x.to_str(), frame2.box_frame.box_data)),
            "categories": transformed_categs}
json.dump(database, file)
file.close()


# Create your views here.
from django.utils.translation import ugettext as _
from django.template import loader, RequestContext
from django.http import HttpResponse, Http404
from django.core.urlresolvers import reverse
from products.models import *
from django.shortcuts import render_to_response, redirect
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from products.models.device import Device
from django.template.defaultfilters import slugify
from django.conf.locale import tr

def index(request):
    request.breadcrumbs(_("Products"), reverse(index))

    product_list = Product.objects.filter(visible=True).order_by('-created')
    paginator = Paginator(product_list, 6) # Show 25 contacts per page

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        products = paginator.page(page)
    except (EmptyPage, InvalidPage):
        products = paginator.page(paginator.num_pages)

    t = loader.get_template('products/list.html')
    c = RequestContext(request, {
                                 "products":products,
                                 })
    return HttpResponse(t.render(c))

def details(request, product_id, slug):
    request.breadcrumbs(_("Products"), reverse(index))
    try:
        product = Product.objects.get(id=product_id, visible=True)
    except Product.DoesNotExist:
        raise Http404

    if slug != slugify(product.name):
        return redirect('products.views.details', permanent=False, product_id=product_id, slug=slugify(product.name))

    productImages = product.productimage_set.all().order_by('-default')
    relatedProducts = product.related.all()
    productSizes = product.productsize_set.all()
    relatedDevices = product.devices.all()

    request.breadcrumbs(product,reverse(details, args=[product_id, slug]))
    t = loader.get_template('products/details.html')
    c = RequestContext(request, {
                                 "product": product,
                                 "productImages":productImages,
                                 "relatedProducts":relatedProducts,
                                 "productSizes":productSizes,
                                 "relatedDevices":relatedDevices
                                 });
    return HttpResponse(t.render(c))

def tags(request, device_id, slug=None):
    request.breadcrumbs(_("Tags"),"#")

    product_list = Product.objects.filter( devices__pk=device_id, visible=True)
    paginator = Paginator(product_list, 6) # Show 25 contacts per page

    try:
        tag = Device.objects.get(pk=device_id);
    except Device.DoesNotExist:
        raise Http404

    if slug != slugify(tag.name):
        return redirect('products.views.tags', permanent=False, device_id=device_id, slug=slugify(tag.name))

    request.breadcrumbs(tag, reverse(tags, args=[device_id,slug]))

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        products = paginator.page(page)
    except (EmptyPage, InvalidPage):
        products = paginator.page(paginator.num_pages)

    t = loader.get_template('products/tag_list.html')
    c = RequestContext(request, {
                                 "products":products,
                                 "tag":tag
                                 })
    return HttpResponse(t.render(c))


import os
import time
import copy
import math

def solve_1(input):
    facing = 90
    x = 0
    y = 0

    for instruction in input:
        action = instruction[0]
        value = int(instruction[1:])
        if action == "N":
            y += value
        elif action == "S":
            y -= value
        elif action == "E":
            x += value
        elif action == "W":
            x -= value
        elif action == "R":
            facing = (facing + value)%360
        elif action == "L":
            facing = (facing - value)%360
        elif action == "F":
            if facing == 0:
                y += value
            elif facing == 90:
                x += value
            elif facing == 180:
                y -= value
            elif facing == 270:
                x -= value
    print(abs(x) + abs(y))

def solve_2(input):
    x_s = 0
    y_s = 0
    x_w = 10
    y_w = 1

    for instruction in input:
        action = instruction[0]
        value = int(instruction[1:])
        if action == "N":
            y_w += value
        elif action == "S":
            y_w -= value
        elif action == "E":
            x_w += value
        elif action == "W":
            x_w -= value
        elif action == "R":
            x_w, y_w = rotate((x_s, y_s), (x_w, y_w), 360-value)
        elif action == "L":
            x_w, y_w = rotate((x_s, y_s), (x_w, y_w), value)
        elif action == "F":
            delta_x = x_w - x_s
            delta_y = y_w - y_s
            x_s += value*delta_x
            y_s += value*delta_y
            x_w += value*delta_x
            y_w += value*delta_y
    print(abs(x_s) + abs(y_s))

# rotates counterclockwise
def rotate(ship, waypoint, degrees):
    ox, oy = ship
    px, py = waypoint
    angle = math.radians(degrees)

    qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
    qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
    return qx, qy

script_dir = os.path.dirname(__file__)
with open(script_dir + "/input", "r") as myInput:
    start_time = time.time()
    input = [line.strip() for line in myInput]
    solve_1(input)
    solve_2(input)
    print("--- Execution time %s s ---" % (time.time() - start_time))


import argparse
import time
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from model import CNN
from loss import Energy_Loss
from torch.utils.data import DataLoader
from utils import *

def train(args, model, optimizer, criterion, train_loader, epoch):
    model.train()
    for batch_idx, (input, target) in enumerate(train_loader):
        if args.use_cuda:
            input, target = input.cuda(args.device, non_blocking=True), target.cuda(
                args.device, non_blocking=True)
        optimizer.zero_grad()
        output, _ = model(input)
        loss = criterion(output, target)
        loss.backward()
        optimizer.step()
        if (batch_idx) * train_loader.batch_size % args.log_rate == 0:
            print('\rTrain Epoch: {} [{}/{} ({:.0f}%)] Loss: {:.6f}'.format(
                epoch, (batch_idx) *
                (train_loader.batch_size), len(train_loader.dataset),
                100. * (batch_idx) / len(train_loader), loss.item()/train_loader.batch_size), end='')
    print()

# tests model to make sure the correct word is the lowest energy

def test1(args, model, criterion, test_loader):
    model.eval()
    correct = 0
    total = 0
    test_loss = 0.0
    with torch.no_grad():
        for i, (input, target) in enumerate(test_loader):
            if args.use_cuda:
                input, target = input.cuda(args.device, non_blocking=True), target.cuda(
                    args.device, non_blocking=True)
            outputs, _ = model(input)
            test_loss += criterion(outputs, target)
            v, j = outputs.min(1)
            # correct ones are 0.
            correct += test_loader.batch_size - torch.nonzero(j).size()[0]
            total += test_loader.batch_size
    print("Test 1: Avg Loss: {:.3f}, Accuracy: {:.3f}".format(
        test_loss/total, correct/total))

# test model to compare 5 correct and 5 incorrect words for energy level.

def test2(args, model, criterion, test_loader):
    model.eval()
    correct = 0
    avg_top5 = 0
    total = 0
    with torch.no_grad():
        for i, (input, target) in enumerate(test_loader):
            if args.use_cuda:
                input, target = input.cuda(args.device, non_blocking=True), target.cuda(
                    args.device, non_blocking=True)
            outputs, _ = model(input)
            # ravel index into 1d
            outputs = outputs.view(-1)
            # get the top half.
            v, i = torch.topk(outputs, test_loader.batch_size, largest=False)
            # unravel index and then see if 2nd index set is all 0s
            # meaning smallest energy levels in the first  column.
            i1d = np.unravel_index(i, (test_loader.batch_size, 2))
            if not np.any(i1d[1]):
                correct += 1
            avg_top5 += test_loader.batch_size - np.sum(i1d[1])
            total += 1
    print("Test 2: Accuracy: {:.3f}, Avg # correct in top5: {:.3f}".format(
        correct/total, avg_top5/total))

def main():
    parser = argparse.ArgumentParser(
        description='Training Energy NN for Spell Correction')
    parser.add_argument('--vocab_file', type=str, default="data/wikipedia.vocab.txt",
                        help='vocabulary file path')
    parser.add_argument('--model_save_file', type=str, default='models/energy_cnn',
                        help='model save path')
    parser.add_argument('--ttsplit', action='store_true', default=False,
                        help='enables train/test splitting (80-20)')
    parser.add_argument('--topk', type=int, default=100000,
                        help="train on top k most common words in vocabulary (default: 100000)")
    parser.add_argument('--epochs', type=int, default=25, metavar='N',
                        help='number of epochs to train (default: 25)')
    parser.add_argument('--lr', type=float, default=0.001, metavar='LR',
                        help='learning rate (default: 0.001)')
    parser.add_argument('--train_num_neg', type=int, default=31,
                        help='number of negative examples in each training batch (default: 31)')
    parser.add_argument('--batch_size', type=int, default=25,
                        help='number of examples in each batch (default: 25)')
    parser.add_argument('--test_num_neg', type=int, default=9,
                        help='number of negative examples in each test (default: 9)')
    parser.add_argument('--beta', type=float, default=1, metavar='B',
                        help='Inverse Temperature value for Energy function (default: 1)')
    parser.add_argument('--log_rate', type=float, default=1000,
                        help='number of samples per log (default: 1000)')
    parser.add_argument('--num_workers', type=int, default=1,
                        help='number of dataloader workers (default: 1)')
    parser.add_argument('--no-cuda', action='store_true', default=False,
                        help='disables CUDA training')
    # some settings for training on specific edits.
    parser.add_argument('--edit', type=int, default=0,
                        help='choose a specific edit. 0:all, 1:swap, 2:add/del, 3:replace (default: 0)')
    args = parser.parse_args()
    args.use_cuda = not args.no_cuda and torch.cuda.is_available()
    args.device = torch.device("cuda" if args.use_cuda else "cpu")
    kwargs = {'num_workers': args.num_workers,
              'pin_memory': True} if args.use_cuda else {}
    print("Using Device: {} with {} workers".format(
        args.device, args.num_workers))

    # instantiate CNN, loss, and optimizer.
    print("Initializing Model...")
    model = CNN(n_chars, 10, 1, 256, [1, 2, 3, 4, 5, 6, 7, 8], 0.25, 100, 1).to(
        device=args.device)
    print("Initializing Energy Loss with beta = {}".format(args.beta))
    criterion = Energy_Loss(beta=args.beta)
    print("Initializing Adam optimizer with lr = {}".format(args.lr))
    optimizer = optim.Adam(model.parameters(), lr=args.lr)
    vocab, freq_dict = read_vocab(args.vocab_file, topk=args.topk)
    print("Using wikipedia vocab of size = {}".format(len(vocab)))

    if args.ttsplit:
        print("Train/Test Splitting - Enabled")
        # default use 0.8 train-test split...
        trainset, testset = traintest_split(vocab, p=0.8)
    else:
        print("Train/Test Splitting - Disabled")
        trainset, testset = vocab, vocab

    print("Edit Parameter: {}".format(args.edit))

    # save dataset in the original GloVe format: word freq\n
    write_vocab_to_file(trainset, freq_dict, 'data/train.txt')
    write_vocab_to_file(testset, freq_dict, 'data/test.txt')

    train_dset = Dataset(trainset, num_neg=args.train_num_neg, edit=args.edit)
    train_loader = DataLoader(train_dset, batch_size=args.batch_size,
                              shuffle=True, collate_fn=collate_fn, **kwargs)

    test1_dset = Dataset(testset, num_neg=args.test_num_neg, edit=args.edit)
    test1_loader = DataLoader(test1_dset, batch_size=args.batch_size,
                              shuffle=True, collate_fn=collate_fn, **kwargs)

    test2_dset = Dataset(testset, num_neg=1, edit=args.edit)
    test2_loader = DataLoader(test2_dset, batch_size=5,
                              shuffle=True, collate_fn=collate_fn, **kwargs)

    start = time.time()
    for epoch in range(1, args.epochs + 1):
        train(args, model, optimizer, criterion, train_loader, epoch)
        test1(args, model, criterion, test1_loader)
        test2(args, model, criterion, test2_loader)
        print("Time Elapsed: {} sec".format(time.time()-start))
    print("Saving model to {}".format(args.model_save_file))
    torch.save(model.state_dict(), args.model_save_file)

if __name__ == '__main__':
    main()


import collections

from speleobox.learning.search import (
    weighted_random,
)

def test_weighted_random():
    weights = {'a': 1, 'b': 9}
    counter = collections.Counter()

    for i in range(10000):
        counter[weighted_random(weights)] += 1

    a_counts = counter['a']
    b_counts = counter['b']

    assert abs(a_counts - 1000) < 200
    assert abs(b_counts - 9000) < 800


import torch
import pytest
from asteroid_filterbanks import make_enc_dec, transforms as tr

from asteroid.dsp.beamforming import (
    Beamformer,
    SCM,
    RTFMVDRBeamformer,
    SoudenMVDRBeamformer,
    SDWMWFBeamformer,
    GEVBeamformer,
    GEVDBeamformer,
    stable_cholesky,
)

torch_has_complex_support = tuple(map(int, torch.__version__.split(".")[:2])) >= (1, 8)

_stft, _istft = make_enc_dec("stft", kernel_size=512, n_filters=512, stride=128)
stft = lambda x: tr.to_torch_complex(_stft(x))
istft = lambda x: _istft(tr.from_torch_complex(x))

@pytest.mark.skipif(not torch_has_complex_support, "No complex support ")
def _default_beamformer_test(beamformer: Beamformer, batch_size=2, n_mics=4, **forward_kwargs):
    scm = SCM()

    speech = torch.randn(batch_size, n_mics, 16000 * 6)
    noise = torch.randn(batch_size, n_mics, 16000 * 6)
    mix = speech + noise
    # GeV Beamforming
    mix_stft = stft(mix)
    speech_stft = stft(speech)
    noise_stft = stft(noise)
    sigma_ss = scm(speech_stft)
    sigma_nn = scm(noise_stft)

    Ys_gev = beamformer.forward(
        mix=mix_stft, target_scm=sigma_ss, noise_scm=sigma_nn, **forward_kwargs
    )
    ys_gev = istft(Ys_gev)

@pytest.mark.skipif(not torch_has_complex_support, reason="No complex support ")
@pytest.mark.parametrize("n_mics", [2, 3, 4])
@pytest.mark.parametrize("batch_size", [1, 2])
def test_gev(n_mics, batch_size):
    _default_beamformer_test(GEVBeamformer(), n_mics=n_mics, batch_size=batch_size)

@pytest.mark.skipif(not torch_has_complex_support, reason="No complex support ")
@pytest.mark.parametrize("n_mics", [2, 3, 4])
@pytest.mark.parametrize("batch_size", [1, 2])
def test_mvdr(n_mics, batch_size):
    _default_beamformer_test(RTFMVDRBeamformer(), n_mics=n_mics, batch_size=batch_size)
    _default_beamformer_test(SoudenMVDRBeamformer(), n_mics=n_mics, batch_size=batch_size)

@pytest.mark.skipif(not torch_has_complex_support, reason="No complex support ")
@pytest.mark.parametrize("n_mics", [2, 3, 4])
@pytest.mark.parametrize("mu", [1.0, 2.0, 0])
@pytest.mark.parametrize("batch_size", [1, 2])
def test_mwf(n_mics, mu, batch_size):
    _default_beamformer_test(SDWMWFBeamformer(mu=mu), n_mics=n_mics, batch_size=batch_size)

@pytest.mark.skipif(not torch_has_complex_support, reason="No complex support ")
@pytest.mark.parametrize("n_mics", [2, 3, 4])
@pytest.mark.parametrize("batch_size", [1, 2])
def test_mwf_indices(n_mics, batch_size):
    _default_beamformer_test(SDWMWFBeamformer(), n_mics=n_mics, batch_size=batch_size, ref_mic=0)
    _default_beamformer_test(SDWMWFBeamformer(), n_mics=n_mics, batch_size=batch_size, ref_mic=None)
    _default_beamformer_test(
        SDWMWFBeamformer(),
        n_mics=n_mics,
        batch_size=batch_size,
        ref_mic=torch.randint(0, n_mics, size=(batch_size,)),
    )
    _default_beamformer_test(
        SDWMWFBeamformer(),
        n_mics=n_mics,
        batch_size=batch_size,
        ref_mic=torch.randn(batch_size, 1, n_mics, 1, dtype=torch.complex64),
    )

@pytest.mark.skipif(not torch_has_complex_support, reason="No complex support ")
@pytest.mark.parametrize("n_mics", [2, 3, 4])
@pytest.mark.parametrize("mu", [2.0, 1.0, 0.5])
@pytest.mark.parametrize("rank", [1, 2, None])
@pytest.mark.parametrize("batch_size", [1, 2])
def test_gevd(n_mics, mu, rank, batch_size):
    _default_beamformer_test(GEVDBeamformer(mu=mu, rank=rank), n_mics=n_mics, batch_size=batch_size)

def test_stable_cholesky():
    a = torch.randn(3, 3)
    a = torch.mm(a, a.t())  # make symmetric positive-definite
    stable_cholesky(a)


#!/usr/bin/python2
# -*- coding:utf-8 -*-
"""
Verify.py: Created by YangFan on 17-6-22
Companion: verify_configs.json
* Verify cosine similarity with two given facial images
* Python API embedding to Java through JPY
"""

import sys, os
# os.environ["GLOG_minloglevel"] = "4"
os.environ["GLOG_minloglevel"] = "2"
sys.path.insert(0, '/usr/local/jpy')
import caffe    # extract feature
import mtcnn    # detect facial points
import jpy, jpyutil # java python bridge
import json         # configs loader
import numpy as np  # image container
import skimage.io   # image reader
from skimage import transform as tf # align: affine transform
from numpy import linalg as la  # linear transformation
from sklearn.externals import joblib   # load pca model

jpyutil.init_jvm(jvm_maxmem='256M')
FloatArray = jpy.get_type('[F')

"""
Details of MTcnn from c++ explosion
python module: mtcnn
 + set_device(int)  # set gpu id used for detection
 * MTcnn(str)       # handle face detection with given model_dir
   * factor      float  read write 0.709
   * minSize     int    read write 40
   * threshold   list   read write [0.5, 0.6, 0.6]
   + detect(np)  list   detected face information
"""

"""
Wrapper for instantiation of FACE in Java
"""
def FACE(config_path, mtcnn_id, center_id):
    return Face(config_path, mtcnn_id, center_id)

class Face:
    """
    Face API : Python Object to be Embedded in Java
        * mtcnn       brief handle mtcnn face detection
        * center      handle center feature similarity
        + verify      compute similarity of two given images
        + detect      detect face information
        + extract     extract face features in given image
    """

    def __init__(self, config_path, mtcnn_id, center_id):
        with open(config_path) as f:
            configs = json.load(f)

        ## init mtcnn
        mtcnn.set_device(mtcnn_id)
        self.mtcnn = mtcnn.MTcnn(str(configs['mtcnn']['model_dir']))
        self.mtcnn.factor = configs['mtcnn']['factor']
        self.mtcnn.minSize = configs['mtcnn']['minSize']
        self.mtcnn.threshold = configs['mtcnn']['threshold']

        ## init center
        self.center = Center(configs['center'], center_id)

    def _listToNp(self, image, height, width):
        """
        Convert byte list to numpy OpenCV like: BGR uint8
        """
        image = np.array(image).reshape(height, width, 3).astype(np.uint8)  # OpenCV like
        return image

    def _detect(self, image):
        """
        Detect face informations of given numpy OpenCV like: BGR uint8
        """
        raw_infos = self.mtcnn.detect(image)
        num = len(raw_infos) / 18

        infos = []
        for i in xrange(num):
            infos.append({})
            raw_info = raw_infos[18*i:18*(i+1)]
            infos[i]['bbox'] = raw_info[:4]
            infos[i]['fpoints'] = raw_info[4:14]
            infos[i]['score'] = raw_info[15]
            infos[i]['rotations'] = raw_info[-3:]
        return infos

    def verify(self, image1, height1, width1, image2, height2, width2):
        """
        Compute facial similarity with given two image byte list
        return cos similar: float to java
        """
        # convert to numpy OpenCV like
        image1 = self._listToNp(image1, height1, width1)
        image2 = self._listToNp(image2, height2, width2)
        # detect face informations
        faceInfo1 = self._detect(image1)
        faceInfo2 = self._detect(image2)
        # verify similarity
        if len(faceInfo1) == 0:
            if len(faceInfo2) == 0: # both no face
                sim = -3
            else:   # only image1 no face
                sim = -1
        else:
            if len(faceInfo2) == 0:  # only image2 no face
                sim = -2
            else:   # both have face
                fpoints1 = faceInfo1[0]['fpoints']
                fpoints2 = faceInfo2[0]['fpoints']
                #sim==4 means image1 is a fake face,otherwise ,return the simiarity.
                sim = self.center.verify(image1, fpoints1, image2, fpoints2)
        return sim

    def detect(self, image, height, width):
        """
        Detect face informations of given numpy OpenCV like: BGR uint8
        return faceInfos : float[][18] to java
        [
          x1, y1, x2, y2,   # bounding box
          xy,xy,xy,xy,xy,   # facial points
          score,            # confidence
          - roll,           # Z axis 翻转角:歪着脸  * NotImplemented
          - pitch,          # X axis 俯仰角:上下看  * NotImplemented
          - yaw             # Y axis 偏航角:左右看  * NotImplemented
        ]
        """
        image = self._listToNp(image, height, width)
        raw_infos = self.mtcnn.detect(image)
        infos = []
        num = len(raw_infos) / 18
        # print num,
        for i in xrange(num):
            info = []
            for f in raw_infos[18*i:18*(i+1)]:
                info.append(round(f, 3))
            infos.append(jpy.array('float', info)) # float[]
        return jpy.array(FloatArray, infos) # flaot[][]

    def extract(self, image, height, width):
        """
        Extract facial features in given image
        return faceFeatures: float[][] to java
        [
          x1, y1, x2, y2,   # bounding box
          score,            # confidence
          feature           # center feature
        ]
        """
        image = self._listToNp(image, height, width)
        face_infos = self._detect(image)
        feat_infos = []
        fpoints = []

        for face_info in face_infos:
            feat_info = face_info['bbox']
            feat_info.append(face_info['score'])
            feat_infos.append(feat_info)
            fpoints.append(face_info['fpoints'])

        features = self.center.extract(image, fpoints)
        for i in xrange(features.shape[0]):
            feat_infos[i].extend(list(features[i]))
            # print feat_infos[i][:6]
            feat_infos[i] = jpy.array('float', feat_infos[i]) # float[]
        return jpy.array(FloatArray, feat_infos)    # float[][]

class Center:
    """
    Handle center feature similarity.
    + verify            compute similarity of two image with facial key points
    - _merge_factory    create merge function with given merge type
    - _align            align face in image with fpoints list
    - _extract          extract center feature with given batch faces
    - _similar          compute cosine similarity of given features
    """
    def __init__(self, configs, device_id):
        # caffe environment settings
        caffe.set_mode_gpu()
        caffe.set_device(device_id)

        # basic settings
        self._ref_points = np.float32(configs['ref_points']).reshape((5,2))
        self._mode = configs['mode']
        self._mirror = configs['mirror']
        self._pca_model = configs['pca_model']

        if self._mode == 'verify':
            self._batch_face = 2
            if self._mirror:
                self._batch_size = self._batch_face * 2
            else:
                self._batch_size = self._batch_face
        else:
            if self._mirror:
                self._batch_face = configs['batch_size'] / 2  # each batch contains face num
                self._batch_size = self._batch_face * 2
            else:
                self._batch_face = configs['batch_size']
                self._batch_size = self._batch_face

        if self._pca_model:
            self._pca = joblib.load(str(self._pca_model))

        # load center model
        self._net = caffe.Net(
                str(configs['deploy']),
                str(configs['model']),
                caffe.TEST)
        self._in = self._net.inputs[0]
        self._layer = self._net.outputs[0]    # feature layer name
        self._image_size = self._net.blobs[self._in].data.shape[2:]
        self._data_shape = (self._batch_size, 3) + self._image_size
        self._net.blobs[self._in].reshape(*self._data_shape)
        self._feature_length = self._net.blobs[self._layer].data.shape[1]

        # data container
        self._input = np.zeros(self._data_shape, dtype=np.float32)
        if self._mirror:
            if str(self._mirror) == 'concatenate':
                self._merge = np.zeros((self._batch_face, self._feature_length*2), dtype=np.float32)
            else:
                self._merge = np.zeros((self._batch_face, self._feature_length), dtype=np.float32)
        self._merge_function = self._merge_factory(str(self._mirror))

        # init transfomer
        self._transformer = caffe.io.Transformer({self._in: self._data_shape})
        self._transformer.set_transpose(self._in, (2,0,1)) # HWC to CHW
        self._transformer.set_raw_scale(self._in, 255)     # [0,1] to [0,255]
        self._transformer.set_mean(self._in, np.array((127.5, 127.5, 127.5)))  # substract mean
        # self._transformer.set_channel_swap(self._in, (2,1,0))    # RGB to BGR
        self._transformer.set_input_scale(self._in, 0.0078125)   # to [-1, 1]
        self.anti_init_net()

    def _merge_factory(self, merge_type):
        """
        Use closure to save 'if' check every time we merge mirror feature
        """
        if merge_type == 'concatenate':
            def merge_feature(features):
                for i in xrange(self._batch_face):
                    self._merge[i] = np.concatenate((features[2*i], features[2*i+1]))
        elif merge_type == 'add': # elem-wise add
            def merge_feature(features):
                for i in xrange(self._batch_face):
                    self._merge[i] = features[2*i] + features[2*i+1]
        elif merge_type == 'max': # elem-wise max
            def merge_feature(features):
                for i in xrange(self._batch_face):
                    for j in xrange(self._feature_length):
                        self._merge[i][j] = max(features[2*i][j], features[2*i+1][j])
        elif merge_type == 'min': # elem-wise min
            def merge_feature(features):
                for i in xrange(self._batch_face):
                    for j in xrange(self._feature_length):
                        self._merge[i][j] = min(features[2*i][j], features[2*i+1][j])
        else:    # None: Disable mirror
            def merge_feature(features):
                self._merge = features

        return merge_feature

    def _align(self, image, fpoints):
        """
        Align Face with given facial key points.
        Affine transformation to reference standard key points
        """
        fpoints = np.float32(fpoints).reshape((5,2))
        tfrom = tf.estimate_transform('similarity', self._ref_points, fpoints)
        warp_image = tf.warp(image, inverse_map=tfrom,
                output_shape=self._image_size)
        return warp_image

    def _extract(self, batch_faces):
        """
        Extract feature with given batch faces using center model
        Enable batch to extract feature simultaneously
        """
        assert(len(batch_faces) <= self._batch_face)
        if self._mirror:
           for i in xrange(len(batch_faces)):
               self._input[2*i] = self._transformer.preprocess(self._in, batch_faces[i])
               self._input[2*i+1] = self._transformer.preprocess(self._in, np.fliplr(batch_faces[i]))
        else:
            for i in xrange(len(batch_faces)):
                self._input[i] = self._transformer.preprocess(self._in, batch_faces[i])
        self._net.blobs[self._in].data[...] = self._input
        self._net.forward()
        self._merge_function(self._net.blobs[self._layer].data)

    def extract(self, image, fpoints):
        """
        Extract feature with given faces using center model
        """
        num = len(fpoints)
        faces = []
        for i in xrange(num):
            faces.append(self._align(image, fpoints[i]))
        features = np.zeros((num, self._feature_length), np.float32)
        for begin in xrange(0, num, self._batch_face):
            end = min(begin+self._batch_face, num)
            self._extract(faces[begin:end])
            features[begin:end] = self._merge[:end-begin]

        if self._pca_model:
            return self._pca.transform(features)
        else:
            return features

    def _similar(self, features):
        """
        Compute cosine similarity between two features
        """
        feat1 = np.mat(features[0])
        feat2 = np.mat(features[1])
        inp = float(feat1 * feat2.T)
        denom = la.norm(feat1) * la.norm(feat2)
        return 0.5 + 0.5 * (inp / denom)

    #def anti_init_net(self):
    #    anti_spoofing_model='./python/center/model/anti_iter_120000.caffemodel'
    #    anti_spoofing_deploy='./python/center/model/anti_deploy.prototxt'
    #    anti_spoofing_net=caffe.Classifier(anti_spoofing_deploy,anti_spoofing_model,
    #            mean=np.array((127.5, 127.5, 127.5)),
    #            channel_swap=(2,1,0),
    #            raw_scale=255,
    #            image_dims=(112,96))#(112,96)
    #    return anti_spoofing_net

    #def anti_spoofing(self, net, img):
    #    #print 'pic shape is:',img.shape[0],img.shape[1]
    #    prediction=(net.predict([img],oversample=False))[0].argmax()
    #    return prediction
    #
    def anti_init_net(self):
        anti_spoofing_model='./python/center/model/anti_iter_120000.caffemodel'
        anti_spoofing_deploy='./python/center/model/anti_deploy.prototxt'
        self._anti_net=caffe.Net(anti_spoofing_deploy,anti_spoofing_model,caffe.TEST)

    def anti_spoofing(self,_anti_net, img):
        _anti_in = _anti_net.inputs[0]
        _anti_layer = _anti_net.outputs[0]    # feature layer name
        _anti_input = self._transformer.preprocess(_anti_in, img)
        _anti_net.blobs[_anti_in].data[...] = _anti_input
        _anti_net.forward()
        prediction=_anti_net.blobs[_anti_layer].data.argmax()
        return prediction

    def verify(self, image1, fpoints1, image2, fpoints2):
        """
        Verify similarity of given two image
        * argv   : numpy  OpenCV like BGR uint8
                   list   Facial key points
        * return : float  Cosine similarity
        """
        face1 = self._align(image1, fpoints1)
        face2 = self._align(image2, fpoints2)

        #anti_net=self.anti_init_net()
        anti_pred=self.anti_spoofing(self._anti_net,face1)
        if anti_pred==0:#face1 is real
            self._extract([face1, face2])
            if self._pca_model:
                return self._similar(self._pca.transform(self._merge))
            else:
                return self._similar(self._merge)
        else:
            return -4
        '''
        self._extract([face1, face2])
        if self._pca_model:
            return self._similar(self._pca.transform(self._merge))
        else:
            return self._similar(self._merge)
        '''
if __name__ == "__main__":
    caffe.init_log(2)
    test_main()


import tensorflow as tf
import tensorflow.contrib as tc

initializer = lambda: tf.contrib.layers.variance_scaling_initializer(
    factor=1.0, mode="FAN_AVG", uniform=True, dtype=tf.float32
)
initializer_relu = lambda: tf.contrib.layers.variance_scaling_initializer(
    factor=2.0, mode="FAN_IN", uniform=False, dtype=tf.float32
)
regularizer = tf.contrib.layers.l2_regularizer(scale=3e-7)

def highway(
    x,
    size=None,
    activation=tf.nn.relu,
    num_layers=2,
    scope="highway",
    dropout=0.0,
    reuse=None,
):
    with tf.variable_scope(scope, reuse):
        if size is None:
            size = x.shape.as_list()[-1]
        else:
            x = conv(x, size, name="input_projection", reuse=reuse)
        for i in range(num_layers):
            T = conv(
                x,
                size,
                bias=True,
                activation=tf.sigmoid,
                name="gate_%d" % i,
                reuse=reuse,
            )
            H = conv(
                x,
                size,
                bias=True,
                activation=activation,
                name="activation_%d" % i,
                reuse=reuse,
            )
            H = tf.nn.dropout(H, 1.0 - dropout)
            x = H * T + x * (1.0 - T)
        return x

def conv(
    inputs,
    output_size,
    bias=None,
    activation=None,
    kernel_size=1,
    name="conv",
    reuse=None,
):
    with tf.variable_scope(name, reuse=reuse):
        shapes = inputs.shape.as_list()
        if len(shapes) > 4:
            raise NotImplementedError
        elif len(shapes) == 4:
            filter_shape = [1, kernel_size, shapes[-1], output_size]
            bias_shape = [1, 1, 1, output_size]
            strides = [1, 1, 1, 1]
        else:
            filter_shape = [kernel_size, shapes[-1], output_size]
            bias_shape = [1, 1, output_size]
            strides = 1
        conv_func = tf.nn.conv1d if len(shapes) == 3 else tf.nn.conv2d
        kernel_ = tf.get_variable(
            "kernel_",
            filter_shape,
            dtype=tf.float32,
            regularizer=regularizer,
            initializer=initializer_relu() if activation is not None else initializer(),
        )
        outputs = conv_func(inputs, kernel_, strides, "VALID")
        if bias:
            outputs += tf.get_variable(
                "bias_",
                bias_shape,
                regularizer=regularizer,
                initializer=tf.zeros_initializer(),
            )
        # outputs = layer_norm(outputs)
        if activation is not None:
            return activation(outputs)
        else:
            return tf.nn.tanh(outputs)

def rnn(
    rnn_type,
    scope,
    inputs,
    length,
    hidden_size,
    layer_num=1,
    dropout_keep_prob=None,
    concat=True,
    reuse=None,
):
    """
    Implements (Bi-)LSTM, (Bi-)GRU and (Bi-)RNN
    Args:
        rnn_type: the type of rnn
        inputs: padded inputs into rnn
        length: the valid length of the inputs
        hidden_size: the size of hidden units
        layer_num: multiple rnn layer are stacked if layer_num > 1
        dropout_keep_prob:
        concat: When the rnn is bidirectional, the forward outputs and backward outputs are
                concatenated if this is True, else we add them.
    Returns:
        RNN outputs and final state
    """
    with tf.variable_scope(scope, reuse=reuse):
        if not rnn_type.startswith("bi"):
            cell = get_cell(rnn_type, hidden_size, layer_num, dropout_keep_prob)
            outputs, states = tf.nn.dynamic_rnn(
                cell, inputs, sequence_length=length, dtype=tf.float32
            )
            if rnn_type.endswith("lstm"):
                c = [state.c for state in states]
                h = [state.h for state in states]
                states = h
        else:
            cell_fw = get_cell(rnn_type, hidden_size, layer_num, dropout_keep_prob)
            cell_bw = get_cell(rnn_type, hidden_size, layer_num, dropout_keep_prob)
            outputs, states = tf.nn.bidirectional_dynamic_rnn(
                cell_bw, cell_fw, inputs, sequence_length=length, dtype=tf.float32
            )
            states_fw, states_bw = states
            if rnn_type.endswith("lstm"):
                c_fw = [state_fw.c for state_fw in states_fw]
                h_fw = [state_fw.h for state_fw in states_fw]
                c_bw = [state_bw.c for state_bw in states_bw]
                h_bw = [state_bw.h for state_bw in states_bw]
                states_fw, states_bw = h_fw, h_bw
            if concat:
                outputs = tf.concat(outputs, 2)
                states = tf.concat([states_fw, states_bw], 1)
            else:
                outputs = outputs[0] + outputs[1]
                states = states_fw + states_bw
        return outputs, states

def get_cell(rnn_type, hidden_size, layer_num=1, dropout_keep_prob=None):
    """
    Gets the RNN Cell
    Args:
        rnn_type: 'lstm', 'gru' or 'rnn'
        hidden_size: The size of hidden units
        layer_num: MultiRNNCell are used if layer_num > 1
        dropout_keep_prob: dropout in RNN
    Returns:
        An RNN Cell
    """
    cells = []
    for i in range(layer_num):
        if rnn_type.endswith("lstm"):
            cell = tc.rnn.LSTMCell(num_units=hidden_size, state_is_tuple=True)
        elif rnn_type.endswith("gru"):
            cell = tc.rnn.GRUCell(num_units=hidden_size)
        elif rnn_type.endswith("rnn"):
            cell = tc.rnn.BasicRNNCell(num_units=hidden_size)
        else:
            raise NotImplementedError("Unsuported rnn type: {}".format(rnn_type))
        if dropout_keep_prob is not None:
            cell = tc.rnn.DropoutWrapper(
                cell,
                input_keep_prob=dropout_keep_prob,
                output_keep_prob=dropout_keep_prob,
            )
        cells.append(cell)
    cells = tc.rnn.MultiRNNCell(cells, state_is_tuple=True)
    return cells

def layer_norm(x, filters=None, epsilon=1e-6, scope=None, reuse=None):
    """Layer normalize the tensor x, averaging over the last dimension."""
    if filters is None:
        filters = x.get_shape()[-1]
    with tf.variable_scope(scope, default_name="layer_norm", values=[x], reuse=reuse):
        scale = tf.get_variable(
            "layer_norm_scale",
            [filters],
            regularizer=regularizer,
            initializer=tf.ones_initializer(),
        )
        bias = tf.get_variable(
            "layer_norm_bias",
            [filters],
            regularizer=regularizer,
            initializer=tf.zeros_initializer(),
        )
        result = layer_norm_compute_python(x, epsilon, scale, bias)
        return result

def layer_norm_compute_python(x, epsilon, scale, bias):
    """Layer norm raw computation."""
    mean = tf.reduce_mean(x, axis=[-1], keep_dims=True)
    variance = tf.reduce_mean(tf.square(x - mean), axis=[-1], keep_dims=True)
    norm_x = (x - mean) * tf.rsqrt(variance + epsilon)
    return norm_x * scale + bias


import asyncio
import io
import json
import shutil
from asyncio import sleep

import discord
import requests
from PIL import Image
from decouple import config
from discord import Message, Member, VoiceState, VoiceChannel, File
from discord.ext import commands
from discord.ext.commands import Context
from gtts import gTTS
from io import StringIO

TOKEN = config("BOT_TOKEN")
TPN_TOKEN = config("TPN_TOKEN")
FFMPEG_PATH = config("FFMPEG_PATH")

intents = discord.Intents.all()
intents.members = True

bot = commands.Bot(intents=intents, command_prefix="!")

@bot.event
async def on_ready():
    print(f"{bot.user.name} has connected to Discord!")

@bot.event
async def on_member_join(member):
    await member.create_dm()
    await member.dm_channel.send(f"Welcome to the rice fields, {member.name},!")

async def play_audio(v_channel, file: str | bytes):
    vc = await v_channel.connect(self_mute=False, self_deaf=True, timeout=5)

    audio = discord.FFmpegPCMAudio(
        file,
        executable=FFMPEG_PATH,
        options='-filter:a "atempo=1.5"',
        pipe=file is bytes,
    )
    vc.play(audio)

    while vc.is_playing():
        await sleep(0.1)

    await vc.disconnect()

@bot.event
async def on_message(message: Message):
    sussy_words = ["sus", "сас", "сус", "сассать"]

    if any(ext in message.content for ext in sussy_words):
        await message.channel.send("❗❗❗❗ SUSSY ALERT ❗❗❗❗")

        if message.author.voice.channel is None:
            return

        await play_audio(message.author.voice.channel, "sounds/sus.mp3")

    elif message.content == "raise-exception":
        raise discord.DiscordException

    await bot.process_commands(message)

@bot.event
async def on_voice_state_update(member: Member, before: VoiceState, after: VoiceState):
    if member.name == "MishaBot":
        return

    if after.channel is not None and not after.mute and before.channel is None:
        myobj = gTTS(
            text=f"Импостер {member.display_name} залетел в {after.channel.name}!",
            lang="ru",
            slow=True,
        )
        myobj.save("kekw.mp3")
        await play_audio(after.channel, "kekw.mp3")
        await play_audio(after.channel, "sounds/join.mp3")
    elif not before.self_deaf and after.self_deaf:
        myobj = gTTS(
            text=f"{member.display_name} нихуя не слышит!", lang="ru", slow=True
        )
        myobj.save("kekw.mp3")
        await play_audio(after.channel, "kekw.mp3")
    elif before.self_deaf and not after.self_deaf:
        myobj = gTTS(
            text=f"{member.display_name}; пока тебя не было, твою мать выебали!",
            lang="ru",
            slow=True,
        )
        myobj.save("kekw.mp3")
        await play_audio(after.channel, "kekw.mp3")

    elif not before.self_mute and after.self_mute:
        myobj = gTTS(
            text=f"{member.display_name} - хули ты замютился, дибил ебаный?",
            lang="ru",
            slow=True,
        )
        myobj.save("kekw.mp3")
        await play_audio(after.channel, "kekw.mp3")
    elif before.self_mute and not after.self_mute:
        myobj = gTTS(
            text=f"{member.display_name} - бичара вернулся!", lang="ru", slow=True
        )
        myobj.save("kekw.mp3")
        await play_audio(after.channel, "kekw.mp3")

@bot.event
async def on_presence_update(before: Member, after: Member):
    pass

@bot.event
async def on_member_update(before: Member, after: Member):
    if before.roles != after.roles:
        new_roles = []
        old_roles = []
        for role in after.roles:
            if role not in before.roles:
                new_roles.append(role.name)
        for role in before.roles:
            if role not in after.roles:
                old_roles.append(role.name)

        if len(new_roles) > 0:
            myobj = gTTS(
                text=f"Поздравляем {after.display_name} - c получением звания {', '.join(new_roles)}",
                lang="ru",
                slow=True,
            )
            myobj.save("kekw.mp3")
            await play_audio(after.voice.channel, "kekw.mp3")
        else:
            myobj = gTTS(
                text=f"{after.display_name} - ты больше не {', '.join(old_roles)}",
                lang="ru",
                slow=True,
            )
            myobj.save("kekw.mp3")
            await play_audio(after.voice.channel, "kekw.mp3")

@bot.command(name="trace", help="Track CSGO")
async def csgo_track(ctx: Context, nickname):
    response = requests.get(
        url=f"https://public-api.tracker.gg/v2/csgo/standard/profile/steam/{nickname}",
        headers={
            "TRN-Api-Key": f"{TPN_TOKEN}",
            "Accept": "application/json",
            "Accept-Encoding": "gzip",
        },
    )
    if response.status_code != 200:
        await ctx.send("No such user exists?? or smth")
        return

    data = json.loads(response.content.decode("utf-8"))

    juice = data["data"]["segments"][0]["stats"]
    username = data["data"]["platformInfo"]["platformUserHandle"]
    image_url = data["data"]["platformInfo"]["avatarUrl"]

    text = (
        f"Nickname: {username}\n\n"
        f"Time Played: {juice['timePlayed']['displayValue']}\n"
        f"K/D: {juice['kd']['displayValue']}\n"
        f"Accuracy: {juice['shotsAccuracy']['displayValue']}\n"
        f"Headshots: {juice['headshotPct']['displayValue']}\n"
        f"Win Rate: {juice['wlPercentage']['displayValue']}\n"
    )

    pic_response = requests.get(image_url)

    if pic_response.status_code != 200:
        await ctx.send(text)
    else:
        response = requests.get(image_url, stream=True)
        with open("img.png", "wb") as out_file:
            shutil.copyfileobj(response.raw, out_file)

        del response
        await ctx.send(text, file=File("img.png", filename="kekw.png"))
    await play_audio(ctx.author.voice.channel, "sounds/gamer.mp3")

if __name__ == "__main__":
    bot.run(TOKEN)


from typing import Type
from dacite import from_dict
from containers import Container
from controllers.v2.abstract.abstract_create_read_controller_v2 import AbstractCreateReadControllerV2
from dtos.v2.account_dto_v2 import AccountLoginRequestV2, AccountLoginResponseV2
from services.account_service import AccountService
from dependency_injector.wiring import inject, Provide
from services.visitor_service import VisitorService

class AccountsView(AbstractCreateReadControllerV2):
    """Controller Class to handle Admin Account Operations"""

    @inject
    def __init__(
            self,
            visitor_service: VisitorService = Provide[Container.visitor_service],
            account_service: AccountService = Provide[Container.account_service],
    ):
        super().__init__(
            service=account_service,
            visitor_service=visitor_service,
            response_dto=AccountLoginResponseV2,
            request_dto=AccountLoginRequestV2,
        )

    def admin_login(self, request:dict):
        """Controller function to perform admin login authentication and return the token"""

        dto: Type[AccountLoginRequestV2] = from_dict(data_class=self.request_dto, data = request)
        if dto.email is not None:
            try:
                login_admin = self.service.login(dto.email, dto.password)
                login_response = self.response_dto.from_model(login_admin)
                return login_response, 200
            except Exception as e:
                print(e)
                return None, 404
        else:
            return None, 403


"""
This class is used to create the following OpenSees TCL Commands:
Constant TimeSeries
Linear TimeSeries
Trigonometric TimeSeries
Triangular TimeSeries
Rectangular TimeSeries
Pulse TimeSeries
Path TimeSeries
PeerMotion
PeerNGAMotion
"""

__author__ = 'marafi'

from OpenSeesAPI.OpenSees import OpenSees

class Path(OpenSees):
    """
    This command is used to construct a Path TimeSeries object. The relationship between load factor and time is input by the user as a series of discrete points in the 2d space (load factor, time). The input points can come from a file or from a list in the script. When the time specified does not match any of the input points, linear interpolation is used between points. There are many ways to specify the load path:
    For a load path where the factors are specified in a tcl list with a constant time interval between points:
    timeSeries Path $tag -dt $dt -values {list_of_values} <-factor $cFactor>
    For a load path where the factors are specified in a file for a constant time interval between points:
    timeSeries Path $tag -dt $dt -filePath $filePath <-factor $cFactor>
    For a load path where the values are specified at non-constant time intervals:
    timeSeries Path $tag -time {list_of_times} -values {list_of_values} <-factor $cFactor>
    For a load path where both time and values are specified in a list included in the command
    timeSeries Path $tag -fileTime $fileTime -filePath $filePath <-factor $cFactor>
    """
    def __init__(self, id, dt, ValuesList):
        self._id = id
        self._dt = dt
        self._ValueList = ValuesList
        self._CommandLine = 'timeSeries Path %d -dt %f -values {%s}'%(self._id, self._dt, ''.join([' %f'%x for x in self._ValueList]))


# -*- coding: utf-8 -*-
"""
Created on Tue Jun 28 12:46:06 2016

@author: Jee-Bee for jBae (c) 2016
"""

import numpy as np
from scipy import signal
from scipy.fftpack import fft, fftshift, fftfreq
import matplotlib.pylab as plt

f0 = 20  # frequency start
f1 = 10000  # frequency end
fs = 44100  # frequency sample
T = 5  # time max
t = np.arange(0, T*fs)/fs  # time array

# Define Window length and window:
factor_f = fs/f1  # factor fs/f1
T = T - (np.ceil(factor_f) + 1) / fs

#x = signal.chirp(t, f0, T, f1, 'log', 90)
x = np.sin(2 * np.pi * 100 * t) + 0.7 * np.sin(2 * np.pi * 880 * t) + 0.2 * np.sin(2 * np.pi * 2400 * t)

bitDept = 16
phi = (f0 * (f1 / f0) ** (t[-4:] / T)) % np.pi
#if all phi >= -1/(2 ** (bitDepth - 1 - 4)) and all phi <= 1/(2 ** (bitDepth - 1 - 4)):

if factor_f < 2:
    # print error
    pass
elif round(factor_f, 0) < 3:
    wl = 2  # window lenght
    overlap = 0.5
    W = signal.get_window('hanning', wl)  # window
elif round(factor_f, 0) < 6:
    wl = 4  # window lenght
    overlap = 0.5
    W = signal.get_window('hanning', wl)  # window
elif round(factor_f, 0) < 13:
    wl = 8  # window lenght
    overlap = 0.5
    W = signal.get_window('hanning', wl)  # window
else:
    wl = 16  # window lenght
    overlap = 0.5
    W = signal.get_window('hanning', wl)  # window

# worked make this concept working in main scripts of signal generators
# except use internal windwo against scipy window for now.
Wx = np.zeros(len(x))
#ul = wl
## loop added for window
#dsample = len(x) % wl  # delta in samples between mod (x/windw length)
#if dsample == 0:
#    nEntries = len(Wx)
#    step = int(wl * overlap)
#    while ul <= nEntries:
#        Wx[ul-wl:ul] += x[ul-wl:ul] * W
#        ul += step
#    Wx = np.append(Wx, 0)
#else:
#    x = np.append(x, np.zeros(wl - dsample))
#    nEntries = len(Wx)
#    step = int(wl * overlap)
#    while ul <= nEntries:
#        Wx[ul-wl:ul] += x[ul-wl:ul] * W
#        ul += step
#    Wx = np.append(Wx, 0)

# using numpy.nditer

dsample = len(x) % wl  # delta in samples between mod (x/windw length)
if dsample == 0:
    ul = np.arange((len(x) - (wl - 1)) / 2) * 2
    it = np.nditer(np.int_(ul), flags=['buffered'], casting='same_kind')  #, 'external_loop'])
    for idx in it:
        Wx[idx:idx + wl] += x[idx:idx + wl] * W
    Wx = np.append(Wx, 0)
else:
    x = np.append(x, np.zeros(wl - dsample))
    ul = np.arange((len(x) - (wl - 1)) / 2) * 2
    it = np.nditer(np.int_(ul), flags=['buffered'], casting='same_kind')  #, 'external_loop'])
    for idx in it:
        Wx[idx:idx + wl] += x[idx:idx + wl] * W
    Wx = np.append(Wx, 0)

# Conclusion:
# becouse nditer makes arrays of 1 value it takes more time as with plain loop!

# NFFT for Pro's:
# Because of the above relationship it is convenient to have N even, as we do assume throughout
# this report. Some subroutine packages even demand that N be a power of 2. That is, however,
# an unnecessarily stringent limitation in many situations. The FFTW package, for example, will
# compute the DFT for any positive integer N , and with high efficiency for integers of the form
# N = 2 a 3 b 5 c 7 d 11 e 13 f ,          (9)
# where e + f is either 0 or 1 and the other exponents are arbitrary.

# Frequency spectrums with NFFT and diferent names (13.152 seconds)
#NFFT = np.int(2 ** np.ceil(np.log2(len(x))))
#NFFW = np.int(2 ** np.ceil(np.log2(len(Wx))))
#X = fft(x, NFFT)
#WX = fft(Wx, NFFW)

# Frequency spectrums with NFFT and same name (13.121 seconds - 13.504 seconds)
NFFT = np.int(2 ** np.ceil(np.log2(len(x))))
X = fft(x, NFFT)
NFFT = np.int(2 ** np.ceil(np.log2(len(Wx))))
WX = fft(Wx, NFFT)

# Frequency spectrums no NFFT (27.034 seconds)
#X = fft(x)
#WX = fft(Wx)
# Conclusion without NFFT (Next number off FFT) loop much slower renamening
# don't do much around the same speed.

#if len(t) < 10000:
#    # mpl.RcParams()
#    plt.rcParams['agg.path.chunksize'] = 2 ** 16
#
#plt.figure()
# plt.plot(t, x)
#plt.plot(t[-10000:], x[-10000:])
#plt.plot(t[-10000:], Wx[-10000:])

# plt.figure()
# # plt.plot(t, x)
# plt.plot(t[:10000], x[:10000])

# plt.figure()
# # plt.plot(t, x)
# plt.plot(W)

# fft signals
#plt.figure()
#plt.semilogx(np.abs(X))
#plt.semilogx(np.abs(WX))
#plt.plot(np.abs(X))
#plt.plot(np.abs(WX))

# Window length frequency band
#fs = 192000
#n = np.arange(10)
#wl = 2 ** n  # window length
#Tw = wl/fs  # time length Window
#freq = 1/Tw
#print(n, wl, freq)


import torch
from ..utility.accumarray import *
from ..utility.strcmpi    import *
from ..math.cross         import *
from ..math.normvec       import *
from .triangle_angle      import *

def vertex_normal(P, T, type=None):
    """
    Returns the normal of the vertices in the triangulation, averaged with the
    specified method.

    Parameters
    ----------
    P : Tensor
        the input point set
    T : LongTensor
        the topology tensor
    type : str (optional)
        the averaging method. Can be either None (mean), 'area' or 'angle' (default is None)

    Returns
    -------
    Tensor
        the vertex normals of the input mesh
    """

    Pi, Pj, Pk = P[T]
    Ni = cross(Pj - Pi, Pk - Pi)
    Nj = cross(Pk - Pj, Pi - Pj)
    Nk = cross(Pi - Pk, Pj - Pk)
    if type is not None:
        if strcmpi(type, 'area'):
            Ai = torch.mul(norm(Ni), 0.5)
            Aj = torch.mul(norm(Nj), 0.5)
            Ak = torch.mul(norm(Nk), 0.5)
            Ni = normr(Ni) * Ai
            Nj = normr(Nj) * Aj
            Nk = normr(Nk) * Ak
        if strcmpi(type, 'angle'):
            Ai, Aj, Ak = triangle_angle(P, T)
            Ni = normr(Ni) * Ai
            Nj = normr(Nj) * Aj
            Nk = normr(Nk) * Ak
    V = torch.cat((Ni, Nj, Nk), dim=0)
    N = accumarray(T.view(-1), V, size=P.size())
    return normr(N)