'''
Udemy Python Course Milestone 2 Challange to create a Black Jack game with the following assumtions:

    You need to create a simple text-based BlackJack game
    The game needs to have one player versus an automated dealer.
    The player can stand or hit.
    The player must be able to pick their betting amount.
    You need to keep track of the player's total money.
    You need to alert the player of wins, losses, or busts, etc...

And most importantly:

    You must use OOP and classes in some portion of your game. You can not just use functions in your game.
    Use classes to help you define the Deck and the Player's hand. There are many right ways to do this,
     so explore it well!
'''

# defining the deck with 52 cards, no spaids all the same we ar enot considering any special
# moves like splitting. will have to import shuffle to randomize deck. will then
# .pop off all drawn cards trhrough the game

import random

class Deck():
    def __init__(self):
        self.bj_deck = [
        '2','3','4','5','6','7','8','9','10','J','Q','K','A',
        '2','3','4','5','6','7','8','9','10','J','Q','K','A',
        '2','3','4','5','6','7','8','9','10','J','Q','K','A',
        '2','3','4','5','6','7','8','9','10','J','Q','K','A',
        ]
# defining Player Class which has a bankroll of money they can start playing withself.
# Player can only play of bankroll > 0

class Player():
    def __init__(self,bankroll):
        self.bankroll = int(bankroll)
        self.hand = []
        self.score = 0

# defining class of Dealer -

class Dealer():
    def __init__(self,bank):
        self.bank = int(bank)
        self.hand = []
        self.score = 0

def calcscore(player_dealer):
    myscore = 0
    for x in player_dealer.hand:
        if x in ['J','Q','K']:
            myscore = myscore + 10
            continue
        if x == 'A' and ((myscore + 10) >= 21):
            myscore = myscore + 1
            continue
        if x == 'A' and ((myscore + 10) < 21):
            myscore = myscore + 10
            continue
        myscore = myscore + int(x)
    player_dealer.score = myscore

# assigning Dealier and Player, bankrolling both

my_dealer = Dealer(1000)
my_player = Player(100)

gamenotover = True
again = True

while again:
    # initializing Game, creating Deck to play and shuffling cards
    gamenotover = True
    again = True
    my_player.hand = []
    my_dealer.hand = []
    my_deck = Deck()
    random.shuffle(my_deck.bj_deck)
    # starting Game - first Player then Dealer, both get two cards

    bet = int(input(f'Your balance is {my_player.bankroll}. Player, place your bet:  '))

    my_player.hand.append(my_deck.bj_deck.pop())
    my_dealer.hand.append(my_deck.bj_deck.pop())
    my_player.hand.append(my_deck.bj_deck.pop())
    my_dealer.hand.append(my_deck.bj_deck.pop())

    calcscore(my_player)
    calcscore(my_dealer)

    print('Dealer holds: ',my_dealer.hand, 'Score: ',my_dealer.score)
    print('Player holds: ',my_player.hand, 'Score: ',my_player.score)

    while True:
        move = input("Player, do you want to Hit or Stay? [H,S]: ")
        if move.upper() == 'H':
            my_player.hand.append(my_deck.bj_deck.pop())
            calcscore(my_player)
            print('Dealer holds: ',my_dealer.hand, 'Score: ',my_dealer.score)
            print('Player holds: ',my_player.hand, 'Score: ',my_player.score)
        if my_player.score > 21:
            print('Player, you are bust and lose the game and your bet')
            my_player.bankroll = my_player.bankroll - bet
            gamenotover = False
            break
        if my_player.score == 21:
            print('Player, you score 21. Congratulations. Dealers turn')
            gamenotover = True
            break
        if move.upper() == 'S':
            gamenotover = True
            break

    while my_dealer.score < my_player.score and gamenotover:
        my_dealer.hand.append(my_deck.bj_deck.pop())
        calcscore(my_dealer)
        print('Dealer holds: ',my_dealer.hand, 'Score: ',my_dealer.score)
        print('Player holds: ',my_player.hand, 'Score: ',my_player.score)

        if my_dealer.score > 21:
            print('Dealer, you are bust and lose the game. Pay up')
            my_player.bankroll = my_player.bankroll + bet
            break
        if my_player.score <= my_dealer.score:
            print('Player, tough luck. The Bank wins')
            my_player.bankroll = my_player.bankroll - bet
            break

    print('=======================')
    print('Player balance: ', my_player.bankroll)
    print('=======================')

    if my_player.bankroll > 0:
        if input('You want to go again [Y|N]? ').upper() == 'Y':
            again = True
            continue
        else:
            again = False
            break
    else:
        print('Sorry you are broke. Good luck next time.')
        again = False
        break

print('Thank you for playing.')


from functools import reduce
from operator import mul, mod
from decimal import getcontext
from decimal import Decimal

