def remove_twitch_clip(self, id):
        #update database,
        #all_clips,
        #all_clip_ids
        ret = False

        if storageSystem.get_twitch_clip(id) == None:
            return ret

        session = Session()
        clipObjectAPI = twitchmisc.getClipObjects([id])
        clipObjectDB = storageSystem.get_twitch_clip(id)

        try:
            #Remove from database
            session.delete(clipObjectDB)
            #Remove from all clips
            all_clips.remove(clipObjectAPI[0])
            #Remove from all_clips_ids
            all_clip_ids.remove(id)
            ret = True
            session.commit()
        except:
            ret = False
        finally:

            session.close()
            return ret
Exemplo n.º 2
0
def import_procedures(procedures):
    print("Importing Procedures")
    count = 0
    session = Session()
    for procedure in procedures:
        source_id = procedure['subject']['reference'].split('/')[1]
        patient_id = session.query(
            Patient.id).where(Patient.source_id == source_id).one().id
        try:
            procedure_date = procedure['performedDateTime']
        except KeyError:
            procedure_date = procedure['performedPeriod']['start']

        procedure_obj = Procedure(
            source_id=procedure['id'],
            patient_id=patient_id,
            procedure_date=procedure_date,
            type_code=procedure['code']['coding'][0]['code'],
            type_code_system=procedure['code']['coding'][0]['system'])
        session.add(procedure_obj)
        count += 1
        print(".", end='', flush=True)  # Show progress

    session.commit()
    session.close()
    print(f"\nImported {count} procedures")
