import django_filters

from users.models import Person

class PersonFilter(django_filters.FilterSet):
    class Meta:
        model = Person
        fields = {
            'birthday': [
                'exact', 'gte', 'lte',
                'year__exact', 'year__lte', 'year__gte',
                'month__exact', 'month__lte', 'month__gte',
                'day__exact', 'day__lte', 'day__gte'
            ],
            'first_name': [
                'iexact', 'icontains'
            ],
            'last_name': [
                'iexact', 'icontains'
            ],
            'username': [
                'iexact', 'icontains'
            ]
        }


#!/usr/bin/env python3

from pwn import *
import hashlib

r = remote("52.59.124.14",10100)
hashed = "9784b18945d230d853e9a999921dcb2656a291ce"
flag = 1
for i in range(1,256):
    if(flag == 0):
        break
    for j in range(1,256):
        if(flag == 0):
            break
        for k in range(1,256):
            val = chr(i).encode() + chr(j).encode() + chr(k).encode()
            hasher = hashlib.sha1(val).hexdigest()
            if(hasher[-4:] == "0000"):
                flag = 0
                break
r.sendline(val)
r.sendline(val)
r.interactive()


import logging
import zmq

from shared.log import setup_logs
from common.util import process_loop

from .stats import StatsStorage
from .stats.receiver import StatsReceiver
from .handler import ClientHandler
from .config import Config

class Runner:
    context: zmq.Context[zmq.Socket[None]]
    client_handler: ClientHandler
    stats_receiver: StatsReceiver

    def __init__(self) -> None:
        self.context = zmq.Context()
        self.context.setsockopt(zmq.LINGER, 0)  # Don't block on close
        stats = StatsStorage()
        self.client_handler = ClientHandler(self.context, stats)
        self.stats_receiver = StatsReceiver(stats)

    def run(self) -> None:
        self.client_handler.start()
        self.stats_receiver.run()

    def cleanup(self) -> None:
        self.stats_receiver.cleanup()
        self.client_handler.stop()
        self.client_handler.join()
        self.context.term()

def main() -> None:
    config = Config()
    setup_logs(config.log_level)

    process_loop(lambda: Runner())

    logging.info("Exiting gracefully")

main()


# generic metadata generator for all urls stored in text file
# reading urls from text file and generating metadata to data.json file

from newsplease import NewsPlease
import json

data = []

f=open("y.txt", "r")

c = f.readlines()

for post in c:
	print(post)
	x = NewsPlease.from_url(post)
	data_json = {
	"URL": x.url,
	"Domain": x.source_domain,
	"title": x.title,
	"author": str(x.authors),
	"text": str(x.text),
	"date_published": str(x.date_publish)}
	data.append(data_json)

with open('data.json', 'w+') as outfile:
    json.dump(data, outfile)


# 作者 ： 赖鑫
# 2022年06月17日00时28分33秒

import socket
import select
import sys

tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 设置目的地址并请求连接服务器
dest_addr = (sys.argv[1], 2000)
name = input("请输入你的名字:")
tcp_client.connect(dest_addr)

# 创建epoll对象
epoll = select.epoll()
# 指定socket监听指定的事件
epoll.register(sys.stdin.fileno(), select.EPOLLIN)  # 监听系统标准输入是否有数据
epoll.register(tcp_client.fileno(), select.EPOLLIN)  # 监听tcp客户端缓冲区

while True:
    events = epoll.poll(-1, 10)
    # fd 文件描述符   event 事件类型
    for fd, event in events:
        if fd == sys.stdin.fileno():  # 当标准输入里有数据
            send_data = input("")
            input_data = name + ':' + send_data
            tcp_client.send(input_data.encode('utf8'))
        elif fd == tcp_client.fileno():  # 当接收缓冲区里有数据
            # 接收服务器发来的数据
            recv_data = tcp_client.recv(1024)
            print(recv_data.decode('utf8'))
            if not recv_data:  # 当读到内容为空时
                print("服务器断开了！")
                exit()
            print(recv_data.decode('utf8'))


import numpy as np
import matplotlib.pyplot as py

U = np.loadtxt('U.csv', delimiter=',')
V = np.loadtxt('V.csv', delimiter=',')
rey_uu= np.loadtxt('rey_uu.csv', delimiter=',')
rey_vu = np.loadtxt('rey_vu.csv', delimiter=',')
rey_vv = np.loadtxt('rey_vv.csv', delimiter=',')
y = np.loadtxt('y.csv', delimiter=',')

U_avg = np.mean(U,axis=0)
#U_avg_5=(U[1,:]+U[50,:]+U[150,:]+U[100,:]+U[180,:])/5
rey_vu_avg = np.mean(rey_vu,axis=0)
rey_vv_avg = np.mean(rey_vv,axis=0)
rey_uu_avg = np.mean(rey_uu,axis=0)

fig, ax = py.subplots()
ax.plot(U_avg[4:106],y[4:106])

ax.set(xlabel='Streamwise Velocity', ylabel='y)',
       title='Time and Spatial Averaged')

fig.savefig("time_n_space.png")
py.show()
"""
fig, axs = py.subplots(3, 2)
axs[0, 0].plot(rey_uu[1,4:106],y[4:106],'tab:blue')
axs[0, 0].set_title('X = 1/5')
axs[0, 1].plot(rey_uu[50,4:106],y[4:106], 'tab:orange')
axs[0, 1].set_title('X = 2/5')
axs[1, 0].plot(rey_uu[100,4:106],y[4:106], 'tab:green')
axs[1, 0].set_title('X = 3/5')
axs[1, 1].plot(rey_uu[150,4:106],y[4:106], 'tab:red')
axs[1, 1].set_title('X = 4/5')
axs[2, 0].plot(rey_uu[180,4:106],y[4:106], 'tab:grey')
axs[2, 0].set_title('X = 5/5')
axs[2, 1].plot(rey_uu_avg[4:106],y[4:106])
axs[2, 1].set_title('Average')

for ax in axs.flat:
    ax.set(xlabel='Reynolds Stress uu', ylabel='y')
for ax in fig.get_axes():
    ax.label_outer()
for ax in axs.flat:
    ax.label_outer()
py.show()
"""
#py.plot(rey_uu[1,3:106],y[3:106])
#py.plot(rey_uu[187,4:106],y[4:106])
#py.plot(rey_uu[50,4:106],y[4:106])
#py.plot(rey_uu[100,4:106],y[4:106])
#py.plot(rey_uu[150,4:106],y[4:106])
#py.show()

#py.plot(rey_vu[1,4:106],y[4:106])
#py.show()

#py.plot(rey_vv[1,4:106],y[4:106])
#py.show()

#py.plot(V[1,4:106],y[4:106])
#py.show()


#!/usr/bin/env python

import socket
import sys
import json

PORT = 50001

if len(sys.argv) == 3:
    PORT = sys.argv.pop()

if len(sys.argv) == 2:
    HOST = sys.argv.pop()
else:
    sys.stdout.write("Need to specify a host IP\n")
    sys.exit()

ADDR = (HOST, PORT)

BUFFER_SIZE = 1024

f = dict()
f['bin'] = 1
f['quantity'] = 20

message = json.dumps(f)

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(ADDR)
s.send(message)
s.close()


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

import hypothesis.strategies as st

from caffe2.python import core, workspace
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu

import numpy as np

class TestNGramOps(hu.HypothesisTestCase):
    @given(
        N=st.integers(min_value=10, max_value=100),
        D=st.integers(min_value=2, max_value=10),
        out_of_vcb=st.floats(min_value=0, max_value=0.5),
        max_categorical_limit=st.integers(min_value=5, max_value=20),
        max_in_vcb_val=st.integers(min_value=1000, max_value=10000),
        **hu.gcs_cpu_only
    )
    def test_ngram_from_categorical_op(
        self, N, D, out_of_vcb, max_categorical_limit, max_in_vcb_val, gc, dc
    ):
        col_num = max(int(D / 2), 1)
        col_ids = np.random.choice(D, col_num, False).astype(np.int32)
        categorical_limits = np.random.randint(
            2, high=max_categorical_limit, size=col_num
        ).astype(np.int32)
        vcb = [
            np.random.choice(max_in_vcb_val, x, False)
            for x in categorical_limits
        ]
        vals = np.array([x for l in vcb for x in l], dtype=np.int32)

        floats = -np.random.rand(N, D).astype(np.float32)
        expected_output = []
        for i in range(N):
            val = 0
            for (k, j) in enumerate(col_ids):
                base = np.prod(categorical_limits[:k])
                r = np.random.randint(categorical_limits[k])
                p = np.random.rand()
                if p > out_of_vcb:
                    val += base * r
                    floats[i][j] = vcb[k][r]
            expected_output.append(val)
        expected_output = np.array(expected_output, dtype=np.int32)

        workspace.ResetWorkspace()
        workspace.FeedBlob('floats', floats)
        op = core.CreateOperator(
            "NGramFromCategorical",
            ['floats'],
            ['output'],
            col_ids=col_ids,
            categorical_limits=categorical_limits,
            vals=vals,
        )
        workspace.RunOperatorOnce(op)
        output = workspace.blobs['output']
        np.testing.assert_array_equal(output, expected_output)


import pandas as pd
import torch
import numpy as np
import random
import matplotlib.pyplot as plt
import os
import time
from model import *
from Modules import *
from sklearn.manifold import TSNE
import timeit
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
torch.cuda.set_device(0)
#device=torch.device('cuda')
#将数据导入
def load_tensor(file_name, dtype):
    result=[]
    np.load.__defaults__=(None, True, True, 'ASCII')
    for d in np.load(file_name):
        #print(d)
        #temp=dtype(d).to(device)
        result.append(d)
    np.load.__defaults__=(None, False, True, 'ASCII')
    return result
#打乱数据集
def shuffle_dataset(dataset, seed):
    np.random.seed(seed)
    np.random.shuffle(dataset)
    return dataset

#将数据集拆分为训练集和测试集
def split_dataset(dataset, ratio):
    n = int(ratio * len(dataset))
    dataset_1, dataset_2 = dataset[:n], dataset[n:]
    return dataset_1, dataset_2

