import discord
from discord.ext import commands, tasks
from discord.utils import get
from itertools import cycle
import asyncio
import json
import pyrebase
from datetime import datetime

with open('settings.json', 'r') as cf:
    config = json.loads(cf.read())
    token = config['token']
    prefix = config['prefix']
    pyrecfg = config['pyrebase']
intents = discord.Intents().all()
client = commands.Bot(command_prefix = prefix, case_insensitive = True, help_command=None, intents=intents)

status = cycle(['Dreamcup League','Campeonatos de CS:GO','Developed by mtz#9765'])

@tasks.loop(seconds=10)
async def change_status():
    await client.change_presence(activity=discord.Game(next(status)))

@client.event
async def on_ready():
    print('Bot está online!\n')
    change_status.start()

# EVENTOS EVENTOS EVENTOS EVENTOS EVENTOS EVENTOS EVENTOS EVENTOS EVENTOS EVENTOS

@client.event
async def on_member_join(member):
    cargo = get(member.guild.roles, id=717810679192748072)
    await member.add_roles(cargo)
    log = client.get_channel(717811612311879732)
    await log.send(f'**{member.mention} entrou no servidor**\nConta criada em: {member.created_at}')

@client.event
async def on_member_remove(member):
    log = client.get_channel(717811612311879732)
    await log.send(f'**{member.mention} saiu do servidor.**')

@client.event
async def on_message_delete(message):
    log = client.get_channel(886375007725436969)
    await log.send(f'**<:alerta:806352926187978793> Mensagem deletada <:alerta:806352926187978793>**\nAutor: {message.author.mention} - Canal: {message.channel.mention}\nMensagem:\n`{message.content}`')

# COMANDOS COMANDOS COMANDOS COMANDOS COMANDOS COMANDOS COMANDOS COMANDOS COMANDOS

@client.command(aliases=['info'])
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def infos(ctx, membro: discord.Member):
    await open_account(membro)
    embed = discord.Embed(color=0xff0000)
    embed.set_author(name=f'Informações de {membro}', icon_url=membro.avatar_url)
    embed.add_field(name='Nome:', value=membro.name, inline=True)
    embed.add_field(name='Discriminador:', value=membro.discriminator, inline=True)
    embed.add_field(name='ID:', value=membro.id, inline=True)
    embed.add_field(name='Conta criada em:', value=membro.created_at.strftime("%d/%m/%Y - %H:%M"), inline=True)
    embed.add_field(name='Entrou em:', value=membro.joined_at.strftime("%d/%m/%Y - %H:%M"), inline=True)
    embed.add_field(name='Banco de Dados:', value=f'Pontos: {db.child(str(membro.id)).child("Pontos").get().val()} / Wins: {db.child(str(membro.id)).child("Wins").get().val()}', inline=False)
    embed.set_thumbnail(url=membro.avatar_url)
    embed.set_footer(text=f'Solicitado por: {membro.id} - DreamCup League')
    embed.timestamp = datetime.utcnow()
    await ctx.send(embed=embed)

@infos.error
async def infos_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f'{ctx.author.mention} **ERRO!** É necessário mencionar ou inserir o ID do membro para pegar suas informações.', delete_after=8.0)
        await ctx.message.delete()

@client.command()
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def mandarip(ctx, time1: discord.Role, time2: discord.Role, *, ipgotv: str):
    chatgeral = client.get_channel(877326085535178762)
    await chatgeral.send(f'**JOGO COMEÇANDO!**\n{time1.name} **X** {time2.name}\nIP GOTV: `{ipgotv}`')
    await ctx.message.delete()

@mandarip.error
async def mandarip_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f'{ctx.author.mention} **ERRO!** É necessário citar o 1º time, o 2º time, e inserir o ip do gotv.', delete_after=8.0)
        await ctx.message.delete()

@client.command(aliases=['register'])
@commands.guild_only()
@commands.cooldown(1,300, commands.BucketType.user)
async def registrar(ctx):
    if ctx.channel.id == 891547982950965258:
        perms = {
            ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
            ctx.author: discord.PermissionOverwrite(read_messages=True, send_messages=True)
        }
        canal = await ctx.guild.create_text_channel(f'registro-time-{ctx.author.discriminator}', category=client.get_channel(id=883201218808266772), overwrites=perms)
        await ctx.message.delete()
        await ctx.send(f'{ctx.author.mention}, canal criado com sucesso! {canal.mention}! Lá estarão as próximas instruções!', delete_after=5.0)
        await canal.send(ctx.author.mention, delete_after=0.2)
        embed = discord.Embed(title='Registro de Times', description=f'**Olá {ctx.author.mention}!**\n\nCaso deseja **registrar** o seu time no campeonato **siga os passos abaixo**:\n\n'
        '```\n1º - Confirme que todos os membros do time estejam neste discord.\n2º - Envie o nome do time aqui\n3º - Envie o discord de todos os membros do time, incluindo reservas e coach se tiver.\n```'
        '\n\n**Após fazer isso aguarde que em breve um staff irá verificar e fazer a criação do time se tudo estiver correto.**', color=0xff0000)
        embed.set_footer(text='DreamCup League')
        embed.timestamp = datetime.utcnow()
        await canal.send(embed=embed)
    else:
        await ctx.reply(f'Você só pode executar este comando no canal <#891547982950965258>.', delete_after=6.0)
        ctx.command.reset_cooldown(ctx)
        await asyncio.sleep(6)
        await ctx.message.delete()

@client.command()
@commands.guild_only()
@commands.cooldown(1,120, commands.BucketType.user)
async def suporte(ctx):
    if not ctx.channel.id == 883196216605823006:
        await ctx.reply('Você só pode executar este comando dentro do <#883196216605823006>.', delete_after=8.0)
        await ctx.message.delete(delay=8.0)
        return ctx.command.reset_cooldown(ctx)
    perms = {
        ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        ctx.author: discord.PermissionOverwrite(read_messages=True, send_messages=True),
    }
    canalsup = await ctx.guild.create_text_channel(f'sup-{ctx.author.discriminator}', category = client.get_channel(id=883201218808266772), overwrites=perms)
    await ctx.message.delete()
    await ctx.send(f'{ctx.author.mention} Ticket de suporte criado! {canalsup.mention}', delete_after=3.0)
    await canalsup.send(f'{ctx.author.mention}',delete_after=0.5)
    embed = discord.Embed(title='Sistema de Tickets de Suporte', description=f'**Olá {ctx.author.mention}!\n\nDescreva sua dúvida ou seu problema abaixo\n\nEm breve um membro da staff realizará o atendimento!**', color=0xff0000)
    embed.set_footer(text='DreamCup League')
    embed.timestamp = datetime.utcnow()
    await canalsup.send(embed=embed)

@client.command()
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def finalizar(ctx):
    await ctx.message.delete()
    if ctx.channel.name.startswith('sup-'):
        msgbotmotivo = await ctx.send('Insira um motivo abaixo para finalizar este ticket!\n`Você tem 60 segundos para responder`')
        try:
            motivo = await client.wait_for('message', timeout=60, check=lambda m: m.author == ctx.author and m.channel == ctx.channel)
            await msgbotmotivo.delete()
            await motivo.delete()
        except asyncio.TimeoutError:
            await ctx.reply('**Você demorou muito para responder**', delete_after=4.0)
            await msgbotmotivo.delete()
            return
        embed = discord.Embed(title="Ticket Finalizado!",description=f"**Ticket finalizado por: {ctx.author.mention}\n\nMotivo:\n```\n{motivo.content}\n```\nO ticket será deletado em 2 minutos automaticamente.**", color=0xff0000)
        embed.set_footer(text="DreamCup League")
        embed.timestamp = datetime.utcnow()
        await ctx.send(embed=embed)
        await asyncio.sleep(120)
        await ctx.channel.delete()
    else:
        await ctx.send(f'{ctx.author.mention} Este comando só pode ser executado dentro de um ticket.', delete_after=8.0)

@client.command()
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def criartime(ctx, membro1: discord.Member, membro2: discord.Member, membro3: discord.Member, membro4: discord.Member, membro5: discord.Member, *, nometime):
    roletime = await ctx.guild.create_role(name=nometime, mentionable=True, reason=f"Cargo de time {nometime} criado.")
    roleedicao = get(ctx.guild.roles, id=888554418142855178) # id do cargo de cada edição
    await ctx.message.delete()
    perms = {
        ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        roletime: discord.PermissionOverwrite(read_messages=True, send_messages=True)}
    for player in membro1, membro2, membro3, membro4, membro5:
        await player.add_roles(roletime)
        await player.add_roles(roleedicao)
        try: # try para evitar dm bloqueada e parada no codigo
            await player.send(f'**Você foi adicionado no time:** `{nometime}`!\n**Em breve será enviada as próximas instruções do campeonato.**\n**Caso você ache que isso seja um erro contate um staff.**')
        except discord.Forbidden:
            pass
    canaltime = await ctx.guild.create_text_channel(nometime, overwrites=perms, category= client.get_channel(id=888602889994502155))
    await canaltime.send(f'**Bem vindo a Dreamcup League!\n\nO time `{nometime}` foi registrado e já está participando do campeonato!\n\nCaso haja alguma dúvida, basta enviar neste canal que iremos te responder.**')
    await ctx.send(f'<a:sucesso:883480591276851222> {ctx.author.mention} Time {roletime} criado com êxito e players registrados com sucesso!', delete_after=3.0)

@criartime.error
async def criartime_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f'{ctx.author.mention} **ERRO!** É necessário mencionar os 5 membros e inserir o nome do time. Uso correto: `!criartime <membro1> <membro2> <membro3> <membro4> <membro5> Nome do time`', delete_after=10.0)
        await ctx.message.delete()

@client.command()
@commands.guild_only()
async def infopause(ctx):
    await ctx.send(f'{ctx.author.mention}\nTodos os campeonatos contam com o sistema de pause dentro do jogo, e nós temos 2 tipos.\n\nPause tático: Para fins táticos, cada equipe tem 4 deles, sendo cada um 30 segundos, e para utiliza-lo basta iniciar a votação de pausa do próprio CS:GO.\n\nPause técnico: É usado para problemas tecnicos, sendo cada equipe com 5 minutos e para usa-lo basta digitar !pause no chat (Após isso informar o problema dentro do chat do jogo no discord).')

@client.command()
@commands.guild_only()
async def infocamp(ctx):
    await ctx.send(f'{ctx.author.mention}\nEste tipo de campeonato é totalmente gratuito, e as premiações são em um sistema de pontos, que funcionam assim:\n\nO campeonato terá um valor em pontos de premiação, o time que ganhar, terá os pontos divididos entre a sua equipe (a divisão é organizada de acordo com o dono responsável pelo time) e após isso você pode digitar !loja e verificar os produtos e fazer a troca pelos pontos por um produto real!\n\nPara verificar quantos pontos você tem digite !pontos.')

@client.command()
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def criarsala(ctx, time1: discord.Role, time2: discord.Role):
    msginicialbot = await ctx.send(f'**Envie a data limite para a partida! {ctx.author.mention}**')
    try:
        datamsg = await client.wait_for('message', timeout=15, check=lambda m: m.author == ctx.author and m.channel == ctx.channel)
        await msginicialbot.delete()
        await datamsg.delete()
    except asyncio.TimeoutError:
        await ctx.send(f'**Você demorou muito para responder** {ctx.author.mention}', delete_after=6.0)
        await msginicialbot.delete()
        return

    try:
        msglinkbot = await ctx.send(f'**Envie o link da partida {ctx.author.mention}**')
        linkmsg = await client.wait_for('message', timeout=120, check=lambda m: m.author == ctx.author and m.channel == ctx.channel)
        await msglinkbot.delete()
        await linkmsg.delete()
    except asyncio.TimeoutError:
        await ctx.send(f'**Você demorou muito para responder** {ctx.author.mention}', delete_after=6.0)
        await msglinkbot.delete()
        return

    perms = {
        ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        time1: discord.PermissionOverwrite(read_messages=True, send_messages=True),
        time2: discord.PermissionOverwrite(read_messages=True, send_messages=True)}
    canaljogo = await ctx.guild.create_text_channel(f'jogo-{time1}-x-{time2}', overwrites=perms, category= client.get_channel(id=884208349200125992))
    await canaljogo.send(f'**Bem vindo! {time1.mention} {time2.mention}**\n\nEste canal foi criado para vocês marcarem a data do jogo.\n\nConversem e arrumem o melhor horário para jogar, a data limite é: **{datamsg.content}**\n\nAo decidirem um horário, marquem um CEO para mudar o horário da partida no link.\n\n**Link da partida** (necessário os 2 times se inscreverem): {linkmsg.content}\nLembrem de se inscrever com antecedência, pois 5 minutos antes do horario marcado as inscrições fecham')
    await ctx.send(f'Sala criada com sucesso. {canaljogo.mention}, com permissão para `{time1}` e `{time2}`.', delete_after=5.0)

