from astroid import Attribute

from pylint.checkers import BaseChecker
from pylint.interfaces import IAstroidChecker

class FunctionOrderChecker(BaseChecker):
    __implements__ = IAstroidChecker
    name = "function-order"
    priority = -1
    msgs = {
        "R1004": ("Function is out of order", "wrong-function-order",
                  "Function should be defined after its caller"),
        "R1005": ("Method is out of order", "wrong-method-order",
                  "Method should be defined after its caller")
    }

    def __init__(self, linter):
        super().__init__(linter)
        self.function_definitions = {}
        self.function_stack = []

    def visit_functiondef(self, node):
        self.function_stack.append(node.name)
        if len(self.function_stack) <= 1:
            self.function_definitions[node.name] = {'called': False, 'method': node.is_method(), 'node': node}

    def visit_call(self, node):
        callee_name = node.func.attrname if isinstance(node.func, Attribute) else node.func.name
        callee = self.function_definitions.get(callee_name, None)
        if callee and not callee['called']:
            callee['called'] = True
            if callee['method']:
                self.add_message('wrong-method-order', node=callee['node'])
            else:
                self.add_message('wrong-function-order', node=callee['node'])

    def leave_functiondef(self, _):
        self.function_stack.pop()


# lst=[]
# f=open("words.txt").readlines()[::-1]
# for i in f:
#     lst.append(i)
# output="".join(lst)
# open("baraks.txt","w").write(output)
# ------------------------------------------
lst=[]
f=open("words.txt").readlines()
for i in f:
    lst.append(i[::-1])
output="".join(lst)
open("kalamebaraks.txt","w").write(output)


from absl.testing import absltest
from learned_optimization.optimizers import test_utils as opt_test_utils
from learned_optimization.research.general_lopt import prefab

class PrefabLOptTest(absltest.TestCase):

  def test_lopt(self):
    opt_test_utils.smoketest_optimizer(prefab.LearnedOptimizer(100))

  def test_lopt_accum(self):
    opt = prefab.LearnedOptimizer(100, max_training_steps=10)
    self.assertEqual(opt.opt.num_average, 10)
    opt_test_utils.smoketest_optimizer(opt)

  def test_lopt_wd(self):
    opt = prefab.LearnedOptimizer(100, weight_decay=1e-6)
    opt_test_utils.smoketest_optimizer(opt)

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


from discord.ext import commands
from aurora_secrets import *
from aurora_lists import *
import asyncio
import discord
import random

class Games(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(aliases=['mini_games'])
    async def games(self, ctx):
        bbo = discord.Embed(title="Mini Games", description="Choose which one you want to play!", color=0xa3ff61)
        bbo.add_field(name="🏀 ``.bbgame``", value="basketball, simple shooting game", inline=False)
        bbo.add_field(name=":soccer: ``.fbgame``", value="football, simple kicking game", inline=False)
        bbo.add_field(name="<:greenball:830467077058854922> ``.blgame``", value="bowling, simple bowling game", inline=False)
        bbo.set_thumbnail(url="https://media.discordapp.net/attachments/807511480878497806/832282579050823711/aurora_games.png")

        await ctx.send(embed=bbo)

    @commands.command()
    async def bbgame(self, ctx):
        bbem = discord.Embed(title="Game Info", description="**React** to the appropriate power level to make a shot based on your intuition", color=random.choice(colors))
        bbem.add_field(name="Start Game: ``.shoot``", value="_ _", inline=False)
        bbem.add_field(name="Power levels (correspond to the reactions):", value="_ _", inline=False)
        bbem.set_image(url='https://media.discordapp.net/attachments/807511480878497806/819109874897911848/brown_square_red_square_orange_square_yellow_square_green_square_blue_square_white_large_square_.png')

        await ctx.send(embed=bbem)

    @commands.command(aliases=["basketball"])
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def shoot(self, ctx):
        x = random.randint(1, 8)
        coloremojis = {"🟫": 7, "🟥": 6, "🟧": 5, "🟨": 4, "🟩": 3, "🟦": 2, "⬜": 1}
        b = await ctx.reply("<:bbball:830475864172789800>" + ("<:transparent:830476759463231498>" * x) + ':wastebasket:', mention_author=False)
        for color in coloremojis.keys():
            await b.add_reaction(color)

        def check(reaction, user):
            return user == ctx.author and str(reaction.emoji) in coloremojis.keys()

        reaction, user = await self.bot.wait_for("reaction_add", check=check)

        a = int(x - coloremojis[str(reaction.emoji)])

        await b.edit(content="<:bbball:830475864172789800>" + "<:transparent:830476759463231498>" * a + ':wastebasket:')

        if a == 0:
            await b.edit(content="<:yay:830336856415666187>")
            await ctx.send(f"{ctx.author.mention}, Nice Shot! <a:jedipepe:796237771990761532> type ``.shoot`` to play again")

        elif a > 0:
            await b.edit(content="<:bbball:830475864172789800>" + "<:transparent:830476759463231498>" * a + ":wastebasket:")
            await ctx.send(f"{ctx.author.mention}, oh no! you're too short <a:wutpepe:796237684170424351> type ``.shoot`` to play again")

        elif a < 0:
            await b.edit(content=':wastebasket:' + "<:transparent:830476759463231498>" + "<:bbball:830475864172789800>")
            await ctx.send(f"{ctx.author.mention}, oh no! you went past the basket <a:wutpepe:796237684170424351> type ``.shoot`` to play again")

    @commands.command()
    async def fbgame(self, ctx):
        fb = discord.Embed(title="Game Info", description="the goal keeper can  move anywhere! use your luck...\nlist of choices to decide where the ball goes (use after command):\n ``left`` ``middle`` ``right``", color=random.choice(colors))
        fb.add_field(name="Start Game: ``.kickball``", value="_ _")
        await ctx.send(embed=fb)

    @commands.command(aliases=["kb"])
    @commands.cooldown(1, 3, commands.BucketType.user)
    async def kickball(self, ctx):
        x = random.randint(0, 2)
        goalie = ":man_standing:\n"
        goal = ":goal::goal::goal:\n"
        goal2 = ":goal::goal:"
        goalmid = ":goal::soccer::goal:\n"
        ball = ":soccer:"
        plane = goal+"<:transparent:830476759463231498>"*x+goalie+ball
        f = await ctx.reply(plane, mention_author=False)

        def check(message):

            return ctx.author == message.author and ctx.channel == message.channel

        ans = await self.bot.wait_for('message', check=check)

        if ans.author == ctx.message.author:

            if ans.content.lower() == "right":
                y = random.randint(1, 3)
                r = random.randint(1, 2)
                if y == 3:
                    newplane = goal + "<:transparent:830476759463231498>" * 2 + goalie + "<:transparent:830476759463231498>"*2 + ball

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+ww + " lol the goalie blocked your kick")
                    return

                elif y == 1:
                    newplane = goal2+ball + "\n" + "<:transparent:830476759463231498>" + goalie

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+vb + " you made it into the goal")
                    return

                elif y == 2:
                    newplane = goal2 + ball + "\n" + "<:transparent:830476759463231498>" * 1 + goalie

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} " + vb + " you made it into the goal")
                    return

                if r == 1:
                    newplane = goal + "<:transparent:830476759463231498>" * 2 + goalie + "<:transparent:830476759463231498>" * 2 + ball

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} " + ww + " lol the goalie blocked your kick")
                    return

                if x == 2:
                    newplane = goal + "<:transparent:830476759463231498>" * 2 + goalie + "<:transparent:830476759463231498>"*2 + ball
                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+ww + " lol the goalie blocked your kick")

                    return

                return

            if ans.content.lower() == "left":
                y = random.randint(1, 3)
                r = random.randint(1, 2)
                if y == 1:
                    newplane = goal + goalie + ball

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+ww + " lol the goalie blocked your kick")
                    return

                elif y == 3:
                    newplane = ball+goal2 + "\n" + "<:transparent:830476759463231498>" * 2 + goalie

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+vb + " you made it into the goal")
                    return

                elif y == 2:
                    newplane = ball+goal2 + "\n" + "<:transparent:830476759463231498>" * 1 + goalie

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+vb + " you made it into the goal")
                    return

                if r == 1:
                    newplane = goal + goalie + ball
                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+ww + " lol the goalie blocked your kick")
                    return

                if x == 0:
                    newplane = goal + goalie + ball

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+ww + " lol the goalie blocked your kick")
                    return

                return

            if ans.content.lower() == "middle":
                y = random.randint(1, 3)
                r = random.randint(1, 2)
                if y == 1:
                    newplane = goalmid + goalie

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} " + vb + " you made it into the goal")
                    return

                elif y == 3:
                    newplane = goalmid + "<:transparent:830476759463231498>"*2 + goalie

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} " + vb + " you made it into the goal")
                    return

                elif y == 2:
                    newplane = goal + "<:transparent:830476759463231498>"*1 + goalie + "<:transparent:830476759463231498>"*1 + ball

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+ww + " lol the goalie blocked your kick")
                    return

                if r == 1:
                    newplane = goal + goalie + ball

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} " + ww + " lol the goalie blocked your kick")
                    return

                if x == 1:
                    newplane = goal + "<:transparent:830476759463231498>" + goalie + "<:transparent:830476759463231498>" + ball

                    await f.edit(content=newplane)
                    await ctx.send(f"{ctx.author.mention} "+ww + " lol the goalie blocked your kick")

                return

            if ans.content.lower() == ".kickball":
                em = discord.Embed(title="", description="", colour=0xffb12b)
                em.add_field(name="ERROR", value="Please respond with the following options next time\n``left``, ``middle``, ``right``\n Support Server: [Join](https://discord.gg/G9vTrsV4aG)")

                await ctx.send(embed=em)
                return

            else:
                em = discord.Embed(title="", description="", colour=0xffb12b)
                em.add_field(name="ERROR",value="Please respond with the following options next time\n``left``, ``middle``, ``right`` & ``.kickball`` to run the command again\n Support Server: [Join](https://discord.gg/G9vTrsV4aG)")

                await ctx.send(embed=em)
                return

    @commands.command()
    async def blgame(self, ctx):
        bl = discord.Embed(title="Game Info", description="Choose an appropriate power level to knock down all the pins\n(type the number listed below)", color=random.choice(colors))
        bl.add_field(name="Start Game: ``.bowl``", value="_ _", inline=False)
        bl.add_field(name="power levels list:", value="1, 2, 3, 4, 5, 6", inline=False)

        await ctx.send(embed=bl)

    @commands.command()
    async def bowl(self, ctx):
        powerlevel = "<:12:831762862124171275><:34:831762862304526356><:56:831762862388936755>"
        win = f"{ctx.author.mention} <a:4919pepelaugh:830345716437352448> You knocked all the pins! "
        lose = f"{ctx.author.mention} <a:2813pepeexit:830345717478326273> lol your too short!"
        bounds = f"{ctx.author.mention} " + ww + "yo slow down the ball went out of bounds"
        emoji = ["<:purpleball:830467076291821638>", "<:redball:830467075575119962>","<:greenball:830467077058854922>", "<:blueball:830467076455137321>"]
        em = random.choice(emoji)
        plane = "<:pin:830469397465792512><:pin:830469397465792512><:pin:830469397465792512>\n      <:pin:830469397465792512><:pin:830469397465792512>\n             <:pin:830469397465792512>"
        broken = f"<:pin:830469397465792512><:pin:830469397465792512><:pin:830469397465792512>\n      <:pin:830469397465792512><:pin:830469397465792512>\n             <:fallenpin3:830469397671182346>{em}"
        broken2 = f"<:pin:830469397465792512><:pin:830469397465792512><:pin:830469397465792512>\n      <:fallenpin2:830469397000486963><:fallenpin1:830469397092892742>{em}\n             <:fallenpin3:830469397671182346>"
        broken3 = "<:fallenpin2:830469397000486963><:fallenpin3:830469397671182346><:fallenpin1:830469397092892742>\n      <:fallenpin2:830469397000486963><:fallenpin1:830469397092892742>\n             <:fallenpin3:830469397671182346>"
        x = random.randint(1, 6)
        newplane = plane + "\n<:transparent:830476759463231498>" * x + "\n" + "             "+em+"\n"*2+powerlevel
        b = await ctx.reply(newplane, mention_author=False)

        def check(message):

            return ctx.author == message.author and ctx.channel == message.channel

        ans = await self.bot.wait_for('message', check=check)

        if ans.author == ctx.message.author:
            if ans.content.lower() == "1":
                if 1 == x:
                    await b.edit(content=plane + "\n"*2 + "             " + em)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken2)
                    await asyncio.sleep(0.5)
                    await b.edit(content="<:transparent:830476759463231498>" + em + "\n" + broken3)
                    await ctx.send(win)
                elif 1 < x:
                    await b.edit(content=plane + "\n"*4 + "             " + em)
                    await ctx.send(lose)

            elif ans.content.lower() == "2":
                if 2 == x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken2)
                    await asyncio.sleep(0.5)
                    await b.edit(content="<:transparent:830476759463231498>" + em + "\n" + broken3)
                    await ctx.send(win)

                elif 2 < x:
                    await b.edit(content=plane + "\n"*2 + "             " + em)
                    await ctx.send(lose)

            elif ans.content.lower() == "3":
                if 3 == x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken2)
                    await asyncio.sleep(0.5)
                    await b.edit(content="<:transparent:830476759463231498>" + em + "\n" + broken3)
                    await ctx.send(win)

                elif 3 < x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await ctx.send(lose)

                elif 3 > x:
                    await b.edit(content="<:transparent:830476759463231498>"+em+"\n"*2+plane)
                    await ctx.send(bounds)

            elif ans.content.lower() == "4":
                if 4 == x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken2)
                    await asyncio.sleep(0.5)
                    await b.edit(content="<:transparent:830476759463231498>" + em + "\n" + broken3)
                    await ctx.send(win)

                elif 4 < x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await ctx.send(lose)

                elif 4 > x:
                    await b.edit(content="<:transparent:830476759463231498>"+em+"\n"*3+plane)
                    await ctx.send(bounds)

            elif ans.content.lower() == "5":
                if 5 == x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken2)
                    await asyncio.sleep(0.5)
                    await b.edit(content="<:transparent:830476759463231498>" + em + "\n" + broken3)
                    await ctx.send(win)

                elif 5 < x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await ctx.send(lose)

                elif 5 > x:
                    await b.edit(content="<:transparent:830476759463231498>"+em+"\n"*4+plane)
                    await ctx.send(bounds)

            elif ans.content.lower() == "6":
                if 6 == x:
                    await b.edit(content=plane + "\n"*3 + "             " + em)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken)
                    await asyncio.sleep(0.5)
                    await b.edit(content=broken2)
                    await asyncio.sleep(0.5)
                    await b.edit(content="<:transparent:830476759463231498>" + em + "\n" + broken3)
                    await ctx.send(win)

                elif 6 > x:
                    await b.edit(content="<:transparent:830476759463231498>"+em+"\n"*6+plane)
                    await ctx.send(bounds)
            else:
                if ans.content.lower() == ".bowl":
                    em = discord.Embed(title="", description="", colour=0xffb12b)
                    em.add_field(name="ERROR", value="Please respond with the following options next time\n``1``, ``2``, ``3``, ``4``, ``5``, ``6``\nrun ``.blgame`` for more info\nSupport Server: [Join](https://discord.gg/G9vTrsV4aG)")
                    await ctx.send(embed=em)
                    return
                else:
                    em = discord.Embed(title="", description="", colour=0xffb12b)
                    em.add_field(name="ERROR", value="Please respond with the following options next time\n``1``, ``2``, ``3``, ``4``, ``5``, ``6`` & ``.bowl`` to run the command again\nrun ``.blgame`` for more info\n Support Server: [Join](https://discord.gg/G9vTrsV4aG)")
                    await ctx.send(embed=em)
                    return

