Ejemplo n.º 1
0
 def _insert(self, values, return_id=False, raw_values=False):
     query = sql.InsertQuery(self.model, getConnection(self.banco))
     query.insert_values(values, raw_values)
     ret = query.execute_sql(return_id)
     #O commit automatico so eh valido para a conexao padrao do banco
     query.connection._commit()
     return ret
Ejemplo n.º 2
0
    def test_update_contact(self):
        nickname = 'contact-name-1-bis'
        thumbnail = 'xxx-bis'
        id = '1000'
        payload = {
            'contact': {
                'id': id,
                'nickname': nickname,
                'thumbnail': thumbnail
            }
        }

        userId = 'user1'
        mock_event = make_mock_event(userId, payload)
        result = handler.post_contact(mock_event, None)

        assert result is True

        schema = os.environ['PGSCHEMA']
        connection = getConnection()
        with closing(connection):
            with closing(connection.cursor(
                    cursor_factory=NamedTupleCursor)) as cursor:
                cursor.execute(
                    f'SELECT * FROM "{schema}"."contact" WHERE id=%s', (id, ))
                assert cursor.rowcount == 1
                for record in cursor:
                    assert record.id == id
                    assert record.nickname == nickname
                    assert record.thumbnail == thumbnail
                    assert record.user_id == userId
    def test_handle_successful_borrower_validation(self, mock_send_message):
        mock_message = make_mock_message(
            {
                'operation': IncomingOperations.VALIDATE_BOOK_BORROWER.value,
                'userId': 'user5',
                'contactId': '1005',
                'lendingId': '1',
                'bookId': '2000'
            }, 'mock-reply-address')
        handler.handle_messages(event=mock_message, context=None)

        # Assert the send_message method is called once, with correct parameters
        mock_send_message.assert_called_once_with(
            {
                'operation': OutgoingOperations.VALIDATE_BOOK_BORROWER.value,
                'userId': 'user5',
                'lendingId': '1',
                'bookId': '2000',
                'result': {
                    'status': BorrowingStatus.BORROWER_VALIDATED.value,
                    'contact': 'contact-1005'
                }
            }, 'mock-reply-address')

        # Assert the borrowing is saved accodingly in database
        schema = os.environ['PGSCHEMA']
        connection = getConnection()
        with closing(connection):
            with closing(connection.cursor(
                    cursor_factory=NamedTupleCursor)) as cursor:
                cursor.execute(
                    f'SELECT * FROM "{schema}"."borrowing" WHERE user_id=%s AND lending_id=%s AND contact_id=%s AND book_id=%s',
                    ('user5', '1', '1005', '2000'))
                assert cursor.rowcount == 1
Ejemplo n.º 4
0
    def post(self):
        req = json_decode(self.request.body)
        user_id = req["user_id"]
        try:
            with getConnection() as conn:
                data = conn.execute(
                    'SELECT face_vec FROM userlist WHERE user_id=%s',
                    (user_id, ))
                vec_mine = data.fetchone()
                data = conn.execute(
                    'SELECT user_id, face_vec FROM userlist WHERE user_id!=%s',
                    (user_id, ))
                user_list = data.fetchall()

            sim_list = []
            for user in user_list:
                sim = cosSimilarity(vec_mine[0], user[1])
                if sim > 0.4:
                    sim_list.append([sim, user[0]])

            new_sim_list = sorted(sim_list, reverse=True)
            data = {"user_id": user_id, "list": [x[1] for x in new_sim_list]}
        except:
            data = {"result": "0"}
        self.write(json.dumps(data))
Ejemplo n.º 5
0
    def start(self, personId, localTaskId):
        taskObject = task.Task()
        taskItem = json.loads(utils.getConnection(taskObject.details(localTaskId)))
        taskId = taskItem['task'][0]['id']

        time = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S")
        infos = {'personid':personId, 'starttime':time, 'taskid':taskId}
        jsonObject = utils.postConnection('timer/', infos)
        urlString = self.current(personId)
        return urlString    
Ejemplo n.º 6
0
    def pause(self, personId):
        # calculate the amount of time lapsed between the starttime and now, and sum that value with the value in the time field (i.e. time = time + (now - starttime)). Then nullify the starttime field.
        taskObject = task.Task()
        taskLocalId = json.loads(utils.getConnection(self.current(personId)))
        timer = taskLocalId['timer'][0]
        
        startTime = timer['starttime'] 
        timer['starttime'] = None
        total = float(timer['time']) + (datetime.datetime.utcnow() - startTime)
        timer['time'] = total

        return None