if __name__ == "__main__":
    SEED = 1
    random.seed(SEED)
    torch.manual_seed(SEED)
    # torch.backends.cudnn.deterministic = True
    DATASET='Human,C.elegans'

    """Load preprocessed data."""

    #dir_input = ('/mnt/sdb/home/hjy/exp1/dataset/' + DATASET+'/Human,C.elegans')
    dir_input='G:/序列预测相关/模型/DrugormerDTI/dataset/Davis/'
    drug = load_tensor(dir_input + 'atom_feat.npy', torch.FloatTensor)
    bond_adj = load_tensor(dir_input + 'bond_adj.npy', torch.FloatTensor)
    dist_adj = load_tensor(dir_input+ 'dist_adj.npy', torch.FloatTensor)
    proteins = load_tensor(dir_input + 'proteins.npy', torch.FloatTensor)
    interactions = load_tensor(dir_input + 'interactions.npy', torch.LongTensor)
    """Create a dataset and split it into train/dev/test."""

    dataset = list(zip(drug, bond_adj, dist_adj, proteins, interactions))
    dataset = shuffle_dataset(dataset,1234)
    dataset_train, dataset_dev = split_dataset(dataset, 0.8)
    print('dataset created!')
    """ create model ,trainer and tester """
    protein_dim = 100#蛋白质的输入维度
    atom_dim = 128
    hid_dim = 128
    n_layers = 3
    n_heads = 8
    pf_dim =256
    dropout = 0.1
    batch = 4
    lr = 1e-4
    weight_decay = 1e-4
    decay_interval = 10
    lr_decay = 1.0
    iteration = 100
    kernel_size = 7

    encoder = Encoder(protein_dim, hid_dim, n_layers, kernel_size, dropout, device)
    graphormer =DrugEncoder(hid_dim)
    decoder = Decoder(atom_dim, hid_dim, n_layers, n_heads, pf_dim, DecoderLayer, MultiHeadAttention, PositionwiseFeedforward, dropout, device)
    model = Predictor(encoder,graphormer,decoder,device,atom_dim)
    encoder=encoder.cuda()
    graphormer=graphormer.cuda()
    decoder=decoder.cuda()
    model=model.cuda()
    model.load_state_dict(torch.load("G:\序列预测相关\模型\DrugormerDTI\Davis"))
    #model.to(device)
    trainer = Trainer(model, lr, weight_decay, batch)
    tester = Tester(model)

    """Output files."""
    file_AUCs = 'G:\序列预测相关\模型\DrugormerDTI\Davis6.txt'
    file_model = 'G:\序列预测相关\模型\DrugormerDTI\Davis'
    AUCs = ('Epoch\tTime(sec)\tLoss_train\tAUC_dev\tPRC_dev\tRecall_dev\tACC_dev\tPrecision_dev\tF1_dev')
    with open(file_AUCs, 'w') as f:
        f.write(AUCs + '\n')

    """Start training."""
    print('Training...')
    print(AUCs)
    start = timeit.default_timer()

    max_AUC_dev = 0
    for epoch in range(1, iteration+1):
        if epoch % decay_interval == 0:
            trainer.optimizer.param_groups[0]['lr'] *= lr_decay
        loss_train = trainer.train(dataset_train, device)
        #print(loss_train)
        print('Testing……')
        AUC_dev, PRC_dev,recall_dev,accuracy_dev,precision_dev,F1_dev,labels,embeddings,attention = tester.test(dataset_dev)
        end = timeit.default_timer()
        time = end - start
        AUCs = [epoch, time, loss_train, AUC_dev,PRC_dev,recall_dev,accuracy_dev,precision_dev,F1_dev]
        tester.save_AUCs(AUCs, file_AUCs)
        if AUC_dev > max_AUC_dev:
            tester.save_model(model, file_model)
            max_AUC_dev = AUC_dev
        print('\t'.join(map(str, AUCs)))
        print('saving……')
        #print(labels)
        #print(attention.shape)
        emd=[]
        for i in range(len(embeddings)):
            emd.append(embeddings[i][0])
        emd_df=pd.DataFrame(emd)
        emd_df.to_csv(r'G:\序列预测相关\模型\DrugormerDTI\file\embeddings_davis.csv', encoding='utf_8_sig')  # 防止中文乱码
        '''
       #print(attention[-1])

        attentions= pd.DataFrame()
        for i in range(len(attention)):
            #print(attention[i].shape)
            if attention[i].shape[1]<300:
                attentions=pd.DataFrame(attention[i].cpu())
            #attentions.append(attention[i][-1].cpu())
        #attention_df = pd.DataFrame(attentions)
        attentions.to_csv('/mnt/sdb/home/hjy/exp1/file/attention.csv', encoding='utf_8_sig')  # 防止中文乱码

        file = open('/mnt/sdb/home/hjy/exp1/file/label.txt', 'w', encoding='utf-8')
        for i in range(len(labels)):
            #print(len(labels[i]))
            file.write(str(labels[i]) + '\n')
        file.close()
        file = open('/mnt/sdb/home/hjy/exp1/file/embeddings.txt', 'w', encoding='utf-8')
        for i in range(len(embeddings)):
            print(embeddings[i])
            print("===============================")
            file.write(str(embeddings[i]) + '\n')
        file.close()
        '''


from __future__ import annotations

from types import SimpleNamespace
from typing import TYPE_CHECKING, Any, Callable, Generic, Type, TypeVar

from ...commands import Command, Group
from ...commands.application.command import ApplicationCommand
from ...events.event_manager import Event
from ...missing import MISSING, MissingEnum
from ...types import AsyncFunc

if TYPE_CHECKING:
    from ...bot import Bot

T = TypeVar('T')
AF = TypeVar('AF', AsyncFunc)

class BaseContext(SimpleNamespace):
    ...

ContextT = TypeVar('ContextT', bound=BaseContext)

class Gear(Generic[ContextT]):
    """
    The Gear. A set of commands & events separate from Bot.
    Useful for multi-file separation for huge bots.

    Parameters
    ----------
    name: :class:`str`
        The name of this Gear.

    Attributes
    ----------
    bot: Union[:class:`pycord.Bot`, None]
        The bot this Gear is attached to.
    """

    ctx: ContextT

    __slots__ = ('_listener_functions', '_commands', 'name', 'ctx', 'bot')

    def __init__(self, name: str, ctx: ContextT | None = None) -> None:
        self.name = name
        self._listener_functions: dict[Type[Event], list[AsyncFunc]] = {}
        self.bot: Bot
        self._commands: list[Command | Group] = []
        if ctx is None:
            self.ctx = BaseContext()
        else:
            self.ctx = ctx

    async def on_attach(self, *args, **kwargs) -> None:
        ...

    def listen(self, name: str) -> T:
        """
        Listen to an event

        Parameters
        ----------
        name: :class:`str`
            The name of the event to listen to.
        """

        def wrapper(func: T) -> T:
            if self._listener_functions.get(name):
                self._listener_functions[name].append(func)
            else:
                self._listener_functions[name] = [func]
            return func

        return wrapper

    def command(
        self,
        name: str | MissingEnum = MISSING,
        cls: Type[T] = ApplicationCommand,
        **kwargs: Any,
    ) -> T:
        """
        Create a command within the Gear

        Parameters
        ----------
        name: :class:`str`
            The name of the Command.
        cls: type of :class:`.commands.Command`
            The command type to instantiate.
        kwargs: dict[str, Any]
            The kwargs to entail onto the instantiated command.
        """

        def wrapper(func: AsyncFunc) -> Command:
            command = cls(func, state=None, name=name, **kwargs)
            self._commands.append(command)
            return command

        return wrapper

    def group(self, name: str, cls: Type[Group], **kwargs: Any) -> Callable[[AF], AF]:
        """
        Create a brand-new Group of Commands

        Parameters
        ----------
        name: :class:`str`
            The name of the Group.
        cls: type of :class:`.commands.Group`
            The group type to instantiate.
        kwargs: dict[str, Any]
            The kwargs to entail onto the instantiated group.
        """

        def wrapper(func: AF) -> AF:
            # I know this partially ruins typing, but
            # Gears are loaded before events are taken in, so
            # theoretically nothing can break with state being None.
            r = cls(func, name, None, **kwargs)  # type: ignore
            self._commands.append(r)
            return r

        return wrapper

    def attach(self, bot: Bot) -> None:
        """
        Attaches this Gear to a bot.

        Parameters
        ----------

        bot: :class:`pycord.Bot`
            The bot to attach onto
        """

        for name, funcs in self._listener_functions.items():
            for func in funcs:
                bot._state.event_manager.add_event(name, func)

        for cmd in self._commands:
            if isinstance(cmd, Command):
                cmd._state = bot._state
                cmd._state.commands.append(cmd)
            elif isinstance(cmd, Group):
                cmd._state = bot._state

        self.bot = bot

        self.bot._state.gears.append(self)


#A set is unordered, unchangable (only the items) and unindexed
thisset = {"apple", "banana", "cherry"}

thisset.add("orange")
thisset.remove("banana") #can raise an error if item doesn't exists
thisset.discard("banana")#raises no errors
thisset.pop() #removes last item
thisset.clear() #empties the set
del thisset #deletes the whole set

tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical) #adding another set

#Joining sets
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2) #new set with items from both sets
set1.update(set2) #inserts items from set2 into set1

x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y) #keeps only the duplicates
z = x.intersection(y) #new list with only the duplicates
x.symmetric_difference_update(y) #keeping everything except the duplicates
z = x.symmetric_difference(y) #new list without the duplicates
x.difference_update(y) #removes items that exist in both sets
z = x.difference(y) #new list with items that only exist in x, and not in y
z = x.isdisjoint(y) #true if no items in set x is present in set y
z = x.issubset(y) #true if all items in x are present in y
z = x.issuperset(y) #true if all items in y are present in x


# 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 insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:

        parent = None
        temp = root

        while temp:
            parent = temp

            if temp.val > val:
                temp = temp.left

            elif temp.val < val:
                temp = temp.right

        newNode = TreeNode(val)

        if not parent:
            parent = newNode
            return parent

        elif parent.val > val:
            parent.left  = newNode
            return root

        else:
            parent.right = newNode
            return root


n = int(input())
matrix = []
for _ in range(n):
    data = input().split(", ")
    matrix.append(data)

first_diagonal = [matrix[i][i] for i in range(len(matrix))]
second_diagonal = [matrix[i][len(matrix)-1-i] for i in range(len(matrix))]
print(f"First diagonal: {', '.join(first_diagonal)}. Sum: {sum(map(int, first_diagonal))}")
print(f"Second diagonal: {', '.join(second_diagonal)}. Sum: {sum(map(int, second_diagonal))}")


import json
from django.conf import settings
from django.http import HttpResponse
from django.views.generic import View
from haystack.query import SearchQuerySet
from haystack.inputs import Raw
from djinn_core.utils import object_to_urn
from djinn_contenttypes.registry import CTRegistry

def map_swappable_ct(ct_name):

    """ Is the model swappable? If so, what is the underlying model """

    result = ct_name

    try:
        swapped_ct_name = CTRegistry.get(ct_name)['class']._meta.swappable

        if swapped_ct_name:
            result = getattr(settings, swapped_ct_name, ct_name).lower()
    except:
        pass

    return result