async def setup(bot):
    await bot.add_cog(Games(bot))


from collections import abc
from distutils import bcppcompiler
from re import A

result = []
def backTrack(wrd,result):
    if len(wrd) > 3:
        return
    elif len(wrd) == 2:
        result += [wrd]
    else:

        for i in range(len(wrd)):
            backTrack(wrd[:i] + wrd[i+1:],result)

backTrack("abcd",result)
print(result)

    #         abc
    #     ab      bc
    #  a      b  b    c

#   a   b   c   d


#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# Get POS2id table
word = set()
pos = set()
data_dir = ['./train.conllu', './dev.conllu', './test.conllu']
for dataset in data_dir:
    with open(dataset, encoding='utf-8') as fin:
        for line in fin:
            line = line.strip()
            if line != '':
                line = line.split('\t')
                if line[3] not in pos:
                    pos.add(line[3])
                word.add(line[1])
fout = open('pos2id.table', 'w')
pos = list(pos)
for item in pos:
    fout.write(item+'\n')
fout.close()

# Get word2id table
emb_dir = 'embedding/embedding.50'
word_table = './word2id.table'
emb_out = 'embedding/emb.50'
fout = open(word_table, 'bw')
fout1 = open(emb_out, 'w')
fout.write('<POS>\n<UNK>\n'.encode('utf-8'))
fout1.write(' '.join(['0.000000']*50)+'\n'+' '.join(['0.000000']*50)+'\n')
with open(emb_dir, encoding='utf-8') as fin:
    for idx, line in enumerate(fin):
        if idx > 0:
            line = line.strip().split(' ')
            if line[0] in word:
                fout.write((line[0]+'\n').encode('utf-8'))
                fout1.write(' '.join(line[1:])+'\n')
fout.close()
fout1.close()

fout = open('./word2id.random.table', 'bw')
word = set()
for dataset in data_dir:
    if dataset.startswith('./train'):
        with open(dataset, encoding='utf-8') as fin:
            for line in fin:
                line = line.strip()
                if line != '':
                    line = line.split('\t')
                    word.add(line[1])
word = list(word)
for item in word:
    fout.write((item+'\n').encode('utf-8'))
fout.close()

max_len = 0
# Transform to the form framework supports
for dataset in data_dir:
    idx = []
    word = []
    upos = []
    xpos = []
    head = []
    length = 0
    fout = open(dataset.split('.conllu')[0]+'.new', 'bw')
    with open(dataset, encoding='utf-8') as fin:
        for line in fin:
            line = line.strip()
            if line != '':
                line = line.split('\t')
                idx.append(line[0])
                word.append(line[1])
                upos.append(line[3])
                xpos.append(line[4])
                head.append(line[6])
                length += 1
            else:
                fout.write((' '.join(idx)+'\t').encode('utf-8'))
                fout.write((' '.join(word)+'\t').encode('utf-8'))
                fout.write((' '.join(upos)+'\t').encode('utf-8'))
                fout.write((' '.join(xpos)+'\t').encode('utf-8'))
                fout.write((' '.join(head)+'\t').encode('utf-8'))
                fout.write((str(length)+'\n').encode('utf-8'))
                max_len = length if length > max_len else max_len
                idx = []
                word = []
                upos = []
                xpos = []
                head = []
                length = 0
    fout.close()

print(max_len)


from __future__ import print_function
import numpy as np
import argparse
import torch
import torch.optim as optim
from torch.autograd import Variable
from sklearn.metrics import precision_score,f1_score
from EvoMIL.Models.model import Attention,GatedAttention
import pandas as pd
from evaluation import aucscore,get_confusion,results2CSV_test

# test settings
parser = argparse.ArgumentParser(description='PyTorch PreTLM-MIL')
parser.add_argument('--epochs', type=int, default=150, metavar='N',
                    help='number of epochs to train (default: 20)')
parser.add_argument('--lr', type=float, default=0.0005, metavar='LR',
                    help='learning rate (default: 0.0005)')
parser.add_argument('--reg', type=float, default=10e-5, metavar='R',
                    help='weight decay')
parser.add_argument('--seed', type=int, default=1, metavar='S',
                    help='random seed (default: 1)')
parser.add_argument('--no-cuda', action='store_true', default=False,
                    help='disables CUDA training')
parser.add_argument('--model', type=str, default='attention', help='Choose b/w attention and gated_attention')

"""
We make changes on Attention_based MIL (Copyright © 2018 ilse.maximilian@gmail.com.) to test viral protein embeddings.
"""
args = parser.parse_args()
args.cuda = not args.no_cuda and torch.cuda.is_available()

torch.manual_seed(args.seed)
if args.cuda:
    torch.cuda.manual_seed(args.seed)
    print('\n GPU is ON!')

print('Load Train and Test Set')
loader_kwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}

print('Init Model')
if args.model=='attention':
    model = Attention()
elif args.model=='gated_attention':
    model = GatedAttention()
if args.cuda:
    model.cuda()

optimizer = optim.Adam(model.parameters(), lr=args.lr, betas=(0.9, 0.999), weight_decay=args.reg)

if __name__ == "__main__":
    # Eukaryota/Prokaryote
    output='../Results/euk_binary/'
    input_data_path="../Data/examples/euk_5fold_cv/"
    # virus_pos_neg_path= input+'virus_'
    virus_host = pd.read_csv(input_data_path+'hostname_count.csv')
    length=virus_host.shape[0]
    for m in [4]:
        hostname=virus_host.iloc[m,0]
        test_loader=torch.load(input_data_path + hostname + '_test_loader')
        for j in range(5):
                model.load_state_dict(torch.load(output + hostname+'_model.'+str(j+1)))
                with torch.no_grad():
                    test_loss=0.
                    test_error=0.
                    test_acc=0.
                    #start validation
                    instance_label_list=[]
                    label_list=[]
                    predicted_label_list=[]
                    pred=[]
                    Y_hats=[]
                    for batch_idx, (dataset,ids,label) in enumerate(test_loader):
                            bag_label = label.gt(0)
                            label_list.append(bag_label.squeeze(0).tolist())
                            data = dataset.unsqueeze(0)
                            data = dataset.view(ids.shape[1], dataset.shape[1])

                            if args.cuda:
                                data, bag_label = data.cuda(), bag_label.cuda()
                            data, bag_label = Variable(data), Variable(bag_label)
                            temp=ids
                            if(label==1):
                                for i in range(len(temp[0,])):
                                    temp[0,i]=1
                            else:
                                for i in range(len(temp[0,])):
                                    temp[0,i]=-1
                            instance_labels = temp.gt(0)
                            loss,acc,attention_weights,Y_prob,Y_hat = model.calculate_objective(data, bag_label)
                            error, predicted_label = model.calculate_classification_error(data, bag_label)
                            test_loss += loss.data[0]
                            test_acc += acc
                            # test_error += error
                            Y_prob_value=Y_prob.cpu().squeeze(0).squeeze(0).tolist()
                            pred.append(Y_prob_value)
                            instance_label_list.append(instance_labels)
                            Y_hats.append(Y_hat.item())
                            predicted_label_list.append(int(predicted_label.cpu().data.numpy()[0][0]))

                test_loss /= len(test_loader)
                test_acc /= len(test_loader)
                # test_error /= len(test_loader)
                test_loss=test_loss.cpu().numpy()[0]
                label_list=torch.tensor(label_list).detach()
                label_list_int=np.array(label_list, dtype='int').tolist()
                Y_hats_int=list(map(int,Y_hats))
                acc,spec,sens = get_confusion(torch.tensor(predicted_label_list), torch.tensor(label_list))
                # calculating precision and reall
                f1= f1_score(label_list_int,Y_hats_int)
                prec = precision_score(label_list_int, Y_hats_int)
                # recall = recall_score(label_list_int, pred)
                auc_score= aucscore(pred, label_list_int)

                csvfile=output+'virus_testset_5fold_cross_validation_epoch150_10.csv'
                results= {'Hostname': hostname,'AUC':str(round(np.array(auc_score).mean(),4)),'Accuracy':round(np.array(acc).mean(),4),'f1':round(np.array(f1).mean(),4),'spec':round(np.array(spec).mean(),4), 'sens':round(np.array(sens).mean(),4),'prec':round(np.array(prec).mean(),4)}
                results2CSV_test(results, hostname,csvfile)