def egcd(a,b):
    if a==0:
        return b, 0, 1
    else:
        g, y, x = egcd(b%a, a)
        return g, x- (b//a)*y, y

def crt(m,a):
    getcontext().prec = 300
    M = reduce(mul, m)
    #print("M = ", M)
    m_i = [Decimal(M) / Decimal(item) for item in m]
    #print("M_1 = ", m_i[0])
    #print("M_2 = ", m_i[1])
    #print("M_3 = ", m_i[2])

    b = map(mod, m_i, m)
    #print("b = " ,b)

    g, k, l = map(egcd, b, m)

    g, k, l = zip(g, k, l)
    t = map(mod, k, m)
    e = map(mul, m_i, t)

    x_sum = sum(map(mul, a, e))
    x = x_sum % M
    return x if x > 0 else x + M


"""
This example explores how logging behaves if no special
configuration is performed.

conclusions:
- we get an error printout which DOES NOT stop the program
    that we do not have handlers.
    "No handlers could be found for logger "root""
    This is printed once and then no more.
    this is true for both "__main__" and "root" which is
    the logger you get when you do "logging.getLogger()"
"""

import logging

# logger = logging.getLogger(__name__)
logger = logging.getLogger()
print("warning")
logger.warning("this is a warning message")
print("debug")
logger.debug("this is a debug message")
print("error")
logger.error("this is an error message")


# LEemar SHOPIFY updates 1-11-22
# Just prepare update file with full description for all SKUS in master
# Author : Sankar Ramaiah
##
import csv
import io
i=0
notStkd="not stocked"
minQty=10  #
defQty=2  # to turn on
markupPct=0.40  # we cancalc our own markup wmt is slighly lower
prefix="LM-"
pack2Str="Pack of 2"
pack3Str="Pack of 3"
pack4Str="Pack of 4"
pack2Ctr=0 # multipack counter for all except 1
recCtr=0 # in sku list counter
pChngCtr=0 # items changing price in this run
qChngCtrOn=0 # items changing from qty=0 to qty=1 turning on
qChngCtrOff=0 # items changing from qty=1 to qty=0 turning off due to not founds
DefShipFee=11.99
com=","
sem=";"
#rStr="Restricted"
#
#M = open('LemQmon.csv', 'w')  # active items with qty to monitor
p = open('LMUpdDESCShop.csv', 'w')  # once items we want is located in our SKU LIST
#L = open('ShopLMChng.log', 'w')  # track items with price changes & qty showing old new pirce
## log file
header=["Handle","Title","Option1 Name","Option1 Value","Option2 Name","Option2 Value","Option3 Name","Option3 Value","SKU","HS Code","COO","Location","Oberlo"]
#
headerP=("Handle,"+"Title,"+"Body (HTML)\n")   # just title and desc fix
#
p.write(headerP)
#
#N = open('LM_SHOP_SKU_MASTER.new', 'w')  # we writeout locally and copy it back to data once successful
## log file
#with open('DCQtyPrc.csv', 'r') as rf: # previosuly prepared with unitcost and unit price
with open('mws/data/LM_SHOP_SKU_MASTER.csv', 'r') as rf: # our shop inventory file
     reader = csv.reader(rf, delimiter=',')
     with open('LMUpdQtyShop.csv', 'w') as wf:
          writer = csv.writer(wf, delimiter=',')
          writer.writerow(header)
          #writer = csv.writer(wf, delimiter='|')
          #desired_column = [6]
          for line in reader:
              skuIn=line[0] # sku in sku list w prefix,need to strip to compare with vendor file
              skuInx=skuIn[3:] #strip prefix
              #print("skuinx",skuInx)
              titleIn=line[1]  # take title as is from sku master (fixed with initial load)
              #titleInX=line[1]  # only 2 columns info needed , has other cols for shop updates
              #titleIn=titleInX.replace(com,sem) # patch title and change comma to semicolon
              #
              qtyIn=line[11]
              # line[12] last colum where we can store price
              priceIn=line[12]  # initial file has "not stocked" and if it was reset again
              if priceIn == notStkd:
                  priceIn="0.0"
              priceinF=float(priceIn)
              #priceOut=str(priceinF)
              skuOut=skuIn.upper() # same as handle in upper
              qtyI=int(qtyIn) # listed qty integer
              qtyOutstr=qtyIn
              found=0
              # we may want to create exception sku list for restricted here so wlmtdel can process it
              #determine pksize based on title
              #print('sku= ',line[0])
              with open('mws/data/LeeMarPet.com_Inventory.csv', 'r') as f:   # vendor data for initial title cleanup
              #with open('LEMQtyPrc.csv', 'r') as f:   # custom vendor data for daily monitoring
                readerV = csv.reader(f, delimiter=',')
                for line in readerV:
                    ###################################################
                    skuLEM=line[0] # item Number in lemar
                    qtyLEM=line[1] #1
                    qtyLEMI=int(qtyLEM)
                    priceLEMstr=line[2] # vendor unit price
                    priceUPC=float(priceLEMstr) # vendor unit price w/out any shipping
                    #productSizeX=line[19] # to append to item title only if reading original vendor data
                    #productSize=productSizeX.replace(com,sem) # patch title and change comma to semicolon
                    ####################################################
                    if skuLEM.lower() == skuInx.lower(): # itemnumber comparison
                        #print("skuLem",skuLEM)
                        productDesc=line[20] # html desc
                        found=1  # our sku list item matches vendor feed
                        #######################  make it multipack based on price ###################
                        #priceData=(skuIn+","+titleIn+","+productDesc+"\n")
                        priceData=(skuIn+"\t"+titleIn+"\t"+productDesc+"\n")
                        p.write(priceData)
                        break
                        # may need break here to exit inner loop
                        #print('matched',skuIn,priceIn,qtyIn)
              recCtr +=1 # how many we have in our SKU list from all listing reprts
              if found == 0:  # item NOT found in vendor data but we have in our SKU list
                  ##
                  # since item not found we keep title data as desc
                  priceData=(skuIn+"\t"+titleIn+"\t"+titleIn+"\n")
                  p.write(priceData)
#
              # Regardless of previous logic we just recreate our .new file
              #priceIn=line[2] # price listed
              #priceIn=line[2] # price listed
              #newStr=(skuIn,itemId,priceOut,qtyOut,gtinIn,pkSize)
              ##newStr=(skuIn+","+titleIn+","+priceOut+","+qtyOutstr+","+gtinIn+","+pkSize+"\n") # new file

#dump to change log instead of print
#print("Total items in SKU List file = ",recCtr)
#print("Total 2 pack items in SKU List file = ",pack2Ctr)
rf.close()
wf.close()
p.close()
#L.close()
#M.close()
#N.close()
#R.close()
#################################-----------------END----------------------###################


from tkinter import END, StringVar, INSERT
import json
import requests
from io import open
from datetime import datetime
from tiempo import tiempo
import ventana
import log

provincias = ["Alava","Albacete", "Alicante", "Almería", "Asturias", "Ávila", "Badajoz", "Islas Baleares", "Barcelona", "Bizkaia", "Burgos", "Cáceres", "Cádiz", "Cantabria", "Castellón",
"Ceuta", "Ciudad Real", "Córdoba", "A Coruña", "Cuenca", "Girona", "Granada", "Guadalajara", "Gipuzkoa", "Huelva", "Huesca", "Jaén", "León", "Lleida", "Lugo", "Madrid", "Málaga",
"Melilla", "Murcia", "Navarra", "Oursense", "Palencia", "Las Palmas", "Pontevedra", "La Rioja", "Salamanca", "Santa Cruz de Tenerife", "Segovia", "Sevilla", "Soria", "Tarragona",
 "Teruel", "Toledo", "Valencia", "Valladolid", "Zamora", "Zaragoza" ]

diccionarioProvincias= {"Alava": "01" ,"Albacete": "02", "Alicante":"03", "Almería":"04", "Asturias":"33", "Ávila":"05", "Badajoz":"06", "Islas Baleares":"07", "Barcelona":"08", "Bizkaia":"48", "Burgos":"09",
"Cáceres":"10", "Cádiz":"11", "Cantabria":"39", "Castellón":"12", "Ceuta":"51", "Ciudad Real":"13", "Córdoba":"14", "A Coruña":"15", "Cuenca":"16", "Girona":"17", "Granada":"18", "Guadalajara":"19",
"Gipuzkoa":"20", "Huelva":"21", "Huesca":"22", "Jaén":"23", "León":"24", "Lleida":"25", "Lugo":"27", "Madrid":"28", "Málaga":"29", "Melilla":"52", "Murcia":"30", "Navarra":"31", "Oursense":"32", "Palencia":"34",
"Las Palmas":"35", "Pontevedra":"36", "La Rioja":"26", "Salamanca":"37", "Santa Cruz de Tenerife":"38", "Segovia":"40", "Sevilla":"41", "Soria":"42", "Tarragona":"43","Teruel":"44", "Toledo":"45",
"Valencia":"46", "Valladolid":"47", "Zamora":"49", "Zaragoza":"50"}

diccionarioCodigos = {"Alava": "01059" ,"Albacete": "02003", "Alicante":"03014", "Almería":"04013", "Asturias":"33044", "Ávila":"05019", "Badajoz":"06015", "Islas Baleares":"07040", "Barcelona":"08019",
"Bizkaia":"48020", "Burgos":"09059", "Cáceres":"10037", "Cádiz":"11012", "Cantabria":"39075", "Castellón":"12040", "Ceuta":"51001", "Ciudad Real":"13034", "Córdoba":"14021", "A Coruña":"15030", "Cuenca":"16078",
"Girona":"17079", "Granada":"18087", "Guadalajara":"19130", "Gipuzkoa":"20069", "Huelva":"21041", "Huesca":"22125", "Jaén":"23050", "León":"24089", "Lleida":"25120", "Lugo":"27028", "Madrid":"28079", "Málaga":"29067",
"Melilla":"52001", "Murcia":"30030", "Navarra":"31201", "Oursense":"32054", "Palencia":"34120","Las Palmas":"35016", "Pontevedra":"36038", "La Rioja":"26089", "Salamanca":"37274", "Santa Cruz de Tenerife":"38038",
"Segovia":"40194", "Sevilla":"41091", "Soria":"42173", "Tarragona":"43148","Teruel":"44216", "Toledo":"45168", "Valencia":"46250", "Valladolid":"47168", "Zamora":"49275", "Zaragoza":"50297"}

def resumenDia ():
    ventana.textoTiempo.delete("1.0", END)
    prov = ventana.prov.get()
    if prov in diccionarioProvincias:
        codProvincia = diccionarioProvincias[prov]
        url = f"https://opendata.aemet.es/opendata/api/prediccion/provincia/hoy/{codProvincia}"
        querystring = {"api_key":"INSERTAR AQUI LA CLAVE DE LA API PROPORCIONADA POR AEMET"}
        response = requests.request("GET", url,  params=querystring)
        respuesta_json = json.loads(response.text)
        datos = respuesta_json["datos"]
        url2 = datos
        respuesta = requests.request("GET", url2,  params=querystring)
        ventana.textoTiempo.insert(INSERT, f"{respuesta.text}")
        log.ProvinciaHoy()

def semanal ():
    ventana.textoTiempo.delete("1.0", END)
    prov = ventana.prov.get()
    if prov in diccionarioCodigos:
        codProvincia =  diccionarioCodigos[prov]
        url = f"https://opendata.aemet.es/opendata/api/prediccion/especifica/municipio/diaria/{codProvincia}"
        querystring = {"api_key":"INSERTAR AQUI LA CLAVE DE LA API PROPORCIONADA POR AEMET"}
        response = requests.request("GET", url, params=querystring)
        respuesta_json = json.loads(response.text)
        datos = respuesta_json["datos"]
        url2 = datos
        respuesta2 = requests.request("GET", url2, params=querystring)
        respuesta_json2 = json.loads(respuesta2.text)
        texto = ""
        lista = []
        for i in range(0,7):
            fechas = respuesta_json2[0]["prediccion"]["dia"][i]["fecha"]
            minimas = respuesta_json2[0]["prediccion"]["dia"][i]["temperatura"]["minima"]
            maximas = respuesta_json2[0]["prediccion"]["dia"][i]["temperatura"]["maxima"]
            precipitacion = respuesta_json2[0]["prediccion"]["dia"][i]["probPrecipitacion"][0]["value"]
            cielo = respuesta_json2[0]["prediccion"]["dia"][i]["estadoCielo"][0]["descripcion"]
            humedadMax = respuesta_json2[0]["prediccion"]["dia"][i]["humedadRelativa"]["maxima"]
            humedadMin = respuesta_json2[0]["prediccion"]["dia"][i]["humedadRelativa"]["minima"]
            data = tiempo(fechas, minimas, maximas, precipitacion, cielo, humedadMax, humedadMin)
            lista.append(data)
        for objeto in lista:
            texto = texto +  str(objeto) + "\n"
        ventana.textoTiempo.insert(INSERT, f"{texto}")
        log.ProvinciaSemana()


# ANTHONY TRUJILLO
# 9/22/2022
# MADLIB TAKE 2

# imports

# globals
OGTEXT2 = """
The (body) (text) or (body) copy is the (text) forming the main content of a
(book), (magazine), (web_page), or any other (printed) or (digital_work).
This is as a contrast to both additional components such as
(headings), (images), (charts), (footnotes) etc. on each (page),
and also the (pages) of front matter that form the introduction to a (book).
"""

OGTEXT2 = OGTEXT2.replace("body","(body)")
OGTEXT2 = OGTEXT2.replace("book","(book)")
OGTEXT2 = OGTEXT2.replace("text","(text)")
#print(OGTEXT2)
#functions

#main

def main():
    text2 = OGTEXT2

    body = input("give me a name")
    text = input("give me an object")
    book = input("give me an object")
    magazine = input("give me an object")
    web_page = input("give me anything")
    printed = input("give me an action")
    digital_work = input("give me an action")
    headings = input("give me a thing")
    images = input("give me an object")
    charts = input("give me an object")
    footnotes = input ("give me a thing")
    pages = input ("give me an object")

    text2 = text2.replace("(body)",body)
    text2 = text2.replace("(text)",text)
    text2 = text2.replace("(book)",book)
    text2 = text2.replace("(magazine)",magazine)
    text2 = text2.replace("(web_page)",web_page)
    text2 = text2.replace("(printed)",printed)
    text2 = text2.replace("(digital_work)",digital_work)
    text2 = text2.replace("(headings)",headings)
    text2 = text2.replace("(images)",images)
    text2 = text2.replace("(charts)",charts)
    text2 = text2.replace("(footnotes)",footnotes)
    text2 = text2.replace("(pages)",pages)
    print(text2)
main()


from typing import IO
from collections import deque
from functools import lru_cache

def parse_file(input_file):
    '''read the input file into a list of ints'''
    return [int(x) for x in input_file.readlines()]

def p_1(input_file: IO,
        debug=False):  # pylint: disable=unused-argument
    '''what is number of 1 diffs * number of 3 diffs'''
    # add 0 for the initial one
    adaptors = [0] + parse_file(input_file)

    # first we need to sort them
    adaptors.sort()

    # now put adaptors into a queue so we can pop out more easily (we
    # just care about the order, we don't need things to stay there)
    adaptors = deque(adaptors)

    # now we just loop thru and find the number that are diff by 1
    # and the number that are diff by three
    num_1 = 0
    num_3 = 0
    most_recent = 0
    while adaptors:
        head = adaptors.popleft()
        if head == 0:
            continue
        if head - most_recent == 1:
            num_1 += 1
            most_recent = head
        elif head - most_recent == 3:
            num_3 += 1
            most_recent = head
        else:
            print('error')

    # add 1 to num_3 because of the final adaptor
    return num_1 * (num_3+1)

def find_iteration_wrapper(adaptors, target):
    '''wrapper to take in the adaptors argument'''
    @lru_cache()
    def find_iteration(target):
        '''how many ways are there to reach target?'''
        if len(adaptors) == 0:
            return 0
        if target == 0:
            return 1
        if target == 1:
            return 1

        possible = {target-i for i in range(1, 4)}

        #this can be optimized if necessary to not pass in all of adaptors
        #but it didn't seem like it had a huge impact on run time vs the cache...
        #n isn't that high after all
        existing = [x for x in adaptors if x in possible and x >= 0]
        total_iterations = sum([find_iteration(x)
                                for x in existing])
        return total_iterations

    return find_iteration(target)

def p_2(input_file: IO,
        debug=False):  # pylint: disable=unused-argument
    '''how many ways are there to arrange the adaptors
    so that the max is still reached'''
    adaptors = [0] + parse_file(input_file)

    # first sort the adaptors
    adaptors.sort()

    #since sorted by ascending target is the last element
    return find_iteration_wrapper(adaptors, adaptors[-1])


import enum
import struct
from typing import Dict, Tuple

# Webots specific library
from controller import Emitter, Receiver, Supervisor  # isort:skip

# Updating? Update `Arena.wbt` too
ZONE_COLOURS = ((1, 0, 1), (1, 1, 0))

RECEIVE_TICKS = 1

# Updating? Update radio.py too.
BROADCASTS_PER_SECOND = 10

# Updating? Update radio.py too.
class Claimant(enum.IntEnum):
    UNCLAIMED = -1
    ZONE_0 = 0
    ZONE_1 = 1

# Updating? Update radio.py too.
class StationCode(str, enum.Enum):
    PN = 'PN'
    EY = 'EY'
    BE = 'BE'
    PO = 'PO'
    YL = 'YL'
    BG = 'BG'
    TS = 'TS'
    OX = 'OX'
    VB = 'VB'
    SZ = 'SZ'
    SW = 'SW'
    BN = 'BN'
    HV = 'HV'

class TerritoryController:

    _emitters: Dict[StationCode, Emitter]
    _receivers: Dict[StationCode, Receiver]

    def __init__(self) -> None:
        self._robot = Supervisor()
        self._station_statuses: Dict[StationCode, Claimant] = {
            code: Claimant.UNCLAIMED for code in StationCode
        }
        self._claim_starts: Dict[Tuple[StationCode, Claimant], float] = {}

    def get_claimant(
        self,
        station_code: StationCode,
    ) -> Claimant:
        return self._station_statuses[station_code]

    def setup(self) -> None:
        self._emitters = {station_code: self._robot.getEmitter(station_code + "Emitter")
                          for station_code in StationCode}

        self._receivers = {station_code: self._robot.getReceiver(station_code + "Receiver")
                           for station_code in StationCode}
        territory_controller.enable_receivers()

    def enable_receivers(self) -> None:
        for receiver in self._receivers.values():
            receiver.enable(RECEIVE_TICKS)

    def _log_territory_claim(
        self,
        station_code: StationCode,
        claimed_by: Claimant,
        claim_time: float,
    ) -> None:
        # TODO add better logging so we can score
        print(f"{station_code} CLAIMED BY {claimed_by} AT {claim_time}s")  # noqa:T001

    def begin_claim(
        self,
        station_code: StationCode,
        claimed_by: Claimant,
        claim_time: float,
    ) -> None:
        self._claim_starts[station_code, claimed_by] = claim_time

    def has_begun_claim_in_time_window(
        self,
        station_code: StationCode,
        claimant: Claimant,
        current_time: float,
    ) -> bool:
        try:
            start_time = self._claim_starts[station_code, claimant]
        except KeyError:
            return False
        time_delta = current_time - start_time
        return 1.8 <= time_delta <= 2.1

    def claim_territory(
        self,
        station_code: StationCode,
        claimed_by: Claimant,
        claim_time: float,
    ) -> None:
        if self.get_claimant(station_code) == claimed_by:
            # This territory is already claimed by this claimant.
            return

        new_colour = ZONE_COLOURS[claimed_by]
        self._robot.getFromDef(station_code).getField("zoneColour").setSFColor(
            list(new_colour),
        )

        self._log_territory_claim(station_code, claimed_by, self._robot.getTime())
        self._station_statuses[station_code] = claimed_by

    def process_packet(
        self,
        station_code: StationCode,
        packet: bytes,
        receive_time: float,
    ) -> None:
        try:
            robot_id, is_conclude = struct.unpack("!BB", packet)
            if is_conclude:
                if self.has_begun_claim_in_time_window(
                    station_code,
                    robot_id,
                    receive_time,
                ):
                    self.claim_territory(
                        station_code,
                        robot_id,
                        receive_time,
                    )
            else:
                self.begin_claim(
                    station_code,
                    robot_id,
                    receive_time,
                )
        except ValueError:
            print(  # noqa:T001
                f"Received malformed packet at {receive_time} on {station_code}: {packet!r}",
            )

    def receive_territory(self, station_code: StationCode, receiver: Receiver) -> None:
        simulation_time = self._robot.getTime()

        while receiver.getQueueLength():
            try:
                data = receiver.getData()
                self.process_packet(station_code, data, simulation_time)
            finally:
                # Always advance to the next packet in queue: if there has been an exception,
                # it is safer to advance to the next.
                receiver.nextPacket()

    def receive_robot_captures(self) -> None:
        for station_code, receiver in self._receivers.items():
            self.receive_territory(station_code, receiver)

    def transmit_pulses(self) -> None:
        for station_code, emitter in self._emitters.items():
            emitter.send(struct.pack("!2sb", station_code.encode('ASCII'),
                         int(self.get_claimant(station_code))))

    def main(self) -> None:
        self.setup()
        timestep = self._robot.getBasicTimeStep()
        steps_per_broadcast = (1 / BROADCASTS_PER_SECOND) / (timestep / 1000)
        counter = 0
        while True:
            counter += 1
            self.receive_robot_captures()
            if (counter > steps_per_broadcast):
                self.transmit_pulses()
                counter = 0
            self._robot.step(int(self._robot.getBasicTimeStep()))

if __name__ == "__main__":
    territory_controller = TerritoryController()
    territory_controller.main()


from zipfile import ZipFile
from .. import feature

from .. import anchor as _anchor

from ... import commons

import pandas as pd
from textwrap import wrap

class Tabular(feature.Feature):
    """
    Represents a table of different measures anchored to a brain location.

    Columns represent different types of values, while rows represent different
    samples. The number of columns might thus be interpreted as the feature
    dimension.

    As an example, receptor fingerprints use rows to represent different
    neurotransmitter receptors, and separate columns for the mean and standard
    deviations measure across multiple tissue samples.
    """

    def __init__(
        self,
        description: str,
        modality: str,
        anchor: _anchor.AnatomicalAnchor,
        data: pd.DataFrame,  # sample x feature dimension
        datasets: list = []
    ):
        feature.Feature.__init__(
            self,
            modality=modality,
            description=description,
            anchor=anchor,
            datasets=datasets
        )
        self._data_cached = data

    @property
    def data(self):
        return self._data_cached.copy()

    def _export(self, fh: ZipFile):
        super()._export(fh)
        fh.writestr("tabular.csv", self.data.to_csv())

    def plot(self, *args, backend="matplotlib", **kwargs):
        """
        Create a bar plot of a columns of the data.
        Parameters
        ----------
        backend: str
            "matplotlib", "plotly", or others supported by pandas DataFrame
            plotting backend.
        **kwargs
            takes Matplotlib.pyplot keyword arguments
        """
        wrapwidth = kwargs.pop("textwrap") if "textwrap" in kwargs else 40
        kwargs["title"] = kwargs.get(
            "title",
            "\n".join(wrap(
                f"{self.modality} in {', '.join({_.name for _ in self.anchor.regions})}",
                wrapwidth
            ))
        )
        kwargs["kind"] = kwargs.get("kind", "bar")
        kwargs["y"] = kwargs.get("y", self.data.columns[0])
        if backend == "matplotlib":
            try:
                import matplotlib.pyplot as plt
            except ImportError:
                commons.logger.error("matplotlib not available. Plotting of fingerprints disabled.")
                return None
            # default kwargs
            if kwargs.get("error_y") is None:
                kwargs["yerr"] = kwargs.get("yerr", 'std' if 'std' in self.data.columns else None)
                yerr_label = f" \u00b1 {kwargs.get('yerr')}" if kwargs.get('yerr') else ''
            kwargs["width"] = kwargs.get("width", 0.95)
            kwargs["ylabel"] = kwargs.get(
                "ylabel",
                f"{kwargs['y']}{yerr_label} {self.unit if hasattr(self, 'unit') else ''}"
            )
            kwargs["grid"] = kwargs.get("grid", True)
            kwargs["legend"] = kwargs.get("legend", False)
            ax = self.data.plot(*args, backend=backend, **kwargs)
            ax.set_title(ax.get_title(), fontsize="medium")
            ax.set_xticklabels(ax.get_xticklabels(), rotation=60, ha="right")
            plt.tight_layout()
            return ax
        elif backend == "plotly":
            kwargs["title"] = kwargs["title"].replace("\n", "<br>")
            kwargs["error_y"] = kwargs.get("error_y", 'std' if 'std' in self.data.columns else None)
            error_y_label = f" ± {kwargs.get('error_y')}" if kwargs.get('error_y') else ''
            kwargs["labels"] = {
                "index": kwargs.pop("xlabel", None) or kwargs.pop("index", ""),
                "value": kwargs.pop("ylabel", None) or kwargs.pop(
                    "value",
                    f"{kwargs.get('y')}{error_y_label} {self.unit if hasattr(self, 'unit') else ''}"
                )
            }
            fig = self.data.plot(*args, backend=backend, **kwargs)
            fig.update_layout(
                yaxis_title=kwargs["labels"]['value'],
                title=dict(
                    automargin=True, yref="container", xref="container",
                    pad=dict(t=40), xanchor="left", yanchor="top"
                )
            )
            return fig
        else:
            return self.data.plot(*args, backend=backend, **kwargs)


import pandas as pd
import os
import argparse

def swap_toxic(reference, translation, ref_tox, trn_tox):
    if trn_tox > ref_tox:
        reference, translation = translation, reference

    return pd.Series([reference, translation], index=["reference", "translation"])

def preprocess(data_path, sep="\t", save_path="data/interim/"):
    data = pd.read_csv(data_path, sep=sep)

    preprocessed = data[["reference", "translation", "ref_tox", "trn_tox"]].apply(
        lambda row: swap_toxic(*row), axis=1
        )

    if not os.path.exists(save_path):
        os.mkdir(save_path)

    preprocessed.to_csv(save_path + data_path.split("/")[-1], sep=sep)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Download data from url")
    parser.add_argument("--path",
                        default= "data/raw/filtered.tsv",
                        dest= "data_path",
                        help= "path to raw data")
    parser.add_argument("--dst",
                        dest= "save_path",
                        default= "data/interim/",
                        help= "save path (default: data/interim/)")
    parser.add_argument("--sep",
                        dest= "sep",
                        default= "\t",
                        help= "csv separator (default: tab)")

    args = parser.parse_args()
    preprocess(args.data_path, args.sep, args.save_path)


from Repository.ExternalTaskRepository.ExternalTaskRepository import ExternalTaskRepository

class CopyExternalTasksBetweenRepositories:

    def __init__(self, source_repository: ExternalTaskRepository, destination_repository: ExternalTaskRepository):
        self.source_repository: ExternalTaskRepository = source_repository
        self.destination_repository: ExternalTaskRepository = destination_repository

    def interact(self):
        source_repository = self.source_repository
        destination_repository = self.destination_repository
        external_tasks = source_repository.get_all()
        for external_task in external_tasks:
            destination_repository.save(external_task=external_task)


number = 0

for i in range(999, 100, -1):
    for j in range(i, 100, -1):
        a = i*j
        if a > number:
            a = str(a)
            if a == a[::-1]:
                number = int(a)

print(number)


import sys
import os

os.environ["PYAEDT_IRONPYTHON_SERVER"] = "1"
sys.path.append(pyaedt_path)
#sys.path.insert(0, os.path.join(pyaedt_path, "pyaedt", "third_party", "ironpython"))
from pyaedt import is_ironpython

if is_ironpython:
    from pyaedt.rpc.rpyc_services import PyaedtServiceWindows
    from pyaedt.third_party.ironpython.rpyc_27 import OneShotServer
else:
    from pyaedt.rpc.rpyc_services import PyaedtServiceWindows
    from rpyc import OneShotServer

safe_attrs = {
    "__abs__",
    "__add__",
    "__and__",
    "__bool__",
    "__code__",
    "__class__",
    "__cmp__",
    "__contains__",
    "__delitem__",
    "__delslice__",
    "__div__",
    "__divmod__",
    "__doc__",
    "__eq__",
    "__float__",
    "__floordiv__",
    "__func__",
    "__ge__",
    "__dict__",
    "__getitem__",
    "__getslice__",
    "__gt__",
    "__hash__",
    "__hex__",
    "__iadd__",
    "__iand__",
    "__idiv__",
    "__ifloordiv__",
    "__ilshift__",
    "__imod__",
    "__imul__",
    "__index__",
    "__int__",
    "__invert__",
    "__ior__",
    "__ipow__",
    "__irshift__",
    "__isub__",
    "__iter__",
    "__itruediv__",
    "__ixor__",
    "__le__",
    "__len__",
    "__long__",
    "__lshift__",
    "__lt__",
    "__mod__",
    "__mro__",
    "__mul__",
    "__name__",
    "__ne__",
    "__neg__",
    "__new__",
    "__nonzero__",
    "__oct__",
    "__or__",
    "__pos__",
    "__pow__",
    "__radd__",
    "__rand__",
    "__rdiv__",
    "__rdivmod__",
    "__repr__",
    "__rfloordiv__",
    "__rlshift__",
    "__rmod__",
    "__rmul__",
    "__ror__",
    "__rpow__",
    "__rrshift__",
    "__rshift__",
    "__rsub__",
    "__rtruediv__",
    "__rxor__",
    "__setitem__",
    "__setslice__",
    "__str__",
    "__sub__",
    "__truediv__",
    "__xor__",
    "next",
    "__length_hint__",
    "__enter__",
    "__exit__",
    "__next__",
    "__format__",
}
OneShotServer(
    PyaedtServiceWindows,
    hostname=hostname,
    port=port,
    protocol_config={
        "sync_request_timeout": None,
        "allow_public_attrs": True,
        "safe_attrs": safe_attrs,
        "allow_setattr": True,
        "allow_getattr": True,
        "allow_delattr": True,
    },
).start()


from tkinter import*
root=Tk()
root.geometry("300x260")
def winsize():
    root.geometry(f"{wdt.get()}x{hgt.get()}")
width=Label(root,text="Width:")
width.grid(row=1)
hight=Label(root,text="Height:")
hight.grid(row=2)
wdt=StringVar
hgt=StringVar
Entry(root,textvariable=wdt).grid(row=1,column=3)
Entry(root,textvariable=hgt).grid(row=2,column=3)
Button(root,text="Submit",relief=SUNKEN,command=winsize).grid()

root.mainloop()


from time import perf_counter_ns

# Ignore below

def format_ns(time: int) -> str:
    lengths = [1, 1000, 1000, 1000, 60, 60, 24]
    units = ["ns", "μs", "ms", "s", "minutes", "hours", "days"]
    idx = 1
    prev = 0
    while time > lengths[idx+1]:
        idx += 1
        time, prev = time//lengths[idx], time%lengths[idx]

    out = f"{time}{units[idx]}"
    if 0 < prev and time < 100:
        out += f" {prev}{units[idx-1]}"
    return out

def read_data(filename="input.txt"):
    with open(filename) as file:
        content = file.read().strip()

    return process_data(content)

# Ignore above

def process_data(content):
    elves = content.split("\n\n")
    elves = [map(int, elf.split("\n")) for elf in elves]
    elves = list(map(sum, elves))
    return elves

def task1(data):
    return max(data)

def task2(data):
    res = data[:3]
    res.sort()
    x, y, z = res
    for cal in data[3:]:
        if cal > x:
            if cal > z:
                y, z = z, cal
            elif cal > y:
                x, y = y, cal
            else:
                x = cal
    return x + y + z

def main():
    # fn = "input_bsp.txt"
    fn = "input.txt"
    t0 = perf_counter_ns()
    data = read_data(fn)
    t1 = perf_counter_ns()
    result1 = task1(data)
    t2 = perf_counter_ns()
    result2 = task2(data)
    t3 = perf_counter_ns()

    print(f"Data preprocessing in {format_ns(t1 - t0)}")
    print(f"Task 1: {result1} in {format_ns(t2 - t1)}")
    print(f"Task 2: {result2} in {format_ns(t3 - t2)}")

if __name__ == "__main__":
    main()


import numpy as np
import time
import scipy.sparse as sparse
from collections import defaultdict

from lib.PoissonFactorModel import PoissonFactorModel
from lib.MultiGaussianModel import MultiGaussianModel
from lib.TimeAwareMF import TimeAwareMF
from lib.metrics import precisionk, recallk, ndcgk, mapk

def read_poi_coos():
    poi_coos = {}
    poi_data = open(poi_file, 'r').readlines()
    for eachline in poi_data:
        lid, lat, lng = eachline.strip().split()
        lid, lat, lng = int(lid), float(lat), float(lng)
        poi_coos[lid] = (lat, lng)
    return poi_coos

def read_training_data():
    # load train data
    train_data = open(train_file, 'r').readlines()
    sparse_training_matrix = sparse.dok_matrix((user_num, poi_num))
    training_tuples = set()
    for eachline in train_data:
        uid, lid, freq = eachline.strip().split()
        uid, lid, freq = int(uid), int(lid), int(freq)
        sparse_training_matrix[uid, lid] = freq
        training_tuples.add((uid, lid))

    # load checkins
    # time_list_hour = open("./result/time_hour" + ".txt", 'w')
    check_in_data = open(check_in_file, 'r').readlines()
    training_tuples_with_day = defaultdict(int)
    training_tuples_with_time = defaultdict(int)
    for eachline in check_in_data:
        uid, lid, ctime = eachline.strip().split()
        uid, lid, ctime = int(uid), int(lid), float(ctime)
        if (uid, lid) in training_tuples:
            hour = time.gmtime(ctime).tm_hour
            training_tuples_with_time[(hour, uid, lid)] += 1.0
            if 8 <= hour < 18:
                # working time
                hour = 0
            elif hour >= 18 or hour < 8:
                # leisure time
                hour = 1

            training_tuples_with_day[(hour, uid, lid)] += 1.0

    # Default setting: time is partitioned to 24 hours.
    sparse_training_matrices = [sparse.dok_matrix((user_num, poi_num)) for _ in range(24)]
    for (hour, uid, lid), freq in training_tuples_with_time.items():
        sparse_training_matrices[hour][uid, lid] = 1.0 / (1.0 + 1.0 / freq)

    # Default setting: time is partitioned to WD and WE.
    sparse_training_matrix_WT = sparse.dok_matrix((user_num, poi_num))
    sparse_training_matrix_LT = sparse.dok_matrix((user_num, poi_num))

    for (hour, uid, lid), freq in training_tuples_with_day.items():
        if hour == 0:
            sparse_training_matrix_WT[uid, lid] = freq
        elif hour == 1:
            sparse_training_matrix_LT[uid, lid] = freq

    print ("Data Loader Finished!")
    return sparse_training_matrices, sparse_training_matrix, sparse_training_matrix_WT, sparse_training_matrix_LT, training_tuples

def read_ground_truth():
    ground_truth = defaultdict(set)
    truth_data = open(test_file, 'r').readlines()
    for eachline in truth_data:
        uid, lid, _ = eachline.strip().split()
        uid, lid = int(uid), int(lid)
        ground_truth[uid].add(lid)
    print("The loading of Ground Truth Finished.")
    return ground_truth

def main():
    sparse_training_matrices, sparse_training_matrix, sparse_training_matrix_WT, sparse_training_matrix_LT, training_tuples = read_training_data()
    ground_truth = read_ground_truth()
    poi_coos = read_poi_coos()

    start_time = time.time()

    PFM.train(sparse_training_matrix, max_iters=10, learning_rate=1e-4)
    # Multi-Center Weekday
    MGMWT.multi_center_discovering(sparse_training_matrix_WT, poi_coos)
    # Multi-Center Weekend
    MGMLT.multi_center_discovering(sparse_training_matrix_LT, poi_coos)

    TAMF.train(sparse_training_matrices, max_iters=30, load_sigma=False)

    elapsed_time = time.time() - start_time
    print("Done. Elapsed time:", elapsed_time, "s")

    execution_time = open("./result/execution_time" + ".txt", 'w')
    execution_time.write(str(elapsed_time))

    rec_list = open("./result/reclist_top_" + str(top_k) + ".txt", 'w')
    result_5 = open("./result/result_top_" + str(5) + ".txt", 'w')
    result_10 = open("./result/result_top_" + str(10) + ".txt", 'w')
    result_15 = open("./result/result_top_" + str(15) + ".txt", 'w')
    result_20 = open("./result/result_top_" + str(20) + ".txt", 'w')

    all_uids = list(range(user_num))
    all_lids = list(range(poi_num))
    np.random.shuffle(all_uids)

    # list for different ks
    precision_5, recall_5, nDCG_5, MAP_5 = 0, 0, 0, 0
    precision_10, recall_10, nDCG_10, MAP_10 = 0, 0, 0, 0
    precision_15, recall_15, nDCG_15, MAP_15 = 0, 0, 0, 0
    precision_20, recall_20, nDCG_20, MAP_20 = 0, 0, 0, 0

    for cnt, uid in enumerate(all_uids):
        if uid in ground_truth:
            # What is the meaning of the following structure?
            overall_scores = [PFM.predict(uid, lid) * (MGMWT.predict(uid, lid) + MGMLT.predict(uid, lid)) * TAMF.predict(uid, lid)
                              if (uid, lid) not in training_tuples else -1
                              for lid in all_lids]

            overall_scores = np.array(overall_scores)

            predicted = list(reversed(overall_scores.argsort()))[:top_k]
            actual = ground_truth[uid]

            # calculate the average of different k
            precision_5 = precisionk(actual, predicted[:5])
            recall_5 = recallk(actual, predicted[:5])
            nDCG_5 = ndcgk(actual, predicted[:5])
            MAP_5 = mapk(actual, predicted[:5], 5)

            precision_10 = precisionk(actual, predicted[:10])
            recall_10 = recallk(actual, predicted[:10])
            nDCG_10 = ndcgk(actual, predicted[:10])
            MAP_10 = mapk(actual, predicted[:10], 10)

            precision_15 = precisionk(actual, predicted[:15])
            recall_15 = recallk(actual, predicted[:15])
            nDCG_15 = ndcgk(actual, predicted[:15])
            MAP_15 = mapk(actual, predicted[:15], 15)

            precision_20 = precisionk(actual, predicted[:20])
            recall_20 = recallk(actual, predicted[:20])
            nDCG_20 = ndcgk(actual, predicted[:20])
            MAP_20 = mapk(actual, predicted[:20], 20)

            rec_list.write('\t'.join([
                str(cnt),
                str(uid),
                ','.join([str(lid) for lid in predicted])
            ]) + '\n')

            # write the different ks
            result_5.write('\t'.join([str(cnt), str(uid), str(precision_5), str(recall_5), str(nDCG_5), str(MAP_5)]) + '\n')
            result_10.write('\t'.join([str(cnt), str(uid), str(precision_10), str(recall_10), str(nDCG_10), str(MAP_10)]) + '\n')
            result_15.write('\t'.join([str(cnt), str(uid), str(precision_15), str(recall_15), str(nDCG_15), str(MAP_15)]) + '\n')
            result_20.write('\t'.join([str(cnt), str(uid), str(precision_20), str(recall_20), str(nDCG_20), str(MAP_20)]) + '\n')

    print("<< STACP is Finished >>")

if __name__ == '__main__':
    data_dir = "../gowalla_u5628/"

    size_file = data_dir + "Gowalla_data_size.txt"
    check_in_file = data_dir + "Gowalla_checkins.txt"
    train_file = data_dir + "Gowalla_train.txt"
    tune_file = data_dir + "Gowalla_tune.txt"
    test_file = data_dir + "Gowalla_test.txt"
    poi_file = data_dir + "Gowalla_poi_coos.txt"

    user_num, poi_num = open(size_file, 'r').readlines()[0].strip('\n').split()
    user_num, poi_num = int(user_num), int(poi_num)

    top_k = 100

    PFM = PoissonFactorModel(K=30, alpha=20.0, beta=0.2)
    MGMWT = MultiGaussianModel(alpha=0.2, theta=0.02, dmax=15)
    MGMLT = MultiGaussianModel(alpha=0.2, theta=0.02, dmax=15)
    TAMF = TimeAwareMF(K=100, Lambda=1.0, beta=2.0, alpha=2.0, T=24)

    main()


# coding: utf-8

from utg import exceptions

class Dictionary(object):
    __slots__ = ('_data',)

    def __init__(self, words=[]):
        self._data = {}

        for word in words:
            self.add_word(word)

    def add_word(self, word):
        for i, word_form in enumerate(word.all_forms()):

            if word_form.form not in self._data:
                self._data[word_form.form] = word_form
                continue

            registered_form = self._data[word_form.form]

            if word_form.word.type.value < registered_form.word.type.value:
                self._data[word_form.form] = word_form
                continue

            if word_form.word.type.value > registered_form.word.type.value:
                continue

            if word_form.word.forms < registered_form.word.forms:
                self._data[word_form.form] = word_form
                continue

            if word_form.word.forms > registered_form.word.forms:
                continue

            if word_form.properties.manhattan_distance() < registered_form.properties.manhattan_distance():
                self._data[word_form.form] = word_form
                continue

            if word_form.properties.manhattan_distance() > registered_form.properties.manhattan_distance():
                continue

            if word_form is registered_form:
                continue

            continue

    def has_word(self, text):
        return text in self._data

    def get_word(self, text):

        word = self._data.get(text)

        if word is None:
            raise exceptions.NoWordsFoundError(text=text)

        return word

    def get_words(self):
        return set(word_form.word for word_form in self._data.values())


from flask import Flask
from waitress import serve
from process_tilt_ciphersmaug.logging import TiltLogger
import requests
from opentelemetry import trace
#from opentelemetry.instrumentation.requests import RequestsInstrumentor
import sqlite3

def initialize_db():
    db = sqlite3.connect("user.sqlite")
    cursor = db.cursor()
    with open("user.sql",mode="r") as f:
        cursor.executescript(f.read())
    db.close()

tracer = trace.get_tracer(__name__)
app = Flask(__name__)
initialize_db()
#RequestsInstrumentor().instrument()
# Create the tilt Logger
tl = TiltLogger("TILT",tracer)

@app.route('/user/<id>')
def user_information(id: int):
    address = request_address(id)
    user_information = get_user_information(id)
    return user_information | address

@tl.log(concept_name = "Combine User Data", tilt = {
    "data_disclosed": ["user.firstname","user.lastname","user.birthday","address.street","address.postcode","address.number"],
    "purposes": ["personal data access"],
    "legal_bases": ["GDPR-6-1-b"]
    }, msg = "Combine User Data")
def get_user_information(id: int):

    if int(id) > 1000:
        return {}
    else:
        db = sqlite3.connect("user.sqlite")
        result = {}
        for row in db.execute(f"SELECT * from user WHERE id == {id}"):
            id,lastname,firstname,email,sex,ip = row
            result["firstname"]=firstname
            result["lastname"]=lastname
            result["birthday"]=ip
            result["description"]=email
            break
        db.close()
        return result

@tl.log(concept_name = "Request User Address", tilt = {
    "data_disclosed": ["user.id"],
    "purposes": ["personal data access"],
    "legal_bases": ["GDPR-6-1-b"]
    }, msg = "Request User Address")
def request_address(id: int):
    with tracer.start_as_current_span("Request User Address"):
        response = requests.get(f"http://address-service/address/{id}")
        return response.json()

if __name__ == "__main__":
    serve(app, host="0.0.0.0", port=8082)


"""

"""
import os
import re
import json
import urllib
import logging
import datetime
import sqlite3
import requests
import collections
from queue import Queue
from bs4 import BeautifulSoup

class Crawler:
    """
    A web crawler that fetches and stores webpages from a given base URL.

    Attributes:
        base_url (str): The base URL from which the crawler starts.
        data_path (str): Path to the directory where data will be stored.
        logs_path (str): Path to the directory where logs will be stored.
        errors_path (str): Path to the directory where error logs will be stored.
        database (str): Name of the SQLite database to use for storing webpages.
    """

    def __init__(self, **kwargs):
        """
        Initializes the crawler with necessary parameters and establishes a database connection.

        Args:
            **kwargs: Keyword arguments for configuration parameters.
        """
        logging.basicConfig(
            level=logging.INFO,
            filename=os.path.join(kwargs.get("logs_path"), "crawler.log"),
            filemode="a",
            format="%(asctime)s - %(levelname)s - %(message)s"
        )
        self.logger = logging.getLogger(__name__)

        self.base_url: str = kwargs.get("base_url")
        self.data_path: str = kwargs.get("data_path", ".")
        self.logs_path: str = kwargs.get("logs_path", ".")
        self.errors_path: str = kwargs.get("errors_path", ".")
        self.database: str = kwargs.get("database", "webpages.db")

        self.errors = collections.defaultdict(lambda: [])
        self.session = requests.Session()
        self.session.headers.update({"Accept-Language": "pt-br,pt-BR"})

        # Establish connection and create table webpages
        self.conn = sqlite3.connect(self.database)
        self.cursor = self.conn.cursor()
        self.cursor.execute("""
            CREATE TABLE IF NOT EXISTS webpages (
                url TEXT PRIMARY KEY,
                webpage BLOB,
                metadata BOOLEAN NOT NULL DEFAULT 0,
                document BOOLEAN NOT NULL DEFAULT 0,
                parsed BOOLEAN NOT NULL DEFAULT 0
            );
        """)
        self.conn.commit()

    def execute(self):
        """
        Executes the web crawling operation, starting from the base URL and traversing its children URLs.
        """
        self.logger.info("started execution")

        queue = Queue()

        visited = set()
        # If database is empty, add base_url to queue, otherwise add all already visited urls
        if self.cursor.execute("SELECT url FROM webpages LIMIT 1").fetchone() is None:
            success = self.database_insert(self.base_url)
            if not success:
                return self.stop()
            queue.put(self.base_url)
            visited.add(self.base_url)
        else:
            res = self.cursor.execute("SELECT url FROM webpages")
            visited_urls = [[_] for _ in res.fetchall()]
            for url in visited_urls:
                queue.put(url)
                visited.add(url)

        # Traverse the website as BFS
        while not queue.empty():
            current: str = queue.get()
            [webpage] = self.database_select_instance(column="url", value=current)
            soup = BeautifulSoup(webpage, "html.parser")

            # Obtain children urls of current webpage
            children = []
            a_tags = soup.find_all("a")
            for a_tag in a_tags:
                url: str = a_tag.attrs.get("href")
                if url is not None:
                    url = urllib.parse.urljoin(self.base_url, url)
                    children.append(url)

            # Traverse children urls
            for child in children:
                parsed_url = urllib.parse.urlparse(child)

                # Ignore the website in other languages
                query: str = parsed_url.query
                if "lang" in query and "lang=pt" not in query:
                    self.logger.warning(f"found lang!=pt: {child}, continuing")
                    continue

                # Ignore links that are not urls
                if parsed_url.scheme and (parsed_url.scheme != "http" or parsed_url.scheme != "https"):
                    self.logger.warning(f"found link!=url: {child}, continuing")
                    continue

                url = urllib.parse.urljoin(self.base_url, child)
                if url not in visited:
                    success = self.database_insert(url)
                    if success:
                        queue.put(url)
                        visited.add(url)

        self.stop()

    def stop(self) -> None:
        """
        Stops the web crawler, closes the database connection and logs the errors encountered during
        execution.
        """
        self.conn.close()
        with open(os.path.join(self.errors_path, "errors_crawler.json"), "w") as f:
            f.write(json.dumps(self.errors))
        self.logger.info(f"Stopping crawler. #Errors: {len(self.errors)}")

    def database_insert(self, url: str) -> bool:
        """
        Fetches the webpage at the given URL and inserts it into the database.

        Args:
            url (str): The URL of the webpage to fetch and insert into the database.

        Returns:
            bool: True if the webpage was successfully inserted into the database, False otherwise.
        """
        response = self.session.get(url)
        if not response.ok:
            self.logger.error(f"unable to obtain {url}. Code: {response.status_code}")
            self.errors["request"].append((url, response.status_code))
            return False

        webpage: bytes = response.content
        metadata: bool = False
        document: bool = False
        if re.search("tde-\d+-\d+", url) is not None:
            if re.search(".pdf$", url) is not None:
                document = True
            else:
                metadata = True
        self.cursor.execute("""
            INSERT INTO webpages VALUES(?, ?, ?, ?, ?)
        """, (url, webpage, metadata, document, 0))
        self.conn.commit()

        self.logger.info(f"successfully inserted {url} to webpages")

        return True

    def database_contains(self, url: str) -> bool:
        """
        Checks if the database contains a webpage at the given URL.
        Args:
            url (str): The URL to check in the database.
        Returns:
            bool: True if the database contains a webpage at the given URL, False otherwise.
        """
        return self.database_select_instance(column="url", value=url) is None

    def database_select_instance(self, column: str, value: str) -> tuple:
        """
        Fetches a row from the database where the given column matches the given value.
        Args:
            column (str): The column to match.
            value (str): The value to match in the column.
        Returns:
            tuple: The row from the database where the column matches the value, or None if no such
            row exists.
        """
        query = f"SELECT * FROM webpages WHERE {column} = ?"
        self.cursor.execute(query, (value, ))
        return self.cursor.fetchone()


import numpy as np
from src.character import Character

def sim_battle(c1, c2):
    """Simulates battle between c1 and c2 and returns name of winner."""
    c1hp_init = c1.health
    c2hp_init = c2.health

    turn_count = 0

    # this is the core loop of a single combat simulation
    while not c1.dead() and not c2.dead():
        c1a = c1.gen_attack(c1hp_init)
        c2a = c2.gen_attack(c2hp_init)
        c1h = c1.gen_heal()
        c2h = c2.gen_heal()

        turn_count += 1

        if np.random.uniform() < 0.5:
            c1.health = c1h - c2a
        else:
            c2.health = c2h - c1a

    # if someone gets defeated
    if c1.dead() and not c2.dead():
        victor = c2.name

    elif c2.dead() and not c1.dead():
        victor = c1.name

    else:
        victor = None

    return victor

def sim_multiple_battles(c1_stats_dict, c2_stats_dict, num_battles):
    """Simulates multiple battles and returns printed results"""

    c1_victories = 0
    c2_victories = 0

    # Iterate through num_battles configured in the YAML file
    for i in range(1, num_battles):
        c1 = Character(
            c1_stats_dict["name"],
            c1_stats_dict["health"],
            c1_stats_dict["attack"],
            c1_stats_dict["crit_rate"],
            c1_stats_dict["crit_mult"],
            c1_stats_dict["berserk_percent"],
            c1_stats_dict["pray_percent"]
        )
        c2 = Character(
            c2_stats_dict["name"],
            c2_stats_dict["health"],
            c2_stats_dict["attack"],
            c2_stats_dict["crit_rate"],
            c2_stats_dict["crit_mult"],
            c2_stats_dict["berserk_percent"],
            c2_stats_dict["pray_percent"]
        )

        whowin = sim_battle(c1, c2)
        if whowin == c1.name:
            c1_victories += 1
        elif whowin == c2.name:
            c2_victories += 1
        else:
            pass

    # print results
    print("_______________________________________________")
    print("{} vs. {} results for {} battles:".format(c1.name, c2.name, num_battles))
    print("{} won: {} times".format(c1.name, c1_victories))
    print("{} won: {} times".format(c2.name, c2_victories))
    print("_______________________________________________")


import json
import requests
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def get_character():
    r = requests.get('https://www.breakingbadapi.com/api/character/random')
    characterjson = r.json()
    character = {
        'image': characterjson[0]['img'],
        'name': characterjson[0]['name'],
        'occupation': characterjson[0]['occupation'],
        'status': characterjson[0]['status'],
        'nickname': characterjson[0]['nickname']
    }

    # Display Character
    return(render_template('green/index.html', character=character))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, debug=True)  # specify port=80


