Esempio n. 1
0
def drop_tables():
    database.connect()
    try:
        database.drop_tables([Pokemon])
        database.commit()
    finally:
        database.close()
Esempio n. 2
0
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))
Esempio n. 3
0
def create_tables():
    database.connect()
    try:
        database.create_tables([Pokemon])
        database.commit()
    finally:
        database.close()
Esempio n. 4
0
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)
Esempio n. 5
0
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()
Esempio n. 6
0
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.')
Esempio n. 7
0
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()
Esempio n. 8
0
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()
Esempio n. 10
0
def syncdb(options, reset=False, create=False):
    from models import DB_FILE, database, create_tables, populate_tables
    import os
    if reset:
        os.unlink(DB_FILE)
        database.connect()
        create_tables()()
        populate_tables()
    elif create:
        database.connect()
        create_tables()()

    else:
        dbshell(options)
Esempio n. 11
0
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()
Esempio n. 12
0
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))
Esempio n. 13
0
def maraserver(options):
    """Run server protocol"""
    from models import database, Profile
    from twisted.internet import reactor
    try:
        database.connect()
        profile = Profile.get(name=options.profile)
        #import IPython; IPython.embed()
        for comaster in profile.comaster_set.filter(enabled=True):
            print "Listening in port %d" % comaster.port
            reactor.listenTCP(comaster.port, MaraServerFactory(comaster)) #@UndefinedVariable
        reactor.run() #@UndefinedVariable
    except Exception:
        from traceback import format_exc
        print format_exc()
        raise
Esempio n. 14
0
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)
Esempio n. 15
0
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))
Esempio n. 16
0
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))
Esempio n. 17
0
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!'
Esempio n. 18
0
    def save(self):
        if self.is_valid():
            # Connect to DB
            try:
                database.connect()
                logs.data_transaction.debug("Open connection to database")

                try:
                    # Populate data to Model
                    user = Traveler(ip=self.ip,
                                    username=self.username,
                                    email=self.email,
                                    sex=1 if self.sex == u"male" else 0,
                                    country=self.country,
                                    message=self.message)
                    # Saving data in ORM
                    user.save()
                    logs.data_transaction.debug("Save data to PostgreSQL")

                except Exception as e:
                    logs.data_transaction.critical(e)
                    logs.data_transaction.critical("Can't save model in DB")

            except Exception as e:
                logs.data_transaction.critical(e)
                logs.data_transaction.critical(
                    "Database conection ERROR!"
                )  # Do you create 'travel' database?"

                # Now create scheme
                try:
                    database.create_table(Traveler)
                    logs.data_transaction.debug("Ok, tables is created!")
                except Exception as e:
                    logs.data_transaction.critical(e)

        else:
            logs.data_transaction.warning(
                "Can't save invalid form data into database")
Esempio n. 19
0
 def test_score_with_extra_space(self):
     table_name = 'players'
     players = ["Anouer Taouerghi\n"]
     content = "\t".join(players)
     data = {'table': table_name, 'column': 0, 'slice': 0, 'total': 1, 'addr': ''}
     data['file_slice'] = (StringIO(content), "players.csv")
     Bite.delete().execute()  # delete all instances
     print("after deletiong: "+str(len(Bite.select())))
     result = self.app.post('/score', data=data, content_type='multipart/form-data')
     database.connect(reuse_if_open=True)
     self.assertEqual(result.status_code, 200)
     bites = Bite.select().where(Bite.table==table_name, Bite.column==0)
     self.assertEqual(len(bites), 1)
     data_dir = os.path.join(DATA_DIR, bites[0].fname)
     print("data_dir: "+data_dir)
     data_file_exists = os.path.isfile(data_dir)
     self.assertTrue(data_file_exists, msg="The data file is not found")
     annotated_cells = {"data":
                            {
                                'Anouer Taouerghi': {u'http://dbpedia.org/resource/Anouer_Taouerghi': [
                                u'http://dbpedia.org/ontology/Person',
                                u'http://dbpedia.org/ontology/Agent',
                                u'http://dbpedia.org/ontology/Athlete',
                                u'http://dbpedia.org/ontology/VolleyballPlayer']},
                            }
                        }
     f = open(data_dir)
     computed_data = json.load(f)
     self.assertDictEqual(annotated_cells, computed_data)
     bite = Bite.select()[0]
     graph_file_name = graph_fname_from_bite(bite)
     graph_file_dir = os.path.join(UPLOAD_DIR, graph_file_name)
     tgraph = type_graph.TypeGraph()
     tgraph.load_from_file(graph_file_dir)
     tgraph.set_score_for_graph(coverage_weight=0.1, m=1, fsid=3)
     results = [n for n in tgraph.get_scores()]
     results.sort(key=lambda node: node.path_specificity)
     self.assertEqual(results[0].title, "http://dbpedia.org/ontology/VolleyballPlayer")
     self.assertEqual(bite.status, "complete")
Esempio n. 20
0
def deletenote():
    print('delete request recepted')
    reqbody = request.get_json()
    userid = reqbody["userid"]
    noteid = reqbody["noteid"]
    conn, cursor = database.connect()

    result = database.deleteNote(conn, cursor, userid, noteid)

    if result == "success":
        return result
    else:
        print(result)
        return "error occured"