@criarsala.error
async def criarsala_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f'{ctx.author.mention} ERRO! Uso correto: `!criarsala <time1> <time2>`', delete_after=10.0)
        await ctx.message.delete()

@client.command()
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def criartime2(ctx, membro1: discord.Member, membro2: discord.Member, *, nometime):
    roletime = await ctx.guild.create_role(name=nometime, mentionable=True, reason=f'Cargo do time {nometime} criado!')
    await ctx.message.delete()
    perms = {
        ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False),
        roletime: discord.PermissionOverwrite(read_messages=True, send_messages=True)}
    for p in membro1, membro2:
        await p.add_roles(roletime)
        await ctx.send(f'Cargo atribuido a {p.mention} com sucesso! <a:sucesso:883480591276851222>', delete_after=2.0)
        try:
            await p.send(f'<a:sucesso:883480591276851222> **Você foi adicionado no time:** `{nometime}` **para o campeonato de Wingman (Braço direito)!**\n**<:alerta:806352926187978793> Em breve serão enviadas as próximas instruções, fique atento no servidor!**\n**Caso você ache que isso seja um erro contate um staff.**')
        except:
            await ctx.send(f'Mensagem privada não pode ser enviada para {p.mention} pelo possível motivo:\n- Privado bloqueado', delete_after=7.0)
    canaltime = await ctx.guild.create_text_channel(nometime, overwrites=perms, category=client.get_channel(id=888602889994502155))
    await canaltime.send(f'**Bem vindo a Dreamcup League!\n\nO time `{nometime}` foi registrado e já está participando do campeonato de braço-direito!\n\nCaso haja alguma dúvida, basta enviar neste canal que iremos te responder.**')
    await ctx.send(f'<a:sucesso:883480591276851222> {ctx.author.mention} Time {roletime} criado com êxito e players registrados com sucesso!', delete_after=3.5)

@client.command()
@commands.guild_only()
@commands.cooldown(1,120, commands.BucketType.user)
async def help(ctx):
    embed = discord.Embed(title="Lista de Comandos", description="**!suporte**: Faz um ticket de suporte\n**!infocamp**: Mostra as informações do campeonato atual.\n**!infopause:** Mostra as informações sobre o sistema de pause.\n**!loja**: Vê os produtos disponíveis para comprar com pontos.\n**!pontos**: Mostra quantos pontos você tem.\n**!transferir**: Transfere pontos para uma pessoa.\n**!perfil**: Mostra o seu perfil com algumas informações.", color=0xff0000)
    embed.set_footer(text='Dreamcup League')
    await ctx.send(embed=embed)

# ERROS ERROS ERROS ERROS ERROS ERROS

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send('Os comandos não podem ser executados no privado. <a:negado:883480639167426560>')
    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f'{ctx.author.mention} Você executou este comando recentemente, aguarde {error.retry_after:.0f} segundos para executar novamente.', delete_after=6.0)
        await ctx.message.delete()
    if isinstance(error, commands.MissingAnyRole):
        await ctx.send(f'{ctx.author.mention} Você não tem permissão para executar este comando. <a:negado:883480639167426560>', delete_after=5.0)
        await ctx.message.delete()

# SISTEMA DE PONTOS

configbase = pyrecfg
firebase = pyrebase.initialize_app(configbase)
db = firebase.database()

@client.command(aliases=['points', 'pontos'])
@commands.guild_only()
async def dinheiro(ctx, pessoa: discord.Member=None):
    if not pessoa:
        await open_account(ctx.author)
        quantia = db.child(str(ctx.author.id)).child("Pontos").get().val()
        await ctx.send(f'{ctx.author.mention} Você possui {quantia} pontos!')
    else:
        await open_account(pessoa)
        quantia = db.child(str(pessoa.id)).child("Pontos").get().val()
        await ctx.send(f'O {pessoa.mention} possui {quantia} pontos no momento!')

@client.command()
@commands.guild_only()
@commands.cooldown(1, 60, commands.BucketType.user)
async def transferir(ctx, pessoa: discord.Member, quantia: int):
    await open_account(ctx.author)
    seumoney = db.child(str(ctx.author.id)).child("Pontos").get().val()
    if seumoney < quantia:
        await ctx.send(f'{ctx.author.mention} Você não tem pontos suficiente. Seus pontos: {seumoney}.')
    elif quantia < 1:
        await ctx.send(f'{ctx.author.mention} É necessário inserir uma quantia acima de 1.')
    elif ctx.author == pessoa:
        await ctx.send(f'{ctx.author.mention} Você não pode enviar pontos para você mesmo.')
    else:
        await open_account(pessoa)
        moneypessoa = db.child(str(pessoa.id)).child("Pontos").get().val()
        valorreceber = moneypessoa + quantia
        valor = seumoney - quantia
        db.child(str(ctx.author.id)).update({"Pontos": valor}) #quem enviou
        db.child(str(pessoa.id)).update({"Pontos": valorreceber}) #quem recebeu
        #logs + msgs
        await ctx.send(f'<a:sucesso:883480591276851222> {ctx.author.mention} Você enviou {quantia} pontos para {pessoa.mention}!')
        embed = discord.Embed(title='LOG - TRANSFERENCIA', description=f'Transferencia de pontos efetuada! <:alerta:806352926187978793>\n\nEnviador: {ctx.author.mention}\nRecebedor: {pessoa.mention}\nQuantia: {quantia}\n')
        embed.set_footer(text='Logs Dreamcup')
        embed.timestamp = datetime.utcnow()
        log = client.get_channel(717811612311879732)
        await log.send(embed=embed)
        try:
            await pessoa.send(f'**Você recebeu {quantia} pontos de {ctx.author.mention} na Dreamcup League**')
        except discord.Forbidden:
            pass

@transferir.error
async def transferir_error(ctx, error):
    if isinstance(error, commands.BadArgument):
        await ctx.send(f'{ctx.author.mention} ERRO! É necessário citar o membro, e inserir uma quantia. Exemplo: `!transferir @membro 10`', delete_after=8.0)
        await ctx.message.delete()

@client.command()
@commands.guild_only()
@commands.cooldown(1,30, commands.BucketType.user)
async def perfil(ctx, membro: discord.Member=None):
    noteam = ['Jogador', 'Capitão', 'Reserva', 'Coach', 'Silenciado', 'Server Booster', 'Campeões 1º Edição 5x5', 'Campeões 2º Edição 5x5'] # Cargos excluidos de times
    membro = ctx.author if not membro else membro
    await open_account(membro)
    pontos = db.child(str(membro.id)).child("Pontos").get().val()
    wins = db.child(str(membro.id)).child("Wins").get().val()
    cargoslist = membro.roles
    teamrole = str(cargoslist[1])
    embed = discord.Embed(color=discord.Color.gold())
    embed.set_author(name=f'Perfil de {membro}', icon_url=membro.avatar_url)
    embed.add_field(name='Pontos:', value=pontos, inline=True)
    embed.add_field(name='Campeonatos ganhos:', value=wins, inline=True)
    embed.add_field(name='Time Atual:', value='Nenhum' if teamrole in noteam else teamrole, inline=True)
    embed.add_field(name='Entrou no servidor:', value=membro.joined_at.strftime("%d/%m/%Y - %H:%M"), inline=True)
    embed.set_thumbnail(url=membro.avatar_url)
    embed.set_footer(text='DreamCup League')
    embed.timestamp = datetime.utcnow()
    await ctx.send(embed=embed)

@client.command(aliases=['givarpontos', 'givepoints'])
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def givepontos(ctx, user: discord.Member, quantia: int):
    await open_account(user)
    pontoatual = db.child(str(user.id)).child("Pontos").get().val()
    db.child(str(user.id)).update({"Pontos": quantia+pontoatual})
    await ctx.send(f'Você givou {quantia} pontos para {user.mention}!')

@client.command(aliases=['givewin'])
@commands.guild_only()
@commands.has_any_role(717807997467885598)
async def givewins(ctx, membro: discord.Member, quantia: int):
    await open_account(membro)
    winsatuais = db.child(str(membro.id)).child("Wins").get().val()
    db.child(str(membro.id)).update({"Wins": winsatuais+quantia})
    await ctx.send(f'Você givou **{quantia}** wins para o **{membro.mention}** com sucesso!')

@client.command()
@commands.guild_only()
@commands.cooldown(1,90, commands.BucketType.user)
async def loja(ctx):
    embed = discord.Embed(title="Loja Dreamcup", description="Ainda estamos adicionando mais produtos, qualquer sugestão contate um CEO.\n\nGiftcard Steam R$ 20,00: 4.500 pontos\nGiftcard Steam R$ 50,00: 10.500 pontos\nPIX R$ 25,00: 5.000 pontos\nPIX R$ 50,00: 10.000 pontos\n\nPara adquirir um produto, faça um ticket em <#883196216605823006>.", color=0xff0000)
    embed.set_footer(text='Para ver quantos pontos você tem use !pontos.')
    await ctx.send(embed=embed)

# criar conta no banco de dados
async def open_account(user):
    if str(user.id) in db.child().get().val():
        return False
    db.child(str(user.id)).update({"Pontos": 0})
    db.child(str(user.id)).update({"Wins": 0})
    return True

client.run(token)


import unittest
import random

import drumkit
##import csound
import sampler

