# from autogluon.tabular import TabularDataset, TabularPredictor
# train_data = TabularDataset('https://autogluon.s3.amazonaws.com/datasets/Inc/train.csv')
# f = open('/workfile.txt', 'r+')
# f.write(train_data)
# subsample_size = 500  # subsample subset of data for faster demo, try setting this to much larger values
# train_data = train_data.sample(n=subsample_size, random_state=0)
# train_data.head()
# label = 'class'
# print("Summary of class variable: \n", train_data[label].describe())
# save_path = 'agModels-predictClass'  # specifies folder to store trained models
# predictor = TabularPredictor(label=label, path=save_path).fit(train_data)
# test_data = TabularDataset('https://autogluon.s3.amazonaws.com/datasets/Inc/test.csv')
# y_test = test_data[label]  # values to predict
# test_data_nolab = test_data.drop(columns=[label])  # delete label column to prove we're not cheating
# test_data_nolab.head()
# predictor = TabularPredictor.load(save_path)  # unnecessary, just demonstrates how to load previously-trained predictor from file
# y_pred = predictor.predict(test_data_nolab)
# test_data_nolab[label] = y_pred
# test_data_nolabel.to_csv(filelist[3],encoding='utf-8', index=False)F

# print("Predictions:  \n", y_pred)
# perf = predictor.evaluate_predictions(y_true=y_test, y_pred=y_pred, auxiliary_metrics=True)

# import os
# import os.path
# from os import path
# # import aif360.datasets.compas_dataset

# # filelist = ['workfile.csv', 'workfile_test.csv', 'workfile_train.csv', 'workfile_test_predictions.csv']
# # for file in filelist:
# #     if path.isfile(file):
# #         os.remove(file)
# import pandas as pd
# # protected_attributes = ['age', 'sex', 'race', 'gender', 'ethnicity',
# #                         'marital status', 'religion', 'national origin',
# #                         'public assistance', 'disability', 'pregnancy', 'maternity']
# # df = pd.read_csv('workfile.csv')
# # print(list(df))
# # present_protected_attributes = []
# # for attr in df:
# #     for prot in protected_attributes:
# #         if prot in attr:
# #             present_protected_attributes.append(attr)

# # print(present_protected_attributes)
from aif360.datasets import StandardDataset
from aif360.metrics import BinaryLabelDatasetMetric
from sklearn.preprocessing import OrdinalEncoder
import pandas as pd
from itertools import permutations

label = 'decile_score'
# protected_attr = 'sex'
# priveledged = 'Female'
# unpriveledged = 'Male'
df = pd.read_csv('compas-scores-low-med-high.csv')
# df[label].mask(df[label] <= 4, 0, inplace=True)
# df[label].mask(df[label] >= 5, 1, inplace=True)

# print(df.head())
# df.fillna(0)

# # # now that we have the binary encoding for scores we can calculate bias metrics
oe = OrdinalEncoder()
df[["sex", "age_cat", "race", "c_days_from_compas", "c_charge_degree", "c_charge_desc"]] = oe.fit_transform(
    df[["sex", "age_cat", "race", "c_days_from_compas", "c_charge_degree", "c_charge_desc"]])
df.to_csv("compas-scores-orig-processed.csv", encoding='utf-8', index=False)

df[label].mask(df[label] == 0, 0, inplace=True)
df[label].mask(df[label] >= 2, 1, inplace=True)
df.fillna(0)

# print(df.head())
# dataset = StandardDataset(df,
#                           label_name=label,
#                           favorable_classes=[0],
#                           protected_attribute_names=[protected_attr],
#                           privileged_classes=[[0]])

# privileged_groups = [{protected_attr: 0}]
# unprivileged_groups = [{protected_attr: 1}]
# metric_orig_train = BinaryLabelDatasetMetric(dataset,
#                                              unprivileged_groups=unprivileged_groups,
#                                              privileged_groups=privileged_groups)

# print(metric_orig_train.mean_difference())
# print(metric_orig_train.disparate_impact())

# if not path.isfile('woo.csv'):
#     print('it works')
# from flask import Flask, render_template, request
# from autogluon.tabular import TabularPredictor
import pandas as pd
from sklearn.model_selection import train_test_split
# import json
# import os
# import shutil
import os.path
# from os import path
import itertools

# label = 'decile_score'
# df = pd.read_csv('compas-scores-orig2.csv')
# make all headers lowercase
# df.columns = df.columns.str.lower()
# # make client label input all lowercase
# label = label.lower()
# df[label].mask(df[label] <= 4, 0, inplace=True)
# df[label].mask(df[label].between(5,7), 1, inplace=True)
# df[label].mask(df[label] >= 8, 2, inplace=True)
# df.fillna(0)

# split the csv into train and test data
# train_data, test_data = train_test_split(df, test_size=0.2)
# # save test and train csv's
# df.to_csv('low_medium_high.csv', encoding='utf-8', index=False)

# models_dir = 'agModels-predictClass'
# predictor = TabularPredictor(label=label, path=models_dir).fit(
#     train_data=train_data, presets='best_quality')
# y_test = test_data[label]  # values to predict
# # delete label column
# test_data_nolabel = test_data.drop(columns=[label])
# # predict
# y_pred = predictor.predict(test_data_nolabel)
# save predictions
# test_data = test_data_nolabel
# test_data_nolabel[label] = y_pred
# test_data_nolabel.to_csv('compas-test.csv',
#                             encoding='utf-8', index=False)
# get random row like in the code
# df = test_data.sample()

# get protected attributes permutations
# protected_attributes = ['age_cat', 'sex', 'race']
# need to make a new df with all permutations of 3 columns
# sex_perms = ['Male', 'Female']
# age_cat_perms = ['Greater than 45', '25-45', 'Less than 25']
# race_perms = ['Other', 'African-American',
#               'Hispanic', 'Asian', 'Native American']
# protected_atrributes = [sex_perms, age_cat_perms, race_perms]
# all_permutations = list(itertools.product(*protected_atrributes))
# print(all_permutations)

# new_df = df.reset_index()
# new_dict = new_df.to_dict('records')
# my_dict = new_dict[0]
# del my_dict['index']

# output = pd.DataFrame()
# # create new df with all permutations
# for permutation in all_permutations:
#     my_dict['sex'] = permutation[0]
#     my_dict['age_cat'] = permutation[1]
#     my_dict['race'] = permutation[2]
#     print(my_dict)
#     output = output.append(my_dict, ignore_index=True)

# print(output.head())
# predictor = TabularPredictor.load(models_dir)
# y_pred = predictor.predict(output)
# # append predictions
# output[label] = y_pred
# # save
# output.to_csv('permutations_csv',
#                                  encoding='utf-8', index=False)

# protected attributes who are the most unpriveledged overall
total_dict_unpriveledged_mean = {}
# protected attributes who have the highest benefit overall
total_dict_higher_benefit = {}

protected_attributes = ['age_cat', 'sex', 'race']
processed_data_sex = {'Male': 1, 'Female': 0}
processed_data_age_cat = {'age_cat_greater_than_45': 1,
                          'age_cat_25_to_45': 0, 'age_cat_less_than_25': 2}
processed_data_race = {'African-American': 0, 'Asian': 1,
                       'Caucasion': 2, 'Hispanic': 3, 'Native American': 4, 'Other': 5}

dataset = StandardDataset(df,
                            label_name=label,
                            # 0 represents low recidivism score
                            favorable_classes=[0],
                            protected_attribute_names=['sex'],
                            # for priveleged class we will use our dict
                            privileged_classes=[[0]]) # Female
# Again using our dict
privileged_groups = [{'sex': 0}] # Female
unprivileged_groups = [{'sex': 1}] # Male
metric_orig_train = BinaryLabelDatasetMetric(dataset,
                                                unprivileged_groups=unprivileged_groups,
                                                privileged_groups=privileged_groups)
# A negative value indicates less favorable outcomes for the unprivileged groups.
mean_diff = metric_orig_train.mean_difference()
# The ideal value of this metric is 1.0 A value < 1 implies higher benefit for the privileged group and a
# value >1 implies a higher benefit for the unprivileged group.
disparate_impact = metric_orig_train.disparate_impact()
if mean_diff < 0:
    sex_unpriveledged_mean = (list(processed_data_sex.keys())[list(processed_data_sex.values()).index(1)])
    total_dict_unpriveledged_mean[sex_unpriveledged_mean] = mean_diff
    key = "{}_mean : {}".format(sex_unpriveledged_mean, mean_diff)
    print(key)
if disparate_impact < 1:
    higher_benefit_priveledged = (list(processed_data_sex.keys())[list(processed_data_sex.values()).index(0)])
    total_dict_higher_benefit[higher_benefit_priveledged] = disparate_impact
    key = "{}_disparate_benefit: {}".format(higher_benefit_priveledged, disparate_impact)
    print(key)
# if disparate_impact > 1:
#     higher_benefit_unpriveledged = (list(pocessed_data_sex.keys())[list(pocessed_data_sex.values()).index(1)])
#     total_dict_higher_benefit[higher_benefit_unpriveledged] = disparate_impact
#     key = "{}_disparate_benefit: {}".format(higher_benefit_unpriveledged, disparate_impact)
#     print(key)

permutations_age_cat = list( permutations( range( 3 ), 2 ) )
lowest_mean_diff = 0
lowest_disparate_impact = 1
mean_list_unpriveledged = []
disparate_impact_list_benefit = []

for combination in permutations_age_cat:
    dataset = StandardDataset(df,
                            label_name=label,
                            # 0 represents low recidivism score
                            favorable_classes=[0],
                            protected_attribute_names=['age_cat'],
                            # for priveleged class we will use our dict
                            privileged_classes=[[combination[0]]])
    # Again using our dict
    privileged_groups = [{'age_cat': combination[0]}]
    unprivileged_groups = [{'age_cat': combination[1]}]
    metric_orig_train = BinaryLabelDatasetMetric(dataset,
                                                    unprivileged_groups=unprivileged_groups,
                                                    privileged_groups=privileged_groups)

    mean_diff = metric_orig_train.mean_difference()
    disparate_impact = metric_orig_train.disparate_impact()

    if mean_diff < 0 and mean_diff < lowest_mean_diff:
        least_priveledged = combination[1]
        lowest_mean_diff = mean_diff
        age_unpriveledged = (list(processed_data_age_cat.keys())[list(processed_data_age_cat.values()).index(least_priveledged)])
        mean_list_unpriveledged.append(age_unpriveledged)

    if disparate_impact < 1 and disparate_impact < lowest_disparate_impact:
        highest_priveledged = combination[0]
        lowest_disparate_impact = disparate_impact
        higher_benefit_priveledged = (list(processed_data_age_cat.keys())[list(processed_data_age_cat.values()).index(highest_priveledged)])
        disparate_impact_list_benefit.append(higher_benefit_priveledged)

age_unpriveledged = (list(processed_data_age_cat.keys())[list(processed_data_age_cat.values()).index(least_priveledged)])
total_dict_unpriveledged_mean[age_unpriveledged] = lowest_mean_diff
key = "{}_mean : {}".format(age_unpriveledged, lowest_mean_diff)
print(key)

higher_benefit_priveledged = (list(processed_data_age_cat.keys())[list(processed_data_age_cat.values()).index(highest_priveledged)])
total_dict_higher_benefit[higher_benefit_priveledged] = lowest_disparate_impact