import tensorflow as tf

flags = tf.app.flags
flags.DEFINE_string('mode', 'train', 'train or test')
flags.DEFINE_string('model', 'Tiramisu', 'FCN or Tiramisu or Densenet or CNN')
flags.DEFINE_integer('reload_step', 0, 'Reload step to continue training')
flags.DEFINE_integer('step_num', 1500, 'Reload step to test the model')

# Training logs
flags.DEFINE_integer('max_step', 2000, '# of step for training')
flags.DEFINE_integer('SUMMARY_FREQ', 100, 'Number of step to save summary')
flags.DEFINE_integer('VAL_FREQ', 100, 'Number of step to evaluate the network on Validation data') #default = 1000
flags.DEFINE_float('init_lr', 1e-3, 'Initial learning rate')
flags.DEFINE_float('lr_min', 1e-5, 'Minimum learning rate')

# Hyper-parameters
flags.DEFINE_string('loss_type', 'MSE', 'Mean-Squared Error')
flags.DEFINE_boolean('use_reg', True, 'Adds L2 regularization')#default False
flags.DEFINE_float('lmbda', 1e-3, 'L2 regularization coefficient')
flags.DEFINE_integer('batch_size',4, 'training batch size')

# data
flags.DEFINE_integer('num_tr', 1, 'Total number of training images')
flags.DEFINE_string('data_dir', './data/', 'Data directory')
flags.DEFINE_boolean('normalize', True, 'Whether to load the normalized data or not') # True
flags.DEFINE_boolean('mask', True, 'Whether to use training mask or not') # True
flags.DEFINE_boolean('data_augment', True, 'Adds augmentation to data')
flags.DEFINE_integer('max_angle', 180, 'Maximum rotation angle along each axis; when applying augmentation')
flags.DEFINE_integer('img_size', [1024,512], 'Size of the large original image')
flags.DEFINE_integer('height', 32, 'Network input height size')
flags.DEFINE_integer('width', 32, 'Network input width size')
flags.DEFINE_integer('in_channel', 60, 'Number of input channels')
flags.DEFINE_integer('out_channel', 3, 'Number of output channels')