Exemplo n.º 3
0
def handler(event, context):
    authorized_user_types = [
        UserType.ADMIN,
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    body = json.loads(event["body"])
    user_email = body.get('email')
    if not user_email:
        return http_status.bad_request()

    chat_freq = 4
    attributes = {
        "custom:user_type": "MENTOR",
        "custom:declared_chats_freq": str(chat_freq),
        "custom:remaining_chats_freq": str(chat_freq)
    }
    admin_update_user_attributes(user_email, attributes)
    admin_enable_user(user_email)

    session = Session()
    for i in range(chat_freq):
        chat_type = ChatType["ONE_ON_ONE"]
        chat = Chat(chat_type=chat_type,
                    chat_status=ChatStatus.PENDING,
                    senior_executive=user_email)
        session.add(chat)

    session.commit()
    session.close()

    return http_status.success()
Exemplo n.º 4
0
def handler(event, context):

    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    jobAppId = event["pathParameters"]["id"]
    jobApp = session.query(JobApplication).get(jobAppId)

    if jobApp == None:
        session.commit()
        session.close()
        return http_status.not_found()
    else:
        delete = session.query(JobApplication).filter(JobApplication.job_application_id == jobAppId).delete()
        session.commit()
        session.close()
        return http_status.success()
Exemplo n.º 5
0
def get_major(sort_name, sort_wage, sort_work, stem):
    all_majors = []
    session = Session()
    majors = session.query(Major)

    majors = parseInputs(sort_name, sort_wage, sort_work, stem, majors)

    print('\n### All Majors')
    for m in majors:
        high_grads_cities = []
        for c in m.cities_high_graduates_2015:
            high_grads_cities.append(c.id)
        high_grads_uni = []
        for uni in m.universities_high_graduates_2015:
            high_grads_uni.append(uni.id)
        u = {
            'id': m.id,
            'name': m.name,
            'image_link': m.image_link,
            'wage_growth_rate': m.wage_growth_rate,
            'is_stem': m.is_stem,
            'average_wage': m.average_wage,
            'total_degrees_awarded_in_2015': m.total_degrees_awarded_in_2015,
            'total_people_in_work_foce': m.total_people_in_work_foce,
            'average_age_work_force': m.average_age_work_force,
            'cities_high_graduates_2015': high_grads_cities,
            'universities_high_graduates_2015': high_grads_uni
        }
        all_majors.append(u)

    session.commit()
    session.close()

    return all_majors
Exemplo n.º 6
0
 def __init__(self, *arg, **kwargs):
     db_session.session = Session()
     super(Chat, self).__init__(*arg, **kwargs)
     self._memory = UserSession(UserMemory, self._memory)
     self._conversation = UserSession(UserConversation, self._conversation)
     self._topic.topic = UserTopic(self._topic.topic)
     db_session.session.close()
class UserRepository:
    session = Session()

    def get_all(self):
        all_books = self.session.query(User).all()
        return jsonify(get_users_list_as_json(all_books))

    def get_by_id(self, user_id):
        book = self.session.query(User).get(user_id)
        return jsonify(get_user_as_json(book))

    def save(self, new_user):
        new_user = User(new_user["name"], new_user["email"], datetime.now())
        self.session.add(new_user)
        self.session.commit()

        return jsonify(get_user_as_json(new_user))

    def update(self, user_id, new_user):
        exist_user = self.session.query(User).filter(
            User.id == user_id).first()
        exist_user.name = new_user["name"]
        exist_user.email = new_user["email"]
        self.session.commit()

        return jsonify(get_user_as_json(exist_user))

    def delete(self, user_id):
        result = self.session.query(User).filter(User.id == user_id).delete()
        self.session.commit()

        if result == 0:
            return False
        else:
            return True
Exemplo n.º 8
0
def handler(event, context):

    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    info = json.loads(event["body"])
    jobAppId = event["pathParameters"]["id"]
    jobApp = session.query(JobApplication).get(jobAppId)

    if jobApp != None:
        keys = info.keys()
        for key in keys:
            setattr(jobApp, key, info[key])

        session.commit()
        session.close()

        return http_status.success(json.dumps(info))
    else:
        return http_status.not_found()
Exemplo n.º 9
0
def updatePoints():
    requestDetails = request.json
    userID = requestDetails['id']
    userPoints = requestDetails['points']

    package = {}

    session = Session()

    user = session.query(User).get(userID)
    user.points += userPoints

    total = user.points

    package["total"] = total
    package["images"] = []

    maskImageReferences = session.query(Mask).filter(
        Mask.points <= total).all()

    for eachReference in maskImageReferences:
        package["images"].append({
            "id": eachReference.id,
            "reference": eachReference.address,
            "points": eachReference.points
        })

    session.commit()
    session.close()

    return package, 200  # Successfully updated the points for the user
Exemplo n.º 10
0
def handler(event, context):

    # check authorization
    authorized_user_types = [UserType.ADMIN, UserType.MENTOR, UserType.PAID]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    # FOR REFERENCE
    # # create a new session
    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)
    if job == None:
        return http_status.not_found()
    if len(job.job_applications
           ) != 0:  # when there are job applications associated to a job
        return http_status.forbidden()

    session.query(Job).filter(Job.job_id == jobId).delete()

    # # commit and close session
    session.commit()
    session.close()
    return http_status.success()
Exemplo n.º 11
0
def handler(event, context):
    
    logging.info('Test')

    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()
    
    # # create a new session
    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)

    
    if job != None:
        job.job_status = JobStatus.CLOSED
        
        session.commit()
        session.close()

        return http_status.success()
    else:
        session.close()
        return http_status.not_found()
Exemplo n.º 12
0
def create_user():
    if (request.method == 'GET'):
        return render_template('create_user.html')
    elif (request.method == 'POST'):

        name = request.form['name']
        phone = request.form['phone']

        # Remove everything except for digits
        p = re.compile(r"[^0-9]")
        phone = re.sub(p, '', phone)

        if (len(phone) != 10):
            response = {"error": "Phone number is wrong length"}
            return jsonify(response), 500

        # Check for a duplicate phone number
        session = Session()
        duplicate = session.query(User).filter(User.phone == phone).all()
        if (len(duplicate) > 0):
            response = {"error": "This phone number is already in the system"}
            return jsonify(response), 500

        # All tests have passed, so create and insert the user.
        new_user = User(name, phone)

        session.add(new_user)
        session.commit()
        session.close()

        # After we have finished inserting the new user,
        # redirect to show all users including the one we just inserted.
        return redirect(url_for('users'))