class TestSampler(unittest.TestCase):

    def setUp(self):

        self.sampler = sampler.Sampler()

        # new instrument
        instr = self.sampler.createInstrument(0)
        # new technique
        tech = self.sampler.createTechnique(instr)
        self.sampler.setTechniqueMIDI(instr, tech, 35)
        self.sampler.setTechniqueMIDI(instr, tech, 36)
        # new target
        target = self.sampler.createTarget(instr, tech)
        # new layer
        layer = self.sampler.createLayer(instr, tech, target)
        layer = self.sampler.createLayer(instr, tech, target)
        # new target
        target = self.sampler.createTarget(instr, tech)
        # new layer
        layer = self.sampler.createLayer(instr, tech, target)
        layer = self.sampler.createLayer(instr, tech, target)
        layer = self.sampler.createLayer(instr, tech, target)
        # sort
        self.sampler.sortLayersByVel(instr, tech, target)

        # new instrument
        instr = self.sampler.createInstrument(0)
        # new technique
        tech = self.sampler.createTechnique(instr)
        self.sampler.setTechniqueMIDI(instr, tech, 38)
        self.sampler.setTechniqueMIDI(instr, tech, 40)
        # new target
        target = self.sampler.createTarget(instr, tech)
        # new layer
        layer = self.sampler.createLayer(instr, tech, target)
        self.sampler.setLayerVelocity(instr, tech, target, layer, 0.33)
        layer = self.sampler.createLayer(instr, tech, target)
        self.sampler.setLayerVelocity(instr, tech, target, layer, 0.75)
        layer = self.sampler.createLayer(instr, tech, target)
        self.sampler.setLayerVelocity(instr, tech, target, layer, 0.25)
        layer = self.sampler.createLayer(instr, tech, target)
        self.sampler.setLayerVelocity(instr, tech, target, layer, 0.66)
        # sort
        self.sampler.sortLayersByVel(instr, tech, target)

        self.sampler.setSampleData(0, 100)
        self.sampler.setSampleData(1, 101)

    def testMapping(self):

        # check MIDI

        assert (int(self.sampler.isExists(35)) == 1)
        assert (int(self.sampler.isExists(36)) == 1)
        assert (int(self.sampler.isExists(38)) == 1)
        assert (int(self.sampler.isExists(40)) == 1)

        # check isntruments

        instr1 = int(self.sampler.getInstrument(35))
        instr2 = int(self.sampler.getInstrument(36))
        assert (instr1 == instr2)
        instr1 = int(self.sampler.getInstrument(35))
        instr2 = int(self.sampler.getInstrument(40))
        assert (instr1 != instr2)

    def testSamplesData(self):

        sd = int(self.sampler.getSampleData(0))
        assert(sd == 100)
        sd = int(self.sampler.getSampleData(1))
        assert(sd == 101)

    def testHuman(self):

        # falloff

        vel = 0.66
        falloff = self.sampler.humanFalloff(vel, 0.33, 0)
        assert (falloff == vel)
        vel = 0.66
        falloff = self.sampler.humanFalloff(vel, 0.33, 0.5)
        assert (falloff < vel)

        # force

        vel = 0.66
        force = self.sampler.humanVelocity(vel, 0.33)
        assert (force >= 0 and force <= 1)

        # time

        human = 0.33
        time = self.sampler.humanTime(human)
        assert (time >= 0 and time <= human)

    def testMorph(self):

        midi = 40
        target = 0

        # check normal mode

        vel = 0.3
        top, bot, morph = self.sampler.getMorph(midi, target, vel)
        assert (morph >= 0 and morph <= 1)

        vel = 0.6
        top, bot, morph = self.sampler.getMorph(midi, target, vel)
        assert (morph >= 0 and morph <= 1)

        # check exceed bounds

        vel = 0.1
        top, bot, morph = self.sampler.getMorph(midi, target, vel)
        assert (morph >= 0 and morph <= 1)

        vel = 0.9
        top, bot, morph = self.sampler.getMorph(midi, target, vel)
        assert (morph >= 0 and morph <= 1)

class TestDrumkit(unittest.TestCase):

    testXML = """
<Drumkit>
<Version>1</Version>
<Description>test</Description>
<License></License>
<Instrument Name="Instrument1">
<Technique>
<MIDI>35</MIDI>
<MIDI>36</MIDI>
<Target>
<Channel>Mono</Channel>
<Gain>1</Gain>
<ADSR><Attack>0.01</Attack><Decay>0</Decay><Sustain>1</Sustain><Release>0.1</Release></ADSR>
<Layer><Velocity>1</Velocity><Gain>1</Gain><Sample>test.wav</Sample></Layer>
<Layer><Velocity>0</Velocity><Gain>1</Gain><Sample>test2.wav</Sample></Layer>
</Target>
</Technique>
</Instrument>
</Drumkit>
"""

    def testParser(self):

        testkit = drumkit.parseXML(self.testXML)
        channels = testkit.getChannels()
        assert (len(channels) == 1)
        assert ("Mono" in channels)
        samples = testkit.getSamples()
        assert (len(samples) == 2)
        assert ("test.wav" in samples)
        assert ("test2.wav" in samples)

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


import csv
import sys

from PIL import Image
import numpy as np
from torch.utils.data import Dataset
import skimage

class CSVDataset(Dataset):
    """CSV dataset."""

    def __init__(self, train_file, class_list, transform=None):
        """
        Args:
            train_file (string): CSV file with training annotations
            annotations (string): CSV file with class list
            test_file (string, optional): CSV file with testing annotations
        """
        self.train_file = train_file
        self.class_list = class_list
        self.transform = transform

        # parse the provided class file
        try:
            with self._open_for_csv(self.class_list) as file:
                self.classes = self.load_classes(csv.reader(file, delimiter=','))
        except ValueError as e:
            raise(ValueError('invalid CSV class file: {}: {}'.format(self.class_list, e)))

        self.labels = {}
        for key, value in self.classes.items():
            self.labels[value] = key

        # csv with img_path, x1, y1, x2, y2, class_name
        try:
            with self._open_for_csv(self.train_file) as file:
                self.image_data = self._read_annotations(csv.reader(file, delimiter=','), self.classes)
        except ValueError as e:
            raise(ValueError('invalid CSV annotations file: {}: {}'.format(self.train_file, e)))
        self.image_names = list(self.image_data.keys())

    def _parse(self, value, function, fmt):
        """
        Parse a string into a value, and format a nice ValueError if it fails.
        Returns `function(value)`.
        Any `ValueError` raised is catched and a new `ValueError` is raised
        with message `fmt.format(e)`, where `e` is the caught `ValueError`.
        """
        try:
            return function(value)
        except ValueError as e:
            raise ValueError(fmt.format(e))

    def _open_for_csv(self, path):
        """
        Open a file with flags suitable for csv.reader.
        This is different for python2 it means with mode 'rb',
        for python3 this means 'r' with "universal newlines".
        """
        if sys.version_info[0] < 3:
            return open(path, 'rb')
        else:
            return open(path, 'r', newline='')

    def load_classes(self, csv_reader):
        result = {}

        for line, row in enumerate(csv_reader):
            line += 1

            try:
                class_name, class_id = row
            except ValueError:
                raise(ValueError('line {}: format should be \'class_name,class_id\''.format(line)))
            class_id = self._parse(class_id, int, 'line {}: malformed class ID: {{}}'.format(line))

            if class_name in result:
                raise ValueError('line {}: duplicate class name: \'{}\''.format(line, class_name))
            result[class_name] = class_id
        return result

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

    def __getitem__(self, idx):

        img = self.load_image(idx)
        annot = self.load_annotations(idx)
        sample = {'img': img, 'annot': annot}
        if self.transform:
            sample = self.transform(sample)

        return sample

    def load_image(self, image_index):
        img = skimage.io.imread(self.image_names[image_index])

        if len(img.shape) == 2:
            img = skimage.color.gray2rgb(img)

        return img.astype(np.float32)/255.0

    def load_annotations(self, image_index):
        # get ground truth annotations
        annotation_list = self.image_data[self.image_names[image_index]]
        annotations     = np.zeros((0, 5))

        # some images appear to miss annotations (like image with id 257034)
        if len(annotation_list) == 0:
            return annotations

        # parse annotations
        for idx, a in enumerate(annotation_list):
            # some annotations have basically no width / height, skip them
            x1 = a['x1']
            x2 = a['x2']
            y1 = a['y1']
            y2 = a['y2']

            if (x2-x1) < 1 or (y2-y1) < 1:
                continue

            annotation        = np.zeros((1, 5))

            annotation[0, 0] = x1
            annotation[0, 1] = y1
            annotation[0, 2] = x2
            annotation[0, 3] = y2

            annotation[0, 4]  = self.name_to_label(a['class'])
            annotations       = np.append(annotations, annotation, axis=0)

        return annotations

    def _read_annotations(self, csv_reader, classes):
        result = {}
        for line, row in enumerate(csv_reader):
            line += 1

            try:
                img_file, x1, y1, x2, y2, class_name = row[:6]
            except ValueError:
                raise ValueError('line {}: format should be \'img_file,x1,y1,x2,y2,class_name\' or \'img_file,,,,,\''.format(line))

            if img_file not in result:
                result[img_file] = []

            # If a row contains only an image path, it's an image without annotations.
            if (x1, y1, x2, y2, class_name) == ('', '', '', '', ''):
                continue

            x1 = self._parse(x1, int, 'line {}: malformed x1: {{}}'.format(line))
            y1 = self._parse(y1, int, 'line {}: malformed y1: {{}}'.format(line))
            x2 = self._parse(x2, int, 'line {}: malformed x2: {{}}'.format(line))
            y2 = self._parse(y2, int, 'line {}: malformed y2: {{}}'.format(line))

            # Check that the bounding box is valid.
            if x2 <= x1:
                raise ValueError('line {}: x2 ({}) must be higher than x1 ({})'.format(line, x2, x1))
            if y2 <= y1:
                raise ValueError('line {}: y2 ({}) must be higher than y1 ({})'.format(line, y2, y1))

            # check if the current class name is correctly present
            if class_name not in classes:
                raise ValueError('line {}: unknown class name: \'{}\' (classes: {})'.format(line, class_name, classes))

            result[img_file].append({'x1': x1, 'x2': x2, 'y1': y1, 'y2': y2, 'class': class_name})
        return result

    def name_to_label(self, name):
        return self.classes[name]

    def label_to_name(self, label):
        return self.labels[label]

    def num_classes(self):
        return max(self.classes.values()) + 1

    def image_aspect_ratio(self, image_index):
        image = Image.open(self.image_names[image_index])
        return float(image.width) / float(image.height)


#%%
from time import sleep
from typing import Sequence, Text
from numpy import NAN, dtype, log, unicode_
import selenium
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import pandas as pd
import time, datetime, os
from csv import writer
import cloudscraper #faz a requisição pra receber os dados da pagina
from bs4 import BeautifulSoup #faz o tratamento do texto e extração por css
import re #para expressoes regulares
import timeit
import unidecode
import re
import numpy as np
import math as mat

#%%
user= "Rafael"

url= "https://www.vivareal.com.br/imoveis-lancamento/sao-paulo/zona-sul/moema/apartamento_residencial/"

#base_exportar="imóveis a venda em itaim bibi SP area-ate=75 - base limpa pelo python"
base_exportar="imoveis novos moema - vvr - base limpa pelo python"

#%%

tic1 = timeit.default_timer()

driver = webdriver.Chrome(executable_path='./chromedriver103')

imoveis_link_list = []

driver.get(url)

try:
    element = WebDriverWait(driver, 5).until(
       EC.presence_of_element_located((By.ID, "cookie-notifier-cta"))
    )
    element.click()
except:
    print("Sem conferência de coockies")

def iniciar_coleta():
    time.sleep(1)
    resultados = driver.find_element_by_class_name("results-list")
    imoveis = resultados.find_elements_by_tag_name("article")
    for imovel in imoveis:
        PAGE_URL = imovel.find_element_by_class_name("property-card__content-link.js-card-title").get_attribute("href")
        imoveis_link_list.append(PAGE_URL)

    time.sleep(3)

iniciar_coleta()

for i in range(300):
    try:
        proxima_pagina = driver.find_element_by_partial_link_text("Próxima")
        proxima_pagina.click()
        time.sleep(5)
        iniciar_coleta()
    except:
        print("Sem próxima página")
        break
    time.sleep(5)

print(imoveis_link_list)
print(len(imoveis_link_list))

links=imoveis_link_list[0:len(imoveis_link_list)]

toc1 = timeit.default_timer()

print(toc1-tic1)

tic2 = timeit.default_timer()

imoveis_list=[]
lista_links_inaces=[]

#links=imoveis_link_list[(5550+2300):len(imoveis_link_list)]
scraper = cloudscraper.create_scraper()

