import discord
import os
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import asyncio
import random
from keep_alive import keep_alive

scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_dict(json.loads(os.getenv("SERVICE CREDS")), scope)
client = gspread.authorize(creds)
sheet = client.open("Amber's Secret Santa 2022").worksheet("Gift Reveal")

participants = sheet.row_count - 1
AMBER_ID = 607544531042304010
GIFTER_ID_COL = 4
GIFTEE_ID_COL = 7
PARTNER_COL = 8
ARTWORK_COL = 10
GALLERY_ID = 1031026351391645767

intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)

@client.event
async def on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  #bot recieves dm
  if isinstance(message.channel, discord.DMChannel):

    #amber sends testids command
    if message.content.startswith(">testids") and message.author.id == AMBER_ID:
      msg = ""
      for i in range(participants):
        rowNum = i+2

        gifterID = int(sheet.cell(rowNum, GIFTER_ID_COL).value)
        gifter = client.get_user(gifterID)

        if gifter == None:
          amber = client.get_user(AMBER_ID)
          msg = msg + str(rowNum) + " " + str(gifterID) + "\n"
        else:
          amber = client.get_user(AMBER_ID)
          msg = msg + str(rowNum) + " <@" + str(gifterID) + ">\n"

        #avoid quota limit
        if (i + 1) % 30 == 0:
          amber = client.get_user(AMBER_ID)
          await amber.send(msg)
          msg = ""
          await asyncio.sleep(60)
        else:
          sentAll = False

      if not sentAll:
        amber = client.get_user(AMBER_ID)
        await amber.send(msg)

    #amber sends sendpartners command
    if message.content.startswith(">sendpartners") and message.author.id == AMBER_ID:
      for i in range(participants):
        rowNum = i+2

        #avoid quota limit
        if (i + 1) % 30 == 0:
          await asyncio.sleep(60)

        gifterID = int(sheet.cell(rowNum, GIFTER_ID_COL).value)
        gifteeID = int(sheet.cell(rowNum, GIFTEE_ID_COL).value)

        gifter = client.get_user(gifterID)
        giftee = client.get_user(gifteeID)

        try:
          if gifter == None:
            amber = client.get_user(AMBER_ID)
            await amber.send(str(rowNum) + " Gifter " + str(gifterID) + " not in server")
          elif giftee == None:
            amber = client.get_user(AMBER_ID)
            await amber.send(str(rowNum) + " Giftee " + str(gifteeID) + " not in server")
          else:
            await gifter.send("Hey <@" + str(gifterID) + ">! \n\nYour giftee for Amber's Secret Santa 2022 is " + giftee.name + "#" + giftee.discriminator + "! Don't tell anyone who your giftee is, it's a surprise! To find your giftee's wishlist, search 'in: wishlists from: " + giftee.name + "#" + giftee.discriminator + "' in the server! \n\nPlease dm a sketch of your artwork to your group leader by **December 14th**! Let your group leader know if you need an extension! \n\nWhenever you're ready to submit your finished artwork, dm '>submit' to this bot and attach your file(s) to the message! Please let your group leader know when you've submitted so that we can double check your submission. To change your submission, send the '>submit' command again and attach your updated file(s), this will replace all previous files. The final artwork deadline is **December 23rd**! \n\nHave fun! :D")
            sheet.update_cell(rowNum, PARTNER_COL, "sent")
        except:
          amber = client.get_user(AMBER_ID)
          await amber.send(str(rowNum) + " Unknown error sending giftee " + str(gifteeID) + " to gifter " + str(gifterID))

    #anyone sends submit command
    if message.content.startswith(">submit"):
      correctFileTypes = True
      senderID = message.author.id

      try:
        if message.attachments:
          allFiles = ""
          confirmMsg = ""
          fileCount = 0

          senderCell = sheet.find(str(senderID), in_row = None, in_column = GIFTER_ID_COL)

          if senderCell:
            senderRow = senderCell.row

            for i in range(len(message.attachments)):
              attachment = message.attachments[i]
              if attachment.content_type in ('image/jpeg', 'image/gif', 'image/png', 'image/heic', 'video/mp4'):
                file = attachment.url
                allFiles = allFiles + file + " "
                fileCount += 1
                confirmMsg = confirmMsg + ":white_check_mark: File " + str(i+1) + " received: " + file + "\n\n"
              else:
                correctFileTypes = False
                confirmMsg = confirmMsg + ":x: Error: File " + str(i+1) + " is not a jpeg, png, gif, heic or mp4 file!\n\n"

            await message.channel.send(confirmMsg)

            if correctFileTypes:
              try:
                sheet.update_cell(senderRow, ARTWORK_COL, allFiles)
                await message.channel.send(str(fileCount) + " file(s) submitted successfully!")
              except:
                await message.channel.send("Failed to add artwork to database. Please dm amber ASAP!")
            else:
              await message.channel.send("Submission failed. Please double check your file formats and try again!")

          else:
            await message.channel.send("No user found. Please dm amber ASAP!")
        else:
          await message.channel.send("No file detected. Please attach your file(s) to your '>submit' message!")
      except:
        await message.channel.send("Unknown error. Please dm amber ASAP!")

    #amber sends testsubmit command
    '''if message.content.startswith(">testsubmit") and message.author.id == AMBER_ID:
      confirmMsg = "gottem"
      fileCount = 1

      for i in range(participants):
        senderID = i

        try:
          file = "https://cdn.discordapp.com/attachments/1041724795357773957/1045794420781490326/anya_-_angry.png"
          senderCell = sheet.find(str(senderID), in_row = None, in_column = GIFTER_ID_COL)

          if senderCell:
            senderRow = senderCell.row

            await message.channel.send(confirmMsg)

            try:
              sheet.update_cell(senderRow, ARTWORK_COL, file)
              await message.channel.send(str(fileCount) + " file(s) submitted!")
            except:
              await message.channel.send("Failed to submit artwork. Please dm amber!")
          else:
            await message.channel.send("No user found. Please dm amber!")
        except:
          await message.channel.send("Unknown error. Please dm amber ASAP!")'''

    #amber sends serversendart command
    if message.content.startswith(">serversendart") and message.author.id == AMBER_ID:
      allPuns = ["Hold on for deer life, this artwork for @ will blow you away!", "This artwork for @ will make you fall in love at frost sight!", "This artwork for @ is snow amazing!", "This artwork for @ is looking tree-mendous!", "This gift for @ sleighs!", "This artwork for @ is the best thing since sliced (ginger)bread!", "This gorgeous gift for @ graces us with its presents!", "It’s rien-ning gorgeous artwork! This one’s for @!", "Tree-t your eyes to this amazing artwork for @!", "This gift for @ is be-yule-tiful!", "You have no i-deer how dazzling this artwork for @ is!", "This amazing gift for @ will leave you feeling santa-mental!", "This pine art for @ will spruce things up!", "This gift for @ is snow joke!", "This jolly artwork for @ will leave a fa-la-la-la-lasting impression!"]

      for i in range(participants):
        rowNum = i+2

        #avoid quota limit
        if (i + 1) % 30 == 0:
          await asyncio.sleep(60)

        gifteeID = int(sheet.cell(rowNum, GIFTEE_ID_COL).value)
        giftee = client.get_user(gifteeID)
        links = sheet.cell(rowNum, ARTWORK_COL).value

        try:
          if links == None:
            amber = client.get_user(AMBER_ID)
            await amber.send(str(rowNum) + " Giftee <@" + str(gifteeID) + "> no links")
          else:
            pun = random.choice(allPuns)
            allPuns.remove(pun)
            pun = pun.replace("@", "<@" + str(gifteeID) + ">")

            galleryChannel = client.get_channel(GALLERY_ID)
            await galleryChannel.send(pun + " " + links)

            if len(allPuns) == 0:
              allPuns = ["Hold on for deer life, this artwork for @ will blow you away!", "This artwork for @ will make you fall in love at frost sight!", "This artwork for @ is snow amazing!", "This artwork for @ is looking tree-mendous!", "This gift for @ sleighs!", "This artwork for @ is the best thing since sliced (ginger)bread!", "This gorgeous gift for @ graces us with its presents!", "It’s rien-ning gorgeous artwork! This one’s for @!", "Tree-t your eyes to this amazing artwork for @!", "This gift for @ is be-yule-tiful!", "You have no i-deer how dazzling this artwork for @ is!", "This amazing gift for @ will leave you feeling santa-mental!", "This pine art for @ will spruce things up!", "This gift for @ is snow joke!", "This jolly artwork for @ will leave a fa-la-la-la-lasting impression!"]
        except:
          amber = client.get_user(AMBER_ID)
          await amber.send(str(rowNum) + "Unknown error for giftee " + str(gifteeID))

    #amber sends dmsendart command
    '''if message.content.startswith(">dmsendart") and message.author.id == AMBER_ID:
      for i in range(participants):
        rowNum = i+2

        #avoid quota limit
        if (i + 1) % 30 == 0:
          await asyncio.sleep(60)

        gifteeID = int(sheet.cell(rowNum, GIFTEE_ID_COL).value)
        giftee = client.get_user(gifteeID)
        links = sheet.cell(rowNum, ARTWORK_COL).value

        try:
          if giftee == None:
            amber = client.get_user(AMBER_ID)
            await amber.send(str(rowNum) + " Giftee " + str(gifteeID) + " not in server")
          elif links == None:
            amber = client.get_user(AMBER_ID)
            await amber.send(str(rowNum) + " Giftee <@" + str(gifteeID) + "> no links")
          else:
            await giftee.send("Hey <@" + str(gifteeID) + ">! Here's the gift you recieved for Amber's Secret Santa 2022! " + links + "\n\nHead over to the #gift-gallery channel in the server to take a look at all the gifts from this event (including what you gifted)! You can also try to guess who your gifter was in the #gifter-guessing channel, the first person to guess correctly will be awarded their own emote in my main discord server, amber's jam jar: <https://discord.gg/hcgwvwApXR>, and everyone who guesses correctly will receive a special role! You have 5 guesses!")
        except:
          amber = client.get_user(AMBER_ID)
          await amber.send(str(rowNum) + " Unknown error for giftee " + str(gifteeID))'''

    if message.content.startswith(">editmsg") and message.author.id == AMBER_ID:
      channel = client.get_channel(GALLERY_ID)
      message = await channel.fetch_message(1056436525002403894)
      await message.edit(content="These artworks for <@1044953902065406003> are the best thing since sliced (ginger)bread! https://cdn.discordapp.com/attachments/1056215594644553779/1056602058272292974/ADBDC920-1386-4DC2-B16A-36855DFBE5D6.jpg https://cdn.discordapp.com/attachments/914323249884708965/1056436177206525952/Untitled_Artwork.png (there were a few complications with your gift, so you got 2!)")

keep_alive()
try:
  client.run(os.getenv("TOKEN"))
except:
  os.system("kill 1")


class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        #bucket sort

        bucket = [0]* (2*(10**4 )+ 1)
        counts = Counter(nums)
        # print(counts)

        for idx in range(len(bucket)-1, -1, -1):
            k -= counts[idx - 10**4]

            if k <= 0:
                return idx - 10**4


# Задание 1
def Work1():
    a = ['one', 'two', 'one', 'three', 'two']
    b={}
    for i in a:
        if i not in b.keys():
            b[i] = 0
        else:
            b[i] += 1
        print(b[i], end=' ')