Exemplo n.º 13
0
def handler(event, context):

    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.PAID, UserType.FREE
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    session = Session()
    jobId = event["pathParameters"]["jobId"]
    job = session.query(Job).get(jobId)

    if job != None:
        job_apps_id = []
        for app in job.job_applications:
            job_apps_id.append(app.job_application_id)
        jobdict = row2dict(job)
        jobdict['job_applications'] = job_apps_id
        session.close()
        return http_status.success(json.dumps(jobdict))
    else:
        session.close()
        return http_status.not_found()
Exemplo n.º 14
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR,
        UserType.FREE,
        UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    status_filter = event["queryStringParameters"].get("status", "") if event["queryStringParameters"] else ""
    requestor_filter = event["queryStringParameters"].get("requestor", "") if event["queryStringParameters"] else ""
    requestee_filter = event["queryStringParameters"].get("requestee", "") if event["queryStringParameters"] else ""

    session = Session()
    filtered_query = session.query(Connection)
    if status_filter:
        filtered_query = filtered_query.filter(Connection.connection_status == status_filter)
    if requestor_filter:
        filtered_query = filtered_query.filter(Connection.requestor == requestor_filter)
    if requestee_filter:
        filtered_query = filtered_query.filter(Connection.requestee == requestee_filter)

    connections = filtered_query.all()
    session.close()

    return http_status.success(json.dumps({
            "connections": [row2dict(r) for r in connections],
            "count": len(connections)
        }))
Exemplo n.º 15
0
def editorC():
    email = dict(session).get('email', None)
    user = User.get_by_email(email)
    given_name = dict(session).get('given_name', None)
    if user.role == "Promotor":
        campanyas = Campanya.getCampaigns(user.organizacion)
    if user.role == "Administrador":
        campanyas = Campanya.getAllCampaigns()
    salary = get_balance(user.blockHash)
    s = Session()
    if request.method == 'POST':
        if 'editar' in request.form:
            return redirect(
                url_for('editorCamp', campanya_id=request.form['id']))
        elif 'eliminar' in request.form:
            query = s.query(Campanya)
            pk = request.form['id']
            query = query.filter(Campanya.id == pk).first()
            s.delete(query)
            s.commit()
        elif 'verAcc' in request.form:
            return redirect(url_for('editor', campanya_id=request.form['id']))
    try:
        del session['accionId']
        del session['offerId']
    except:
        pass
    return render_template('admincampanyas.html',
                           title='Campañas',
                           wallet=salary,
                           email=email,
                           name=given_name,
                           w3=web3,
                           user=user,
                           campanyas=campanyas)
Exemplo n.º 16
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.FREE, UserType.PAID
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    connectId = event["pathParameters"].get(
        "connectId") if event["pathParameters"] else None
    if not connectId:
        return http_status.bad_request(
            "missing path parameter(s): 'connectId'")

    session = Session()
    connection = session.query(Connection).get(connectId)
    if not connection:
        session.close()
        return http_status.not_found()

    session.delete(connection)
    session.commit()
    session.close()

    return http_status.success()