# Documentation:
#   qute://help/configuring.html
#   qute://help/settings.html

# Disable autoconfig
config.load_autoconfig(False)

# Require a confirmation before quitting the application.
# Type: ConfirmQuit
# Valid values:
#   - always: Always show a confirmation.
#   - multiple-tabs: Show a confirmation if multiple tabs are opened.
#   - downloads: Show a confirmation if downloads are running
#   - never: Never show a confirmation.
c.confirm_quit = ['downloads']

# Additional arguments to pass to Qt, without leading `--`. With
# QtWebEngine, some Chromium arguments (see
# https://peter.sh/experiments/chromium-command-line-switches/ for a
# list) will work.
# Type: List of String
c.qt.args = [
    'enable-gpu-rasterization'
]

# Allow websites to request geolocations.
# Type: BoolAsk
# Valid values:
#   - true
#   - false
#   - ask
c.content.geolocation = False

c.content.pdfjs = True

# Value to send in the `DNT` header. When this is set to true,
# qutebrowser asks websites to not track your identity. If set to null,
# the DNT header is not sent at all.
# Type: Bool
c.content.headers.do_not_track = True

c.content.cookies.accept = "no-3rdparty"

c.content.canvas_reading = True

c.content.dns_prefetch = True

c.content.webrtc_ip_handling_policy = "default-public-interface-only"

# Allow JavaScript to read from or write to the clipboard. With
# QtWebEngine, writing the clipboard as response to a user interaction
# is always allowed.
# Type: Bool
c.content.javascript.can_access_clipboard = False

# Allow JavaScript to open new tabs without user interaction.
# Type: Bool
c.content.javascript.can_open_tabs_automatically = False

# Enable JavaScript.
# Type: Bool
c.content.javascript.enabled = True

# Enable JavaScript.
# Type: Bool
config.set('content.javascript.enabled', True, 'file://*')

# Enable JavaScript.
# Type: Bool
config.set('content.javascript.enabled', True, 'chrome://*/*')

# Enable JavaScript.
# Type: Bool
config.set('content.javascript.enabled', True, 'qute://*/*')

# Allow locally loaded documents to access remote URLs.
# Type: Bool
c.content.local_content_can_access_remote_urls = False

# Allow locally loaded documents to access other local URLs.
# Type: Bool
c.content.local_content_can_access_file_urls = True

# Enable support for HTML 5 local storage and Web SQL.
# Type: Bool
c.content.local_storage = True

# Enable plugins in Web pages.
# Type: Bool
c.content.plugins = True

# Draw the background color and images also when the page is printed.
# Type: Bool
c.content.print_element_backgrounds = True

# Open new windows in private browsing mode which does not record
# visited pages.
# Type: Bool
c.content.private_browsing = False

# Enable WebGL.
# Type: Bool
c.content.webgl = True

# Monitor load requests for cross-site scripting attempts. Suspicious
# scripts will be blocked and reported in the inspector's JavaScript
# console. Enabling this feature might have an impact on performance.
# Type: Bool
c.content.xss_auditing = True

# What to display in the download filename input.
# Type: String
# Valid values:
#   - path: Show only the download path.
#   - filename: Show only download filename.
#   - both: Show download path and filename.
c.downloads.location.suggestion = 'filename'

# Where to show the downloaded files.
# Type: VerticalPosition
# Valid values:
#   - top
#   - bottom
c.downloads.position = 'top'

# Duration (in milliseconds) to wait before removing finished downloads.
# If set to -1, downloads are never removed.
# Type: Int
c.downloads.remove_finished = 8000

# Automatically enter insert mode if an editable element is focused
# after loading the page.
# Type: Bool
c.input.insert_mode.auto_load = True

# Leave insert mode if a non-editable element is clicked.
# Type: Bool
c.input.insert_mode.auto_leave = True

# Duration (in milliseconds) to show messages in the statusbar for. Set
# to 0 to never clear messages.
# Type: Int
c.messages.timeout = 8000

# Enable smooth scrolling for web pages. Note smooth scrolling does not
# work with the `:scroll-px` command.
# Type: Bool
c.scrolling.smooth = True

# Languages to use for spell checking. You can check for available
# languages and install dictionaries using scripts/dictcli.py. Run the
# script with -h/--help for instructions.
# Type: List of String
# Valid values:
#   - af-ZA: Afrikaans (South Africa)
#   - bg-BG: Bulgarian (Bulgaria)
#   - ca-ES: Catalan (Spain)
#   - cs-CZ: Czech (Czech Republic)
#   - da-DK: Danish (Denmark)
#   - de-DE: German (Germany)
#   - el-GR: Greek (Greece)
#   - en-AU: English (Australia)
#   - en-CA: English (Canada)
#   - en-GB: English (United Kingdom)
#   - en-US: English (United States)
#   - es-ES: Spanish (Spain)
#   - et-EE: Estonian (Estonia)
#   - fa-IR: Farsi (Iran)
#   - fo-FO: Faroese (Faroe Islands)
#   - fr-FR: French (France)
#   - he-IL: Hebrew (Israel)
#   - hi-IN: Hindi (India)
#   - hr-HR: Croatian (Croatia)
#   - hu-HU: Hungarian (Hungary)
#   - id-ID: Indonesian (Indonesia)
#   - it-IT: Italian (Italy)
#   - ko: Korean
#   - lt-LT: Lithuanian (Lithuania)
#   - lv-LV: Latvian (Latvia)
#   - nb-NO: Norwegian (Norway)
#   - nl-NL: Dutch (Netherlands)
#   - pl-PL: Polish (Poland)
#   - pt-BR: Portuguese (Brazil)
#   - pt-PT: Portuguese (Portugal)
#   - ro-RO: Romanian (Romania)
#   - ru-RU: Russian (Russia)
#   - sh: Serbo-Croatian
#   - sk-SK: Slovak (Slovakia)
#   - sl-SI: Slovenian (Slovenia)
#   - sq: Albanian
#   - sr: Serbian
#   - sv-SE: Swedish (Sweden)
#   - ta-IN: Tamil (India)
#   - tg-TG: Tajik (Tajikistan)
#   - tr-TR: Turkish (Turkey)
#   - uk-UA: Ukrainian (Ukraine)
#   - vi-VN: Vietnamese (Viet Nam)
c.spellcheck.languages = []

# Position of the tab bar.
# Type: Position
# Valid values:
#   - top
#   - bottom
#   - left
#   - right
c.tabs.position = 'top'

# When to show the tab bar.
# Type: String
# Valid values:
#   - always: Always show the tab bar.
#   - never: Always hide the tab bar.
#   - multiple: Hide the tab bar if only one tab is open.
#   - switching: Show the tab bar when switching tabs.
c.tabs.show = 'switching'

# Search engines which can be used via the address bar. Maps a search
# engine name (such as `DEFAULT`, or `ddg`) to a URL with a `{}`
# placeholder. The placeholder will be replaced by the search term, use
# `{{` and `}}` for literal `{`/`}` signs. The search engine named
# `DEFAULT` is used when `url.auto_search` is turned on and something
# else than a URL was entered to be opened. Other search engines can be
# used by prepending the search engine name to the search term, e.g.
# `:open google qutebrowser`.
# Type: Dict
c.url.searchengines = {
    'DEFAULT': 'https://duckduckgo.com/?q={}',
    'y': 'https://youtube.com/results?search_query={}',
    'w': 'https://en.wikipedia.org/w/index.php?search={}',
    'aw': 'https://wiki.archlinux.org/index.php?search={}',
    'g': 'https://www.google.com/search?source=&q={}',
    'gi': 'https://www.google.com/search?tbm=isch&q={}',
    'aur': 'https://aur.archlinux.org/packages/?O=0&K={}',
    'c': 'https://en.cppreference.com/w/cpp/keyword/{}',
    'r': 'https://doc.rust-lang.org/stable/std/?search={}'
}

c.url.start_pages = ['https://nixos.org/nixos/manual/options.html']

c.hints.chars = "asdfghjklvbcntyruewom"

c.colors.webpage.darkmode.enabled = True

c.colors.webpage.prefers_color_scheme_dark = True

# Font color for hints.
# Type: QssColor
c.colors.hints.fg = '#EFF0EB'

# Background color for hints. Note that you can use a `rgba(...)` value
# for transparency.
# Type: QssColor
c.colors.hints.bg = '#1E1F29'

# Font color for the matched part of hints.
# Type: QssColor
c.colors.hints.match.fg = '#5AF78E'

# leave listed modes easily with <a-j>
for mode in\
        ['caret', 'command', 'hint',
            'insert', 'passthrough', 'prompt',
            'yesno']:
    config.bind('<Alt+j>', 'leave-mode', mode=mode)

# Bindings for normal mode
config.bind(',P', 'set-cmd-text -s :open -p')
config.bind(',r', 'restart')
config.bind(',c', 'config-source')
config.bind(';I', 'hint images download')
config.bind('X', 'undo')
config.bind('d', 'scroll-page 0 0.5')
config.bind('u', 'scroll-page 0 -0.5')
config.bind('x', 'tab-close')


import cv2
import numpy as np
import glob
from imutils.video import VideoStream
from imutils.video import FPS
import argparse
import imutils
import time
def select_roi(event, x, y, flags, param):
    global refPt, cropping
    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
        cropping = True
    elif event == cv2.EVENT_LBUTTONUP:
        refPt.append((x, y))
        cropping = False
        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        cv2.imshow("image", image)

refPt = []
cropping = False

image_files = sorted(glob.glob('/home/t1rant/Downloads/DriftCar1/img/*.jpg'))
start_time = time.time()
image = cv2.imread(image_files[0], cv2.IMREAD_COLOR)
clone = image.copy()
cv2.namedWindow("image")
cv2.setMouseCallback("image", select_roi)

while True:
    cv2.imshow("image", image)
    key = cv2.waitKey(1) & 0xFF
    if key == ord("r"):
        image = clone.copy()
    elif key == ord("c"):
        break

cv2.destroyAllWindows()

roi = (refPt[0][0], refPt[0][1], refPt[1][0]-refPt[0][0], refPt[1][1]-refPt[0][1])  # x, y, w, h