key = "{}_disparate_benefit: {}".format(higher_benefit_priveledged, lowest_disparate_impact)
print(key)

age_list = ['age_cat_greater_than_45', 'age_cat_25_to_45', 'age_cat_less_than_25']

age_mean_least_counts = {}
for val in age_list:
    c = mean_list_unpriveledged.count(val)
    age_mean_least_counts[val] = c

# To return
age_highest_benefit_counts = {}
for val in age_list:
    c = disparate_impact_list_benefit.count(val)
    age_highest_benefit_counts[val] = c
# print((list(processed_data_age_cat.keys())[list(processed_data_age_cat.values()).index(least_priveledged)]))
# print((list(processed_data_age_cat.keys())[list(processed_data_age_cat.values()).index(compared_to)]))
# print(worst)

permutations_race = permutations_age_cat = list( permutations( range( 6 ), 2 ) )

# reset values
lowest_mean_diff = 0
lowest_disparate_impact = 1

mean_list_unpriveledged_race = []
disparate_impact_list_benefit_race = []
for combination in permutations_race:
    dataset = StandardDataset(df,
                            label_name=label,
                            # 0 represents low recidivism score
                            favorable_classes=[0],
                            protected_attribute_names=['race'],
                            # for priveleged class we will use our dict
                            privileged_classes=[[combination[0]]])
    # Again using our dict
    privileged_groups = [{'race': combination[0]}]
    unprivileged_groups = [{'race': combination[1]}]
    metric_orig_train = BinaryLabelDatasetMetric(dataset,
                                                    unprivileged_groups=unprivileged_groups,
                                                    privileged_groups=privileged_groups)

    mean_diff = metric_orig_train.mean_difference()
    disparate_impact = metric_orig_train.disparate_impact()

    if mean_diff < 0:
        if mean_diff < lowest_mean_diff:
            least_priveledged = combination[1]
            lowest_mean_diff = mean_diff
        race_unpriveledged = (list(processed_data_race.keys())[list(processed_data_race.values()).index(combination[1])])
        mean_list_unpriveledged_race.append(race_unpriveledged)

    if disparate_impact < 1:
        if disparate_impact < lowest_disparate_impact:
            highest_priveledged = combination[0]
            lowest_disparate_impact = disparate_impact
        higher_benefit_priveledged = (list(processed_data_race.keys())[list(processed_data_race.values()).index(combination[0])])
        disparate_impact_list_benefit_race.append(higher_benefit_priveledged)

race_unpriveledged = (list(processed_data_race.keys())[list(processed_data_race.values()).index(least_priveledged)])
total_dict_unpriveledged_mean[race_unpriveledged] = lowest_mean_diff

higher_benefit_priveledged = (list(processed_data_race.keys())[list(processed_data_race.values()).index(highest_priveledged)])
total_dict_higher_benefit[higher_benefit_priveledged] = lowest_disparate_impact

race_list = ['African-American', 'Asian', 'Caucasion', 'Hispanic', 'Native American', 'Other']
race_mean_least_counts = {}
for val in race_list:
    c = mean_list_unpriveledged_race.count(val)
    race_mean_least_counts[val] = c

# To return
race_highest_benefit_counts = {}
for val in race_list:
    c = disparate_impact_list_benefit_race.count(val)
    race_highest_benefit_counts[val] = c

print("\nAge Category: unpriveledged occurences - mean diffence")
print(age_mean_least_counts)
print("\nAge Category: higher benefit occurrences - disparate impact")
print(age_highest_benefit_counts)

print("\nRace: unpriveledged occurences - mean diffence")
print(race_mean_least_counts)
print("\nRace: higher benefit occurrences - disparate impact")
print(race_highest_benefit_counts)

print("\nTotal: Highest benefitting attribute - disparate impact")
print(total_dict_higher_benefit)
print("\nTotal: Most Unpriveledged attribute - mean difference")
print(total_dict_unpriveledged_mean)
# print((list(processed_data_race.keys())[list(processed_data_race.values()).index(least_priveledged)]))
# print((list(processed_data_race.keys())[list(processed_data_race.values()).index(compared_to)]))
# # print(worst_mean)
# print(least_priveledged_list)
# print(max(set(least_priveledged_list), key=least_priveledged_list.count))
# print("Most unpriveledged to Least")
# for i in range (5):
#     print(least_priveledged_list.count(i))
# for unpriv in least_priveledged_list:
#     print((list(processed_data_race.keys())[list(processed_data_race.values()).index(unpriv)]))

dataset = StandardDataset(df,
                            label_name=label,
                            # 0 represents low recidivism score
                            favorable_classes=[0],
                            protected_attribute_names=['race'],
                            # for priveleged class we will use our dict
                            privileged_classes=[[0]])
    # Again using our dict
privileged_groups = [{'race': 0}]
unprivileged_groups = [{'race': 4}]
metric_orig_train = BinaryLabelDatasetMetric(dataset,
                                                unprivileged_groups=unprivileged_groups,
                                                privileged_groups=privileged_groups)

mean_diff = metric_orig_train.mean_difference()
disparate_impact = metric_orig_train.disparate_impact()
print(mean_diff)

# from itertools import permutations
# all_combinations = list( permutations( range( 6 ), 2 ) )
# print(all_combinations)


#!/usr/bin/env python3
import cv2
import numpy as np
import dlib
import Facerecognize as fr

font=cv2.FONT_ITALIC
cap=cv2.VideoCapture(0)
detector=dlib.get_frontal_face_detector()
face_data,face_id,dic=fr.training_dataset_and_labels()
recognizer=cv2.face.LBPHFaceRecognizer_create()
recognizer.train(face_data,np.array(face_id))
while cap.isOpened():
    status,frame=cap.read()
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    faces=detector(gray)
    for face in faces:
        x1=face.left()
        y1=face.top()
        x2=face.right()
        y2=face.bottom()
        cv2.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
        value,confidence=recognizer.predict(gray[y1:y2,x1:x2])
        text=dic[str(value)]
        if confidence < 100:
            cv2.putText(frame,text,(x1,y1),font,2,(255,0,0),4)
        #print(value)
        #print(confidence)
    cv2.imshow("live",frame)
    if cv2.waitKey(30) & 0xff==ord('q'):
        break
cv2.destroyAllWindows()
cap.release()


import discord
from discord.ext import commands
import datetime
import nekos
import asyncio
import wikipedia
import pyowm
import os
from discord import utils
from discord.ext.commands import Bot
import urllib.parse
import re
import json
import io
import requests
import random
import time
from Cybernator import Paginator
import COVID19Py

Bot = commands.Bot(command_prefix='Lt!')
Bot.remove_command('help')
def postfix(num:int, end_1:str='год', end_2:str='года', end_3:str='лет'):
    num = num % 10 if num > 20 else num # Делим число на 10 и получаем то что осталось после деления, дальше проверка это больше чем 20 или нет, если больше то оставляем число не изменныс, а если меньше то заменяем число на остаток деления
    return end_1 if num == 1 else end_2 if 1 < num < 5 else end_3 # Тут уже просто прлверяем

@Bot.event
async def on_ready():
	print('Ну я тут')

@Bot.command()
async def help(ctx):
    embed1 = discord.Embed(title="Привет это все команды", description='Нажимай на стрелки и смотри команды')
    embed2 = discord.Embed(title="Эмоции", description='Lt!pat(Человек) Погладить \n Lt!hug (Человек) Обнять \n Lt!spal (Человек) ударить \n Lt!kiss (Человек) поцеловать')
    embed3 = discord.Embed(title="Игры", description='Lt!knb Сыграть в камень ножницы бумага \n Lt!wea (Город) Погода в городе \n Lt!wiki (запрос) Вики-Вики! \n Lt!ball (Запрос) спросить у шара \n Lt!gl (Запрос) гуглю за вас \n Lt!cat Котики! \n Lt!num_msg (Человек) посмотреть сколько у тебя сообшений' )
    embed4 = discord.Embed(title="Другое", description='Lt!ava (Человек) посмотреть аву себя или человека \n Lt!ran_ava Аниме ава \n Lt!profile Свой профиль или другое \n Lt!serverinfo Инфо о сервере \n Lt!covid (Название страны в коде из двух букв) Инфо о COVID-19 ')
    embeds = [embed1, embed2, embed3, embed4]
    message = await ctx.send(embed=embed1)
    page = Paginator(Bot, message, only=ctx.author, use_more=False, embeds=embeds)
    await page.start()

@Bot.event
async def on_ready():
    while True:
        await Bot.change_presence(activity= discord.Activity(name=' на сервер Лататы', type= discord.ActivityType.watching))
        await asyncio.sleep(10)
        await Bot.change_presence(activity= discord.Game("Команда помощи Lt!help"))
        await asyncio.sleep(10)

@Bot.command() # Декоратор команды
async def ava(ctx, member : discord.Member = None): # Название команды и аргументы
    user = ctx.message.author if member == None else member # Проверка аргуменат и переменная участника
    emb = discord.Embed( # Переменная ембеда
        title=f'Аватар пользователя {user}', # Заполняем заголовок
        description= f'[Ссылка на изображение]({user.avatar_url})', # Запонлняем описание
        color=user.color # Устанавливаем цвет
    )
    emb.set_image(url=user.avatar_url) # Устанавливаем картинку
    await ctx.send(embed=emb) # Отпрвака ембеда

@Bot.command()
async def knb(ctx):
    solutions = ['✂', '🧱', '📄']
    winner = "**НИЧЬЯ**"
    msg = await ctx.send('Выберите ход :')
    for r in solutions:
        await msg.add_reaction(r)
    try:
        react, user = await Bot.wait_for('reaction_add', timeout= 30.0, check= lambda react, user: user == ctx.author and react.message.channel == ctx.channel and react.emoji in solutions)
    except asyncio.TimeoutError:
        await ctx.send('Время вышло')
        await msg.delete()
        await ctx.message.delete()
    else:
        p1 = solutions.index(f'{react.emoji}')
        p2 = random.randint(0, 2)
        if p1 == 0 and p2 == 1 or p1 == 1 and p2 == 2 or p1 == 2 and p2 == 0:
            winner = f"{ctx.message.author.mention} ты **Проиграл**"
        elif p1 == 1 and p2 == 0 or p1 == 2 and p2 == 1 or p1 == 0 and p2 == 2:
            winner = f"{ctx.message.author.mention} ты **Выиграл**"
        await ctx.send(
            f"{ctx.message.author.mention} **=>** {solutions[p1]}\n"
            f"{Bot.user.mention} **=>** {solutions[p2]}\n"
            f"{winner}")
        await msg.delete()
        await ctx.message.delete()

@Bot.command() # Декоратор команды
async def ran_ava(ctx): # Название команды
    emb = discord.Embed(description= 'Вот подобраная Вам аватарка.') # Переменная ембеда и его описание
    emb.set_image(url=nekos.img('avatar')) # Тут мы с помощью новой библиотеки ищем картинку на тему аватар и ставим её в ембед
    await ctx.send(embed=emb)  # Отпрвака ембеда

@Bot.command() # Декоратор команды
async def kiss(ctx, member : discord.Member): # Название команды и аргумент
    if member == ctx.message.author: # Проверка кого упомянули
        await ctx.send('Вы не можете поцеловать сами себя.')
    else:
        emb = discord.Embed(description= f'{member.mention}, Вас поцеловал(а) {ctx.message.author.mention}.') # Переменная ембеда и описание
        emb.set_image(url=nekos.img('kiss')) # Ищем картинку и ставим её в ембед

        await ctx.send(embed=emb) # Отпрвака ембед