# Задание 2
def Work2():
    a = int(input('Введите количество синонимов : '))
    print(a)
    b = [input('Введите  синонимы :').split() for i in range(a)]
    c = {}
    d = []
    for i in range(len(b)):
        for j in range(len(b[i])):
            if d == []:
                d = b[i][j]
            else:
                c[d] = b[i][j]
                c[b[i][j]] = d
        d= []
    print('Ответ : ', c[input()])

# Задание 3
def Work3():
    a = int(input())
    b = [input().split() for i in range(a)]
    c = {}
    for i in range(len(b)):
        b[i][1]=int(b[i][1])
        if b[i][0] not in c:
            c[b[i][0]] = b[i][1]
        else:
            c[b[i][0]] += b[i][1]
    for i in sorted(c.keys()):
        print(i,c[i])

# Задание 4

def Work4():
    a = int(input())
    b = [input().split() for i in range(a)]
    c = {}
    for i in range(len(b)):
        for j in range(len(b[i])):
            if b[i][j] in c:
                c[b[i][j]] +=1
            else:
                c[b[i][j]] = 1
    for i, j in sorted(c.items(), key = lambda para: (para[1], para[0]) ):
        print(i)
        break

# Задание 5
def Work5():
    a_score_file = int(input())
    b_file = [input().split() for i in range(a_score_file)]
    c = {'write': 'W', 'read': 'R', 'execute': 'X'}
    a_score_op = int(input())
    b_op = [input().split() for i in range(a_score_op)]
    for i in range(len(b_op)):
        if b_op[i][0] in c:
            b_op[i][0] = c[b_op[i][0]]
    for i in range(len(b_op)):
        for j in range(len(b_file)):
            if b_op[i][1] in b_file[j][0] and b_op[i][0] in b_file[j][1:]:
                print('OK')
                break
            elif j == len(b_file)-1:
                print('Denied')

# Задание 6
def Work6():
    a_score_file = int(input())
    b_file = [input().split() for i in range(a_score_file)]

    a_score_op = int(input())
    b_op = [input().split() for i in range(a_score_op)]
    c={}
    print(b_op)
    for i in range(len(b_file)):
        for j in range(1,len(b_file[i])):
            c[b_file[i][j]] = b_file[i][0]

    for i in range(len(b_op)):
        for j in range(len(b_op[i])):
            if b_op[i][j] in c:
                print(c[b_op[i][j]])

# Задание 7
def Work7():
    a = int(input())
    b = [input().split() for i in range(a)]
    c = {}
    for i in range(len(b)):
        for j in range(len(b[i])):
            if b[i][j] not in c:
                c[b[i][j]] = 1
            else:
                c[b[i][j]] += 1
    for i,j in sorted(c.items(), key= lambda par:(par[1]),reverse=True):
        print(i,j)

a = input('Введите номер работы :')
if a == 'Задание 1':
    Work1()
elif a == 'Задание 2':
    Work2()
elif a == 'Задание 3':
    Work3()
elif a == 'Задание 4':
    Work4()
elif a == 'Задание 5':
    Work5()
elif a == 'Задание 6':
    Work6()
elif a == 'Задание 7':
    Work7()

Сборник/Модульл_7.py

Модульл_7.py


# author: Jeremy Temple, Eli Manning
import enum

class Tokens(object):
    def __init__(self):
        self._data = []

    def __iter__(self):
        return iter(self._data)

    def append(self, token):
        self._data.append(token)

    @property
    def lookahead(self):
        return self._data[0]

    def consume(self):
        self._data.pop(0)

    def __str__(self):
        w = []
        for i in self._data:
            w.append("Kind: {0}\nValue: {1}\n\n".format(i._kind, i._value))
        return "".join(w)
class tokenenum(enum.Enum):
    BEGIN = enum.auto()
    DO = enum.auto()
    END = enum.auto()
    FALSE = enum.auto()
    HALT = enum.auto()
    IF = enum.auto()
    PRINT = enum.auto()
    PROGRAM = enum.auto()
    THEN = enum.auto()
    TRUE = enum.auto()
    VAR = enum.auto()
    WHILE = enum.auto()

class token(object):
    def __init__(self, kind, value):
        self._kind = kind
        self._value = value

    def __str__(self):
        return "{0} {1}".format(self.kind, self.value)

    @property
    def kind(self):
        return self._kind

    @property
    def value(self):
        return self._value

keywords = {"begin" : tokenenum.BEGIN,
           "do" : tokenenum.DO,
           "end" : tokenenum.END,
           "false" : tokenenum.FALSE,
           "halt" : tokenenum.HALT,
           "if" : tokenenum.IF,
            "print" : tokenenum.PRINT,
            "program" : tokenenum.PROGRAM,
            "then" : tokenenum.THEN,
            "true" : tokenenum.TRUE,
            "var" : tokenenum.VAR,
            "while" : tokenenum.WHILE}


#!/usr/bin/env python3
import os
import aws_cdk as cdk
# from eks_rds.eks_flask_rds_stack import EksFlaskRdsStack
from _stacks.eks_rds import EksRdsStack

env = cdk.Environment(
    account=os.environ.get("CDK_DEPLOY_ACCOUNT", os.environ["CDK_DEFAULT_ACCOUNT"]),
    region=os.environ.get("CDK_DEPLOY_REGION", os.environ["CDK_DEFAULT_REGION"]),
)

app = cdk.App()
EksRdsStack(app, "EksFlaskRdsStack", env=env)

app.synth()


#! /usr/bin/env python
# -*- coding   : utf-8 -*-
import os
import re
import ujson
from dotmap     import DotMap
from subprocess import check_output
from datetime   import datetime, timedelta

# output = '(Connected)' in check_output( "scutil --nc list".split( ' ' ) ).decode( 'utf-8' )

# print( output )
refresh_delta = timedelta( seconds = 10 )
now           = datetime.utcnow()
refresh_time  = now + refresh_delta

print( now )
print( refresh_time )

now_str          = now.isoformat()
refresh_time_str = refresh_time.isoformat()

print( now_str )
print( refresh_time_str )

now_reconstituted          = datetime.fromisoformat( now_str )
refresh_time_reconstituted = datetime.fromisoformat( refresh_time_str )

print( now_reconstituted )
print( refresh_time_reconstituted )

print( ['DONE'] )


'''
이름, 전화번호, 이메일, 주소를 받아서
연락처 입력, 출력, 삭제하는 프로그램을 개발하시오.
단, 인명은 여러명 저장 가능합니다.
'''

class Contacts(object):

    def __init__(self, name, tel, email, adress):
        self.name = name
        self.tel = tel
        self.email = email
        self.adress = adress

    def __str__(self):
        return f"{self.name} {self.tel} {self.email} {self.adress}"

    @staticmethod
    def result(ls):
        print(" ### 주소록 ### ")
        print("****************************")
        print("이름   전화번호    이메일 주소")
        print("****************************")
        [print(i) for i in ls]
        print("****************************")

    @staticmethod
    def delete(ls, name):
        for i,j in enumerate(ls):
            if j.name == name:
                del ls[i]

    @staticmethod
    def new_contacts():
        return Contacts(input(" 이름 : "), input(" 전화번호 : "),
                        input(" 이메일 : "), input(" 주소 : "))


def palindromo(palabra):
    pila = []
    for letra in palabra:
        pila.append(letra)
    palabra_invertida = ""
    while len(pila) > 0:
        palabra_invertida += pila.pop()
    return palabra == palabra_invertida

palabra = "reconocer"
if palindromo(palabra):
    print(f"La palabra: {palabra} es un palíndromo")
else:
    print(f"La palabra: {palabra} no es un palíndromo")


class Coche():
    ruedas=4
    puertas=5
    largoChasis=260
    anchoChasis=130
    arrancado=False

    def arrancar(self):
        self.arrancado=True

    def estadoCoche(self):
        if(self.arrancado):
            return "El coche está funcionando"
        else:
            return "El coche está parado"

mazda=Coche() #ejemplar de clase
mazda.puertas=3
print(str(mazda.puertas)+" "+str(mazda.largoChasis))
print(mazda.arrancado)
mazda.arrancar()
print(mazda.arrancado)
print(mazda.estadoCoche())


class Product():
    def __init__(self, key, transport):
        self.key = key
        self.transport = transport

    def Encryption(self, plaintext):
        # Make Key Info
        keyList = self.key.split(' ')
        tranList = self.transport.split(' ')

        # Encryption
        ciphertextList = [''] * len(keyList)
        for i in range(len(keyList)):
            pos = tranList.index(keyList[i])
            ciphertextList[pos] = plaintext[i]
        ciphertext = ''.join(ciphertextList)

        return ciphertext

    def Decryption(self, ciphertext):
        # Make Key Info
        keyList = self.key.split(' ')
        tranList = self.transport.split(' ')

        # Encryption
        plaintextList = [''] * len(keyList)
        for i in range(len(keyList)):
            pos = keyList.index(tranList[i])
            plaintextList[pos] = ciphertext[i]
        plaintext = ''.join(plaintextList)

        return plaintext

def main():
    key = "01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20"
    transport = "15 11 19 18 16 03 07 14 02 20 04 12 09 06 01 05 17 13 10 08"

    method = Product(key, transport)
    plaintext = 'keepgoingnevergiveup'
    ciphertext = method.Encryption(plaintext)
    print(ciphertext)
    print(method.Decryption(ciphertext))

if __name__ == '__main__':
    main()


import pytesseract
import os
import sys
from PIL import Image
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.pagesizes import A4
import fitz
import shutil

from PyQt5.QtGui     import *
from PyQt5.QtCore    import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMessageBox

class Form(QMainWindow):
    def __init__(self,parent=None):
        super().__init__(parent)

        getFileNameButton = QPushButton("Выбрать файл")
        getFileNameButton.clicked.connect(self.getFileName)
        getFileNameButton.setFixedSize(160,160)

        layoutV = QVBoxLayout()
        layoutV.addWidget(getFileNameButton)

        layoutH = QHBoxLayout()
        layoutH.addLayout(layoutV)

        centerWidget = QWidget()
        centerWidget.setLayout(layoutH)
        self.setCentralWidget(centerWidget)

        self.resize(200,200)
        self.setWindowTitle("PdfReader")

    def getFileName(self):
        filename, filetype = QFileDialog.getOpenFileName(self,
                             "Выбрать файл",
                             ".",
                             "PDF Files(*.pdf)")

        pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

        pdf_document = fitz.open(filename)

        try:
            os.mkdir("imagepdf")
        except OSError:
            None
        os.chdir("imagepdf")

        for current_page in range(len(pdf_document)):
            for image in pdf_document.getPageImageList(current_page):
                xref = image[0]
                pix = fitz.Pixmap(pdf_document, xref)
                if pix.n < 5:        # this is GRAY or RGB
                    pix.writePNG("%s.png" % (current_page))
                else:                # CMYK: convert to RGB first
                    pix1 = fitz.Pixmap(fitz.csRGB, pix)
                    pix1.writePNG("%s.png" % (current_page))
                    pix1 = None
                pix = None
        os.chdir('..')

        c = canvas.Canvas("Результат.pdf", pagesize=A4)

        for k in range(len(pdf_document)):
            os.chdir("imagepdf")
            img = Image.open(str(k) + '.png')
            os.chdir('..')

            custom_config = r'--oem 3 --psm 6'

            text = pytesseract.image_to_string(img, lang='rus', config= custom_config)

            with open('Text.txt', 'w', encoding="cp1251") as text_file:
                text_file.write(text)

            sumtext = sum(1 for line in open('Text.txt'))
            l = []
            pdfmetrics.registerFont(TTFont('FreeSans', 'FreeSans.ttf'))
            c.setFont('FreeSans', 14)
            i = 29.0
            with open('Text.txt', 'r+') as sumtext:
                for l in sumtext:
                    i = i - 0.5
                    c.drawString(0.5 * cm, i * cm, l.rstrip())
            if os.path.isfile('Text.txt'):
                os.remove('Text.txt')
            else: print("File doesn't exists!")
            c.showPage()
            m = k + 1

            if m == len(pdf_document):
                QMessageBox.about(self, "Выполнено", "Выполнено")
                c.save()

        shutil.rmtree("imagepdf") #удалить директорию с фото

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Form()
    ex.show()
    sys.exit(app.exec_())