# Directories
flags.DEFINE_string('run_name', 'tira_575_kid_dapi', 'Run name')
flags.DEFINE_string('logdir', './Results/log_dir/', 'Logs directory')
flags.DEFINE_string('modeldir', './Results/model_dir/', 'Model directory')
flags.DEFINE_string('model_name', 'model', 'Nothing but a name :)')

# network architecture
flags.DEFINE_boolean('use_BN', True, 'Adds Batch-Normalization to all convolutional layers')# use to be True
flags.DEFINE_integer('start_channel_num', 16, 'start number of outputs for the first conv layer')
flags.DEFINE_integer('filter_size', 3, 'Filter size for the conv and deconv layers')
flags.DEFINE_integer('pool_filter_size', 2, 'Filter size for pooling layers')
flags.DEFINE_float('drop_out_rate', 0.8, 'Dropout rate') # used to be 0.8
flags.DEFINE_integer('growth_rate', 2, 'growth rate of the DenseNet')
flags.DEFINE_float('theta_down', 0.5, 'encoder compression rate')
flags.DEFINE_float('theta_up', 0.5, 'decoder compression rate')

args = tf.app.flags.FLAGS


from pyspecdata import *
import os, time
import SpinCore_pp
from pyspecdata.file_saving.hdf_save_dict_to_group import hdf_save_dict_to_group
import h5py
from datetime import datetime