#work

@Bot.command() # Декоратор команды
async def hug(ctx, member : discord.Member): # Название команды и аргумент
    if member == ctx.message.author: # Проверка кого упомянули
        await ctx.send('Вы не можете обнять сами себя.')
    else:
        emb = discord.Embed(description= f'{member.mention}, Вас обнял(а) {ctx.message.author.mention}.') # Переменная ембеда и описание
        emb.set_image(url=nekos.img('hug')) # Ищем картинку и ставим её в ембед

        await ctx.send(embed=emb) # Отпрвака ембед
#work

@Bot.command() # Декоратор команды
async def slap(ctx, member : discord.Member): # Название команды и аргумент
    if member == ctx.message.author: # Проверка кого упомянули
        await ctx.send('Вы не можете ударить сами себя.')
    else:
        emb = discord.Embed(description= f'{member.mention}, Вас ударил(а) {ctx.message.author.mention}.') # Переменная ембеда и описание
        emb.set_image(url=nekos.img('slap')) # Ищем картинку и ставим её в ембед

        await ctx.send(embed=emb) # Отпрвака ембед
#work

@Bot.command() # Декоратор команды
async def pat(ctx, member : discord.Member): # Название команды и аргумент
    if member == ctx.message.author: # Проверка кого упомянули
        await ctx.send('Вы не можете погладить сами себя.')
    else:
        emb = discord.Embed(description= f'{member.mention}, Вас погладил(а) {ctx.message.author.mention}.') # Переменная ембеда и описание
        emb.set_image(url=nekos.img('pat')) # Ищем картинку и ставим её в ембед

        await ctx.send(embed=emb) # Отпрвака ембед

@Bot.command() # Декоратор команды
async def profile(ctx, userf: discord.Member = None): # Название команды и аргумент
    user = ctx.message.author if userf == None else userf # Проверка указан ли пользователь, если нет то заменяем автором команды
    status = user.status # Получаем статус

    if user.is_on_mobile() == True: stat = 'На телефоне' # Проверка статуса и указываем статус
    if status == discord.Status.online: stat = 'В сети' # Проверка статуса и указываем статус
    elif status == discord.Status.offline: stat = 'Не в сети' # Проверка статуса и указываем статус
    elif status == discord.Status.idle: stat = 'Не активен' # Проверка статуса и указываем статус
    elif status == discord.Status.dnd: stat = 'Не беспокоить' # Проверка статуса и указываем статус

    create_time = (datetime.datetime.today()-user.created_at).days # Узнаем кол-во дней в дискорде
    join_time = (datetime.datetime.today()-user.joined_at).days # Узнаем кол-во дней на сервере

    emb = discord.Embed(title='Профиль', colour= user.color) # Делаем ембед и устанавливаем цвет
    emb.add_field(name= 'Ник', value= user.display_name, inline= False) # Добавляем поле и заполняем
    emb.add_field(name= 'ID', value= user.id, inline= False) # Добавляем поле и заполняем

    if create_time == 0: # Проверка на число дней
        emb.add_field(name= 'Присоиденился к дискорду', value= f'{user.created_at.strftime("%d.%m.%Y")} ( Меньше дня )', inline= False) # Добавляем поле и заполняем дни в дискорде
    else:
        emb.add_field(name= 'Присоиденился к дискорду', value= f'{user.created_at.strftime("%d.%m.%Y")} ( {create_time} {postfix(create_time, "день", "дня", "дней")})', inline= False)# Добавляем поле и заполняем кол-во дней в дискорде и подбираем окончание
    if join_time == 0: # Проверка на число дней
        emb.add_field(name= 'Присоединился к серверу', value= f'{user.joined_at.strftime("%d.%m.%Y")} ( Меньше дня )', inline= False) # Добавляем поле и заполняем дни на сервере
    else:
        emb.add_field(name= 'Присоединился к серверу', value= f'{user.joined_at.strftime("%d.%m.%Y")} ( {join_time} {postfix(join_time, "день", "дня", "дней")} )', inline= False) # Добавляем поле и заполняем кол-во дней на сервере и подбираем окончание
    emb.add_field(name= 'Наивысшая роль', value= f"<@&{user.top_role.id}>", inline= False) # Добавляем поле и заполняем роль
    emb.add_field(name= 'Статус', value= stat, inline= False) # Добавляем поле и заполняем статус
    emb.set_thumbnail(url= user.avatar_url) # Устанавливаем картинку сбоку ( В душе хз как назвать xD )

    await ctx.send(embed=emb)

owm = pyowm.OWM('9963f6627710292d5125e8200fc5b2b5', language= 'ru')
@Bot.command()
async def wea(ctx, *, arg):
    observation = owm.weather_at_place(arg)
    w = observation.get_weather()
    prs = w.get_pressure()
    tmp = w.get_temperature('celsius')
    hmd = w.get_humidity()
    cld = w.get_clouds()
    wnd = w.get_wind()
    wnds = wnd.get('speed')
    wnds_str = ''
    rn = w.get_rain()
    emb = discord.Embed(
        title= 'Текущая погода'
    )
    emb.add_field(
        name= 'Температура',
        value= f'{tmp.get("temp")}°'
    )
    emb.add_field(
        name= 'Давление',
        value= str(prs.get('press')) + 'мм рт.ст.'
    )
    emb.add_field(
        name= 'Влажность',
        value= str(hmd) + '%'
    )
    emb.add_field(
        name= 'Облачность',
        value= str(cld) + '%'
    )
    if wnds < 0.2:wnds_str = 'Штиль'
    elif wnds < 1.5: wnds_str = 'Тихий'
    elif wnds < 3.3: wnds_str = 'Лёгкий'
    elif wnds < 5.4: wnds_str = 'Слабый'
    elif wnds < 7.9: wnds_str = 'Умеренный'
    elif wnds < 10.7: wnds_str = 'Свежий'
    elif wnds < 13.8: wnds_str = 'Сильный'
    elif wnds < 17.1: wnds_str = 'Крепкий'
    elif wnds < 20.7: wnds_str = 'Очень крепкий'
    elif wnds < 24.4: wnds_str = 'Шторм'
    elif wnds < 28.4: wnds_str = 'Сильный шторм'
    elif wnds < 32.6: wnds_str = 'Жестокий шторм'
    elif wnds > 32.6: wnds_str = 'Ураган'
    emb.add_field(
        name= 'Степень ветра',
        value= wnds_str
    )
    emb.add_field(
        name= 'Скорость ветра',
        value= str(wnds) + ' м/с'
    )
    emb.set_image(url= w.get_weather_icon_url())
    await ctx.send(embed=emb)

@Bot.command()
async def wiki(ctx, *, text):
    wikipedia.set_lang("ru")
    new_page = wikipedia.page(text)
    summ = wikipedia.summary(text)
    emb = discord.Embed(
        title= new_page.title,
        description= summ
    )
    emb.set_author(name= 'Больше информации тут! Кликай!', url= new_page.url, icon_url= 'https://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Wikipedia-logo-v2.svg/1200px-Wikipedia-logo-v2.svg.png')

    await ctx.send(embed=emb)

@Bot.command()
async def serverinfo(ctx):
    members = ctx.guild.members
    online = len(list(filter(lambda x: x.status == discord.Status.online, members)))
    offline = len(list(filter(lambda x: x.status == discord.Status.offline, members)))
    idle = len(list(filter(lambda x: x.status == discord.Status.idle, members)))
    dnd = len(list(filter(lambda x: x.status == discord.Status.dnd, members)))
    allchannels = len(ctx.guild.channels)
    allvoice = len(ctx.guild.voice_channels)
    alltext = len(ctx.guild.text_channels)
    allroles = len(ctx.guild.roles)
    embed = discord.Embed(title=f"{ctx.guild.name}", color=0xff0000, timestamp=ctx.message.created_at)
    embed.description=(
        f":timer: Сервер создали **{ctx.guild.created_at.strftime('%A, %b %#d %Y')}**\n\n"
        f":flag_white: Регион **{ctx.guild.region}\n\nГлава сервера **{ctx.guild.owner}**\n\n"
        f":tools: Ботов на сервере: **{len([m for m in members if m.bot])}**\n\n"
        f":green_circle: Онлайн: **{online}**\n\n"
        f":black_circle: Оффлайн: **{offline}**\n\n"
        f":yellow_circle: Отошли: **{idle}**\n\n"
        f":red_circle: Не трогать: **{dnd}**\n\n"
        f":shield: Уровень верификации: **{ctx.guild.verification_level}**\n\n"
        f":musical_keyboard: Всего каналов: **{allchannels}**\n\n"
        f":loud_sound: Голосовых каналов: **{allvoice}**\n\n"
        f":keyboard: Текстовых каналов: **{alltext}**\n\n"
        f":briefcase: Всего ролей: **{allroles}**\n\n"
        f":slight_smile: Людей на сервере **{ctx.guild.member_count}\n\n"
    )

    embed.set_thumbnail(url=ctx.guild.icon_url)
    embed.set_footer(text=f"ID: {ctx.guild.id}")
    embed.set_footer(text=f"ID Пользователя: {ctx.author.id}")
    await ctx.send(embed=embed)
@Bot.command()
async def ball(ctx, *, arg):

    message = ['Нет','Да','Возможно','Опредленно нет', 'Попробуй ещё раз' ,'Даже не думай!' ,'Никогда!'  ]
    s = random.choice( message )
    await ctx.send(embed = discord.Embed(description = f'Кот кидает шар :pouting_cat: :right_facing_fist: :8ball:  \n и шар говорит ** {s}**', color=0x0c0c0c))
    return
@Bot.command()
async def gl( ctx, *, question ):

    url = 'https://google.gik-team.com/?q='
    emb = discord.Embed( title = question, description = 'Вот чего я должен все за тебя делать?',
                         colour = discord.Color.green(), url = url + str(question).replace(' ', '+') )

    await ctx.send( embed = emb )

@Bot.command()
async def cat(ctx):
    meow = random.randint(1, 100000)
    embed = discord.Embed(title='**Вот тебе котик**' ,colour=0x00ffff)
    embed.set_image(url = f'https://cataas.com/cat?{meow}')
    await ctx.send(embed=embed)
@Bot.command()
async def covid(ctx, code: str= None):
    covid19 = COVID19Py.COVID19()
    if not code:
        location = covid19.getLocationByCountryCode("RU")[0]
    else:
        code = code.upper()
        with open('country_codes.json') as h_file:
            c_codes = json.load(h_file)
        if not code in c_codes:
            await ctx.send('Неверный код страны.')
            return
        location = covid19.getLocationByCountryCode(code)[0]
    date = location['last_updated'].split("T")
    time = date[1].split(".")

    embed = discord.Embed(
        title = f'Случаи заболевания COVID-19, {location["country"]}:',
        description = f'''Заболевших: {location['latest']['confirmed']}\nСмертей: {location['latest']['deaths']}\n\nНаселение: {location['country_population']}\nПоследние обновление: {date[0]} {time[0]}''',
        color=0x0c0c0c
    )

    await ctx.send(embed = embed)