hsv_roi = cv2.cvtColor(clone[roi[1]:roi[1]+roi[3], roi[0]:roi[0]+roi[2]], cv2.COLOR_BGR2HSV)
roi_hist = cv2.calcHist([hsv_roi], [0], None, [180], [0, 180])
cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)

# for every other image
for idx, image_file in enumerate(image_files[1:]):
    frame = cv2.imread(image_file, cv2.IMREAD_COLOR)
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    dst = cv2.calcBackProject([hsv], [0], roi_hist, [0, 180], 1)

    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(dst)

    roi_center = maxLoc

    print(f'Frame {idx}: ROI Center (x, y) = {roi_center}')

    cv2.drawMarker(frame, roi_center, (0, 255, 0), markerType=cv2.MARKER_CROSS, markerSize=20)
    cv2.imshow('Manual Tracking', frame)

    if cv2.waitKey(1) & 0xFF == 27:  # Press 'Esc' key to exit
        break
# End timestamp
end_time = time.time()

# Calculate execution time
execution_time = end_time - start_time
print("Execution time: {:.2f} seconds".format(execution_time))
cv2.destroyAllWindows()


import cvxpy as cp
import numpy as np

class SlowPruningBenchmark:

    def setup(self):
        """Regression test for https://github.com/cvxpy/cvxpy/issues/1668

        Pruning matrices caused order-of-magnitude slow downs in compilation times.
        """
        s = 2000
        t = 10
        x = np.linspace(-100.0, 100.0, s)
        rows = 50
        var = cp.Variable(shape=(rows, t))

        cost = cp.sum_squares(
            var @ np.tile(np.array([x]), t).reshape((t, x.shape[0]))
            - np.tile(x, rows).reshape((rows, s))
        )
        objective = cp.Minimize(cost)
        problem = cp.Problem(objective)
        self.problem = problem

    def time_compile_problem(self):
        self.problem.get_problem_data(solver=cp.SCS)

if __name__ == '__main__':
    issue_1668 = SlowPruningBenchmark()
    issue_1668.setup()
    issue_1668.time_compile_problem()
    print(f"compilation time: {issue_1668.problem._compilation_time:.3f}")


import sys
import math
import time
from collections import defaultdict

class grid():
    def __init__(self, la_map):
        self.grille = la_map

    def show(self):
        for each_line in self.grille:
            print(each_line, file=sys.stderr)

    def update_map(self, pos1, pos2, dist):
        for y in range(h):
            for x in range(w):
                if self.grille[y][x] == 0:
                    if (x,y) in memo_dist.keys():
                        dist1 = memo_dist[(x,y)]
                    else:
                        dist1 = math.sqrt((pos1[0]-x)**2+(pos1[1]-y)**2) #distance from previous point
                    dist2 = math.sqrt((pos2[0]-x)**2+(pos2[1]-y)**2) #distance from latest position
                    memo_dist[(x,y)]=dist2
                    if dist == "COLDER" and dist1 > dist2: #si on s'eloigne et que la distance d'origine est plus grande que la nouvelle
                        self.grille[y][x]=1
                        del memo_dist[(x,y)]
                    elif dist == "WARMER" and dist2 > dist1:
                        self.grille[y][x]=1
                        del memo_dist[(x,y)]
                    elif dist == "SAME" and dist1 != dist2:
                        self.grille[y][x]=1
                        del memo_dist[(x,y)]

class aDallas():
    def __init__(self, X0, Y0):
        self.position = (X0, Y0)
        self.previous_position = (-1,-1)
        self.distance = "UNKNOWN"

    def move(self, new_x, new_y):
        global tower
        tower.grille[new_y][new_x] = 1
        self.previous_position = self.position
        self.position = (new_x, new_y)
        print(str(new_x), str(new_y))

    def update_sensor(self, result):
        self.distance = result

    def first_move(self):
        self.move((w-1)-self.position[0], (h-1)-self.position[1])

    def next_move(self, carte):
        max_dist = 0
        position = (0,0)
        for y in range(h):
            for x in range(w):
                if carte[y][x]==0:
                    dist = memo_dist[(x,y)]
                    if dist > max_dist:
                        max_dist = dist
                        position = (x,y)
        self.move(position[0], position[1])

memo_dist = defaultdict(list)
# w: width of the building.
# h: height of the building.
w, h = [int(i) for i in input().split()]
carte = [[0 for x in range(w)] for x in range(h)]
tower = grid(carte)
#tower.show()

n = int(input())  # maximum number of turns before game over.
x0, y0 = [int(i) for i in input().split()]
batman = aDallas(x0, y0)
start_time_global = time.time()
# game loop
while True:
    bomb_dir = input()  # Current distance to the bomb compared to previous distance (COLDER, WARMER, SAME or UNKNOWN)
    if bomb_dir == "UNKNOWN":
        batman.first_move()
    else:
        print(bomb_dir, file=sys.stderr)
        start_time_round = time.time()
        batman.update_sensor(bomb_dir)
        tower.update_map(batman.previous_position, batman.position, batman.distance)
        #tower.show()
        batman.next_move(tower.grille)
        interval = time.time() - start_time_round
        print("Round time : ", interval, file=sys.stderr)
        interval_global = time.time() - start_time_global
        print("Total time : ", interval_global, file=sys.stderr)

    # Write an action using print
    # To debug: print("Debug messages...", file=sys.stderr)

CG/training/very hard/trilateration v2 62%.py


import optparse
import sys
from data_mangle.cv_fold_sparse_reader import CVFoldSparseReader
from data_mangle.cv_fold_lol_sparse_reader import CVFoldLoLSparseReader
from data_mangle.cv_fold_dense_reader import CVFoldDenseReader
from utils import constants

def parse_ml_parameters():
    if len(sys.argv) < 2:
        print('no argument set. use default.')
        return None

    parser = optparse.OptionParser(usage="usage: %prog [options]")
    # FM
    parser.add_option("--fm_order", dest="fm_order", type="int", default=0)
    parser.add_option("--fm_rank", dest="fm_rank", type="int", default=0)
    parser.add_option("--fm_epoch", dest="fm_epoch", type="int", default=0)
    parser.add_option("--fm_reg", dest="fm_reg", type="float", default=0.0)
    parser.add_option("--fm_featconfig", dest="fm_featconfig", type="string", default='')
    # NN
    parser.add_option("--nn_hidden", dest="nn_hidden", type="int", default=0)
    parser.add_option("--nn_featconfig", dest="nn_featconfig", type="string", default='')
    #GBDT
    parser.add_option("--gbdt_featconfig", dest="gbdt_featconfig", type="string", default='')
    parser.add_option("--gbdt_ntree", dest="gbdt_ntree", type="int", default=100)
    parser.add_option("--gbdt_lr", dest="gbdt_lr", type="float", default=0.1)
    parser.add_option("--gbdt_maxdepth", dest="gbdt_maxdepth", type="int", default=3)
    parser.add_option("--gbdt_minsampleleaf", dest="gbdt_minsampleleaf", type="int", default=1)
    # general
    parser.add_option("--density", dest='density', type='string', default='')
    parser.add_option("--dataset", dest='dataset', type='string', default='')
    parser.add_option("--fold", dest='fold', type='int', default=3)
    parser.add_option("--seed", dest='seed', type='int', default=718)
    (kwargs, args) = parser.parse_args()
    return kwargs

def parse_reader(dataset, feature_config, density, fold=10, seed=None):
    if dataset == 'lol':
        if density == 'sparse':
            reader = CVFoldLoLSparseReader(data_path=constants.lol_pickle, folds=fold,
                                           feature_config=feature_config, seed=seed)
        else:
            raise NotImplementedError
    elif dataset == 'lol2':
        if density == 'dense':
            reader = CVFoldDenseReader(data_path=constants.lol2_pickle, folds=fold,
                                       feature_config=feature_config, seed=seed)
    elif dataset == 'dota':
        if density == 'dense':
            reader = CVFoldDenseReader(data_path=constants.dota_pickle, folds=fold,
                                       feature_config=feature_config, seed=seed)
        elif density == 'sparse':
            reader = CVFoldSparseReader(data_path=constants.dota_pickle, folds=fold,
                                        feature_config=feature_config, seed=seed)
        else:
            raise NotImplementedError
    elif dataset == 'dota2':
        if density == 'dense':
            reader = CVFoldDenseReader(data_path=constants.dota2_pickle, folds=fold,
                                       feature_config=feature_config, seed=seed)
        elif density == 'sparse':
            reader = CVFoldSparseReader(data_path=constants.dota2_pickle, folds=fold,
                                        feature_config=feature_config, seed=seed)
        else:
            raise NotImplementedError
    elif dataset == 'dota3':
        if density == 'dense':
            reader = CVFoldDenseReader(data_path=constants.dota3_pickle, folds=fold,
                                       feature_config=feature_config, seed=seed)
        elif density == 'sparse':
            reader = CVFoldSparseReader(data_path=constants.dota3_pickle, folds=fold,
                                        feature_config=feature_config, seed=seed)
        else:
            raise NotImplementedError
    else:
        raise NotImplementedError
    return reader

def parse_mcts_exp_parameters():
    if len(sys.argv) < 2:
        print('no argument set. use default.')
        return None

    parser = optparse.OptionParser(usage="usage: %prog [options]")

    parser.add_option("--num_matches", dest="num_matches", type="int", default=0)
    parser.add_option("--p0", dest="p0", type="string", default='')
    parser.add_option("--p1", dest="p1", type="string", default='')
    parser.add_option("--env_path", dest="env_path", type="string", default='')
    (kwargs, args) = parser.parse_args()
    return kwargs

def parse_mcts_maxiter_c(player_str):
    assert player_str.startswith('mcts')
    _, maxiter, c = player_str.split('_')
    return int(maxiter), float(c)

def parse_rave_maxiter_c_k(player_str):
    assert player_str.startswith('rave')
    _, maxiter, c, k = player_str.split('_')
    return int(maxiter), float(c), float(k)


import os
import torch
import json
import errno
import codecs
from tqdm import tqdm

if not os.path.exists('data/raw/train-images-idx3-ubyte'):
    try:
        os.makedirs(os.path.join('data', 'raw'))
        os.makedirs(os.path.join('data', 'processed'))
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass
        else:
            raise
    from six.moves import urllib
    import gzip
    urls = [
        'http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz',
        'http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz',
        'http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz',
        'http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz',
    ]
    for url in urls:
        print('Downloading ' + url)
        data = urllib.request.urlopen(url)
        filename = url.rpartition('/')[2]
        file_path = os.path.join('data', 'raw', filename)
        with open(file_path, 'wb') as f:
            f.write(data.read())
        with open(file_path.replace('.gz', ''), 'wb') as out_f, \
             gzip.GzipFile(file_path) as zip_f:
            out_f.write(zip_f.read())
        os.unlink(file_path)

def get_int(b):
    return int(codecs.encode(b, 'hex'), 16)

def parse_byte(b):
    if isinstance(b, str):
        return ord(b)
    return b

def read_label_file(path):
    with open(path, 'rb') as f:
        data = f.read()
        assert get_int(data[:4]) == 2049
        length = get_int(data[4:8])
        labels = [parse_byte(b) for b in tqdm(data[8:], total=length)]
        assert len(labels) == length
        return torch.LongTensor(labels)