fl = figlist_var()
target_directory = getDATADIR(exp_type="ODNP_NMR_comp/COSY")
raise RuntimeError(
    "This pulse program has been updated to use active.ini, but not the ppg functions.. Before running again, it should be possible to replace a lot of the code below with a call to the function provided by the 'generic' pulse program inside the ppg directory!"
)
# {{{importing acquisition parameters
config_dict = SpinCore_pp.configuration("active.ini")
nPoints = int(config_dict["acq_time_ms"] * config_dict["SW_kHz"] + 0.5)
# }}}
# NOTE: Number of segments is nEchoes * nPhaseSteps
# {{{create filename and save to config file
date = datetime.now().strftime("%y%m%d")
config_dict["type"] = "COSY"
config_dict["date"] = date
config_dict["COSY_counter"] += 1
filename = f"{config_dict['date']}_{config_dict['chemical']}_{config_dict['type']}"
# }}}
# {{{phase cycling and tx phases
tx_phases = r_[0.0, 90.0, 180.0, 270.0]
# NOTE: Number of segments is nEchoes * nPhaseSteps
phase_cycling = True
ph1 = r_[0, 1, 2, 3]
ph2 = r_[0, 2]
if phase_cycling:
    nPhaseSteps = 8
if not phase_cycling:
    nPhaseSteps = 1