class Messages:

    def __init__(self, Bot):
        self.Bot = Bot

    async def number_messages(self, member):
        n_messages = 0
        for guild in self.Bot.guilds:
            for channel in guild.text_channels:
                try:
                    async for message in channel.history(limit = None):
                        if message.author == member:
                            n_messages += 1
                except (discord.Forbidden, discord.HTTPException):
                    continue
        return n_messages

@Bot.command(name = "messages")
async def num_msg(ctx, member: discord.Member = None):
    user = ctx.message.author if (member == None) else member
    number = await Messages(Bot).number_messages(user)
    embed = discord.Embed(description = f":envelope: Количество сообщений на сервере от **{user.name}** — **{number}**!", color= 0x39d0d6)
    await ctx.send(embed = embed)

token = os.environ.get('BOT_TOKEN')

Bot.run(str(token))


import ui
from PIL import Image as ImageP
import io
import random

mainWindow = ui.View()
mainWindow.name = 'Image Conversion'
mainWindow.background_color = 'white'
mainWindow.width = 700 #ui.get_screen_size().width
mainWindow.height = 700 #ui.get_screen_size().height

def pil2ui(pil_img):
	with io.BytesIO() as buffer:
		pil_img.save(buffer, format='PNG')
		return ui.Image.from_data(buffer.getvalue())

path = "../Images/"
quarter = pil2ui(ImageP.open(path + "quarter.png").resize((70,70), ImageP.ANTIALIAS))
dime = pil2ui(ImageP.open(path + "dime.png").resize((50,50), ImageP.ANTIALIAS))
nickel = pil2ui(ImageP.open(path + "nickel.png").resize((60,60), ImageP.ANTIALIAS))
penny = pil2ui(ImageP.open(path + "penny.png").resize((55,55), ImageP.ANTIALIAS))

picture1 = ui.ImageView()
picture1.width = 70
picture1.height = 70
picture1.image = quarter

mainWindow.add_subview(picture1)

#mainWindow.present('fullscreen')
mainWindow.present('sheet')


from flask import Flask, flash, redirect,\
    url_for, session, g

from functools import wraps
from database import connect_db, query_db

from tigergrader.config import cfg

app = Flask(__name__)
app.config.update(cfg)

class GraderConfiguration():

    def __setitem__(self, k, v):
        g.db.execute('replace into configuration values (?, ?)', (k, v))
        g.db.commit()

    def __getitem__(self, k):
        v = query_db('select value from configuration where key == ?', [k])
        if v and "value" in v[0]:
            return v[0]["value"]

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if "username" not in session:
            flash('You need to log in')
            return redirect(url_for('login'))

        elif session["username"] == app.config["ADMIN_USERNAME"]:
            return redirect(url_for('admin'))

        return f(*args, **kwargs)
    return decorated_function

def get_active_modules():
    conf = GraderConfiguration()
    active_modules = conf["active_modules"]
    if active_modules:
        active_modules = active_modules.split(",")
    else:
        active_modules = []
    return active_modules

import tigergrader.admin
import tigergrader.student


import os
import tempfile
from functools import partial

from jinja2 import Environment, FunctionLoader
from babel.dates import format_date, format_datetime
from babel.numbers import format_currency

try:
    import weasyprint
except ImportError:
    pass

from genshi.template import MarkupTemplate
from trytond.tools import file_open
from trytond.pool import Pool
from trytond.transaction import Transaction
from trytond.report import Report, TranslateFactory, Translator
from executor import execute

class ReportWebkit(Report):
    render_method = "webkit"

    @classmethod
    def render(cls, report, report_context):
        pool = Pool()
        Translation = pool.get('ir.translation')
        Company = pool.get('company.company')

        # Convert to str as buffer from DB is not supported by StringIO
        report_content = (str(report.report_content) if report.report_content
                          else False)
        if not report_content:
            raise Exception('Error', 'Missing report file!')

        translate = TranslateFactory(cls.__name__, Transaction().language,
                                     Translation)
        report_context['setLang'] = lambda language: translate.set_language(
            language)

        company_id = Transaction().context.get('company')
        report_context['company'] = Company(company_id)

        return cls.render_template(report_content, report_context, translate)

    @classmethod
    def convert(cls, report, data):
        # Convert the report to PDF if the output format is PDF
        # Do not convert when report is generated in tests, as it takes
        # time to convert to PDF due to which tests run longer.
        # Pool.test is True when running tests.
        output_format = report.extension or report.template_extension

        if output_format == "html" or Pool.test:
            return output_format, data
        elif cls.render_method == "webkit":
            return output_format, cls.wkhtml_to_pdf(data)
        elif cls.render_method == "weasyprint":
            return output_format, cls.weasyprint(data)

    @classmethod
    def render_template_genshi(cls, template_string, localcontext, translator):
        """
        Legacy genshi rendered for backward compatibility. If your report is
        still dependent on genshi, implement the method render_template in
        your custom report and call this method with the same arguments and
        return the value instead.
        """
        report_template = MarkupTemplate(template_string)

        # Since Genshi >= 0.6, Translator requires a function type
        report_template.filters.insert(
            0, Translator(lambda text: translator(text))
        )

        stream = report_template.generate(**localcontext)

        return stream.render('xhtml').encode('utf-8')

    @classmethod
    def jinja_loader_func(cls, name):
        """
        Return the template from the module directories using the logic
        below:

        The name is expected to be in the format:

            <module_name>/path/to/template

        for example, if the account_reports module had a base template in
        its reports folder, then you should be able to use:

            {% extends 'account_reports/report/base.html' %}
        """
        module, path = name.split('/', 1)
        try:
            with file_open(os.path.join(module, path)) as f:
                return f.read()
        except IOError:
            return None

    @classmethod
    def get_jinja_filters(cls):
        """
        Returns filters that are made available in the template context.
        By default, the following filters are available:

        * dateformat: Formats a date using babel
        * datetimeformat: Formats a datetime using babel
        * currencyformat: Formats the given number as currency
        * modulepath: Returns the absolute path of a file inside a
            tryton-module (e.g. sale/sale.css)

        For additional arguments that can be passed to these filters,
        refer to the Babel `Documentation
        <http://babel.edgewall.org/wiki/Documentation>`_.
        """

        def module_path(name):
            module, path = name.split('/', 1)
            with file_open(os.path.join(module, path)) as f:
                return 'file://' + f.name

        return {
            'dateformat': partial(format_date, locale=Transaction().language),
            'datetimeformat': partial(
                format_datetime, locale=Transaction().language
            ),
            'currencyformat': partial(
                format_currency, locale=Transaction().language
            ),
            'modulepath': module_path
        }

    @classmethod
    def get_environment(cls):
        """
        Create and return a jinja environment to render templates

        Downstream modules can override this method to easily make changes
        to environment
        """
        env = Environment(loader=FunctionLoader(cls.jinja_loader_func))
        env.filters.update(cls.get_jinja_filters())
        return env

    @classmethod
    def render_template(cls, template_string, localcontext, translator):
        """
        Render the template using Jinja2
        """
        env = cls.get_environment()

        # Update header and footer in context
        company = localcontext['company']
        localcontext.update({
            'header': env.from_string(company.header_html or ''),
            'footer': env.from_string(company.footer_html or ''),
        })
        report_template = env.from_string(template_string.decode('utf-8'))
        return report_template.render(**localcontext).encode('utf-8')

    @classmethod
    def weasyprint(cls, data, options=None):
        return weasyprint.HTML(string=data).write_pdf()

    @classmethod
    def wkhtml_to_pdf(cls, data, options=None):
        """
        Call wkhtmltopdf to convert the html to pdf
        """
        with tempfile.NamedTemporaryFile(
                suffix='.html', prefix='trytond_', delete=False
        ) as source_file:
            file_name = source_file.name
            source_file.write(data)
            source_file.close()

            # Evaluate argument to run with subprocess
            args = 'wkhtmltopdf'
            # Add Global Options
            if options:
                for option, value in options.items():
                    args += ' --%s' % option
                    if value:
                        args += ' "%s"' % value

            # Add source file name and output file name
            args += ' %s %s.pdf' % (file_name, file_name)
            # Execute the command using executor
            execute(args)
            return open(file_name + '.pdf').read()


import uuid

from fastapi import status
from fastapi.testclient import TestClient
from httpx import Response

from internal.types import ScopedSession
from models.chat import Room

def test_POST_create_new_room_api_success_should_return_200(client: TestClient) -> None:
    response: Response = client.post("/rooms", json={"name": "New room", "creator_id": None})
    assert response.status_code == status.HTTP_200_OK

def test_GET_get_all_rooms_api_success_should_return_200(client: TestClient, db_session) -> None:
    for i in range(10):
        enc_key: str = uuid.uuid4().hex
        room = Room(name=f"Room {i}", slug=f"room-{i}", encryption_key=enc_key)
        db_session.add(room)
    db_session.commit()

    response: Response = client.get("/rooms")
    assert response.status_code == status.HTTP_200_OK
    assert len(response.json()) == 10

def test_POST_join_existing_room_api_success_should_return_200(
    client: TestClient, db_session: ScopedSession
) -> None:
    room = Room(name="Room", slug="room", encryption_key=uuid.uuid4().hex)
    db_session.add(room)
    db_session.commit()

    response: Response = client.post("/rooms/join", json={"name": room.name})
    assert response.status_code == status.HTTP_200_OK

def test_POST_join_existing_room_api_failed_should_return_404(
    client: TestClient, db_session: ScopedSession
) -> None:
    response: Response = client.post("/rooms/join", json={"name": "Some name"})
    assert response.status_code == status.HTTP_404_NOT_FOUND


import random
import cv2
import cvzone
import time
from cvzone.HandTrackingModule import HandDetector

cap = cv2.VideoCapture(0)

cap.set(3, 1080)
cap.set(4, 720)

detector=HandDetector(maxHands=1)

timer=0
stateResult=False
startGame=False
scores =[0,0]

while True:
    bg_main = cv2.imread('F:/rps/New folder/BG.png')

    success, img = cap.read()

    imgScaled = cv2.resize(img,(0,0),None,0.7222, 0.7222)
    imgScaled = imgScaled[:, 3:515]
    imgScaled= cv2.resize(imgScaled,(418,388))

    #finds Hands
    hands, img = detector.findHands(imgScaled)
    if startGame:
        if stateResult is False:
            timer = time.time()- initialTime
            cv2.putText(bg_main, str(int(timer)),(605,435),cv2.FONT_HERSHEY_PLAIN ,6,(255,0,255),4)

            if timer>3:
                stateResult = True
                timer= 0

                if hands:
                    playermove = None
                    hand = hands[0]
                    fingers = detector.fingersUp(hand)
                    if fingers == [0,0,0,0,0]:
                        playermove =1
                    if fingers == [1,1,1,1,1]:
                        playermove = 2
                    if fingers ==[0,1,1,0,0]:
                        playermove = 3

                    randomNumber = random.randint(1,3)
                    imgai= cv2.imread(f"F:/rps/New folder/data/{randomNumber}.png",cv2.IMREAD_UNCHANGED)
                    bg_main = cvzone.overlayPNG(bg_main, imgai ,(235,280))

                    # player Win
                    if (playermove == 1 and randomNumber == 3) or\
                            (playermove == 2 and randomNumber == 1) or\
                            (playermove == 3 and randomNumber == 2):
                        scores[1] +=1

                    # ai Win
                    if (playermove == 3 and randomNumber == 1) or\
                            (playermove == 1 and randomNumber == 2) or\
                            (playermove == 2 and randomNumber == 3):
                        scores[0] +=1

    bg_main[114:502,756:1174]= imgScaled
    print(imgScaled.shape)
    print(bg_main[114:502, 756:1174].shape)
    if stateResult:

        bg_main = cvzone.overlayPNG(bg_main, imgai ,(235,280))

        cv2.putText(bg_main, str(scores[0]),(410,215),cv2.FONT_HERSHEY_PLAIN ,4,(255,255,255),6)
        cv2.putText(bg_main, str(scores[1]),(1112,215),cv2.FONT_HERSHEY_PLAIN ,4,(255,255,255),6)

    #cv2.imshow("image" , img)
    cv2.imshow("BG" ,bg_main)

    #cv2.imshow("scaled", imgScaled)
    key=cv2.waitKey(1)
    if key == ord('s'):
        startGame = True
        initialTime = time.time()
        stateResult = False