def read_image_file(path):
    with open(path, 'rb') as f:
        data = f.read()
        assert get_int(data[:4]) == 2051
        length = get_int(data[4:8])
        num_rows = get_int(data[8:12])
        num_cols = get_int(data[12:16])
        images = []
        idx = 16
        for l in tqdm(range(length)):
            img = []
            images.append(img)
            for r in range(num_rows):
                row = []
                img.append(row)
                for c in range(num_cols):
                    row.append(parse_byte(data[idx]))
                    idx += 1
        assert len(images) == length
        return torch.FloatTensor(images)

print("Loading training set")
training_set = (
    read_image_file('data/raw/train-images-idx3-ubyte'),
    read_label_file('data/raw/train-labels-idx1-ubyte'),
)
print("Saving training set")
with open('data/processed/training.pt', 'wb') as f:
    torch.save(training_set, f)

print("Loading test set")
test_set = (
    read_image_file('data/raw/t10k-images-idx3-ubyte'),
    read_label_file('data/raw/t10k-labels-idx1-ubyte')
)
print("Saving test set")
with open('data/processed/test.pt', 'wb') as f:
    torch.save(test_set, f)


from collections.abc import Callable, Sequence
import functools
from typing import Any

from jax import jit
from jax import lax
from jax import numpy as jnp
from jaxonnxruntime.core import handler
from jaxonnxruntime.core import onnx_node

@handler.register_op("LRN")
class LRN(handler.Handler):
  """Implementation of the ONNX LRN operator."""

  @classmethod
  def _prepare(
      cls, node: onnx_node.OnnxNode, inputs: Sequence[Any], onnx_jax_impl: Any
  ):
    node.attrs_dict["alpha"] = node.attrs.get("alpha", float(0.0001))
    node.attrs_dict["beta"] = node.attrs.get("beta", float(0.75))
    node.attrs_dict["bias"] = node.attrs.get("bias", float(1.0))
    node.attrs_dict["size"] = int(node.attrs.get("size"))
    assert node.attrs_dict["size"] is not None

  @classmethod
  def version_1(
      cls, node: onnx_node.OnnxNode, inputs: Sequence[Any]
  ) -> Callable[..., Any]:
    """ONNX version_1 LRN op."""
    cls._prepare(node, inputs, onnx_lrn)
    return onnx_lrn

  @classmethod
  def version_13(
      cls, node: onnx_node.OnnxNode, inputs: Sequence[Any]
  ) -> Callable[..., Any]:
    """ONNX version_13 LRN op."""
    cls._prepare(node, inputs, onnx_lrn)
    return onnx_lrn

@functools.partial(jit, static_argnames=("alpha", "beta", "bias", "size"))
def onnx_lrn(*input_args, alpha, beta, bias, size):
  """https://github.com/onnx/onnx/blob/v1.12.0/docs/Operators.md#LRN for more details."""
  assert len(input_args) == 1
  x = input_args[0]
  shape = x.shape
  div = jnp.reshape(jnp.multiply(x, x), (shape[0], 1, shape[1], shape[2], -1))
  kernel_shape = (1, 1, size, 1, 1)
  strides = (1, 1, 1, 1, 1)
  pads = "SAME"
  div = (
      lax.reduce_window(
          div,
          jnp.array(0, dtype=div.dtype),
          lax.add,
          kernel_shape,
          strides,
          pads,
      )
      / size
  )
  div = jnp.reshape(div, shape)
  div = jnp.power(jnp.add(jnp.multiply(div, alpha), bias), beta)
  return jnp.true_divide(x, div)


from __future__ import annotations

from abc import abstractmethod
from dataclasses import dataclass
from datetime import datetime
import json
import re
import sys
from time import time
from typing import Any, AsyncGenerator, Dict, Optional, Sequence, Type, cast

import anyio
from anyio.abc import AsyncResource
from dandi.consts import known_instances
from dandi.dandiapi import AssetType, DandiAPIClient
from dandi.dandiapi import RemoteDandiset as SyncRemoteDandiset
from dandi.dandiapi import Version
from dandi.exceptions import NotFoundError
from dandischema.models import DigestType
import httpx
from pydantic import BaseModel, Field

from .aioutil import arequest
from .consts import USER_AGENT
from .logging import log

if sys.version_info[:2] >= (3, 10):
    from contextlib import aclosing
else:
    from async_generator import aclosing

@dataclass
class AsyncDandiClient(AsyncResource):
    session: httpx.AsyncClient
    api_url: str

    @classmethod
    def for_dandi_instance(
        cls, instance: str, token: Optional[str] = None
    ) -> AsyncDandiClient:
        headers = {"User-Agent": USER_AGENT}
        if token is not None:
            headers["Authorization"] = f"token {token}"
        return cls(
            session=httpx.AsyncClient(
                base_url=known_instances[instance].api,
                headers=headers,
                follow_redirects=True,
            ),
            api_url=known_instances[instance].api,
        )

    async def aclose(self) -> None:
        await self.session.aclose()

    def get_url(self, path: str) -> str:
        if path.lower().startswith(("http://", "https://")):
            return path
        else:
            return self.api_url.rstrip("/") + "/" + path.lstrip("/")

    async def get(self, path: str, **kwargs: Any) -> Any:
        return (await arequest(self.session, "GET", path, **kwargs)).json()

    async def post(self, path: str, **kwargs: Any) -> Any:
        return (await arequest(self.session, "POST", path, **kwargs)).json()

    async def delete(self, path: str, **kwargs: Any) -> None:
        await arequest(self.session, "DELETE", path, **kwargs)

    async def paginate(
        self,
        path: str,
        page_size: Optional[int] = None,
        params: Optional[dict] = None,
        **kwargs: Any,
    ) -> AsyncGenerator:
        """
        Paginate through the resources at the given path: GET the path, yield
        the values in the ``"results"`` key, and repeat with the URL in the
        ``"next"`` key until it is ``null``.
        """
        if page_size is not None:
            if params is None:
                params = {}
            params["page_size"] = page_size
        r = await self.get(path, params=params, **kwargs)
        while True:
            for item in r["results"]:
                yield item
            if r.get("next"):
                r = await self.get(r["next"], **kwargs)
            else:
                break

    async def get_dandiset(
        self, dandiset_id: str, version_id: Optional[str] = None
    ) -> RemoteDandiset:
        data = await self.get(f"/dandisets/{dandiset_id}/")
        d = RemoteDandiset.from_data(self, data)
        if version_id is not None and version_id != d.version_id:
            if version_id == "draft":
                return d.for_version(d.draft_version)
            else:
                return d.for_version(await d.aget_version(version_id))
        return d

    async def get_dandisets(self) -> AsyncGenerator[RemoteDandiset, None]:
        # Unlike the synchronous method, this always uses the draft version
        async with aclosing(self.paginate("/dandisets/")) as ait:
            async for data in ait:
                yield RemoteDandiset.from_data(self, data)

    async def get_dandisets_by_ids(
        self, dandiset_ids: Sequence[str]
    ) -> AsyncGenerator[RemoteDandiset, None]:
        for did in dandiset_ids:
            data = await self.get(f"/dandisets/{did}/")
            yield RemoteDandiset.from_data(self, data)

    async def create_dandiset(
        self, name: str, metadata: dict[str, Any]
    ) -> RemoteDandiset:
        return RemoteDandiset.from_data(
            self,
            await self.post("/dandisets/", json={"name": name, "metadata": metadata}),
        )

class RemoteDandiset(SyncRemoteDandiset):
    def __init__(self, aclient: AsyncDandiClient, **kwargs: Any) -> None:
        # We need to provide a DandiAPIClient so that pydantic doesn't error
        # when trying to construct asset instances
        nullclient = DandiAPIClient()
        # Ensure it doesn't accidentally make any requests:
        nullclient.session = None
        super().__init__(client=nullclient, **kwargs)
        self.aclient = aclient

    @classmethod
    def from_data(cls, aclient: AsyncDandiClient, data: dict) -> RemoteDandiset:
        # Unlike the synchronous method, this always uses the draft version
        return cls(
            aclient=aclient,
            identifier=data["identifier"],
            version=Version.parse_obj(data["draft_version"]),
            data=data,
        )

    def __repr__(self) -> str:
        return f"<Dandiset {self.identifier}/{self.version_id}>"

    def __str__(self) -> str:
        return f"Dandiset {self.identifier}/{self.version_id}"

    def for_version(self, v: Version) -> RemoteDandiset:
        return type(self)(
            aclient=self.aclient,
            identifier=self.identifier,
            version=v,
            data=self._data,
        )

    async def aget_raw_metadata(self) -> dict:
        return cast(dict, await self.aclient.get(self.version_api_path))

    async def aget_version(self, version_id: str) -> Version:
        return Version.parse_obj(
            self.aclient.get(f"/dandisets/{self.identifier}/versions/{version_id}/info")
        )

    async def aget_versions(
        self, include_draft: bool = True, order: Optional[str] = None
    ) -> AsyncGenerator[Version, None]:
        async with aclosing(
            self.aclient.paginate(f"{self.api_path}versions/", params={"order": order})
        ) as ait:
            async for v in ait:
                if v["version"] != "draft" or include_draft:
                    yield Version.parse_obj(v)

    async def aget_assets(self) -> AsyncGenerator[RemoteAsset, None]:
        async with aclosing(
            self.aclient.paginate(
                f"{self.version_api_path}assets/",
                params={"order": "created", "metadata": "1", "page_size": "1000"},
                timeout=60,
            )
        ) as ait:
            async for item in ait:
                yield RemoteAsset.from_data(self, item)

    async def aget_zarr_assets(self) -> AsyncGenerator[RemoteZarrAsset, None]:
        async with aclosing(self.aget_assets()) as ait:
            async for asset in ait:
                if isinstance(asset, RemoteZarrAsset):
                    yield asset

    async def aget_asset(self, asset_id: str) -> RemoteAsset:
        info = await self.aclient.get(f"{self.version_api_path}assets/{asset_id}/info/")
        return RemoteAsset.from_data(self, info)

    async def aget_asset_by_path(self, path: str) -> RemoteAsset:
        async with aclosing(
            self.aclient.paginate(
                f"{self.version_api_path}assets/",
                params={"path": path, "metadata": "1", "page_size": "1000"},
            )
        ) as ait:
            async for item in ait:
                if item["path"] == path:
                    return RemoteAsset.from_data(self, item)
        raise ValueError(f"Asset not found: {path}")

    async def await_until_valid(self, max_time: float = 120) -> None:
        log.debug("Waiting for Dandiset %s to complete validation ...", self.identifier)
        start = time()
        while time() - start < max_time:
            r = await self.aclient.get(f"{self.version_api_path}info/")
            if r["status"] == "Valid" and not r.get("asset_validation_errors"):
                return
            await anyio.sleep(0.5)
        about = {
            "asset_validation_errors": r.get("asset_validation_errors"),
            "version_validation_errors": r.get("version_validation_errors"),
        }
        raise ValueError(
            f"Dandiset {self.identifier} is {r['status']}:"
            f" {json.dumps(about, indent=4)}"
        )

    async def apublish(self, max_time: float = 120) -> RemoteDandiset:
        draft_api_path = f"/dandisets/{self.identifier}/versions/draft/"
        await arequest(self.aclient.session, "POST", f"{draft_api_path}publish/")
        log.debug(
            "Waiting for Dandiset %s to complete publication ...", self.identifier
        )
        start = time()
        while time() - start < max_time:
            v = await self.aclient.get(f"{draft_api_path}info/")
            if v["status"] == "Published":
                break
            await anyio.sleep(0.5)
        else:
            raise ValueError(f"Dandiset {self.identifier} did not publish in time")
        async for v in self.aget_versions(order="-created"):
            return self.for_version(v)
        raise AssertionError(
            f"No published versions found for Dandiset {self.identifier}"
        )

    async def adelete(self) -> None:
        await self.aclient.delete(self.api_path)