# }}}
data_length = 2 * nPoints * nEchoes * nPhaseSteps
# NOTE: Number of segments is nEchoes * nPhaseSteps
# cannot have a delay of 0, so set to minimum SpinCore can take
# {{{making t1 list
min_t1 = 0.065  # us (lower limit of SpinCore)
max_t1 = 200 * 1e3
t1_step = 1.25 * 1e3
t1_list = r_[min_t1:max_t1:t1_step]
# }}}
# {{{ run ppg
for index, val in enumerate(t1_list):
    t1 = val
    for x in range(config_dict["nScans"]):
        SpinCore_pp.configureTX(
            config_dict["adcOffset"],
            config_dict["carrierFreq_MHz"],
            tx_phases,
            config_dict["amplitude"],
            nPoints,
        )
        SpinCore_pp.init_ppg()
        if phase_cycling:
            SpinCore_pp.load(
                [
                    ("marker", "start", 1),
                    ("phase_reset", 1),
                    ("delay_TTL", config_dict["deblank_us"]),
                    ("pulse_TTL", config_dict["p90_us"], "ph1", r_[0, 1, 2, 3]),
                    ("delay", t1),
                    ("delay_TTL", config_dict["deblank_us"]),
                    ("pulse_TTL", config_dict["p90_us"], "ph2", r_[0, 2]),
                    ("delay", config_dict["deadtime_us"]),
                    ("acquire", config_dict["acq_time_ms"]),
                    ("delay", config_dict["repetition_us"]),
                    ("jumpto", "start"),
                ]
            )
        if not phase_cycling:
            SpinCore_pp.load(
                [
                    ("marker", "start", config_dict["nScans"]),
                    ("phase_reset", 1),
                    ("delay_TTL", config_dict["deblank_us"]),
                    ("pulse_TTL", config_dict["p90_us"], 0),
                    ("delay", t1),
                    ("delay_TTL", config_dict["deblank_us"]),
                    ("pulse_TTL", config_dict["p90_us"], 0),
                    ("delay", config_dict["deadtime_us"]),
                    ("acquire", config_dict["acq_time"]),
                    ("delay", config_dict["repetition_us"]),
                    ("jumpto", "start"),
                ]
            )
        SpinCore_pp.stop_ppg()
        SpinCore_pp.runBoard()
        raw_data = SpinCore_pp.getData(
            data_length, nPoints, config_dict["nEchoes"], nPhaseSteps
        )
        raw_data.astype(float)
        data = []
        data[::] = np.complex128(raw_data[0::2] + 1j * raw_data[1::2])
        dataPoints = float(np.shape(data)[0])
        time_axis = np.linspace(
            0.0,
            config_dict["nEchoes"] * nPhaseSteps * config_dict["acq_time_ms"] * 1e-3,
            dataPoints,
        )
        data = nddata(np.array(data), "t")
        data.setaxis("t", time_axis).set_units("t", "s")
        data.name("signal")
        data.set_prop("acq_params", config_dict.asdict())
        data.set_prop("t1_list", t1_list)
        if index == 0 and x == 0:
            COSY_data = ndshape(
                [len(t1_list), config_dict["nScans"], len(time_axis)],
                ["t1", "nScans", "t"],
            ).alloc(dtype=np.complex128)
            COSY_data.setaxis("t1", t1_list * 1e-6).set_units("t1", "s")
            COSY_data.setaxis("nScans", r_[0 : config_dict["nScans"]])
            COSY_data.setaxis("t", time_axis).set_units("t", "s")
        COSY_data["t1", index]["nScans", x] = data
        COSY_data.set_prop("acq_params", config_dict.asdict())
SpinCore_pp.stopBoard()
# }}}
# {{{saving data
config_dict.write()
if phase_cycling:
    COSY_data.chunk("t", ["ph2", "ph1", "t2"], [2, 4, -1])
    COSY_data.setaxis("ph1", r_[0, 1, 2, 3] / 4.0)
    COSY_data.setaxis("ph2", r_[0, 2] / 4.0)
else:
    COSY_data.rename("t", "t2")
nodename = config_dict["type"] + "_" + str(config_dict["cpmg_counter"])
filename_out = filename + "_" + ".h5"
with h5py.File(
    os.path.normpath(os.path.join(target_directory, f"{filename_out}"))
) as fp:
    if nodename in fp.keys():
        print("this nodename already exists, so I will call it temp_%d" % j)
        COSY_data.name("temp_COSY_%d" % config_dict["cpmg_counter"])
        nodename = "temp_COSY_%d" % config_dict["cpmg_counter"]
        COSY_data.hdf5_write(f"{filename_out}", directory=target_directory)
    else:
        COSY_data.hdf5_write(f"{filename_out}", directory=target_directory)
print("\n*** FILE SAVED IN TARGET DIRECTORY ***\n")
print(("Name of saved data", COSY_data.name()))
print(("Shape of saved data", ndshape(COSY_data)))
# }}}
# {{{image data
fl.next("raw data")
fl.image(COSY_data.setaxis("t1", "#"))
fl.next("abs raw data")
fl.image(abs(COSY_data).setaxis("t1", "#"))
COSY_data.ft("t2", shift=True)
fl.next("FT raw data")
fl.image(COSY_data.setaxis("t1", "#"))
fl.next("FT abs raw data")
fl.image(abs(COSY_data).setaxis("t1", "#"))
fl.show()
# }}}


from turtle import Turtle as T,Screen as S
from random import randint
import turtle
tim=T()
turtle.colormode(255)
tim.speed("fastest")
def get_colors():
    r=randint(0,256)
    g=randint(0,256)
    b=randint(0,256)
    tup=(r,g,b)
    return tup

def create_circles(value):
    for i in range(int(360/value)):
        tim.circle(100)
        tim.color(get_colors())
        tim.setheading(tim.heading()+value)

create_circles(5)
myscreen=S()
myscreen.exitonclick()


import tensorflow as tf
from tensorflow.contrib import rnn
import numpy as np
import time
import esposallesData

class SeqLearn():
    def __init__(self, n_classes, datasets):
        self.trainImg, self.seqLen_train, self.trainLabel, self.validationImg, self.seqLen_validation, self.validationLabel,  self.testImg, self.seqLen_test, self.testLabel = datasets
        self.n_examples = len(self.trainImg)
        self.n_examples_t = len(self.validationImg)
        self.n_features = esposallesData.IMG_HEIGHT
        if esposallesData.TEXTLINE:
            self.batch_size = 8
        else:
            self.batch_size = 64
        self.n_classes = n_classes
        self.n_hidden = 100
        self.n_layers = 1
        self.learning_rate = 1e-3
        self.n_epochs = 800
        self.n_batches_per_epoch = int(self.n_examples/self.batch_size)
        self.n_batches_per_epoch_t = int(self.n_examples_t/self.batch_size)
        self.summary = tf.Summary()
        self.summary_writer = tf.summary.FileWriter('ler_epoch_tensorboard')
        self.model()
        self.saver = tf.train.Saver()

    def sparse_tuple_from(self, sequences, dtype=np.int32):
        # Create a sparse representention of x.
        # Args:
        # sequences: a list of lists of type dtype where each element is a sequence
        # Returns:
        # A tuple with (indices, values, shape)
        indices = []
        values = []
        for n, seq in enumerate(sequences):
            indices.extend(zip([n]*len(seq), range(len(seq))))
            values.extend(seq)
        indices = np.asarray(indices, dtype=np.int64)
        values = np.asarray(values, dtype=dtype)
        shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1]+1], dtype=np.int64)
        return indices, values, shape

    def model(self):
        self.x = tf.placeholder(tf.float32, [None, self.n_features, None]) # (batch_size, n_features, time_steps)
        self.y = tf.sparse_placeholder(tf.int32)
        self.seqLen = tf.placeholder(tf.int32, [None])

        # <CNN>
        batch_s = tf.shape(self.x)[0]
        conv = tf.reshape(self.x, shape=[batch_s, self.n_features, -1, 1])
        w_conv = tf.Variable(tf.random_normal([3, 3, 1, 32])) # 3,3 better
        b_conv = tf.Variable(tf.constant(0., shape=[32]))
        conv = tf.nn.conv2d(conv, w_conv, strides=[1, 1, 1, 1], padding='SAME')
        conv = tf.nn.bias_add(conv, b_conv)
        conv = tf.nn.relu(conv)
        conv = tf.nn.max_pool(conv, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # (batch_s, n_features/2, time_s/2, 32)

        w_conv2 = tf.Variable(tf.random_normal([3, 3, 32, 64])) # 3,3 better
        b_conv2 = tf.Variable(tf.constant(0., shape=[64]))
        conv2 = tf.nn.conv2d(conv, w_conv2, strides=[1, 1, 1, 1], padding='SAME')
        conv2 = tf.nn.bias_add(conv2, b_conv2)
        conv2 = tf.nn.relu(conv2)
        conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # (batch_s, n_features/4, time_s/4, 64)

        w_conv3 = tf.Variable(tf.random_normal([3, 3, 64, 128])) # 3,3 better
        b_conv3 = tf.Variable(tf.constant(0., shape=[128]))
        conv3 = tf.nn.conv2d(conv2, w_conv3, strides=[1, 1, 1, 1], padding='SAME')
        conv3 = tf.nn.bias_add(conv3, b_conv3)
        conv3 = tf.nn.relu(conv3)
        #conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # (batch_s, n_features/8, time_s/8, 128)

        xx = tf.transpose(conv3, (2, 0, 1, 3)) # (time/4, batch, features/4, channels==128)
        xx = tf.reshape(xx, [-1, batch_s, int(self.n_features*128/4)]) # (time/4, batch, features/4 * 128)
        # </CNN>

        lstm_fw_cell = rnn.BasicLSTMCell(self.n_hidden)
        lstm_bw_cell = rnn.BasicLSTMCell(self.n_hidden)
        outputs, states = tf.nn.bidirectional_dynamic_rnn(lstm_fw_cell, lstm_bw_cell, xx, self.seqLen, dtype=tf.float32, time_major=True)
        outputs = tf.concat(outputs, 2) # (time_step_new, batch, features_new*2)

        outputs = tf.reshape(outputs, [-1, self.n_hidden*2])
        weight2 = tf.Variable(tf.random_normal([self.n_hidden*2, self.n_classes+1]))
        bias2 = tf.Variable(tf.constant(0., shape=[self.n_classes+1]))
        pred = tf.matmul(outputs, weight2) + bias2
        self.pred = tf.reshape(pred, [-1, batch_s, self.n_classes+1])

        loss = tf.nn.ctc_loss(self.y, self.pred, self.seqLen)
        self.cost = tf.reduce_mean(loss)
        #self.loss_summary = tf.summary.scalar('loss', self.cost) ###
        #self.optimizer = tf.train.MomentumOptimizer(self.learning_rate, 0.9).minimize(self.cost)
        self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.cost)
        self.decoded, log_prob = tf.nn.ctc_greedy_decoder(self.pred, self.seqLen)
        self.decoded_long, log_prob = tf.nn.ctc_greedy_decoder(self.pred, self.seqLen, merge_repeated=False)
        self.mistake_num = tf.edit_distance(tf.cast(self.decoded[0], tf.int32), self.y, normalize=False)
        #self.error_rate_summary = tf.summary.scalar('error rate', self.label_error_rate) ###
        #self.merged_summary = tf.summary.merge([self.loss_summary, self.error_rate_summary]) ###

    def train(self, test_flag=True):
        with tf.Session() as sess:
            tf.global_variables_initializer().run()
            #self.saver.restore(sess, 'models/model_textline.ckpt-763')
            #print('@@@@Model restored@@@@')
            for epoch in range(self.n_epochs+1):
                train_cost = mistake_num = y_label_len = 0
                start = time.time()
                for batch in range(self.n_batches_per_epoch):
                    batch_x = np.array(self.trainImg[batch*self.batch_size: (batch+1)*self.batch_size])
                    batch_train_seqLen = self.seqLen_train[batch*self.batch_size: (batch+1)*self.batch_size]
                    batch_y = self.trainLabel[batch*self.batch_size: (batch+1)*self.batch_size]
                    label_len = sum([len(i) for i in batch_y])
                    batch_y = self.sparse_tuple_from(batch_y)
                    feed = {self.x: batch_x, self.y: batch_y, self.seqLen: batch_train_seqLen}
                    batch_cost, _, prediction = sess.run([self.cost, self.optimizer, self.pred], feed_dict=feed)
                    train_cost += batch_cost * self.batch_size
                    mistake_num += sess.run(self.mistake_num, feed_dict=feed).sum()
                    y_label_len += label_len
                train_cost /= self.n_examples
                train_cer = mistake_num / y_label_len
                self.summary.value.add(tag='train_cer', simple_value=train_cer)
                print('epoch {}/{}, train_cost={:.3f}, train_cer={:.3f}, time={:.3f}'.format(epoch, self.n_epochs, train_cost, train_cer, time.time()-start))
                if esposallesData.TEXTLINE:
                    save_path = self.saver.save(sess, 'models/model_textline.ckpt', global_step=epoch)
                else:
                    save_path = self.saver.save(sess, 'models/model_word.ckpt', global_step=epoch)
                print('Model saved in file:', save_path)

                with open('train_cer.log', 'a') as f:
                    f.write(str(train_cer))
                    f.write(' ')

                if test_flag:
                    mistake_num_t = y_label_len_t = 0
                    start_t = time.time()
                    for bat in range(self.n_batches_per_epoch_t):
                        batch_x_t = np.array(self.validationImg[bat*self.batch_size: (bat+1)*self.batch_size])
                        batch_validation_seqLen = self.seqLen_validation[bat*self.batch_size: (bat+1)*self.batch_size]
                        batch_y_t = self.validationLabel[bat*self.batch_size: (bat+1)*self.batch_size]
                        label_len_t = sum([len(i) for i in batch_y_t])
                        batch_y_t = self.sparse_tuple_from(batch_y_t)
                        feed_t = {self.x: batch_x_t, self.y: batch_y_t, self.seqLen: batch_validation_seqLen}
                        mistake_num_t += sess.run(self.mistake_num, feed_dict=feed_t).sum()
                        y_label_len_t += label_len_t
                    test_cer = mistake_num_t / y_label_len_t
                    self.summary.value.add(tag='test_cer', simple_value=test_cer)
                    print('###TEST### test_cer={:.3f}, time={:.3f}'.format(test_cer, time.time()-start_t))
                    with open('test_cer.log', 'a') as f:
                        f.write(str(test_cer))
                        f.write(' ')

                self.summary_writer.add_summary(self.summary, epoch)

