from deta import Deta
import numpy as np
import pandas as pd
import os
from dotenv import load_dotenv
import datetime
import streamlit as st

class datamodel:
	'''
	Dataclass model for getting and processing data for visualization
	'''
	def __init__(self, ):
		# load enviroment variables and extract database key
		# for localhost version
		#load_dotenv(".env")
		#os.getenv('key')
		# for streamlit app in live mode
		key = st.secrets['key']
		# create database object
		deta = Deta(key)
		# create databse connection
		self.db = deta.Base("YgoEloBase")
		# set default miesteschaft dictonary for saving and updating
		self.df_default_meisterschaft = pd.DataFrame(index=['Wanderpokal', 'Local', 'Fun Pokal'], columns=['Teilnahme', 'Top', 'Win']).fillna(0).to_dict()
		# filter parameter for deck building page
		amount_dict = {'Starter':0, 'Handtrap':0, 'Boardbreaker':0, 'Extender':0, 'Brick':0,
                       'Floodgate':0, 'Searcher':0, 'Monster':0, 'Zauber':0, 'Falle':0,
                       'Engine 1':0, 'Engine 2':0, 'Engine 3':0, 'Engine 4':0,'Draw':0,
					   'Feuer':0, 'Wasser':0, 'Licht':0, 'Finsternis':0, 'Erde':0, 'Wind':0,
					   'Divine':0}
		cardtyp_default = ['Starter', 'Extender', 'Handtrap', 'Boardbreaker', 'Brick']
		# load data to session state of get data from session state
		if "reload_flag" not in st.session_state:
			# get data from data base
			self.df, self.cols, self.hist_cols = self.__create_data_model()
			# setup session state
			st.session_state = {'owner':self.df['Owner'].unique(),
								'types_select':self.df['Type'].unique(),
								'tier':self.df['Tier'].unique(),
								'sorting':['Elo-Rating'],
								'tournament':'Alle',
								'deck_i':'',
								'deck':[],
								'reload_flag':False,
								'dataframe':self.df,
								'hist_cols':self.hist_cols,
								'cols':self.cols,
								'login':None,
								'card_amounts':amount_dict,
								'cardtyp_defaults':cardtyp_default
								}
		# if page get a forced reload after data base insertion reload data
		elif st.session_state['reload_flag']:
			# get data from data base
			self.df, self.cols, self.hist_cols = self.__create_data_model()
			# setup session state
			st.session_state = {'owner':self.df['Owner'].unique(),
								'types_select':self.df['Type'].unique(),
								'tier':self.df['Tier'].unique(),
								'sorting':['Elo-Rating'],
								'tournament':'Alle',
								'deck_i':'',
								'deck':[],
								'reload_flag':False,
								'dataframe':self.df,
								'hist_cols':self.hist_cols,
								'cols':self.cols,
								'login':None,
								'card_amounts':amount_dict,
								'cardtyp_defaults':cardtyp_default
								}
		# use already loaded data
		else:
			self.df = st.session_state['dataframe']
			self.hist_cols = st.session_state['hist_cols']
			self.cols = st.session_state['cols']

	def get(self):
		'''
		Method for returng the processed data from the databse to
		the dashbord.
		'''
		return self.df, self.cols, self.hist_cols

	def __create_data_model(self):
		'''
		Method for getting and preprocessing the yugioh data from the
		database
		:return df: dataframe with data
		:return cols: list with sorted columns of the dataframe
		'''
		# get data from data base
		df, hist_cols, save_cols = self.__get_all_data()
		hist_cols = self.__sort_hist_cols(hist_cols)
		df = self.__clean_data(df, hist_cols)
		return df, save_cols, hist_cols

	def __get_all_data(self, ):
		'''
		Method to get all data from the Database
		:use db: as detabase keys
		:return df_all: Dtaframe with all data like deck name, player and elo
		:return hist_cols: list of columns with historic elo data
		:return save_cols:list with all columns with further infos
		'''
		# get all data
		res = self.db.fetch()
		# create a dataframe
		df = pd.DataFrame(res.items)
		#df.to_csv('db.csv')
		# build a dataframe from the history
		tmp = df.loc[:, 'History'].to_list()
		hist_df = pd.DataFrame(tmp).fillna(0).astype(int)
		hist_cols = list(np.flip(hist_df.columns.to_list()))
		del df['History']
		save_cols = df.columns.to_numpy()
		save_cols = np.delete(save_cols, np.where(save_cols == 'key'))
		save_cols = np.delete(save_cols, np.where(save_cols == 'Meisterschaft'))
		# merge history dataframe and rest
		df_all = pd.merge(df, hist_df, right_index=True, left_index=True)

		return df_all, hist_cols, save_cols

	def update_elo_ratings(self, deck1, deck2, erg1, erg2, df_elo, hist_cols, save_cols):
		'''
		Method for updating Elo Rating and result stats after a new match
		'''
		# get index
		idx1 = int(df_elo[df_elo['Deck']==deck1].index.to_numpy())
		idx2 = int(df_elo[df_elo['Deck']==deck2].index.to_numpy())
		# update siege/niederlagen
		if not erg1 == erg2:
				df_elo.at[idx1, 'Siege'] += erg1
				df_elo.at[idx1, 'Niederlage'] += erg2

				df_elo.at[idx2, 'Siege'] += erg2
				df_elo.at[idx2, 'Niederlage'] += erg1
		else:
				df_elo.at[idx1, 'Remis'] +=erg1
				df_elo.at[idx2, 'Remis'] +=erg2
		# update matches
		df_elo.at[idx1, 'Matches'] += 1
		df_elo.at[idx2, 'Matches'] += 1
		# update dgp
		df_elo.at[idx1, 'dgp'] = (df_elo.at[idx1, 'dgp'] + 2*df_elo.at[idx2, 'Elo'])//3
		df_elo.at[idx2, 'dgp'] = (df_elo.at[idx2, 'dgp'] + 2*df_elo.at[idx1, 'Elo'])//3
		# update elo
		norm = erg1 + erg2
		score1 = erg1/norm
		score2 = erg2/norm

		# calculate winning probabilities
		# Formula from Chess ELO System
		alpha = 10**((df_elo.at[idx1, 'Elo']-df_elo.at[idx2, 'Elo'])/400)
		p1 = alpha/(alpha+1)
		p2 = 1-p1

		# Update ELO (Chess Formula)
		df_elo.at[idx1, 'Elo'] += int(32*(score1-p1))
		df_elo.at[idx2, 'Elo'] += int(32*(score2-p2))

		df_elo = self.__update_tiers(df_elo)

		key1 = df_elo.at[idx1, 'key']
		key2 = df_elo.at[idx2, 'key']

		self.__update_element(key1, df_elo.loc[idx1, :], save_cols, hist_cols)
		self.__update_element(key2, df_elo.loc[idx2, :], save_cols, hist_cols)

	def __update_tiers(self, df):
		'''
		Method for updating tier standing of a deck after a match
		'''
		Label = ['Kartenstapel','Fun', 'Good', 'Tier 2', 'Tier 1', 'Tier 0']
		NCl = len(Label)

		mean = int(df['Elo'].mean())
		std = float(df['Elo'].std())
		bins = np.array([0, mean-2*std, mean-std, mean, mean+std, mean+2*std, 10e6])
		liste =[]
		for jj in range(len(df)):
			for kk in range(NCl):
				if(df.at[jj, 'Elo']>=bins[kk] and df.at[jj, 'Elo']<=bins[kk+1]):
					liste.append(Label[kk])
					break

		df['Tier'] = liste
		return df

	def __update_element(self, unique_key, ds, save_cols, hist_cols):
		'''
		Method for updating an element in the database
		:param unique_key: key of the element to updated
		:param ds: data series with the data with sould be updated
		:param save_cols: list of columns with element infos
		:param hist_cols: list with column names to build elo history
		:param db: key to database
		:return: nothing
		'''
		# empty update dictionaries
		dict_update = {}
		dict_hist = {}
		# build historic elo dictionary
		for col in save_cols:
			dict_update[col] = str(ds[col])
		# build ifon dictionary
		for col in hist_cols:
			dict_hist[col] = str(ds[col])
		# include historic elo dictonary to info dictionary
		dict_update['History'] = dict_hist
		dict_update['Meisterschaft'] = ds['Meisterschaft']
		# update database
		self.db.put(dict_update, unique_key)

	def update_tournament(self, deck, tour, result, df, save_cols, hist_cols):
		'''
		Method for updating the tournament column of a spezific deck
		:param deck: name des decks to update
		:param tour: name of the tournament to update
		:param df: dataframe with all daa
		:param save_cols:list with columns with deck infos
		:param hist_cols: list with all columns with historic elo data
		:param db: key to database
		:return: nothing
		'''
		# find index of the deck to update
		idx = int(df[df['Deck']==deck].index.to_numpy())
		# increase choosen tournament
		df.at[idx, 'Meisterschaft']['Teilnahme'][tour] += 1
		if result == 'Win':
			df.at[idx, 'Meisterschaft']['Win'][tour] += 1
		if result == 'Top':
			df.at[idx, 'Meisterschaft']['Top'][tour] += 1
		# get key of the deck
		unique_key = df.at[idx, 'key']
		# update element in database
		self.__update_element(unique_key, df.loc[idx, :], save_cols, hist_cols)

	def update_stats(self, deck_choose, in_stats, modif_in, in_stats_type, new_type, df_elo, save_cols, hist_cols):
		'''
		Method for updating deck characteristica
		:param deck_choosen: name of the deck to update
		:param in_stats: info column to update
		:parm modif_in: value of the midification
		:param in_stats_type: update type of tthe choosen deck
		:param new_type: new_type to update
		:param df_elo: dataframe with all data
		:param save_cols: list with info columns
		:param hist_cols: columns with historic elo data
		:param db: key to database
		:return: nothing
		'''
		# find index of choosen deck to update
		idx = int(df_elo[df_elo['Deck']==deck_choose].index.to_numpy())
		# update characteristics if choosen
		if len(in_stats) > 0:
			df_elo.at[idx, in_stats] = modif_in
		# update deck type if choosen
		if len(in_stats_type)>0:
			df_elo.at[idx, in_stats_type] = new_type
		# get deck key and update the database
		unique_key = df_elo.at[idx, 'key']
		df_elo['Meisterschaft'] = df_elo['Meisterschaft'].astype(object)
		self.__update_element(unique_key, df_elo.loc[idx, :], save_cols, hist_cols)

	def update_history(self, df, hist_cols, save_cols):
		'''
		Method for increase the historic elo columns with the actual elo
		:param df: dataframe with all data
		:param hist_cols: list with historic elo columns
		:param save_cols: list with deck info columns
		:param db: key to database
		:return: nothing
		'''
		# get actual date and modify layout
		date = datetime.date.today()
		name = date.strftime("%m/%Y")
		# if actual date is not in historic columns include new column
		if not name in hist_cols:
			# include new column
			df[name] = df['Elo']
		# add new column to hist columns
		hist_cols += [name]
		# update all decks in database with new historic deck column
		for i in range(len(df)):
				unique_key = df.at[i, 'key']
				self.__update_element(unique_key, df.loc[i, :], save_cols, hist_cols)

	def insert_new_deck(self, deck, name, atk, contr, rec, cons, combo, resi, typ):
		'''
		Function for inserting a new deck to the database
		:param deck: name of the deck
		:param name: name of the player
		:param atk: attack rating
		:param contr: control rating
		:param rec: recovery rating
		:param cons: consistency rating
		:param combo: combo rating
		:param resi: resilience rating
		:param typ; type of the deck
		:param db: key to database
		:return: nothing
		'''
		# build info dictionary
		input_dict = {
		'Deck':deck,
		'Owner':name,
		'Tier':'Tier 2',
		'Attack':atk,
		'Control':contr,
		'Recovery':rec,
		'Consistensy':cons,
		'Combo':combo,
		'Resilience':resi,
		'Type':typ,
		'Wanderpokal':0,
		'Meisterschaft':self.df_default_meisterschaft,
		'Liga Pokal':0,
		'Fun Pokal':0,
		'Matches':0,
		'Siege':0,
		'Remis':0,
		'Niederlage':0,
		'dgp':0,
		'Elo':1500,
		'History':{}}
		# inserting the new deck
		self.db.put(input_dict)

	def __clean_data(self, df, hist_cols):
		'''
		Method for cleaning and calculation of new data with data from the database
		:param df: dataframe with data from the database
		:param hist_cols: list with all historic elo columns
		:return df: dataframe with data in right format and new calculated values
		'''
		# columns with integer values
		cols_to_int = ['Elo', 'dgp', 'Wanderpokal', 'Liga Pokal', 'Fun Pokal', 'Attack', 'Combo', 'Resilience', 'Recovery',
					'Consistensy', 'Control','Matches', 'Siege', 'Remis', 'Niederlage']+hist_cols
		# fill nulls and transform float data to interes
		for k in cols_to_int:
			df[k] = df[k].fillna(0).astype(float)
			df[k] = df[k].astype(int)
		# calculate last 3 month difference
		df['Letzte 3 Monate'] = 0
		idx = df[df[hist_cols[-1]]>0].index
		df.loc[idx, 'Letzte 3 Monate'] = df.loc[idx, 'Elo']-df.loc[idx, hist_cols[-1]]
		df['Letzte 3 Monate'] = df['Letzte 3 Monate'].astype(int)
		# calculate last 6 month difference
		df['Letzte 6 Monate'] = 0
		idx = df[df[hist_cols[-2]]>0].index
		df.loc[idx, 'Letzte 6 Monate'] = df.loc[idx, 'Elo']-df.loc[idx, hist_cols[-2]]
		df['Letzte 6 Monate'] = df['Letzte 6 Monate'].astype(int)
		# calculate last 12 month difference
		df['Letzte 12 Monate'] = 0
		idx = df[df[hist_cols[-4]]>0].index
		df.loc[idx, 'Letzte 12 Monate'] = df.loc[idx, 'Elo']-df.loc[idx, hist_cols[-4]]
		df['Letzte 12 Monate'] = df['Letzte 12 Monate'].astype(int)
		# calculate mean and std of the last year
		df['Mean 1 Year'] = np.nanmean(df[hist_cols[-5:-1]+['Elo']],1)
		df['Mean 1 Year'] = df['Mean 1 Year'].astype(int)
		df['Std. 1 Year'] = np.nanstd(df[hist_cols[-5:-1]+['Elo']],1)
		df['Std. 1 Year'] = df['Std. 1 Year'].astype(int)
		# calculate win rate
		df['Gewinnrate'] = 100*np.round(df['Siege']/(df['Siege']+df['Remis']+df['Niederlage']), 2)
		return df.fillna(0)

	def __sort_hist_cols(self, hist_cols):
		'''
		Method for sorting the list with historic elo in ascending order
		:param hist_cols: list with columns with historic elo
		:return out: sorted list with historic elo
		'''
		# empty list for transformed (to date) column names
		t = []
		# loop over historic columns
		for c in hist_cols:
			t.append(datetime.date(year = int(c[-4:]), month = int(c[:2]), day=1))
		# sort dates
		t = pd.Series(t).sort_values().reset_index(drop=True)
		# list for sorted cback transformed (to string) column names
		out = []
		# loop over all dates in ascending order
		for i in range(len(t)):
			out.append(t[i].strftime('%m/%Y'))
		return out