for i in range(0,len(links)):
    content = scraper.get(links[i]).text
    soup = BeautifulSoup(content, 'html.parser')

    try:
        TITULO= soup.find("h1",class_="title__title js-title-view").text
    except:
        TITULO = ''
    try:
        PAGE_URL= links[i]
    except:
        PAGE_URL = ""
    try:
        ENDERECO_COMP= soup.find("div",class_="title__address-wrapper").text
    except:
        ENDERECO_COMP = ""
    try:
        AREA=soup.find("li",class_="features__item features__item--area js-area").text
    except:
        AREA = ""
    try:
        QUARTO= soup.find("li",class_="features__item features__item--bedroom js-bedrooms").text
    except:
        QUARTO = ""
    try:
        BANHEIRO = soup.find("li",class_="features__item features__item--bathroom js-bathrooms").text
    except:
        BANHEIRO = ""
    try:
        SUITE=soup.find("small",class_="features__extra-info").text
    except:
        SUITE= ''
    try:
        VAGA=soup.find("li",class_="features__item features__item--parking js-parking").text
    except:
        VAGA = ''
    try:
        ANUNCIANTE= soup.find("a",class_="publisher__name")
        ANUNCIANTE= str(ANUNCIANTE)
    except:
        ANUNCIANTE = ''
    try:
        VALOR_VENDA= soup.find("h3",class_="price__price-info js-price-sale").text
    except:
        VALOR_VENDA = ''
    try:
        VALOR_ALUGUEL= soup.find("h3",class_="price__price-info js-price-rent").text
    except:
        VALOR_ALUGUEL = ''
    try:
        DESCRICAO= soup.find("h3",class_="description__title js-description-title").text
    except:
        DESCRICAO = ''
    try:
        DESCRICAO_COMP=soup.find("p",class_="description__text").text
    except:
        DESCRICAO_COMP = ''

    try:
        list_links_fotos=soup.find_all("ul",class_="carousel__container js-carousel-scroll")
        FOTOS = str(list_links_fotos)
    except:
        FOTOS = ''

    try:
        CONDOMINIO=soup.find("span",class_="price__list-value condominium js-condominium").text
    except:
        CONDOMINIO = ''
    try:
        IPTU=soup.find("li",class_="price__list-value iptu js-iptu").text
    except:
        IPTU = ''

    SCRAPING_TIME = datetime.datetime.now().strftime("%D %H:%M:%S")

    imoveis_dic = {
        'TITULO': TITULO,
        'ENDERECO_COMP': ENDERECO_COMP,
        'AREA': AREA,
        'QUARTO': QUARTO,
        'BANHEIRO': BANHEIRO,
        'SUITE': SUITE,
        'VAGA': VAGA,
        'CONDOMINIO': CONDOMINIO,
        'IPTU': IPTU,
        'ANUNCIANTE': ANUNCIANTE,
        'VALOR_VENDA': VALOR_VENDA,
        'VALOR_ALUGUEL': VALOR_ALUGUEL,
        'DESCRICAO': DESCRICAO,
        'DESCRICAO_COMP': DESCRICAO_COMP,
        'FOTOS': FOTOS,
        'SCRAPING_TIME': SCRAPING_TIME,
        'PAGE_URL': PAGE_URL,
    }

    imoveis_list.append(imoveis_dic)
    print("pegou um imóvel {}, com título:{}".format(i+1,TITULO))
    time.sleep(3)

dds = pd.DataFrame(imoveis_list)

toc2 = timeit.default_timer()

print(toc2-tic2)

#ddssss=pd.read_excel('C:/Users/Admin/Ermida/Ícaro Costa - Quadra Urbana/03 - Clientes [Projetos]/QU/imóveis a venda em campo-belo SP area-ate=230 area-desde=151 - base suja.xlsx')
#ddssss=ddssss.iloc[:,1:len(ddssss.columns)]

dds1=dds

dds1["DATA_ID"] = range(0,len(dds1))
dds1.columns= ["TITULO","ENDERECO_COMP","AREA","QUARTO","BANHEIRO","SUITE","VAGA","CONDOMINIO","IPTU","ANUNCIANTE","VALOR_VENDA","VALOR_ALUGUEL","DESCRICAO","DESCRICAO_COMP","FOTOS","SCRAPING_TIME","LINK","DATA_ID"]

for i in range(0,len(dds1)):
    for j in range(0,len(dds1.columns)):
        dds1.iloc[i,j]=unidecode.unidecode(str(dds1.iloc[i,j])).upper()

dds1["VALOR"]=""
dds1["TIPO_ANUNCIO"]=""

tamanho= len(dds1)

t_a=pd.DataFrame([url]).iloc[:,0].str.extract("(vivareal\\.com\\.br.*\\/)").iloc[:,0].str.split("\\/",expand=True).iloc[0,1]

if t_a == 'imoveis-lancamento':
    t_a = "venda"

if t_a == "venda":
    for i in range(0,tamanho-1):
        if dds1["VALOR_ALUGUEL"][i] != '':
            tam=len(dds1)

            dds1.loc[tam]= list(dds1.iloc[i,:])
            dds1["VALOR"][tam] =  dds1["VALOR_ALUGUEL"][tam]
            dds1["TIPO_ANUNCIO"][tam]= "ALUGUEL"

            dds1["VALOR"][i]= dds1["VALOR_VENDA"][i]

        if dds1["VALOR_ALUGUEL"][i] == '':
            dds1["VALOR"][i]= dds1["VALOR_VENDA"][i]
            dds1["TIPO_ANUNCIO"][i]= "VENDA"

        if dds1["TIPO_ANUNCIO"][i] == '':
            dds1["TIPO_ANUNCIO"][i] = "VENDA"

if t_a == "aluguel":
    for i in range(0,tamanho-1):
        if dds1["VALOR_ALUGUEL"][i] != '': # nesse caso VALOR_VENDA = valordealuguel e VALOR_ALUGUEL = valordevenda
            tam=len(dds1)

            dds1.loc[tam]= list(dds1.iloc[i,:])
            dds1["VALOR"][tam] =  dds1["VALOR_ALUGUEL"][tam]
            dds1["TIPO_ANUNCIO"][tam]= "ALUGUEL"

            dds1["VALOR"][i]= dds1["VALOR_VENDA"][i]

        if dds1["VALOR_ALUGUEL"][i] == '':
            dds1["VALOR"][i]= dds1["VALOR_VENDA"][i]
            dds1["TIPO_ANUNCIO"][i]= "ALUGUEL"

        if dds1["TIPO_ANUNCIO"][i] == '':
            dds1["TIPO_ANUNCIO"][i] = "VENDA"

dds1["TIPO_IMOVEL"]=dds1["TITULO"].str.extract(pat='(LOTE\\/TERRENO|PREDIO COMERCIAL|FAZENDA\\/SITIO|LOTE RESIDENCIAL|CASA CONDOMINIO|LOTE COMERCIAL|PONTO COMERCIAL|GALPAO\\/DEPOSITO\\/ARMAZEM|CHACARA|FLAT|HOTEL|SALA CLINICA|KITNET|COBERTURA|CASA SOBRADO|PREDIO RESIDENCIAL|GARAGEM|LOJA|SALA COMERCIAL|SOBRADO|IMOVEL COMERCIAL|CONSULTORIO|KITNET KITNET-STUDIO|APARTAMENTO DUPLEX|SALA|KITNET MOBILIADO|CASA DE CONDOMINIO|CASAS DE CONDOMINIO|APARTAMENTO COBERTURA|HOTEL FLAT|LOJA SOBRELOJA|GALPAO|APARTAMENTO LOFT|PREDIO MISTO|PONTO COMERCIAL GALPAO|SALA CONSULTORIO|APARTAMENTO MOBILIADO|CASA CONDOMINIO SOBRADO|SALA ANDAR|PONTO COMERCIAL PREDIO|PONTO COMERCIAL HOTEL|LOTE INDUSTRIAL|PONTO COMERCIAL PADARIA|PONTO COMERCIAL POSTO DE GASOLINA|CASA BARRACAO|PONTO COMERCIAL POUSADA|APARTAMENTO TRIPLEX|PONTO COMERCIAL FARMACIA|CASA|APARTAMENTO)')

dds1["TIPO_IMOVEL"] = dds1["TIPO_IMOVEL"].fillna("LANCAMENTO")

dds1 = dds1[ dds1.ENDERECO_COMP != '' ]

dds1.index = range(0,len(dds1))

dds1["ENDERECO_COMP"]= dds1["ENDERECO_COMP"].str.replace(" VER NO MAPA","")

dds1["ESTADO"] = dds1["ENDERECO_COMP"].str.extract("(...$)")

cidade=dds1["ENDERECO_COMP"].str.extract("(.*\\-)")
cidade.iloc[:,0] = "-"+cidade.iloc[:,0]
cidade=cidade.iloc[:,0].str.split(",")

cidade2=[]

for i in range(0,len(dds1)):
    cidade2.append(str(cidade[i][len(cidade[i])-1]))

dds1["CIDADE"]=cidade2
dds1["CIDADE"] = dds1["CIDADE"].str.replace("-","")
dds1["CIDADE"] = dds1["CIDADE"].str.strip()

BAIRRO=dds1["ENDERECO_COMP"].str.extract("(.*\\,)")
BAIRRO.iloc[:,0] = " - "+BAIRRO.iloc[:,0]
BAIRRO=BAIRRO.iloc[:,0].str.split("-")

BAIRRO2=[]
for i in range(0,len(dds1)):
    try:
        BAIRRO2.append(str(BAIRRO[i][len(BAIRRO[i])-1]))
    except:
        BAIRRO2.append(" ")

dds1["BAIRRO"]=BAIRRO2
dds1["BAIRRO"] = dds1["BAIRRO"].str.replace(",","")
dds1["BAIRRO"] = dds1["BAIRRO"].str.strip()

area= dds1["AREA"].str.replace("M2","")
area = area.str.split("a", expand = True)
dds1["AREA"] = area.iloc[:,0].str.strip()
dds1["AREA"] = pd.to_numeric(dds1["AREA"],errors = 'coerce')

QUARTO= dds1["QUARTO"].str.replace("QUARTO","")
QUARTO= QUARTO.str.replace("S","")
QUARTO = QUARTO.str.split("a", expand = True)
dds1["QUARTO"] = QUARTO.iloc[:,0].str.strip()
dds1['QUARTO'] = pd.to_numeric(dds1['QUARTO'],errors = 'coerce')

SUITE= dds1["SUITE"].str.replace("SUITE","")
SUITE= SUITE.str.replace("S","")
SUITE = SUITE.str.split("a", expand = True)
dds1["SUITE"] = SUITE.iloc[:,0].str.strip()
dds1['SUITE'] = pd.to_numeric(dds1['SUITE'],errors = 'coerce')

BANHEIRO = dds1["BANHEIRO"].str.strip().str.split(" ", expand = True)
BANHEIRO = BANHEIRO.iloc[:,0].str.strip()
BANHEIRO = pd.to_numeric(BANHEIRO,errors = 'coerce')
dds1['BANHEIRO']=BANHEIRO

VAGA = dds1["VAGA"].str.strip().str.split(" ", expand = True)
VAGA = VAGA.iloc[:,0].str.strip()
VAGA = pd.to_numeric(VAGA,errors = 'coerce')
dds1['VAGA']=VAGA

condo= dds1["CONDOMINIO"].str.replace("R\\$","")
condo = condo.str.replace("\\.","")
condo = condo.str.replace(",","\\.")
condo = pd.to_numeric(condo,errors = 'coerce')
dds1['CONDOMINIO']=condo

IPTU= dds1["IPTU"].str.replace("R\\$","")
IPTU = IPTU.str.replace("\\.","")
IPTU = IPTU.str.replace(",","\\.")
IPTU = pd.to_numeric(IPTU,errors = 'coerce')
dds1['IPTU']=IPTU

VALOR= dds1["VALOR"]
VALOR= VALOR.str.replace("R\\$","")
VALOR= VALOR.str.replace("\\.","")
VALOR= VALOR.str.replace("\\,",".")
VALOR= VALOR.str.replace("\\/MES","")
VALOR= VALOR.str.strip()

dds1["VALOR"] = pd.to_numeric(VALOR,errors = 'coerce')

dds1["VALOR_M2"] = dds1["VALOR"]/dds1["AREA"]

dds1["VALOR_LN"] = log(dds1["VALOR"])
dds1["VALOR_M2_LN"] = log(dds1["VALOR_M2"])

fts=dds1["FOTOS"].str.split("</LI> <LI",expand=True)

for j in range(0,len(fts.columns)):
    fts.iloc[:,j]=fts.iloc[:,j].str.extract("( SRC=\"HTTPS\\:\\/\\/RESIZEDIMGS.*JPG)")
    fts.iloc[:,j]=fts.iloc[:,j].str.replace(" SRC=\"","").str.lower()

dds1["FOTOS"] = fts.iloc[:,0]

dds1["LINK"]=dds1["LINK"].str.lower()

dds1 = dds1.drop_duplicates(subset=["LINK","TIPO_ANUNCIO"])

dds1.index = range(0,len(dds1))