Exemplo n.º 17
0
def sendCoins(dest, amount, imgHash, urlProof):
    destUser = User.get_by_email(dest)
    account_2 = destUser.blockHash

    nonce = web3.eth.getTransactionCount(test_address)

    accion = Accion.getActionById(session['accionId'])
    float_amount = float(amount) / valorUDC
    bytesStr = "acc:" + accion.nombre + " img: " + imgHash
    tx = {
        'chainId': 3,  # es 3 para Ropsten
        'nonce': nonce,
        'to': account_2,
        'value': web3.toWei(float_amount, 'ether'),
        'gas': 50000,
        'gasPrice': web3.toWei(50, 'gwei'),
        'data': bytes(bytesStr, 'utf8')
    }
    signed_tx = web3.eth.account.signTransaction(tx, private_key)
    tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
    s = Session()
    dateTimeObj = datetime.now()
    timestampStr = dateTimeObj.strftime("%d-%m-%Y (%H:%M:%S.%f)")
    t = Transaccion(timestampStr, tx_hash, accion.empresa, dest,
                    accion.campanya_id, amount, imgHash, urlProof)
    s.add(t)
    s.commit()
    query = s.query(Accion)
    kpi = int(float(request.form['kpi']))
    dictupdate = {Accion.kpi: Accion.kpi + kpi}
    query.filter(Accion.id == accion.id).update(dictupdate,
                                                synchronize_session=False)
    s.commit()
    s.close()
Exemplo n.º 18
0
def run():
    args = parser_cl()
    Base.metadata.create_all(engine)
    session = Session()
    root = get_xml_root(args.file)

    # f = open('log', 'w')
    for i, sms in enumerate(root):
        json_data = xml_to_dict(sms)

        sender = sms.get('contact_name').encode('utf-8') if sms.get(
            'type') == '1' else 'Me'
        # print('sender = %s' % sender.decode("utf-8") )
        # print(type(sender))
        json_data['sender'] = sender.decode('utf-8')
        item = json_to_b(json_data)
        session.add(item)

        date = time.strftime("%D %H:%M", time.localtime(int(sms.get('date'))))
        body = sms.get('body').encode('utf-8')
        # line = '%s - %s : %s\n' % (date, sender, body)

        # f.write(line)
    session.commit()

    # for sms in session.query(Backup).all():
    #     print(sms.body)

    # print('Testing f to_file')
    # to_file("I'm testing\ncheck")

    # print('Testing find data')
    ret = find_data(session.query(Backup).all)
    print(ret)
Exemplo n.º 19
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN, UserType.MENTOR, UserType.PAID, UserType.FREE
    ]
    success, _ = check_auth(event['headers']['Authorization'],
                            authorized_user_types)
    if not success:
        return http_status.unauthorized()

    search = event["queryStringParameters"].get(
        "search", "") if event["queryStringParameters"] else ""
    fuzzy = event["queryStringParameters"].get(
        "fuzzy", "") if event["queryStringParameters"] else ""

    session = Session()
    if fuzzy.lower() == "true":
        industry_tags = session.query(IndustryTag).filter(
            IndustryTag.tag.ilike("%{}%".format(search))).all()
    else:
        industry_tags = session.query(IndustryTag).filter(
            IndustryTag.tag.ilike("{}%".format(search))).all()
    session.close()

    return http_status.success(
        json.dumps({
            "industry_tags": [row2dict(r) for r in industry_tags],
            "count": len(industry_tags)
        }))
class BooksRepository:
    session = Session()

    def get_all(self):
        all_books = self.session.query(Book).all()
        return jsonify(get_books_list_as_json(all_books))

    def get_by_id(self, book_id):
        book = self.session.query(Book).get(book_id)
        return jsonify(get_book_as_json(book))

    def save(self, new_book):
        new_book = Book(new_book["name"])
        self.session.add(new_book)
        self.session.commit()

        return jsonify(get_book_as_json(new_book))

    def update(self, book_id, new_data):
        exist_book = self.session.query(Book).filter(
            Book.id == book_id).first()
        exist_book.name = new_data["name"]
        self.session.commit()

        return jsonify(get_book_as_json(exist_book))

    def delete(self, book_id):
        result = self.session.query(Book).filter(Book.id == book_id).delete()
        self.session.commit()

        if result == 0:
            return False
        else:
            return True