Ejemplo n.º 7
0
    def __setstate__(self, obj_dict):
        """Unpickling support."""
        # Rebuild list of field instances
        obj_dict['select_fields'] = [
            name is not None and obj_dict['model']._meta.get_field(name) or None
            for name in obj_dict['select_fields']
        ]

        self.__dict__.update(obj_dict)
        # XXX: Need a better solution for this when multi-db stuff is
        # supported. It's the only class-reference to the module-level
        # connection variable.
        self.connection = getConnection(self.banco)
Ejemplo n.º 8
0
    def test_delete_contact(self):

        userId = 'user3'
        id = '1003'
        mock_event = make_mock_event(userId, {'id': id})
        result = handler.delete_contact(mock_event, None)

        assert result is True

        schema = os.environ['PGSCHEMA']
        connection = getConnection()
        with closing(connection):
            with closing(connection.cursor(
                    cursor_factory=NamedTupleCursor)) as cursor:
                cursor.execute(
                    f'SELECT * FROM "{schema}"."contact" WHERE id=%s', (id, ))
                assert cursor.rowcount == 0
Ejemplo n.º 9
0
    def post(self):

        req = json_decode(self.request.body)
        img_path = req["image_path"]
        user_id = req["user_id"]
        img = io.BytesIO(urllib.request.urlopen(img_path).read())
        img = Image.open(img).convert('RGB')
        try:
            vector = getVec(img, mtcnn, resnet)
        except:
            self.write(json.dumps({"result": "-1"}))
            return
        try:
            with getConnection() as conn:
                conn.execute(
                    'INSERT INTO userlist (user_id, face_vec) VALUES (%s, %s)',
                    (user_id, list(vector.astype(float))))
            data = {"result": "1"}
        except:
            data = {"result": "0"}
        self.write(json.dumps(data))
Ejemplo n.º 10
0
 def test_handle_returned_book(self):
     # user does not exists
     mock_message = make_mock_message({
         'operation':
         IncomingOperations.RETURN_LENT_BOOK.value,
         'userId':
         'user6',
         'contactId':
         '1006',
         'lendingId':
         '2',
         'bookId':
         'book-id-2'
     })
     handler.handle_messages(event=mock_message, context=None)
     schema = os.environ['PGSCHEMA']
     connection = getConnection()
     with closing(connection):
         with closing(connection.cursor(
                 cursor_factory=NamedTupleCursor)) as cursor:
             cursor.execute(
                 f'SELECT * FROM "{schema}"."borrowing" WHERE user_id=%s AND lending_id=%s AND contact_id=%s AND book_id=%s',
                 ('user6', '2', '1006', 'book-id-2'))
             assert cursor.rowcount == 0
Ejemplo n.º 11
0
 def __init__(self, model, banco):
     self.banco = banco
     self.model = model
     self.connection = getConnection(self.banco)
     super(MultiBdQueryBase, self).__init__( self.model, self.connection, WhereNode)
Ejemplo n.º 12
0
import pandas as pd
import cx_Oracle as oracle
import utils
import matplotlib.pyplot as plt
from io import StringIO

conn = utils.getConnection()
cur = conn.cursor()
cur.execute('SELECT LON,LAT,AVG(SPEED_GPS) FROM TR_GPSTRACK_0700_0710 GROUP BY LON,LAT')
rows = cur.fetchall()
cur.executemany('INSERT INTO TR_GPSTRACK_0700_0710_AVGSPEED(LON,LAT,SPEED_GPS_AVG) VALUES(:1,:2,:3)',rows)
conn.commit()

cur.execute('SELECT * FROM TR_GPSTRACK_0700_0710_AVGSPEED')
data = utils.formatall(cur)
data.to_csv('avg_speed.csv')

# cm = plt.cm.get_cmap('RdYlBu')
# sc = plt.scatter(data.LON,data.LAT,c=data.SPEED_GPS_AVG,vmin=0,vmax=120,s=2,cmap=cm)
# plt.colorbar(sc)
# plt.show()

cur.close()
conn.close()