data = dds1["SCRAPING_TIME"].str.split(" ",expand=True).iloc[:,0].str.split("/",expand=True)
dds1["DATA_SCRAPING"]=""
for i in range(0,len(dds1)):
    dds1["DATA_SCRAPING"][i]= "{}/{}/{}".format(data.iloc[i,0],data.iloc[i,1],data.iloc[i,2])
dds1["DATA_SCRAPING"]

dds1["SCRAPING_TIME"]= dds1["SCRAPING_TIME"].str.split(" ",expand=True).iloc[:,1]

dds2=dds1[["DATA_ID","TITULO","TIPO_ANUNCIO","TIPO_IMOVEL","ENDERECO_COMP","ESTADO","CIDADE","BAIRRO","AREA","QUARTO","BANHEIRO","SUITE","VAGA","CONDOMINIO","IPTU","VALOR","VALOR_LN","VALOR_M2","VALOR_M2_LN","ANUNCIANTE","DESCRICAO","DATA_SCRAPING","SCRAPING_TIME","FOTOS","LINK"]]
dds2["SITE"]= "VIVAREAL"

dds2=dds2.rename(columns={"ENDERECO_COMP":"RUA_OU_QUADRA"})

dds2= dds2.dropna(subset=["VALOR"])
dds2= dds2.dropna(subset=["AREA"])
dds2= dds2.dropna(subset=["RUA_OU_QUADRA"])

dds2["DATA_ID"] = range(1,len(dds2)+1)
dds2.index = range(1,len(dds2)+1)

dds2["DESCRICAO_COMP"]= " "

if user == "Pupe":
    dds2.to_excel('C:/Users/Admin/Ermida/Ícaro Costa - Quadra Urbana/03 - Clientes [Projetos]/QU/{}.xlsx'.format(base_exportar))

if user == "Rafael":
    dds2.to_excel('C:/Users/Ermida/OneDrive - Ermida/Quadra Urbana/03 - Clientes [Projetos]/QU/{}.xlsx'.format(base_exportar))

# %%
dds = pd.DataFrame(imoveis_list)
dds
# %%


'''
Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

Constraints:

    The number of nodes in the list is in the range [1, 100].
    1 <= Node.val <= 100

'''
from typing import Optional

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

from math import ceil

class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        res = 0
        tail = head
        if not tail.next:
            return head
        while tail.next:
            res += 1
            tail = tail.next
        l = 0
        tail = head
        mid = ceil(res / 2)
        print(mid)
        while tail.next:
            l += 1
            if l == mid:
                return tail.next
            else:
                tail = tail.next

# using slow and fast pointer when fast reaches end slow will be in middle
# slow moves 1 step and fast moves 2 steps
class SolutionTwo:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        if not slow.next:
            return head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow


import sys
import sqlite3

from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QCheckBox, QMessageBox
from PyQt5.QtGui import *
from PyQt5.QtCore import QRect, Qt
from game import ChessHardGame
from skinsshow import SkinsShow
from pygame import mixer

mixer.init(channels=2)

with open('game_info.txt', 'w') as f:
    f.write('')  # перезапись файла с данными игры для новой игры