Exemplo n.º 21
0
def profile_info():
    try:
        if session and session["logged"]:
            if request.args:
                username = request.args['username'].upper()
                sess = Session()
                user = sess.query(UserDetail).filter_by(name=username).first()
                sess.close()
                user_detail = {
                    "name": user.name,
                    "email": user.email,
                    "phone": user.phone
                }
                return jsonify({"status": 200, "data": user_detail})
            else:
                return jsonify({
                    "status": 400,
                    "result": "Username not passed"
                })
        else:
            return jsonify({
                "status": 200,
                "result": "Session Expired. Please Login...."
            })
    except Exception as exception:
        return jsonify({"status": 500, "result": exception})
Exemplo n.º 22
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN,
        UserType.MENTOR
    ]
    success, user = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    chatId = event["pathParameters"].get("chatId") if event["pathParameters"] else None
    if not chatId:
        return http_status.bad_request("missing path parameter(s): 'chatId'")

    session = Session()
    chat = session.query(Chat).get(chatId)
    if not chat:
        session.close()
        return http_status.not_found("chat with id '{}' not found".format(chatId))

    success = edit_auth(user, chat.senior_executive)
    if not success:
        session.close()
        return http_status.unauthorized()
 
    # DONE state can be achieved from RESERVED_CONFIRMED
    if chat.chat_status != ChatStatus.RESERVED_CONFIRMED:
        session.close()
        return http_status.forbidden("cannot mark DONE unconfirmed reservation of chat with id '{}'".format(chatId))

    chat.chat_status = ChatStatus.DONE

    session.commit()
    session.close()
    return http_status.success()
Exemplo n.º 23
0
 def __init__(self):
     self.date_format = '%Y-%m-%d'
     self.curr_session = Session()
     self.curr_importer = importer.Importer(self.curr_session)
     self.curr_importer.db_init()
     self.curr_controller = controller.Controller(self.curr_session)
     self.parser = argparse.ArgumentParser()
Exemplo n.º 24
0
def main(filename):
    '''Funcón principal que nos permite crear el schema, tomar datos del csv y pasarlo a un .db

    Parameter
    --------
    - filename : str
        Nombre del dataset csv
    
    Return
    -------
    - database : database from sqlite
    '''
    Base.metadata.create_all(engine)  # Nos genera el schema
    session = Session()  # Generamos nuestra sesion
    articles = pd.read_csv(filename)

    for index, row in articles.iterrows():  # Comenzamos a iterar por todos elementos del archivo
        logger.info('Loading article uid {} info DB'.format(row['uid']))
        article = Article(row['uid'],
                          row['body'],
                          row['host'],
                          row['newspaper_uid'],
                          row['n_token_body'],
                          row['n_token_title'],
                          row['title'],
                          row['url'],)
        session.add(article)

    session.commit()
    session.close()
Exemplo n.º 25
0
def handler(event, context):
    # check authorization
    authorized_user_types = [
        UserType.ADMIN
    ]
    success, _ = check_auth(event['headers']['Authorization'], authorized_user_types)
    if not success:
        return http_status.unauthorized()

    chatId = event["pathParameters"].get("chatId") if event["pathParameters"] else None
    if not chatId:
        return http_status.bad_request("missing path parameter(s): 'chatId'")

    session = Session()
    chat = session.query(Chat).get(chatId)
    if not chat:
        session.close()
        return http_status.not_found("chat with id '{}' not found".format(chatId))

    admin_update_declared_chats_frequency(chat.senior_executive, -1)
    if chat.chat_status == ChatStatus.PENDING:
        admin_update_remaining_chats_frequency(chat.senior_executive, -1)

    session.delete(chat)
    session.commit()
    session.close()

    return http_status.success()