for i in range(int(input())):
    s=input()
    l=list(s)
    print(set(l))
    c=0
    for j in l:
        if j=="s":
            c+=1
        else:
            c+=1
    print(c)


import sys
input = sys.stdin.readline

N, K = map(int, input().split())
num = list(input())

k = K
stack = list()

#! 아래 주석은 내 코드 시간초과가 난다 왜??
# for i in num:

#     if not stack: # 처음에 스택에 아무것도 없을 때 실행
#         stack.append(i)
#         continue

#     for j in reversed(stack): # 넣을 수 보다 앞에 작은수가 있으면 빼는것이 핵심
#         if j < i and k > 0: # 스택안에 넣을 수 보다 작은 것이 있고 빼는 횟수를 초과하지 않았을 때
#             k -= 1
#             stack.pop()

#     stack.append(i)

for i in range(N):
    while k > 0 and stack and stack[-1] < num[i]:
        stack.pop()
        k -= 1
    stack.append(num[i])

print(''.join(stack[:N-K]))


def heapify(arr,n,i):
    largest = i # initialize largest as root
    l = 2*i + 1 # left child
    r = 2*i + 2 # right child

    # see if left child of root exists and is greater than root
    if l<n and arr[l]>arr[largest]:
        largest = l
    # see if right child of root exists and is greater than root
    if r<n and arr[r]>arr[largest]:
        largest = r
    # change root, if needed
    if largest != i:
        arr[i],arr[largest] = arr[largest],arr[i]

        # heapify the root
        heapify(arr,n,largest)