import os
import sys
import torch
import torchvision.models
from torch import optim
from torch import nn
from tqdm import tqdm
from collections import Counter
from easydict import EasyDict as edict
from tools import CustomDataSet, Averagemeter, Speedometer, print_one_line, model_size_mb, ROCEstimator
from torch.utils.tensorboard import SummaryWriter
from torch.cuda import amp
import resnet

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# --------- CONFIG -----------

os.environ['TORCH_HOME'] = './weights'

cfg = edict()
cfg.train_in_fp16 = True
cfg.crop_size = (256, 256)
cfg.batch_size = 32
cfg.grad_accum_batches = 4
cfg.num_epochs = 32
cfg.num_classes = 2
cfg.augment = True
cfg.model_name = "effnet_v2_s"
cfg.pretrained = True
cfg.labels_smoothing = 0.05
cfg.max_batches_per_train_epoch = -1  # -1 - all
crop_format = '256x60x0.1' if cfg.crop_size[0] == 256 else '224x90x0.2'
local_path = f"/home/alex/Fastdata/deepfakes/sequence/{crop_format}"

for key in cfg:
    print(f" - {key}: {cfg[key]}")

# ---------- DNN --------------

if cfg.model_name == "effnet_v2_s":
    model = torchvision.models.efficientnet_v2_s()
    if cfg.pretrained:
        model.load_state_dict(torchvision.models.efficientnet_v2_s(
            weights=torchvision.models.EfficientNet_V2_S_Weights.IMAGENET1K_V1).state_dict())
    model.classifier[1] = nn.Linear(in_features=1280, out_features=cfg.num_classes, bias=True)
    max_lr = 0.001
elif cfg.model_name == "resnet18-ir":
    model = resnet.ResNetFaceGray(block=resnet.IRBlock, layers=[2, 2, 2, 2], use_se=True, attention=False,
                                  output_features=cfg.num_classes)
    max_lr = 0.01

model = model.to(device)
# model = nn.DataParallel(model)

print(f" - model size: {model_size_mb(model):.3f} MB")

# Loss and optimizer
loss_fn = nn.CrossEntropyLoss(label_smoothing=cfg.labels_smoothing)
optimizer = optim.Adam(model.parameters(), lr=max_lr)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', patience=2, factor=0.2, min_lr=0.0001,
                                                       verbose=True)

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

writer = SummaryWriter(filename_suffix=cfg.model_name)

print("Train dataset:")
train_dataset = CustomDataSet([
    f"{local_path}/roop",
    f"{local_path}/FaceForensics++",
    f"{local_path}/Celeb-DF-v2",
    f"{local_path}/dfdc",
], cfg.crop_size, do_aug=cfg.augment)
print(f"  {train_dataset.labels_names()}")
assert cfg.num_classes == len(train_dataset.labels_names())
lbls_count = dict(Counter(train_dataset.targets))
print(f"  {lbls_count}")
class_weights = list(1 / torch.Tensor(list(lbls_count.values())))
samples_weights = [class_weights[lbl] for lbl in train_dataset.targets]
sampler = torch.utils.data.WeightedRandomSampler(weights=samples_weights, num_samples=len(train_dataset),
                                                 replacement=True)
train_dataloader = torch.utils.data.DataLoader(train_dataset, sampler=sampler, batch_size=cfg.batch_size, num_workers=8)

alive_lbl = None
for key in train_dataset.labels_names():
    if train_dataset.labels_names()[key] == 'live':
        alive_lbl = key
        break

print("Test dataset:")
test_dataset = CustomDataSet([
    f"{local_path}/toloka"
], cfg.crop_size, do_aug=False)
print(f"  {test_dataset.labels_names()}")
print(f"  {dict(Counter(test_dataset.targets))}")
test_dataloader = torch.utils.data.DataLoader(test_dataset, batch_size=cfg.batch_size, shuffle=True, num_workers=6)

metrics = {
    'train': {'EER': float('inf'), 'loss': float('inf'), 'BPCER@0.01': float('inf')},
    'test': {'EER': float('inf'), 'loss': float('inf'), 'BPCER@0.01': float('inf')}
}

def update_metrics(mode, epoch, running_loss, roc_estimator):
    if not os.path.exists('./weights'):
        os.makedirs('./weights')
    writer.add_scalar(f"Loss/{mode}", running_loss, epoch)
    if running_loss < metrics[mode]['loss']:
        metrics[mode]['loss'] = running_loss
        print(f" - loss:  {running_loss:.5f} - improvement")
    else:
        print(f" - loss:  {running_loss:.5f}")
    eer, err_s = roc_estimator.estimate_eer()
    writer.add_scalar(f"EER/{mode}", eer, epoch)
    if eer < metrics[mode]['EER']:
        metrics[mode]['EER'] = eer
        if mode == 'test':
            torch.save(model, f"./weights/tmp_{cfg.model_name}@{crop_format}.pth")
        print(f" - EER: {eer:.4f} (score: {err_s:.3f}) - improvement")
    else:
        print(f" - EER: {eer:.4f} (score: {err_s:.3f})")
    print(f" - BPCER@0.1: {roc_estimator.estimate_bpcer(target_apcer=0.1):.4f}")
    bpcer01 = roc_estimator.estimate_bpcer(target_apcer=0.01)
    print(f" - BPCER@0.01: {bpcer01:.4f}")
    writer.add_scalar(f"BPCER@0.01/{mode}", bpcer01, epoch)
    print(f" - BPCER@0.001: {roc_estimator.estimate_bpcer(target_apcer=0.001):.4f}")

loss_avgm = Averagemeter()
ae_avgm = Averagemeter()
speedometer = Speedometer()
scaler = amp.grad_scaler.GradScaler()
train_roc_est = ROCEstimator()
test_roc_est = ROCEstimator()

def train(epoch, dataloader):
    print("TRAIN:")
    train_roc_est.reset()
    loss_avgm.reset()
    ae_avgm.reset()
    speedometer.reset()
    model.train()
    running_loss = 0
    true_positive_live = 0
    false_positive_live = 0
    true_negative_live = 0
    false_negative_live = 0
    samples_enrolled = 0
    for batch_idx, (inputs, labels) in enumerate(dataloader):
        if batch_idx == cfg.max_batches_per_train_epoch:
            break
        inputs = inputs.to(device)
        labels = labels.to(device)
        #u,c = torch.unique(labels, return_counts=True)
        #print(u,c)
        if cfg.train_in_fp16:
            with amp.autocast():
                outputs = model(inputs)
                loss = loss_fn(outputs, labels)
                loss = loss / cfg.grad_accum_batches
            scaler.scale(loss).backward()
            if (batch_idx + 1) % cfg.grad_accum_batches == 0 or batch_idx == (len(dataloader) - 1):
                scaler.unscale_(optimizer)
                torch.nn.utils.clip_grad_norm_(model.parameters(), 5)
                scaler.step(optimizer)
                scaler.update()
                optimizer.zero_grad()
        else:
            outputs = model(inputs)
            loss = loss_fn(outputs, labels)
            loss = loss / cfg.grad_accum_batches
            loss.backward()
            if (batch_idx + 1) % cfg.grad_accum_batches == 0 or batch_idx == (len(dataloader) - 1):
                torch.nn.utils.clip_grad_norm_(model.parameters(), 5)
                optimizer.step()
                optimizer.zero_grad()
        with torch.no_grad():
            scores = torch.nn.functional.softmax(outputs, dim=1)
            train_roc_est.update(live_scores=scores[labels == alive_lbl, alive_lbl].tolist(),
                                 attack_scores=scores[labels != alive_lbl, alive_lbl].tolist())
            running_loss += loss.item()
            _, predicted = outputs.max(1)
            _tp_live = (predicted[labels == alive_lbl] == alive_lbl).sum().item()
            true_positive_live += _tp_live
            _fp_live = (predicted[labels != alive_lbl] == alive_lbl).sum().item()
            false_positive_live += _fp_live
            _tn_live = (predicted[labels != alive_lbl] != alive_lbl).sum().item()
            true_negative_live += _tn_live
            _fn_live = (predicted[labels == alive_lbl] != alive_lbl).sum().item()
            false_negative_live += _fn_live
            loss_avgm.update(loss.item())
            ae_avgm.update((_fp_live / (_fp_live + _tn_live + 1E-6) + _fn_live / (_fn_live + _tp_live + 1E-6)) / 2)
            samples_enrolled += labels.size(0)
            speedometer.update(labels.size(0))
        print_one_line(
            f'Epoch {epoch} >> loss {loss_avgm.val:.3f}, AE {ae_avgm.val * 100:.2f}%, '
            f'{samples_enrolled}/{len(train_dataset)} ~ '
            f'{100 * samples_enrolled / len(train_dataset):.1f} % | '
            f'{speedometer.speed():.0f} samples / s '
        )
    update_metrics('train', epoch, running_loss / batch_idx, train_roc_est)

def test(epoch, dataloader):
    print("TEST:")
    test_roc_est.reset()
    model.eval()
    running_loss = 0
    with torch.no_grad():
        for batch_idx, (inputs, labels) in enumerate(tqdm(dataloader, file=sys.stdout)):
            inputs = inputs.to(device)
            labels = labels.to(device)
            outputs = model(inputs)
            loss = loss_fn(outputs, labels)
            running_loss += loss.item()
            _, predicted = outputs.max(1)
            scores = torch.nn.functional.softmax(outputs, dim=1)
            test_roc_est.update(live_scores=scores[labels == alive_lbl, alive_lbl].tolist(),
                                attack_scores=scores[labels != alive_lbl, alive_lbl].tolist())
    update_metrics('test', epoch, running_loss / len(dataloader), test_roc_est)
    scheduler.step(metrics['test']['EER'])
    print("\n")

for epoch in range(cfg.num_epochs):
    train(epoch, train_dataloader)
    test(epoch, test_dataloader)


# -*- coding: utf-8 -*-
__all__ = ('random_policy', 'stdin_policy', 'imitation_policy', 'inference_policy')

from utils.distribution import sample_by_mask
from utils.match_data import MatchData
from utils.tile_traits import str2tile, tile2str
from torch import nn
import numpy as np

class random_policy:
    def __init__(self):
        pass

    def __call__(self, obs):
        return sample_by_mask(obs[1])

class stdin_policy:
    def __init__(self, env):
        self.env = env

    def __call__(self, obs):
        assert self.env.verbose, "To use stdin policy, you must set env to be verbose."
        self.env.render()
        if obs[1].astype(np.uint8).sum() == 1:
            return obs[1].nonzero()[0]
        return input('> ')