class RemoteAsset(BaseModel):
    """
    A minimal, asynchronous version of `dandi.dandiapi.RemoteAsset`, which it
    differs from in the following ways:

    - `refetch()` method added
    - `aclient` property added
    - `get_digest()` and `get_raw_digest()` methods combined into
      `get_digest_value()`
    - No `BaseRemoteAsset` base class, as backups2datalad doesn't operate on
      Dandiset-less asset URLs
    - `dandiset` attribute added
    - `dandiset_id` and `version_id` attributes are now properties
    - `_metadata` attribute renamed to `metadata`
    - The `metadata` attribute is now always set
    - `from_data()` now expects ``metadata`` to be a field of ``data`` instead
      of a separate argument
    - The following methods & properties have been removed:

      - `get_metadata()`
      - `get_raw_metadata()` (Use the `metadata` attribute instead)
      - `get_download_file_iter()`
      - `download()`
      - `set_metadata()`
      - `set_raw_metadata()`
      - `rename()`
      - `delete()`
      - `api_url`
      - `download_url`

    - `get_content_url()` does not take ``follow_redirects`` or ``strip_query``
      parameters
    """

    dandiset: RemoteDandiset
    #: The asset identifier
    identifier: str = Field(alias="asset_id")
    #: The asset's (forward-slash-separated) path
    path: str
    #: The size of the asset in bytes
    size: int
    #: The date at which the asset was created
    created: datetime
    #: The date at which the asset was last modified
    modified: datetime
    #: The asset's raw metadata
    metadata: Dict[str, Any]

    class Config:
        """Configuration for pydantic"""

        # To use the non-pydantic RemoteDandiset as an attribute and to be able
        # to create instances with RemoteAsset(identifier=...) instead of
        # RemoteAsset(alias_id=...)
        allow_population_by_field_name = True
        arbitrary_types_allowed = True

    @classmethod
    def from_data(cls, dandiset: RemoteDandiset, data: Dict[str, Any]) -> RemoteAsset:
        """
        Construct a `RemoteAsset` instance from a `RemoteDandiset` and a `dict`
        of raw data in the same format as returned by the API's pagination
        endpoints (including metadata).
        """
        klass: Type[RemoteAsset]
        if data.get("blob") is not None:
            klass = RemoteBlobAsset
            if data.pop("zarr", None) is not None:
                raise ValueError("Asset data contains both `blob` and `zarr`'")
        elif data.get("zarr") is not None:
            klass = RemoteZarrAsset
            if data.pop("blob", None) is not None:
                raise ValueError("Asset data contains both `blob` and `zarr`'")
        else:
            raise ValueError("Asset data contains neither `blob` nor `zarr`")
        return klass(dandiset=dandiset, **data)  # type: ignore[call-arg]

    @property
    def aclient(self) -> AsyncDandiClient:
        return self.dandiset.aclient

    @property
    def dandiset_id(self) -> str:
        return cast(str, self.dandiset.identifier)

    @property
    def version_id(self) -> str:
        return cast(str, self.dandiset.version_id)

    def json_dict(self) -> dict[str, Any]:
        return cast(
            Dict[str, Any],
            json.loads(self.json(exclude={"aclient", "dandiset"}, by_alias=True)),
        )

    @property
    def api_path(self) -> str:
        """
        The path (relative to the base endpoint for a Dandi Archive API) at
        which API requests for interacting with the asset itself are made
        """
        return (
            f"/dandisets/{self.dandiset_id}/versions/{self.version_id}/assets"
            f"/{self.identifier}/"
        )

    @property
    def base_download_url(self) -> str:
        """
        The URL from which the asset can be downloaded, sans any Dandiset
        identifiers
        """
        return self.aclient.get_url(f"/assets/{self.identifier}/download/")

    def get_digest_value(self, algorithm: Optional[DigestType] = None) -> Optional[str]:
        if algorithm is None:
            algorithm = self.digest_type
        try:
            val = self.metadata["digest"][algorithm.value]
        except KeyError:
            raise NotFoundError(f"No {algorithm.value} digest found in metadata")
        assert val is None or isinstance(val, str)
        return val

    def get_content_url(self, regex: str = r".*") -> str:
        """
        Returns a URL for downloading the asset, found by inspecting the
        metadata; specifically, returns the first ``contentUrl`` that matches
        ``regex``.  Raises `NotFoundError` if the metadata does not contain a
        matching URL.
        """
        for url in self.metadata.get("contentUrl", []):
            assert isinstance(url, str)
            if re.search(regex, url):
                return url
        raise NotFoundError(
            "No matching URL found in asset's contentUrl metadata field"
        )

    async def refetch(self) -> RemoteAsset:
        # Query the Dandiset-free asset endpoint in case the asset's been
        # deleted from the Dandiset since we started running
        info = await self.aclient.get(f"/assets/{self.identifier}/info/")
        return RemoteAsset.from_data(self.dandiset, info)

    @property
    @abstractmethod
    def asset_type(self) -> AssetType:
        """The type of the asset's underlying data"""
        ...

    @property
    def digest_type(self) -> DigestType:
        """
        The primary digest algorithm used by Dandi Archive for the asset,
        determined based on its underlying data: dandi-etag for blob resources,
        dandi-zarr-checksum for Zarr resources
        """
        if self.asset_type is AssetType.ZARR:
            return DigestType.dandi_zarr_checksum
        else:
            return DigestType.dandi_etag

class RemoteBlobAsset(RemoteAsset):
    """A `RemoteAsset` whose actual data is a blob resource"""

    #: The ID of the underlying blob resource
    blob: str

    @property
    def asset_type(self) -> AssetType:
        """The type of the asset's underlying data"""
        return AssetType.BLOB

class RemoteZarrAsset(RemoteAsset):
    """A `RemoteAsset` whose actual data is a Zarr resource"""

    #: The ID of the underlying Zarr resource
    zarr: str

    @property
    def asset_type(self) -> AssetType:
        """The type of the asset's underlying data"""
        return AssetType.ZARR


import torch
from torch import nn
import torch.nn.functional as F
from torch.nn import Linear, LayerNorm, ReLU

from torch_scatter import scatter
from torch_geometric.nn import MessagePassing
from torch_geometric.utils import add_self_loops, degree, softmax
from torch_geometric.nn import global_add_pool, global_mean_pool, global_max_pool

from auglichem.utils import NUM_ATOM_TYPE, NUM_CHIRALITY_TAG, NUM_BOND_TYPE, NUM_BOND_DIRECTION

class GINEConv(MessagePassing):
    def __init__(self, emb_dim, aggr="add"):
        super(GINEConv, self).__init__()
        self.mlp = nn.Sequential(
            nn.Linear(emb_dim, 2*emb_dim),
            nn.ReLU(),
            nn.Linear(2*emb_dim, emb_dim))
        self.edge_embedding1 = nn.Embedding(NUM_BOND_TYPE, emb_dim)
        self.edge_embedding2 = nn.Embedding(NUM_BOND_DIRECTION, emb_dim)

        nn.init.xavier_uniform_(self.edge_embedding1.weight.data)
        nn.init.xavier_uniform_(self.edge_embedding2.weight.data)
        self.aggr = aggr

    def forward(self, x, edge_index, edge_attr):
        # add self loops in the edge space
        edge_index = add_self_loops(edge_index, num_nodes=x.size(0))[0]
        # print(edge_index)

        # add features corresponding to self-loop edges.
        self_loop_attr = torch.zeros(x.size(0), 2)
        self_loop_attr[:,0] = 4 #bond type for self-loop edge
        self_loop_attr = self_loop_attr.to(edge_attr.device).to(edge_attr.dtype)
        edge_attr = torch.cat((edge_attr, self_loop_attr), dim=0)

        edge_embeddings = self.edge_embedding1(edge_attr[:,0]) + self.edge_embedding2(edge_attr[:,1])

        # return self.propagate(self.aggr, edge_index, x=x, edge_attr=edge_embeddings)
        return self.propagate(edge_index, x=x, edge_attr=edge_embeddings)

    def message(self, x_j, edge_attr):
        return x_j + edge_attr

    def update(self, aggr_out):
        return self.mlp(aggr_out)