class RelateSearch(View):

    """ Find related stuff, using autocomplete """

    def get(self, request, term=None):

        term = term or request.GET.get('term', '')

        if not term:
            return HttpResponse(
                json.dumps([]),
                content_type='application/json')

        search_field = "%s__contains" % request.GET.get("searchfield",
                                                        "title")

        ct_parameter = request.GET.get("ct_searchfield", "meta_ct")

        ct_search_field = "%s__in" % ct_parameter

        content_types = request.GET.get('content_type', '').split(",")

        # MJB map
        # content_types = map(map_swappable_ct, content_types)
        content_types = [map_swappable_ct(ctn) for ctn in content_types]

        _filter = {search_field: Raw("*%s*" % term)}

        if content_types:
            _filter[ct_search_field] = content_types

        parentusergroup = request.GET.get("parentusergroup", None)
        if parentusergroup and parentusergroup != '-1':
            _filter['parentusergroup'] = parentusergroup

        sqs = SearchQuerySet().filter(**_filter)

        results = []

        for res in [res for res in sqs if res.object]:
            results.append({"label": str(res.object),
                            "value": object_to_urn(res.object)
                            })

        if len(results) == 0:
            results.append({"label": "Geen resultaat gevonden",
                            "value": ''})

        return HttpResponse(json.dumps(results), content_type='application/json')


import pandas as pd
from io import StringIO

data = 'Airline Code;DelayTimes;FlightCodes;To_From\nAir Canada (!);[21, 40];20015.0;WAterLoo_NEWYork\n<Air France> (12);[];;Montreal_TORONTO\n(Porter Airways. );[60, 22, 87];20035.0;CALgary_Ottawa\n12. Air France;[78, 66];;Ottawa_VANcouvER\n""".\\.Lufthansa.\\.""";[12, 33];20055.0;london_MONTreal\n'

StringData = StringIO("""{}""".format(data))

df = pd.read_csv(StringData, sep=";")
# print("Intial Data:\n", df)

# 1 Find null rows, pandas series groupby (series.diff compares current and previous row)
nul = df.FlightCodes.isnull()
df.FlightCodes = nul.groupby(
    (nul.diff() == True).cumsum()).sum()*10 + df.FlightCodes.ffill()
df.FlightCodes = df.FlightCodes.astype('int')
# print("Cleaned FlightCodes:\n", df)

# 2
df[['To', 'From']] = df.To_From.str.split('_', expand=True)
df.To = df.To.str.upper()
df.From = df.From.str.upper()
df = df.drop(['To_From'], axis=1)
# print("Cleaned To_From:\n", df)

# 3
df['Airline Code'] = df['Airline Code'].str.replace(
    r'[^a-zA-Z]+', " ", regex=True)
df['Airline Code'] = df['Airline Code'].str.strip()
# print("Cleaned Airline Code:\n", df)

df.to_csv('cleanedData', sep=';', index=False)
print("Cleaned data:\n", df)


import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfVectorizer
import os
import sys
import requests
from PyLyrics import *
import requests
import urllib.parse

#https://github.com/shreyans29/thesemicolon/blob/master/Text%20Analytics%20tfidf.ipynb
if __name__ == '__main__':

    df=pd.read_csv("finaldset.csv")

    df.head()

    #print(len(df))
    '''
    print("0-> ", len(df[df.mood==0]))
    print("1-> ", len(df[df.mood==1]))
    print("2-> ", len(df[df.mood == 2]))
    print("3-> ", len(df[df.mood == 3]))
    '''
    #df.loc[df["Status"]=='ham',"Status",]=1

    #df.loc[df["Status"]=='spam',"Status",]=0

    #df.head()

    df_x=df["lyrics"]
    df_y=df["mood"]

    cv = TfidfVectorizer(min_df=1,stop_words='english')

    x_train, x_test, y_train, y_test = train_test_split(df_x, df_y, test_size=0.20, random_state=22)

    #print(x_train.head())

    cv = TfidfVectorizer(min_df=1,stop_words='english')
    '''
    x_traincv = cv.fit_transform(["Hi How are you How are you doing","Hi what's up","Wow that's awesome"])

    x_traincv.toarray()

    cv.get_feature_names()
    '''
    cv1 = TfidfVectorizer(min_df=1,stop_words='english')

    x_traincv = cv1.fit_transform(x_train)

    a=x_traincv.toarray()

    print(a[0])
    print(cv1.get_feature_names())
    cv1.inverse_transform(a[0])

    print(x_train.iloc[1])
    print("x-test--------------",x_test)
    x_testcv=cv1.transform(x_test)

    x_testcv.toarray()

    mnb = MultinomialNB()

    y_train=y_train.astype('int')

    #print(y_train)

    mnb.fit(x_traincv,y_train)

    #testmessage=x_test.iloc[0]

    #print(testmessage)
    print("---input format---", x_testcv)

    predictions=mnb.predict(x_testcv)

    #print(predictions)

    a=np.array(y_test)

    #print(a)

    count=0

    for i in range (len(predictions)):
        if predictions[i]==a[i]:
            count=count+1

    out=len(predictions)
    accuracy=(count/out)*100
    print("accuracy-> ", accuracy)

    #get percentage'''

    n_testcv = cv1.fit_transform(["Hi How are you How are you doing"])

    n_testcv.toarray()
    print(n_testcv)
    predict_val = mnb.predict(n_testcv)
    print(predict_val)


graph = {
    '0': ['1', '4'],
    '1': ['2', '3', '4'],
    '2': ['1', '3'],
    '3': ['1', '2'],
    '4': ['0', '1'],
}

vis = []
q = []

def bsf(vis,  graph, node):
    vis.append(node)
    q.append(node)
    while q:
        k = q.pop(0)
        print(k, end=" ")
        for nbr in graph[k]:
            if nbr not in vis:
                vis.append(nbr)
                q.append(nbr)

# main code
bsf(vis, graph, '0')


from gi.repository import GLib

from gnome_appfolders_manager.constants import MISSING_ICON_NAME
from gnome_appfolders_manager.functions import get_pixbuf_from_icon_name
from gnome_appfolders_manager.models.abstract import ModelAbstract

class ModelApplications(ModelAbstract):
    COL_TITLE = 1
    COL_COMMENT = 2
    COL_DESCRIPTION = 3
    COL_ICON = 4
    COL_VALID = 5
    COL_VISIBLE = 6

    def __init__(self, model):
        super(self.__class__, self).__init__(model)
        self.items = {}

    def add_data(self, item):
        """Add a new row to the model if it doesn't exist"""
        super(self.__class__, self).add_data(item)
        if item.filename not in self.rows:
            icon = None
            if item.icon_name:
                icon = get_pixbuf_from_icon_name(item.icon_name, 48)
            # Use a fallback icon if the icon was not found, or it was missing
            if not icon:
                icon = get_pixbuf_from_icon_name(MISSING_ICON_NAME, 48)
            new_row = self.model.append((
                item.filename,
                item.name,
                item.description,
                '{name}\n'
                '{description}\n'
                '{filename}'.format(**{
                    'name': item.name,
                    'description': item.description,
                    'filename': GLib.markup_escape_text(item.filename)}),
                icon,
                item.valid,
                item.valid))
            self.rows[item.filename] = new_row
            self.items[item.filename] = item
            return new_row

    def get_title(self, treeiter):
        """Get the title from a TreeIter"""
        return self.model[treeiter][self.COL_TITLE]

    def get_description(self, treeiter):
        """Get the description from a TreeIter"""
        return self.model[treeiter][self.COL_DESCRIPTION]

    def get_icon(self, treeiter):
        """Get the icon from a TreeIter"""
        return self.model[treeiter][self.COL_ICON]

    def set_all_rows_visibility(self, visible):
        """Set all items visible or restore the valid column for visibility"""
        for treeiter in self.model:
            self.model[treeiter.path][self.COL_VISIBLE] = (
                # All rows are visible
                True if visible
                # Only valid rows are visible
                else self.model[treeiter.path][self.COL_VALID])


from django.shortcuts import get_object_or_404
from blog.models import Post, Category, Like, Comment, View
from users.models import NewUser
from .serializers import PostSerializer, CommentSerializer, CreatePostSerializer, LikeSerializer, CommentSerializer, ViewSerializer, PostRankingSerializer
# from .serializers import  UpdateViewSerializer, UpdateLikeSerializer, UpdateCommentSerializer,
from rest_framework import  filters, generics, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.parsers import MultiPartParser, FormParser
from django_filters.rest_framework import DjangoFilterBackend
# Display Posts
from rest_framework.pagination import PageNumberPagination

class CustomPageNumberPagination(PageNumberPagination):
    page_size = 6
    page_size_query_param = 'page_size'
    max_page_size = 100

    def get_paginated_response(self, data):
        res = super().get_paginated_response(data)
        res.data['page_size'] = 6
        return res

class PostList(generics.ListAPIView):
    permission_classes = [permissions.AllowAny]
    serializer_class = PostSerializer
    queryset = Post.objects.all()
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['category__slug', 'author__user_name']
    # Thêm trình xử lý phân trang vào view
    pagination_class = CustomPageNumberPagination

class PostRankingList (generics.ListAPIView):
    permission_classes = [permissions.AllowAny]
    serializer_class = PostRankingSerializer
    queryset = Post.objects.all()
    filter_backends = [filters.OrderingFilter]

class PostDetail(generics.RetrieveAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = PostSerializer

    def get_object(self):
        item = self.kwargs.get('slug')
        post = get_object_or_404(Post, slug=item)
        view = View.objects.create(post=post, author=self.request.user)
        post.num_view += 1
        post.author.num_view += 1
        post.save()
        post.author.save()
        return post

class LikeAPIView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request, slug):
        try:
            post = Post.objects.get(slug=slug)
            # Kiểm tra xem người dùng đã Like bài viết chưa
            user = request.user
            if Like.objects.filter(post=post, author=user).exists():
                return Response({"detail": "Bạn đã Like bài viết này rồi."}, status=status.HTTP_400_BAD_REQUEST)

            like = Like.objects.create(post=post, author=user)
            serializer = LikeSerializer(like)
            post.author.num_like += 1
            post.num_like += 1
            post.save()
            post.author.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except Post.DoesNotExist:
            return Response({"detail": "Bài viết không tồn tại."}, status=status.HTTP_404_NOT_FOUND)

class CommentAPIView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request, slug):
        try:
            post = Post.objects.get(slug=slug)
            # Lấy dữ liệu từ request.data để tạo Comment
            author = request.user
            content = request.data.get('content', '')

            comment = Comment.objects.create(
                post=post, author=author, content=content)
            serializer = CommentSerializer(comment)
            post.num_comment += 1
            post.author.num_comment += 1
            post.save()
            post.author.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except Post.DoesNotExist:
            return Response({"detail": "Bài viết không tồn tại."}, status=status.HTTP_404_NOT_FOUND)

class ViewAPIView(APIView):
    permission_classes = [permissions.IsAuthenticated]

    def post(self, request, slug):
        try:
            post = Post.objects.get(slug=slug)
            # Kiểm tra xem người dùng đã View bài viết chưa
            user = request.user
            view = View.objects.create(post=post, author=user)
            serializer = ViewSerializer(view)
            post.num_view += 1
            post.author.num_view += 1
            post.save()
            post.author.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except Post.DoesNotExist:
            return Response({"detail": "Bài viết không tồn tại."}, status=status.HTTP_404_NOT_FOUND)