def proper_seq_len(seqLen, timeRatio):
    return [int(l/timeRatio) for l in seqLen]

if __name__ == '__main__':
    # labelNum, (trainImg, seqLen_train, trainLabel), (validationImg, seqLen_validation, validationLabel), (testImg, seqLen_test, testLabel) = esposallesData.getData(1280, 10, 4)
    labelNum, (trainImg, seqLen_train, trainLabel), (validationImg, seqLen_validation, validationLabel), (testImg, seqLen_test, testLabel) = esposallesData.getData(None, None, None)
    seqLen_train = proper_seq_len(seqLen_train, 4)
    seqLen_validation = proper_seq_len(seqLen_validation, 4)
    seqLen_test = proper_seq_len(seqLen_test, 4)
    model = SeqLearn(labelNum, [trainImg, seqLen_train, trainLabel, validationImg, seqLen_validation, validationLabel, testImg, seqLen_test, testLabel])
    model.train()


import os
import glob
import importlib, importlib.util
import logging

default_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "default")
loaded = {}

def dummy_callback():
    pass

def on(event_name, *args, **kwargs):
    global loaded
    cb_name = 'on_%s' % event_name
    for plugin_name, plugin in loaded.items():
        if cb_name in plugin.__dict__:
            # print("calling %s %s(%s)" %(cb_name, args, kwargs))
            try:
                plugin.__dict__[cb_name](*args, **kwargs)
            except Exception as e:
                logging.error("error while running %s.%s : %s" % (plugin_name, cb_name, e))

def load_from_file(filename):
    plugin_name = os.path.basename(filename.replace(".py", ""))
    spec = importlib.util.spec_from_file_location(plugin_name, filename)
    instance = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(instance)
    return plugin_name, instance

def load_from_path(path, enabled=()):
    global loaded
    for filename in glob.glob(os.path.join(path, "*.py")):
        name, plugin = load_from_file(filename)
        if name in loaded:
            raise Exception("plugin %s already loaded from %s" % (name, plugin.__file__))
        elif name not in enabled:
            # print("plugin %s is not enabled" % name)
            pass
        else:
            loaded[name] = plugin

    return loaded

def load(config):
    enabled = [name for name, options in config['main']['plugins'].items() if 'enabled' in options and options['enabled']]
    custom_path = config['main']['custom_plugins'] if 'custom_plugins' in config['main'] else None
    # load default plugins
    loaded = load_from_path(default_path, enabled=enabled)
    # set the options
    for name, plugin in loaded.items():
        plugin.__dict__['OPTIONS'] = config['main']['plugins'][name]
    # load custom ones
    if custom_path is not None:
        loaded = load_from_path(custom_path, enabled=enabled)
        # set the options
        for name, plugin in loaded.items():
            plugin.__dict__['OPTIONS'] = config['main']['plugins'][name]

    on('loaded')


import requests
if __name__ == '__main__':
    header = {
        "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34"
    }

    url = 'https://www.sogou.com/web'
    search_word = input('enter word: ')
    param = {
        'query': search_word
    }

    response = requests.get(url=url,params=param,headers=header)
    print(response.text)
    file_name = search_word+'.html'
    print(file_name)
    with open(file_name,'w',encoding='utf-8') as f:
        f.write(response.text)

    print(file_name,'game over')


import torch
from transformers import BertTokenizer, BertForMaskedLM, BertModel, BertConfig
from torch.utils.data import Dataset, DataLoader
from torch.nn.utils.rnn import pad_sequence
import torch.distributed as dist
from sklearn.model_selection import train_test_split
import tqdm
import json
import os

device = "cuda" if torch.cuda.is_available() else "cpu"
model_name = "bert-base-chinese"
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForMaskedLM.from_pretrained(model_name)
config = BertConfig.from_pretrained(model_name)
if torch.cuda.device_count() > 1:
    dist.init_process_group(backend='nccl')
    model = torch.nn.DataParallel(model)
model = model.to(device)