import pygame
import sys

class UI:

    def __init__(self, UIdeck):
        self.drawMap = {0:self.drawPlayer1, 1:self.drawPlayer2, 2:self.drawPlayer3, 3:self.drawPlayer4}
        self.discardMap = {0:self.discardCardP1, 1:self.discardCardP2, 2:self.discardCardP3, 3:self.discardCardP4}
        pygame.init()
        width = 800
        height = 600
        gameOver = False

        ## makes the screen
        self.screen = pygame.display.set_mode((width,height))
        pygame.display.set_caption('Uno')

        black = (0,0,0)
        white = (255,255,255)
        self.transparent = (0, 0, 0, 0)

        self.cards= ['images/black_+4.png','images/black_+4.png','images/black_+4.png','images/black_+4.png','images/black_wildcard.png','images/black_wildcard.png','images/black_wildcard.png','images/black_wildcard.png',
                 'images/blue_+2.png','images/blue_0.png', 'images/blue_1.png', 'images/blue_2.png', 'images/blue_3.png', 'images/blue_4.png', 'images/blue_5.png', 'images/blue_6.png', 'images/blue_7.png', 'images/blue_8.png', 'images/blue_9.png', 'images/blue_reverse.png', 'images/blue_skip.png',
                 'images/green_+2.png','images/green_0.png', 'images/green_1.png', 'images/green_2.png', 'images/green_3.png', 'images/green_4.png', 'images/green_5.png', 'images/green_6.png', 'images/green_7.png', 'images/green_8.png', 'images/green_9.png', 'images/green_reverse.png', 'images/green_skip.png',
                 'images/red_+2.png','images/red_0.png', 'images/red_1.png', 'images/red_2.png', 'images/red_3.png', 'images/red_4.png', 'images/red_5.png', 'images/red_6.png', 'images/red_7.png', 'images/red_8.png', 'images/red_9.png', 'images/red_reverse.png', 'images/red_skip.png',
                 'images/yellow_+2.png','images/yellow_0.png', 'images/yellow_1.png', 'images/yellow_2.png', 'images/yellow_3.png', 'images/yellow_4.png', 'images/yellow_5.png', 'images/yellow_6.png', 'images/yellow_7.png', 'images/yellow_8.png', 'images/yellow_9.png', 'images/yellow_reverse.png', 'images/yellow_skip.png',]

        for card in UIdeck:
            if card.color == 'wild':
                card.color = 'black'
            if card.value == 'basic':
                card.value = 'wildcard'
        # print(UIdeck)

        self.cardMap = {card:'images/' + card.color + '_' + str(card.value) + '.png' for card in UIdeck}
        self.reverseMap = {'images/' + card.color + '_' + str(card.value) + '.png':card for card in UIdeck}
        self.deck = []
        self.discard = []
        self.player1Hand = []
        self.player2Hand = []
        self.player3Hand = []
        self.player4Hand = []
        self.player1XPoints = []
        self.player2XPoints = []
        self.player3XPoints = []
        self.player4XPoints = []
        self.screen.fill(black)
        self.turnCondition = True
        self.dealDeck(card)

    ## deals all the cards to player 1 and loads them onto the screen, keeping track of what cards are in player 1's hand and where they are on the screen
    def dealPlayer1(self, hand):
        x = 0
        y = 10
        for card in hand:
            image = pygame.image.load(self.cardMap[card])
            self.player1Hand.append(self.cardMap[card])
            self.screen.blit(image, (x,y))
            self.player1XPoints.append(x)
            x += 50

    ## deals all the cards to player 2 and loads them onto the screen, keeping track of what cards are in player 2's hand and where they are on the screen
    def dealPlayer2(self, hand):
        x =  10
        y = 135
        for card in hand:
            image = pygame.image.load(self.cardMap[card])
            self.player2Hand.append(self.cardMap[card])
            self.screen.blit(image, (x,y))
            self.player2XPoints.append(x)
            x += 25

    ## deals all the cards to player 3 and loads them onto the screen, keeping track of what cards are in player 3's hand and where they are on the screen
    def dealPlayer3(self, hand):
        x =  10
        y = 260
        for card in hand:
            image = pygame.image.load(self.cardMap[card])
            self.player3Hand.append(self.cardMap[card])
            self.screen.blit(image, (x,y))
            self.player3XPoints.append(x)
            x += 25

    ## deals all the cards to player 4 and loads them onto the screen, keeping track of what cards are in player 4's hand and where they are on the screen
    def dealPlayer4(self, hand):
        x =  10
        y = 385
        for card in hand:
            image = pygame.image.load(self.cardMap[card])
            self.player4Hand.append(self.cardMap[card])
            self.screen.blit(image, (x,y))
            self.player4XPoints.append(x)
            x += 25

## after cards are dealt to each player, the remaining cards are displayed as a stack in the center of the screen
## and flips the first card over to start the game
    def dealDeck(self, card = None):
        x =  540
        y = 260
        image = pygame.image.load('images/back.png')
        self.screen.blit(image, (x,y))
        # image = pygame.image.load(self.cardMap[card])
        # self.screen.blit(image, (440,260))

    def draw(self, player, card):
        self.drawMap[player](card)

    def drawPlayer1(self, card):
        self.player1Hand.append(self.cardMap[card])
        size1X = len(self.player1XPoints)
        nextPoint = self.player1XPoints[size1X-1] + 25
        self.player1XPoints.append(nextPoint)
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (nextPoint,10))
        pygame.display.update()

    ## when called, will draw a card from the draw pile and add it to player 2's hand
    def drawPlayer2(self, card):
        self.player2Hand.append(self.cardMap[card])
        size2X = len(self.player2XPoints)
        nextPoint = self.player2XPoints[size2X-1] + 25
        self.player2XPoints.append(nextPoint)
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (nextPoint,135))
        pygame.display.update()

    ## when called, will draw a card from the draw pile and add it to player 3's hand
    def drawPlayer3(self, card):
        self.player3Hand.append(self.cardMap[card])
        size3X = len(self.player3XPoints)
        nextPoint = self.player3XPoints[size3X-1] + 25
        self.player3XPoints.append(nextPoint)
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (nextPoint,260))
        pygame.display.update()

    ## when called, will draw a card from the draw pile and add it to player 4's hand
    def drawPlayer4(self, card):
        self.player4Hand.append(self.cardMap[card])
        size4X = len(self.player4XPoints)
        nextPoint = self.player4XPoints[size4X-1] + 25
        self.player4XPoints.append(nextPoint)
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (nextPoint,385))
        pygame.display.update()

    def discardfoo(self, player, card):
        # print(self.player1Hand)
        # print(self.player2Hand)
        # print(self.player3Hand)
        # print(self.player4Hand)
        # print(card)
        # print(self.cardMap[card])
        print('p'+str(player+1), 'discarded', card)
        self.discardMap[player](card)

    def discardCardP1(self, card):
        self.discard.append(self.cardMap[card])
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (440,260))
        pygame.display.update()
        self.player1Hand.remove(self.cardMap[card])
        lastI = len(self.player1XPoints)-1
        self.player1XPoints.remove(self.player1XPoints[lastI])
        pygame.draw.rect(self.screen, self.transparent,(0,10,600,125))
        pygame.display.update()

        for x_point in self.player1XPoints:
            index = self.player1XPoints.index(x_point)
            card = self.player1Hand[index]
            image = pygame.image.load(card)
            self.screen.blit(image, (x_point,10))
            pygame.display.update()

    def discardCardP2(self, card):
        self.discard.append(self.cardMap[card])
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (440,260))
        pygame.display.update()

        self.player2Hand.remove(self.cardMap[card])
        lastI = len(self.player2XPoints)-1
        self.player2XPoints.remove(self.player2XPoints[lastI])
        pygame.draw.rect(self.screen, self.transparent,(10,135,600,125))
        pygame.display.update()

        for x_point in self.player2XPoints:
            index = self.player2XPoints.index(x_point)
            card = self.player2Hand[index]
            image = pygame.image.load(card)
            self.screen.blit(image, (x_point,135))
            pygame.display.update()

    def discardCardP3(self, card):
        # print(card)
        # print(self.cardMap[card])
        self.discard.append(self.cardMap[card])
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (440,260))
        pygame.display.update()

        self.player3Hand.remove(self.cardMap[card])
        lastI = len(self.player3XPoints)-1
        self.player3XPoints.remove(self.player3XPoints[lastI])
        pygame.draw.rect(self.screen, self.transparent, (10,260,400,125))
        pygame.display.update()

        for x_point in self.player3XPoints:
            index = self.player3XPoints.index(x_point)
            card = self.player3Hand[index]
            image = pygame.image.load(card)
            self.screen.blit(image, (x_point,260))
            pygame.display.update()

    def discardCardP4(self, card):
        self.discard.append(self.cardMap[card])
        image = pygame.image.load(self.cardMap[card])
        self.screen.blit(image, (440,260))
        pygame.display.update()

        self.player4Hand.remove(self.cardMap[card])
        lastI = len(self.player4XPoints)-1
        self.player4XPoints.remove(self.player4XPoints[lastI])
        pygame.draw.rect(self.screen, self.transparent,(10,385,600,125))
        pygame.display.update()

        for x_point in self.player4XPoints:
            index = self.player4XPoints.index(x_point)
            card = self.player4Hand[index]
            image = pygame.image.load(card)
            self.screen.blit(image, (x_point,385))
            pygame.display.update()

    def humanTurn(self, drawnCard = None):
        print('v')
        events = []
        drawn = False
        while True:
            # print('y')
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    print('quitted')
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN: ## if there is a mouse click
                    if not drawn:
                        print('sdf')
                        if event.pos[0] > 540 and event.pos[0] < 600:
                            if event.pos[1] > 265 and event.pos[1] < 365: ## if the click is on the draw pile -> player 1 gets that card in it's hand
                                if self.turnCondition: return 'draw a card'
                                drawn = True
                                self.player1Hand.append(self.cardMap[drawnCard])
                                size1X = len(self.player1XPoints)
                                nextPoint = self.player1XPoints[size1X-1] + 50
                                self.player1XPoints.append(nextPoint)
                                print(self.cardMap[drawnCard])
                                image = pygame.image.load(self.cardMap[drawnCard])
                                self.screen.blit(image, (nextPoint,10))
                                pygame.display.update()

                    if event.pos[1] > 10 and event.pos[1] < 110:
                        for xPos in self.player1XPoints:
                            if event.pos[0] > xPos and event.pos[0] < xPos + 50:
                                index = self.player1XPoints.index(xPos)
                                selectedCard = self.player1Hand[index]
                                self.discard.append(selectedCard)
                                image = pygame.image.load(selectedCard)
                                self.screen.blit(image, (440,260))
                                pygame.display.update()
                                self.player1Hand.remove(selectedCard)
                                lastI = len(self.player1XPoints)-1
                                self.player1XPoints.remove(self.player1XPoints[lastI])
                                pygame.draw.rect(self.screen, self.transparent,(0,10,600,125))
                                pygame.display.update()

                                for x_point in self.player1XPoints:
                                    index = self.player1XPoints.index(x_point)
                                    card = self.player1Hand[index]
                                    image = pygame.image.load(card)
                                    self.screen.blit(image, (x_point,10))
                                    pygame.display.update()

                                return ('discard', self.reverseMap[selectedCard])