class PostListDetailfilter(generics.ListAPIView):

    serializer_class = PostSerializer
    queryset = Post.objects.all()
    filter_backends = [filters.SearchFilter]
    # '^' Starts-with search.
    # '=' Exact matches.
    search_fields = ['^slug']

# Post Admin

# class CreatePost(generics.CreateAPIView):
#     permission_classes = [permissions.IsAuthenticated]
#     queryset = Post.objects.all()
#     serializer_class = PostSerializer

class CreatePost(APIView):
    permission_classes = [permissions.IsAuthenticated]
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request, format=None):
        category_slug = request.data.get('category')
        category = Category.objects.get(slug=category_slug)
        data_copy = request.data.copy()
        data_copy['category'] = category.id

        serializer = CreatePostSerializer(data=data_copy)
        if serializer.is_valid():
            serializer.save()
            request.user.num_post += 1
            request.user.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class UserPostDetail(generics.RetrieveAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

class EditPost(generics.UpdateAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

    def update(self, request, *args, **kwargs):
        category_slug = request.data.get('category', None)
        category = Category.objects.get(slug=category_slug)

        request.data['category'] = category.id

        return super().update(request, *args, **kwargs)

class DeletePost(generics.RetrieveDestroyAPIView):
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = PostSerializer
    queryset = Post.objects.all()

    def perform_destroy(self, instance):
        # Xác định tác giả của bài viết trước khi xóa nó
        author = instance.author
        author.num_post -= 1
        author.num_comment -= instance.num_comment
        author.num_view -= instance.num_view
        author.num_like -= instance.num_like
        author.save()
        # Xóa bài viết
        instance.delete()

""" Concrete View Classes
# CreateAPIView
Used for create-only endpoints.
# ListAPIView
Used for read-only endpoints to represent a collection of model instances.
# RetrieveAPIView
Used for read-only endpoints to represent a single model instance.
# DestroyAPIView
Used for delete-only endpoints for a single model instance.
# UpdateAPIView
Used for update-only endpoints for a single model instance.
# ListCreateAPIView
Used for read-write endpoints to represent a collection of model instances.
RetrieveUpdateAPIView
Used for read or update endpoints to represent a single model instance.
# RetrieveDestroyAPIView
Used for read or delete endpoints to represent a single model instance.
# RetrieveUpdateDestroyAPIView
Used for read-write-delete endpoints to represent a single model instance.
"""


#!/usr/bin/env python3
# Fundamentals of Python Network Programming, Third Edition
"""Simple TCP client and server that send and receive 16 octets."""

import argparse
import socket
import sys

def server(interface, port, bytecount):
    """Socket server."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((interface, port))
    sock.listen(1)
    print("Server listening at", sock.getsockname())
    try:
        while True:
            conn, addr_info = sock.accept()
            print("Processing up to 1024 bytes at at time from", addr_info)
            n = 0
            while True:
                data = conn.recv(1024)
                if not data:
                    break
                output = data.decode('ascii').upper().encode('ascii')
                conn.sendall(output)  # send back as uppercase
                n += len(data)
                print('\r  {} bytes processed so far'.format(n), end=' ')
                sys.stdout.flush()
            print()
            conn.close()
            print("    Reply sent, socket closed.")
    except KeyboardInterrupt:
        print("Shutting down server.")
        sock.close()
        sys.exit(0)

def client(host, port, bytecount):
    """Socket client."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    bytecount = (bytecount + 15) // 16 * 16
    message = b'capitalize this!'  # 16-byte message to repeat over and over
    print('Sending', bytecount, 'bytes of data, in chunks of 16 bytes')
    sock.connect((host, port))
    sent = 0
    while sent < bytecount:
        sock.sendall(message)
        sent += len(message)
        print('\r {} bytes sent'.format(sent), end=' ')
        sys.stdout.flush()

    print()
    sock.shutdown(socket.SHUT_WR)

    print("Receiving all the data the server sends back")

    received = 0
    while True:
        data = sock.recv(42)
        if not received:
            print('    The first data received says', repr(data))
        if not data:
            break
        received += len(data)
        print('\r    {} bytes received'.format(received), end=' ')
    print()
    sock.close()

if __name__ == "__main__":
    choices = {"client": client, "server": server}
    parser = argparse.ArgumentParser(description="Send and receive over TCP")
    parser.add_argument("role", choices=choices, help="which role to play")
    parser.add_argument("host", help="interface the server listens at; host the client send to")
    parser.add_argument("bytecount", type=int, nargs="?", default=16, help="number of bytes for client to send (default 16)")
    parser.add_argument("-p", metavar="PORT", type=int, default=1060, help="TCP port (default 1060)")
    args = parser.parse_args()
    function = choices[args.role]
    function(args.host, args.p, args.bytecount)


import requests
from bs4 import BeautifulSoup
import Executando

def obtendoResposta(pergunta,Swan):
    print(pergunta)
    headers = {'User-Agent':"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"}
    r = requests.get(f'https://www.google.com/search?q={pergunta}',headers=headers)
    soup = BeautifulSoup(r.content, 'html.parser')
    texto = soup.find(class_='kno-rdesc')
    filtrando = texto
    if filtrando:
        texto2 = filtrando.find('span').get_text()
        print("XXXX")
        print(texto2)
        return texto2
    else:
        Executando.Executar(Swan,'pesquisa','')

if __name__ == '__main__':
    obtendoResposta('Quantos habitantes o brasil tem', '')


import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
from sklearn.ensemble import RandomForestClassifier
from sklearn import tree
# from sklearn.metrics import cr

hr_data = pd.read_csv('data/hr.csv', header=0)
hr_data.head()
print(" Data Set Shape ", hr_data.shape)
print(list(hr_data.columns))
print(" Sample Data", hr_data.head())

data_trnsf = pd.get_dummies(hr_data, columns=['salary', 'sales'])
data_trnsf.columns
X = data_trnsf.drop('left', axis=1)
X.columns

X_train, X_test, Y_train, Y_test = train_test_split(X, data_trnsf.left, test_size=0.3, random_state=42)
print(X_train)

num_trees = 100
max_features = 3
attrition_forest = RandomForestClassifier(n_estimators=num_trees, max_features=max_features)
attrition_forest.fit(X_train, Y_train)

Y_pred = attrition_forest.predict(X_test)
confusionMatrix = confusion_matrix(Y_test, Y_pred)
print(confusionMatrix)

print('Accuracy of Decision Tree classifier on test set:{:.2f}', format(attrition_forest.score(X_test, Y_test)))
print(classification_report(Y_test, Y_pred))

crossval_5_scores = cross_val_score(attrition_forest, X_train, Y_train, cv=5)
print(crossval_5_scores)
print(np.mean(crossval_5_scores))
crossval_10_scores = cross_val_score(attrition_forest, X_train, Y_train, cv=10)
print(crossval_10_scores)
print(np.mean(crossval_10_scores))


# Fetch arxiv data from S3

from boto3.session import Session
import dotenv
import logging
import os

from ai_papers_with_code import PROJECT_DIR

dotenv.load_dotenv(f"{PROJECT_DIR}/.env")
DATA_PATH = f"{PROJECT_DIR}/inputs/data"

key = os.getenv("aws_access_key_id")
secret_key = os.getenv("aws_secret_access_key")

def main():
    session = Session(aws_access_key_id=key, aws_secret_access_key=secret_key)
    s3 = session.resource("s3")

    pwc_bucket = s3.Bucket("ai-papers-with-code")

    for s3_file in pwc_bucket.objects.all():
        logging.info(f"downloading {s3_file.key}")

        with open(f"{PROJECT_DIR}/inputs/data/{s3_file.key}", "wb") as out:
            pwc_bucket.download_fileobj(s3_file.key, out)

if __name__ == "__main__":
    main()


import pytest
import ray
import time
import shutil
import numpy as np

from gym import spaces

from malib import settings
from malib.envs.agent_interface import AgentInterface
from malib.algorithm import random
from malib.utils.typing import BehaviorMode, ParameterDescription, Status

from tests.parameter_server import FakeParameterServer

@pytest.mark.parametrize(
    "observation_space,action_space",
    [
        (spaces.Box(low=-1.0, high=1.0, shape=(1,)), spaces.Discrete(3)),
        (
            spaces.Box(low=-1.0, high=1.0, shape=(4,)),
            spaces.Box(low=-1.0, high=1.0, shape=(2,)),
        ),
    ],
    scope="class",
)
class TestEnvAgentInterface:
    @pytest.fixture(autouse=True)
    def init(self, observation_space, action_space):
        if not ray.is_initialized():
            ray.init()

        try:
            parameter_server = ray.get_actor(settings.PARAMETER_SERVER_ACTOR)
        except ValueError:
            parameter_server = FakeParameterServer.remote()

        self.interface = AgentInterface(
            agent_id="test",
            observation_space=observation_space,
            action_space=action_space,
            parameter_server=parameter_server,
        )

        self.env_id = "test"
        desc = dict(
            registered_name=random.NAME,
            observation_space=observation_space,
            action_space=action_space,
            model_config={},
            custom_config={},
        )
        self.interface.add_policy(
            self.env_id,
            "policy_0",
            desc,
            ParameterDescription(
                time_stamp=time.time(),
                identify="policy_0",
                env_id=self.env_id,
                id="policy_0",
                version=0,
                description=desc,
            ),
        )

    def test_set_behavior_mode(self):
        self.interface.set_behavior_mode(BehaviorMode.EXPLOITATION)
        assert self.interface.behavior_mode == BehaviorMode.EXPLOITATION
        self.interface.set_behavior_mode(BehaviorMode.EXPLORATION)
        assert self.interface.behavior_mode == BehaviorMode.EXPLORATION

    def test_set_behavior_dist(self, observation_space, action_space):
        PPOOL_SIZE = 10
        for i in range(PPOOL_SIZE):
            pid = f"policy_{i}"
            desc = dict(
                registered_name=random.NAME,
                observation_space=observation_space,
                action_space=action_space,
                model_config={},
                custom_config={},
            )
            parameter_desc = ParameterDescription(
                time_stamp=time.time(),
                identify=pid,
                env_id=self.env_id,
                id=pid,
                version=0,
                description=desc,
            )
            self.interface.add_policy(self.env_id, pid, desc, parameter_desc)

        dist = dict(zip([f"policy_{i}" for i in range(PPOOL_SIZE)], [1 / PPOOL_SIZE]))
        self.interface.set_behavior_dist(dist)

    def test_serialize(self):
        # since pickle does not support __post_init__
        # while install dill has no need, we just test __setstate__ and __getstate__
        state = self.interface.__getstate__()
        self.interface.__setstate__(state)

    def test_reset(self, observation_space, action_space):
        PPOOL_SIZE = 10
        for i in range(PPOOL_SIZE):
            pid = f"policy_{i}"
            desc = dict(
                registered_name=random.NAME,
                observation_space=observation_space,
                action_space=action_space,
                model_config={},
                custom_config={},
            )
            parameter_desc = ParameterDescription(
                time_stamp=time.time(),
                identify=pid,
                env_id=self.env_id,
                id=pid,
                version=0,
                description=desc,
            )
            self.interface.add_policy(self.env_id, pid, desc, parameter_desc)

        # reset without any policy figured out?
        self.interface.reset()
        assert self.interface.behavior_policy is not None, (
            self.interface.behavior_policy,
            list(self.interface.policies.keys()),
        )

        # reset with policy figure out?
        self.interface.reset(policy_id="policy_2")
        assert (
            self.interface.behavior_policy == "policy_2"
        ), self.interface.behavior_policy
        assert np.isclose(sum(self.interface.sample_dist.values()), 1.0)
        for e in self.interface.sample_dist.values():
            assert e == 1 / PPOOL_SIZE

        # reset with sample dist figureout?
        sample_dist = [1.0 / PPOOL_SIZE] * PPOOL_SIZE
        sample_dist = dict(zip([f"policy_{i}" for i in range(PPOOL_SIZE)], sample_dist))
        self.interface.reset(sample_dist=sample_dist)
        assert self.interface.behavior_policy is not None

        sample_dist = [0.0] * PPOOL_SIZE
        sample_dist[-1] = 1.0
        sample_dist = dict(zip([f"policy_{i}" for i in range(PPOOL_SIZE)], sample_dist))
        self.interface.reset(sample_dist=sample_dist)
        assert self.interface.behavior_policy == "policy_{}".format(PPOOL_SIZE - 1), (
            self.interface.behavior_policy,
            list(self.interface.policies.keys()),
        )

    def test_compute_action(self, observation_space: spaces.Space):
        self.interface.reset()
        x = self.interface.compute_action(
            observation=np.asarray(
                [observation_space.sample() for _ in range(4)]
            ).reshape((-1,) + observation_space.shape),
            rnn_state=[self.interface.get_initial_state() for _ in range(4)],
        )
        assert len(x) == 3
        action = []
        action_dist = []
        rnn_state = []
        for e in x[0]:
            action.append(e)
        for e in x[1]:
            action_dist.append(e)
        for e in x[2]:
            rnn_state.append(e)
        assert len(action) == len(action_dist) == 4

    def test_weight_update(self):
        self.interface.reset()
        pid = self.interface.behavior_policy
        status = self.interface.update_weights([pid], waiting=True)
        assert isinstance(status, dict) and status[pid] == Status.SUCCESS, status
        status = self.interface.update_weights([pid], waiting=False)
        assert isinstance(status, dict) and status[pid] == Status.SUCCESS, status

    def test_observation_transformation(self, observation_space):
        self.interface.reset()
        res1 = self.interface.transform_observation(observation_space.sample())
        res2 = self.interface.transform_observation(
            [observation_space.sample() for _ in range(4)]
        )
        target_shape = observation_space.shape
        if target_shape == (1,):
            target_shape = ()
        assert res1["obs"].shape == target_shape
        assert res2["obs"].shape == (4,) + target_shape

    def test_save_and_close(self):
        self.interface.reset()
        pid = self.interface.behavior_policy
        tmp_dir = "/tmp/model_{}".format(time.time())
        self.interface.save(tmp_dir)
        self.interface.close()
        shutil.rmtree(tmp_dir)

    @classmethod
    def teardown_class(cls):
        ray.shutdown()


from tkinter import ttk
from tkinter import *

from tkinter import filedialog
from PIL import Image, ImageTk
import sqlite3
from adress.count_screen import Counting

class Win(Counting):
    """Class for Main Window."""

    def __init__(self):
        self.connection = sqlite3.connect("database/adress_cat.db")
        self.win = Tk()
        self.win.title=("Adress-Management")
        self.win.geometry('800x600')
        self.co0 = "#ffffff"
        self.co1 = "#000000"
        self.co2 = "#20214f"
        self.win.configure(background=self.co0)
        self.win.resizable(width=False, height=False)

    def Delete_Win(self):
        self.win.withdraw()
        self.win.destroy()
        from delete_contact_gui import MainWinDelete
        win = MainWinDelete()
        win.Window()
        win.win.mainloop()

    def Add_Win(self):
        self.win.withdraw()
        self.win.destroy()
        from add_contact_gui import MainWin
        win = MainWin()
        win.Window_Main()
        win.win.mainloop()

    def Query_Win(self):
        self.win.withdraw()
        self.win.destroy()
        from gui_query import MainWinQuery
        win = MainWinQuery()
        win.Window()
        win.win.mainloop()

    def Update_Win(self):
        self.win.withdraw()
        self.win.destroy()
        from gui_update_record import MainWinUpdate
        wind = MainWinUpdate()
        wind.MainWinUpdate()
        wind.wind.mainloop()

    def Window(self):
        # top
        top = Frame(self.win, width=800, height=50, bg=self.co2)
        top.grid(row=0, column=0, padx=0, pady=1)

        # bottom
        bottom = Frame(self.win, width=800, height=150, bg=self.co2)
        bottom.place(x=0, y=480)

        # header
        header = Label(top, text="Adress-Management ✆", height=1, font=("Bahnschrift 22 bold"), bg= self.co2, fg=self.co0)
        header.place(x=280, y=2)

        # Instruction
        center = Label(text="Bitte wählen Sie Ihre gewünschte Aktion", height=1, font=("Calibri 18 bold"), bg= self.co0, fg=self.co1)
        center.place(x=220, y=80)

        # Add Contact Button
        self.bAdd = Button(self.win, text="Kontakt Hinzufügen", font=("Bahnschrift 14 bold"), bg=self.co2, fg=self.co0, command=self.Add_Win)
        self.bAdd.place(x=290, y=140, width=260, height=40)

        # Update Button
        self.bUpdate = Button(self.win, text="Kontakt Aktualisieren", font=("Bahnschrift 14 bold"), bg=self.co2, fg=self.co0, command=self.Update_Win)
        self.bUpdate.place(x=290, y=200, width=260, height=40)

        # Query Button
        self.bQuery = Button(self.win, text="Kontakt Abfragen", font=("Bahnschrift 14 bold"), bg=self.co2, fg=self.co0, command=self.Query_Win)
        self.bQuery.place(x=290, y=260, width=260, height=40)

        # Delete Button
        self.bDelete = Button(self.win, text="Kontakt Löschen", font=("Bahnschrift 14 bold"), bg=self.co2, fg=self.co0, command=self.Delete_Win)
        self.bDelete.place(x=290, y=320, width=260, height=40)

        self.get_school()
        frame = Frame(self.win, bg="blue", width=80, height=80)
        frame.place(x=230, y=390)
        school_text = Label(self.win, text="Schulkollegen", fg=self.co1, bg=self.co0)
        school_text.place(x=230, y= 368)
        label = Label(frame, text="🏫" +"\n" + str(self.school) , font=("Arial", 22), bg="white")
        label.place(x=4, y=4, width=72, height=72)

        self.get_family()
        frame = Frame(self.win, bg="green", width=80, height=80)
        frame.place(x=330, y=390)
        family_text = Label(self.win, text="Familie", fg=self.co1, bg=self.co0)
        family_text.place(x=348, y= 368)
        label = Label(frame, text="👨👩👧👦" +"\n" + str(self.family) , font=("Arial", 22), bg="white")
        label.place(x=4, y=4, width=72, height=72)

        self.get_work()
        frame = Frame(self.win, bg="orange", width=80, height=80)
        work_text = Label(self.win, text="Arbeitskollegen", fg=self.co1, bg=self.co0)
        work_text.place(x=424, y= 368)
        frame.place(x=430, y=390)
        label = Label(frame, text="💼" +"\n"+ str(self.work) , font=("Arial", 22), bg="white")
        label.place(x=4, y=4, width=72, height=72)

        self.get_friends()
        frame = Frame(self.win, bg="red", width=80, height=80)
        friend_text = Label(self.win, text="Freunde", fg=self.co1, bg=self.co0)
        frame.place(x=530, y=390)
        friend_text.place(x=544, y= 368)
        label = Label(frame, text="🧍" + "\n" + str(self.friend) , font=("Arial", 22), bg="white")
        label.place(x=4, y=4, width=72, height=72)

def main():
    win = Win()
    win.Window()
    win.win.mainloop()

if __name__ == "__main__":
    main()


### IMPORTANDO BIBLIOTECAS
from typing import Concatenate
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
import pandas_datareader.data as web
import win32com.client as win32
from datetime import date, datetime, timedelta

### CAMINHOS DE ARQUIVO
CAMINHO_CARTEIRA = Path('C:/Users/paulo/Desktop/paulocesarm/python study/#HASHTAG/ENCONTROS AO VIVO/03 - ANÁLISES FINANCEIRS/CarteiraMentoria.xlsx')
CAMINHO_TD = 'https://www.tesourotransparente.gov.br/ckan/dataset/f0468ecc-ae97-4287-89c2-6d8139fb4343/resource/e5f90e3a-8f8d-4895-9c56-4bb2f7877920/download/VendasTesouroDireto.csv'
tesouro_direto = 'https://www.tesourotransparente.gov.br/ckan/dataset/f0468ecc-ae97-4287-89c2-6d8139fb4343/resource/e5f90e3a-8f8d-4895-9c56-4bb2f7877920/download/VendasTesouroDireto.csv'

### CAMINHO PARA SALVAR GRÁFICOS
VALOR_INVESTIDO_ATIVO = r'C:/Users/paulo/Desktop/paulocesarm/python study/#HASHTAG/ENCONTROS AO VIVO/03 - ANÁLISES FINANCEIRS/valor_investido_ativo.png'
VALOR_INVESTIDO_TIPO = r'C:/Users/paulo/Desktop/paulocesarm/python study/#HASHTAG/ENCONTROS AO VIVO/03 - ANÁLISES FINANCEIRS/valor_investido_tipo.png'
VALOR_IBOV = r'C:/Users/paulo/Desktop/paulocesarm/python study/#HASHTAG/ENCONTROS AO VIVO/03 - ANÁLISES FINANCEIRS/valores_ibov.png'
COMPARATIVO_CARTEIRA_IBOV = r'C:/Users/paulo/Desktop/paulocesarm/python study/#HASHTAG/ENCONTROS AO VIVO/03 - ANÁLISES FINANCEIRS/comparativo_carteira_ibov.png'

### DEFININDO DATA ATUAL
data_atual = date.today()
data_atual = data_atual.strftime('%Y-%m-%d')

def enviando_email():

    outlook = win32.Dispatch('outlook.application') #definindo aplicação pelo outlook
    mail = outlook.CreateItem(0) #criando o email
    mail.To = 'paulocesaradvice@gmail.com' #defindo o destinatário
    mail.Subject = 'Relatório Gerencial da Carteira' #definindo título
    mail.Body = f''' Olá Paulo, tudo bem?
    Conforme solicitado, levantamos os principais gráficos referente a sua carteira e enviamos em anexo.
    Caso tenha alguma dúvida, não hesite em entrar em contato conosco.''' #corpo do email#corpo do email
    mail.Attachments.Add(VALOR_INVESTIDO_ATIVO) #adicionando anexo
    mail.Attachments.Add(VALOR_INVESTIDO_TIPO) #adicionando anexo
    mail.Attachments.Add(VALOR_IBOV) #adicionando anexo
    mail.Attachments.Add(COMPARATIVO_CARTEIRA_IBOV) #adicionando anexo
    mail.Send() #enviando :)

    return print("Email Enviado")

def main():

    ### PEGANDO COTAÇÕES
    ## indices: ^iINDICE
    ## ações brasileiras: TICKER.SA
    ## source = yahoo
    ## datas: 'aaaa-mm-dd'

    ## IBOVESPA
    ibov_df = web.DataReader('^BVSP', data_source='yahoo', start = '2020-01-02', end = f'{data_atual}') #web.DataReader('TICKER', data_source='fonte', start = 'data inicio', end = 'data final')
    print(ibov_df.info()) #printando info do dataframe para análise

    ## MINHA CARTEIRA
    carteira = pd.read_excel(CAMINHO_CARTEIRA)
    carteira_tipo = carteira.groupby('Tipo')['Valor Investido'].sum()
    carteira_df = pd.DataFrame()
    for ativo in carteira['Ativos']:
        if 'Tesouro' not in ativo: #retirando o tesouro direto do FOR (Não da para retirar as informações dele pelo link do yahoo)
            carteira_df[ativo] = web.DataReader('{}.SA'.format(ativo), data_source='yahoo', start = '2020-01-01', end = f'{data_atual}')['Adj Close'] #pegando os dados dos ativos da carteira
        else:
            pass

    carteira_df = carteira_df.ffill() #preenche o vazio com o dado da linha anterior, a coluna do SMALL11 estava faltando 2 dados. Fizemos isso para preencher.
    print(carteira_df.info()) #printando info do dataframe para análise

    ## TESOURO
    tesouro_df = pd.read_csv(CAMINHO_TD, sep = ';', decimal = ',') #lendo o arquivo CSV com os dados do tesouro (através de um link direto de csv)
    print(tesouro_df.info()) #printando informações do dataframe para análise
    tesouro_df['Data Venda'] = pd.to_datetime(tesouro_df['Data Venda'], format = '%d/%m/%Y') #passando o formato de data de dd/mm/aaaa para o datetime padrão do pandas ('aaaa-mm-dd'), o format não é o formato que ele vai ficar e sim o que ele é.
    tesouro_df = tesouro_df[tesouro_df['Tipo Titulo'] == 'Tesouro Selic'] #pegando somente as linhas que o tipo título é o tesouro selic
    tesouro_df = tesouro_df[['Data Venda', 'PU']] #filtrando base para pegar apenas as colunas de Data Venda e PU
    tesouro_df = tesouro_df.rename(columns = {'Data Venda':'Date' , 'PU': 'Tesouro Selic'}) #renomeando as colunas de Data Venda e PU.

    ## UNINDO DADOS DA MINHA CATEIRA COM O TESOURO
    carteira_df = carteira_df.merge(tesouro_df[['Date','Tesouro Selic']], on = 'Date', how = 'left') #colando os dados do lado e juntando a coluna em comum. (sempre tem que ter uma coluna em comum para usar o merge!)
    print(carteira_df.info()) #printando informações do dataframe para análise

    ### REALIZANDO CALCULO DE INDICADORES
    ## TRATANDO DADOS
    carteira_copia = carteira_df.copy() #criando uma cópia do dataframe da carteira, para não mudar o original na hora dos cálculos

    for i,ativo in enumerate(carteira['Ativos']):
        carteira_copia[ativo] = carteira_copia[ativo]*carteira.loc[i, 'Qtde'] #substituindo os valores das colunas dos ativos pelo Total Investido

    carteira_copia = carteira_copia.set_index('Date') #setando a coluna de data para ser o indice para que no SUM ela não seja contabilizada.

    carteira_copia['Total'] = carteira_copia.sum(axis = 1) #criando coluna de total somando as linhas das colunas restantes (o axis = 1 muda o padrão de somar coluna para somar linha)
    ## CALCULANDO INDICADORES
    carteira_copia_norm = carteira_copia/carteira_copia.iloc[0] #colocando na mesma base para que a comparação no gráfico seja real (partam do mesmo ínicio)
    ibov_df_norm = ibov_df/ibov_df.iloc[0] #colocando na mesma base para que a comparação no gráfico seja real
    rentabilidde_carteira = carteira_copia['Total'].iloc[-1]/carteira_copia['Total'].iloc[0] - 1 #calculando a rentabilidade da carteira
    rentabilidade_ibov = ibov_df['Adj Close'].iloc[-1]/ibov_df['Adj Close'].iloc[0] - 1 #calculando a rentabilidade do ibovespa
    print('Rentabilidade da Carteira {:.1%}'.format(rentabilidde_carteira)) #printando a rentabilidade da carteira
    print('Rentabilidade da IBOV {:.1%}'.format(rentabilidade_ibov)) #printando a rentabilidade do ibovespa

    ### PLOTANDO GRÁFICOS
    ## PLOTANDO GRÁFICO DE DISTRIBUIÇÃO DO VALOR INVESTIDO EM PERCENTUAL POR ATIVO DA CARTEIRA
    grafico1 = carteira['Valor Investido'].plot.pie(labels = carteira['Ativos'], y = 'Valor Investido', legend = False, title ="Distruibuição dos ativos da Carteira",figsize = (15,5), autopct = "%.1f%%") # plotando gráfico de pizza
    grafico1.set_ylabel('') #tirando título do eixo y
    grafico1.set_xlabel('') #tirando título do eixo x
    fig1 = grafico1.figure #atribuindo gráfico a essa variavel
    fig1.savefig(VALOR_INVESTIDO_ATIVO) #salvando gráfico no caminho especificado
    ## PLOTANDO GRÁFICO DE DISTRIBUIÇÃO DO VALOR INVESTIDO EM PERCENTUAL POR TIPO DE ATIVO DA CARTEIRA
    grafico2 = carteira.groupby('Tipo')['Valor Investido'].sum().plot.pie(y = 'Valor Investido', legend = False, title ="Distruibuição dos tipos da Carteira",figsize = (15,5), autopct = "%.1f%%")
    grafico2.set_ylabel('') #tirando o título do eixoo y do gráfico 2
    grafico2.set_xlabel('') #tirando título do eixo x grafico 2
    fig2 = grafico2.figure #atribuindo gráfico a essa variavel
    fig2.savefig(VALOR_INVESTIDO_TIPO)
    ## PLOTANDO GRÁFICO COM OS VALORES DO IBOV AO LONGO DO TEMPO
    grafico3 = ibov_df['Adj Close'].plot(figsize = (15,5))
    grafico3.set_xlabel('')
    fig3 = grafico3.figure #atribuindo gráfico a essa variavel
    fig3.savefig(VALOR_IBOV) #salvando gráfico no caminho especificado
    ## PLOTANDO GRÁFICO COMPARATIVO DA CATEIRA COM O IBOVESPA
    grafico4 =carteira_copia_norm['Total'].plot(figsize = (15,5), label = 'Carteira')
    grafico4 = ibov_df_norm['Adj Close'].plot(figsize = (15,5), label = 'IBOV')
    plt.legend()
    fig4 = grafico4.figure #atribuindo gráfico a essa variavel
    fig4.savefig(COMPARATIVO_CARTEIRA_IBOV) #salvando gráfico no caminho especificado

    print("Iniciando rotina de envio de email")
    enviar_email = enviando_email()

    return None

funcao = main()


def solution(s):
    answer = []
    temp = s[2:-2].split('},{')
    temp.sort(key=lambda x: x.count(','))

    for x in temp:
        l = x.split(',')
        for i in l:
            if int(i) not in answer:
                answer.append(int(i))
                break

    return answer


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
NStack.ImageProcess Service
"""
import tempfile
import random
import os
import nstack

from imaging import *

class Module(nstack.Module):
  def __init__(self):
    # make sure call the superclass to initialise correctly
    super().__init__()
    self.random_funcs = [mk_gotham, mk_kelvin, mk_lomo, mk_nashville, mk_toaster]
    self.counter = 0

  # (Text, ByteString) -> (Text, ByteString)
  def _processImage(self, processor, msg):
    title, in_poster_data = msg

    # save bytestring to disk
    tmp_file_name = tempfile.mktemp(suffix=".jpg")
    with open(tmp_file_name, "wb") as f:
      f.write(bytearray(in_poster_data))

    # apply filter
    processor(tmp_file_name)

    # load modified file as bytestring
    with open(tmp_file_name, "rb") as f:
      out_poster_data = f.read()
    os.remove(tmp_file_name)

    return (title, out_poster_data)

  def applyFilter(self, msg):
    filters = {
      'gotham' : mk_gotham,
      'kelvin' : mk_kelvin,
      'lomo' : mk_lomo,
      'nashville' : mk_nashville,
      'toaster' : mk_toaster,
      'random' : random.choice(self.random_funcs)
    }

    filter_name = self.args.get('filtertype', 'gotham')
    print("Applying filter {}".format(filter_name))
    return self._processImage(filters.get(filter_name), msg)


# The syntax threading and multiprocessing is very similar.

# Process - an instance of program, like
# multiple opened internet explorers

# + takes advantage of CPUs and cores
# + separate memory space - memory is not shared between processes
# + great for CPU bound processing
# + new process is started independently of other processes
# + processes are killable
# + one GIL(global interreter lock) for each process - avoids GIL limitation

# - heavy weight
# - starting a process is slower then starting tread
# - needs more memory
# - inter-process communication is more complicated

# You can check in your desktop system task manager, all the parallel
# python processes, when you execute this code
import concurrent.futures
import multiprocessing
import time
from Python.utilities.separate_text_stdout import SeparateText

def do_something_(seconds):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    print(f'Done Sleeping...{seconds}')

def do_something(number):
    return number**number**number

# for some reason multiprocessing must be guarded by '__name__ == '__main__'',
# check why
if __name__ == '__main__':
    sep = SeparateText()
    start = time.perf_counter()
    p1 = multiprocessing.Process(target=do_something_, args=(1,))
    p2 = multiprocessing.Process(target=do_something_, args=(1,))

    p1.start()
    p2.start()

    p1.join()
    p2.join()
    finish = time.perf_counter()

    print(f'Finished in {round(finish - start, 2)} second(s)')
    print(sep.separator())

    start = time.perf_counter()
    with concurrent.futures.ProcessPoolExecutor() as executor:
        numbers = [n for n in range(5, 15)]
        results = executor.map(do_something, numbers)

        # here you can get the results, when using the map function
        # for result in results:
        #     print(result)

    finish = time.perf_counter()
    print(f'Finished in {round(finish - start, 2)} second(s)')


import enum
from secrets import choice
from typing import List
import discord
from discord import app_commands
from discord.ext import commands
import mdtools
import os, uuid, requests, textwrap
import cocapi

class GeneralCog(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    async def __make_screenplay__ (self, interaction, ephemeral=False) -> None:
        if isinstance(interaction.channel, discord.Thread):
            # Get all messages from the channel as a list
            all_messages = [f"{message.content}"
                            async for message in interaction.channel.history(oldest_first=True)]

            # extract the code fence from each message individually, and create a new list
            fountain_md = []
            for message in all_messages:
                fences = mdtools.extract_code_fences(message)
                if len(fences) > 0:
                    fountain_md.append('\n\n'.join(fences))

            # join each line together with a line break.
            fountain_md_joined = '\n\n'.join(fountain_md)

            # make fountain file
            tempfilename = f"{interaction.channel.name}_{uuid.uuid4()}.fountain"
            f = open(tempfilename, "w")
            f.write(fountain_md_joined)
            f.close()

            if len(fountain_md) == 0:
                await interaction.response.send_message(
                    content="There appears to be no screenplay formatted items here.",
                    ephemeral=True)
            else:
                await interaction.response.send_message(
                    file=discord.File(tempfilename),
                    ephemeral=ephemeral)

            os.remove(tempfilename) if os.path.exists(tempfilename) else print("The file does not exist")
        else:
            await interaction.response.send_message(
                content="This only works in threads",
                ephemeral=True)

    async def skill_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:

        # get full skills list
        skills = requests.get(f"http://localhost:8000/api/skill").json()

        skills_to_return = [] # blank results

        if current == "":
            pass
        else:
            for skill in skills:

                # check if search is present in both skill name and specialization
                if current.lower() in skill['name'].lower() + skill['specialization'].lower():
                    name = skill['name']
                    specialization = f"" if skill['specialization'] == "" else f"[{skill['specialization']}]"
                    skills_to_return.append(
                        app_commands.Choice(
                            name=' '.join(filter(None, [name, specialization])),
                            value=int(skill['id']) ) )

        return skills_to_return[0:24]

    async def skillset_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:

        # get full skills list
        skillsets = cocapi.get_skillsets()

        skills_to_return = [] # blank results

        for skillset in skillsets:
            if current.lower() in skillset['name'].lower():
                skills_to_return.append(
                    app_commands.Choice(
                        name=skillset.get('name', ""),
                        value=skillset.get('id')))

        return skills_to_return[0:24]

    async def char_stats_autocomplete(self,
                                           interaction: discord.Interaction,
                                           current: str) -> List[app_commands.Choice[str]]:
        for_return = []

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        character = cocapi.character(player.get('character'))

        if character:

            character_stats = requests.get(f"http://localhost:8000/character-stats/{player.get('character')}").json()

            for_return = [app_commands.Choice(
                name=f"{stat_name} ({stat_value})",
                value=str(stat_name))
                    for stat_name, stat_value in character_stats.items()
                    if current == "" or current.lower() in stat_name.lower()]

        return for_return[0:24]

    async def char_skill_autocomplete(self,
                                           interaction: discord.Interaction,
                                           current: str) -> List[app_commands.Choice[str]]:
        for_return = []

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        character = cocapi.character(player.get('character'))

        if character:

            for_return = [app_commands.Choice(
                name=f"{skill.get('name')} ({skill.get('points')})",
                value=int(skill.get('id')))
                    for skill in character.get('characterskill_set', [])
                    if current.lower() in skill['name'].lower()]

        return for_return[0:24]

    async def attach_autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:

        # get full skills list
        characters = requests.get(f"http://localhost:8000/api/character/").json()
        for_return = []

        if current == "":
            # return list of characters.
            for character in characters:
                if character.get('player_fk'):
                    for_return.append(app_commands.Choice(
                        name=f"{character['investigator_name']} (TAKEN)",
                        value=str(character['id'])))
                else:
                    for_return.append(app_commands.Choice(
                        name=f"{character['investigator_name']}",
                        value=str(character['id'])))
        else:
            for character in characters:

                # check if search is present in both skill name and specialization
                if current.lower() in character['investigator_name'].lower():
                    for_return.append(app_commands.Choice(
                        name=character['investigator_name'],
                        value=str(character['id'])))

        return for_return[0:24]

    @app_commands.command(name="hello")
    async def hello(self, interaction: discord.Interaction) -> None:
        """ Say Hello to the bot """
        await interaction.response.send_message(
            content=f"Hi, {interaction.user.mention}, I'm Barnautomaton 3000. I was pieced back together at Miskatonic University and now my brain is in a jar!")

    @app_commands.command(name="skill_info")
    @app_commands.autocomplete(skill=skill_autocomplete)
    @app_commands.describe(
        skill="Skill info. Only top 25 are visible, type to find more.",
        hide="Hide result from channel? Only you will see this." )
    async def skill_info(self, interaction: discord.Interaction, skill: int, hide: bool = True) -> None:
        """ Get detailed information on a skill. """
        skill_json = requests.get(f"http://localhost:8000/api/skill/{skill}").json()
        category = f"" if skill_json['category'] == "" else f"[{skill_json['category']}]"
        specialization = f"" if skill_json['specialization'] == "" else f"[{skill_json['specialization']}]"
        name_row_list = [skill_json['name'], category, specialization]
        name_row = ' '.join(filter(None, name_row_list))

        embed = discord.Embed(title=f"{name_row} | {skill_json['base_points']}%", colour=discord.Colour(0x804423), description=skill_json['description'])

        await interaction.response.send_message(
            embed=embed,
            ephemeral=hide)

    @app_commands.command(name="make_screenplay")
    async def make_screenplay(self, interaction: discord.Interaction) -> None:
        """ Creates a screenplay from the current channel or thread. """
        await self.__make_screenplay__(interaction, ephemeral=True)

    @app_commands.command(name="fadeout")
    async def fadeout(self, interaction: discord.Interaction) -> None:
        """ End the scene, makes a screenplay and lock the thread. """
        await self.__make_screenplay__(interaction, ephemeral=False)
        if isinstance(interaction.channel, discord.Thread) : await interaction.channel.edit(archived=True, locked=True)

    @app_commands.command(name="template")
    async def template(self, interaction: discord.Interaction) -> None:
        """ Get a template for the screenplay format. """
        content = """
        ```
        NAME
        Dialogue.
        ```
        """

        await interaction.response.send_message(
            content=textwrap.dedent(content),
            ephemeral=True)

    @app_commands.command(name="character_create")
    @app_commands.describe(
        skillset="What preset character skillset would you like to attach?")
    @app_commands.autocomplete(skillset=skillset_autocomplete)
    async def character_create(self,
                               interaction: discord.Interaction,
                               investigator_name: str,
                               alias: str,
                               occupation: str,
                               birthplace: str,
                               sex: str,
                               age: int,
                               strength: int,
                               intelligence: int,
                               appearance: int,
                               dexterity: int,
                               education: int,
                               size: int,
                               constitution: int,
                               power: int,
                               luck: int,
                               hp: int,
                               magic: int,
                               san: int,
                               skillset: int,
                               ) -> None:
        """ Create a new character by inputting stats. """

        # get or add player to DB
        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        # TODO If the player already has a character, just make new character.  if the player does NOT, auto-connect it.

        # add new character to DB
        character = cocapi.create_character(json={
            "passcode": "",
            "investigator_name": investigator_name,
            "investigator_alias": alias,
            "occupation": occupation,
            "birthplace": birthplace,
            "sex": sex,
            "age": age,
            "strength": strength,
            "intelligence": intelligence,
            "appearance": appearance,
            "dexterity": dexterity,
            "education": education,
            "size": size,
            "constitution": constitution,
            "power": power,
            "luck": luck,
            "hp": hp,
            "magic": magic,
            "san": san,
            "san_daystart": san,
            "temporary_insanity": False,
            "indefinite_insanity": False,
            "dying_unconcious": False,
            "dying_majorwound": False,
            "location_fk": None,
            "player_fk": None
            })

        # edit the character by updating the skillset they're attached to.
        cocapi.attach_skillset_to_character(
            character_id=character.get('id'),
            skillset_id=skillset)

        embed = discord.Embed(title=f"{character.get('investigator_name')} created!",
                              colour=discord.Colour(0x804423))

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="character_attach")
    @app_commands.autocomplete(character=attach_autocomplete)
    @app_commands.describe(
        character="Which character are you taking control?")
    async def character_attach(self, interaction: discord.Interaction, character: str) -> None:
        """ Attach a character to yourself. """

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        # set default embed
        embed = discord.Embed(title=f"Character is already in use.", description=f"", colour=discord.Colour(0x804423))

        # get the chosen character
        character_json = cocapi.character(character)

        # does the chosen character have a player?
        if character_json.get('player_fk'):
            embed.title = f"Character is already in use."
        else:
            # does the player choosing have a character already?
            if player.get('character'):
                requests.get(f"http://localhost:8000/player/{interaction.user.id}/release_character").json()

            requests.get(f"http://localhost:8000/character/{character}/attach_player/{interaction.user.id}").json()
            new_character = cocapi.character(character)
            embed.title = f"You are now {new_character.get('investigator_name')}"

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="character_release")
    async def character_release(self, interaction: discord.Interaction) -> None:
        """ Releases the character you currenty have (if you have one). """
        success = requests.get(f"http://localhost:8000/player/{interaction.user.id}/release_character").json()

        embed = discord.Embed(title=f"{interaction.user.name} released a character: {success.get('success')}", colour=discord.Colour(0x804423))

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="character_change_name")
    @app_commands.describe(name="Character's full name",
                           alias="Character's shorthand name (as it appears in the script).")
    async def character_change_name(self, interaction: discord.Interaction, name: str = "", alias: str = "") -> None:
        """ Edit your name and alias. """
        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        if player.get('character'):
            character = cocapi.character(player.get('character'))

            name  = character.get('investigator_name') if name == "" else name
            alias = character.get('investigator_alias') if alias == "" else alias

            cocapi.change_stat(
                id=character.get('id'),
                json={"investigator_name": name,
                      "investigator_alias": alias })

            embed = discord.Embed(title=f"You are now {name} aka {alias}.", colour=discord.Colour(0x804423))

        else:
            embed = discord.Embed(title="You have no character attached. You are nobody.", colour=discord.Colour(0x804423))

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="character_sheet")
    async def character_sheet(self, interaction: discord.Interaction) -> None:
        """ View your character sheet. """

        def split(a, n):
            k, m = divmod(len(a), n)
            return (a[i*k+min(i, m):(i+1)*k+min(i+1, m)] for i in range(n))

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        embed = discord.Embed(title=f"Error?",
                              description="Error?",
                              colour=discord.Colour(0x804423))

        if player.get('character'):
            character = cocapi.character(player.get('character'))

            description = f"""
                {character.get('occupation')} | {character.get('age')} | {character.get('sex')}

                **STR** {character.get('strength')} | **INT** {character.get('intelligence')} | **APP** {character.get('appearance')} | **DEX** {character.get('dexterity')}
                **EDU** {character.get('education')} | **SIZ** {character.get('size')} | **CON** {character.get('constitution')} | **POW** {character.get('power')}
                **MOV** {character.get('move')} | **DMG BONUS** {character.get('damage_bonus')} | **BUILD** {character.get('build')}

                **HP** {character.get('hp')} / {character.get('hp_max')}
                **SAN** {character.get('san')} / {character.get('san_max')}  ||  **DAY**: {character.get('san_daystart')}
                **LUCK** {character.get('luck')}

                **MAGIC** {character.get('magic')} / {character.get('magic_max')}

                """

            embed = discord.Embed(

                title=f"{character.get('investigator_name')}",
                description=textwrap.dedent(description),
                colour=discord.Colour(0x804423))

            # split the skills list into 3 columns
            newlist = sorted(character.get('characterskill_set'), key=lambda d: d['name'])
            skill_columns = list(split(newlist, 3))

            for column in skill_columns:
                skills_list = ""
                for skill in column:
                    skills_list += f"{skill.get('name')} {skill.get('points')}\n"

                embed.add_field(name=f"SKILLS", value=f"{skills_list}", inline=True)

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="who_am_i")
    async def who_am_i(self, interaction: discord.Interaction) -> None:
        """ Who am I currently playing as? """

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        embed = discord.Embed(title=f"You are nobody.", colour=discord.Colour(0x804423))

        if player.get('character'):
            character = cocapi.character(player.get('character'))
            embed = discord.Embed(title=f"You are {character.get('investigator_name')}", colour=discord.Colour(0x804423))

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="change_stat")
    @app_commands.autocomplete(stat=char_stats_autocomplete)
    @app_commands.describe(
        stat="Characteristic modify.",
        modify="New characteristic value.")
    async def change_stat(self, interaction: discord.Interaction, stat: str, modify: int) -> None:
        """ Modify your character's characteristics. """

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        character = cocapi.character(player.get('character'))

        cocapi.change_stat(
            id=character.get('id'),
            json={stat: modify})
        embed = discord.Embed(title=f"{stat} now {modify}.", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="add_skill")
    @app_commands.autocomplete(skill=skill_autocomplete)
    @app_commands.describe(
        skill="Skill to add.")
    async def add_skill(self, interaction: discord.Interaction, skill: int) -> None:
        """ Add a skill to your character. """

        embed = discord.Embed(title=f"ERROR", colour=discord.Colour(0x804423))

        player = cocapi.get_or_create_player(json={
            "name": "",
            "discord_name": interaction.user.name,
            "discord_id": interaction.user.id })

        if player.get('character'):
            character = cocapi.character(id=player.get('character'))
            # apply the new fields to the skill
            cocapi.add_charskill(json={"skill_fk": skill,
                                    "character_fk": character.get('id') })

            embed = discord.Embed(title=f"Skill added.", colour=discord.Colour(0x804423))

        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="change_skill")
    @app_commands.autocomplete(skill=char_skill_autocomplete)
    @app_commands.describe(
        skill="Skill to check or modify.",
        name="Modify the name as it appears on your character sheet, e.g. Language(Other) could be Spanish.",
        stat="New skill value.",
        delete="Delete the selected skill from your character sheet.")
    async def change_skill(self, interaction: discord.Interaction, skill: int, name: str = "", stat: int = -1, delete: bool = False) -> None:
        """ Modify your character's skills. """

        charskill = requests.get(f"http://localhost:8000/api/characterskill/{skill}").json()

        # sets the stat to the default if its not included
        stat = stat if stat >= 0 else charskill.get('points')

        # set name to old name unless changed
        name = charskill.get('name') if name == "" else name

        # get the new experience points based on what the user enters
        difference = stat - charskill.get('points')
        new_experience = charskill.get('experience_points') + difference

        # apply the new fields to the skill
        new_skill = cocapi.change_charskill(
            id=skill,json={"name_override": name,
                           "experience_points": new_experience })

        # delete the skill if delete is selected
        if delete:
            cocapi.delete_charskill(id=skill)

        embed = discord.Embed(title=f"Skill: {new_skill.get('name')} now {new_skill.get('points')}", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="skill_favorite")
    @app_commands.autocomplete(skill=char_skill_autocomplete)
    @app_commands.describe(
        skill="Skill to favorite or unfavorite.",
        favorite="True to favorite, False to unfavorite.")
    async def skill_favorite(self, interaction: discord.Interaction, skill: int, favorite: bool) -> None:
        """ Add skill to favorites list. """

        # apply the new fields to the skill
        cocapi.change_charskill(id=skill, json={ "favorite": favorite })
        embed = discord.Embed(title=f"Skill Favorited: {favorite}.", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="admin_rolls_testing")
    async def admin_rolls_testing(self, interaction: discord.Interaction, totalmsgs: int) -> None:
        """ Testing for admin use only."""

        rolls = cocapi.get_rolls_history(interaction.channel.id, 4)
        embed = discord.Embed(title=f"check logs.", colour=discord.Colour(0x804423))
        await interaction.response.send_message(embed=embed, ephemeral=True)

    @app_commands.command(name="admin_testing")
    async def admin_testing(self, interaction: discord.Interaction, totalmsgs: int) -> None:
        """ Testing for admin use only."""

        embed = discord.Embed(title=f"You are not an admin.", colour=discord.Colour(0x804423))

        if interaction.user.id == 222234033650794497:
            async for message in interaction.channel.history(limit=totalmsgs):

                # reference = message.reference.message_id if message.reference is not None and not message.is_system else None

                # check if player is in the system, if not add.
                player = cocapi.get_or_create_player(json={
                    "name": "",
                    "discord_name": message.author.name,
                    "discord_id": message.author.id })

                print (player)

                # check if this particular channel is in the system, if not, add.
                channel = cocapi.get_or_create_channel(json={
                    "name": message.channel.name,
                    "channel_id": message.channel.id,
                    "parent_id": 0 })

                print (channel)

                # save the message to the db
                newmessage = cocapi.create_message(json={
                    "messagetime": message.created_at.isoformat(),
                    "discord_id": message.id,
                    "content": message.content,
                    "reply_msg_id": message.reference.message_id if message.reference is not None else None,
                    "player": player.get('id'),
                    "discordchannel": channel.get('id') })

                print (newmessage)

            embed = discord.Embed(title=f"Added messages to DB.", colour=discord.Colour(0x804423))

        await interaction.response.send_message(embed=embed, ephemeral=True)

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(GeneralCog(bot))


import datetime
import glob
import os
import sys

def main(argv):
    # pattern = r'T:\qraleg_service\build\CATS_logs\**\*'
    pattern = argv[0]
    for filename in glob.glob(pattern, recursive=True):
        if os.path.isfile(filename):
            print(filename)
            modified_date = datetime.datetime.fromtimestamp(os.path.getmtime(filename))
            today = datetime.datetime.today()
            if (today - modified_date).days > 7:
                try:
                    os.remove(filename)
                    print("The file is deleted.")
                except :
                    print("Warning: The file is unable to delete.")

if __name__ == '__main__':
    main(sys.argv[1:])


"""
Задача:
Выводить пользовалю по одному вопросу с вариантами ответов.
Просить пользователя ввести его вариант ответа.
Показать пользователю - правильно или нет.
Записать результат в файл. (пример в answers.txt)
"""

class Task:
    def __init__(self, question='', option1='', option2='', option3='', answer=''):
        self.__question = question
        self.__option1 = option1
        self.__option2 = option2
        self.__option3 = option3
        self.__answer = answer

    def set_question(self, question):
        self.__question = question

    def get_question(self):
        return self.__question

    def set_option1(self, option1):
        self.__option1 = option1

    def set_option2(self, option2):
        self.__option2 = option2

    def set_option3(self, option3):
        self.__option3 = option3

    def set_answer(self, answer):
        self.__answer = answer

    def get_answer(self):
        return self.__answer

    def __repr__(self):
        return f"\n{self.__question}{self.__option1}{self.__option2}{self.__option3}"

def get_exam():
    correct = 0
    questions = []
    with open('questions', 'r', encoding='UTF-8') as questions_file:
        text = questions_file.readlines()
        for i, line in enumerate(text):
            if i % 5 == 0:
                task = Task()
            if i in [*range(0, 50, 5)]:
                task.set_question(line)
            elif i in [*range(1, 50, 5)]:
                task.set_option1(line)
            elif i in [*range(2, 50, 5)]:
                task.set_option2(line)
            elif i in [*range(3, 50, 5)]:
                task.set_option3(line)
            elif i in [*range(4, 50, 5)]:
                task.set_answer(int(line.replace("Answer: ", "")))
            if i % 5 == 0:
                questions.append(task)

    with open('answers', 'w', encoding='UTF-8') as answers_file:
        answer = None
        for q in questions:
            print(q)
            answers_file.write(q.get_question())
            try:
                answer = int(input('Enter your answer:\n>>'))
            except ValueError as e:
                print(e)
                print("Entered answer in not an Integer")
                answers_file.write("Entered answer in not an Integer\n")
            if answer == q.get_answer():
                correct += 1
                print(f"Answer {{{answer}}} is CORRECT")
                answers_file.write(f"Answer {{{answer}}} is CORRECT\n\n")

            else:
                print(f"Answer {{{answer}}} is WRONG")
                print(f"Correct answer is - {q.get_answer()}")
                answers_file.write(f"Answer {{{answer}}} is WRONG\n\n")
        print(f'\nAmount of correct answers is {{{correct}}} from 10')
        print(f"Percent is {correct * 10}%")

if __name__ == '__main__':
    get_exam()


"""
https://www.acmicpc.net/problem/1303

전쟁-전투

1303
"""

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)

N,M = map(int,input().split()) # N 가로 M 세로

# borad = [[0 for _ in range(N)] for _ in range(M)]
borad = []
visited = [[False for _ in range(N)] for _ in range(M)]
for _ in range(M):
    borad.append(input().rstrip())

def dfs(x,y,ally):
    if(visited[x][y] == True):
        return 0
    visited[x][y] = True
    cnt = 1

    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]

        if 0 <= nx < M and 0 <= ny < N and ally == borad[nx][ny] and visited[nx][ny] == False:
            cnt += dfs(nx,ny,ally)

    return cnt
W = 0 # 아군
B = 0 # 적군

for y in range(N):
    for x in range(M):
        if(visited[x][y] == False):
            if borad[x][y] == 'W' :
                W += dfs(x,y,'W') ** 2
            else:
                B += dfs(x,y,'B') ** 2

print(W, end=" ")
print(B)
#print(borad[0][4])