Exemplo n.º 26
0
def offerTransaction(rem, dest, offer):
    destUser = User.get_by_email(dest)
    account_2 = destUser.blockHash
    remUser = User.get_by_email(rem)
    nonce = web3.eth.getTransactionCount(remUser.blockHash)
    amount = offer.precio
    strOffer = "Pago por oferta: " + offer.nombre
    float_amount = float(amount) / valorUDC
    tx = {
        'chainId': 3,  # es 3 para Ropsten
        'nonce': nonce,
        'to': account_2,
        'value': web3.toWei(float_amount, 'ether'),
        'gas': 50000,
        'gasPrice': web3.toWei(50, 'gwei'),
        'data': bytes(strOffer, 'utf8')
    }
    signed_tx = web3.eth.account.signTransaction(tx, remUser.pk)
    tx_hash = web3.eth.sendRawTransaction(signed_tx.rawTransaction)
    s = Session()
    dateTimeObj = datetime.now()
    timestampStr = dateTimeObj.strftime("%d-%m-%Y (%H:%M:%S.%f)")
    t = Transaccion(timestampStr, tx_hash, rem, destUser.organizacion, None,
                    amount, "", "")
    s.add(t)
    s.commit()
    s.close()
Exemplo n.º 27
0
def university_basic_populate():
    Base.metadata.create_all(engine)
    with open('../scrapers/university.json', 'r') as f:
        university_data = json.load(f)

    for uni in university_data:
        session = Session()
        university = University(uni["university_id"], uni["name"])

        university.set_extra_info(uni["type"], uni["website"],
                                  uni["oos_tuition"], uni["state_tuition"],
                                  uni["survey_year"])

        university.set_location(uni["longitude"], uni["latitude"],
                                uni["county_id"], uni["state"])
        university.set_enrollment(uni["enrolled_men"], uni["enrolled_women"])

        university.set_demographics(uni["demographics_asian"],
                                    uni["demographics_white"],
                                    uni["demographics_black"],
                                    uni["demographics_hispanic"],
                                    uni["demographics_other"])
        session.add(university)
        print("Added " + uni["name"])
        session.commit()
        session.close()
Exemplo n.º 28
0
def editor(campanya_id):
    email = dict(session).get('email', None)
    user = User.get_by_email(email)
    given_name = dict(session).get('given_name', None)
    acciones = Accion.getActionsOfCampaign(campanya_id)
    campanya = Campanya.getCampaignById(campanya_id)
    salary = get_balance(user.blockHash)
    s = Session()
    if request.method == 'POST':
        if 'editarAcc' in request.form:
            return redirect(
                url_for('editorAccion', accion_id=request.form['accion_id']))
        elif 'eliminarAcc' in request.form:
            query = s.query(Accion)
            pk = request.form['accion_id']
            query = query.filter(Accion.id == pk).first()
            s.delete(query)
            s.commit()
            acciones = Accion.getActionsOfCampaign(campanya_id)

    return render_template('adminacciones.html',
                           title='Acción',
                           wallet=salary,
                           email=email,
                           name=given_name,
                           w3=web3,
                           user=user,
                           acciones=acciones,
                           campanya=campanya)
Exemplo n.º 29
0
def insert(itemList):
    init()
    # create a new session
    session = Session()
    session.add_all(itemList)
    session.commit()
    session.close()
    def add_twitch_clip(self, id):
        ret = False
        #print(id)
        if (storageSystem.get_twitch_clip(id) != None):
            return ret

        session = Session()
        clipObject = twitchmisc.getClipObjects([id])
        if (len(clipObject) == 0 or clipObject[0] == None):
            return False

        #print (clipObject[0])

        try:
            session.add(clipObject[0])
            session.commit()
            #update_clips(all_clip_ids, all_clips)
            for i in range(len(clipObject)):
                if clipObject[i].id not in all_clip_ids:
                    session.expunge(clipObject[i])
                    all_clips.append(clipObject[i])
                    all_clip_ids.append(clipObject[i].id)

            ret = True
        except:
            ret = False
        finally:
            session.close()
            return ret