class inference_policy:
    def __init__(self, match_lines):
        self.inferred = [[], [], [], []]
        self.match_lines = match_lines[6:-2]
        self.idx = 0
        self.match_id = match_lines[0].split()[-1]
        self.quan = int(match_lines[1].split()[-1])
        self.tile_wall = [[], [], [], []]
        self.fan_info = match_lines[-2]
        self.scores = list(map(int, match_lines[-1].split()[1:]))
        self.translate_fn = None
        self.last = None
        self.count = 0
        for i in range(4):
            self.tile_wall[i] = match_lines[2+i].split()[3:]
        no_ignored = []
        for idx, line in enumerate(self.match_lines):
            lst = line.split()
            if lst[2] == "Draw":
                self.tile_wall[int(lst[1])].append(lst[3])
            elif lst[2] == "Chi":
                lst[2] = "rChi"
            if 'Ignore' in lst:
                subset = [' '.join(lst[:lst.index('Ignore')])]
                while 'Ignore' in lst:
                    j = lst.index('Ignore')
                    subset.append(' '.join(lst[j+1:j+4] + [lst[3]]))
                    lst = lst[:j] + lst[j+4:]
                subset.sort(key=lambda x:int(x[len('Player x') - 1]))
                no_ignored += subset
            else:
                no_ignored.append(' '.join(lst))
        self.match_lines = no_ignored + ['PLAY 4 PASS PASS']
        for i in range(4):
            self.tile_wall[i] = self.tile_wall[i] + ['??'] * (34 - len(self.tile_wall[i]))
        assert sum([len(self.tile_wall[i]) == 34 for i in range(4)]) == 4

    def __call__(self, obs):
        players = obs[2].reshape(-1)
        mask = obs[1].reshape(players.shape[0], -1)
        self.count += (mask.sum(1) > 1).sum() * 4 * 9 * 145 / 1024 / 1024
        lst = self.match_lines[self.idx].split()
        while lst[2] == 'Draw':
            self.last = None
            self.idx += 1
            lst = self.match_lines[self.idx].split()
        next_player = int(lst[1])
        next_last_tile = lst[3] if lst[2] == 'Play' else None
        for idx, player in enumerate(players):
            if player == next_player:
                action = self.valid_to_do(mask[idx], lst[2], lst[3])
                if action is not None:
                    self.inferred[player].append(action)
                    self.idx += 1
                    lst = self.match_lines[self.idx].split()
                    next_player = int(lst[1])
                    continue
            self.inferred[player].append(self.translate_fn('PASS'))
        if next_last_tile:
            self.last = next_last_tile
        if players.shape[0] == 1:
            return self.inferred[players[0]][-1]
        return np.asarray([self.inferred[player][-1] for player in players])

    def valid_to_do(self, mask, action, tile):
        action = action.upper()
        if action in ['DRAW', 'PASS']:
            return None
        if action == 'CHI':
            if tile[1] <= '7':
                try_action = self.translate_fn(action + ' ' + tile[0] + chr(ord(tile[1]) + 1), self.last)
                if mask[try_action]:
                    return try_action
            if '2' <= tile[1] <= '8':
                try_action = self.translate_fn(action + ' ' + tile, self.last)
                if mask[try_action]:
                    return try_action
            if '3' <= tile[1]:
                try_action = self.translate_fn(action + ' ' + tile[0] + chr(ord(tile[1]) - 1), self.last)
                if mask[try_action]:
                    return try_action
            return None
        if action == 'RCHI':
            action = 'CHI'
        if action in ['CHI', 'BUGANG', 'PLAY']:
            action += ' ' + tile
        elif action == 'GANG' and self.last is None:
            action += ' ' + tile

        try_action = self.translate_fn(action, self.last)
        if not mask[try_action]:
            return None
        return try_action

    def as_match_data(self, id=0):
        tile_wall = sum(map(lambda x:list(reversed(x)), self.tile_wall), [])
        tile_wall = np.asarray([34 if tile == '??' else str2tile[tile] for tile in tile_wall], dtype=np.uint8)
        return MatchData(
            match_id=self.match_id,
            id=id,
            quan=self.quan,
            tile_wall=tile_wall,
            actions=list(map(lambda x:np.asarray(x, dtype=np.uint8), self.inferred)),
            final_info=self.fan_info,
            scores=np.asarray(self.scores, dtype=np.int32)
        )

class imitation_policy:
    def __init__(self, match):
        self.actions = np.zeros((4, max([match.actions[i].shape[0] for i in range(4)])), dtype=np.uint8)
        for i in range(4):
            self.actions[i, :match.actions[i].shape[0]] = match.actions[i]
        self.idxs = np.asarray([0] * 4)

    def __call__(self, obs):
        action = self.actions[obs[2], self.idxs[obs[2]]]
        self.idxs[obs[2]] += 1
        return action


# -*- coding: utf-8 -*-
"""
Chapter 02 script 02
"""

import numpy as np
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
#should see 2.0.0 or higher1.0
print(keras.__version__)
#should see 2.2.4 – tf

# the four different states of the XOR gate
training_data = np.array([[0,0],[0,1],[1,0],[1,1]], "float32")

# the four expected results in the same order
target_data = np.array([[0],[1],[1],[0]], "float32")

model = keras.models.Sequential()
model.add(keras.layers.Flatten(input_shape=[2]))
model.add(keras.layers.Dense(16, activation = 'sigmoid'))
model.add(keras.layers.Dense(16, activation = 'sigmoid'))
model.add(keras.layers.Dense(1, activation = 'sigmoid'))

model.summary()

model.layers

hidden1 = model.layers[1]
hidden1.name

model.get_layer('dense') is hidden1

weights, biases = hidden1.get_weights()
print(weights)
print(weights.shape)

weights.shape

biases

biases.shape

model.compile(loss='mean_squared_error', optimizer='adam', metrics=['binary_accuracy'])

history = model.fit(training_data, target_data, epochs=750, verbose=2)

import pandas as pd
import matplotlib.pyplot as plt

pd.DataFrame(history.history).plot(figsize=(8, 5))
plt.grid(True)
plt.gca().set_ylim(0, 1)
plt.show()

print(model.predict(training_data).round())


import uuid
import datetime
import json

from oscal_pydantic import (
    catalog,
    assessment_plan,
    assessment_results,
    complete,
    component,
    poam,
    profile,
    ssp,
)

cg_uuid=uuid.uuid5(uuid.NAMESPACE_DNS, 'cloud.gov')

ssp_au_01 = ssp.SpecificControlStatement(
    statement_id="au_01_smt",
    uuid = str(uuid.uuid5(cg_uuid, 'ssp_au_01')),
    remarks = "This is a remark"
)

print(ssp_au_01.json())


#!/usr/bin/python3
"""
 script that takes your GitHub credentials
"""

import requests
from sys import argv

def getgithub():
    url = "https://api.github.com/user"
    response = requests.get(url, auth=(argv[1], argv[2]))
    response = response.json()
    print(response.get("id"))

if __name__ == "__main__":
    getgithub()


# chat/consumers.py
import base64
import random

from asgiref.sync import async_to_sync
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.db import database_sync_to_async
import json
import time
from face_machine_client.models import PassInfo, ClientInfo, SyncInfo
from face_irobot_main.models import FaceStore

import string
import random

def create_client_id(randomlength=15):
    """
    生成client_id
    """
    random_str = ''
    base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
    length = len(base_str) - 1
    for i in range(randomlength):
        random_str += base_str[random.randint(0, length)]
    return random_str

class FaceWebsocket(AsyncWebsocketConsumer):
    """
    人脸后台websocket服务
    """

    def __init__(self, *args, **kwargs):
        # 初始化参数
        super().__init__(args, kwargs)
        self.client_user = None
        self.client_id = None
        self.company_id = None

    async def connect(self):
        # 初始化连接
        await self.accept()
        # 生成本次连接的client_id
        self.client_id = create_client_id()
        await self.send(text_data=json.dumps(
            {
                'type': 'init',
                'message': 'connected',
                'error_code': 0,
                'client_id': self.client_id  # 返还client_id,用于判断是否是本次连接
            }))

    async def disconnect(self, close_code):
        await self.send(text_data=json.dumps(
            {
                'message': 'disconnect'
            }))

    async def receive(self, text_data=None, bytes_data=None):
        # 处理websocket
        text_data_json = json.loads(text_data)
        message_type = text_data_json.get('type')
        # 登录进程
        if message_type == "authenticate":
            # 设备认证
            client_user = text_data_json.get('client_user')
            client_key = text_data_json.get('client_key')
            # 校验连接是否有效
            if text_data_json.get('client_id') == self.client_id:
                # 异步database
                results = await database_sync_to_async(auth_client_token)(client_user, client_key)
                # 登录成功
                if results[0] == 'ok':
                    self.company_id = results[2]
                    self.client_user = client_user
                    await self.send(text_data=json.dumps(
                        {
                            # 返还登录状态与设备参数
                            'message': 'auth_success',
                            'client_token': results[1],
                            'company_id': results[2]
                        }))
                    # 加入到相同企业通信通道中，用于主动下发参数
                    await self.channel_layer.group_add(
                        str(self.company_id),
                        self.channel_name
                    )
                    # 加入设备单独通信通道，用于点对点下发参数
                    await self.channel_layer.group_add(
                        str(client_user),
                        self.channel_name
                    )
                # 登录失败
                else:
                    await self.send(text_data=json.dumps(
                        {
                            'message': 'auth_fail'
                        }))
                    await self.close()
            else:
                await self.send(text_data=json.dumps(
                    {
                        'message': 'client_id_error'
                    }))
                await self.close()
        # 通行日志
        elif message_type == "pass_info":
            if self.company_id:
                info_detail = text_data_json.get("info_detail")
                task_id = text_data_json.get("task_id")
                update_results = await database_sync_to_async(update_pass_info)(info_detail_list=info_detail,
                                                                                task_id=task_id,
                                                                                client_user=self.client_user
                                                                                )
                await self.send(text_data=json.dumps(update_results))
            else:
                await self.send(text_data=json.dumps(
                    {
                        'message': 'need_auth'
                    }))
        # 同步人脸数据库
        elif message_type == "sync_database":
            if self.company_id:
                data_sync_type = text_data_json.get('sync_type')

                # 全同步模式
                if data_sync_type == "full_sync":
                    resp_data = await database_sync_to_async(get_face_store)(client_user=self.client_user,
                                                                             data_sync_type=data_sync_type,
                                                                             company_id=self.company_id)
                    await self.send(text_data=json.dumps(resp_data))

                # 检验同步模式,设备发送本地数据库人员列表进行数据量比对
                elif data_sync_type == "check_sync":
                    check_sync_list = text_data_json.get("check_sync_list")
                    resp_data = await database_sync_to_async(get_face_store)(client_user=self.client_user,
                                                                             data_sync_type=data_sync_type,
                                                                             company_id=self.company_id,
                                                                             check_sync_list=check_sync_list)
                    await self.send(text_data=json.dumps(resp_data))

                # 确认比对状态
                elif data_sync_type == "check_finished":
                    check_finished_list = text_data_json.get("check_finished_list")
                    resp_data = await database_sync_to_async(get_face_store)(client_user=self.client_user,
                                                                             data_sync_type=data_sync_type,
                                                                             company_id=self.company_id,
                                                                             check_sync_list=check_finished_list)
                    await self.send(text_data=json.dumps(resp_data))

                # 指定人员同步
                elif data_sync_type == "single_sync":
                    staff_id_list = text_data_json.get('staff_id_list')
                    resp_data = await database_sync_to_async(get_face_store)(data_sync_type=data_sync_type,
                                                                             staff_id_list=staff_id_list)
                    await self.send(text_data=json.dumps(resp_data))

            else:
                await self.send(text_data=json.dumps(
                    {
                        'message': 'need_auth'
                    }))
        # 同步状态
        elif message_type == "sync_info":
            if self.company_id:
                sync_state = text_data_json.get('sync_state')
                state = sync_state.get("state")
                face_data_len = sync_state.get("face_data_len")
                success_sync = sync_state.get("success_sync")
                # 判断同步类型
                if sync_state['type'] == "full_sync":
                    sync_type = "full_sync"
                elif sync_state['type'] == 'single_sync':
                    sync_type = "single"
                elif sync_state['type'] == 'check_sync':
                    sync_type = 'check_sync'
                    face_data_len = 0
                    success_sync = 0
                else:
                    sync_type = ''
                # 进行数据库同步
                await database_sync_to_async(update_sync_state)(sync_type=sync_type,
                                                                sync_state=state,
                                                                client_user=self.client_user,
                                                                face_data_len=face_data_len,
                                                                success_sync=success_sync)

            else:
                await self.send(text_data=json.dumps(
                    {
                        'message': 'need_auth'
                    }))

    # 向设备下发通知
    async def get_notification(self, event):
        message = event['message']
        # 异步下发
        await self.send(text_data=json.dumps({
            'message': message
        }))