# deal()
# chooseCardP2(random.choice(player2Hand))
# chooseCardP3(random.choice(player3Hand))
# chooseCardP4(random.choice(player4Hand))
# ##drawPlayer3()
# ##drawPlayer4()

# pygame.display.update()
# while not gameOver:
#     for event in pygame.event.get():
#         if event.type == pygame.QUIT:
#             sys.exit()
#         if event.type == pygame.MOUSEBUTTONDOWN: ## if there is a mouse click
#             if event.pos[0] > 540 and event.pos[0] < 600:
#                 if event.pos[1] > 265 and event.pos[1] < 365: ## if the click is on the draw pile -> player 1 gets that card in it's hand
#                     card = deck.pop()
#                     player1Hand.append(card)
#                     size1X = len(player1XPoints)
#                     nextPoint = player1XPoints[size1X-1] + 50
#                     player1XPoints.append(nextPoint)
#                     image = pygame.image.load(card)
#                     screen.blit(image, (nextPoint,10))
#                     pygame.display.update()
#
#             if event.pos[1] > 10 and event.pos[1] < 110:
#                 for xPos in player1XPoints:
#                     if event.pos[0] > xPos and event.pos[0] < xPos + 50:
#                         index = player1XPoints.index(xPos)
#                         selectedCard = player1Hand[index]
#
#                         discard.append(selectedCard)
#                         image = pygame.image.load(selectedCard)
#                         screen.blit(image, (440,260))
#                         pygame.display.update()
#                         player1Hand.remove(selectedCard)
#                         lastI = len(player1XPoints)-1
#                         player1XPoints.remove(player1XPoints[lastI])
#                         pygame.draw.rect(screen, self.transparent,(0,10,600,125))
#                         pygame.display.update()
#
#                         for x_point in player1XPoints:
#                             index = player1XPoints.index(x_point)
#                             card = player1Hand[index]
#                             image = pygame.image.load(card)
#                             screen.blit(image, (x_point,10))
#                             pygame.display.update()
#
#                         break
#
#
# pygame.display.update()

##pygame.quit()
##quit()


# 该程序用动态规划算法
# 判断回文串可用判断s == s[::-1]

def longestPalindrome(s):
    length = len(s)
    # 如果本身为回文数,则直接返回
    if s == s[::-1]:
        return s
    # 设置最大长度和开始索引
    max_len, begin = 1, 0
    for i in range(1, length):
        odd = s[i - max_len - 1:i + 1]
        even = s[i - max_len:i + 1]
        if i - max_len >= 1 and odd == odd[::-1]:
            begin = i - max_len - 1
            max_len += 2
            continue
        if i - max_len >= 0 and even == even[::-1]:
            begin = i - max_len
            max_len += 1
    return s[begin:begin + max_len]

if __name__ == "__main__":
    s = "abaa"
    s = longestPalindrome(s)
    print(s)


import pyrealsense2 as rs
import numpy as np
from pybot.cmn_structs import *
from pybot.sensor_structs import *

class RealsenseInterface():
    def __init__(self):
        self.pipeline = rs.pipeline()
        config = rs.config()
        config.enable_stream(rs.stream.depth,1280, 720, rs.format.z16, 30)
        config.enable_stream(rs.stream.color, 1920, 1080, rs.format.bgr8, 30)
        config.enable_stream(rs.stream.accel, rs.format.motion_xyz32f, 250)
        config.enable_stream(rs.stream.gyro, rs.format.motion_xyz32f, 200)
        # Start streaming
        profile = self.pipeline.start(config)
        depth_sensor = profile.get_device().first_depth_sensor()
        align_to = rs.stream.color
        self.align = rs.align(align_to)

    def __next__(self):
        frames = self.pipeline.wait_for_frames()
        # Align the depth frame to color frame
        aligned_frames = self.align.process(frames)

        # Get aligned frames
        aligned_depth_frame = aligned_frames.get_depth_frame() # aligned_depth_frame is a 640x480 depth image
        color_frame = aligned_frames.get_color_frame()
        for frame in frames:
            if frame.is_motion_frame():
                pose_frame = frame.as_motion_frame().get_motion_data()
        # Validate that both frames are valid
        if not aligned_depth_frame or not color_frame:
            print("Either color or depth frame is invalid, skipping")
            return

        depth_image = np.array(aligned_depth_frame.get_data()).astype(np.int64)
        color_image = np.array(color_frame.get_data()).astype(np.int64)

        i = color_frame.profile.as_video_stream_profile().get_intrinsics()
        intrin = np.array([[i.fx,0,i.ppx,0],[0,i.fy,i.ppy,0],[0,0,1,0],[0,0,0,1]]).astype(np.int64)

        #convert to our structs
        header = make_header()
        height,width=color_image.shape[:2]
        color_image = Image(header,height,width,"BGR8",color_image)
        depth_image = Image(header,height,width,"Z16",depth_image)
        intrin = CameraInfo(height,width,None,None,intrin,None,None)
        return {'color':color_image,'depth':depth_image,'intrin':intrin}


import os
import sys
import numpy as np
from collections import OrderedDict

def groupSinglets(comp_name):
    d = { "sm": "SM",
          "lin": "L ",
          "quad": "Q ",
          "lin_mixed": "M ",
          "sm_lin_quad": "SM+L+Q ",
          "quad_mixed": "Q+Q+M ",
          "sm_lin_quad_mixed": "SM+L+L+Q+Q+M ",
          "DATA": "DATA"
        }

    type_ = comp_name.split("_c")[0]
    if type_ in d:
        newName = d[type_]
    else:
        return comp_name

    if type_ != "sm" and type_!= "DATA": #need to account for operators here
        ops = comp_name.split(type_ + "_")[1]
        if len(ops.split("_")) == 2:
            ops = ops.split("_")
            newName += ops[0] + " " + ops[1]
        else:
            newName += ops

    return newName

def isBSM(sample):
    if any(i in sample for i in ["sm_", "quad_", "lin_"]):
        return True
    else:
        return False

def makeStructure(h_dict, model, outdir, isMkDC = True):

    for sample in h_dict:
        if isMkDC:
            first_var = h_dict[sample].keys()[0]
            structure = h_dict[sample][first_var].keys()
        else:
            structure = h_dict[sample]

        file_name = outdir + "/structure_" + sample + "_" + model + ".py"
        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        for key in structure:

            isData = 0
            if key == "DATA": isData = 1

            f.write('structure["{}"]  = {} \n'.format(key, "{"))
            f.write("        'isSignal' : 0, \n")
            f.write("        'isData' : {}, \n".format(isData))
            f.write("{}\n".format("}"))
            f.write("\n\n")

        f.close()

# THIS FUNCTION IS TERRIBLE, HOPEFULLY SOMEONE STRONG OF HEART WILL FIX IT
# anyway we do not need the Latinos plot card redineed in order to generate the datacards
def makePlot(h_dict, model, config, outdir, isMkDC = True):

    colors = config.getlist("d_plot", "colors")
    c_types = [i.split(":")[0] for i in colors]
    c_vals = [[int(j) for j in i.split(":")[1:]] for i in colors]

    user_colors = {}
    for i,j in zip(c_types, c_vals):
        user_colors[i] = j

    group = []
    g_colors = []

    if config.has_option("d_plot", "isSignal"):
        isSignal = config.getlist("d_plot", "isSignal")
        comp = [i.split(":")[0] for i in isSignal]
        val = [i.split(":")[1] for i in isSignal]
        isSignal = dict((c,v) for c,v in zip(comp, val))

    else:
        isSignal = {}

    if config.has_option("d_plot", "group"): group = config.getlist("d_plot", "group")
    if config.has_option("d_plot", "g_colors"): g_colors = [int(col) for col in config.getlist("d_plot", "g_colors")]

    for sample in h_dict:
        if isMkDC:
            first_var = h_dict[sample].keys()[0]
            structure = h_dict[sample][first_var].keys()
        else:
            structure = h_dict[sample]

        ops = sample.split("_")[1:]

        cd = {}

        for key in user_colors.keys():
            if key != "sm" and key not in config.getlist("variables", "makeDummy"):
                if len(user_colors[key]) == len(ops):
                    for j,op in enumerate(ops):
                        cd[key + "_" + op] = user_colors[key][j]

                if len(user_colors[key]) < len(ops):
                    if key + "_" + "_".join(op for op in ops) in structure:
                        cd[key + "_" + "_".join(op for op in ops)] = user_colors[key][0]
                    else:
                        cd[key + "_" + "_".join(op for op in ops[::-1])] = user_colors[key][0]

                if len(user_colors[key]) > len(ops):
                    for j,op in enumerate(ops):
                        cd[key + "_" + op] = user_colors[key][j]
            else:
                cd[key] = user_colors[key][0]

        for key in config.getlist("variables", "makeDummy"):
            if key not in user_colors.keys():
                cd[key] = 1

        file_name = outdir + "/plot_" + sample + "_" + model + ".py"
        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        for idx,g_ in enumerate(group):

            group_these = {}

            if  g_.split(":")[1] == "BSM":

                g_name = g_.split(":")[0]
                if g_name == "model": g_name = model

                group_these[g_name] = {}

                if g_name in isSignal.keys(): sig_val = isSignal[g_name]
                else: sig_val = 2

                group_these[g_name]['nameHR'] = "'{}'".format(g_name)
                group_these[g_name]['isSignal'] = sig_val
                group_these[g_name]['color'] = g_colors[idx]
                group_these[g_name]['samples'] = []
                components = h_dict[sample][h_dict[sample].keys()[0]].keys() #they are equal forall variables

                for comp in components:
                    if isBSM(comp): group_these[g_name]['samples'].append(comp)

            elif g_.split(":")[1] == "all":
                for i,key in enumerate(structure):
                    if key != "DATA":
                        leg_name = groupSinglets(key)
                        group_these[key] = {}

                        if key in isSignal.keys(): sig_val = isSignal[key]
                        else: sig_val = 2

                        # thisif else are ridicolous now
                        if key not in cd.keys(): cd[key] = 1

                        group_these[key]['nameHR'] = "'{}'".format(leg_name)
                        group_these[key]['isSignal'] = sig_val
                        group_these[key]['color'] = cd[key]
                        group_these[key]['samples'] = [key]

            else:
                g_name = g_.split(":")[0]
                g_list = [str(i) for i in (g_.split(":")[1])[1:-1].split(" ")]

                group_these[g_name] = {}

                if g_name in isSignal.keys(): sig_val = isSignal[g_name]
                else: sig_val = 2

                group_these[g_name]['nameHR'] = "'{}'".format(g_.split(":")[0])
                group_these[g_name]['isSignal'] = sig_val
                group_these[g_name]['color'] = g_colors[idx]
                group_these[g_name]['samples'] = []

                components = h_dict[sample][h_dict[sample].keys()[0]].keys() #they are equal forall variables

                for comp in g_list:
                    if comp not in components:
                        sys.exit("[ERROR] The sample {} specified for grouping into {} does not exists ...".format(comp, g_name))

                    group_these[g_name]['samples'].append(comp)

            if len(group_these.keys()) != 0:

                #sort the dict to allow right plotting
                group_these = OrderedDict(sorted(group_these.items(), key=lambda t: t[1]["isSignal"], reverse=True))

                for key in group_these.keys():
                    f.write('groupPlot["{}"]  = {} \n'.format(key, "{"))
                    for subkey in group_these[key]:
                        if subkey != 'samples':
                            f.write("        '{}' : {}, \n".format(subkey, group_these[key][subkey]))
                        else:
                            write_list = "["
                            for s in group_these[key][subkey]:
                                write_list += "'{}'".format(s) + ","

                            write_list = write_list[:-1] + "]"
                            f.write("        '{}' : {}, \n".format(subkey, write_list))

                    f.write("{}\n".format("}"))
                    f.write("\n\n")

        for i,key in enumerate(structure):

            if key in isSignal.keys(): sig_val = isSignal[key]
            else: sig_val = 2

            isData = 0
            if key == "DATA":
                isData = 1

            color = 1
            if key in cd:
                color = cd[key]

            if i > len(cd.keys()): sys.exit("[ERROR]: Colors not sufficient, add more...")

            f.write('plot["{}"]  = {} \n'.format(key, "{"))
            f.write("        'color' : {}, \n".format(cd[key]))
            f.write("        'isSignal' : {}, \n".format(sig_val))
            f.write("        'isData' : {}, \n".format(isData))
            f.write("        'scale' : 1, \n")

            if key == "DATA":
                f.write("        'isBlind' : 1, \n") #default blinding on data

            f.write("{}\n".format("}"))
            f.write("\n\n")

        f.close()