class MainMenu(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUi()

    def initUi(self):
        self.setFixedSize(700, 700)
        self.setWindowTitle('Главное меню')
        main_menu = mixer.Sound('sounds/main_menu_theme.mp3')
        mixer.Channel(0).set_volume(0.1)
        mixer.Channel(0).play(main_menu, loops=-1)

        self.taunt = QLabel('Перед боем шахматист должен выбрать скин. \n'
                            'Стиль - это тоже важно, ведь если \n'
                            'шахматист придёт на бой голым, \n'
                            'он и сам опростоволосится, и врага насмешит.', self)   # и не говорите мне,
        # что я не предупреждал
        self.taunt.resize(500, 70)
        self.taunt.move(225, 525)
        self.secret = ''   # ???

        self.count1, self.count2 = 0, 0   # счётчики испытаний
        self.skin_count = 0   # открытие меню со скинами
        self.black, self.lava = False, False   # условия испытаний

        self.main_label = QLabel(self)
        self.main_label.resize(300, 200)
        self.main_label.move(200, 20)
        self.hard_mode = QMovie('menu_gif.gif')   # гифка
        self.main_label.setMovie(self.hard_mode)
        self.hard_mode.frameChanged.connect(self.stop_gif)
        self.hard_mode.start()

        self.label = QLabel('ШАХМАТЫ', self)
        self.label.setFont(QFont('RUSBoycott', 17))
        self.label.setStyleSheet('color: red')
        self.label.move(300, 0)

        self.challenge_label = QLabel(self)
        self.challenge_label.resize(70, 60)
        self.challenge_label.setPixmap(QPixmap('challenge_label.png'))
        self.challenge_label.move(20, 335)

        self.blackout = QCheckBox('Blackout', self)
        self.blackout.move(20, 330)
        self.blackout.stateChanged.connect(self.set_challenge)
        self.lava_floor = QCheckBox('Lava Floor', self)
        self.lava_floor.move(20, 370)
        self.lava_floor.stateChanged.connect(self.set_challenge)
        # установка испытаний

        self.challenges = [self.blackout, self.lava_floor]

        self.blackout_label = QLabel('Blackout (И погаснет свет навсегда) - \nмир вокруг тебя погружается во тьму!\n'
                                     'Теперь, кроме вражеского короля \nда твоих фигур, больше не видно \nНИЧЕГО!!!',
                                     self)
        self.blackout_label.resize(200, 200)
        self.blackout_label.move(350, 100)
        self.blackout_label.hide()

        self.lava_label = QLabel('Lava Floor (Пол - это лава) - \nслучайные клетки\nблокируются лавой!\n'
                                 'Ставить фигуры на них - \nБЕСЧЕСТЬЕ И ГРЕХ!!!',
                                 self)
        self.lava_label.resize(200, 200)
        self.lava_label.move(350, 350)
        self.lava_label.hide()

        self.start_button = QPushButton('Щёлкните, чтобы СТРАДАТЬ!!!', self)
        self.start_button.setFont(QFont('RUSBoycott', 15))
        self.start_button.setGeometry(QRect(300, 50, 300, 50))
        self.start_button.move(200, 600)
        self.start_button.clicked.connect(self.start_game)

        self.skins_button = QPushButton('Скин-паки', self)
        self.skins_button.move(50, 600)
        self.skins_button.clicked.connect(self.skins_show)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_J or event.key() == Qt.Key_O or event.key() == Qt.Key_Y:
            self.secret += str(event.key())
        if self.secret == '747989':
            secret = mixer.Sound('sounds/secret.mp3')
            mixer.Channel(1).play(secret, loops=0)

            que = sqlite3.connect('skins')
            cur = que.cursor()
            cur.execute('''UPDATE info SET unlockation = 'unlocked' WHERE names = 'smeshariki' ''')
            que.commit()
            que.close()
            # запись Смешариков в БД

    def stop_gif(self, frame):
        if self.hard_mode.frameCount() == frame + 1:
            self.hard_mode.stop()   # остановка воспроизведения

    def skins_show(self):
        global ex2
        with open('game_info.txt', 'r') as f:
            lines = f.read()
            if 'BLACKOUT\n' not in lines and 'LAVA_FLOOR\n' not in lines:
                self.taunt.setText('Сначала выбери испытания.')   # просьба выбрать испытания
                self.taunt.show()
            else:
                ex2 = SkinsShow()   # открытие меню со скинами
                ex2.show()

                skins = mixer.Sound('sounds/skins.mp3')
                mixer.music.set_volume(0.5)
                mixer.Channel(0).play(skins, loops=-1)

    def start_game(self):
        global ex1
        with open('game_info.txt', 'r') as f:
            lines = f.read()
            if 'BLACKOUT\n' not in lines and 'LAVA_FLOOR\n' not in lines:
                self.taunt.setText('Слабак! Таких шахматистов у нас не жалуют!')   # да-да, не жалуют!
                self.taunt.show()
            else:
                mixer.Channel(0).stop()
                ex.hide()
                ex1 = ChessHardGame()   # игра
                ex1.show()

    def closeEvent(self, event):
        check = QMessageBox.question(self, 'Уже уходишь?', 'Ну и ладно! Давай, топай спасать свою никчёмную жизнь! '
                                                           'Но этим ты лишь докажешь, что в шахматисты ты '
                                                           'НЕ ГОДЕН!!!', QMessageBox.Yes, QMessageBox.No)
        # когда мы показали ему, кто тут босс доски, он делает выбор
        if check == QMessageBox.Yes:
            event.accept()   # закрытие
        else:
            event.ignore()   # игнорирование

    def set_challenge(self):
        global count1, count2, count3
        if self.challenges.index(self.sender()) == 0:   # проверка испытания
            if self.count1 == 0:   # проверка индекса
                self.count1 += 1
                with open('game_info.txt', 'a') as f:
                    f.write('BLACKOUT\n')   # запись в файл
                self.blackout_label.show()
                self.black = True
            else:
                self.count1 = 0
                with open('game_info.txt', 'r') as f:
                    data = f.read()
                    new_data = data.replace('BLACKOUT\n', '')
                with open('game_info.txt', 'w') as f:
                    f.write(new_data)
                self.blackout_label.hide()
                self.black = False
        elif self.challenges.index(self.sender()) == 1:
            if self.count2 == 0:
                self.count2 += 1
                with open('game_info.txt', 'a') as f:
                    f.write('LAVA_FLOOR\n')
                self.lava_label.show()
                self.lava = True
            else:
                self.count2 = 0
                with open('game_info.txt', 'r') as f:
                    data = f.read()
                    new_data = data.replace('LAVA_FLOOR\n', '')
                with open('game_info.txt', 'w') as f:
                    f.write(new_data)
                self.lava_label.hide()
                self.lava = False

def except_hook(cls, exception, traceback):
    sys.__excepthook__(cls, exception, traceback)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    sys.excepthook = except_hook
    ex = MainMenu()
    ex1 = None   # изначально None, чтобы он не генерировался сразу
    ex2 = None
    ex.show()
    sys.exit(app.exec_())


# valueIterationAgents.py
# -----------------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

# valueIterationAgents.py
# -----------------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

import mdp, util

from learningAgents import ValueEstimationAgent
import collections

class ValueIterationAgent(ValueEstimationAgent):
    """
        * Please read learningAgents.py before reading this.*

        A ValueIterationAgent takes a Markov decision process
        (see mdp.py) on initialization and runs value iteration
        for a given number of iterations using the supplied
        discount factor.
    """
    def __init__(self, mdp, discount = 0.9, iterations = 100):
        """
          Your value iteration agent should take an mdp on
          construction, run the indicated number of iterations
          and then act according to the resulting policy.

          Some useful mdp methods you will use:
              mdp.getStates()
              mdp.getPossibleActions(state)
              mdp.getTransitionStatesAndProbs(state, action)
              mdp.getReward(state, action, nextState)
              mdp.isTerminal(state)
        """
        self.mdp = mdp
        self.discount = discount
        self.iterations = iterations
        self.values = util.Counter() # A Counter is a dict with default 0
        self.runValueIteration()

    def runValueIteration(self):
        # Write value iteration code here
        "*** YOUR CODE HERE ***"
        prob = self.mdp
        states = prob.getStates()

        for i in range(self.iterations):
            holderValues = util.Counter()
            for state in states:
                newVal = []
                actions = prob.getPossibleActions(state)
                if not actions:
                    holderValues[state] = self.values[state]
                else:
                    for action in actions:
                        newVal.append(self.computeQValueFromValues(state, action))

                    holderValues[state] = max(newVal)
            self.values = holderValues

    def getValue(self, state):
        """
          Return the value of the state (computed in __init__).
        """
        return self.values[state]

    def computeQValueFromValues(self, state, action):
        """
          Compute the Q-value of action in state from the
          value function stored in self.values.
        """
        "*** YOUR CODE HERE ***"
        prob = self.mdp
        possibleStates = prob.getTransitionStatesAndProbs(state, action)
        qVal = 0
        for nextState in possibleStates:
            qVal = qVal + nextState[1]*(prob.getReward(state, action, nextState[0]) +
                                        self.discount*self.getValue(nextState[0]))
        return qVal

    def computeActionFromValues(self, state):
        """
          The policy is the best action in the given state
          according to the values currently stored in self.values.

          You may break ties any way you see fit.  Note that if
          there are no legal actions, which is the case at the
          terminal state, you should return None.
        """
        "*** YOUR CODE HERE ***"
        bestVal = float('-inf')
        chosenAction = None
        actions = self.mdp.getPossibleActions(state)
        for action in actions:
            newScore = self.computeQValueFromValues(state, action)
            if newScore > bestVal:
                chosenAction = action
                bestVal = newScore
        return chosenAction

    def getPolicy(self, state):
        return self.computeActionFromValues(state)

    def getAction(self, state):
        "Returns the policy at the state (no exploration)."
        return self.computeActionFromValues(state)

    def getQValue(self, state, action):
        return self.computeQValueFromValues(state, action)

class AsynchronousValueIterationAgent(ValueIterationAgent):
    """
        * Please read learningAgents.py before reading this.*

        An AsynchronousValueIterationAgent takes a Markov decision process
        (see mdp.py) on initialization and runs cyclic value iteration
        for a given number of iterations using the supplied
        discount factor.
    """
    def __init__(self, mdp, discount = 0.9, iterations = 1000):
        """
          Your cyclic value iteration agent should take an mdp on
          construction, run the indicated number of iterations,
          and then act according to the resulting policy. Each iteration
          updates the value of only one state, which cycles through
          the states list. If the chosen state is terminal, nothing
          happens in that iteration.

          Some useful mdp methods you will use:
              mdp.getStates()
              mdp.getPossibleActions(state)
              mdp.getTransitionStatesAndProbs(state, action)
              mdp.getReward(state)
              mdp.isTerminal(state)
        """
        ValueIterationAgent.__init__(self, mdp, discount, iterations)

    def runValueIteration(self):
        "*** YOUR CODE HERE ***"
        prob = self.mdp
        states = prob.getStates()
        divider = len(states)
        for i in range(self.iterations):
            state = states[i % divider]
            newVal = []
            actions = prob.getPossibleActions(state)
            if actions and (not prob.isTerminal(state)):
                for action in actions:
                    newVal.append(self.computeQValueFromValues(state, action))
                self.values[state] = max(newVal)

class PrioritizedSweepingValueIterationAgent(AsynchronousValueIterationAgent):
    """
        * Please read learningAgents.py before reading this.*

        A PrioritizedSweepingValueIterationAgent takes a Markov decision process
        (see mdp.py) on initialization and runs prioritized sweeping value iteration
        for a given number of iterations using the supplied parameters.
    """
    def __init__(self, mdp, discount = 0.9, iterations = 100, theta = 1e-5):
        """
          Your prioritized sweeping value iteration agent should take an mdp on
          construction, run the indicated number of iterations,
          and then act according to the resulting policy.
        """
        self.theta = theta
        ValueIterationAgent.__init__(self, mdp, discount, iterations)

    def runValueIteration(self):
        "*** YOUR CODE HERE ***"
        prob = self.mdp
        predecessors = self.getPredecessors(prob)
        from util import PriorityQueue
        heap = PriorityQueue()
        states = prob.getStates()
        for state in states:
            if not prob.isTerminal(state):
                actions = prob.getPossibleActions(state)
                value = []

                for action in actions:

                    value.append(self.computeQValueFromValues(state, action))

                diff = abs(self.values[state] - max(value))

                heap.push(state, -1 * diff)
        for i in range(self.iterations):
            if heap.isEmpty():
                break
            s = heap.pop()
            if not prob.isTerminal(s):
                self.bellmanUpdate(s)
                if predecessors[s]:
                    for pred in predecessors[s]:
                        predactions = prob.getPossibleActions(pred)
                        value = []

                        for predaction in predactions:
                            value.append(self.computeQValueFromValues(pred, predaction))

                        preddiff = abs(self.values[pred] - max(value))

                        if preddiff > self.theta:
                            heap.push(pred, -1 * preddiff)

    def bellmanUpdate(self, state):
        actions = self.mdp.getPossibleActions(state)
        val = float('-inf')
        if not actions:
            return
        else:
            for action in actions:
                newval = self.computeQValueFromValues(state, action)
                if newval > val:
                    val = newval
            self.values[state] = val

    def getPredecessors(self, problem):
        dict = {}
        states = problem.getStates()
        for state in states:
            dict[state] = []
        for state in states:
            actions = problem.getPossibleActions(state)
            reachable = set()
            for action in actions:
                reachableStates = problem.getTransitionStatesAndProbs(state, action)
                for nextstate in reachableStates:
                    if nextstate[1] > 0:
                        reachable.add(nextstate[0])
            for newstate in states:
                if newstate in reachable:
                    dict[newstate].append(state)
        return dict


class Solution:
    def backspaceCompare(self, S: str, T: str) -> bool:
        s_lst = list(S)
        t_lst = list(T)
        s_stack = []
        t_stack = []

        for i in s_lst:
            if i == "#":
                if len(s_stack) > 0:
                    s_stack.pop()
            else:
                s_stack.append(i)

        for i in t_lst:
            if i == "#":
                if len(t_stack) > 0:
                    t_stack.pop()
            else:
                t_stack.append(i)

        return "".join(s_stack) == "".join(t_stack)


class Solution:
    def removeKdigits(self, num: str, k: int) -> str:
        stack = []
        num_list = list(num)
        while num_list:
            while stack and k and int(stack[-1]) > int(num_list[0]):
                stack.pop()
                k -= 1
            if stack or int(num_list[0]):
                stack.append(num_list.pop(0))
            else:
                num_list.pop(0)

        if k:
            stack = stack[:-k]

        return "".join(stack) or "0"


def base10(num):
    m = int(input('What base is the number?: '))
    word = str(num)
    s = 0
    for i in range(0, len(word)):
        n = num % 10
        s += n * m ** i
        num //= 10
    s = 'The number in base 10 is ' + str(s) + '.'
    return s
x = int(input('Insert number here: '))
print(base10(x))


# GUI - Graphical User Interface
import tkinter as tk
from tkinter import ttk

# Creating the window
window = tk.Tk()

# Window size
window.geometry('600x400')

# Window title
window.title('New window')

# Window icon
window.iconbitmap('section56-59-tkinter-basics/icono.ico')

# Listing events
def on_click():
    # Changing properties
    button1.config(text='Button pressed')
    button2 = ttk.Button(window, text='New button')
    button2.pack()
    print('Clicked')

# Adding elements or widgets
button1 = ttk.Button(window, text='Click me', command=on_click)

# Layout Manager to deploy widgets
button1.pack()

# Main loop
window.mainloop()


import cv2
import numpy as np
import matplotlib.pyplot as plt
from global_lane import *
#img = cv2.imread('/home/hoaiphuong/CodePython/a.png',0)
#img_HSV = cv2.cvtColor(img,cv2.COLOR_RGB2HSV)
#img_threshold = cv2.inRange(img_HSV,(0,0,240),(180,255,255))
#thresh, im_bw = cv2.threshold(img, 200, 255, cv2.THRESH_BINARY)
#print im_bw.shape
def sliding_window(binary_warped):
    histogram = np.sum(binary_warped, axis=0)
    #print img_threshold[img_threshold.shape[0]/2:,:]
    #plt.plot(histogram)
    #plt.show()
    #print ('histogram %s'%(histogram.shape))
    midpoint = np.int(histogram.shape[0]/2)
    #print midpoint
    #print histogram.shape
    leftx_base = np.argmax(histogram[:midpoint])
    rightx_base = np.argmax(histogram[midpoint:]) + midpoint
    #print leftx_base
    #print rightx_base
    #print leftx_base , rightx_base
    #binary_warped = np.copy(img_threshold)
    nwindows = 9
    # Set height of windows
    window_height = np.int(binary_warped.shape[0]/nwindows)
    # Identify the x and y positions of all nonzero pixels in the image
    nonzero = binary_warped.nonzero()
    nonzeroy = np.array(nonzero[0])
    nonzerox = np.array(nonzero[1])
    # Current positions to be updated for each window
    leftx_current = leftx_base
    rightx_current = rightx_base
    # Set the width of the windows +/- margin
    margin = 20
    # Set minimum number of pixels found to recenter window
    minpix = 10
    # Create empty lists to receive left and right lane pixel indices
    left_lane_inds = []
    right_lane_inds = []
    # Step through the windows one by one
    for window in range(nwindows):
        # Identify window boundaries in x and y (and right and left)
        win_y_low = binary_warped.shape[0] - (window+1)*window_height
        win_y_high = binary_warped.shape[0] - window*window_height
        win_xleft_low = leftx_current - margin
        win_xleft_high = leftx_current + margin
        win_xright_low = rightx_current - margin
        win_xright_high = rightx_current + margin
        #print ((nonzeroy >= win_y_low).nonzero())
        #Draw the windows on the visualization image
        #cv2.rectangle(binary_warped,(win_xleft_low,win_y_low),(win_xleft_high,win_y_high),255, 2)
        #cv2.rectangle(binary_warped,(win_xright_low,win_y_low),(win_xright_high,win_y_high),255, 2)
        #Identify the nonzero pixels in x and y within the window
        #trich xuat cac vi tru x = 1
        good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
        good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
        #Append these indices to the lists
        left_lane_inds.append(good_left_inds)
        right_lane_inds.append(good_right_inds)
        # If you found > minpix pixels, recenter next window on their mean position
        # cal adventage lane x
        if len(good_left_inds) > minpix:
            leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
            #print leftx_current
        if len(good_right_inds) > minpix:
            rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
    # Concatenate the arrays of indices
    # noi cac mang lai voi nhau
    #print len(left_lane_inds)
    left_lane_inds = np.concatenate(left_lane_inds)
    right_lane_inds = np.concatenate(right_lane_inds)
    #print len(left_lane_inds)
    # Extract left and right line pixel positions
    leftx = nonzerox[left_lane_inds]
    lefty = nonzeroy[left_lane_inds]
    rightx = nonzerox[right_lane_inds]
    righty = nonzeroy[right_lane_inds]
    if (leftx.size < 5):
        left_lane.detected = False
        #print ("Left lane deteceted - False")
    else:
        left_lane.detected = True
        #print ("Left lane detected - true")
    if (rightx.size < 5):
        right_lane.detected = False
        #print ("Right lane detected False")
    else:
        right_lane.detected = True
        #print ("Right lane detected True")
    if left_lane.detected == True & right_lane.detected == True:
        # Fit a second order polynomial to each
        left_fit = np.polyfit(lefty, leftx, 2)
        right_fit = np.polyfit(righty, rightx, 2)
        left_lane.best_fit = np.vstack([left_lane.best_fit,left_fit])
        left_lane.best_fit[0] = left_fit
        right_lane.best_fit = np.vstack([right_lane.best_fit,right_fit])
        right_lane.best_fit[0] = right_fit
        left_lane.best_fit = np.average(left_lane.best_fit[-left_lane.smoothen_nframes:], axis = 0)
        right_lane.best_fit = np.average(right_lane.best_fit[-right_lane.smoothen_nframes:], axis = 0)
        #print ("saved best fit")
    else:
        #use the history avg values
        left_fit = left_lane.best_fit
        right_fit = right_lane.best_fit
    left_lane.detected == False
    right_lane.detected == False
    #cv2.imshow('sliding',binary_warped)
    return left_fit,right_fit,left_lane_inds, right_lane_inds
def poly_fit(binary_warped,left_fit,right_fit,left_lane_inds, right_lane_inds, plot=False):

    # Generate x and y values for plotting
    ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] )
    left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
    right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
    #k = np.int(left_fitx)
    # Identify the x and y positions of all nonzero pixels in the image
    nonzero = binary_warped.nonzero()
    nonzeroy = np.array(nonzero[0])
    nonzerox = np.array(nonzero[1])
    #print nonzeroy.shape
    #print left_lane_inds.shape
    out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255
    out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0]
    out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255]
    out_img[ploty.astype('int'),left_fitx.astype('int')] = [0, 255, 255]
    out_img[ploty.astype('int'),right_fitx.astype('int')] = [0, 255, 255]
    #out_img[nonzeroy[left_fitx], nonzerox[left_fitx]] = [0, 0, 255]
    #k = np.array (left_fitx,dtype=int)
    #out_img[ploty,k] = [0, 255,0 ]
    cv2.imshow('out_img',out_img)
    if(plot):
        plt.imshow(out_img)
        plt.plot(left_fitx, ploty, color='yellow')
        plt.plot(right_fitx, ploty, color='yellow')
        plt.xlim(0,640)
        plt.ylim(480, 0)
        plt.show()

    return left_fitx,right_fitx