def auth_client_token(client_user, client_key):
    """
    设备认证
    """
    # 在数据库中检索设备号与认证码
    auth = ClientInfo.objects.filter(client_user=client_user, client_key=client_key)
    # print('auth', auth)
    auth_state = auth.count()
    # print('auth_state', auth_state)
    if auth_state >= 1:
        # 生成设备唯一token
        auth.update(client_token=create_token())
        return 'ok', auth.get().client_token, auth.get().client_info.company_id
    else:
        return 'error', None

def create_token():
    """
    生成Token
    """
    token = 'time=' + str(int(time.time())) + 'num=' + str(random.randint(1000, 9999))
    token = base64.b64encode(token.encode('utf-8')).decode('utf-8')
    print('token', token)
    return token

def get_face_store(client_user, data_sync_type, company_id=None, staff_id_list=None, check_sync_list=None):
    """
    获取人脸数据库
    """
    if check_sync_list is None:
        check_sync_list = []
    resp_data = {
        'type': data_sync_type,
        'face_store': []
    }
    # 全同步方式
    if data_sync_type == "full_sync":
        full_store = FaceStore.objects.filter(company_id=company_id)
        for single_face in full_store:
            single_data = {'name': single_face.name,
                           'phone': single_face.phone,
                           'staff_id': single_face.staff_id,
                           'company_id': single_face.company_id,
                           'face_code': str(single_face.face_code)}
            resp_data['face_store'].append(single_data)
        print(len(resp_data['face_store']))
        return resp_data
    # 指定人员同步
    elif data_sync_type == "single_sync":
        for single_staff in staff_id_list:
            single_face = FaceStore.objects.filter(staff_id=single_staff).get()
            print('single_face', single_face)
            single_data = {'name': single_face.name,
                           'phone': single_face.phone,
                           'staff_id': single_face.staff_id,
                           'company_id': single_face.company_id,
                           'face_code': str(single_face.face_code)}
            resp_data['face_store'].append(single_data)
        print(len(resp_data['face_store']))
        return resp_data
    # 人员列表检查同步
    elif data_sync_type == "check_sync":
        local_staff_list = []
        for x in FaceStore.objects.filter(company_id=company_id):
            local_staff_list.append(x.staff_id)
        print('local_staff_list', local_staff_list)
        if check_sync_list:
            check_sync_list = check_sync_list
        else:
            check_sync_list = []
        update_list = []
        for check_staff in local_staff_list:
            if check_staff not in check_sync_list:
                update_list.append(check_staff)
        # 检测数据库改动(人脸更新,人脸删除)
        for k in FaceStore.objects.filter(company_id=company_id):
            local_client_list = eval(k.client_sync_list)
            print('local_client_list', local_client_list)
            if client_user in local_client_list:
                pass
            else:
                update_list.append(k.staff_id)
        print('update_list', update_list)
        resp_data['update_list'] = update_list
        return resp_data
    # 确认比对状态
    elif data_sync_type == "check_finished":
        try:
            for single_staff in check_sync_list:
                local_client_list = FaceStore.objects.filter(staff_id=single_staff).get().client_sync_list
                new_local_client_list = eval(local_client_list)
                # print('new_local_client_list', new_local_client_list)
                new_local_client_list.append(client_user)
                # print('new_local_client_list_return', new_local_client_list)
                # 设备号去重
                new_local_client_list = list(set(new_local_client_list))
                FaceStore.objects.filter(staff_id=single_staff).update(client_sync_list=str(new_local_client_list))
        except Exception as e:
            print(e)
        else:
            resp_data['update_state'] = "cool"
            return resp_data

def update_sync_state(sync_type, sync_state, client_user, face_data_len=0, success_sync=0):
    """
    更新同步状态
    """
    try:
        # 全同步
        if sync_type == "full_sync":
            SyncInfo.objects.create(sync_type=sync_type,
                                    sync_state=sync_state,
                                    client_user_id=client_user,
                                    face_data_len=face_data_len,
                                    success_sync=success_sync)
        # 人员列表检查同步
        elif sync_type == "check_sync":
            SyncInfo.objects.create(sync_type=sync_type,
                                    sync_state=sync_state,
                                    client_user_id=client_user)
    except Exception as e:
        print(e)
        return "sync_info_error"
    else:
        return 'ok'

def update_pass_info(info_detail_list, task_id, client_user):
    """
    更新通行日志
    """
    resp_data = {
        'task_id': task_id,
        'pass_update_state': ''
    }
    try:
        # 分条插入数据库中
        for single_info in info_detail_list:
            name = single_info.get('name')
            staff_id = single_info.get('staff_id')
            company_id = single_info.get('company_id')
            pass_time = single_info.get('pass_time')
            PassInfo.objects.create(name=name,
                                    staff_id=staff_id,
                                    company_id=company_id,
                                    pass_time=pass_time,
                                    client_user=client_user)
    except Exception as e:
        print(e)
        resp_data['pass_update_state'] = 'error'
        return resp_data
    else:
        resp_data['pass_update_state'] = 'success'
        return resp_data


from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import (
    QHBoxLayout,
    QListWidgetItem,
    QCheckBox,
    QGridLayout,
    QWidget,
    QComboBox,
    QListWidget,
)
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib
import matplotlib.pyplot as plt
from code_SRC.composantes import Time
from datetime import date

class Save_plot_app(QWidget):
    """Plot app that shows a plot chart of a specific leaderboard.

    #####################################################
    #           #                                       #
    #           #                                       #
    #           #                                       #
    #           #                                       #
    #           #               Plot                    #
    #   DATA    #               CHART                   #
    #   LIST    #                                       #
    #           #                                       #
    #           #                                       #
    #           #                                       #
    #           #                                       #
    #####################################################
    """

    def __init__(self, data):
        def list_widget() -> QListWidget:
            self.listwidget = QListWidget()
            self.listwidget.setFixedWidth(450)
            for rank, entry in enumerate(runs_times, start=1):
                delta = Time(entry - runs_times[0])
                string = f"{rank:4} {Time(entry)} {str(delta):>10} (-{(runs_times[0] - entry) / runs_times[0]:>6.2%})"

                one_line = QListWidgetItem(string)
                one_line.setFont(QFont("Lucida Sans Typewriter", 10))
                self.listwidget.addItem(one_line)
            # self.listwidget.clicked.connect(self.list_clicked)
            return self.listwidget

        def plot_widget() -> FigureCanvas:
            self.canvas = FigureCanvas(plt.Figure(tight_layout=True))
            matplotlib.rc("font", **{"weight": "normal", "size": 16})
            self.update_plot()
            return self.canvas

        runs_times, pb, WR_time = data

        super().__init__()
        self.data = runs_times
        self.pb = pb.seconds
        self.WR = WR_time
        self.setMinimumSize(1400, 600)
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        self.layout.addWidget(list_widget(), 0, 0)
        self.layout.addWidget(plot_widget(), 0, 1)

    def plot(self):
        self.canvas.figure.clf()
        self.ax = self.canvas.figure.subplots()

        self.ax.plot([x for x in range(1, len(self.data) + 1)], self.data)
        self.ax.axhline(self.WR, color="goldenrod")
        self.ax.set_yticks(self.ax.get_yticks())
        self.ax.set_yticklabels([str(Time(x)) for x in self.ax.get_yticks()])
        self.canvas.draw()

    def update_plot(self):
        self.plot()


import pandas as pd
from openpyxl.styles import PatternFill

def rgb_to_hex(rgb):
    return '%02x%02x%02x' % rgb

def darken(hex_code, shade):
    shade = shade/10
    #add something to convert shade number ie 9 actually equals 10% darker
    RGB = tuple(int(hex_code[i:i + 2], 16) for i in (0, 2, 4))
    r = RGB[0]
    g = RGB[1]
    b = RGB[2]

    # darken by 10%
    darken_R = int(round(r * shade))
    darken_G = int(round(g * shade))
    darken_B = int(round(b * shade))

    rgbTuple = (darken_R, darken_G, darken_B) #tuple of RGB values to convert to Hex

    return rgb_to_hex(rgbTuple)

def lighten(hex_code, shade):
    shade = shade/10
    RGB = tuple(int(hex_code[i:i + 2], 16) for i in (0, 2, 4))
    r = RGB[0]
    g = RGB[1]
    b = RGB[2]

    # lighten by 10%
    lighten_R = int(round(r + ((255 - r) * shade), 0))
    lighten_G = int(round(g + ((255 - g) * shade), 0))
    lighten_B = int(round(b + ((255 - b) * shade), 0))

    rgbTuple = (lighten_R, lighten_G, lighten_B) #tuple of RGB values to convert to Hex

    return rgb_to_hex(rgbTuple)

def create_lighten_df(colorList):
    empty_df_list = []
    df = pd.DataFrame(columns=['Original Color Hex', 'Change %', 'Color Hex', 'Direction', 'Color'])
    for item in colorList:
        for num in range(11):
            original_color = "#" + item
            change_percent = str(num) + '0%'
            color_hex = "#" + lighten(hex_code=item, shade=num)
            direction = 'Lighter'
            df = pd.concat([df,
                            pd.DataFrame.from_dict({'Original Color Hex': [original_color],
                                                    'Change %': [change_percent],
                                                    'Color Hex': [color_hex],
                                                    'Direction': [direction],
                                                     'Color' : ""})],
                           ignore_index=True)
    return df