def makeVariables(h_dict, model, config, outdir):

    xaxis_ = config.getlist("d_variables", "xaxis")
    name_ = config.getlist("d_variables", "name")
    range_ = config.getlist("d_variables", "range")
    fold_ = config.getlist("d_variables", "fold")

    for sample in h_dict:
        vars_ = h_dict[sample].keys()

        bl = len(vars_)
        #if not all(len(lst) == bl for lst in [xaxis_, name_, range_, fold_]):

        if xaxis_[0] == "auto": xaxis_ = dict((i,j) for i,j in zip(vars_, vars_))
        elif len(xaxis_) == len(vars_):
            tn = config.getlist("variables", "treenames")
            xaxis_ = dict((i,j) for i,j in zip(tn, xaxis_))
        else:
            sys.exit("[ERROR] xaxis name do not match variables, check inputs in cfg ...")

        if name_[0] == "auto": name_ = dict((i,j) for i,j in zip(vars_, vars_))
        elif len(name_) == len(vars_):
            tn = config.getlist("variables", "treenames")
            name_ = dict((i,j) for i,j in zip(tn, name_))
        else:
            sys.exit("[ERROR] names do not match variables, check inputs in cfg ...")

        if fold_[0] == "auto": fold_ = dict((i,0) for i in vars_)
        elif len(fold_) == len(vars_):
            tn = config.getlist("variables", "treenames")
            fold_ = dict((i,j) for i,j in zip(tn, fold_))
        else:
            sys.exit("[ERROR] folds do not match variables, check inputs in cfg ...")

        if range_[0] == "auto":
            tn = config.getlist("variables", "treenames")
            range_ = dict.fromkeys(tn)
            bins = [int(i) for i in config.getlist("variables", "bins")]
            ranges = [i[1:-1].split(":") for i in config.getlist("variables", "xrange")]
            ranges = [list(map(float, sublist)) for sublist in ranges]

            for k,b,r in zip(range_.keys(), bins, ranges):
                range_[k] = {'bins': b, 'range': [r[0], r[1]]}

        elif len(range_) == len(vars_):
            tn = config.getlist("variables", "treenames")
            range_ = dict((i,j) for i,j in zip(tn, range_))
        else:
            sys.exit("[ERROR] ranges do not match variables, check inputs in cfg ...")

        file_name = outdir + "/variables_" + sample + "_" + model + ".py"
        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        for var, xa, name, ra, fold in zip(vars_, xaxis_, name_, range_, fold_):

            f.write('variables["{}"]  = {} \n'.format(var, "{"))
            f.write("        'name' : '{}', \n".format(name_[var]))
            f.write("        'range' : ({},{},{}), \n".format(range_[var]['bins'], range_[var]['range'][0], range_[var]['range'][1]))
            f.write("        'xaxis' : {}, \n".format(xaxis_[var]))
            f.write("        'fold' : {}, \n".format(fold_[var]))
            f.write("{}\n".format("}"))
            f.write("\n\n")

        f.close()

def makeSamples(h_dict, model, config, outdir, isMkDC = True):

    for sample in h_dict:
        if isMkDC:
            first_var = h_dict[sample].keys()[0]
            structure = h_dict[sample][first_var].keys()
        else:
            structure = h_dict[sample]

        file_name = outdir + "/samples_" + sample + "_" + model + ".py"
        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        f.write("import os \n")
        f.write("import inspect \n")
        f.write("configurations = os.path.realpath(inspect.getfile(inspect.currentframe())) # this file \n")
        f.write("configurations = os.path.dirname(configurations) \n\n")
        f.write("from LatinoAnalysis.Tools.commonTools import getSampleFiles, getBaseW, addSampleWeight\n\n")

        #Samples declaration
        f.write("# samples\n\n")
        f.write("try:\n")
        f.write("   len(samples)\n")
        f.write("except NameError:\n")
        f.write("   import collections\n")
        f.write("   samples = collections.OrderedDict()")
        f.write("\n\n")

        names = config.getlist("d_samples", "name")
        w = config.getlist("d_samples", "weight")
        ws = config.getlist("d_samples", "weights")
        fxj = config.getlist("d_samples", "filesperjob")

        if len(names) == len(w) == len(ws) == len(fxj) == 1:
            names = names*len(structure)
            w = w*len(structure)
            ws = ws*len(structure)
            fxj = fxj*len(structure)

        elif len(names) == len(w) == len(ws) == len(fxj) != len(structure):
            sys.exit("[ERROR] While making sample, provide a list of parameters = to number of EFT component \
                        or only one value (repeated). Nothing inbetween ...")
        else:
            sys.exit("[ERROR] While making sample, provide a list of parameters = to number of EFT component \
                        or only one value (repeated). Nothing inbetween ...")

        for i,key in enumerate(structure):

            f.write('samples["{}"]  = {} \n'.format(key, "{"))
            f.write("        'name' : {}, \n".format(names[i]))
            f.write("        'weight' : {}, \n".format(w[i]))
            f.write("        'weights' : {}, \n".format(ws[i]))
            f.write("        'isData' : 0, \n")
            f.write("        'FilesPerJob' : {}, \n".format(fxj[i]))
            f.write("{}\n".format("}"))
            f.write("\n\n")

        f.close()

def makeConfiguration(h_dict, model, config, outdir):

    for sample in h_dict:

        file_name = outdir + "/configuration_" + sample + "_" + model + ".py"

        write_out = {}

        write_out["tag"] = config.get("d_configuration", "tag")

        aliasesFile = config.get("d_configuration", "aliasesFile")
        if aliasesFile == "auto":
            aliasesFile = "aliases_" + sample + "_" + model + ".py"
        write_out["aliasesFile"] = aliasesFile

        variablesFile = config.get("d_configuration", "variablesFile")
        if variablesFile == "auto":
            variablesFile = "variables_" + sample + "_" + model + ".py"
        write_out["variablesFile"] = variablesFile

        cutsFile = config.get("d_configuration", "cutsFile")
        if cutsFile == "auto":
            cutsFile = "cuts_" + sample + "_" + model + ".py"
        write_out["cutsFile"] = cutsFile

        samplesFile = config.get("d_configuration", "samplesFile")
        if samplesFile == "auto":
            samplesFile = "samples_" + sample + "_" + model + ".py"
        write_out["samplesFile"] = samplesFile

        plotFile = config.get("d_configuration", "plotFile")
        if plotFile == "auto":
            plotFile = "plot_" + sample + "_" + model + ".py"
        write_out["plotFile"] = plotFile

        structureFile = config.get("d_configuration", "structureFile")
        if structureFile == "auto":
            structureFile = "structure_" + sample + "_" + model + ".py"
        write_out["structureFile"] = structureFile

        nuisancesFile = config.get("d_configuration", "nuisancesFile")
        if nuisancesFile == "auto":
            nuisancesFile = "nuisances_" + sample + "_" + model + ".py"
        write_out["nuisancesFile"] = nuisancesFile

        write_out["lumi"] = config.get("d_configuration", "lumi")
        write_out["outputDirPlots"] = config.get("d_configuration", "outputDirPlots")
        write_out["outputDirDatacard"] = config.get("d_configuration", "outputDirDatacard")

        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        for key, value in write_out.items():
            if type(value) == str:
                f.write("{} = '{}' \n\n".format(key, value))
            else:
                f.write("{} = {} \n\n".format(key, value))

        f.close()

def makeAliases(h_dict, model, outdir):

    for sample in h_dict:

        file_name = outdir + "/aliases_" + sample + "_" + model + ".py"
        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        f.write('aliases["inclusive"] = {} \n'.format("{"))
        f.write("      'expr': 0 == 0'\n".format("{"))
        f.write("{}\n".format("}"))
        f.write("\n\n")

        f.close()

def makeCuts(h_dict, model, outdir):

    for sample in h_dict:

        file_name = outdir + "/cuts_" + sample + "_" + model + ".py"
        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        f.write("cuts['{}'] = {} \n".format(sample, "{"))
        f.write("  'expr': 'inclusive', \n")
        f.write("{}\n".format("}"))
        f.write("\n\n")

        f.close()

def whatNuis(comp):

    test = np.array(["sm", "lin", "quad", "mixed"])
    base = np.array(comp.split("_")) #sm #lin #quad #

    if base.size == 1: return base #only identical sm has 1 len

    mask = np.isin(base, test)
    c = base[mask]
    ops = np.setdiff1d(base, c)

    #so finally this component
    #receives nuis contributions from these

    final = [mod + "_" + op  for mod in c if mod != "sm" for op in ops]
    if "sm" in c:
        final.append("sm")

    return final