with open("../Raw_data/new_chinese_poems_cws.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()

poems_data = [{"text": line.strip()} for line in lines]
poems_train, poems_test = train_test_split(poems_data, test_size=0.2, random_state=42)

class PoemsDataset(Dataset):
    def __init__(self, data,limit=None):
        self.data = data[:limit] if limit is not None else data
        # self.data = data

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

    def __getitem__(self, index):
        inputs = tokenizer.encode_plus(
            self.data[index]["text"],
            add_special_tokens=True,
            return_attention_mask=True,
            return_tensors="pt",
            max_length=128,
            truncation=True,
        )

        # Apply whole word masking
        inputs_whole_word = tokenizer.prepare_for_model(
            inputs["input_ids"].squeeze().tolist(),
            max_length=128,
            padding="max_length",
            truncation=True,
            return_attention_mask=True,
            return_tensors="pt",
            whole_word_masking=True,
        )
        input_ids = inputs_whole_word["input_ids"].squeeze()
        attention_mask = inputs_whole_word["attention_mask"].squeeze()
        masked_indices = torch.where(input_ids == tokenizer.mask_token_id)
        labels = input_ids.clone()
        labels[masked_indices] = -100  # ignore loss for masked tokens
        return {
            "input_ids": input_ids.to(device),
            "attention_mask": attention_mask.to(device),
            "labels": labels.to(device),
            "masked_indices": masked_indices[0].to(device),
        }

def collate_fn(batch):
    input_ids = pad_sequence([data["input_ids"] for data in batch], batch_first=True, padding_value=0)
    attention_mask = pad_sequence([data["attention_mask"] for data in batch], batch_first=True, padding_value=0)
    labels = pad_sequence([data["labels"] for data in batch], batch_first=True, padding_value=-100)
    masked_indices = [data["masked_indices"] for data in batch]
    return {
        "input_ids": input_ids,
        "attention_mask": attention_mask,
        "labels": labels,
        "masked_indices": masked_indices,
    }

train_dataset = PoemsDataset(poems_train)
eval_dataset = PoemsDataset(poems_test)

train_loader = DataLoader(train_dataset, batch_size=128, collate_fn=collate_fn)
eval_loader = DataLoader(eval_dataset, batch_size=128, collate_fn=collate_fn)

# print("Number of samples in the train dataset:", len(train_loader))
# print("Number of samples in the eval dataset:", len(eval_loader))
#
# print("First 5 samples from train dataset:")
# for i in range(5):
#     sample = train_dataset[i]
#     text = tokenizer.decode(sample["input_ids"].tolist(), skip_special_tokens=True)
#     masked_token = tokenizer.decode(sample["input_ids"][sample["masked_indices"]].tolist())
#     print(f"Text: {sample}")
#     print(f"Text: {text}")
#     print(f"Masked token: {masked_token}")
#     print(f"Labels: {sample['labels'].tolist()}")
#     print("=" * 50)

mlm_loss = torch.nn.CrossEntropyLoss(ignore_index=-100)
optimizer = torch.optim.Adam(model.parameters(), lr=2e-5)
epoch_num = 50
for epoch in range(epoch_num):
    model.train()
    total_loss = 0
    for batch in tqdm.tqdm(train_loader):
        optimizer.zero_grad()
        outputs = model(
            input_ids=batch["input_ids"],
            attention_mask=batch["attention_mask"],
            labels=batch["labels"],
        )
        loss = mlm_loss(outputs.logits.view(-1, tokenizer.vocab_size), batch["labels"].view(-1))
        loss.backward()
        optimizer.step()
        total_loss += loss.item()
    avg_train_loss = total_loss / len(train_loader)
    print(f"Epoch {epoch + 1} - Average training loss: {avg_train_loss:.4f}")
    # evaluation loop
    model.eval()
    total_eval_loss = 0
    with torch.no_grad():
        for batch in tqdm.tqdm(eval_loader):
            outputs = model(
                input_ids=batch["input_ids"],
                attention_mask=batch["attention_mask"],
                labels=batch["labels"],
            )
            loss = mlm_loss(outputs.logits.view(-1, tokenizer.vocab_size), batch["labels"].view(-1))
            total_eval_loss += loss.item()

    avg_eval_loss = total_eval_loss / len(eval_loader)
    print(f"Epoch {epoch + 1} - Average evaluation loss: {avg_eval_loss:.4f}")

    # Save the model and optimizer
    folder_path = "../checkpoints/model_round2/"
    if (epoch + 1) % 10 == 0:
        if isinstance(model, torch.nn.DataParallel):
            model.module.save_pretrained(folder_path)
        else:
            model.save_pretrained(folder_path)
        tokenizer.save_pretrained(folder_path)

    # Save the logs
    logs = {"epoch": epoch + 1, "avg_train_loss": avg_train_loss, "avg_eval_loss": avg_eval_loss}
    logs_path = f"{folder_path}logs_{epoch + 1}.json"
    with open(logs_path, "w") as f:
        json.dump(logs, f)

# CUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch wwm_pretrain_torch.py
# CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun wwm_pretrain_torch.py


"""
"""

# Write your code here
num_tests = int(input())
for _ in range(num_tests):
    n, k = map(int, input().strip().split())
    if k == 0:
        print(*list(range(1, n+1)))
    elif n == k:
        print(-1)
    else:
        ans = [i for i in range(k+1, n+1)]
        ans.extend(list(range(1, k+1)))
        print(*ans)


# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys

mod = 10**9+7
sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

N,M,K = map(int,input().split())

def mCn(m,n):
    return math.factorial(m)//(math.factorial(n)*math.factorial(m-n)) % mod

def cmb(n, r, mod):
    if ( r<0 or r>n ):
        return 0
    r = min(r, n-r)
    return g1[n] * g2[r] * g2[n-r] % mod

N1 = 10**6
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル计算用テーブル

for i in range( 2, N1 + 1 ):
    g1.append( ( g1[-1] * i ) % mod )
    inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
    g2.append( (g2[-1] * inverse[-1]) % mod )

ans = 0
for i in range(1,M):
    ans += (M-i)*N**2*i*(cmb(M*N-2,K-2,mod))
    if ans > mod:
        ans = ans % mod

for i in range(1,N):
    ans += (N-i)*M**2*i*(cmb(M*N-2,K-2,mod))
    if ans > mod:
        ans = ans % mod

print(ans)


#num = float(input("enter a price: "))
#print("Total price: ", round(num+0.35*num), "\n Sales Tax: ", 0.35*num)

import random
winnum = random.randint(0,99)
guess = int(input("Enter your lottery pick(2digits): "))
winnumD1 = winnum//10
winnumD2 = winnum%10
guessD1 = guess//10
guessD2 = guess%10
while(guess != winnum or guess != -1):

	if guess == winnum:
		print('Exact Match, you win $1000000')
		break

	elif (guessD2 == winnumD1) and (guessD1 == winnumD2):
		print('Match all digits, you win $700000')
		break
	elif (guessD1 == winnumD1 or guessD1 == winnumD2 or guessD2 == winnumD1
		or guessD2 == winnumD2):
	    print('Match one digit, you win $3000')
	    break
	elif guess < winnum:
		print("Please guess a higher number: ")
		guess = int(input("Enter your lottery pick(2digits): "))
	elif guess > winnum:
		print("Please guess a lower number: ")
		guess = int(input("Enter your lottery pick(2digits): "))

	guessD1 = guess//10
	guessD2 = guess%10
print("Congrats on the correct num")


#!/usr/bin/python2.7

#######################################################################################################################
# slack_plugin.py
# Description: Slack operator to send message on a channel
#######################################################################################################################

from airflow.exceptions import AirflowException
from airflow.models import BaseOperator

import logging
from airflow.utils.decorators import apply_defaults
from airflow.plugins_manager import AirflowPlugin
from airflow.configuration import conf
import requests
import json

class SlackOperator(BaseOperator):
    template_fields = tuple()
    ui_color = '#ededef'

    @apply_defaults
    def __init__(self,
                 channel=None,
                 message=None,
                 *args, **kwargs):
        super(SlackOperator, self).__init__(*args, **kwargs)
        if channel is None or message is None:
            if channel is None:
                logging.error('Need to provide slack channel')
            else:
                logging.error('Need to provide message')
            raise AirflowException("Missing channel/message for Slack Operator")

        self.channel = "#" + channel
        self.message = message

    def get_slack_url(self):
        return conf.get('slack', 'url')

    def get_cluster_stamp(self):
        return "[from airflow-{cluster}] ".format(cluster=conf.get('core', 'cluster'))

    def send_slack_message(self, webhook_url, slack_data):
        response = requests.post(
            webhook_url, data=json.dumps(slack_data),
            headers={'Content-Type': 'application/json'}
        )
        if response.status_code != 200:
            raise AirflowException(
                'Request to slack returned an error %s, the response is:\n%s'
                % (response.status_code, response.text)
            )

    def execute(self, context):
        webhook_url = self.get_slack_url()
        cluster_stamp = self.get_cluster_stamp()
        message = str(cluster_stamp) + self.message
        slack_data = {'text': message, 'channel': self.channel}
        logging.info('sending slack message {message} to {channel}'.format(message=self.message, channel=self.channel))
        self.send_slack_message(webhook_url, slack_data)
        logging.info('message sent successfully')

class SlackPlugin(AirflowPlugin):
    name = "slack_plugin"
    operators = [SlackOperator]


import numpy as np
import obspy

from pyadjoint.config import ADJSRC_TYPES

class AdjointSource:
    """
    Adjoint Source class to hold calculated adjoint sources
    """
    def __init__(self, adjsrc_type, misfit, dt, min_period, max_period,
                 component, adjoint_source=None, windows=None,
                 network=None, station=None, location=None, starttime=None,
                 window_stats=None):
        """
        Class representing an already calculated adjoint source.

        :param adjsrc_type: The type of adjoint source.
        :type adjsrc_type:  str
        :param misfit: The misfit value.
        :type misfit: float
        :param dt: The sampling rate of the adjoint source.
        :type dt: float
        :param min_period: The minimum period of the spectral content
            of the data.
        :type min_period: float
        :param max_period: The maximum period of the spectral content
            of the data.
        :type max_period: float
        :param component: The adjoint source component, usually ``"Z"``,
            ``"N"``, ``"E"``, ``"R"``, or ``"T"``.
        :type component: str
        :param adjoint_source: The actual adjoint source.
        :type adjoint_source: :class:`numpy.ndarray`
        :type windows: list of dict
        :param windows: measurement windows used to generate the adjoint
            source, each carrying information about the misfit of the window
        :param network: The network code of the station.
        :type network: str
        :param station: The station code of the station.
        :type station: str
        :param location: The location code of the station.
        :type location: str
        :param starttime: starttime of adjoint source
        :type starttime: obspy.UTCDateTime
        """
        if adjsrc_type not in ADJSRC_TYPES:
            raise ValueError(f"Unknown adjoint source type {adjsrc_type}")

        self.adjsrc_type = adjsrc_type
        self.adj_src_name = adjsrc_type
        self.misfit = misfit
        self.dt = dt
        self.min_period = min_period
        self.max_period = max_period
        self.component = component
        self.network = network
        self.station = station
        self.location = location
        self.starttime = starttime
        self.adjoint_source = adjoint_source
        self.windows = windows
        self.window_stats = window_stats

    def __str__(self):
        if self.network and self.station:
            station = f" at station {self.network}.{self.station}"
        else:
            station = ""

        if self.adjoint_source is not None:
            adj_src_status = \
                f"available with {len(self.adjoint_source)} samples"
        else:
            adj_src_status = "has not been calculated"

        if self.windows is not None:
            windows_status = f"generated with {len(self.windows)} windows"
        else:
            windows_status = "has no windows"

        return (f"'{self.adj_src_name}' Adjoint Source for "
                f"channel {self.component}{station}\n"
                f"\tmisfit: {self.misfit:.4g}\n"
                f"\tadjoint_source: {adj_src_status}\n"
                f"\twindows: {windows_status}"
                )

    def write(self, filename, format, **kwargs):
        """
        Write the adjoint source to a file.

        :param filename: Determines where the adjoint source is saved.
        :type filename: str, open file, or file-like object
        :param format: The format of the adjoint source. Currently available
            are: ``"SPECFEM"``
        :type format: str

        .. rubric:: SPECFEM

        SPECFEM requires one additional parameter: the temporal offset of the
        first sample in seconds. The following example sets the time of the
        first sample in the adjoint source to ``-10``.

        >>> adj_src.write("NET.STA.CHAN.adj", format="SPECFEM",
        ...               time_offset=-10)  # doctest: +SKIP

        .. rubric ASDF

        Adjoint sources can be written directly to an ASDFDataSet if provided.
        Optional ``coordinates`` parameter specifies the location of the
        station that generated the adjoint source

        >>> adj_src.write(ds, format="ASDF", time_offset=-10,
        ...               coordinates={'latitude':19.2,
        ...                            'longitude':13.4,
        ...                            'elevation_in_m':2.0})
        """
        if self.adjoint_source is None:
            raise ValueError("Can only write adjoint sources if the adjoint "
                             "source has been calculated.")

        format = format.upper()
        available_formats = ["SPECFEM", "ASDF"]
        if format not in available_formats:
            raise ValueError("format '%s' not known. Available formats: %s" %
                             (format, ", ".join(available_formats)))

        if format == "SPECFEM":
            self._write_specfem(filename, **kwargs)
        elif format == "ASDF":
            self._write

    def _write_specfem(self, filename, time_offset):
        """
        Write the adjoint source for SPECFEM.

        :param filename: name of file to write adjoint source to
        :type filename: str
        :param time_offset: time offset of the first time point in array
        :type time_offset: float
        """
        l = len(self.adjoint_source)

        to_write = np.empty((l, 2))

        to_write[:, 0] = np.linspace(0, (l - 1) * self.dt, l)
        to_write[:, 0] += time_offset
        # SPECFEM expects non-time reversed adjoint sources.
        to_write[:, 1] = self.adjoint_source[::-1]

        np.savetxt(filename, to_write)

    def _write_asdf(self, ds, time_offset, coordinates=None, **kwargs):
        """
        Writes the adjoint source to an ASDF file.

        :param ds: The ASDF data structure read in using pyasdf.
        :type ds: str
        :param time_offset: The temporal offset of the first sample in seconds.
            This is required if using the adjoint source as input to SPECFEM.
        :type time_offset: float
        :param coordinates: If given, the coordinates of the adjoint source.
            The 'latitude', 'longitude', and 'elevation_in_m' of the adjoint
            source must be defined.
        :type coordinates: list
        """
        # Import here to not have a global dependency on pyasdf
        from pyasdf.exceptions import NoStationXMLForStation  # NOQA

        # Convert the adjoint source to SPECFEM format
        l = len(self.adjoint_source)
        specfem_adj_source = np.empty((l, 2))
        specfem_adj_source[:, 0] = np.linspace(0, (l - 1) * self.dt, l)
        specfem_adj_source[:, 0] += time_offset
        specfem_adj_source[:, 1] = self.adjoint_source[::-1]

        tag = "%s_%s_%s" % (self.network, self.station, self.component)
        min_period = self.min_period
        max_period = self.max_period
        component = self.component
        station_id = "%s.%s" % (self.network, self.station)

        if coordinates:
            # If given, all three coordinates must be present
            if {"latitude", "longitude", "elevation_in_m"}.difference(
                    set(coordinates.keys())):
                raise ValueError(
                    "'latitude', 'longitude', and 'elevation_in_m'"
                    " must be given")
        else:
            try:
                coordinates = ds.waveforms[
                    "%s.%s" % (self.network, self.station)].coordinates
            except NoStationXMLForStation:
                raise ValueError("Coordinates must either be given "
                                 "directly or already be part of the "
                                 "ASDF file")

        # Safeguard against funny types in the coordinates dictionary
        latitude = float(coordinates["latitude"])
        longitude = float(coordinates["longitude"])
        elevation_in_m = float(coordinates["elevation_in_m"])

        parameters = {"dt": self.dt, "misfit_value": self.misfit,
                      "adjoint_source_type": self.adjsrc_type,
                      "min_period": min_period, "max_period": max_period,
                      "latitude": latitude, "longitude": longitude,
                      "elevation_in_m": elevation_in_m,
                      "station_id": station_id, "component": component,
                      "units": "m"}

        # Use pyasdf to add auxiliary data to the ASDF file
        ds.add_auxiliary_data(data=specfem_adj_source,
                              data_type="AdjointSource", path=tag,
                              parameters=parameters)