class GINE(nn.Module):
    def __init__(self,
                 task='classification',
                 emb_dim=300,
                 feat_dim=256,
                 num_layer=5,
                 pool='mean',
                 drop_ratio=.0,
                 output_dim=None,
                 **kwargs):

        super(GINE, self).__init__()
        self.num_layer = num_layer
        self.emb_dim = emb_dim
        self.feat_dim = feat_dim
        self.drop_ratio = drop_ratio
        self.task = task
        if(output_dim == None):
            self.output_dim = 1
        else:
            self.output_dim = output_dim

        if self.num_layer < 2:
            raise ValueError("Number of GNN layers must be greater than 1.")

        self.x_embedding1 = nn.Embedding(NUM_ATOM_TYPE + 1, emb_dim)
        self.x_embedding2 = nn.Embedding(NUM_CHIRALITY_TAG, emb_dim)

        nn.init.xavier_uniform_(self.x_embedding1.weight.data)
        nn.init.xavier_uniform_(self.x_embedding2.weight.data)

        # List of MLPs
        self.gnns = nn.ModuleList()
        for layer in range(num_layer):
            self.gnns.append(GINEConv(emb_dim, aggr="add"))

        # List of batchnorms
        self.batch_norms = nn.ModuleList()
        for layer in range(num_layer):
            self.batch_norms.append(nn.BatchNorm1d(emb_dim))

        if pool == 'mean':
            self.pool = global_mean_pool
        elif pool == 'add':
            self.pool = global_add_pool
        elif pool == 'max':
            self.pool = global_max_pool
        else:
            raise ValueError('Not defined pooling!')

        self.feat_lin = nn.Linear(self.emb_dim, self.feat_dim)

        if self.task == 'classification':
            self.output_dim *= 2
            self.pred_lin = nn.Sequential(
                nn.Linear(self.feat_dim, self.feat_dim//2),
                nn.ReLU(inplace=True),
                nn.Linear(self.feat_dim//2, self.output_dim)
            )
        elif self.task == 'regression':
            self.pred_lin = nn.Sequential(
                nn.Linear(self.feat_dim, self.feat_dim//2),
                nn.ReLU(inplace=True),
                nn.Linear(self.feat_dim//2, self.feat_dim//2),
                nn.ReLU(inplace=True),
                nn.Linear(self.feat_dim//2, self.feat_dim//4),
                nn.ReLU(inplace=True),
                nn.Linear(self.feat_dim//4, self.output_dim)
            )

    def forward(self, data):
        x = data.x
        edge_index = data.edge_index
        edge_attr = data.edge_attr

        h = self.x_embedding1(x[:,0]) + self.x_embedding2(x[:,1])

        for layer in range(self.num_layer):
            h = self.gnns[layer](h, edge_index, edge_attr)
            h = self.batch_norms[layer](h)

            h = F.dropout(F.relu(h), self.drop_ratio, training=self.training)

        h = self.feat_lin(h)
        h = self.pool(h, data.batch)

        return h, self.pred_lin(h)

    def load_my_state_dict(self, state_dict):
        own_state = self.state_dict()
        for name, param in state_dict.items():
            if name not in own_state:
                continue
            if isinstance(param, nn.parameter.Parameter):
                param = param.data
            own_state[name].copy_(param)

class EMA:
    def __init__(self, model: torch.nn.Module, decay: float):
        self.decay = decay
        self.shadow = {}
        self.original = {}

        # Register model parameters
        for name, param in model.named_parameters():
            if param.requires_grad:
                self.shadow[name] = param.clone().detach()

    def __call__(self, model):
        with torch.no_grad():
            for name, param in model.named_parameters():
                if param.requires_grad:
                    assert name in self.shadow
                    new_average = (1.0 - self.decay) * param + self.decay * self.shadow[
                        name
                    ]
                    self.shadow[name] = new_average

    def assign(self, model: torch.nn.Module):
        for name, param in model.named_parameters():
            if param.requires_grad:
                self.original[name] = param.clone()
                param.data.copy_(self.shadow[name].data)

    def resume(self, model: torch.nn.Module):
        for name, param in model.named_parameters():
            if param.requires_grad:
                param.data.copy_(self.original[name].data)


class FibonacciDynamicMemoization:
    def fibonacci(n):
        # Base case: n = 0 or 1
        if n <= 1:
            return n

        # Recursive case: fib(n) = fib(n - 1) + fib(n - 1)
        return FibonacciDynamicMemoization.fibonacci(n - 1) + FibonacciDynamicMemoization.fibonacci(n - 2)

    # Memoization
    def fibonaccimemoization(n, cache):
        if n <= 1:
            return n
        if n in cache:
            return cache[n]

        cache[n] = FibonacciDynamicMemoization.fibonaccimemoization(n - 1, cache) + FibonacciDynamicMemoization.fibonaccimemoization(n - 2, cache)
        return cache[n]

    # Dynamic Programming
    def fibonaccidp(n):
        if n < 2:
            return n

        dp = [0, 1]
        i = 2
        while i <= n:
            tmp = dp[1]
            dp[1] = dp[0] + dp[1]
            dp[0] = tmp
            i += 1
        return dp[1]

if __name__ == '__main__':
    print(FibonacciDynamicMemoization.fibonaccidp(6))
    print(FibonacciDynamicMemoization.fibonaccimemoization(6, {}))


from django.db import models
from django.contrib.sites.models import Site

class ProviderManager(models.Manager):

    def get_queryset(self):
        return super(models.Manager, self).get_queryset().select_related(
            'site',
            'site__siteprofile',
        )

    def public(self):
        return self.filter(is_public=True, )

class Provider(models.Model):

    site = models.ForeignKey(
        Site,
    )

    name = models.CharField(
        max_length=16,
        unique=True,
    )

    feed_url = models.URLField(
        blank=True,
        null=True,
        unique=True,
    )

    is_public = models.BooleanField(
        default=True,
    )

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = ProviderManager()

    class Meta:
        ordering = ['name', ]

    def __str__(self):
        return self.name

    def update_tidbits(self):
        """Add/Update provider tidbits from a RSS/Atom feed."""
        import feedparser

        feed_result = feedparser.parse(self.feed_url)

        for item in feed_result.entries:

            tidbit, created = self.tidbit_set.get_or_create(
                original_url=item.id,
            )

            if created:
                tidbit.title = item.title
                tidbit.author = item.author
                tidbit.content = item.description
                tidbit.save()


import pygame
from sprite import *
from background import Background
import string, random
import time

class Scene:

    def __init__(self, size=(640, 480), position=(100, 100), frame_rate=30):
        # Initialize the scene
        pygame.init()

        # Start music
        pygame.mixer.music.load("resources/music/song1.wav")
        pygame.mixer.music.play(-1)

        self.sfx = pygame.mixer.Channel(2)
        self.coin_sfx = pygame.mixer.Channel(3)
        self.shield_sfx = pygame.mixer.Channel(4)
        self.hit = pygame.mixer.Sound("resources/music/hit.wav")
        # For whatever reason, set volume does not work
        #self.hit.set_volume(50)
        self.gain = pygame.mixer.Sound("resources/music/coin.wav")
        self.shield_sound = pygame.mixer.Sound("resources/music/shield.wav")

        self.size = size
        self.position = position
        self.frame_rate = frame_rate
        self.__game_clock = pygame.time.Clock()
        self.window_icon = None
        self.window_title = None
        self.screen = pygame.display.set_mode(self.size)
        self.background = None

        self.sprites = pygame.sprite.Group() # all enemies
        self.coins = pygame.sprite.Group() # all coins
        self.playable_sprites = pygame.sprite.Group() # just player
        self.player = None

        # Initialize fonts used
        self.font_size = 16
        self.font_name = 'arial'
        self.font = pygame.font.Font(pygame.font.match_font(self.font_name), self.font_size)
        self.score_pos = (500, 50)

        self.__running = False

        self.enemy_num = 3
        self.enemy_time_int = 2

        self.__totaltime = time.time()
        self.__enemytime = self.__totaltime
        # Used to track timing of enemy spawns
        self.__timestart = self.__totaltime
        # Used to track coin spawns
        self.__cointime = self.__totaltime

    def set_font_size(self, size : int):
        self.font_size = size
        self.font = pygame.font.Font(pygame.font.match_font(self.font_name), self.font_size)

    def set_font_name(self, name : string):
        self.font_name = name
        self.font = pygame.font.Font(pygame.font.match_font(self.font_name), self.font_size)

    def set_font(self, font: pygame.font.Font):
        self.font = font

    def set_background(self, background : Background):
        self.background = background

    def get_player(self):
        return self.player

    def __cleanup(self):
        pygame.quit()

    def __event(self, event):
        # event handling will happen here
        if event.type == pygame.QUIT:
            # Window exit
            self.__running = False
        if event.type == pygame.KEYDOWN:
            # Single action
            print(pygame.key.name(event.key))
            if event.key == pygame.K_m:
                # Toggle bg scrolling
                if self.background:
                    if self.background.scrolling:
                        self.background.scrolling = False
                    else:
                        self.background.scrolling = True
            if event.key == pygame.K_p:
                # Player becomes next available sprite
                print(len(self.playable_sprites))
                if self.player:
                    self.swap_player()
            if event.key == pygame.K_q:
                # Position each sprite at bottom of screen
                self.drop_all_sprites()
            if event.key == pygame.K_b:
                # Toggle red border around player
                self.toggle_player_highlight()

    def __render(self):
        # Draw everything to the screen

        # Draw background
        if self.background:
            if self.background.scrolling and self.background.scroll == 'x':
                self.background.scroll_updateX()
                bg_img, bg_pos1, bg_pos2 = self.background.scroll_render()
                self.screen.blit(bg_img, bg_pos1)
                self.screen.blit(bg_img, bg_pos2)
            elif self.background.scrolling and self.background.scroll == 'y':
                self.background.scroll_updateY()
                bg_img, bg_pos1, bg_pos2 = self.background.scroll_render()
                self.screen.blit(bg_img, bg_pos1)
                self.screen.blit(bg_img, bg_pos2)
            else:
                bg_img, bg_pos1, bg_pos2 = self.background.render()
                if bg_pos1 == None or bg_pos2 == None:
                    self.screen.blit(self.background.render(), (0, 0))
                else:
                    self.screen.blit(bg_img, bg_pos1)
                    self.screen.blit(bg_img, bg_pos2)

        # Draw scorebox
        pygame.draw.rect(self.screen, (0, 0, 0), [self.screen.get_width() - 200, 0, self.screen.get_width(), 100], 0)

        # Draw score
        score = self.font.render("Distance: " + str(round(self.player.score, 1)) + "m", True, (255, 255, 255))
        score_rect = score.get_rect()
        score_rect.midtop = (self.screen.get_width() - 125, 10)
        self.screen.blit(score, score_rect)

        # Draw lives
        lives = self.font.render("Lives: " + str(self.player.lives), True, (255, 255, 255))
        lives_rect = lives.get_rect()
        lives_rect.midtop = (self.screen.get_width() - 125, 30)
        self.screen.blit(lives, lives_rect)

        # Draw enemy spawn interval
        enemy_spawn_int = self.font.render("Enemy spawn: " + str(round(self.enemy_time_int, 1)) + "s", True, (255, 255, 255))
        spawn_rect = enemy_spawn_int.get_rect()
        spawn_rect.midtop = (self.screen.get_width() - 100, 50)
        self.screen.blit(enemy_spawn_int, spawn_rect)

        # Draw time elapsed
        elapsed = self.font.render("Time running: " + str(round(time.time() - self.__totaltime, 1)) + "s", True, (255, 255, 255))
        time_rect = elapsed.get_rect()
        time_rect.midtop = (self.screen.get_width() - 100, 75)
        self.screen.blit(elapsed, time_rect)

        # left, top, width, height
        # Draw shields and enemy slows
        pygame.draw.rect(self.screen, (0, 0, 0), [self.screen.get_width() / 2 - 90, 15, 180, 45], 0)
        if (self.player.invincible):
            shield_timer = self.font.render("Shield active for " + str(round(5 - (time.time() - self.player.shieldtimer), 1)) + "s", True, (255, 255, 255))
        else:
            shield_timer = self.font.render("Shields: " + str(self.player.shields), True, (255, 255, 255))
        shield_rect = shield_timer.get_rect()
        shield_rect.midtop = (self.screen.get_width() / 2, 15)
        slow = self.font.render("Enemies slowed by " + str(self.enemy_slows), True, (255, 255, 255))
        slow_rect = slow.get_rect()
        slow_rect.midtop = (self.screen.get_width() / 2, 35)
        self.screen.blit(shield_timer, shield_rect)
        self.screen.blit(slow, slow_rect)

        self.playable_sprites.draw(self.screen)
        self.coins.draw(self.screen)
        self.sprites.draw(self.screen)

        pygame.display.flip()

    def create_owl(self):
        enemy = Owl(self.size[0], self.enemy_slows)
        self.add_npc_sprite(enemy)
        print("Owl enemy spawned")
        self.__timestart = time.time()

    def create_snake(self):
        enemy = Snake(self.size[0], self.enemy_slows)
        self.add_npc_sprite(enemy)
        print("Snake enemy spawned")
        self.__timestart = time.time()

    def create_coin(self):
        coin = Coin(self.size[0])
        self.coins.add(coin)
        print("Coin spawned")
        self.__cointime = time.time()

    def __update(self):
        # All updates every frame
        self.player.add_score(.1)

        self.coins.update(self.size)
        self.playable_sprites.update(self.size)
        self.sprites.update(self.size)

        # Enemy spawns every two seconds
        if ((time.time() - self.__timestart >= self.enemy_time_int)):

            # Val represents our randomness for enemy spawns
            # Stored once so enemies multiple enemies don't spawn simultaneously
            # Range is numbers 1-25
            val = random.randrange(1, 26)

            # Logic for creating owls
            if ((val % 2 == 0) and len(self.sprites) < self.enemy_num):
                self.create_owl()

            # Logic for creating snakes
            if ((val % 2 == 1) and len(self.sprites) < self.enemy_num):
                self.create_snake()

        # Logic for creating coins every 5 seconds
        if ((time.time() - self.__cointime >= 5)):
            val = random.randrange(1, 11)
            if (val % 5 == 0):
                self.create_coin()

        # Logic for removing enemies offscreen
        for enemy in self.sprites:
            if enemy.offscreen:
                enemy.kill()
                print("Enemy offscreen removed.\nSprites: {}".format(len(self.sprites)))

        # Collisions with enemies
        npc_collision = pygame.sprite.groupcollide(self.playable_sprites, self.sprites, False, False)
        for player, enemies in npc_collision.items():
            for enemy in enemies:
                if not player.invincible:
                    self.sfx.play(self.hit)
                    player.add_lives(-1)
                    print("Enemy collided removed.\nSprites: {}".format(len(self.sprites)))
                else:
                    self.shield_sfx.play(self.shield_sound)
                    print("Enemy collided with player shield.")
                enemy.kill()

        # Collisions with coins
        coin_collision = pygame.sprite.groupcollide(self.playable_sprites, self.coins, False, False)
        for player, coins in coin_collision.items():
            for coin in coins:
                self.coin_sfx.play(self.gain)
                coin.kill()
                player.add_score(50)
                print("Coin collided removed.")

        # Player out of lives?
        if (self.player.lives <= 0):
            self.stop_game()

        # Every 10 seconds, increase enemy spawn time
        if ((time.time() - self.__enemytime) >= 10):
            # Increase enemy spawn time
            self.enemy_time_int -= .2
            print("Enemy spawn time: {}".format(self.enemy_time_int))
            self.__enemytime = time.time()

        # Begin drawing
        self.__render()

    def check_collision(self, sprite1, sprite2):
        collides = pygame.sprite.collide_rect(sprite1, sprite2)
        return collides

    def drop_all_sprites(self):
        for sprite in self.sprites:
            spr_height = sprite.get_height()
            sprite.change_position((sprite.get_x(), self.size[1] - spr_height))

    def add_npc_sprite(self, sprite):
        self.sprites.add(sprite)

    def add_playable_sprite(self, sprite):
        self.playable_sprites.add(sprite)
        self.add_player_sprite(sprite)

    def add_player_sprite(self, sprite):
        self.set_player(sprite)

    def set_player(self, sprite):
        if self.player:
            self.player.is_player = False
        self.player = sprite
        self.player.is_player = True

    def start_game(self, slows):
        # Main game loop
        self.enemy_slows = slows
        self.__running = True
        while self.__running:
            self.__game_clock.tick(self.frame_rate)
            for event in pygame.event.get():
                self.__event(event)

            # Updates to happen
            self.__update()

        # After the game loop breaks, we clean things up on
        # pygame's end
        self.__cleanup()

    def stop_game(self):
        pygame.mixer.music.stop()

        sfx = pygame.mixer.Channel(1)
        death = pygame.mixer.Sound("resources/music/death.wav")
        sfx.play(death)
        while sfx.get_busy():
            # Waiting until sfx are done
            pass
        self.__running = False

    def set_window_title(self, title):
        self.window_title = title
        pygame.display.set_caption(self.window_title)


# -*- coding: utf-8 -*-
#9. Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр.
# Вывести на экран это число и сумму его цифр.
def sumfig(num):
    if num==0: return 0;
    return sumfig(num//10) + (num % 10)

lst=[]
while 1:
    next = int(input('введи натуральное число, или 0 - конец набора: '))
    if next== 0: break;
    lst.append(next)

sum_record =0; recordsmen =0
for i in lst:
    sum_i = sumfig(i)
    if sum_i > sum_record:
        sum_record,recordsmen =sum_i,i

print('{} {}'.format(recordsmen,sum_record))


import os
import sys
import random

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from player.participant import Participant

class Player(Participant):
    def __init__(self, user) -> None:
        super().__init__(user)

    def __get_user_input(self, prompt: str, valid_responses: list) -> str:
        while True:
            response = input(prompt).lower()
            if response in valid_responses:
                return response
            else:
                self.logger.log("Invalid input. Please try again.")

    def wants_to_hit(self) -> bool:
        while True:
            self.logger.log(f"{self.get_user().name}: {[card.name + ' ' + card.suit.symbol for card in self.hand.get_cards()]} - Points: {self.hand.get_value()}")

            response = self.__get_user_input(f"{self.get_user().name}, do you want to hit or stand or surrender? ", ['hit', 'stand', 'h', 's', 'surrender', 'sur'])

            if response in ['hit', 'h']:
                self.logger.log(f"{self.get_user().name} says: {random.choice(super().HITS)}")
                return True
            elif response in ['stand', 's']:
                self.logger.log(f"{self.get_user().name} says: {random.choice(super().STANDS)}")
                return False
            elif response in ['surrender', 'sur']:
                has_surrender = self.wants_to_surrender()
                if(has_surrender):
                    self.logger.log(f"{self.get_user().name} says: {random.choice(super().SURRENDERS)}")
                return has_surrender


# cuda env instead of taichi env provide the api similar to taichi env and mpm simulators.
import os
import yaml
from tools import CN, Configurable, merge_inputs
# from plb import load
from .simulator import MPMSimulator
from .renderer import Renderer

FILEPATH = os.path.dirname(os.path.abspath(__file__))

class CudaEnv(Configurable):
    def __init__(
        self,
        cfg:CN=None,
        cfg_path='configs/plb_cuda.yml',
        SIMULATOR=None,
        PRIMITIVES:CN=None,
        RENDERER:CN=Renderer.get_default_config(),
        SHAPES=None,
    ):
        super().__init__()
        # if PRIMITIVES is None or len(PRIMITIVES) == 0:
        #     PRIMITIVES = load(os.path.join(FILEPATH, cfg_path)).PRIMITIVES
        n_bodies, kwargs = self.parse_tools(PRIMITIVES)
        self.simulator = MPMSimulator(n_bodies, cfg=SIMULATOR)
        self.simulator.init_bodies(**kwargs)
        self.renderer = Renderer(cfg=RENDERER)
        import numpy as np
        self.particle_colors = np.zeros(self.simulator.n_particles) + (((((255)<<8)+255)<<8)+255)
        self.simulator.states[0].x.upload(np.random.random(size=(self.simulator.n_particles, 3)) * 0.2 + np.array((0.4, 0.1, 0.4)))

    def default_tool_config(self):
        cfg = CN()
        cfg.shape = ''
        cfg.init_pos = (0.3, 0.3, 0.3)  # default color
        cfg.init_rot = (1., 0., 0., 0.)  # default color
        cfg.color = (0.3, 0.3, 0.3)  # default color
        cfg.lower_bound = (0., 0., 0.)  # default color
        cfg.upper_bound = (1., 1., 1.)  # default color
        cfg.friction = 0.9  # default color
        cfg.variations = None  # TODO: not support now
        cfg.mass = 1.
        cfg.stiffness = 0.

        action = cfg.action = CN()
        action.dim = 0  # in this case it can't move ...
        action.scale = ()
        return cfg

    def parse_tools(self, cfgs):
        tools = []

        for i in cfgs:
            if isinstance(i, CN):
                cfg = i
            else:
                cfg = CN(new_allowed=True)
                cfg = cfg._load_cfg_from_yaml_str(yaml.safe_dump(i))

            cfg = merge_inputs(self.default_tool_config(), **cfg)
            tools.append(cfg)

        self.action_dims = [0]
        outs = []

        types = []
        softness = []
        pos = []
        rot = []
        mu = []
        round = []
        args = []
        action_scales = []

        for i in tools:
            #primitive = eval(i.shape)(cfg=i, dim=dim, max_timesteps=max_timesteps, dtype=dtype)
            #self.primitives.append(primitive)
            #self.action_dims.append(self.action_dims[-1] + primitive.action_dim)
            if i['shape'] == 'Box':
                types.append(0)
                args.append([*i['size'], 0])
            elif i['shape'] == 'Capsule':
                types.append(1)
                args.append([*i['size'], 0, 0])

            action_scales.append(i['action']['scale'])
            softness.append(666.)
            mu.append(i['friction'])
            round.append(i['round'])
            pos.append(i.init_pos)
            rot.append(i.init_rot)

        return len(tools), {
            'types': types,
            'softness': softness,
            'mu': mu,
            'round': round,
            'args': args,
            'action_scales': action_scales,
            'pos': pos,
            'rot': rot
        }


import os
import json
from .shell_agent import ShellAgent
from .sysadmin_agent import SysAdminAgent
from .utils import SpecialAction
from .cat_agent import CatAgent
import openai
import sys

openai.api_key = os.getenv("OPENAI_API_KEY")

CONTEXT_LENGTH = 50

class Game:
    def __init__(self):
        self.history = []
        self.agent_stack = []
        self.nextAgent = None

    def pushToNextAgent(self, agent):
        self.history = []
        self.agent_stack.append(agent)
        self.nextAgent = agent

    def popToNextAgent(self):
        if len(self.agent_stack) == 0:
            raise Exception("Cannot pop agent from empty stack")
        self.agent_stack.pop()
        self.nextAgent = self.agent_stack[len(self.agent_stack) - 1]

    def applyNextAgent(self):
        if self.nextAgent is None:
            raise Exception("Cannot apply next agent when next agent is None")
        self.history = []
        self.agent = self.nextAgent
        self.nextAgent = None

    def handleInput(self, line):
        self.history.append({ "role": "user", "content": line })

        userMessages = self.history[-CONTEXT_LENGTH:]

        override = self.agent.overrideCompletion(line)

        if override is not None:
            res = override

            special = override.get("special")

            if special is SpecialAction.TURN_INTO_CAT:
                self.pushToNextAgent(CatAgent())
            if special is SpecialAction.POP:
                self.popToNextAgent()

        else:
            completion = openai.ChatCompletion.create(
                model="gpt-3.5-turbo-0613",
                messages=[
                    {"role": "system", "content": self.agent.systemPrompt},
                ]
                + userMessages,
                functions=[{"name": "fn", "parameters": self.agent.schema}],
                function_call={"name": "fn"},
                temperature=0.7,
            )
            res = json.loads(completion.choices[0].message.function_call.arguments)  # type: ignore

            self.agent.handleGptOutput(res)

            self.history.append({ "role": "assistant", "content": self.agent.completion_to_history(res) })

            print(json.dumps(self.history), file=sys.stderr)

            if isinstance(self.agent, SysAdminAgent) and res.get("shell") == "true":
                self.pushToNextAgent(ShellAgent())

        response = self.agent.print(res)

        if self.nextAgent:
            self.applyNextAgent()

        return {"response": response, "prompt": self.agent.prompt()}

    def run(self):
        while True:
            print(self.agent.prompt(), end="")

            line = input().strip()
            self.history.append(line)

            userMessages = list(
                map(
                    lambda l: {"role": "user", "content": l},
                    self.history[-CONTEXT_LENGTH:],
                )
            )

            override = self.agent.overrideCompletion(line)

            if override is not None:
                res = override

                special = override.get("special")

                if special is SpecialAction.TURN_INTO_CAT:
                    self.pushToNextAgent(CatAgent())
                if special is SpecialAction.POP:
                    self.popToNextAgent()

            else:
                completion = openai.ChatCompletion.create(
                    model="gpt-4-0613",
                    messages=[
                        {"role": "system", "content": self.agent.systemPrompt},
                    ]
                    + userMessages,
                    functions=[{"name": "fn", "parameters": self.agent.schema}],
                    function_call={"name": "fn"},
                    temperature=0.7,
                )
                res = json.loads(completion.choices[0].message.function_call.arguments)  # type: ignore

                self.agent.handleGptOutput(res)

                if isinstance(self.agent, SysAdminAgent) and res.get("shell") == "true":
                    self.pushToNextAgent(ShellAgent())

            print(self.agent.print(res), end="")

            if self.nextAgent:
                self.applyNextAgent()