def propagateNuis(h_dict, nuis_dict):

    var = h_dict.keys()[0]
    s_int = h_dict[var].keys()

    for key_name in nuis_dict.keys():
        samples_dict = nuis_dict[key_name]['samples']

        for sam in samples_dict.keys():
            sam_nuis_prop = 0
            c = whatNuis(sam)
            sample_nuis = samples_dict[sam] - 1

            #propagation
            if sam in s_int:
                #comp_yield = float('%.4f'%h_dict[var][sam].Integral())
                comp_yield = h_dict[var][sam].Integral()
            else: continue

            for basic_component in c:
                if basic_component in s_int and basic_component in samples_dict.keys():
                    #yield_ = float('%.4f'%h_dict[var][basic_component].Integral())
                    yield_ = h_dict[var][basic_component].Integral()

                    sam_nuis_prop += (yield_ * samples_dict[basic_component]) / comp_yield

            nuis_dict[key_name]['samples'][sam] = sam_nuis_prop

    return nuis_dict

# def switchNuis(comp_1, nuis_comp_1, comp_2):
#     #this stands also if the component is not sm
#     #print("sigma_{} = ({}-1) * {}/{} + 1 = {}".format("2", nuis_comp_1, comp_1, comp_2, (nuis_comp_1 - 1) * float(comp_1)/comp_2 + 1))
#     return (nuis_comp_1 - 1) * float(comp_1)/comp_2 + 1

# def propagateNuis(h_dict, nuis_dict):

#     #only lnN nuisances can be propagated
#     #checks are made

#     for nuis_name in nuis_dict.keys():
#         if nuis_dict[nuis_name]['type'] == "lnN":
#             if len(nuis_dict[nuis_name]['samples'].keys()) > 1:
#                 sys.exit("[ERROR] Cannot propagate more than one nuisance, there is \
#                 ambiguity... Please insert only one component for each nuisance and it will be propagated")

#             for sample in nuis_dict[nuis_name]['samples'].keys():

#                 #cerco questo oggetto nella dict degli histo
#                 comp_yield = 0
#                 comp_nuis = nuis_dict[nuis_name]['samples'][sample]
#                 for var in h_dict.keys():
#                     compnames = h_dict[var].keys()
#                     for j in compnames:
#                         if j == sample:
#                             #We do this because mkDatacards saves only the first 4 decimal places
#                             #in the rate. Without this the models are distorted... Not nice but still..
#                             #card.write(''.join(('%-.4f' % yieldsSig[name]) line 240
#                             comp_yield = float('%.4f'%h_dict[var][j].Integral())
#                     # propagate to other components having
#                     # the nuis name in their name

#                     for cn in compnames:
#                         if (sample in cn) and sample != cn:
#                             comp2_yield = float('%.4f'%h_dict[var][cn].Integral())
#                             #print(cn, comp2_yield)
#                             comp2_nuis = switchNuis(comp_yield, comp_nuis, comp2_yield)
#                             #print(comp2_nuis)

#                             nuis_dict[nuis_name]['samples'][cn] = comp2_nuis

#     #print(nuis_dict)
#     return nuis_dict

def check_Nuisances(nuis_dict, h_dict):

    for nuis_name in nuis_dict.keys():
        for sample in nuis_dict[nuis_name]['samples'].keys():

            for sam in h_dict.keys():
                for var in h_dict[sam].keys():
                    compnames = h_dict[sam][var].keys()
                    #check if the nuis same is present in at least one component
                    #for each variable
                    if not any([sample in i for i in compnames]):
                        return False
    return True

def makeNuisDict(config, d_name_, name_, type_, samples_, components):

    n_d = {}

    if len(samples_) == 1 and samples_[0][0].split(":")[0] == "all":
        val = float(samples_[0][0].split(":")[1])
        t = type_[0]
        dn = d_name_[0]
        n = name_[0]
        n_d[dn] = {}
        n_d[dn]['name'] = n
        n_d[dn]['type'] = t
        n_d[dn]['samples'] = {}
        for comp in components:
            if comp not in config.getlist("variables", "makeDummy"):
                n_d[dn]['samples'][comp] = val

        return n_d

    for dn, n, t, s in zip(d_name_, name_, type_, samples_):
        n_d[dn] = {}
        n_d[dn]['name'] = n
        n_d[dn]['type'] = t
        n_d[dn]['samples'] = {}

        for kv in s:
            comp = kv.split(":")[0]
            val = float(kv.split(":")[1])
            n_d[dn]['samples'][comp] = val

    return n_d

def makeNuisances(h_dict, model, config, outdir, isMkDC = True):

    #THIS PART IS NOT PERFECT
    #CAN WORK IF THE NUISANCE IS ONLY ON SM
    #DID NOT CHECK FOR OTHER SCENARIOS

    defname = config.getlist("d_nuisances", "defname") #the name in dict key
    name = config.getlist("d_nuisances", "name") # the 'name' field
    samples = [i[1:-1].split("|") for i in config.getlist("d_nuisances", "samples")]
    samples = [list(map(str, sublist)) for sublist in samples]
    types = config.getlist("d_nuisances", "types")

    for sample in h_dict:

        if isMkDC: components = h_dict[sample][h_dict[sample].keys()[0]].keys()
        else: components = h_dict[sample]

        nd = makeNuisDict(config, defname, name, types, samples, components)

        if isMkDC:
            if not check_Nuisances(nd, h_dict):
                sys.exit("[ERROR] Nuisances specified in cfg file are not present in components dict ... Check inputs")

        if config.get("d_nuisances", "propagate") == "True":
            #
            # HORRIBLE FIX FOR 1D NUIS
            #

            nd = propagateNuis(h_dict[sample], nd)

        file_name = outdir + "/nuisances_" + sample + "_" + model + ".py"
        f = open(file_name, 'w')

        f.write("#-----------------------------------\n")
        f.write("#     Automatically generated       # \n")
        f.write("#        by mkDCInputs.py           # \n")
        f.write("#-----------------------------------\n")
        f.write("\n\n\n")

        for key in nd.keys():
            f.write("nuisances['{}'] = {} \n".format(key, "{"))
            f.write("        'name' : '{}', \n".format(nd[key]['name']))
            f.write("        'type' : '{}', \n".format(nd[key]['type']))
            f.write("        'samples': {} \n".format("{"))

            for sample in nd[key]['samples']:
                f.write("            '{}' : '{}', \n".format(sample, nd[key]['samples'][sample]))
            f.write("        {} \n".format("}"))

            f.write("{}\n".format("}"))
            f.write("\n\n")

        f.close()


import os
import unittest
import itertools
import traceback
from chesspy import players
from chesspy.game import Game
from chesspy.board import Board
from chesspy.color import Color
from multiprocessing import Pool
from chesspy.analyzers import is_in_check, is_in_mate, adjacent_kings

class PlayerTest:
    class TestPlayer(unittest.TestCase):
        def setUp(self):
            self.game = Game()
            self.game.assert_check = False
            self.game.assert_mate = False

            self.avoids_adjacent_kings_test_count = 1000
            self.exit_check_test_count = 1000

            self.pool = Pool()

        def tearDown(self):
            self.pool.close()
            self.pool.join()

        def test_pvp(self):
            players = ((self.player_w, 'white'), (self.player_b, 'black'))
            with open(f"logs/{str(self.player_w)}_v_{str(self.player_b)}.log", "w") as game_file:
                for move, (player, color) in enumerate(itertools.cycle(players)):
                    if self.game.over or move > 300:
                        break

                    game_file.write(f"{str(self.game.board)}\n")
                    game_file.write(f"|{repr(self.game.board)}|\n")

                    sanstr = player.suggest_move_san()

                    game_file.write(f"{move}: {color}: {sanstr}\n")
                    game_file.write("\n")
                    game_file.flush()

                    if sanstr is None:
                        self.assertTrue(is_in_mate(self.game.board, self.game.turn))
                        break

                    try:
                        self.game.move_san(sanstr)
                    except (IndexError, AssertionError) as exc:
                        traceback.print_exception(exc, file=game_file)
                        raise

        def test_exits_check(self):
            # Player gets out of check
            for _ in range(self.exit_check_test_count):
                self.game.board = Board("rnb k nrpp p pp  qp p  p   N     b P            P P PPPP RBQKBNR")
                self.assertTrue(is_in_check(self.game.board, Color.WHITE))
                self.assertFalse(is_in_check(self.game.board, Color.BLACK))

                self.game.turn = Color.WHITE

                sanstr = self.player_w.suggest_move_san()
                self.game.move_san(sanstr)

                self.assertFalse(is_in_check(self.game.board, Color.WHITE))

        def test_avoids_adjacent_kings(self):
            # Player doesn't move into adjacent kings
            for _ in range(self.avoids_adjacent_kings_test_count):
                self.game.board = Board("       rk               p K  N PP                               ")
                self.assertFalse(adjacent_kings(self.game.board))

                self.game.turn = Color.WHITE

                sanstr = self.player_w.suggest_move_san()
                self.game.move_san(sanstr)

                self.assertFalse(adjacent_kings(self.game.board))

        def test_checkmated(self):
            # Player suggests None when he's checkmated
            self.game.board = Board("P                               R               k KR           p")
            self.assertTrue(is_in_check(self.game.board, Color.BLACK))
            self.assertTrue(is_in_mate(self.game.board, Color.BLACK))
            self.game.turn = Color.BLACK
            self.assertIsNone(self.player_b.suggest_move_san())

        @unittest.skip
        def test_stalemated(self):
            # Player suggests None when he's stalemated
            # case A) only pieces left are kings
            # case B) king isn't in check but could only move to check
            self.assertFalse(True)

        @unittest.skip
        def test_castle(self):
            # Player Castles once in a while
            self.assertFalse(True)

class TestRandy(PlayerTest.TestPlayer):
    def setUp(self):
        super().setUp()
        self.player_w = players.Randy(self.game, color=Color.WHITE)
        self.player_b = players.Randy(self.game, color=Color.BLACK)

class TestRicky(PlayerTest.TestPlayer):
    def setUp(self):
        super().setUp()
        self.player_w = players.Ricky(self.game, color=Color.WHITE)
        self.player_b = players.Ricky(self.game, color=Color.BLACK)

class TestJulian(PlayerTest.TestPlayer):
    def setUp(self):
        super().setUp()
        self.avoids_adjacent_kings_test_count = 1
        self.exit_check_test_count = 1
        self.player_w = players.Julian(self.game, color=Color.WHITE, pool=self.pool)
        self.player_b = players.Julian(self.game, color=Color.BLACK, pool=self.pool)

class TestRandyVsRicky(PlayerTest.TestPlayer):
    def setUp(self):
        super().setUp()
        self.player_w = players.Randy(self.game, color=Color.WHITE)
        self.player_b = players.Ricky(self.game, color=Color.BLACK)

    @unittest.skip
    def test_ricky_usually_wins(self):
        # Ricky is supposed to be smarter than Randy, so Ricky should win more often
        self.assertFalse(True)

class TestRandyVsJulian(PlayerTest.TestPlayer):
    def setUp(self):
        super().setUp()
        self.avoids_adjacent_kings_test_count = 1
        self.exit_check_test_count = 1
        self.player_w = players.Randy(self.game, color=Color.WHITE)
        self.player_b = players.Julian(self.game, color=Color.BLACK, pool=self.pool)

    @unittest.skip
    def test_julian_usually_wins(self):
        # Julian is supposed to be smarter than Randy, so Julian should win more often
        self.assertFalse(True)

