예제 #1
0
 def save_question(q):
     try:
         data = load(QUESTIONS_FILENAME)
     except FileNotFoundError:
         data = []
     data.append(q)
     save(QUESTIONS_FILENAME, data)
예제 #2
0
파일: qt.py 프로젝트: zudzuka/VKFaceMash
 def closeEvent(self, event):
     reply = QtGui.QMessageBox.question(self, 'Message',
         "Are you sure to quit?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
     if reply == QtGui.QMessageBox.Yes:
         functions.save(self.person)
         event.accept()
     else:
         event.ignore()
예제 #3
0
def run(n, group_path, plotFlag, saveFlag):

    # Loading setups configurations
    config = setup()

    #rm-list_resources() to find address for smu
    address_2612b = 26
    address_2400 = 24

    clear_all()

    #running tests (smua measures iv and smub measures r)

    [smu_2612b, smu_2400, rm] = gpib(address_2612b, address_2400)

    [readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led,
     readingsR] = SelfHeating(smu_2612b, smu_2400, config[0], config[1],
                              config[2], config[3], config[4], config[5],
                              config[6], config[7], config[8], config[9],
                              config[10], config[11], config[12], config[13],
                              config[14], config[15], config[16], config[17],
                              config[18], config[19], config[20], config[21])

    smu_2612b.write('reset()')

    smu_2612b.write('smua.nvbuffer1.clear()')
    smu_2612b.write('smub.nvbuffer1.clear()')
    smu_2400.write('*CLS')

    rm.close

    Number = []
    led_power = []
    for i in range(0, len(readingsR)):
        Number.append(i)
        led_power.append(readingsV_led[i] * readingsI_led[i])

    if plotFlag == 1:
        graphR = plot(Number, readingsR, 'N', 'R', 1)
        graphIV = plot(readingsI_led,
                       readingsI_sipm,
                       'Iled',
                       'Isipm',
                       2,
                       log=True,
                       errorbars_2612=True)
        graphIVLed = plot(readingsV_led, readingsI_led, 'Vled', 'I', 3)

    else:
        graphR = 'NULL'
        graphIV = 'NULL'

    if saveFlag == 1:
        save(readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led,
             readingsR, graphIV, graphR, n, group_path)

    return
예제 #4
0
    async def remove_cringe_word(self, ctx, word=None):
        if not word:
            return await ctx.send("Include in a word maybe???")

        cringe_words = functions.load("cringe_word_list.json")
        try:
            cringe_words.remove(word)
            functions.save("cringe_word_list.json", cringe_words)
            await ctx.send(f"`{word}` removed from cringe word list!")
        except:
            await ctx.send(f"`{word}` not in cringe word list!")
예제 #5
0
    async def add_cringe_word(self, ctx, word=None):
        if not word:
            return await ctx.send("Include in a word maybe???")

        cringe_words = functions.load("cringe_word_list.json")
        if word not in cringe_words:
            cringe_words.append(word)
            functions.save("cringe_word_list.json", cringe_words)
            await ctx.send(f"`{word}` added to cringe word list!")
        else:
            await ctx.send(f"`{word}` in cringe word list already!")
예제 #6
0
async def on_message(message):
    user = "******" + str(message.author.id) + ">"
    embed = discord.Embed(title="Sent to VK!",
                          description="Поздравляем, " + user,
                          colour=discord.Colour.blue())
    if message.channel.name == "success":
        if message.attachments:
            data = message.attachments[0].url
            if isImage(data) in ok_photos:
                save(data)
                send_vk(message.author.name, token, group_id, album_id)
                await message.channel.send(embed=embed)
예제 #7
0
def main():
    torch.manual_seed(43)

    criterion = nn.CrossEntropyLoss()
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    train_loader, test_loader = data_loaders()

    model = FNN_ID(750).to(device)
    optimizer = optim.Adam(model.parameters())

    train(model, device, train_loader, criterion, optimizer)
    test(model, device, test_loader, criterion)
    save(model)
예제 #8
0
def parse_cmd(cmd):
    """Checks if a command is a builtin like help or quit and handles it, otherwise passes it to eval_cmd()"""
    # TODO make these functions in functions.py instead of here?
    # will fix misleading error message, e.g. "command exit not found" (since it goes to the final else and technically it isn't a function in functions.py)
    if cmd.strip() == "exit" or cmd.strip() == "quit":
        if data.opened_file is not None:
            if ask("Save unsaved changes to {}?".format(data.opened_file)):
                functions.save()
        print("Thank you for using Macrosoft Axel '88. Your license expires in 2 minutes.")
        exit()
    elif cmd.strip() == "help":
        do_help()
    else:
        eval_cmd(cmd)
예제 #9
0
def main():
    config = recibe_args()
    pdf = FPDF()
    quotes = I.QuoteAndImage()
    G.plots()
    f.createPdf(pdf)
    if config.Phoebe:
        f.addImagesPdf(pdf, "OUTPUT/Phoebe.jpg", quotes[' Phoebe'], 'Phoebe')
    elif config.Joey:
        f.addImagesPdf(pdf, "OUTPUT/Joey.jpg", quotes[' Joey'], 'Joey')
    elif config.Monica:
        f.addImagesPdf(pdf, "OUTPUT/Monica.jpg", quotes[' Monica'], 'Monica')
    elif config.Rachel:
        f.addImagesPdf(pdf, "OUTPUT/Rachel.jpg", quotes[' Rachel'], 'Rachel')
    elif config.Ross:
        f.addImagesPdf(pdf, "OUTPUT/ross.jpg", quotes[' Ross'], 'Ross')
    elif config.Chandler:
        f.addImagesPdf(pdf, "OUTPUT/Chandler.jpg", quotes[' Chandler'],
                       'Chandler')
    else:
        pdf.image('OUTPUT/lines_episode.png', x=30, y=50, w=150)
        pdf.ln(160)
        pdf.cell(170, 20, txt="Rachel is the most talkative one", align='C')
        pdf.add_page()
        pdf.image('OUTPUT/mean_lines.png', x=10, y=20, w=150)
        pdf.ln(150)
        pdf.image('OUTPUT/mean_lines_season.png', x=20, y=120, w=150)
        pdf.add_page()
        pdf.image('OUTPUT/mean_words.png', x=20, y=30, w=150)
        pdf.cell(170, 20, txt="Phoebe says more words per line", align='C')
        pdf.ln(150)
        pdf.image('OUTPUT/Rating.png', x=20, y=130, w=150)

    print('Pdf report with results saved in the Output folder')
    f.save(pdf)

    if config.mailto:
        E.SendEmail(config.mailto)
        print('Sending Email')
예제 #10
0
def upload():
    try:
        data = request.files
        file = data.get('image')
        image_urlpath = save(file)
        image = Images(image=image_urlpath[0], small=image_urlpath[1],
         medium=image_urlpath[2], large=image_urlpath[3], x_large=image_urlpath[4])
        db.session.add(image) 
        db.session.commit()
         
        return "images added succefull"
    except Exception as e:
        print({'message': e})
        return "failed"
예제 #11
0
파일: tests.py 프로젝트: PostPushr/web
def run_simple():
	import hashlib
	import functions
	import datetime

	body = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
	user = "******"
	message = {"to": {"prefix": "Dear", "name": "Test User"}, "_from": {"prefix": "Sincerely,", "name": "Yasyf Mohamedali"}, "body": body}

	to_address = functions.lob.Address.create(name=message["to"]["name"], address_line1='104 Printing Boulevard', address_city='Boston', address_state='MA', address_country='US', address_zip='12345')
	from_address = functions.lob.Address.create(name=message["_from"]["name"], address_line1='1234 Candyland Drive', address_city='Vancouver', address_state='BC', address_country='CA', address_zip='V1Y 7E2')

	message["to"]["address"] = functions.format_address(to_address)
	message["_from"]["address"] = functions.format_address(from_address)

	obj_loc = functions.save(functions.render_text(message), hashlib.md5(user).hexdigest())

	return "http://"+os.environ['domain']+"/"+obj_loc
예제 #12
0
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if int(message.author.id) not in authorized:
        func.add_score(message.author.id,1,1,fliving)

    # Makes sure the player is still alive or at least signed up (we do not want to give any spoilers!)
    if func.is_still_alive(message.author,fdata) and not int(message.author.id) in authorized:
        return

    if message.server == client.get_server("436257067573968908") and not message.channel == client.get_channel(play_zone) and message.content.startswith('!') and not int(message.author.id) in authorized:
        answer = await client.send_message(message.channel,"Wrong channel, buddy! Please go to <#{}> or to my DMs to play with the bot.".format(play_zone))
        await asyncio.sleep(10)
        await client.delete_message(answer)
        return

    # ----------------------------------------
    #               HELP
    # ----------------------------------------
    if message.content.startswith('!h') and not (message.channel == client.get_channel(game_log) or message.channel == client.get_channel(stock_market)):
        msg = ''
        args = message.content.split(' ')

        if len(args) == 1:
            msg += '`!balance` - View the balance of a user\n'
            msg += '`!buy` - Buy certain items'
            msg += '`!description` - View the meaning of all emojis\n'
            msg += '`!market` - View the market\n'
            msg += "`!retract` - Retract certain offers or requests you've made\n"
            msg += '`!sell` - Sell certain items\n'
            if int(message.author.id) in authorized:
                msg += '\n\n**Admin commands:**\n'
                msg += '`!kill` - Kill a player, effectively allowing them to participate on the market.\n'
                msg += '`!redeem` - Redeem a coin and make it invalid\n'
            msg += '\n To view the specific documentation of a command, please type `!help <command>`.'

        elif args[1].startswith('ba'):
            msg += '`!balance` - View your own balance.\n'
            msg += '`!balance <user>` - View the balance of a specific user. The user is a mention.'
        elif args[1].startswith('bu'):
            msg += '`!buy <emoji> <amount>` - Buy a certain emoji for a certain amount.'
        elif args[1].startswith('d'):
            msg += '`!description` - Get an explanation of what certain emojis mean.\n'
            msg += 'If a desciption reads **Player coin**, that means that the emoji is redeemed when the corresponding player dies.'
        elif args[1].startswith('m'):
            msg += '`!market` - See an overview of the whole market.\n'
            msg += '`!market <emoji> - See an overview of the market of a specific emoji. Make sure the emoji exists on the market.`'
        elif args[1].startswith('ret'):
            msg += "`!retract` - Retract all offers and requests you've made on the whole market.\n"
            msg += "`!retract` - Retract all offers and requests you've made on a specific emoji."
        elif args[1].startswith('s'):
            msg += '`!sell <emoji> <amount>` - Sell a certain emoji for a certain amount.'
        elif args[1].startswith('k'):
            if int(message.author.id) in authorized:
                msg += '`!kill <user> <emoji> <amount>` - Kill a user that got voted out by `<amount>` players. The user had `<emoji>` as their emoji in the game.'
            else:
                msg += "You're not even an admin! Why bother looking up this command?"
        elif args[1].startswith('red'):
            if int(message.author.id) in authorized:
                msg += '`!redeem <emoji> <amount>` - Remove a given emoji from the market, and pay all users a given amount for each emoji they had left.'
            else:
                msg += "You're not even an admin! Why bother looking up this command?"
        else:
            msg += "I am terribly sorry! I did not understand what command you meant to type!\n"
            msg += "Please type `!help` for help."

        await client.send_message(message.channel,msg)



    # ----------------------------------------
    #               DESCRIPTION
    # ----------------------------------------
    if message.content.startswith('!d'):
        await client.send_message(message.channel,func.show_desc(femoji))

    # ----------------------------------------
    #               KILL FUNCTION
    # ----------------------------------------
    if int(message.author.id) in authorized and message.content.startswith('!kill') and len(message.mentions) > 0:

        if len(message.content.split(' ')) != 4:
            await client.send_message(message.channel,"**Invalid syntax:**\n\n`!kill <player> <emoji> <amount>`.\n\nExample: `!kill @Randium#6521 😏 12`")
            return


        currency = message.content.split(' ')[2]
        amount = message.content.split(' ')[3]

        if not func.check_for_int(amount):
            await client.send_message(message.channel,"**ERROR:** Invalid amount!")
            return

        amount = int(amount)
        victim = message.mentions[0]

        if int(victim.id) in authorized:
            await client.send_message(message.channel,"I am terribly sorry, but I can't kill an admin! That'd be treason.")
            return

        await client.send_message(client.get_channel(bot_spam),"Are you sure you want to kill <@{}>?\nPlease type `Yes` to confirm.".format(victim.id))

        if func.isvalid(currency,femoji):
            await client.send_message(client.get_channel(bot_spam),"Careful! The emoji you gave up is still valid! You can override by typing `Yes`, but I would advise saying `No`!")
            await client.send_message(client.get_channel(bot_spam),"You can override emojis by typing `!redeem {} <amount>`.".format(currency))

        response = await client.wait_for_message(author = message.author,channel = client.get_channel(bot_spam))

        if not response.content[0] in ['y', 'Y']:
            await client.send_message(response.channel,"Kill function canceled.")
            return

        msg, money = func.kill(victim,fdata,fliving,femoji)
        await client.send_message(client.get_channel(bot_spam),msg)
        if msg[-1] == '!':
            msg = "Hey there, buddy! It seems like you have died!\n"
            msg += "Though the game may be over for you as a living player, it will still be very interesting for you while you're dead!"
            msg += " How so? Well, it is time to use your knowledge about the game to become the richest ghost of all!\n"
            msg += "Players weren't allowed to use the :ghost: emoji as their avatar. Why not? Because that emoji now has a meaning to the dead - it's ectoplasm."
            msg += " The money of the dead.\n\n"
            msg += "See, every player, every team has a type of coin. When a player dies, their coins will be exchanged for money."
            msg += " For example, when you died, your {} coin was exchanged for money.".format(currency)
            msg += " How much? Well, in total, {} players voted to kill you, so every player gained {} ectoplasm for each {} coin they had.\n\n".format(amount,100*amount,currency)
            msg += "Because of your activity, you will gain {} ectoplasm and 10 of every coin as a starter pack.".format(money)
            msg += " Buy and sell these coins on the market to get rich! The player who has the most ectoplasm at the end of the game, wins a special victory badge! Enjoy!"
            await client.send_message(victim,msg)
            await client.send_message(client.get_channel(game_log),"<@{}> has been killed.".format(victim.id))
        return

    # ----------------------------------------
    #               REDEEM COINS
    # ----------------------------------------
    if int(message.author.id) in authorized and message.content.startswith('!red'):
        if len(message.content.split(' ')) != 3:
            await client.send_message(message.channel,"**Invalid syntax:**\n\n`!redeem <emoji> <amount>`.\n\nExample: `!redeem 😏 12`")
            return

        currency = message.content.split(' ')[1]
        amount = message.content.split(' ')[2]

        if not func.check_for_int(amount) or not func.isvalid(currency,femoji):
            await client.send_message(message.channel,"**Invalid syntax:**\n\n`!redeem <emoji> <amount>`.\n\nExample: `!redeem 😏 12`")
            return

        amount = int(amount)

        await client.send_message(client.get_channel(bot_spam),"Are you sure you want to exchange the {} coin for {} ectoplasm?\nPlease type `Yes` to confirm.".format(currency,amount))

        response = await client.wait_for_message(author = message.author,channel = client.get_channel(bot_spam))

        if not response.content[0] in ['y', 'Y']:
            await client.send_message(response.channel,"Money redeem function canceled.")
            return

        score_table = func.import_data(fdata)

        for user in score_table:
            target = await client.get_user_info(user[0])
            user_amount = user[func.position(currency,femoji)]

            func.retract_emoji(target,currency,fmarket,femoji,fdata)

            user[1] = int(user[1]) + amount * int(user_amount)
            if int(user_amount) > 0:
                await client.send_message(target,"The emoji {} has been redeemed for {} ectoplasm! You had {} emojis, meaning that you gained {} coins.".format(currency,amount,user_amount,int(user_amount)*amount))
            user[func.position(currency,femoji)] = 0

        func.save(score_table,fdata)

        emojis = func.import_data(femoji)
        emojis[func.position(currency,femoji)-2][0] = 'N'
        func.save(emojis,femoji)

        await client.send_message(client.get_channel(game_log),"The emoji {} has been redeemed for {} ectoplasm.".format(currency,amount))
        print("The emoji {} has been cleared succesfully.".format(currency))
        await client.send_message(client.get_channel(bot_spam),"The emoji {} has been succesfully redeemed for {} per emoji!".format(currency,amount))
        return

    # ----------------------------------------
    #               BALANCE
    # ----------------------------------------
    if message.content.startswith('!ba'):
        target = message.author

        if len(message.mentions) > 0:
            if len(message.mentions) > 1:
                await client.send_message(message.channel,"Whoah, dude! One person at a time, please!")
                asyncio.sleep(2)
                await client.send_message(message.channel,"Showing you the results for {}...".format(message.mentions[0]))
            target = message.mentions[0]
            print('{} has requested the balance of {}.'.format(message.author,message.mentions[0]))
        else:
            print('{} has requested the balance of themselves.'.format(message.author))

        await client.send_message(message.channel,func.make_balance(target.id,fdata,femoji,target))
        return

    # ----------------------------------------
    #               MARKET
    # ----------------------------------------
    if message.content.startswith('!m'):

        # When a specific emoji has been chosen.
        if len(message.content.split(' ')) > 1:

            emoji = message.content.split(' ')[1]

            if func.isvalid(emoji,femoji) == True:
                await client.send_message(message.channel,func.make_market_branch(emoji,fmarket))
            else:
                await client.send_message(message.channel,"I am terribly sorry! I couldn't recognize the emoji `{}`.".format(emoji))

            return

        await client.send_message(message.channel,func.make_complete_market(femoji,fmarket))

    # ----------------------------------------
    #               BUY STUFF
    # ----------------------------------------
    if message.content.startswith('!bu'):

        message_table = message.content.split(' ')

        # Find all the valid emojis. If not, end with syntax error.
        if len(message_table) != 3:

            await client.send_message(message.channel,"**Invalid syntax:**\n\n`!buy <emoji> <amount>`.\n\nExample: `!buy {} 1`".format(func.import_data(femoji)[0][0]))
            return

        if func.check_for_int(message_table[1]) == True and func.isvalid(message_table[2],femoji) == True:
            if int(message_table[1]) <= 0 or int(message_table[1]) > 1000000:
                await client.send_message(message.channel,"I'm sorry, your sell value is out of bounds! Please choose a reasonable amount.")
                return

            if func.count(message.author.id,1,fdata) < int(message_table[1]):
                await client.send_message(message.channel,"I'm sorry! You do not have enough money to make this deal!")
                return

            msg, person, amount = func.buy_something(message.author,message_table[2],int(message_table[1]),femoji,fmarket,fdata)
            if person != '0':
                victim = await client.get_user_info(person)
                await client.send_message(client.get_channel(stock_market),":moneybag: **{}** bought {} from **{}** for the price of {} coins!".format(message.author,message_table[2],victim,amount))
                print("{} bought {} from {} for the price of {} coins!".format(message.author,message_table[2],victim,amount))
            await client.send_message(message.channel,msg)
            return

        if func.check_for_int(message_table[2]) == True and func.isvalid(message_table[1],femoji) == True:
            if int(message_table[2]) <= 0 or int(message_table[2]) > 1000000:
                await client.send_message(message.channel,"I'm sorry, your sell value is out of bounds! Please choose a reasonable amount.")
                return

            if func.count(message.author.id,1,fdata) < int(message_table[2]):
                await client.send_message(message.channel,"I'm sorry! You do not have enough money to make this deal!")
                return

            msg, person, amount = func.buy_something(message.author,message_table[1],int(message_table[2]),femoji,fmarket,fdata)
            if person != '0':
                victim = await client.get_user_info(person)
                await client.send_message(client.get_channel(stock_market),":moneybag: **{}** bought {} from **{}** for the price of {} coins!".format(message.author,message_table[1],victim,amount))
                print("{} bought {} from {} for the price of {} coins!".format(message.author,message_table[1],victim,amount))
            await client.send_message(message.channel,msg)
            return

        await client.send_message(message.channel,"**Invalid syntax:**\n\n`!buy <emoji> <amount>`.\n\nExample: `!buy {} 1`".format(func.import_data(femoji)[0][0]))
        return

    # ----------------------------------------
    #               SELL STUFF
    # ----------------------------------------
    if message.content.startswith('!s'):

        message_table = message.content.split(' ')

        # Find all the valid emojis. If not, end with syntax error.
        if len(message_table) != 3:

            await client.send_message(message.channel,"**Invalid syntax:**\n\n`!sell <emoji> <amount>`.\n\nExample: `!sell {} 100`".format(func.import_data(femoji)[0][0]))
            return

        if func.check_for_int(message_table[1]) == True and func.isvalid(message_table[2],femoji) == True:
            if int(message_table[1]) <= 0 or int(message_table[1]) > 1000000:
                await client.send_message(message.channel,"I'm sorry, your sell value is out of bounds! Please choose a reasonable amount.")
                return

            if func.count(message.author.id,func.position(message_table[2],femoji),fdata) < 1:
                await client.send_message(message.channel,"I'm sorry! You do not have the {} at your disposal to make this deal!".format(message_table[2]))
                return

            msg, person, amount = func.sell_something(message.author,message_table[2],int(message_table[1]),femoji,fmarket,fdata)
            if person != '0':
                victim = await client.get_user_info(person)
                await client.send_message(client.get_channel(stock_market),":money_with_wings: **{}** sold {} to **{}** for {} coins!".format(message.author,message_table[2],victim,amount))
                print("{} sold {} to {} for {} coins!".format(message.author,message_table[2],victim,amount))
            await client.send_message(message.channel,msg)
            return

        if func.check_for_int(message_table[2]) == True and func.isvalid(message_table[1],femoji) == True:
            if int(message_table[2]) <= 0 or int(message_table[2]) > 1000000:
                await client.send_message(message.channel,"I'm sorry, your sell value is out of bounds! Please choose a reasonable amount.")
                return

            if func.count(message.author.id,func.position(message_table[1],femoji),fdata) < 1:
                await client.send_message(message.channel,"I'm sorry! You do not have the {} at your disposal to make this deal!".format(message_table[1]))
                return

            msg, person, amount = func.sell_something(message.author,message_table[1],int(message_table[2]),femoji,fmarket,fdata)
            if person != '0':
                victim = await client.get_user_info(person)
                await client.send_message(client.get_channel(stock_market),":money_with_wings: **{}** sold {} to **{}** for {} coins!".format(message.author,message_table[1],victim,amount))
                print("{} sold {} to {} for the price of {} coins!".format(message.author,message_table[1],victim,amount))
            await client.send_message(message.channel,msg)
            return

        await client.send_message(message.channel,"**Invalid syntax:**\n\n`!sell <emoji> <amount>`.\n\nExample: `!sell {} 100`".format(func.import_data(femoji)[0][0]))
        return
    # ----------------------------------------
    #               RETRACT
    # ----------------------------------------

    if message.content.startswith('!ret'):

        if len(message.content.split(' ')) > 1:

            emoji = message.content.split(' ')[1]

            if func.isvalid(emoji,femoji) == True:

                await client.send_message(message.channel,'Are you sure you want to retract all offers and requests of the emoji {}?\nType `Yes` to confirm, or type `No` to cancel.')
                response = await client.wait_for_message(author = message.author)

                if response.content.startswith('Y') or response.content.startswith('y'):
                    msg = func.retract_emoji(message.author,emoji,fmarket,femoji,fdata)
                    if msg != '':
                        await client.send_message(message.channel,msg)
                    await client.send_message(message.channel,"{} has been cleared!".format(emoji))
                    await asyncio.sleep(1)
                    return

                await client.send_message(message.channel,"Retraction canceled.")
                return

        await client.send_message(message.channel,'Are you sure you want to retract all offers and requests on the *WHOLE* market?\nType `Yes` to confirm, or type `No` to cancel.')
        response = await client.wait_for_message(author = message.author)

        if response.content.startswith('Y') or response.content.startswith('y'):
            for emoji in func.import_data(femoji):
                msg = func.retract_emoji(message.author,emoji[0],fmarket,femoji,fdata)
                if msg != '':
                    await client.send_message(message.channel,msg)
                await client.send_message(message.channel,"{} has been cleared!".format(emoji[0]))
                await asyncio.sleep(1)

            await client.send_message(message.channel,"All emojis have been cleared!")
            return

        await client.send_message(message.channel,"Retraction canceled.")
        return
예제 #13
0
                        print(
                            f'\n\n{subject.upper()} has NOT been added to the record books.')
                        time.sleep(1.5)
                        break
                    else:
                        new_record = pd.DataFrame(

                            {'Subject': [subject],
                             'Date': [date],
                             'Hours': [hours]
                             }
                        )
                        print(
                            '----------------------------------------------------------------------')
                        try:  # This try and except allows incorrect values such as 12/29/39
                            functions.save(new_record, historical_records)
                            # This is the back up save. Can be recovered if original data is corrupted.
                            functions.backup(historical_records)
                        except TypeError and ValueError:
                            print('Something went wrong')
                            cont = input('Press "Enter" to continue ')

                else:
                    print(
                        '----------------------------------------------------------------------')
                    track = input(f'You are about to enter that you have studied [{subject.swapcase()}] for [{hours}] hours\n'
                                  f'on [{date}]. Is this correct? [Y/n]: ').lower()
                    print(
                        '----------------------------------------------------------------------')
                    if track == 'n':
                        pass
예제 #14
0
파일: rec_test.py 프로젝트: evocell/rec
            ric_scores = functions.read_ric(ric_output)
        else:
            ric_scores = None
        if algorithm != "RIC":
            rric_scores = functions.read_ric(rric_output)
        else:
            rric_scores = None

    #Classify sequences
    result = functions.classify(algorithm = algorithm, 
            crossed_scores = crossed_scores, ric_scores = ric_scores,
            rric_scores = rric_scores, data = data, length = length)

    #Save result
    functions.save(output = args.output, result = result, 
            algorithm = algorithm, original = args.test, 
            ric_scores = ric_scores, rric_scores = rric_scores, 
            crossed_scores = crossed_scores)
    try:
        os.remove("test_crossed_" +args.output)
    except:
        pass
    try:
        os.remove("test_ric_" + args.output)
    except:
        pass
    try:
        os.remove("test_ric_results_" + args.output)
    except:
        pass
    try:
        os.remove("test_rric_results_" + args.output)
예제 #15
0
import functions
import helpers

# Asks
data = functions.askForExpenditures()
functions.printData(data)

functions.save(helpers.getMonth())

# functions.read(helpers.getMonth())
예제 #16
0
def main(random_gen, canLose, player_name):
    """ Main function. Contains the main loop of the game.

    INPUTS: 
            if True, toggles random generation (bool)
            name of the player (str)
    """

    # List of all the Blocks
    blocks = []

    # Init the player
    player = entities.Player.Player()

    # Display Setup
    WINDOW = pygame.display.set_mode((
        cfg.SIZE_X,  # Dimensions of WINDOW
        cfg.SIZE_Y))

    # Time
    CLOCK = pygame.time.Clock()

    # Inits TODO: explain variables
    chunk_num = 1  # 1 because of the init chunk
    prev_chunks_passed = 0

    chunk_times = []
    last_time = 0

    # Loads the first chunk of the map
    functions.loadChunk(blocks, levels.level[0], 0)

    # Idle screen
    # Using this to wait for the user input to start time but still picture the level
    chunk_num = idleLoop(random_gen, blocks, chunk_num, WINDOW, player)

    start_time = pygame.time.get_ticks() / 1000

    # Main loop
    over = False
    while not over:

        CLOCK.tick(20)  # 20 FPS

        for e in pygame.event.get():
            pygame.event.set_allowed(None)
            pygame.event.set_allowed((QUIT, MOUSEBUTTONDOWN, KEYDOWN))
            pygame.event.pump()

            if e.type == pygame.QUIT or (e.type == KEYDOWN and e.key
                                         == K_RETURN):  # quit condition
                over = True

        if player.rect.y + cfg.PLAYER_HEIGHT > cfg.SIZE_Y and canLose:
            over = True

        # Moves the camera if needed
        functions.camera(player, blocks)

        # Moves the player when m1 is on click
        if pygame.mouse.get_pressed()[0]:
            functions.mouse(player)

        # Moves the player
        functions.move(player, blocks)

        # Not very viable but works for that list length
        chunks_passed = 0
        for block in blocks:
            if block.type == "end" and block.rect.x < player.rect.x:
                chunks_passed += 1

        if chunks_passed == prev_chunks_passed + 1:
            current_time = pygame.time.get_ticks() / 1000 - start_time
            print("chunk n°", chunks_passed, ": ", current_time)

            chunk_times.append(round(current_time - last_time, 3))
            last_time = current_time
            prev_chunks_passed += 1

        # Loads the next chunk if needed
        chunkWasLoaded = functions.levelGeneration(random_gen, blocks,
                                                   levels.level, chunk_num)

        if chunkWasLoaded:
            chunk_num += 1

        functions.display(WINDOW, blocks, player)  # Window dispay

    # Displays the score in console
    score, chunks_passed, end_time = functions.score_func(
        current_time, player, blocks)
    print('Chunk nb:', chunks_passed, 'Time:', end_time)
    print('Score:', score)

    # Saving
    filename = os.path.join(cfg.DATA_FOLDER, cfg.DATA_FILE)
    functions.save(filename, player_name, score, chunks_passed, end_time,
                   chunk_times, levels.NB_CHUNK)
예제 #17
0
 def save_history(self):
     save(HISTORY_FILENAME, self.history)
예제 #18
0
if len(arg) == 1:
    print("\033[1;33mOlá! Bem-vindo ao Header!\033[0;0m")
    print("\033[1;32mStatus do Header: iniciado\033[0;0m" if status ==
          True else "\033[1;31mStatus do Header: não iniciado\033[0;0m")
    print("\033[1;32mPara obter ajuda no uso da ferramenta, digite:\033[0;0m")
    print("python3 header.py help")
else:
    arg.pop(0)

if status and arg[0].lower() == "w":
    print(functions.write(arg))
elif status and arg[0].lower() == "ws":
    print(functions.write_save(arg, directory))
elif status and arg[0].lower() == "s":
    print(functions.save(arg, directory))
elif status and arg[0].lower() == "c":
    print(functions.create(arg, directory))
elif not status and arg[0].lower() == "init":
    print(functions.init(directory))
elif status and arg[0].lower() == "init":
    print("Seu Header já foi iniciado!")
elif status and arg[0].lower() == "list":
    functions.list_ws(directory)
elif status and arg[0].lower() == "e":
    print(functions.edit(arg, directory))
elif status and arg[0].lower() == "d":
    print(functions.delete(arg, directory))
elif arg[0].lower() == "help":
    help("header")
예제 #19
0

classifier = KerasClassifier(build_fn=build_classifier,
                             batch_size=10,
                             epochs=300)
parameters = {'neuronN': [6, 7], 'neuronP': [6, 7]}

#sendHttp(parameters)

grid_search = GridSearchCV(estimator=classifier,
                           param_grid=parameters,
                           scoring='accuracy',
                           cv=10)
grid_search = grid_search.fit(x_train, y_train)
best_parameters = grid_search.best_params_
best_accuracy = grid_search.best_score_
print(best_parameters)
print(best_accuracy)
final = {
    "best_parameters": best_parameters,
    "best_accuracy": best_accuracy,
    "Finish": time.time()
}
#sendHttp(final)
save(str(parameters))
save(str(best_parameters))
save(str(best_accuracy))
#accurancies = cross_val_score(estimator = classifier, X = x_train, y = y_train, cv = 10, n_jobs = -1 )
#mean = accurancies.mean()
#variance = accurancies.std()
예제 #20
0
print("PyTorch Architecture: {}".format(args.arch))
print()
print("<" + "-" * 10, "Hyperparameters", "-" * 10 + ">")
print("Hidden Units: {}".format(args.hidden_units))
print("Learning Rate: {}".format(args.learning_rate))
print("Epochs: {}".format(args.epochs))
print("Batch Size: {}".format(args.batch_size))
print()

# See if the user would like to continue based on the settings
while True:
    inp = input("Do the settings above look correct? [y/n]: ")
    if inp.lower() == 'y':
        break
    else:
        exit("Adjust the settings and retry again, exiting.")

# Get the class-->name mappings
cat_names = functions.get_category_names('cat_to_name.json')

# Build a transfer learning model and optimizer with user defined settings
model, optimizer = functions.build_model(args.arch, args.hidden_units,
                                         args.learning_rate)

# Train the model
model = functions.train(model, train_data, val_data, optimizer, args.epochs,
                        args.gpu)

# Save the model
functions.save(model, args.arch, class_to_idx, cat_names, args.save_dir)
예제 #21
0
파일: game.py 프로젝트: HemaSindara/HangMan
#GAME2
#TODO: Merge  GAME1 and GAME2
    while count<values.retries:
        letter=raw_input("Type a letter: ")
        word1 = functions.goodletter(word_to_guess, letter)
        word = functions.merge(word, word1, "-")
        if word1=="-"*len(word_to_guess) and letter and len(letter)==1:
            count+=1
        if not letter or len(letter)>1:
            print "Invalid!"
        else:
            print word
        print "Left:",values.retries-count, "retries."

#win/lose
        if word==word_to_guess:
            print "You win."
            score+=count
            break
    if word!=word_to_guess:
        print "You lose.\nThe word was", word_to_guess
    print "The definition of", word_to_guess, 'is:\n',functions.getDefinition(word_to_guess)

#continue/quit/save
    answer=raw_input("Do you want to continue ? yes/no: ")
    if answer[0].lower()=='n':
        saveOrNot=raw_input("Do you want to save ? yes/no: ")
        if saveOrNot[0].lower()=='y':
            score_save={username:score}
            functions.save(values.savefile, score_save)
예제 #22
0
def run(n, test, group_path, plotFlag, saveFlag):

    # Loading setups configurations
    config = setup()

    #rm-list_resources() to find address for smu
    address_2612b = 26
    address_2400 = 24

    clear_all()

    #running tests (smua measures iv and smub measures r)

    [smu_2612b, smu_2400, rm] = gpib(address_2612b, address_2400)

    if test == 'iv':

        [readingsV_sipm, readingsI_sipm,
         readingsR] = IVComplete(smu_2612b, smu_2400, config)

        smu_2612b.write('reset()')

        smu_2612b.write('smua.nvbuffer1.clear()')
        smu_2612b.write('smub.nvbuffer1.clear()')
        smu_2400.write('*CLS')

        readingsV_sipm_neg, readingsV_sipm_pos, readingsI_sipm_neg, readingsI_sipm_pos, readingsR_neg, readingsR_pos = split(
            readingsV_sipm, readingsI_sipm, readingsR)

        number_neg = []
        number_pos = []

        for g in range(len(readingsR_neg)):
            number_neg.append(g)

        for g in range(len(readingsR_pos)):
            number_pos.append(g)

        if plotFlag == 1:
            graphR_neg = plot(number_neg,
                              readingsR_neg,
                              'N',
                              'R',
                              1,
                              log=False,
                              errorbars_2400=True)
            graphR_pos = plot(number_pos,
                              readingsR_pos,
                              'N',
                              'R',
                              2,
                              log=False,
                              errorbars_2400=True)
            graphIV_neg = plot(readingsV_sipm_neg,
                               readingsI_sipm_neg,
                               'Vsipm',
                               'Isipm',
                               3,
                               log=False,
                               errorbars_2612=True)
            graphIV_pos = plot(readingsV_sipm_pos,
                               readingsI_sipm_pos,
                               'Vsipm',
                               'Isipm',
                               4,
                               log=False,
                               errorbars_2612=True)

        else:
            graphR_neg = 'NULL'
            graphR_pos = 'NULL'
            graphIV_neg = 'NULL'
            graphIV_pos = 'NULL'

        if saveFlag == 1:
            group_path_pos = group_path + " (rq)"
            group_path_neg = group_path + " (vbr)"
            save_iv(readingsV_sipm_neg, readingsI_sipm_neg, readingsR_neg,
                    graphIV_neg, graphR_neg, n, group_path_pos)

            save_iv(readingsV_sipm_pos, readingsI_sipm_pos, readingsR_pos,
                    graphIV_pos, graphR_pos, n, group_path_neg)

        time.sleep(45)
        [readingsI_sipm, readingsR] = DarkCurrent(smu_2612b, smu_2400, config)

        smu_2612b.write('reset()')

        smu_2612b.write('smua.nvbuffer1.clear()')
        smu_2612b.write('smub.nvbuffer1.clear()')
        smu_2400.write('*CLS')

        number = []
        for g in range(len(readingsR)):
            number.append(g)

        if plotFlag == 1:
            graphR = plot(number,
                          readingsI_sipm,
                          'N',
                          'Isipm',
                          5,
                          log=False,
                          errorbars_2612=True)
        else:
            graphR = 'NULL'

        if saveFlag == 1:
            group_path_dark = group_path + " (idark)"
            save_dark(readingsI_sipm, readingsR, graphR, n, group_path_dark)

        rm.close
        return

    elif test == 'self_heating':

        [
            readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led,
            readingsR
        ] = SelfHeating(smu_2612b, smu_2400, config)

        smu_2612b.write('reset()')

        smu_2612b.write('smua.nvbuffer1.clear()')
        smu_2612b.write('smub.nvbuffer1.clear()')
        smu_2400.write('*CLS')

        rm.close

        Number = []
        for i in range(0, len(readingsR)):
            Number.append(i)

        if plotFlag == 1:
            graphR = plot(Number, readingsR, 'N', 'R', 1)
            graphIV = plot(readingsI_led,
                           readingsI_sipm,
                           'Iled',
                           'Isipm',
                           2,
                           log=True,
                           errorbars_2612=True)

        else:
            graphR = 'NULL'
            graphIV = 'NULL'

        if saveFlag == 1:
            save(readingsV_sipm, readingsI_sipm, readingsV_led, readingsI_led,
                 readingsR, graphIV, graphR, n, group_path)

        return

    else:
        print(str(test) + " is not a valid mode")
        return
예제 #23
0
def run(n, mode, group_path, plotFlag, saveFlag, wait_time):

    # Loading setups configurations
    config = setup()

    #rm-list_resources() to find address for smu
    address_2612b = 26
    address_2400 = 24

    clear_all()

    #running tests (smua measures iv and smub measures r)

    if mode == 'iv':
        [smu, rm] = gpib(address_2612b)

        [readingsV, readingsI, readingsR, readingsIR
         ] = ivr(smu, config[0], config[1], config[2], config[3], config[4],
                 config[5], config[6], config[7], config[8], config[9],
                 config[10], config[11], config[12], config[13], config[14],
                 config[15], config[16], config[18], wait_time)

        smu.write('reset()')

        smu.write('smua.nvbuffer1.clear()')
        smu.write('smub.nvbuffer1.clear()')

        rm.close

        Number = []
        for i in range(0, len(readingsR)):
            Number.append(i)

        if plotFlag == 1:
            graphR = plot(Number, readingsR, 'N', 'R', 1)
            graphIV = plot(readingsV, readingsI, 'V', 'I', 2)
        else:
            graphR = 'NULL'
            graphIV = 'NULL'

        if saveFlag == 1:
            save(readingsV, readingsI, readingsR, readingsIR, graphIV, graphR,
                 n, group_path)

        return

    elif mode == 'led1':

        [smu_2612b, smu_2400, rm] = gpib2(address_2612b, address_2400)

        #polarization voltage for sipm on led1 test
        vPolarization_sipm = 30

        [readingsI_sipm, readingsV_led, readingsI_led, readingsR, readingsIR
         ] = led1(smu_2612b, smu_2400, config[0], config[1], config[2],
                  config[3], config[4], config[5], config[6], config[7],
                  config[8], config[9], config[13], config[14], config[15],
                  config[19], vPolarization_sipm, wait_time)

        smu_2612b.write('reset()')

        smu_2612b.write('smua.nvbuffer1.clear()')
        smu_2612b.write('smub.nvbuffer1.clear()')
        smu_2400.write('*CLS')

        rm.close

        Number = []
        for i in range(0, len(readingsR)):
            Number.append(i)

        if plotFlag == 1:
            graphR = plot(Number, readingsR, 'N', 'R', 1)
            graphIV = plot(readingsI_led, readingsI_sipm, 'Iled', 'Isipm', 2)
        else:
            graphR = 'NULL'
            graphIV = 'NULL'

        if saveFlag == 1:
            save_led(readingsI_sipm, readingsV_led, readingsI_led, readingsR,
                     readingsIR, graphIV, graphR, n, group_path)

        return

    elif mode == 'led2':

        [smu_2612b, smu_2400, rm] = gpib2(address_2612b, address_2400)

        #polarization current for led on led2 test
        iPolarization_led = 100 * P('m')
        vPolarization_sipm = 30

        [readingsI_sipm, readingsV_led, readingsR, readingsIR
         ] = led2(smu_2612b, smu_2400, config[0], config[1], config[2],
                  config[3], config[4], config[5], config[6], config[7],
                  config[8], config[9], config[17], config[20],
                  vPolarization_sipm, iPolarization_led, wait_time)

        smu_2612b.write('reset()')

        smu_2612b.write('smua.nvbuffer1.clear()')
        smu_2612b.write('smub.nvbuffer1.clear()')
        smu_2400.write('*CLS')

        rm.close

        Time = []
        for i in range(0, len(readingsR)):
            Time.append(i * wait_time)

        if plotFlag == 1:
            graphR = plot(Time, readingsR, 't', 'R', 1)
            graphI = plot(Time, readingsI_sipm, 't', 'Isipm', 2)
        else:
            graphR = 'NULL'
            graphI = 'NULL'

        if saveFlag == 1:
            save_led(Time, readingsI_sipm, readingsV_led, readingsR,
                     readingsIR, graphI, graphR, n, group_path)

        return
예제 #24
0
        print("Enter the Key : ")
        key = input()
        print("Enter the value : ")
        value = input()
        print("Do you wish for the key to have time-to-live : [y/n]")
        cond = input()

        # asking whether user wants to provide the key with time-to-live property or not
        if cond == 'y':
            print(
                "Enter how long should the key be active (time in seconds) : ")
            time = int(input())
            functions.create(key, value, time)
        else:
            functions.create(key, value)
        functions.save()

    elif operation == 2:
        print("Enter the Key to read the value : ")
        key = input()
        print(functions.read(key))
        functions.save()

    elif operation == 3:
        print("Enter the Key to be deleted : ")
        key = input()
        functions.delete(key)
        functions.save()

    elif operation == 4:
        functions.save()
예제 #25
0
 def magic(self):
     self.text.setText("yay")
     functions.save("this.txt", self.edit.toPlainText())
     functions.do_thing("this.txt")
import main_menu, weapons, functions
global gameOn
gameOn = 1

gameOn = main_menu.mainMenu(gameOn)  #Load main menu
if (gameOn == 1):
    attributes = main_menu.attributes  #creates variable with attributes chosen in previous function
    functions.show_attributes(attributes)  #shows all attributes of character
    functions.save(attributes)  #saves attributes to file
while (gameOn == 1):
    gameOn = functions.whatToDo(attributes, gameOn)
"""placeholder for function testing"""
#while(gameOn == 1):
#   for level in range(1,11):
#      loadLevel(level)
#     level=+1
예제 #27
0
axis[1, 2].plot(transits[5], flux_tran[5])
axis[1, 2].set_ylabel("Flux(Watts/m^2)")
axis[1, 2].set_xlabel("Time(days)")
axis[1, 2].set_title("Transit 6")
for label in axis[0, 1].get_xticklabels()[::2]:
    label.set_visible(False)  #make less tick marks so looks better
fig.tight_layout()
plt.savefig("hill_project6aii.png")
plt.show()
plt.close()

#aiv
plt.plot(transits[0], flux_tran[0], label="1")
plt.plot(transits[1], flux_tran[1], label="2")
plt.plot(transits[2], flux_tran[2], label="3")
plt.plot(transits[3], flux_tran[3], label="4")
plt.plot(transits[4], flux_tran[4], label="5")
plt.plot(transits[5], flux_tran[5], label="6")
plt.legend()
plt.savefig("hill_project6aiv.png")
plt.show()

save("hill_project6a.txt", ("transits", "1", "2", "3", "4", "5"), transits)
save("hill_project6aflux.txt", ("1", "2", "3", "4", "5", "6"), flux_tran)
save("hill_project6aerror.txt", ("1", "2", "3", "4", "5", "6"), error_tran)
#basiaclly lots of plots and save it

# In[ ]:

# In[ ]: