def create_tables(): database.connect() try: database.create_tables([Pokemon]) database.commit() finally: database.close()
def tearDown(self) -> None: # Close connection after test database.close() # Back to old database database.init(DB_NAME) # Remove test db file os.remove(TEST_DB_NAME)
def start_training(message): """Command: start training - starts a one hour training.""" if message.author.id in stop_training_events: yield from client.send_message(message.channel, "You are already training.") return stop_event = asyncio.Event() stop_training_events[message.author.id] = stop_event start_time = client.loop.time() - 5 handler = client.loop.call_later(3600, stop_event.set) yield from client.send_message(message.channel, "Training started.") yield from stop_event.wait() handler.cancel() del stop_training_events[message.author.id] delta_time = (client.loop.time() - start_time) // 60 database.connect() try: team = (Pokemon.select().where((Pokemon.owner_id == message.author.id) & (Pokemon.storage == TEAM))) for pkmn in team: pkmn.add_exp(delta_time) pkmn.save() database.commit() finally: database.close() ensure_future( client.send_message( message.author, "Training finished. You trained for %u minutes." % delta_time))
def drop_tables(): database.connect() try: database.drop_tables([Pokemon]) database.commit() finally: database.close()
def interactive(classifier): try: while True: print "CLASSIFY YOUR MESSAGE:" text = raw_input("enter a text: ") print "result:", classifier.classify(tokenize(text)) print except KeyboardInterrupt: database.close()
def list_pokemon_team(message): """Command: team - list the pokemons in user's team.""" database.connect() text = 'Your team:\n' + '\n'.join( " - **{0.name}** lv. {0.level}".format(pkmn) for pkmn in (Pokemon.select().where((Pokemon.owner_id == message.author.id) & (Pokemon.storage == TEAM)))) database.close() yield from client.send_message(message.channel, text)
def main(): try: database.connect() user_data_sync_service = UserDataSyncService() user_data_sync_service.sync() except: print("Unexpected error: ", sys.exc_info()[0]) finally: database.close()
def interactive(classifier): try: while True: print 'CLASSIFY YOUR MESSAGE:' text = raw_input('enter a text: ') print 'result:', classifier.classify(tokenize(text)) print except KeyboardInterrupt: database.close()
def start_trade(message): seller = message.author buyer = message.mentions[0] channel = message.channel tokens = message.content.split() pkmn_name = ' '.join(tokens[3:]) database.connect() try: seller_pkmn = Pokemon.get(Pokemon.owner_id == seller.id, Pokemon.name == pkmn_name) except Pokemon.DoesNotExist: return finally: database.close() # pokemon exists, send invitation to trade text = ("{}, {} invites you to trade and offers {}.\n" "Enter 'pkmn offer {} <pokemon>' to trade.".format( buyer.mention, seller.name, pkmn_name, seller.mention)) yield from client.send_message(channel, text) # wait for buyer to accept trade def check(message): return message.content.startswith('pkmn offer {}'.format( seller.mention)) response = yield from client.wait_for_message(300, channel=channel, author=buyer, check=check) if not response: yield from client.send_message(channel, 'Trade cancelled.') return tokens = response.content.split() pkmn_name = ' '.join(tokens[3:]) database.connect() try: buyer_pkmn = Pokemon.get(Pokemon.owner_id == buyer.id, Pokemon.name == pkmn_name) buyer_pkmn.owner_id = seller.id seller_pkmn.owner_id = buyer.id buyer_pkmn.storage = seller_pkmn.storage = BOX buyer_pkmn.save() seller_pkmn.save() database.commit() except Pokemon.DoesNotExist: return except: database.rollback() raise finally: database.close() yield from client.send_message(channel, 'Trade completed.')
def drop_tables(): database.connect() # Initialize db by deleting all tables Item.drop_table(fail_silently=True) User.drop_table(fail_silently=True) Address.drop_table(fail_silently=True) Order.drop_table(fail_silently=True) OrderItem.drop_table(fail_silently=True) Picture.drop_table(fail_silently=True) database.close()
def create_tables(): database.connect() # Create new table with the same name Item.create_table() User.create_table() Address.create_table() Order.create_table() OrderItem.create_table() Picture.create_table() database.close()
def create_superuser(email, password): database.connect() User.create( uuid=uuid.uuid4(), first_name='', last_name='', email=email, password=(crypt_password(password)), superuser=True, ) database.close()
def test_db(): conn = database.connect() user = Users(create_date=datetime.now(), email="*****@*****.**", first_name="Serkan", surname="Dağlıoğlu", password="******", follower_count=0, following_count=0, username="******") user.save() database.close() return 'Hello World!'
def create_tables(): database.connect() database.create_tables([Goods, Admins, Orders_Info, Orders_Content], safe=True) Goods.create(name='.BASE_CAT', amount=0) Goods.create(name='Браслеты', amount=100, parent_id=1) Goods.create(name='Значки', amount=75, parent_id=1) Goods.create(name='Кружки', amount=150, price=100, parent_id=1) Goods.create(name='Синие', amount=50, price=10, parent_id=2) Goods.create(name='Красные', amount=36, price=15, parent_id=2) Goods.create(name='Желтые', amount=14, price=20, parent_id=2) Goods.create(name='Жестяные', amount=30, price=17, parent_id=3) Goods.create(name='Деревянные', amount=45, price=13, parent_id=3) Admins.create(chat_id='1234') database.close()
def deposit_pkmn_handler(message): tokens = message.content.split() pkmn_name = ' '.join(tokens[2:]) database.connect() try: pkmn = ( Pokemon.select().where((Pokemon.storage == TEAM) & (Pokemon.owner_id == message.author.id) & (Pokemon.name == pkmn_name)).first()) pkmn.storage = BOX pkmn.save() finally: database.commit() database.close() yield from client.send_message(message.channel, '{} sent to box'.format(pkmn.name))
def show_pokemon(message): """Command: show [index] - show the pokemon from your team. Displays information about the pokemon in the current channel. The pokemon is selected fron your team at the specified index, if index is not given, show the first pokemon. """ num = int(message.content[10:] or 1) database.connect() pkmn = (Pokemon.select().where((Pokemon.owner_id == message.author.id) & ( Pokemon.storage == TEAM)).offset(num - 1).limit(1).first()) database.close() if pkmn is None: return em = discord.Embed(title='{} lv. {}'.format(pkmn.name, pkmn.level), colour=0xC00000) em.set_image(url=pkmn.get_img_url()) yield from client.send_message(message.channel, embed=em)
def add_caught_pokemon(user, pkmn, channel): """Add caught pokemon to the user's storage. Adds the pokemon to the storage and sends a notification about caught pokemon to the channel. """ text = ('Congratulations! {} caught {}.'.format(user.mention, pkmn.name)) pkmn.owner_id = user.id database.connect() count = (Pokemon.select().where((Pokemon.owner_id == user.id) & (Pokemon.storage == 1)).count()) if count < TEAM_SIZE: pkmn.storage = TEAM else: pkmn.storage = BOX text += '\nPokemon was added to your box.' pkmn.save() database.commit() database.close() ensure_future(client.send_message(channel, text))
def withdraw_pokemon(message): database.connect() num = (Pokemon.select().where((Pokemon.storage == TEAM) & ( Pokemon.owner_id == message.author.id)).count()) if num >= TEAM_SIZE: database.close() yield from client.send_message(message.channel, 'Your team is full.') return try: tokens = message.content.split() pkmn_name = ' '.join(tokens[2:]) pkmn = ( Pokemon.select().where((Pokemon.storage == BOX) & (Pokemon.owner_id == message.author.id) & (Pokemon.name == pkmn_name)).first()) pkmn.storage = TEAM pkmn.save() finally: database.commit() database.close() yield from client.send_message(message.channel, '{} withdrawn.'.format(pkmn.name))
def interactive(classifier): try: while True: print "CLASSIFY YOUR MESSAGE:" text = raw_input("enter a text: ") print "result:", classifier.classify(tokenize(text)) print except KeyboardInterrupt: database.close() if __name__ == "__main__": database.connect() train, test = split_me_not_me(0.9) print "ME AND NOT ME:" run_naive_bayes(train, test) threshold = 200 print print "PEOPLE WITH OVER %d TEXTS:" % threshold run_naive_bayes(*people_with_many_texts(threshold)) print # train, test = split_me_not_me(1.0) # train, test = people_with_many_texts(threshold) # classifier = build_classifier(train) # interactive(classifier) database.close()
def inner_clean_up(): database.close() utilities.recursively_delete_directory(self._tempdir)
def _db_close(_): if not database.is_closed(): database.close()
def interactive(classifier): try: while True: print 'CLASSIFY YOUR MESSAGE:' text = raw_input('enter a text: ') print 'result:', classifier.classify(tokenize(text)) print except KeyboardInterrupt: database.close() if __name__ == '__main__': database.connect() train, test = split_me_not_me(0.9) print 'ME AND NOT ME:' run_naive_bayes(train, test) threshold = 200 print print 'PEOPLE WITH OVER %d TEXTS:' % threshold run_naive_bayes(*people_with_many_texts(threshold)) print # train, test = split_me_not_me(1.0) # train, test = people_with_many_texts(threshold) # classifier = build_classifier(train) # interactive(classifier) database.close()
def close_db(resp): database.close() return resp
def close_db_on_err(err): database.close()
def close_db_connection(): database.close()
def _db_close(_): if not database.is_closed(): print("[DEBUG] close() called") database.close()
def on_finish(self): if not database.is_closed(): database.close() return super().on_finish()
def teardown_method(self, method): database.close() self._output_manager.stop() self._data_extractor.stop() self._db_creator.stop() utilities.recursively_delete_directory(self._tempdir)
def database_disconnect(response): if not database.is_closed(): database.close() return response
def after_request(response): database.close() return response