class TestRickyVsJulian(PlayerTest.TestPlayer):
    def setUp(self):
        super().setUp()
        self.avoids_adjacent_kings_test_count = 1
        self.exit_check_test_count = 1
        self.player_w = players.Ricky(self.game, color=Color.WHITE)
        self.player_b = players.Julian(self.game, color=Color.BLACK, pool=self.pool)

    @unittest.skip
    def test_julian_usually_wins(self):
        # Julian is supposed to be smarter than Ricky, so Julian should win more often
        self.assertFalse(True)


from math import tan, pi

def polysum(n: int, s: float) -> float:
    '''Returns the sum of the area and square of the perimeter of the polygon

        Args:
            n (int) -> number of sides of the regular polygon.

            s (float) -> the length of each side.

        Returns (float) -> the sum of area and square of perimeter of the
                           regular polygon, rounded to 4th decimal places.
    '''
    assert n > 0 and type(n) == int, 'n should be a posive integer'
    assert type(s) in (int, float), 's should be either a float or an integer'
    area = 0.25 * n * s**2 / tan(pi / n)
    perisq = (n * s) ** 2                 # square of the perimeter
    return round(area + perisq, 4)        # rounded to 4th decimal places


import torch
import torch.nn as nn
import torch.optim as optim
import torchtext
from torchtext.datasets import SST
from torchtext.data import Field, LabelField, BucketIterator
from torchtext.vocab import Vectors, GloVe, CharNGram, FastText
import time
import torch.nn.functional as F
from network import LSTM
import argparse
import numpy as np
from losses import loss
from optimizer import create_optimizer
from engine import train, test, validate
from dataset import data_load
from plot import plot_loss_and_acc

import warnings
warnings.filterwarnings('ignore')

def get_args_parser():
    parser = argparse.ArgumentParser('CNN Training', add_help=False)
    parser.add_argument('--dataset', default='SST', type=str,
                        help='choose dataset (default: SST)')
    parser.add_argument('--batch_size', type=int, default=64)
    parser.add_argument('--epoch', type=int, default=10)
    # Optimization parameters
    parser.add_argument('--opt', default='adam', type=str, metavar='OPTIMIZER',
                        help='Optimizer (default: "adam"')
    parser.add_argument('--momentum', type=float, default=0.9, metavar='M',
                        help='SGD momentum (default: 0.9)')
    parser.add_argument('--weight_decay', type=float, default=0.0001,
                        help='weight decay (default: 0.05)')
    parser.add_argument('--lr', type=float, default=3e-4, metavar='LR',
                        help='learning rate (default: 4e-3), with total batch size 4096')
    parser.add_argument('--layer_decay', type=float, default=1.0)

    parser.add_argument('--loss', type=str, default='ce')

    parser.add_argument('--device', type=str, default='cuda')

    parser.add_argument('--exp', type=str, default='debug')

    parser.add_argument('--model', type=str, default='lstm')
    parser.add_argument('--tag', type=str, default='debug')

    parser.add_argument('--hidden_dim', type=int, default=128)
    parser.add_argument('--num_layers', type=int, default=1)
    parser.add_argument('--dropout', type=float, default=0.5)
    parser.add_argument('--pretrained', type=int, default=1)

    return parser

def main(args):
    # set up fields
    TEXT = Field(fix_length=60)
    LABEL = Field(sequential=False,dtype=torch.long)

    # make splits for data
    # DO NOT MODIFY: fine_grained=True, train_subtrees=False
    train_data, val_data, test_data = SST.splits(
    TEXT, LABEL, fine_grained=True, train_subtrees=False)

    # print information about the data
    print('train.fields', train_data.fields)
    print('len(train)', len(train_data))
    print('vars(train[0])', vars(train_data[0]))

    # build the vocabulary
    # you can use other pretrained vectors, refer to https://github.com/pytorch/text/blob/master/torchtext/vocab.py
    TEXT.build_vocab(train_data, vectors=Vectors(name='vector.txt', cache='./data'))
    LABEL.build_vocab(train_data)
    # We can also see the vocabulary directly using either the stoi (string to int) or itos (int to string) method.
    print("itos", TEXT.vocab.itos[:10])
    print("stoi", LABEL.vocab.stoi)
    print("most_common", TEXT.vocab.freqs.most_common(20))

    # print vocab information
    print('len(TEXT.vocab)', len(TEXT.vocab))
    print('TEXT.vocab.vectors.size()', TEXT.vocab.vectors.size())

    batch_size = 64
    # make iterator for splits
    train_it, val_it, test_it = BucketIterator.splits(
    (train_data, val_data, test_data), batch_size=batch_size,
    device=torch.device('cuda' if torch.cuda.is_available() else 'cpu'))

    # 初始化模型
    vocab_size = len(TEXT.vocab)
    # print(vocab_size)
    # time.sleep(100)
    embedding_dim = 300
    hidden_dim = args.hidden_dim
    output_dim = 5
    num_layers = args.num_layers
    dropout = args.dropout
    model = LSTM(vocab_size, embedding_dim, hidden_dim, output_dim, num_layers, dropout)

    # Copy the pre-trained word embeddings we loaded earlier into the embedding layer of our model.
    pretrained_embeddings = TEXT.vocab.vectors

    print(pretrained_embeddings.shape)

    # you should maintain a nn.embedding layer in your network
    if args.pretrained:
        model.embedding.weight.data.copy_(pretrained_embeddings)
        model.embedding.requires_grad = False
    # 设置训练设备
    device = torch.device(args.device)
    # 定义模型
    model = model.to(device)
    # 打印信息
    print(f"使用 {device} device")
    print(f"数据集:{args.dataset}")
    print(f"模型:{args.model}")

    # 定义代价函数
    criterion = loss(args)
    # 定义优化器
    optimizer = create_optimizer(args, model)
    # 训练
    model_trained, train_los, train_acc, val_los, val_acc = train(model=model,
                                    criterion=criterion,
                                    train_iter=train_it,
                                    val_iter=val_it,
                                    optimizer=optimizer,
                                    device=device,
                                    max_epoch=args.epoch,
                                    disp_freq=100)
    # 测试
    test(model=model,
        criterion=criterion,
        test_iter=test_it,
        device=device)

    # 模型保存
    # torch.save(model.state_dict(), 'model/my_model.pth')

    # 绘制损失和准确率图
    suffix1 = args.tag + args.dataset + '_' + args.model + '_lr' + str(args.lr) + '_' + str(args.opt) + '_wd' + str(args.weight_decay) + '_epoch' + str(args.epoch) +  '.png'
    path1 = ['los_acc/train_loss_' + suffix1, 'los_acc/train_acc_' + suffix1]
    suffix2 = args.tag + args.dataset + '_' + args.model + '_lr' + str(args.lr) + '_' + str(args.opt) + '_wd' + str(args.weight_decay) + '_epoch' + str(args.epoch) +  '.png'
    path2 = ['los_acc/val_loss_' + suffix2, 'los_acc/val_acc_' + suffix2]
    plot_loss_and_acc({'TRAIN': [train_los, train_acc]}, path1)
    plot_loss_and_acc({'VAL': [val_los, val_acc]}, path2)

if __name__ == "__main__":
    """
    Please design the initial and target state.
    """
    parser = argparse.ArgumentParser('Prombelm solver', parents=[get_args_parser()])
    args = parser.parse_args()
    main(args)


# https://github.com/Pierian-Data/Complete-Python-3-Bootcamp

from random import randint

def display_board(board):
    print(' ', '|', ' ', '|', ' ')
    print(board[7], '|', board[8], '|', board[9])
    print('_', '|', '_', '|', '_')
    print(' ', '|', ' ', '|', ' ')
    print(board[4], '|', board[5], '|', board[6])
    print('_', '|', '_', '|', '_')
    print(' ', '|', ' ', '|', ' ')
    print(board[1], '|', board[2], '|', board[3])
    print(' ', '|', ' ', '|', ' ')

def decide_player(player1, player2):
    player1 = input('Player 1: Choose "X" or "O"\t\t')
    print(player1)
    if player1.lower() == 'x':
        player1 = 'X'
        player2 = 'O'
        return 'X', 'O'
    elif player1.lower() == 'o':
        player2 = 'X'
        player1 = 'O'
        return 'O', 'X'
    else:
        return decide_player(None,None)

def result(board):
    r1, r2, r3 = board[7:10], board[4:7], board[1:4]
    c1, c2, c3 = [board[7], board[4], board[1]], [board[8], board[5], board[2]], [board[9], board[6], board[3]]
    d1, d2 = [board[7], board[5], board[3]], [board[9], board[5], board[1]]
    s = [r1, r2, r3, c1, c2, c3, d1, d2]

    if ['X'] * 3 in s:
        return True, 'X'
    elif ['O'] * 3 in s:
        return True, 'O'
    elif ' ' not in board:
        return True, 'Tied'
    else:
        return False, 'NO WINNER YET'

def play(i, turn, board, key, move):
    print(turn[i], 'make your move......')
    display_board(board)
    while True:
        mark = input()
        try:
            mark = int(mark)
            if mark not in range(1, 10):
                print(mark, 'Please enter a valid move')
                display_board(key)
                continue
            index = key.index(mark)
            key[index] = ' '
            break
        except:
            print('Available keys as follows')
            display_board(key)
            print('Please enter correct number to place your move according to the left moves on grid\t')
    board[mark] = move[turn[i]]

def make_board():
    return ['#'] + [' '] * 9, ['#', 1, 2, 3, 4, 5, 6, 7, 8, 9]

def map_player_to_marker(player1, player2):
    return {'Player_1': player1, 'Player_2': player2}, ['Player_1', 'Player_2'], randint(0, 1)

def game():
    player1, player2 = decide_player(None, None)

    board, key = make_board()
    move, turn, turn_index = map_player_to_marker(player1,player2)

    while True:
        play(turn_index, turn, board, key, move)

        game_over, winner = result(board)
        if game_over:
            display_board(board)
            break
        turn_index = (turn_index + 1) % 2

    print('GAME OVER::')
    if winner == 'X' or winner == 'O':
        print(winner, 'is winner')
    else:
        print('Game is', winner)

def replay():
    print('Do you want to replay??\nPress y for YES and any  other key for NO\t')
    response = input()
    return response.lower() == 'y'

def tic_tac_toe():
    game()

    if replay():
        tic_tac_toe()

tic_tac_toe()


from django.core.management.base import BaseCommand
from django.utils.crypto import get_random_string
from django.utils import timezone
from user_paste.models import User, Post
import datetime
import string