Esempio n. 21
0
def maraclient(options):
    '''
    Conexión con el mara
    '''
    from twisted.internet import reactor
    try:
        from models import database, Profile
        database.connect()
        profile = Profile.get(name=options.profile)

        for comaster in profile.comaster_set.filter(enabled=True):
            print "Conectando con %s" % comaster
            reactor.connectTCP(comaster.address,
                               comaster.port,
                               MaraClientProtocolFactory(comaster),
                               timeout=comaster.timeout,
                               #bindAddress=None,
                               )
        # Una vez que está conectado todo, debemos funcionar...
        reactor.run() #@UndefinedVariable
    except Exception as e:
        from traceback import format_exc
        print format_exc()
        print e
Esempio n. 22
0
def getnote():
    print("get note api was called")
    userid = 'mon'
    noteid = request.args.get('noteid')
    conn, cursor = database.connect()
    result = database.getNote(cursor, userid, noteid)
    conn.close()
    result = result[0]

    # 整形
    res = {
        "noteid":str(result[0]),
        "title": result[1],
        "body": result[2],
        "updateAt": result[3]
    }

    return jsonify(res)
Esempio n. 23
0
def makenote():
    if request.method == 'POST':
        print("POST request recepted")
        reqbody = request.get_json()
        print(reqbody)
        userid = reqbody["userid"]
        noteid = reqbody["noteid"]
        title = reqbody["title"]
        body = reqbody["body"]
        updateAt = reqbody["updateAt"]
        conn, cursor = database.connect()
        
        print(title)
        result = database.writeNotes(conn, cursor, userid, noteid, title, body, updateAt)

        if result == "success":
            return result
        else:
            print(result)
            return "error occured"
    else:
        print("request is not POST")
Esempio n. 24
0
def getTitles():
    print("get titles api was called")
    userid = request.args.get('userid')
    conn, cursor = database.connect()
    result = database.getTitles(cursor, userid)
    conn.close()
    '''
    {
        "userid": "abc",
        "titleList": [
            {
                "noteid": num,
                "title" : title
            },
            {
                "noteid": num,
            },
    }
    '''
    # dict list "titleList"

    titleList = []
    for i in range(len(result)):
        noteid = result[i][0]
        title = result[i][1]
        titleList.append({
            "noteid": noteid,
            "title": title
        })
    # 整形
    res = {
        "userid": userid,
        "titleList": titleList
    }
    print(type(titleList), titleList)
    print(jsonify(res))
    return jsonify(res)
Esempio n. 25
0
    run_test(classifier, test)


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)
Esempio n. 26
0
def _db_connect():
    database.connect()
Esempio n. 27
0
    run_test(classifier, test)


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)
Esempio n. 28
0
def before_request():
    database.connect()
Esempio n. 29
0
def open_db():
    database.connect()
Esempio n. 30
0
def _db_connect():
    if not database.is_connection_usable():
        database.connect()
Esempio n. 31
0
def database_connect():
    if database.is_closed():
        database.connect()
Esempio n. 32
0
def main():
    database.connect()
    seed(2)

    fake = Factory.create('it_IT')
    fake.seed(99)

    items_list = []
    users_list = []

    for _ in range(10):
        item = Item.create(
            uuid=fake.uuid4(),
            name=fake.word(),
            price=fake.random_int(),
            description=fake.sentence(),
            category=fake.word(),
            availability=randint(1, 10),
            )
        items_list.append(item)

    for _ in range(20):
        user = User.create(
            uuid=fake.uuid4(),
            first_name=fake.first_name(),
            last_name=fake.last_name(),
            email=fake.email(),
            password=fake.password(),
            )
        users_list.append(user)

    for user in users_list:
        for x in range(randint(1, 3)):
            Address.create(
                uuid=fake.uuid4(),
                user=user,
                nation=fake.country(),
                city=fake.city(),
                postal_code=fake.postcode(),
                local_address=fake.address(),
                phone=fake.phone_number(),
            )

    for user in users_list:
        # User has three chance on four to make an order
        make_order = randint(0, 4)

        # If use make an order, I insert an order and I iterate the items list
        if make_order != 0:
            order_total_price = 0

            order_item_quantity = 0
            order_item_subtotal = 0

            order = Order.create(
                uuid=fake.uuid4(),
                total_price=order_total_price,
                user=user,
                )

            for item in items_list:
                # If item_quantity == 0, the item isn't counted in the order
                order_item_quantity = randint(0, 3)

                if order_item_quantity != 0:
                    order_item_subtotal = item.price * order_item_quantity
                    order_total_price += order_item_subtotal

                    OrderItem.create(
                        order=order,
                        item=item,
                        quantity=item.price,
                        subtotal=order_item_subtotal,
                        )

            order.total_price = order_total_price
            order.save()
Esempio n. 33
0
def create_db():
    if database.is_closed():
        database.connect()
    drops_all_tables(database)
    create_tables()
    good_bye('created')
Esempio n. 34
0
def _db_connect():
    print("[DEBUG] connect() called")
    database.connect()