def create_darken_df(colorList):
    empty_df_list = []
    df = pd.DataFrame(columns=['Original Color Hex', 'Change %', 'Color Hex', 'Direction', 'Color'])
    for item in colorList:
        for num in range(11):
            original_color = "#" + item
            change_percent = str(num) + '0%'
            color_hex = "#" + darken(hex_code=item, shade=num)
            direction = 'Darken'
            df = pd.concat([df,
                            pd.DataFrame.from_dict({'Original Color Hex': [original_color],
                                                    'Change %': [change_percent],
                                                    'Color Hex': [color_hex],
                                                    'Direction': [direction],
                                                     'Color' : ""})],
                           ignore_index=True)
        print(df)

    percDict = {
        '100%': "00%",
        '90%': "10%",
        '80%': "20%",
        '70%': "30%",
        '60%': "40%",
        '50%': "50%",
        '40%': "60%",
        '30%': "70%",
        '20%': "80%",
        '10%': "90%",
        '00%': "100%"
    }
    df['Change %'] = df['Change %'].apply(lambda x: percDict[x])
    df['Original Color Hex'] = df['Original Color Hex'].astype('category')
    df = df.sort_index(ascending=False).reset_index(drop=True)
    df['Sorting'] = df.index
    sorter = ['#' + str(x) for x in colorList]
    df['Original Color Hex'] = df['Original Color Hex'].cat.set_categories(sorter)
    df = df.sort_values(by=['Original Color Hex', 'Sorting']).drop(columns='Sorting')

    return df

###############start of work###################

# colorList is the list of hex codes that will be used to generate the report

colorList = ['CC0000', #red
             '000000', #black
             '4d4d4f', #dark gray
             '969697', #medium gray
             'dddddd', # light gray
             'f3f3f3', # ultra light gray
             'f58025', # ada compliant orange
             'fdb913', # ada compliant yellow
             '97ca3e', # ada compliant green
             '479cd6', # ada compliant blue
             '1d3c6d', # ada compliant navy
             '751c59' # ada compliant purple
             ]

lighten_df = create_lighten_df(colorList) #create a dataframe of lightened colors
darken_df = create_darken_df(colorList) # create a dataframe of darkened colors

with pd.ExcelWriter("ColorShadeReferenceWorkbook.xlsx", engine="openpyxl") as writer:
    # create the "Lighten" worksheet
    sheet_name = "Lighten"
    # Export DataFrame content
    lighten_df.to_excel(writer, sheet_name=sheet_name, index=False)
    # Set column width dimensions
    sheet = writer.sheets[sheet_name]# open sheet
    sheet.column_dimensions['A'].width = 18
    sheet.column_dimensions['B'].width = 10
    sheet.column_dimensions['C'].width = 10
    sheet.column_dimensions['D'].width = 10
    sheet.column_dimensions['E'].width = 9
    # Set background colors depending on cell values
    for cell, in sheet[f'E2:E{len(lighten_df) + 1}']: # Skip header row, process as many rows as there are DataFrames
        value = lighten_df["Color Hex"].iloc[cell.row - 2] #set color value to row['Color Hex'] value
        value = value.strip("#")
        cell.fill = PatternFill(start_color=value, end_color=value, fill_type='solid')

    #create the "Darken" worksheet
    sheet_name = "Darken"
    # Export DataFrame content
    darken_df.to_excel(writer, sheet_name=sheet_name, index=False)
    sheet = writer.sheets[sheet_name]
    # Set column width dimensions
    sheet.column_dimensions['A'].width = 18
    sheet.column_dimensions['B'].width = 10
    sheet.column_dimensions['C'].width = 10
    sheet.column_dimensions['D'].width = 10
    sheet.column_dimensions['E'].width = 9
    # Set background colors depending on cell values
    for cell, in sheet[f'E2:E{len(darken_df) + 1}']: # Skip header row, process as many rows as there are DataFrames
        value = darken_df["Color Hex"].iloc[cell.row - 2] #set color value to row['Color Hex'] value
        value = value.strip("#") #strip #
        cell.fill = PatternFill(start_color=value, end_color=value, fill_type='solid') #fill cell colid color


"""empty message

Revision ID: cadce5b06ea7
Revises: 5c4a7cc7d0e2
Create Date: 2020-03-25 11:23:09.141719

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = 'cadce5b06ea7'
down_revision = '5c4a7cc7d0e2'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index('ix_user_email', table_name='user')
    op.drop_index('ix_user_username', table_name='user')
    op.drop_table('user')
    op.drop_table('followers')
    op.drop_index('ix_post_timestamp', table_name='post')
    op.drop_table('post')
    op.add_column('label_data', sa.Column('is_labeled', sa.Integer(), nullable=True))
    op.create_index(op.f('ix_label_data_is_labeled'), 'label_data', ['is_labeled'], unique=False)
    op.drop_index('ix_label_data_is_labled', table_name='label_data')
    op.drop_column('label_data', 'is_labled')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('label_data', sa.Column('is_labled', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True))
    op.create_index('ix_label_data_is_labled', 'label_data', ['is_labled'], unique=False)
    op.drop_index(op.f('ix_label_data_is_labeled'), table_name='label_data')
    op.drop_column('label_data', 'is_labeled')
    op.create_table('post',
    sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
    sa.Column('body', mysql.VARCHAR(length=140), nullable=True),
    sa.Column('timestamp', mysql.DATETIME(), nullable=True),
    sa.Column('user_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.Column('language', mysql.VARCHAR(length=5), nullable=True),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], name='post_ibfk_1'),
    sa.PrimaryKeyConstraint('id'),
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    op.create_index('ix_post_timestamp', 'post', ['timestamp'], unique=False)
    op.create_table('followers',
    sa.Column('follower_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.Column('followed_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),
    sa.ForeignKeyConstraint(['followed_id'], ['user.id'], name='followers_ibfk_1'),
    sa.ForeignKeyConstraint(['follower_id'], ['user.id'], name='followers_ibfk_2'),
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    op.create_table('user',
    sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),
    sa.Column('username', mysql.VARCHAR(length=64), nullable=True),
    sa.Column('email', mysql.VARCHAR(length=120), nullable=True),
    sa.Column('password_hash', mysql.VARCHAR(length=128), nullable=True),
    sa.Column('about_me', mysql.VARCHAR(length=140), nullable=True),
    sa.Column('last_seen', mysql.DATETIME(), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    mysql_default_charset='utf8mb4',
    mysql_engine='InnoDB'
    )
    op.create_index('ix_user_username', 'user', ['username'], unique=True)
    op.create_index('ix_user_email', 'user', ['email'], unique=True)
    # ### end Alembic commands ###


from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    page = '
Powers of two
\n'
    for i in range(32):
        line = '2^{} = {}
\n'.format(i, 2**i)
        page += line
    return page

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


from .model import ImageEncoder, ImageDecoder128
import torch

class AE(torch.nn.Module):
    def __init__(self):
        super().__init__()

        self.encoder = ImageEncoder([1, 128, 256, 512, 1024, 2048, 4096], kernel_size=3, stride=2)
        self.decoder = ImageDecoder128()

        self.tanh = torch.nn.Tanh()
#         self.gelu = torch.nn.GELU()
        self.sigmoid = torch.nn.Sigmoid()

        self.range = 1024.0

    def forward(self, image):
        x = image / self.range
        x = self.encoder(x)
        # activate here if u want, tho prob bad idea :(
        x = self.tanh(x) #maybe not so bad idea, enforces latent space to be between -1 and 1
        x = self.decoder(x)

        x = self.sigmoid(x) * self.range

        return x


import requests
import unittest
import json
from Global_base import global_base,globa_phone
from parameterized import parameterized
from Global_base import login

class GetMainLinkBySublink(unittest.TestCase):
    """我的建议接口"""
    def setUp(self):
        self.url = global_base.DefTool.url(self, '/usercenter/user/suggest')

    def tearDown(self):
        print("请求地址为{}".format(self.url))
        print("请求参数为{}".format(json.dumps(self.params, indent=2, sort_keys=False, ensure_ascii=False)))
        print("请求结果为：{}".format(json.dumps(self.result, indent=2, sort_keys=False, ensure_ascii=False)))

    @parameterized.expand([
        (
        "建议提交", "A11", "", "867910035562539", "2.6.0", "15", "1003",
        "1", "sinaif", "ef70fb3178dccde19df9295a68aca0a3", "qsj")
    ])
    # @unittest.skip("pass")
    def test_getMainLinkBySublink(self, name, suggestcontent, contactway, deviceId, ver, verno,
                                  productId, deviceType, channelId, deviceToken, mjbname):
        """我的建议接口"""
        values = login.LoginByPassWord().login_by_password(int(globa_phone.phone()))
        token = values[1]
        header = {"token": token}
        pa = {"suggestcontent": suggestcontent, "contactway": contactway, "deviceId": deviceId, "ver": ver,
              "verno": verno, "productId": productId, "channelId": channelId, "deviceToken": deviceToken,
              "mjbname": mjbname, "deviceType": deviceType}
        self.params = global_base.DefTool().payload(**pa)
        self.result = requests.post(url=self.url, headers=header, data=self.params).json()
        self.assertEqual(self.result["msg"], "ok")
        self.assertEqual(self.result['code'], 200)

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


from __future__ import annotations

from dataclasses import dataclass

from pants.backend.codegen.soap.soap_subsystem import SoapSubsystem
from pants.backend.codegen.soap.target_types import WsdlSourcesGeneratorTarget
from pants.core.goals.tailor import (
    AllOwnedSources,
    PutativeTarget,
    PutativeTargets,
    PutativeTargetsRequest,
)
from pants.engine.fs import PathGlobs, Paths
from pants.engine.internals.selectors import Get
from pants.engine.rules import collect_rules, rule
from pants.engine.unions import UnionRule
from pants.util.dirutil import group_by_dir
from pants.util.logging import LogLevel

@dataclass(frozen=True)
class PutativeWsdlTargetsRequest(PutativeTargetsRequest):
    pass

@rule(level=LogLevel.DEBUG, desc="Determine candidate WSDL targets to create")
async def find_putative_targets(
    req: PutativeWsdlTargetsRequest,
    all_owned_sources: AllOwnedSources,
    soap_subsystem: SoapSubsystem,
) -> PutativeTargets:
    if not soap_subsystem.tailor:
        return PutativeTargets()

    all_wsdl_files = await Get(Paths, PathGlobs, req.path_globs("*.wsdl"))
    unowned_wsdl_files = set(all_wsdl_files.files) - set(all_owned_sources)
    pts = [
        PutativeTarget.for_target_type(
            WsdlSourcesGeneratorTarget,
            path=dirname,
            name=None,
            triggering_sources=sorted(filenames),
        )
        for dirname, filenames in group_by_dir(unowned_wsdl_files).items()
    ]
    return PutativeTargets(pts)

def rules():
    return [
        *collect_rules(),
        UnionRule(PutativeTargetsRequest, PutativeWsdlTargetsRequest),
    ]


import math
import time

from selenium import webdriver

def calc(x):
    return str(math.log(abs(12 * math.sin(int(x)))))

link = 'http://suninjuly.github.io/redirect_accept.html'
try:
     browser = webdriver.Chrome()
     browser.get(link)
     time.sleep(4)
     # browser.execute_script("document.getElementsByTagName('button')[0].classList.remove('trollface');")
     browser.find_element_by_css_selector('[type="submit"]').click()
     lst_win = browser.window_handles
     current_win = lst_win[1]
     browser.switch_to.window(current_win)
     print(browser.current_url)
     x = browser.find_element_by_id('input_value')
     print(x.text)

     browser.find_element_by_id('answer').send_keys(calc(x.text))
     browser.find_element_by_css_selector("[type='submit']").click()
     print(browser.switch_to.alert.text)
     time.sleep(2)
     browser.switch_to.alert.accept()

finally:
     browser.quit()