class Command(BaseCommand):
    help = 'Generates fake data for a local sqlite database'

    def add_arguments(self, parser):
        parser.add_argument('--num_users', type=int, required=True)
        parser.add_argument('--num_user_posts', type=int, required=True)

    def handle(self, *args, **options):
        created_date = timezone.now() - datetime.timedelta(weeks=100)
        for i in range(options['num_users']):
            user_name = get_random_string(20, string.ascii_letters + string.digits)
            user = User.objects.create(user_name=user_name)
            for i in range(options['num_user_posts']):
                created_date += datetime.timedelta(days=1)
                post_content = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
                                  Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
                                  Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
                                  Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'''
                Post(post_title = user.user_name + f'post{i}',
                        post_author = user,
                        post_content = post_content,
                        post_description = 'Lorem ipsum dolor sit amet, consectetur adipiscing',
                        post_category = 'Plain Text',
                        post_type = 'Notes',
                        post_created_date = created_date).save()


import argparse
import os
import pickle
from datetime import datetime, timedelta
from matplotlib.dates import YearLocator, DateFormatter, MonthLocator

import numpy
from matplotlib import pyplot as plt
from pandas.io.data import get_data_yahoo

class Investor(object):
    """Represents a single investor with initial cash, income, and
    set buy/sell thresholds.

    :param buy_at   float   if the pe ratio is less than or equal to this
      value, the investor will buy all the shares she can
    :param sell_at  float   if the pe ratio is greater than this value, the
      investor will sell all her shares (if any)
    :param init_cash float  initial cash
    :param shares   float   initial shares
    :param income   float   cash increase on call to `get_paid`

    """
    def __init__(self, buy_at, sell_at=None, init_cash=10000., shares=0.,
                 income=2000.):
        self.buy_at = buy_at
        if sell_at is None:
            sell_at = buy_at
        self.sell_at = sell_at
        self.init_cash = self.cash = init_cash
        self.shares = shares
        self.income = income

    def get_paid(self):
        """Receive the income"""
        self.cash += self.income

    def get_net_worth(self, market_price):
        """Total net worth is cash + worth of shares"""
        return self.cash + self.shares * market_price

    def sell_all(self, market_price):
        """Convert all stocks to cash"""
        self.cash += market_price * self.shares
        self.shares = 0.

    def buy_all(self, market_price):
        """Buy all shares I can afford"""
        self.shares += self.cash / market_price
        self.cash = 0.

    def react_to_pe(self, pe_ratio, market_price):
        """React to P/E depending on investor thresholds (buy, sell, or hold)

        """
        if self.shares and pe_ratio > self.sell_at:
            self.sell_all(market_price)
        elif self.cash and pe_ratio <= self.buy_at:
            self.buy_all(market_price)

class CapeValidator(object):
    """
    Compares the performance of a suite of investors with different buy/sell
    thresholds for CAPE ratio.

    :param pe_data_file str csv of pe_data. TODO: write script to download
    :param start_date   datetime    datetime at which to start analysis
    :param buy_thresholds   [float, ...]    list of buy thresholds for suite
        of investors. Each entry will instantiate a new investor.
    :param sell_thresholds [float, ...]     list of sell thresholds
        corresponding to `buy_thresholds`. If None, will be equal to
        `buy_thresholds`.
    :param end_date datetime    datetime at which to stop analysis. If None,
        will go to current day.
    :param index    str     stock symbol of index to invest in.

    """
    def __init__(self, pe_data_file, start_date, buy_thresholds,
                 sell_thresholds=None, end_date=None, index='^GSPC'):
        if sell_thresholds is None:
            sell_thresholds = [None] * len(buy_thresholds)
        if len(buy_thresholds) != len(sell_thresholds):
            raise RuntimeError("Buy and Sell Thresholds must be equal length")
        if end_date is None:
            end_date = datetime.now()
        self.investors = []
        self.pe_array = []
        self.index = index
        self.index_cache = {}

        self.load_pe_array(pe_data_file, start_date, end_date)
        self.init_investors(buy_thresholds, sell_thresholds)
        self.load_index_cache()
        size = (len(self.investors), len(self.pe_array))
        self.worth_matrix = numpy.empty(size)
        self.shares_matrix = numpy.empty(size)
        self.cash_matrix = numpy.empty(size)

    @property
    def _cache_filename(self):
        return '.cache_{}.pkl'.format(self.index)

    def _parse_pe_date(self, date_str):
        # the date_str is the beginning of the month, but we want the end
        # because the CAPE for a given month is the avg of prices for the
        # entire month
        date0 = datetime.strptime(date_str, '%m/%Y')
        date = date0 + timedelta(27)
        while date.month == date0.month or date.weekday() > 4:
            date += timedelta(1)
        return date

    def load_pe_array(self, pe_data_file, start_date, end_date):
        """Load the CAPE data from the specified file"""
        with open(pe_data_file) as fp:
            for line in fp:
                line = line.strip()
                if line:
                    date_str, pe = line.split(',')
                    pe = float(pe)
                    date = self._parse_pe_date(date_str)
                    if start_date <= date <= end_date:
                        self.pe_array.append([date, pe])

    def init_investors(self, buy_thresholds, sell_thresholds):
        """Initialize Investor instances from threshold lists"""
        for b, s in zip(buy_thresholds, sell_thresholds):
            self.investors.append(Investor(b, s))

    def load_index_cache(self):
        """Load the cache for the specified index, if available"""
        if os.path.exists(self._cache_filename):
            with open(self._cache_filename, 'rb') as fp:
                self.index_cache = pickle.load(fp)

    def save_index_cache(self):
        """Save the cache to disk"""
        with open(self._cache_filename, 'wb') as fp:
            pickle.dump(self.index_cache, fp)

    def _get_market_price(self, date, try_next=2):
        """Get the market price for the given date from yahoo or the cache.

        Tries to account for holidays by stepping backwards through time when
        the specified date is not found. Intermittent network errors may cause
        unexpected results here.

        """
        while date.weekday() > 4:
            date -= timedelta(1)
        if date in self.index_cache:
            return self.index_cache[date]
        try:
            df = get_data_yahoo(self.index, date, date)
            price = df['Adj Close'][0]
        except (IndexError, OSError):
            # try to account for holidays and wutnot
            if try_next:
                date1 = date - timedelta(1)
                return self._get_market_price(date1, try_next - 1)
            else:  # pragma no cover
                raise
        self.index_cache[date] = price
        return price

    def calculate_worth_vs_time(self):
        """Calculate the worth, shares, and cash of all the investors across
        the specified time interval

        """
        i = 0
        for date, pe_ratio in self.pe_array:
            market_price = self._get_market_price(date)
            for j, investor in enumerate(self.investors):
                investor.get_paid()
                investor.react_to_pe(pe_ratio, market_price)
                self.worth_matrix[j][i] = investor.get_net_worth(market_price)
                self.shares_matrix[j][i] = investor.shares
                self.cash_matrix[j][i] = investor.cash
            i += 1
        self.save_index_cache()

    def plot_worth_vs_time(self, names=None):
        """Plot the worth of each investor vs. time. If names is specified,
        will use these names in the legend. Otherwise, will name the investors
        based off their thresholds.

        """
        if names is None:
            names = [
                'Investor ({:0.2f},{:0.2f})'.format(inv.buy_at, inv.sell_at)
                for inv in self.investors]
        dates = [x[0] for x in self.pe_array]
        year = YearLocator()
        date_fmt = DateFormatter('%Y')
        plt.xkcd()

        # investor worth plots
        fig = plt.figure()
        ax = fig.gca()
        lines = []
        for i in range(len(self.investors)):
            result = ax.plot_date(dates, self.worth_matrix[i], '-')
            lines.append(result[0])
        ax.xaxis.set_major_locator(year)
        ax.xaxis.set_major_formatter(date_fmt)
        # ax.xaxis.set_minor_formatter(MonthLocator())
        ax.autoscale_view()
        ax.legend(lines, names, 'upper left')
        fig.autofmt_xdate()
        return fig

    def plot_pe_ratio(self):
        """
        Plot the CAPE values for the time interval in question.

        """
        dates = [x[0] for x in self.pe_array]
        year = YearLocator()
        date_fmt = DateFormatter('%Y')

        fig = plt.figure()
        ax_pe = fig.gca()
        ax_pe.plot_date(dates, [x[1] for x in self.pe_array], '-')
        ax_pe.xaxis.set_major_locator(year)
        ax_pe.xaxis.set_major_formatter(date_fmt)
        ax_pe.autoscale_view()
        ax_pe.set_title('PE Ratio vs. Time')
        fig.autofmt_xdate()
        return fig

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="CAPE Value determination")
    default_thresholds = ','.join(str(i) for i in range(16, 26)) + ',1000'
    parser.add_argument('-t', '--buy_thresholds',  default=default_thresholds)
    parser.add_argument('--sell_thresholds', default=None)
    parser.add_argument('--pe_file', default='pe_data.csv')
    parser.add_argument('--index', default='^GSPC')
    parser.add_argument('--start_date', default='01/1980')
    parser.add_argument('--end_date', default=None)
    args = parser.parse_args()

    buys = [float(b) for b in args.buy_thresholds.split(',')]
    sells = args.sell_thresholds
    if sells:
        sells = [float(b) for b in sells.split(',')]
    d0 = datetime.strptime(args.start_date, '%m/%Y')
    if args.end_date:
        d1 = datetime.strptime(args.end_date, '%m/%Y')
    else:
        d1 = datetime.now()

    validator = CapeValidator(args.pe_file, d0, buys, sells, d1, args.index)
    validator.calculate_worth_vs_time()
    import ipdb; ipdb.set_trace()
    validator.plot_worth_vs_time()
    # validator.plot_pe_ratio()
    plt.show()


from collections import defaultdict

class Solution:
    def calcEquation(self, equations: list, values: list, queries: list) -> list:
        graph = defaultdict(list)
        for i in range(len(equations)):
            d1, d2 = equations[i]
            val = values[i]
            graph[d1].append((d2, val))
            graph[d2].append((d1, 1 / val))

        def dfs(d1, d2, visted, curVal):
            if d1 == d2:
                return curVal

            if d1 in visted:
                return -1

            visted.add(d1)

            tmp = -1
            for child, val in graph[d1]:
                tmp = max(tmp,dfs(child, d2, visted, curVal * val))
            return tmp

        ans = []
        for d1, d2 in queries:
            if d1 in graph and d2 in graph:
                ans.append(dfs(d1, d2, set(), 1))
            else:
                ans.append(-1)

        return ans


from connections.connection import execute_query

## SHOW ALL SUPER HEROES ##
def show_all_heroes():
    show_heroes = """
        SELECT * FROM heroes
        ORDER BY name ASC
    """
    heroes = execute_query(show_heroes).fetchall()
    print("The Superheroes Are:")
    for hero in heroes:
        print("- " + hero[1])

## WILL PRINT 'CHILL WOMAN' ##
def print_hero_name():
    select_chill = """
        Select name from heroes
        where name = 'Chill Woman'
    """
    chill = execute_query(select_chill).fetchone()
    print("Printing Chill Woman: " + (chill[0]))

## SEARCHES ENEMIES OF A HERO INPUT ##
def show_specific_enemies(search):
    enemies = execute_query("""
    SELECT h2.name
    FROM relationships
    INNER JOIN heroes h1
    ON h1.id=relationships.hero1_id
    INNER JOIN heroes h2
    ON h2.id=relationships.hero2_id
    WHERE h1.name = %(search_name)s and relationship_type_id = 1
    """,
    {'search_name': search}).fetchall()
    if not enemies:
         print("Has no enemies")
    for enemy in enemies:
        # print("Something enemies are:")
        print("- " + enemy[0])

## SEARCHES FRIEND OF A HERO INPUT ##
def show_specific_friends(search):
    friends = execute_query("""
    SELECT h2.name
    FROM relationships
    INNER JOIN heroes h1
    ON h1.id=relationships.hero1_id
    INNER JOIN heroes h2
    ON h2.id=relationships.hero2_id
    WHERE h1.name = %(search_name)s and relationship_type_id = 1
    """,
    {'search_name': search}).fetchall()
    if not friends:
         print("Has no friends")
    for friend in friends:
        # print("Something friends are:")
        print("- " + friend[0])

# show_all_heroes()
# print_hero_name()
# show_enemies()
# show_specific_enemies()
# show_specific_friends()