#left_fit,right_fit,left_lane_inds, right_lane_inds=sliding_window(im_bw)
#left_fitx,right_fitx=poly_fit(im_bw,left_fit,right_fit,left_lane_inds, right_lane_inds, plot=True)
#polynomial to each lane left and right
#left_fit = np.polyfit(lefty,leftx,2)
#right_fit = np.polyfit()
#return leftx, lefty, rightx, righty, left_lane_inds, right_lane_inds
#cv2.imshow('img_threshold',img_threshold)
#cv2.waitKey(0)


# coding=utf-8

from .api.exchange import Exchange
from .api.websocket import Quotes, Executions
from .utils import dump, pdump

import json

# EXCHANGE

class Market:
  def __init__(self, config):
    self._conf = config

  def api_is_up(self):
    ex = Exchange(self._conf)
    r = ex.heartbeat()
    if r and 'ok' in r:
      return r['ok']
    return False

  def venue_is_up(self):
    ex = Exchange(self._conf)
    r = ex.venue_heartbeat()
    if r and 'ok' in r:
      return r['ok']
    return False

  def stocks(self):
    ex = Exchange(self._conf, method='GET')
    resp = ex.venue_fetch('/stocks')
    if resp and 'symbols' in resp:
      return [ s['symbol'] for s in resp['symbols'] ]
    return resp

  def orderbook(self):
    ex = Exchange(self._conf, method='GET')
    return ex.stock_fetch()

  def quote(self):
    ex = Exchange(self._conf, method='GET')
    return ex.fetch('/quote')

  def ask(self, cost, quantity, direction="sell", order_type='limit'):
    ex = Exchange(self._conf)
    order = {
      "account" : self._conf['account'],
      "venue" : self._conf['venue'],
      "stock" : self._conf['stock'],
      "price" : abs(cost),
      "qty" : quantity,
      "direction" : direction,
      "orderType" : order_type
    }
    return ex.fetch("/orders", data=order, method='POST')

  def bid(self, cost, quantity, order_type='limit'):
    return self.ask(cost, quantity, direction="buy", order_type=order_type)

  def status(self, oid):
    ex = Exchange(self._conf)
    return ex.fetch("/orders/{}".format(oid), method='GET')

  def cancel(self, oid):
    ex = Exchange(self._conf)
    return ex.fetch("/orders/{}".format(oid), method='DELETE')

  def websocket(self, callback=pdump, on_error=None, objclass=Quotes):
    def process(m):
      if m.is_text:
        data = m.data.decode("utf-8")
        out = json.loads(data)
        if 'ok' in out and out['ok']:
          if 'quote' in out:
            q = out['quote']
            return callback(q)
          else:
            return callback(out)

    try:
      e = objclass(self._conf, process)
      e.connect()
      e.run_forever()
    except:
      if on_error:
        on_error()
    finally:
      e.close()

    return e

  def quotes(self, callback=pdump, on_error=None):
    return self.websocket(callback, on_error, objclass=Quotes)

  def executions(self, callback=pdump, on_error=None):
    return self.websocket(callback, on_error, objclass=Executions)


# comment: 串行接口控制类, 控制是采用模拟接口还是真实接口以及串行接口通讯日志
from serial_module.base.real_serial import RealSerial
from serial_module.base.mock_serial import MockSerial
import logging

class NotSetSerial(Exception):
    pass

class SerialController:
    real_serial = None
    mock_serial = None
    is_mock = False
    debug = False
    __logger = None

    def set_real_serial(self, serial: RealSerial):
        self.real_serial = serial

    def set_mock_serial(self, serial: MockSerial):
        self.mock_serial = serial

    def set_debug(self, debug=True):
        self.debug = debug

    @property
    def logger(self):
        if self.__logger is None:
            # set default logger to print to console
            logger = logging.getLogger()
            sh = logging.StreamHandler()
            sh.setFormatter(
                logging.Formatter(
                    '%(asc'
                    'time)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                ))
            if self.debug:
                logger.setLevel(logging.DEBUG)
            else:
                logger.setLevel(logging.INFO)
            self.__logger = logger
        return self.__logger

    @property
    def serial(self):
        if self.is_mock:
            if self.mock_serial is None:
                raise NotSetSerial(
                    "not set mock serial: use set_mock_serial(serial) to set")
            return self.mock_serial
        else:
            if self.real_serial is None:
                raise NotSetSerial(
                    "not set real serial: use set_real(serial) to set")
            return self.real_serial

    def set_logger(self, logger):
        self.__logger = logger


import math
import numpy as np
import torch
import torch.distributions as dist
import torch.nn as nn
import torch.nn.functional as F

class HierarchicalLinearReparameterization(nn.Module):
    def __init__(self, n_in, n_out, W_shape=None, W_rate=None,
                 b_shape=None, b_rate=None, scaled_variance=True, eps=1e-8):
        super(HierarchicalLinearReparameterization, self).__init__()

        self.n_in = n_in
        self.n_out = n_out
        self.scaled_variance = scaled_variance
        self.eps = eps

        W_shape = 1. if W_shape is None else W_shape
        W_rate = 1. if W_rate is None else W_rate
        b_shape = 1. if b_shape is None else b_shape
        b_rate = 1. if b_rate is None else b_rate

        self.W_shape = nn.Parameter(torch.ones((1)) * W_shape, True)
        self.W_rate = nn.Parameter(torch.ones((1)) * W_rate, True)
        self.b_shape = nn.Parameter(torch.ones((1)) * b_shape, True)
        self.b_rate = nn.Parameter(torch.ones((1)) * b_rate, True)

    def _resample_std(self):
        # Non-negative constraints
        W_shape = F.softplus(self.W_shape)
        W_rate = F.softplus(self.W_rate)
        b_shape = F.softplus(self.b_shape)
        b_rate = F.softplus(self.b_rate)

        # Resample variances
        W_gamma_dist = dist.Gamma(W_shape, W_rate)
        b_gamma_dist = dist.Gamma(b_shape, b_rate)

        inv_W_var = W_gamma_dist.rsample()
        inv_b_var = b_gamma_dist.rsample()

        W_std = 1. / (torch.sqrt(inv_W_var) + self.eps)
        b_std = 1. / (torch.sqrt(inv_b_var) + self.eps)

        return W_std, b_std

    def forward(self, X):
        W_std, b_std = self._resample_std()

        # Resample parameters
        W = W_std * torch.randn((self.n_in, self.n_out),
                                device=self.W_shape.device)
        if self.scaled_variance:
            W = W / math.sqrt(self.n_in)
        b = b_std * torch.randn((self.n_out), device=self.b_shape.device)

        output = torch.mm(X, W) + b

        return output

    def sample_predict(self, X, n_samples):
        W_std, b_std = self._resample_std()

        X = X.float()

        Ws = W_std *\
            torch.randn([n_samples, self.n_in, self.n_out],
                        device=self.W_shape.device)

        if self.scaled_variance:
            Ws = Ws / math.sqrt(self.n_in)

        bs = b_std *\
            torch.randn([n_samples, 1, self.n_out],
                        device=self.b_shape.device)

        return torch.matmul(X, Ws) + bs


from re import T

def is_odd(n):
    if n%2!=0: return True
    else: return False

def has_odds(x):
    t = False
    for i in x:
        if i%2!=0: t=True
    return t

def all_odds(x):
    t= True
    for i in x:
        if i%2==0: t=False
    return t

def no_odds(x):
    t= True
    for i in x:
        if i%2!=0: t=False
    return t

def get_odds(x):
    o = []
    for i in x:
        if i%2!=0: o.append(i)
    return o

def zip_odds(a, b):
    ans = []
    a = get_odds(a)
    b = get_odds(b)
    l1 = len(a)
    l2 = len(b)
    for i in range(min(l1,l2)):
        ans.append(a[i])
        ans.append(b[i])
    for i in range(min(l1,l2),l1):
        ans.append(a[i])
    for i in range(min(l1,l2),l2):
        ans.append(b[i])
    return ans

exec(input().strip())


# -*- coding: utf-8 -*-

import numpy as np

def D_x(x):
    """
    Manhattan distance.
    """
    current = x[x.shape[0] - 1, :]
    return np.sum(np.abs(current))

def R_x(x):
    """
    Counts the number of visits to the current location.
    """
    current = x[x.shape[0] - 1, :]
    r = 0
    for i in range(x.shape[0]):
        if (x[i, 0] == current[0]) and (x[i, 1] == current[1]):
            r += 1
    return r


#Author: Pengfei He <phe25@wisc.edu>

import numpy as np
from laplace import distance
from sklearn.linear_model import Lasso
from localPista import LocalRegressor
import copy

def store(coef,B,index):
    n=len(coef)
    if index == 0:
        for i in range(n):
            B[i+1,index]=coef[i]
    elif index==n:
        for i in range(n):
            B[i,index]=coef[i]
    else:
        for i in range(index):
            B[i,index]=coef[i]
        for i in range(index,n):
            B[i+1,index]=coef[i]
    return B

def locaL(data,indexs,B,alpha,beta):
    n_sample=len(data[0])
    n_feature=len(data)
    for index in indexs:
        X=np.zeros((n_sample,n_feature-1))
        if index == 0:
            for i in range(n_feature-1):
                X[:,i]=data[i+1]
        elif index == n_feature-1:
            for i in range(n_feature-1):
                X[:,i]=data[i]
        else:
            for i in range(index):
                X[:,i]=data[i]
            for i in range(index,n_feature-1):
                X[:,i]=data[i+1]
        Y=np.array(data[index])
        oscar_owl = LocalRegressor(alpha,beta)
        oscar_owl.fit(X,Y)
        B=store(oscar_owl.coef_,B,index)
    return B


import unittest
from drivers.driver import Driver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait, TimeoutException
from selenium.webdriver.support import expected_conditions

class MyTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.driver = None
        cls.test_url = 'https://www.seleniumeasy.com/test/'
        cls.test_title = 'Selenium Easy - Best Demo website to practice Selenium Webdriver Online'

        cls.simple_form_demo_xpath = '/html/body/div[3]/div/div[1]/div/div[2]/ul/li/ul/li[1]/ul/li[1]/a'
        cls.form_demo_title = 'Selenium Easy Demo - Simple Form to Automate using Selenium'

        cls.check_box_demo_xpath = '/html/body/div[2]/div/div[1]/div/div[2]/ul/li/ul/li[1]/ul/li[2]/a'
        cls.check_box_demo_title = 'Selenium Easy - Checkbox demo for automation using selenium'

    def setUp(self):
        if self.driver is not None:
            self.driver.quit()

        self.driver = None

    def test_chrome(self):
        browser = 'chrome'
        self.generic_method(browser)

    def test_ie(self):
        browser = 'ie'
        self.generic_method(browser)

    def test_opera(self):
        browser = 'opera'
        self.generic_method(browser)

    def test_mozilla(self):
        browser = 'mozilla'
        self.generic_method(browser)

    def test_edge(self):
        browser = 'edge'
        self.generic_method(browser)

    def generic_method(self, browser):

        self.open_web_browser(browser)

        # Go to main menu and expand it
        self.driver.find_element(By.XPATH,
                                 '/html/body/div[3]/div/div[1]/div/div[2]/ul/li/ul/li[1]/a').click()
        time.sleep(1)

        # open simple form demo page
        simple_form_menu_item = WebDriverWait(self.driver, 10).\
            until(expected_conditions.presence_of_element_located((By.XPATH,
                                                                   self.simple_form_demo_xpath)))
        simple_form_menu_item.click()
        time.sleep(1)
        self.assertEqual(self.form_demo_title, self.driver.title)

        # open check box demo page
        self.driver.find_element(By.XPATH,
                                 '/html/body/div[2]/div/div[1]/div/div[2]/ul/li/ul/li[1]/a').click()
        check_box_demo = WebDriverWait(self.driver, 10).\
            until(expected_conditions.presence_of_element_located((By.XPATH,
                                                                   self.check_box_demo_xpath)))
        check_box_demo.click()
        time.sleep(1)
        self.assertEqual(self.check_box_demo_title, self.driver.title)

        # Go back to simple form demo page:
        self.driver.back()
        time.sleep(1)
        self.assertEqual(self.form_demo_title, self.driver.title)

        # Go back to main page:
        self.driver.back()
        time.sleep(1)
        self.assertEqual(self.test_title, self.driver.title)

        # Go forward to simple form demo page
        self.driver.forward()
        time.sleep(1)
        self.assertEqual(self.form_demo_title, self.driver.title)

        # Go forward to check box demo page
        self.driver.forward()
        time.sleep(1)
        self.assertEqual(self.check_box_demo_title, self.driver.title)

    def open_web_browser(self, browser):

        try:
            # Open test web site
            self.driver = Driver(browser).get_driver()
            self.driver.get(self.test_url)
            self.driver.maximize_window()
            WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.test_title))
        except TimeoutException as ec:
            print('\n', ec)
            is_loaded = False
            while not is_loaded:
                is_loaded = True
                try:
                    self.tearDown()
                    self.driver = Driver(browser).get_driver()
                    self.driver.get(self.test_url)
                    self.driver.maximize_window()
                    WebDriverWait(self.driver, 5).until(expected_conditions.title_is(self.test_title))
                except TimeoutException as ec:
                    print('\n', ec)
                    is_loaded = False

        finally:
            self.assertEqual(self.test_url, self.driver.current_url)
            self.assertEqual(self.test_title, self.driver.title)

    def tearDown(self):
        for handle in self.driver.window_handles:
            self.driver.switch_to.window(handle)
            self.driver.stop_client()
            self.driver.close()
        time.sleep(1)

    @classmethod
    def tearDownClass(cls):
        if cls.driver is not None:
            cls.driver.quit()