def heapsort(arr):
    n = len(arr)
    # Build a max heap
    for i in range(n//2-1,-1,-1):
        heapify(arr,n,i)
    # after that, one by one extract element
    for i in range(n-1,0,-1):
        arr[i],arr[0] = arr[0],arr[i] #swap... move current root to end
        heapify(arr,i,0) # call max heapify on the reduced heap

if __name__ == '__main__':
    #arr = [12,11,13,5,6,7]
    arr = [i for i in range(20,-1,-1)]
    print("Original array is : ",arr)
    heapsort(arr)
    n = len(arr)
    print("Sorted array is : ",arr)


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 28 17:32:38 2019

@author: Anne
"""

import numpy as np
import cv2
from matplotlib import pyplot as plt

def variance_of_laplacian(image):
	# compute the Laplacian of the image and then return the focus
	# measure, which is simply the variance of the Laplacian
	return cv2.Laplacian(image, cv2.CV_64F).var()

path="C:/Image_Aesthetic/3blue.png"

img = cv2.imread(path)

#cv2.imshow('image',img
plt.imshow(img)

#cv2.waitKey(0)

mask = np.zeros(img.shape[:2],np.uint8)

bgdModel = np.zeros((1,65),np.float64)

fgdModel = np.zeros((1,65),np.float64)
#from left, from top, from right, from bottom
rect = (100,75,200,150)

cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')

mask3 = np.where(~((mask==2)|(mask==0)),0,1).astype('uint8')

img1 = img*mask3[:,:,np.newaxis]

plt.imshow(img1)

gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
fm = variance_of_laplacian(gray)
text = "Not Blurry"

	# if the focus measure is less than the supplied threshold,
	# then the image should be considered "blurry"

print(fm)
if fm < 650:                            #THRESHOLD
	text = "Blurry\nAppealing"
else:
   text="Not Blurry\nNot Appealing"
print(text)

	# show the image
#cv2.putText(img1, "{}: {:.2f}".format(text, fm), (5, 30),
#	cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 255), 1)
#cv2.imshow("Image", img1)
key = cv2.waitKey(0)


import os
os.system('cls' or 'clear')
import math

#EX Aula4 Ex 5

num = float(input('Digite um número qualquer: '))

if num > 0:
    raiz = math.sqrt(num)
    print(f'A raiz quadrada de {num} é {raiz:.2f}')
else:
    print('Não há raiz quadrada de um número negativo em R!')


from django.db import models

from accounts.models import User

class Customer(models.Model):
    user = models.OneToOneField(User, related_name="customer", on_delete=models.CASCADE)
    profile_picture = models.URLField(blank=True)
    created = models.TimeField(auto_now_add=True)
    updated = models.TimeField(auto_now=True)

    class Meta:
        ordering = ('-created',)

    def __str__(self):
        return f'{self.user.full_name} for user {self.user.username}'


from datetime import datetime
from calendar import monthrange
from ntplib import NTPClient

def get_timestamp(ntp_client):
    ntp_response = ntp_client.request('ntp.shoa.cl')
    return datetime.fromtimestamp(ntp_response.tx_time)

def main():
    ntp_client = NTPClient()
    date_obj = get_timestamp(ntp_client)

    first_day = date_obj.replace(day=1).day
    days_in_month = monthrange(date_obj.year, date_obj.month)[1]

    month = [day for day in range(first_day, days_in_month)]
    print(month)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

#
#Valentines Day
#
# 20April20
#
import os
import csv
import fileinput

os.chdir("/home/pi/physrpi/coursefiles")

with open('classlist.csv') as csvfile:
	readcsv = csv.reader(csvfile, delimiter=',')
	for row in readcsv:
		FIRST = row[1]
		first=FIRST.title()
		LAST= row[0]
		last=LAST.title()
		print("Happy Valentine's Day,", first , last,"!")


class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left = 0
        right = len(height) - 1
        left_max = 0
        right_max = 0
        volume = 0
        while left < right:
            if height[left] < height[right]:
                if height[left] >= left_max:
                    left_max = height[left]
                else:
                    volume += left_max - height[left]
                left += 1
            else:
                if height[right] >= right_max:
                    right_max = height[right]
                else:
                    volume += right_max - height[right]
                right -= 1
        return volume

        # # Dynamic Programming
        # if len(height) == 0:
        #     return 0
        # left_max = [height[0]]
        # for i in range(1,len(height)):
        #     if height[i] > left_max[i-1]:
        #         left_max.append(height[i])
        #     else:
        #         left_max.append(left_max[i-1])
        # right_max = [0 for i in range(1,len(height))]+[height[-1]]
        # for i in range(-2,-len(height)-1,-1):
        #     if height[i] > right_max[i+1]:
        #         right_max[i] = height[i]
        #     else:
        #         right_max[i] = right_max[i+1]
        # volume = 0
        # for i in range(1,len(height)-1):
        #     volume += min(right_max[i],left_max[i]) - height[i]
        # return volume


from enum import Enum
from typing import TypeVar, Generic, List
from unittest import TestCase

from pydictable import GenericDictAble, ListField, EnumField, DictAble, ObjectField, DataValidationError

class TestGeneric(TestCase):
    def test_generic(self):
        class Gender(Enum):
            male = 'male'
            female = 'female'

        class City(Enum):
            Bangalore = 'Bangalore'
            Chennai = 'Chennai'

        T = TypeVar('T')

        class SelectField(GenericDictAble, Generic[T]):
            options: List[T] = None

            @staticmethod
            def inject(item: T):
                return {'options': ListField(EnumField(item))}

        class Profile(DictAble):
            gender: SelectField[Gender] = ObjectField(SelectField.make(Gender))

        class Lead(DictAble):
            city: SelectField[City] = ObjectField(SelectField.make(City))

        p = Profile(dict={'gender': {'options': ['male']}})
        l = Lead(dict={'city': {'options': ['Bangalore']}})
        self.assertEqual(p.gender.options[0], Gender.male)
        self.assertNotEqual(l.city.options[0], Gender.male)
        self.assertEqual(l.city.options[0], City.Bangalore)

        self.assertRaises(DataValidationError, lambda: Profile(dict={'gender': {'options': ['invalid']}}))


#!/usr/bin/env python
__coding__ = "utf-8"
__author__ = " Ng WaiMing "

from numpy import *
import matplotlib.pyplot as plt

set_printoptions(linewidth=10000)
# 1. 数组与标量之间的运算
arr = array([[1., 2., 3.], [4., 5., 6.]])
# print(arr)
# # 1.1 数组的矢量化:大小相等的数组之间的任何算数运算都会将运算应用到元素级别
# print(arr + arr)
# print(arr * arr)
# print(arr - arr)
# print(arr / arr)
#
# # 1.2 数组与标量的算数运算也会将标量传播(广播)到各个元素
# # 不同大小的数组之间的运算叫做广播
# print(arr ** 0.5)
#
# # 基本的索引和切片
# # 数组切片和列表切片最重要的区别在于,数组切片是原始数组的视图.这意味着数据不会被复制,视图熵的任何修改都会直接反映到源数组上
arr = arange(0, 100, 10)
# print(arr)
# print(arr[5])
# print(arr[5:8])
# arr1 = arr[5:8].copy()
# arr[5:8] = 120
# print(arr)
#
# # 1.3 高维数组上的索引
arr3d = empty((3, 4, 5))
# print(arr3d, '\n')
# # print(arr3d[2])
# # print(arr3d[2][2][1], '<==>', arr3d[2, 2, 1])
# # # 1.3.1 高维数组熵的切片
# print(arr3d[2:, 2:, 1][0, 0])
# 1.4 Boolean型索引
random.seed(0)
names = array(['Bob', 'Joe', 'Will', 'Bob', 'Will', 'Joe', 'Joe'])
data = random.randn(7, 4)
# print(data, '\n')
# print(data[names == 'Bob', 2:], '\n')
# print(data[-(names == 'Bob')], '\n\n', '<==>', '\n\n', data[names != 'Bob'], '\n')
# data[data < 0] = 0
# print(data)
#
# # 花式索引,即传入一组索引下标的数组
arr = zeros((8, 4))
for i in range(shape(arr)[0]):
    arr[i] = i
# print(arr, '\n')
# print(arr[[4, 3, 0, 6]])
# # 当一次传入多个索引时,写法稍有不同
arr = arange(32).reshape((8, 4))
# print(arr, '\n')
# print(arr[[4, 3, 0, 6]][:, [3, 1, 0, 2]])
#
# # 数组的转置和轴对换
arr = arange(15).reshape((3, 5))
# print(arr, '\n')
# print(arr.T, '\n')
# print(dot(arr.T, arr))
arr = arange(16).reshape((2, 2, 4))
# print(arr, '\n')
# print(arr.transpose((1, 0, 2)),'\n')
# print(arr.transpose())
# print(arr.swapaxes(1, 2))
arr = random.randn(7) * 5
# print(arr)
# # modf返回浮点数的整数部分数组以及浮点部分数组
# print(modf(arr))

# 利用数据进行数据处理
points = arange(-5, 5, 0.01)
xs, ys = meshgrid(points, points)
# print(xs, '\n\n', ys)
z = sqrt(xs ** 2 + ys ** 2)
# print(z)
# plt.imshow(z, cmap=plt.cm.gray)
# plt.colorbar()
# plt.title('Image plot of $\sqrt{x^2+y^2}$ for grid of value')
# plt.show()

# # 将条件逻辑表述为数组运算
xarr = array([1.1, 1.2, 1.3, 1.4, 1.5])
yarr = array([2.1, 2.2, 2.3, 2.4, 2.5])
cond = array([True, False, True, True, False])
result = where(cond, xarr, yarr)
# print(result)

arr = random.randn(4, 4)
# print(arr, '\n')
result = where(arr > 0, 2, -2)
# print(result)
cond1 = array([True, False, True, True, False])
cond2 = array([True, False, True, True, False])
result = where(cond1 & cond2, 0, where(cond1, 1, where(cond2, 2, 3)))
# print(result)
# print('<==>')
result = 1 * (cond1 - cond2) + 2 * (cond1 & -cond2) + 3 * -(cond1 | cond2)
# print(result)

# # 随机漫步
nsteps = 1000
draw = random.randint(0, 2, size=nsteps)
steps = where(draw > 0, 1, -1)
walk = steps.cumsum()
# print(walk.min())
# print(walk.max())
# print((abs(walk) >= 10).argmax())
# # 一次模仿多个随机漫步
nwalks = 5000
nsteps = 1000
draw = random.randint(0, 2, size=(nwalks, nsteps))
steps = where(draw > 0, 1, -1)
walk = steps.cumsum(1)
print(walk, '\n')
print(walk.max(), '\n')
print(walk.min(), '\n')
hits30 = (abs(walk) >= 30).any(1)
print(hits30, hits30.sum())
crossing_times = (abs(walk[hits30]) >= 30).argmax(1)
print(crossing_times, crossing_times.min(),crossing_times.mean())


import random
import csv

alphabet = "А Б В Г Д Е Ё Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ъ Ы Ь Э Ю Я " \
           "а б в г д е ё ж з и й к л м н о п р с т у ф х ц ч ш щ ъ ы ь э ю я"

class Table(object):

    # path - путь к месту сохранения таблицы в csv файл
    # table - словарь

    def __init__(self, path, table=""):
        self.path = path

        # Если в конструктор передали таблицу, то используем её

        if table != "":
            self.table = table

        # Если таблицу не передали, то создаёем таблицу шифрования, а именно
        # словарь, где key - буква алфавита, а value - его зашифрованная версия того же алфавита
        else:
            mixed_alphabet = alphabet.split().copy()
            random.shuffle(mixed_alphabet)

            self.table = dict(zip(alphabet.split(), mixed_alphabet))

    def print(self):
        print("Path = " + self.path)
        print("Table = " + str(self.table))

    # Шифрует по таблице файл из path_in и сохраняет зашифрованну версию в path_out

    def encrypt(self, path_in, path_out):
        with open(path_in, 'r', encoding="Windows 1251") as source:
            with open(path_out, 'w', encoding="Windows 1251") as encoded_file:
                for line in source:
                    for char in line:
                        if char in self.table:
                            encoded_char = self.table.get(char)
                            encoded_file.write(encoded_char)
                        else:
                            encoded_file.write(char)

    # Сохраняет таблицу в csv файл

    def save(self):
        with open(self.path, 'w', newline="", encoding='Windows 1251') as file:
            writer = csv.DictWriter(file, fieldnames=['decode', 'encode'], delimiter=";")
            writer.writeheader()

            for key, value in self.table.items():
                writer.writerow({'decode': key, 'encode': value})

    def get(self, key):
        return self.table.get(key)

    def get_by_value(self, needed_value):
        for key, value in self.table.items():
            if value == needed_value:
                return key

        return ""

    # Считает коэфициент совападения с переданной таблицей

    def number_of_coincidences(self, second):
        rating = 0
        for key, value in self.table.items():
            if second.get(key) == value:
                rating += 1
        return round(rating * 100 / len(alphabet.split()))

    # Расшифровывает по таблице файл из path_in и сохраняет расшифрованную версию в path_out

    def spell_out(self, path_in, path_out="decoded.txt"):
        with open(path_in, 'r', encoding="Windows 1251") as encodedFile:
            with open(path_out, 'w', encoding="Windows 1251") as decodedFile:
                for line in encodedFile:
                    for char in line:
                        value = self.get_by_value(char)
                        if value != "":
                            decodedFile.write(value)
                        else:
                            decodedFile.write(char)

    def add_element(self, key, value):
        self.table[key] = value
        self.save()

    # Редактирует таблицу, меняя местами элементы

    def change_by_key(self, a, b):
        c = self.get(a)
        d = self.get(b)

        self.table[a], self.table[b] = d, c

        self.save()


from StateMachine import States
from frm import handles as handles
from DataBase import db

handlePost =handles.post
handleAction = handles.action
handleString = handles.st

def contact_check(i,s,d,role=None):
    c= i.contact
    # check if user sent his own contact
    if i.from_user.id ==c.user_id:
        # database call
        if db.user_registered(c.phone_number):
            db.add_chat_id(c.phone_number,c.user_id)
            d['role']='student'
            if db.user_gmail(c.user_id):
                new_state = States.HOME
            else:
                new_state=States.GMAIL
        else:
            if d.get('role')=='applicant':
                # set applicant info
                d['phone'] = c.phone_number
                d['tgchat'] = c.user_id
                new_state =States.GMAIL
            else:
                new_state=States.NOT_ENROLLED
    else:
        new_state = States.TG_ERR
    return new_state, d

login_kb= [
    {'Send contact':handleAction(contact_check,react_to='contact'),
     'kwargs':{'request_contact':True}},
    {'<- Back':handleAction(States.START)}
]

def set_name(i,s,**d):
    d['name'] = i.from_user.first_name
    return d
def save_gmail(i,d,name=None,role=None):
    if role:
        if role=='applicant':
            # finish application process
            data = {'firstname':d['fname'],
                    'lastname':d['lname'],
                    'phone':d['phone'],
                    'tgchat':i.from_user.id,
                    'email':i.text
                   }
            db.save_new_user(data)
            # now send notification to admins
            new_state = States.USER_SAVED
        else:
            new_state = States.HOME
            print('saving gmail addr')
            db.save_gmail(i.text,i.from_user.id)
    else:
        new_state = States.ERROR
        db.save_gmail(i.text,i.from_user.id)
    return new_state,{'role':role}

UI={
    States.START:{'t':
        handleString(
      ("Hey %s, nice to meet you! "
       "I'm Aristotle, and I will help you at Fless. "
           "What would you like to do?"), 'name'),
          'b':[{'Log in as student':handleAction(States.TG)},

               {'Explore Fless':handleAction(States.ALL_COURSES)}
              ],
                'prepare':set_name,
      },
    States.TG:{'t':
               handleString(
          ("%s, please share your contact details "
           "so I can recognize you"),'name'),
               'kb':handles.obj(login_kb)
              },

    States.TG_ERR:{'t':
                   handleString(
          ("%s, I'm afraid this is not your contact. "
           "Please share your contact"),'name'),
               'kb':handles.obj(login_kb)
      },
    States.GMAIL:{'t':
          handleString("%s, Please share your email address",
              'name'),
                  'react':handleAction(save_gmail,react_to='text'),
                  'kb':'Remove'
      },

    States.NOT_ENROLLED:{'t':
         ("It seems that you are "
          "not currently enrolled in any of"
          "the courses. Would you like to enrol "
          "now? Or contact Fless if you think "
          "here was a mistake"),
                         'b':[
         {'List Fless courses':handleAction(States.ALL_COURSES)},
         {'Contact':handleAction(States.CONTACT)}
                         ]
                        }
}


# !/usr/bin/python
# -*- coding: utf-8 -*-

# author      : Tao Qitian
# email       : taoqt@mail2.sysu.edu.cn
# datetime    : 2021/4/12 21:48
# filename    : solution.py
# description : LC 226 翻转二叉树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        """ DFS 递归（后序遍历） """
        if not root:
            return root

        left = self.invertTree(root.left)
        right = self.invertTree(root.right)
        root.left, root.right = right, left
        return root

    def invertTreeDFSNonRecursive(self, root: TreeNode) -> TreeNode:
        """ DFS 非递归（前序遍历） """
        if not root:
            return root
        # 显式调用栈
        stack = [root]
        while stack:
            # 栈后进先出
            node = stack.pop()
            # 翻转左右子树
            left, right = node.left, node.right
            node.left, node.right = right, left
            # 右子节点先入栈
            if node.right:
                stack.append(node.right)
            # 左子节点后入栈，先出栈
            if node.left:
                stack.append(node.left)
        return root

    def invertTreeBFS(self, root: TreeNode) -> TreeNode:
        """ BFS（层序遍历） """
        if not root:
            return root
        # 引入队列
        queue = [root]
        while queue:
            # 队列先进先出
            node = queue.pop(0)
            # 翻转左右子树
            left, right = node.left, node.right
            node.left, node.right = right, left
            # 左子节点先入队
            if node.left:
                queue.append(node.left)
            # 右子节点后入队
            if node.right:
                queue.append(node.right)
        return root


import vcf
from Bio import SeqIO
# builtin libs
from typing import Any, List, Iterator, Tuple, NoReturn, Dict, Callable, Union, Sequence
from itertools import groupby, starmap, chain
import re
import argparse
import copy
import csv
import os
import sys
# for types
from Bio.SeqRecord import SeqRecord

def raise_(e: Exception) -> NoReturn:
   raise e

def sanitize(fn: str) -> str: return re.sub('[^\w\-_\. ]', '_', fn)
debug_log = sys.stderr.write

def write_subfiles(vcf_reader: vcf.parser.Reader, seqio_refs: dict, refid: str, vcf_grp: Iterator[Any]) -> Tuple[str, str, str, str]:
   refseq: Dict[str, SeqRecord] =  seqio_refs.get(refid) or raise_(ValueError(f"{refid} not found inreference fasta file"))
   basename = f"{sanitize(vcf_reader.filename)}.{sanitize(refid)}"
   vcf_name = f"{basename}.vcf"
   ref_name = f"{basename}.fasta"
   vartable_fn = f"{basename}.tsv"
   with open(vcf_name, 'w') as vcf_out_file:
       vcf_writer = vcf.Writer(vcf_out_file, vcf_reader)
       for r in vcf_grp: vcf_writer.write_record(r)
   with open(ref_name, 'w') as ref_out_file:
       SeqIO.write([refseq], ref_out_file, 'fasta')
   return (refid, ref_name, vcf_name, vartable_fn)

def make_args(in_args: argparse.Namespace, chrom: str, ref_fn: str, vcf_fn: str, vartable_out_fn: str) -> argparse.Namespace:
    ns = copy.deepcopy(in_args)
    ns.vcf_path = vcf_fn
    ns.ref = ref_fn
    ns.out = vartable_out_fn
    return ns
    #subprocess.check_call('vartable', '--bam', args.bam, '--vcf', vcf_fn, '--ref'
def chrom_(r: vcf.model._Record) -> str:
   return r.CHROM
# def read_tsv
DEBUG = False
COMPILE_SUB_RESULTS = True
def validate_file_overwrites(arg_sets: Sequence[argparse.Namespace]) -> Union[None,NoReturn]:
    for arg_set in arg_sets:
       problems=[]
       if (not arg_set.allow_overwrite) and os.path.exists(arg_set.out):
           problems.append( (f"--allow-overwrite option is off, but file {arg_set.out} exists! Stopping.") )
    if any(problems):
       raise ValueError("\n".join(problems))
    return None

def dispatch(args: argparse.Namespace, vartable_dispatch: Callable[[argparse.Namespace], int], writer: Callable) -> int:
    vcf_fn, ref_fn = args.vcf_path, args.ref
    with open(ref_fn) as ref_file, open(vcf_fn) as vcf_file:
        refs = { x.id : x for x in SeqIO.parse(ref_file, 'fasta') }
        vcf_reader = vcf_reader = vcf.Reader(vcf_file)
        vcf_groups = groupby(vcf_reader, key=chrom_) # lambda x: x.CHROM)
        chrom_files =  [write_subfiles(vcf_reader, refs, chrom, grp) for chrom, grp in vcf_groups]
    subrun_args = [make_args(args, *info) for info in chrom_files]
    validate_file_overwrites(subrun_args)
    for arg_set in subrun_args:
        debug_log(f"Running: {arg_set}")
        if not DEBUG:
            headers = vartable_dispatch(arg_set)
            # debug_log(result)
    if COMPILE_SUB_RESULTS:
        readers = [csv.DictReader(open(args.out), delimiter='\t') for args in subrun_args ]
        headers.sort()
        sub_headers = [ sorted(r.fieldnames) for r in readers ]
        assert all( (x == headers for x in sub_headers)  ), f"Header missmatch of {headers} of output csv files, see:\n {subrun_args}\n{sub_headers}"
        all_rows = chain.from_iterable( readers )
        writer(args.out, all_rows, headers)
    return 0


"""
This experiment shows an example of how the loader and preprocess modules can be used to load a dataset and
do some simple preprocessing
"""
from coburn.data import preprocess, loader
from showit import tile
from matplotlib import pyplot as plt

def main():
    # these samples will be automatically downloaded if they are not found locally
    dataset = loader.load(samples=['4bad52d5ef5f68e87523ba40aa870494a63c318da7ec7609e486e62f7f7a25e8',
                                   'a7e37600a431fa6d6023514df87cfc8bb5ec028fb6346a10c2ececc563cc5423',
                                   '70a6300a00dbac92be9238252ee2a75c86faf4729f3ef267688ab859eed1cc60'])

    # this transform will cause the dataset to find the mean image of a movie
    # anytime an item is requested from the dataset
    transform = preprocess.Mean()
    dataset.set_transform(transform)

    mean_images = list()
    for i in range(len(dataset)):
        sample = dataset[i]  # mean transform has already been applied!
        mean_images.append(sample)

    tile(mean_images)
    plt.show()


from tensorflow.keras.layers import Embedding
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense, Embedding

# Embedding 층은 적어도 두 개의 매개변수를 받습니다.
# 가능한 토큰의 개수(여기서는 1,000으로 단어 인덱스 최댓값 + 1입니다)와 임베딩 차원(여기서는 64)입니다
embedding_layer = Embedding(1000, 64)

from tensorflow.keras.datasets import imdb
from tensorflow.keras import preprocessing

# 특성으로 사용할 단어의 수
max_features = 10000
# 사용할 텍스트의 길이(가장 빈번한 max_features 개의 단어만 사용합니다)
maxlen = 20

# 정수 리스트로 데이터를 로드합니다.
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
""" 데이터 설명 : x_train
- 넘파이 array
- 25000개의 리스트로 이루어져 있음
- 즉 , 25000개의 샘플

    데이터 설명 : y_train
- 25000개의 데이터
- 2개의 카테고리 (0,1)중 하나로 라벨링
 """

# 리스트를 (samples, maxlen) 크기의 2D 정수 텐서로 변환합니다.
# maxlen만큼 zero_padding을 적용한다 (길이를 maxlen으로 통일)
x_train = preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = preprocessing.sequence.pad_sequences(x_test, maxlen=maxlen)

model = Sequential()
# 나중에 임베딩된 입력을 Flatten 층에서 펼치기 위해 Embedding 층에 input_length를 지정합니다.
model.add(Embedding(10000, 8, input_length=maxlen))
# Embedding 층의 출력 크기는 (samples, maxlen, 8)가 됩니다.

# 3D 임베딩 텐서를 (samples, maxlen * 8) 크기의 2D 텐서로 펼칩니다.
model.add(Flatten())

# 분류기를 추가합니다.
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.summary()

history = model.fit(x_train,
                    y_train,
                    epochs=10,
                    batch_size=32,
                    validation_split=0.2)


from enum import Enum

import pyxel

class UiState(Enum):
    IN_PLAY = 1,
    WIN = 2,
    LOSE = 3

class UI:

    def __init__(self) -> None:
        self.state = UiState.IN_PLAY

    def draw(self):
        pyxel.text(157, 54, "Press 'R' to restart.", pyxel.COLOR_YELLOW)

        if self.state == UiState.IN_PLAY:
            self._draw_in_play()
        elif self.state == UiState.WIN:
            self._draw_win()
        elif self.state == UiState.LOSE:
            self._draw_lose()

    def set_state(self, state: UiState):
        self.state = state

    def _draw_in_play(self):
        pyxel.text(80, 10, "Legend", pyxel.COLOR_YELLOW)

        pyxel.rect(80, 20, 4, 4, pyxel.COLOR_LIME)
        pyxel.text(88, 20, "Fuel", pyxel.COLOR_LIME)

        pyxel.rect(80, 30, 4, 4, pyxel.COLOR_YELLOW)
        pyxel.text(88, 30, "Treasure", pyxel.COLOR_YELLOW)

        pyxel.rect(80, 40, 4, 4, pyxel.COLOR_RED)
        pyxel.text(88, 40, "Bombs", pyxel.COLOR_RED)

        pyxel.rect(80, 50, 4, 4, pyxel.COLOR_LIGHT_BLUE)
        pyxel.text(88, 50, "Granite", pyxel.COLOR_LIGHT_BLUE)

    def _draw_win(self):
        pyxel.text(100, 30, "YOU\nWIN!", 10)

    def _draw_lose(self):
        pyxel.text(100, 30, "GAME\nOVER!", 10)


class Student:
    def __init__(self, name, gender, height):
        self.__name = name
        self.__gender = gender
        self.__height = height

    @property
    def name(self):
        return self.__name

    @property
    def gender(self):
        return self.__gender

    @property
    def height(self):
        return self.__height

    @height.setter
    def height(self, height):
        self.__height = height

    # 대부분의 객체를 출력할 때 많이 사용하는 함수 (객체의 표현을 지원)
    def __repr__(self):
        return "{0}(name: {1}, gender: {2}, height: {3})"\
            .format(self.__class__.__name__, self.name, self.gender, self.height)

s1 = Student("홍길동", "남", 155.5)

# __repr__() 을 통해 객체 출력
# __str__() 과 결과값 동일
print(s1)

students = [
    Student("최영인", "남", 170.5),
    Student("김용남", "여", 160.5),
    Student("최지선", "여", 160.5),
    Student("최지훈", "남", 174.5)
]

for student in students:
    print(student)

print("name 기준으로 오름차순 정렬")
for student in sorted(students, key=lambda x: x.name, reverse=False):
    print(student)

print("name 기준으로 내림차순 정렬")
for student in sorted(students, key=lambda x: x.name, reverse=True):
    print(student)

print("height 기준으로 오름차순 정렬")
for student in sorted(students, key=lambda x: x.height, reverse=False):
    print(student)

print("name 기준으로 내림차순 정렬")
for student in sorted(students, key=lambda x: x.height, reverse=True):
    print(student)


n, m = map(int, input().split())

grafico = []

for i in range(n):
  grafico.append(input())

def vizinho(vertice, cor):
  x, y = vertice
  lista = []
  if (x > 0) and (grafico[x - 1][y] == cor):
    lista.append((x - 1, y))

  if (y > 0) and (grafico[x][y - 1] == cor):
    lista.append((x, y - 1))

  if (x < n - 1) and (grafico[x + 1][y] == cor):
    lista.append((x + 1, y))

  if (y < m - 1) and (grafico[x][y + 1] == cor):
    lista.append((x, y + 1))

  return lista

def encontra_circulos(x, y):
  cor = grafico[x][y]
  visitado = set()
  pilha = [((x, y), None)]

  while pilha:
    v, no = pilha.pop()

    if v in visitado:
      return set()

    visitado.add(v)

    for u in vizinho(v, cor):

      if u != no:
        pilha.append((u, v))

  return visitado

visitado = set()

for i in range(n):
  for j in range(m):

    if (i, j) not in visitado:
      t = encontra_circulos(i, j)

      if not t:

        print('Yes')
        exit()

      visitado |= t

print('No')


import keras.backend as K
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt

def mean_predctn(y_true, y_pred):
    return K.mean(y_pred)

def load_dataset():
    dataset = h5py.File('datasets/train.h5', "r")
    train_set_x = np.array(dataset["train_set_x"][:]) # your train set features
    train_set_y = np.array(dataset["train_set_y"][:]) # your train set labels

    test_dataset = h5py.File('datasets/test.h5', "r")
    test_set_x = np.array(test_dataset["test_set_x"][:]) # your test set features
    test_set_y = np.array(test_dataset["test_set_y"][:]) # your test set labels

    classes = np.array(test_dataset["list_classes"][:]) # the list of classes

    train_set_y = train_set_y.reshape((1, train_set_y.shape[0]))
    test_set_y = test_set_y.reshape((1, test_set_y.shape[0]))

    return train_set_x, train_set_y, test_set_x, test_set_y, classes


#Queries @riz4d on telegram

import requests
import time
from pyrogram import *
import os
from Config import *
from faker import Faker

@bot.on_message(filters.command('start'))
async def start_message(client,message):
    await message.reply('__Hey '+str(message.from_user.first_name)+" ðŸ‘»__")
    await message.reply("__Hope you're fine.__")
    await message.reply("__can i show you AI generated photo of a fictional person,that person doesn't exist's in the real world__")
    await message.reply("__- sent /person\n- for bulk purpose /bulkpersons \n- For source code /source\n- connect developer /dev__")
@bot.on_message(filters.command('about'))
async def help_message(client,message):
    await message.reply("__I can generate different person's face each time the people being shown are not real. Instead, each of these fake yet strangely familiar faces are generated through the use of a special kind of artificial intelligence algorithm called generative adversarial networks (GANs)__")

@bot.on_message(filters.command('source'))
async def help_message(client,message):
    await message.reply('Here is the Git Repo\n[AI-Fakerbot](https://github.com/riz4d/AI-Fakerbot)')

@bot.on_message(filters.command('dev'))
async def help_message(client,message):
    await message.reply('@riz4d')

@bot.on_message(filters.command('person'))
async def gen(client,message):
     r = requests.get(url, allow_redirects=True)
     pic=r.content
     file=open(f"person.png", "wb").write(pic)
     fake=Faker()
     name=fake.profile()['name']
     job=fake.profile()['job']
     residence=fake.profile()['residence']
     ssn=fake.profile()['ssn']
     company=fake.profile()['company']
     address=fake.profile()['address']
     blood=fake.profile()['blood_group']
     mail=fake.profile()['mail']
     pc = fake.chrome()
     cc = fake.credit_card_full()
     ip = fake.ipv4_private()
     android = fake.android_platform_token()
     fake_res='__Name__ : `'+name+'`\n\n__Job__ : `'+job+'`\n\n__Residence__ : `'+residence+'`\n\n__SSN__ : `'+ssn+'`\n\n__Blood Group__ : `'+blood+'`\n\n__Company__ : `'+company+'`\n\n__Address__ : `'+address+'`\n\n__Mail__ : `'+mail+'`\n\n__PC__ : `'+pc+'`\n\n__Credit Card__ : `'+cc+'`__IPV4__ : `'+ip+'`\n\n__PlatForm__ : `'+android+'`'
     await message.reply_photo('person.png',caption=fake_res)
     os.remove('person.png')
@bot.on_message(filters.command('bulkpersons'))
async def bulkgen(client,message):
    await message.reply('__How many fake persons you want??__')
    if message.text=='/bulkpersons':
        @bot.on_message(filters.text)
        async def bulkgen(client,messsage):
            howmany=messsage.text
            picno=0
            for i in range(int(howmany)):
                fake=Faker()
                name=fake.profile()['name']
                job=fake.profile()['job']
                residence=fake.profile()['residence']
                ssn=fake.profile()['ssn']
                company=fake.profile()['company']
                address=fake.profile()['address']
                blood=fake.profile()['blood_group']
                mail=fake.profile()['mail']
                pc = fake.chrome()
                cc = fake.credit_card_full()
                ip = fake.ipv4_private()
                android = fake.android_platform_token()
                fake_res='__Name__ : `'+name+'`\n\n__Job__ : `'+job+'`\n\n__Residence__ : `'+residence+'`\n\n__SSN__ : `'+ssn+'`\n\n__Blood Group__ : `'+blood+'`\n\n__Company__ : `'+company+'`\n\n__Address__ : `'+address+'`\n\n__Mail__ : `'+mail+'`\n\n__PC__ : `'+pc+'`\n\n__Credit Card__ : `'+cc+'`__IPV4__ : `'+ip+'`\n\n__PlatForm__ : `'+android+'`'
                picno+=1
                await messsage.reply('`uploading` '+str(picno)+'/'+str(howmany))
                r = requests.get(url, allow_redirects=True)
                pic=r.content
                file=open(f"pic.png", "wb").write(pic)
                await messsage.reply_photo('pic.png',caption=fake_res)
                os.remove('pic.png')
                time.sleep(2)

bot.run()
#Queries @riz4d on telegram


#!/usr/bin/env python
#coding=utf8
import os,sys,json,time,argparse
from utils import *
from global_vars import *
from models.seq_rnn_model import SeqRNNModel
from models.seq_rnn_crf_model import SeqRNNCRFModel
from models.focus_model import FocusModel
from models.decoder_and_eval import *
from models.loss_function import *
import torch
from torch.autograd import Variable
import gpu_selection
from collections import defaultdict

if __name__=='__main__':

    parser=argparse.ArgumentParser()
    parser.add_argument('-d','--domain',choices=['SpeechLab','AISpeech'],default='SpeechLab')
    parser.add_argument('-m','--model',default='RNN',help='choose model from rnn,rnn+crf,focus models')
    parser.add_argument('--cuda',action='store_true')
    parser.add_argument('--beos',action='store_true')
    parser.add_argument('-idpt','--input_dropout',type=float,default=0.2)
    parser.add_argument('-odpt','--dropout',type=float,default=0.5)
    parser.add_argument('--use_word_embeddings',action='store_true')
    parser.add_argument('--bidirection',action='store_true')
    parser.add_argument('-l','--layers',type=int,default=1)
    parser.add_argument('-c','--cell',choices=['LSTM','GRU'],default='LSTM')
    parser.add_argument('-e','--embedding_size',type=int,default=256,help='use an additional embedding layer before network input')
    parser.add_argument('-hs','--hidden_size',type=int,default=512)
    parser.add_argument('-bs','--batch_size',type=int,default=64,help='size of mini-batches')
    parser.add_argument('-voc','--voc_ratio',type=float,default=0.939)
    parser.add_argument('--post_attention',action='store_true')
    parser.add_argument('--annotation',action='store_true',help='eval data whether has annotation')
    args=parser.parse_args()
    args.model=args.model.lower()
    if args.model not in ['rnn','rnn+crf','seq2seq','attention','focus']:
        raise ValueError('[Error]: unknown model name',args.model)
    if args.model in ['seq2seq','attention','focus']:
        args.beos=True
        args.seq2seq=True
    else:
        args.seq2seq=False
    if args.cuda:
        deviceId, gpu_name, valid_gpus = gpu_selection.auto_select_gpu()
        print("Valid GPU list: %s ; GPU %d (%s) is auto selected." % (valid_gpus, deviceId, gpu_name))
        torch.cuda.set_device(deviceId)
    args.cuda=args.cuda and torch.cuda.is_available()
    if args.cuda:
        print('We will use cuda ... ...')
        torch.cuda.manual_seed(1)
    torch.manual_seed(1)

    start_time=time.time()
    # load vocabulary and tagset
    print('Load vocabulary dict and slots,tags dict:...')
    voc_dict,reverse_voc_dict=load_vocabulary(PATH_TO_VOC[args.domain],args.voc_ratio,args.beos)
    slot_tag_dict,reverse_slot_tag_dict=load_tagset(PATH_TO_SLOT_TAGSET[args.domain],seq2seq=args.seq2seq)
    sentence_tag_dict,reverse_sentence_tag_dict=load_tagset(PATH_TO_SENTENCE_TAGSET[args.domain])
    # prepare eval data
    evalset=load_evaldata(PATH_TO_EVAL_DATA[args.domain],voc_dict,args.beos,PATH_TO_STOP_PATTERN[args.domain],annotation=args.annotation)
    dataloader=Dataset(evalset,1,0) # 对测试数据进行封装
    print('Size of eval data is',len(evalset))
    print('Size of vocabulary is',len(voc_dict))
    pad_num=len(voc_dict)
    ignore_slot_index=-100 if args.model in ['rnn','rnn+crf'] else len(slot_tag_dict)
    print('Prepare resource time:',(time.time()-start_time))
    if args.model=='rnn':
        eval_net=SeqRNNModel(args,len(voc_dict),len(slot_tag_dict),len(sentence_tag_dict))
    elif args.model=='rnn+crf':
        eval_net=SeqRNNCRFModel(args,len(voc_dict),len(slot_tag_dict),len(sentence_tag_dict))
    elif args.model in ['seq2seq','attention','focus']:
        eval_net=FocusModel(args,len(voc_dict),len(slot_tag_dict),len(sentence_tag_dict))
    eval_net.load_module(os.path.join(PATH_TO_MODELS[args.domain],'train.'+args.model+'.'+args.cell+'.'+str(args.embedding_size)+'.'+str(args.hidden_size)+'.model'))
    if args.cuda:
        eval_net.cuda()

    eval_net.eval()
    file_path=open(os.path.join(PATH_TO_MODELS[args.domain],'eval.result'),'w')
    if args.annotation:
        error_path=open(os.path.join(PATH_TO_MODELS[args.domain],'eval.error'),'w')
        slot_dict=defaultdict(lambda :{'T':0,'P':0,'TP':0,'FP':0})
        sentence_dict=defaultdict(lambda :{'T':0,'P':0,'TP':0,'FP':0})
        whole_dict={'Num':0,'TP':0,'SubSet':0,'SuperSet':0}
        char_path=os.path.join(PATH_TO_MODELS[args.domain],'eval.char.'+args.model.lower()+'.'+args.cell+'.'+str(args.embedding_size)+'.'+str(args.hidden_size)+'.score')
        slot_path=os.path.join(PATH_TO_MODELS[args.domain],'eval.slot.'+args.model.lower()+'.'+args.cell+'.'+str(args.embedding_size)+'.'+str(args.hidden_size)+'.score')
    domain_ontology=Ontology(PATH_TO_ONTOLOGY[args.domain])
    post_processor=PostProcessor(PATH_TO_CONSTRAINT_MAPPINGS[args.domain],PATH_TO_POST_PROCESS_DIR[args.domain],domain_ontology)
    for step,(data_sample,eval_length_list) in enumerate(dataloader.get_mini_batches(batch_size=args.batch_size,data=dataloader.data,pad_num=pad_num,ignore_slot_index=ignore_slot_index,shuffle=False)):
        if args.annotation:
            eval_raw_data,padded_eval_data,ref_semantics=data_sample
        else:
            eval_raw_data,padded_eval_data=data_sample
        if args.cuda:
            padded_eval_data=padded_eval_data.cuda()
        if args.model=='rnn':
            eval_slot_scores,eval_sentence_scores=eval_net(padded_eval_data,eval_length_list)
            # kbest decoder
            # eval_slot_result,eval_sentence_result=kbest_decoder(eval_slot_scores,eval_sentence_scores,eval_length_list,kbest=5,ignore_slot_index=ignore_slot_index)
            # bio decoder
            eval_slot_result,eval_sentence_result=bio_decoder(eval_slot_scores,eval_sentence_scores,eval_length_list,reverse_slot_tag_dict,kbest=1,ignore_slot_index=ignore_slot_index,penalty=-1000000)
            # eval_slot_result : [batch_size,kbest,max_sequence_length]
            # eval_sentence_result : [batch_size,kbest]
            flag=True
        elif args.model=='rnn+crf':
            eval_slot_result,eval_sentence_result=eval_net(padded_eval_data,eval_length_list,ignore_slot_index=ignore_slot_index)
            eval_slot_result,eval_sentence_result=eval_slot_result.data.cpu(),eval_sentence_result.data.cpu()
            flag=False
        elif args.model in ['seq2seq','focus','attention']:
            eval_slot_result,_,_,eval_sentence_scores=eval_net.decoder_greed(padded_eval_data,eval_length_list,init_tags=slot_tag_dict['<BEOS>'],ignore_slot_index=ignore_slot_index)
            _,eval_sentence_result=eval_sentence_scores.max(dim=1)
            flag=False
            eval_slot_result,eval_sentence_result=eval_slot_result.data.cpu(),eval_sentence_result.data.cpu()

        semantics_list=obtain_semantics(
            eval_slot_result,eval_sentence_result,
            eval_raw_data,reverse_slot_tag_dict,reverse_sentence_tag_dict,
            domain_ontology,kbest=flag,use_ontology=False,ignore_slot_index=ignore_slot_index,
            fp=file_path,post_processor=post_processor,encapsulate=args.annotation)
        if args.annotation:
            for i,each_ref in enumerate(ref_semantics):
                #对参考标注进行归一化
                current_semantic=post_processor.post_process_constraint(each_ref,semantic_type='recursive')
                current_semantic=post_processor.post_process_entity(current_semantic,semantic_type='recursive')
                ref_semantics[i]=current_semantic
            slot_dict,sentence_dict,whole_dict=compare_semantic(semantics_list,ref_semantics,slot_dict,sentence_dict,whole_dict,error_fp=error_path)
        else:
            for i,each_semantic_result in enumerate(semantics_list):
                print("Query: "+' '.join(eval_raw_data[i])+' =>\nParse: '+json.dumps(each_semantic_result,ensure_ascii=False)+'\n')
    if args.annotation:
        print_char_level_scores(slot_result_dict=None,sentence_result_dict=sentence_dict,path=char_path)
        print_slot_level_scores(slot_result_dict=slot_dict,sentence_result_dict=whole_dict,path=slot_path)
    file_path.close()


from ctypes import sizeof
from typing import BinaryIO, Optional, SupportsBytes, Union, cast

from peclasses.pe_classes import (
    ImageDataDirectory,
    ImageDataDirectoryArray,
    ImageDosHeader,
    ImageFileHeader,
    ImageNTHeaders,
    ImageNTHeaders64,
    ImageOptionalHeader,
    ImageOptionalHeader64,
    OptionalHeaderVersionMagic,
)
from peclasses.relocation_table import RelocationTable
from peclasses.section_table import Section, SectionTable
from peclasses.type_aliases import Offset
from peclasses.utilities import align, read_structure, write_structure

class PortableExecutable:
    file: BinaryIO
    dos_header: ImageDosHeader
    nt_headers: Union[ImageNTHeaders, ImageNTHeaders64]
    file_header: ImageFileHeader
    optional_header: Union[ImageOptionalHeader, ImageOptionalHeader64]
    data_directory: ImageDataDirectoryArray
    _section_table: Optional[SectionTable]
    _relocation_table: Optional[RelocationTable]

    def __init__(self, file: BinaryIO):
        self._read_file(file)

    def _read_file(self, file: BinaryIO) -> None:
        self.file = file
        self.file.seek(0)
        self.dos_header = read_structure(ImageDosHeader, file)
        assert self.dos_header.e_magic == b"MZ"

        file.seek(cast(int, self.dos_header.e_lfanew))
        nt_headers_signature = file.read(4)
        assert nt_headers_signature == b"PE\0\0"

        file.seek(self.optional_header_offset)
        optional_header_magic = int.from_bytes(file.read(2), "little")
        nt_headers_offset = cast(int, self.dos_header.e_lfanew)

        if optional_header_magic == OptionalHeaderVersionMagic.IMAGE_NT_OPTIONAL_HDR32_MAGIC:
            self.nt_headers = read_structure(ImageNTHeaders, file, nt_headers_offset)
        elif optional_header_magic == OptionalHeaderVersionMagic.IMAGE_NT_OPTIONAL_HDR64_MAGIC:
            self.nt_headers = read_structure(ImageNTHeaders64, file, nt_headers_offset)
        else:
            raise ValueError(f"Optional header magic 0x{optional_header_magic:X} is not supported")

        self.file_header = self.nt_headers.file_header
        self.optional_header = self.nt_headers.optional_header
        self.data_directory = self.optional_header.data_directory
        self._section_table = None
        self._relocation_table = None

    def reread(self) -> None:
        self._read_file(self.file)

    @property
    def optional_header_offset(self) -> Offset:
        return cast(int, self.dos_header.e_lfanew) + 4 + sizeof(ImageFileHeader)

    def rewrite_nt_headers(self) -> None:
        offset = self.dos_header.e_lfanew
        nt_headers_data = bytes(cast(SupportsBytes, self.nt_headers))[: self.nt_headers_size]
        self.file.seek(cast(int, offset))
        self.file.write(nt_headers_data)

    def rewrite_data_directory(self) -> None:
        data_directory_data = bytes(cast(SupportsBytes, self.data_directory))[: self.data_directory_size]
        self.file.seek(self.data_directory_offset)
        self.file.write(data_directory_data)

    @property
    def data_directory_offset(self) -> Offset:
        return cast(int, self.dos_header.e_lfanew) + sizeof(self.nt_headers) - sizeof(ImageDataDirectoryArray)

    @property
    def data_directory_size(self) -> int:
        return sizeof(ImageDataDirectory) * cast(int, self.optional_header.number_of_rva_and_sizes)

    @property
    def nt_headers_size(self) -> int:
        # Real size of the optional_header depends on number_of_rva_and_sizes value
        return sizeof(self.nt_headers) - sizeof(ImageDataDirectoryArray) + self.data_directory_size

    @property
    def section_table_offset(self) -> Offset:
        return cast(int, self.dos_header.e_lfanew) + self.nt_headers_size

    @property
    def section_table(self) -> SectionTable:
        if self._section_table is None:
            n = cast(int, self.file_header.number_of_sections)
            offset = self.section_table_offset
            self._section_table = SectionTable.read(self.file, offset, n)
        return self._section_table

    @property
    def relocation_table(self) -> RelocationTable:
        if self._relocation_table is None:
            rva = cast(int, self.data_directory.basereloc.virtual_address)
            offset = self.section_table.rva_to_offset(rva)
            size = cast(int, self.data_directory.basereloc.size)
            self.file.seek(offset)
            self._relocation_table = RelocationTable.from_file(self.file, size)
        return self._relocation_table

    def add_new_section(self, new_section: Section, data_size: int) -> None:
        file = self.file
        sections = self.section_table
        section_alignment = cast(int, self.optional_header.section_alignment)
        file_alignment = cast(int, self.optional_header.file_alignment)
        file_size = align(cast(int, new_section.pointer_to_raw_data) + data_size, file_alignment)
        new_section.size_of_raw_data = file_size - cast(int, new_section.pointer_to_raw_data)

        # Align file size
        file.truncate(file_size)

        # Set the new section virtual size
        new_section.virtual_size = data_size

        # Write the new section info
        write_structure(new_section, file, self.section_table_offset + len(sections) * sizeof(Section))

        # Fix number of sections
        self.file_header.number_of_sections = len(sections) + 1
        # Fix ImageSize field of the PE header
        self.optional_header.size_of_image = align(
            cast(int, new_section.virtual_address) + new_section.virtual_size, section_alignment
        )
        self.rewrite_nt_headers()


from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        mappings = {}
        for index, value in enumerate(nums):
            mappings[value] = index

        for index, value in enumerate(nums):
            required = target - value
            if required in mappings and mappings[required] != index:
                return [index, mappings[required]]


import pytest
from page.home_page import *
from page.add_company_notice import *
import time

'''测试新增公告'''
class TestAddNotice():
    def enter_in_notice_page(self,driver,host,pkUser,pkCompany):
        '''进入公司公告页'''
        HomePage(driver).open(host,pkUser,pkCompany)
        add=AddCompanyNotice(driver)
        add.enter_in_page()
        return  add

    # def test_exist_add_button(self, driver, host):
    #     '''测试有新增管理公司权限-显示【新增文章】按钮'''
    #     add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
    #                                     "68dc0e06-82b7-4024-9a5b-ae921cc53914")
    #     result = add.check_add_article_button()
    #     assert result == True
    #     time.sleep(5)
    #
    # def test_notExist_add_button(self, driver, host):
    #     '''测试没有新增管理公司权限-显示【新增文章】按钮'''
    #     add = self.enter_in_notice_page(driver, host, "a01ef2d3-e87f-4910-9c37-288a3dca325e",
    #                                     "68dc0e06-82b7-4024-9a5b-ae921cc53914")
    #     time.sleep(4)
    #     result = add.check_add_article_button()
    #     assert result == False
    #
    # def test_article_type(self, driver, host):
    #     '''测试新增文章的类型'''
    #     add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
    #                                     "68dc0e06-82b7-4024-9a5b-ae921cc53914")
    #     add.click_add_article_button()
    #     assert add.get_title() == "编辑/新增公告"  # 检查新增公告页面显示
    #     selected_type = add.get_selected_type()
    #     assert selected_type == "公司公告"  # 检查默认选中类型
    #     all_types = add.get_all_types()
    #     assert all_types == ["公司公告", "门店公告", "规章制度", "新增类型"]  # 检查所有类型
    #
    # def test_article_title(self, driver, host):
    #     '''测试新增文章的标题'''
    #     add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
    #                                     "68dc0e06-82b7-4024-9a5b-ae921cc53914")
    #     add.click_add_article_button()
    #     # 检查不输入标题
    #     add.input_title()
    #     add.click_realease()
    #     assert add.get_toast_text() == "标题不能为空"
    #     # 检查标题小于4个中文字符
    #     time.sleep(3)
    #     add.input_title("测试")
    #     add.click_realease()
    #     assert add.get_toast_text() == "标题不少于4个字"
    #     # 检查输入超过40位字符  ！！！！无法获取到标题文本框中的内容
    #     # add.input_title("测试数据"*12)
    #     # title_text=add.get_title_text()
    #     # assert title_text=="测试数据"*10
    #     # 输入大于4个小于40个任意字符
    #     time.sleep(3)
    #     add.input_title("测试aa123")
    #     add.click_realease()
    #     assert add.get_toast_text() == "内容不能为空"
    #
    # def test_add_attachment(self,driver,host):
    #     '''检查新增文章添加附件'''
    #     add = self.enter_in_notice_page(driver, host,"d43c2133-a058-487d-b271-ade608548bfb","68dc0e06-82b7-4024-9a5b-ae921cc53914")
    #     add.click_add_article_button()
    #     #检查附件大小提示文本
    #     attachment_tip_text=add.get_attachment_tip_text()
    #     assert attachment_tip_text=="(附件大小不超过5M)"
    #     #上传应用程序附件
    #     add.add_attachment("D:\\phpStudy.exe")
    #     assert  "格式不对" in add.get_toast_text()
    #     time.sleep(2)
    #     #上传大于5M的文件
    #     add.add_attachment("D:\\chromedriver.exe")
    #     assert  add.get_toast_text()=="仅支持5M以内文件上传"
    #     time.sleep(2)
    #     #上传支持的文件
    #     add.add_attachment("D:\\1.txt")
    #     assert  add.get_toast_text()=="上传成功"
    #     assert  add.get_attachment_title()=="1.txt"
    #     #检查删除附件
    #     assert add.check_delete_attchment()
    #     #再次添加附件
    #     add.add_attachment("D:\\2.txt")
    #     assert add.get_toast_text() == "上传成功"
    #     assert add.get_attachment_title() == "2.txt"
    #
    # def test_edit_notice_body(self,host,driver):
    #     '''检查编辑正文'''
    #     add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
    #                                     "68dc0e06-82b7-4024-9a5b-ae921cc53914")
    #     add.click_add_article_button()
    #     add.input_title("测试aa123")
    #     #检查不输入内容
    #     add.click_realease()
    #     assert add.get_toast_text() == "内容不能为空"
    #     #检查输入任意类型内容
    #     text="张三123；！aaaddd"
    #     add.edit_notice_body(text)
    #     assert  text==add.get_body_text()
    #     #检查输入内容超过2万字
    #     # text2="测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试" \
    #     #       "测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试"*250
    #     # add.edit_notice_body(text2)
    #     # add.click_realease()
    #     # assert add.get_toast_text() == "公告正文最多2万字"
    #
    # def test_title_marked_red(self,driver,host):
    #     '''检查标题标红复选框'''
    #     add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
    #                                     "68dc0e06-82b7-4024-9a5b-ae921cc53914")
    #     add.click_add_article_button()
    #     #检查默认不勾选
    #     class_name=add.get_title_marked_red_checkbox_class_name()
    #     assert "is-checked" not  in class_name
    #     #检查勾选后标题为红色字体
    #     title="测试"+time.strftime("%Y_%m_%d_%H_%M_%S")
    #     add.input_title_and_body(title,"测试正文")
    #     add.check_title_marked_red()
    #     add.click_and_confirm_release()
    #     assert add.check_title_red(title)

    def test_publish_to_scroll_bar(self,driver,host):
        '''检查发布到滚动栏复选框'''
        add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
                                        "68dc0e06-82b7-4024-9a5b-ae921cc53914")
        add.click_add_article_button()
        # 检查默认不勾选
        class_name=add.get_publish_to_scroll_bar_checkbox_class_name()
        assert "is-checked" not in class_name
        #检查勾选发布到滚动栏
        title = "测试" + time.strftime("%Y_%m_%d_%H_%M_%S")
        add.input_title_and_body(title, "测试正文")
        add.check_publish_to_scroll_bar()
        add.click_and_confirm_release()
        assert  add.get_scroll_bar_text() == title

    def test_release_article(self,driver,host):
        '''测试发布'''
        add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
                                        "68dc0e06-82b7-4024-9a5b-ae921cc53914")
        add.click_add_article_button()
        title = "测试" + time.strftime("%Y_%m_%d_%H_%M_%S")
        add.input_title_and_body(title, "测试正文")
        #检查发布
        add.click_and_confirm_release()
        assert  add.get_toast_text()=="操作成功"
        #检查发布的文章显示在文章列表中
        assert  add.check_title_in_article_list(title)

    def test_cancel_edit(self,driver,host):
        '''测试取消编辑'''
        add = self.enter_in_notice_page(driver, host, "d43c2133-a058-487d-b271-ade608548bfb",
                                        "68dc0e06-82b7-4024-9a5b-ae921cc53914")
        add.click_add_article_button()
        title = "测试" + time.strftime("%Y_%m_%d_%H_%M_%S")
        add.input_title_and_body(title, "测试正文")
        #检查点击【返回】显示的提示信息文本
        assert add.get_not_saving_prompt()=="您编辑的内容尚未保存，离开会使内容丢失。是否确认离开？"
        #检查在提示页面点击【关闭】按钮
        assert add.check_click_close_in_prompt()==True
        #检查在提示页面点击【确定】按钮
        add.click_return()
        assert add.check_click_confirm_in_prompt()==True

if __name__ == '__main__':
    pytest.main(["-s","test_add_company_notice.py"])


import json

import dash
import dash_core_components as dcc
import dash_daq as daq
import dash_html_components as html
from dash.dependencies import Input, Output
import dash_bio as dashbio

from dashboard.file_management import get_match_list,get_team_list
import plotly.graph_objects as go

tabs_styles = {
    'height': '36px',
    'width': '256px'
}
tab_style = {
    'borderBottom': '1px solid #d6d6d6',
    'padding': '5px',
}

tab_selected_style = {
    'borderTop': '1px solid #d6d6d6',
    'borderBottom': '1px solid #d6d6d6',
    'backgroundColor': '#119DFF',
    'color': 'white',
    'padding': '5px',
    'fontWeight': 'bold'
}

def create_tab_one():
    return html.Div([
            # Left column
            html.Div(
                id="left-column",
                className="three columns",
                children=[dcc.Tabs(id="column-tabs", value='column-tab-1',
                    children=[
                        dcc.Tab(label='Info', value='column-tab-1', style=tab_style, selected_style=tab_selected_style),
                        dcc.Tab(label='Team 1', value='column-tab-2', style=tab_style, selected_style=tab_selected_style),
                        dcc.Tab(label='Team 2', value='column-tab-3', style=tab_style, selected_style=tab_selected_style),
                    ], style=tabs_styles),
                    html.Div(id='column-tabs-content')]
            ),
            # Right column
            html.Div(
                id="right-column",
                className="nine columns",
                children=[
                    html.Div(
                        id="football pitch",
                        children=[
                            html.Br(),
                            dcc.Loading(id="loading-1", type="default",
                                children=[
                                    html.Div(id='loading-analytics')
                                    ]
                            ),
                            html.Div(children=[
                                html.Div(id='graph1'),
                                html.Div(id='graph2'),
                                html.Div(id='graph3'),
                                html.Div(id='graph4')
                            ]),
                            html.Br()
                        ],
                    )
                ]
            )
        ])

def create_column_tab_one():
    """
    :return: A Div containing dashboard title & descriptions.
    """
    match_list=get_match_list()
    return html.Div(
        id="description-card",
        children=[
            html.H5("Football Game Analytics"),
            html.H3("Welcome to the Tactical Analytics Dashboard"),
            html.Div(
                id="intro",
                children="Explore tactical orientation of football teams during various game phases.",
            ),
            html.Div(
                id="match-card",
                children=[
                    html.Br(),
                    html.H6("Select Match"),
                    dcc.Dropdown(
                        id="match-select",
                        options=[{"label": i[0], "value": i[1]} for i in match_list],
                        style = dict(width = '20em')
                    )
                ]
            )
        ],
    )

def create_column_tab_two(match_id):
    """
    :return: A Div containing controls for graphs.
    """
    if match_id is None:
        return html.H6("Please select a match in the Info Tab")
    team_list=get_team_list(match_id)
    return html.Div(
        id="control-card",
        children=[
            html.Br(),
            html.H6("Select Team"),
            dcc.Dropdown(
                id="team-select",
                options=[{"label": i[0], "value": i[1]} for i in team_list],
                style = dict(width = '20em')
            ),
            html.Div(id='match-settings')
        ]
    )

def create_column_tab_three(match_id):
    """
    :return: A Div containing controls for graphs.
    """
    if match_id is None:
        return html.H6("Please select a match in the Info Tab")
    team_list=get_team_list(match_id)
    return html.Div(
        id="control-card",
        children=[
            html.Br(),
            html.H6("Select Team"),
            dcc.Dropdown(
                id="team-select",
                options=[{"label": i[0], "value": i[1]} for i in team_list],
                style = dict(width = '20em')
            ),
            html.Div(id='match-settings')
        ]
    )

def add_match_settings():
    return html.Div(
        children=[
            html.Br(),
            html.H6("Select Time Window"),
            dcc.RangeSlider(
                id='slider-window',
                count=1,
                min=0,
                max=90,
                step=1,
                value=[0, 90]
            ),
            html.Div(id='slider-output-container'),
            html.Br(),
            html.Br(),
            html.H6("Select Time Frame Size"),
            daq.NumericInput(
                id='time-input',
                min=0,
                value=10,
                max=120
            ),
            html.Br(),
            html.H6(id='ex_secs',children=['Exclude Seconds After Possession Change']),
            daq.NumericInput(
                id='ex_secs-input',
                min=0,
                value=1,
                max=10
            ),
            html.Br(),
            html.H6("Ball Possession Phase"),
            dcc.RadioItems(
                id='possession-radio',
                options=[
                    {'label': 'Ball possession', 'value': 'bp'},
                    {'label': 'No ball possession', 'value': 'nbp'},
                    {'label': 'Both', 'value': 'bo'}
                ],
                value='bo'
            ),
            html.Br(),
            html.Div(
                id="start-btn-outer",
                children=html.Button(id="start-btn", children="Go"),
            )
        ]
    )


import torch
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from torch.utils.data import Dataset, DataLoader
import datetime

def load_data():

    df = pd.read_csv('train.csv')
    building = pd.read_csv('building_info.csv')
    df = pd.merge(df, building, on='건물번호')

    return df

def fill_missing_with_avg(df, columns):
    for i in range(len(df)):
        if pd.isna(df.loc[i, columns]):

            prev_value_sum = df.loc[i-4:i-1, columns].sum()
            next_value_sum = df.loc[i+1:i+4, columns].sum()
            avg_value = (prev_value_sum + next_value_sum) / 8

            df.loc[i, columns] = avg_value
    return df

def CDH(df, num_building):
    df_ = df.copy()
    cdhs = np.array([])
    for num in range(1, num_building+1, 1):
        cdh = []
        cdh_df = df_[df_['building_num'] == num_building]
        cdh_temp = cdh_df['temperature'].values
        for i in range(len(cdh_temp)):
            if i < 11:
                cdh.append(np.sum(cdh_temp[:(i+1)] - 26))
            else:
                cdh.append(np.sum(cdh_temp[(i-11):(i+1)] - 26))

        cdhs = np.concatenate([cdhs, cdh])

    return cdhs

def preprocess(train_set):

    train_set = train_set.drop(columns=['num_date_time', '일조(hr)', '일사(MJ/m2)', '건물유형', '태양광용량(kW)', 'ESS저장용량(kWh)', 'PCS용량(kW)'])
    train_set.columns = ['building_num', 'date', 'temperature', 'precipitation', 'windspeed', 'humidity', 'power_consumption', 'total_area', 'cooling_area']

    train_set['precipitation'].fillna(0, inplace=True)
    train_set = fill_missing_with_avg(train_set, 'windspeed')
    train_set = fill_missing_with_avg(train_set, 'humidity')

    train_set['date'] = pd.to_datetime(train_set['date'], format='%Y%m%d %H')

    # train_set['month'] = train_set.date.dt.month
    train_set['day'] = train_set.date.dt.day
    train_set['weekday'] = train_set.date.dt.weekday
    train_set['hour'] = train_set.date.dt.hour
    # train_set['date'] = train_set.date.dt.date

    # day_periodic = (train_set['day'] - 1) / 30
    # weekday_periodic = train_set['weekday'] / 6
    # hour_periodic = train_set['hour'] / 23

    # train_set['sin_weekday'] = sin_transform(weekday_periodic)
    # train_set['cos_weekday'] = cos_transform(weekday_periodic)
    # train_set['sin_hour'] = sin_transform(hour_periodic)
    # train_set['cos_hour'] = cos_transform(hour_periodic)

    # month_dummy = pd.get_dummies(train_set['month']).rename(columns={6:'month_6', 7:'month_7', 8:'month_8'})
    # train_set = pd.concat([train_set, month_dummy[['month_6', 'month_7']]], axis=1)

    train_set['holiday'] = train_set.apply(lambda x : 0 if x['day']<5 else 1, axis = 1)
    train_set.loc[(train_set.date == datetime.date(2022, 6, 6))&(train_set.date == datetime.date(2022, 8, 15)), 'holiday'] = 1

    train_set['DI'] = 9/5*train_set['temperature'] - 0.55*(1 - train_set['humidity']/100) * (9/5*train_set['humidity'] - 26) + 32

    train_set['CDH'] = CDH(train_set, 100)

    train_set = train_set.drop(columns=['date'])
    train_set = pd.concat([train_set.iloc[:,0:5], train_set.iloc[:,6:], train_set.iloc[:,5:6]], axis=1)

    train_set = train_set[[
        'building_num', #'total_area', 'cooling_area', # static variable
        'day', 'weekday', 'hour', 'holiday', # future variable
        'temperature', 'precipitation', 'windspeed', 'humidity', 'DI', 'CDH', # observed variable
        'power_consumption' # target
        ]]

    return train_set, train_set.columns

def split_data(data):

    train_list = []
    valid_list = []
    test_list = []

    for i in range(len(data['building_num'].unique())):

        train, test = train_test_split(data[data['building_num'] == i+1], test_size=24*7, shuffle=False)
        train, valid = train_test_split(train[train['building_num'] == i+1], test_size=24*7, shuffle=False)
        valid = pd.concat([train[-24*7:], valid]).reset_index(drop=True)
        test = pd.concat([valid[-24*7:], test]).reset_index(drop=True)

        train_list.append(train)
        valid_list.append(valid)
        test_list.append(test)

    train_set = pd.concat(train_list).reset_index(drop=True)
    valid_set = pd.concat(valid_list).reset_index(drop=True)
    test_set = pd.concat(test_list).reset_index(drop=True)

    return train_set, valid_set, test_set

def scaler(train_set, valid_set, test_set):

    scaler_list = []
    train_set_s = pd.DataFrame()
    valid_set_s = pd.DataFrame()
    test_set_s = pd.DataFrame()
    scaling_features = ['temperature', 'precipitation', 'windspeed', 'humidity', 'DI', 'CDH']
    scaling_target = ['power_consumption']
    for i in range(1, len(train_set['building_num'].unique())+1):

        train_set_each_building = train_set[train_set['building_num']==i]
        valid_set_each_building = valid_set[valid_set['building_num']==i]
        test_set_each_building = test_set[test_set['building_num']==i]

        train_features_mean = train_set_each_building[scaling_features].mean()/10
        train_target_mean = train_set_each_building[scaling_target].mean()/10

        train_set_each_building[scaling_features] = train_set_each_building[scaling_features] / train_features_mean
        valid_set_each_building[scaling_features] = valid_set_each_building[scaling_features] / train_features_mean
        test_set_each_building[scaling_features] = test_set_each_building[scaling_features] / train_features_mean

        train_set_each_building[scaling_target] = train_set_each_building[scaling_target] / train_target_mean
        valid_set_each_building[scaling_target] = valid_set_each_building[scaling_target] / train_target_mean
        test_set_each_building[scaling_target] = test_set_each_building[scaling_target] / train_target_mean

        train_set_s = pd.concat([train_set_s, train_set_each_building])
        valid_set_s = pd.concat([valid_set_s, valid_set_each_building])
        test_set_s = pd.concat([test_set_s, test_set_each_building])

        scaler_list.append(train_target_mean.item())

    return train_set_s, valid_set_s, test_set_s, scaler_list

def loader(train_set, valid_set, test_set, batch_size):

    train_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)
    valid_loader = DataLoader(valid_set, batch_size=1, shuffle=False)
    test_loader = DataLoader(test_set, batch_size=1, shuffle=False)

    return train_loader, valid_loader, test_loader

class TemporalFusionPowerDataset(Dataset):
    def __init__(self,
                 data,
                 encoder_len:int,
                 decoder_len:int,
                 static_categorical_variables:list,
                 #static_continuous_variables:list,
                 future_variables:list,
                 past_categorical_variables:list,
                 past_continuous_variables:list,
                 target:str,
                 stride=1
                 ):
        super(TemporalFusionPowerDataset, self).__init__()

        self.data = data
        self.encoder_len = encoder_len
        self.decoder_len = decoder_len
        self.stride = stride
        self.sequence_len = self.encoder_len + self.decoder_len # 192

        self.num_buildings = len(data[static_categorical_variables].iloc[:,0].unique()) # 100
        self.each_build_seq_data_len = len(self.data) // self.num_buildings - self.sequence_len + 1
        # train : 1503
        # valid : 145
        # test : 145

        self.static_cate_data = data[static_categorical_variables]
        #self.static_conti_data = data[static_continuous_variables]
        self.future_data = data[future_variables]
        self.past_cate_data = data[past_categorical_variables]
        self.past_conti_data = data[past_continuous_variables]
        self.target = data[target]

    def __len__(self):

        data_len = ((len(self.data) // self.num_buildings - self.sequence_len) // self.stride + 1) * self.num_buildings

        return data_len

    def __getitem__(self, idx):

        new_idx = idx + (idx//self.each_build_seq_data_len) * (self.sequence_len-1)

        static_cate_data = torch.tensor(self.static_cate_data[new_idx:new_idx+1].to_numpy())
        #static_conti_data = torch.tensor(self.static_conti_data[new_idx:new_idx+1].to_numpy())
        future_data = torch.tensor(self.future_data[new_idx+self.encoder_len:new_idx+self.sequence_len].to_numpy())
        past_cate_data = torch.tensor(self.past_cate_data[new_idx:new_idx+self.encoder_len].to_numpy())
        past_conti_data = torch.tensor(self.past_conti_data[new_idx:new_idx+self.encoder_len].to_numpy())
        target = torch.tensor(self.target[new_idx+self.encoder_len:new_idx+self.sequence_len].to_numpy())

        return static_cate_data, future_data, past_cate_data, past_conti_data, target


import logging
import re
import contextlib

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

from ks_includes.KlippyGcodes import KlippyGcodes
from ks_includes.screen_panel import ScreenPanel

def create_panel(*args):
    return FineTunePanel(*args)

class FineTunePanel(ScreenPanel):
    bs_deltas = ["0.01", "0.05"]
    bs_delta = bs_deltas[-1]
    percent_deltas = ['1', '5', '10', '25']
    percent_delta = percent_deltas[-2]
    speed = extrusion = 100

    def __init__(self, screen, title):
        super().__init__(screen, title)
        if self.ks_printer_cfg is not None:
            bs = self.ks_printer_cfg.get("z_babystep_values", "0.01, 0.05")
            if re.match(r'^[0-9,\.\s]+$', bs):
                bs = [str(i.strip()) for i in bs.split(',')]
                if 1 < len(bs) < 3:
                    self.bs_deltas = bs
                    self.bs_delta = self.bs_deltas[-1]

        # babystepping grid
        bsgrid = Gtk.Grid()
        for j, i in enumerate(self.bs_deltas):
            self.labels[f"bdelta{i}"] = self._gtk.Button(label=i)
            self.labels[f"bdelta{i}"].connect("clicked", self.change_bs_delta, float(i))
            ctx = self.labels[f"bdelta{i}"].get_style_context()
            if j == 0:
                ctx.add_class("distbutton_top")
            elif j == len(self.bs_deltas) - 1:
                ctx.add_class("distbutton_bottom")
            else:
                ctx.add_class("distbutton")
            if i == self.bs_delta:
                ctx.add_class("distbutton_active")
            bsgrid.attach(self.labels[f"bdelta{i}"], j, 0, 1, 1)
        # Grid for percentage
        deltgrid = Gtk.Grid()
        for j, i in enumerate(self.percent_deltas):
            self.labels[f"pdelta{i}"] = self._gtk.Button(label=f"{i}%")
            self.labels[f"pdelta{i}"].connect("clicked", self.change_percent_delta, int(i))
            ctx = self.labels[f"pdelta{i}"].get_style_context()
            if j == 0:
                ctx.add_class("distbutton_top")
            elif j == len(self.percent_deltas) - 1:
                ctx.add_class("distbutton_bottom")
            else:
                ctx.add_class("distbutton")
            if i == self.percent_delta:
                ctx.add_class("distbutton_active")
            deltgrid.attach(self.labels[f"pdelta{i}"], j, 0, 1, 1)

        grid = self._gtk.HomogeneousGrid()
        grid.set_row_homogeneous(False)

        self.labels['z+'] = self._gtk.Button("z-farther", f'{_("Raise Nozzle")}', "color1")
        self.labels['z-'] = self._gtk.Button("z-closer", f'{_("Lower Nozzle")}', "color1")
        self.labels['zoffset'] = self._gtk.Button("refresh", '  0.00' + _("mm"),
                                                  "color1", self.bts, Gtk.PositionType.LEFT, 1)
        self.labels['speed+'] = self._gtk.Button("speed+", _("Speed +"), "color3")
        self.labels['speed-'] = self._gtk.Button("speed-", _("Speed -"), "color3")
        self.labels['speedfactor'] = self._gtk.Button("refresh", "  100%",
                                                      "color3", self.bts, Gtk.PositionType.LEFT, 1)

        self.labels['extrude+'] = self._gtk.Button("flow+", _("Extrusion +"), "color4")
        self.labels['extrude-'] = self._gtk.Button("flow-", _("Extrusion -"), "color4")
        self.labels['extrudefactor'] = self._gtk.Button("refresh", "  100%",
                                                        "color4", self.bts, Gtk.PositionType.LEFT, 1)
        if self._screen.vertical_mode:
            grid.attach(self.labels['z+'], 0, 0, 1, 1)
            grid.attach(self.labels['z-'], 1, 0, 1, 1)
            grid.attach(self.labels['zoffset'], 2, 0, 1, 1)
            grid.attach(bsgrid, 0, 1, 3, 1)
            grid.attach(self.labels['speed-'], 0, 2, 1, 1)
            grid.attach(self.labels['speed+'], 1, 2, 1, 1)
            grid.attach(self.labels['speedfactor'], 2, 2, 1, 1)
            grid.attach(self.labels['extrude-'], 0, 3, 1, 1)
            grid.attach(self.labels['extrude+'], 1, 3, 1, 1)
            grid.attach(self.labels['extrudefactor'], 2, 3, 1, 1)
            grid.attach(deltgrid, 0, 4, 3, 1)
        else:
            grid.attach(self.labels['zoffset'], 0, 0, 1, 1)
            grid.attach(self.labels['z+'], 0, 1, 1, 1)
            grid.attach(self.labels['z-'], 0, 2, 1, 1)
            grid.attach(bsgrid, 0, 3, 1, 1)
            grid.attach(self.labels['speedfactor'], 1, 0, 1, 1)
            grid.attach(self.labels['speed+'], 1, 1, 1, 1)
            grid.attach(self.labels['speed-'], 1, 2, 1, 1)
            grid.attach(self.labels['extrudefactor'], 2, 0, 1, 1)
            grid.attach(self.labels['extrude+'], 2, 1, 1, 1)
            grid.attach(self.labels['extrude-'], 2, 2, 1, 1)
            grid.attach(deltgrid, 1, 3, 2, 1)

        self.labels['z+'].connect("clicked", self.change_babystepping, "+")
        self.labels['zoffset'].connect("clicked", self.change_babystepping, "reset")
        self.labels['z-'].connect("clicked", self.change_babystepping, "-")
        self.labels['speed+'].connect("clicked", self.change_speed, "+")
        self.labels['speedfactor'].connect("clicked", self.change_speed, "reset")
        self.labels['speed-'].connect("clicked", self.change_speed, "-")
        self.labels['extrude+'].connect("clicked", self.change_extrusion, "+")
        self.labels['extrudefactor'].connect("clicked", self.change_extrusion, "reset")
        self.labels['extrude-'].connect("clicked", self.change_extrusion, "-")

        self.content.add(grid)

    def process_update(self, action, data):

        if action != "notify_status_update":
            return

        if "gcode_move" in data:
            if "homing_origin" in data["gcode_move"]:
                self.labels['zoffset'].set_label(f'  {data["gcode_move"]["homing_origin"][2]:.2f}mm')
            if "extrude_factor" in data["gcode_move"]:
                self.extrusion = round(float(data["gcode_move"]["extrude_factor"]) * 100)
                self.labels['extrudefactor'].set_label(f"  {self.extrusion:3}%")
            if "speed_factor" in data["gcode_move"]:
                self.speed = round(float(data["gcode_move"]["speed_factor"]) * 100)
                self.labels['speedfactor'].set_label(f"  {self.speed:3}%")

    def change_babystepping(self, widget, direction):
        if direction == "reset":
            self.labels['zoffset'].set_label('  0.00mm')
            self._screen._ws.klippy.gcode_script("SET_GCODE_OFFSET Z=0 MOVE=1")
        elif direction in ["+", "-"]:
            with contextlib.suppress(KeyError):
                z_offset = float(self._printer.data["gcode_move"]["homing_origin"][2])
                if direction == "+":
                    z_offset += float(self.bs_delta)
                else:
                    z_offset -= float(self.bs_delta)
                self.labels['zoffset'].set_label(f'  {round(z_offset, 2):.2f}mm')
            self._screen._ws.klippy.gcode_script(f"SET_GCODE_OFFSET Z_ADJUST={direction}{self.bs_delta} MOVE=1")

    def change_bs_delta(self, widget, bs):
        logging.info(f"### BabyStepping {bs}")
        self.labels[f"bdelta{self.bs_delta}"].get_style_context().remove_class("distbutton_active")
        self.labels[f"bdelta{bs}"].get_style_context().add_class("distbutton_active")
        self.bs_delta = bs

    def change_extrusion(self, widget, direction):
        if direction == "+":
            self.extrusion += int(self.percent_delta)
        elif direction == "-":
            self.extrusion -= int(self.percent_delta)
        elif direction == "reset":
            self.extrusion = 100

        self.extrusion = max(self.extrusion, 1)
        self.labels['extrudefactor'].set_label(f"  {self.extrusion:3}%")
        self._screen._ws.klippy.gcode_script(KlippyGcodes.set_extrusion_rate(self.extrusion))

    def change_speed(self, widget, direction):
        if direction == "+":
            self.speed += int(self.percent_delta)
        elif direction == "-":
            self.speed -= int(self.percent_delta)
        elif direction == "reset":
            self.speed = 100

        self.speed = max(self.speed, 1)
        self.labels['speedfactor'].set_label(f"  {self.speed:3}%")
        self._screen._ws.klippy.gcode_script(KlippyGcodes.set_speed_rate(self.speed))

    def change_percent_delta(self, widget, delta):
        logging.info(f"### Delta {delta}")
        self.labels[f"pdelta{self.percent_delta}"].get_style_context().remove_class("distbutton_active")
        self.labels[f"pdelta{delta}"].get_style_context().add_class("distbutton_active")
        self.percent_delta = delta


# Написать функцию, аргументы имена сотрудников, возвращает словарь,
# ключи — первые буквы имён, значения — списки, содержащие имена, начинающиеся с соответствующей буквы.

def retrieve_integer(msg):
    while True:
        try:
            return int(input(msg))
        except ValueError:
            print("Вы вводите не цифровое значение, попробуйте еще раз")

def create_and_sort_dict(some_list):
    result = {}
    for i in some_list:
        colleague_name = i[0]
        if colleague_name not in result:
            result[colleague_name] = []
        result[colleague_name].append(i)
    result_keys = list(result.keys())
    result_keys.sort()
    sorted_result = {i: result[i] for i in result_keys}
    return sorted_result

names_list = []
amount = retrieve_integer("Введите количество сотрудников, чьи имена Вам необходимо обработать: ")
for i in range(amount):
    name = input("Введите имя сотрудника: ")
    names_list.append(name)

print(create_and_sort_dict(names_list))