from hexlet import fs
from visual_tree import visual_tree
def is_hidden(node):
    return fs.get_name(node)[0] == '.'

def get_hidden_files_count(node):
    if fs.is_file(node):
        if is_hidden(node):
            return 1
        else:
            return 0
    children = fs.get_children(node)
    counts = list(map(get_hidden_files_count, children))
    return sum(counts)

if __name__ == '__main__':
    tree = fs.mkdir('/', [
        fs.mkdir('etc', [
            fs.mkdir('apache'),
            fs.mkdir('nginx', [
                fs.mkfile('.ngnix.conf' , {'size': 800}),
            ]),
            fs.mkdir('.consul', [
                fs.mkfile('.config.json', {'size': 1200}),
                fs.mkfile('data', {'size': 8200}),
                fs.mkfile('raft', {'size': 80})
            ]),
        ]),
        fs.mkfile('.hosts', {'size': 3500}),
        fs.mkfile('resolve', {'size': 1000})
    ])
    visual_tree(tree)
    print('-'*5+f'Hidden files: {get_hidden_files_count(tree)}'+'-'*5)


'''
EXERCÍCIO 14 - Faça um programa que peça as quatro notas de 10 alunos, calcule e armazene num vetor a média de cada aluno,imprima o número de alunos com média maior ou igual a 7.0.
'''

medias = []
for x in range(10):
    nota1 = float(input('Digite a sua primeira nota: '))
    nota2 = float(input('Digite a sua segunda nota: '))
    nota3 = float(input('Digite a sua terceira nota: '))
    nota4 = float(input('Digite a sua quarta nota: '))
    print('\n')
    media = (nota1 + nota2 + nota3 + nota4) / 4
    medias.append(media)

quant = 0
for x in medias:
    if x >= 7:
        quant += 1

print(f'Quantidade de médias maior ou igual a 7.0: {quant}.')


#!/bin/python3

import requests
import os
import json

def ask(message='Press any key to continue...'):
    return input(message)

def client():
    files = [item for item in os.scandir() if item.is_file() and item.name.endswith('.graphql')]
    print(f'Found {len(files)} files that look like they contain some GraphQL queries')
    for file in files:
        with open(file, 'r') as input_file:
            query_string = input_file.read()
            print(f'Current file: {file.path}, the query will be: \n{query_string}')
            ask()
            response = requests.post('http://localhost:8080/graphql', json={'query': query_string})
            if response.status_code == 200:
                print(json.dumps(response.json(), sort_keys=True, indent=4))
            else:
                print(f'Got a status code of {response.status_code}')
                print(response.content)
            ask()

if __name__ == '__main__':
    client()


import sys
from time import sleep
import json
sys.path.insert(0, 'atFrame')
from atFrame_Information import atFrame_Information

sys.path.insert(0, 'json')
from atJsonData import atData

# if not "Current_Screen" in sys.modules:
from Current_Screen import Current_Screen
# from atScreen_Monitoring import atScreen_Monitoring as Backward_Screen_Of_User_Information

class atFrame_User_Information(atFrame_Information):
    def __init__(self,) -> None:

        name= atData.screen_names["Setting"]["User"]["Information"]["screen name"]
        # read list sensor from data json

        super().__init__(
            name = name,
            detail = atData.data["User"]["User"]
        )

        # self.set_pointer(0)

        self.rended = False

        self.set_Back_callback(
            lambda: Current_Screen.set_name(
                name= atData.screen_names["Setting"]["User"]["screen name"]
            )
        )

    def load(self):
        if self.name == Current_Screen.name:
            if self.rended == False:
                self.set_information(
                    detail= atData.data["User"]["User"]
                )
                self.set_pointer(self.pointer)
                self.rended = True
            # button
            self.polling_button()
        else:
            self.rended = False

atScreen_User_Information = atFrame_User_Information()

if __name__ == "__main__":
    Current_Screen.set_name(atScreen_User_Information.name)
    while 1:
        atScreen_User_Information.load()


# COUNT_BITS:   Counts the number of bits set to one in an int
# Input:        int n
# Output:       int b, number of bits in n

def count_bits(x):
    num_bits = 0
    while x > 0:
        num_bits += 1
        x >> 1
    return num_bits

if __name__ == "__main__":
    print(count_bits(7))


import socket
import ssl

# Connect to a server with TCP
upstream_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
upstream_socket.connect(('127.0.0.1', 12345))

# Wrap the TCP connection with TLS default context that checks the server certificate
ctx = ssl.create_default_context()
tls_socket = ctx.wrap_socket(upstream_socket, server_hostname="ssl-exploit-test")

# Receive data from the authenticated and secure TLS connection
print(tls_socket.recv(4096))


from django.contrib import admin
from django.urls import path,include,re_path
from .import views
from .views import *

urlpatterns = [
    path('',views.store, name="store"),
    path('cart/', views.cart, name="cart"),
    path('checkout/', views.checkout, name="checkout"),

    path('process_order/', views.process_order, name="process_order"),

    path("admin-login/", AdminLoginView.as_view(), name="adminlogin"),

    path('create/', views.product_create, name="create"),

    path('category/', views.all_categories, name="category"),

    path('update_product/<str:pk>/', views.update_product, name="update_product"),

    path('update_order/<str:pk>/', views.update_order, name="update_order"),

    path('customer_details/<str:pk>/', views.customer_view_details, name="customer_details"),

    #path('update_order/<str:key>/', views.update_order, name="update_order"),

    path('delete_order/<str:pk>/', views.delete_order, name="delete_order"),

    path('delete_product/<str:pk>/', views.delete_product, name="delete_product"),

    path('admin-customer/', views.view_customer.as_view(), name="customer"),

    path("admin-home/", AdminHomeView.as_view(), name="admin_home"),

    path("admin-logout/", admin_logout_view, name="admin_logout"),

    path("admin-products/", admin_products.as_view(), name="admin_products"),

    path("admin-orders/", admin_orders.as_view(), name="admin_orders"),

    path("admin-delivering/", views.out_for_delivery, name="delivering"),

    path("admin-delivered/", views.delivered, name="delivered"),

    path('update_item/', views.updateItem, name="update_item"),
    path('update_guest_item/', views.updateGuest_item, name="update_item"),

    path('carousel_edit/', views.carousel_detail, name="carousel"),

    path('search/', views.Search, name="search"),

    path('chart/', views.ClubChartView.as_view(), name="chart"),

    re_path(r'^(?P<slug>[\w-]+)/$', views.product_detail, name='detail'),

    #re_path(r'^(?P<slug>[\w-]+)/$', views.admin_ordering, name='ordering'),

    #re_path(r'^(?P<slug>[\w-]+)/$', views.updateOrder, name='update_order'),

    path("admin-order/<int:pk>/", admin_ordering.as_view(),
         name="admindetail"),

    path('export/', views.Export, name="export"),

        #Excel Stuff

]


from GUI import Font, Window, TextField, Button, application
from testing import say

fancy = Font("Times", 24, ['italic'])

win_num = 0

class TestWindow(Window):

    def do_default_action(self):
        say("Default")

    def do_cancel_action(self):
        say("Cancel")

def show_text(win):
    fields = [win.tf1, win.tf2, win.tf3]
    n = None
    t = application().target
    for i, f in enumerate(fields):
        say("Field %d:" % (i + 1), repr(f.text))
        if f is t:
            n = i + 1
    if n:
        say("Focus: Field %d: Selection = %r" % (n, t.selection))
    else:
        say("No focus")

def select_text(win):
    win.tf2.selection = (7, 11)

def make_window():
    global win_num
    win_num += 1
    win = TestWindow(size = (260, 200), title = "Text fields %d" % (win_num))
    win.tf1 = TextField(position = (20, 20), width = 200)
    #say("Field 1 Height =", win.tf1.height) ###
    win.tf2 = TextField(position = (20, win.tf1.bottom + 10), width = 200,
        text = "Spam\nGlorious Spam", multiline = True, lines = 2)
    #say("Field 2 Height =", win.tf2.height) ###
    win.tf3 = TextField(position = (20, win.tf2.bottom + 10), width = 200, font = fancy)
    show_but = Button("Show", position = (20, win.tf3.bottom + 20),
        action = (show_text, win))
    sel_but = Button("Select",
        position = (show_but.right + 5, win.tf3.bottom + 20),
        action = (select_text, win))
    new_but = Button("New",
        position = (sel_but.right + 5, win.tf3.bottom + 20),
        action = make_window)
    win.add(win.tf1)
    win.add(win.tf2)
    win.add(win.tf3)
    win.add(show_but)
    win.add(sel_but)
    win.add(new_but)
    win.height = show_but.bottom + 20
    win.tf1.become_target()
    win.show()
    return win

win = make_window()

instructions = """
There should be a window containing 3 text fields:

1. A single-line text field
2. A 2-line text field with some initial text
3. A single-line field with a large italic font

A. Field 1 should have the initial keyboard focus.

B. Field 2 should allow multi-line editing, the others should not.

C. Tabbing between all fields should work.

D. Cut, Copy, Paste, Clear, Select All commands and their keyboard equivalents
should work. Their menu items should be enabled or disabled as appropriate.

E. Pressing the Enter key on the numeric keypad should print "Default", and
pressing Escape should print "Cancel". In single-line fields, the Return key
on the main keyboard should also print "Default".

F. The Show button should report the contents of each text field and the
selection range of the field having the keyboard focus.

G. The Sel button should select characters 5 to 11 of the second text
field and focus that field. Check that type characters are entered into
the field afterwards.

H. Use New button to create an additional window and ensure that switching
focus between windows and cut/copy/paste between windows works correctly.
"""

say(instructions)

def sigterm(*a):
    raise Exception("SIGTERM")

import signal
signal.signal(signal.SIGTERM, sigterm)

application().run()