Ejemplo n.º 1
0
def main(start_date, end_date, email_recp):
    """
    driver function
    """
    process_date_from = parse(start_date)
    process_date_to = parse(end_date)

    if process_date_from.month != (process_date_to + timedelta(days=-1)).month:
        logger.error('Please enter dates for same month. Exiting...')
        return

    # Create Spreadsheet if not already done
    spreadsheet_id = gdrive.get_sheet_id(SHEET_NAME)
    if not spreadsheet_id:
        spreadsheet_id = gsheet.create_spreadsheet(SHEET_NAME)
    logger.info(f"spreadsheet_id={spreadsheet_id}")

    if not spreadsheet_id:
        logger.error('unable to create spreadsheet. Exiting!!!')
        return

    # Add a sheet for current month
    current_sheet_name = process_date_from.strftime("%Y%m")
    gsheet.add_sheet(spreadsheet_id, current_sheet_name)

    # Get the emails for the given date range
    mime_messages = gmail.get_mails(process_date_from, process_date_to)
    logger.info('total number of messgaes = %s' % len(mime_messages))

    # Parse and extract the data from emails
    records = []
    for message_id, mime_message in mime_messages.items():
        data = gmail_parser.parse(mime_message)
        if not data:
            logger.warning('couldnt parse %s' % mime_message['subject'])
            continue
        data = __enrich(data, mime_message, message_id)
        records.append(data)
        logger.debug(data)

    # Write the data to google sheet
    HEADER = ['date', 'amount', 'seller', 'tx_type', 'category', 'id']
    request = []
    for record in records:
        expense = [record.get(name) or '' for name in HEADER]
        request.append(expense)

    if request:
        gsheet.write_to_sheet(spreadsheet_id, current_sheet_name, request)
        gsheet.de_duplicate(spreadsheet_id, current_sheet_name)

    # Generate Expense report and email it.
    report_date = process_date_from
    expense_report = report.generate(spreadsheet_id, current_sheet_name,
                                     process_date_from, process_date_to)
    logger.debug(expense_report)
    send_mail.send_message(
        'Expense report : ' + report_date.strftime('%Y-%m-%d'), expense_report,
        email_recp)
Ejemplo n.º 2
0
def register():
    form = RegForm()
    if request.method == "POST":
        user = request.form['username']
        passw = request.form['password']
        email = request.form['email']
        print(user, passw, email)
        try:

            if user != '' and passw != '' and email_validator.validate_email(email) and \
                    len(user) <= 30 and len(email) <= 30:
                cur.execute("SELECT * FROM users WHERE username = %s",
                            (user, ))
                if cur.fetchall() == []:
                    code = ''.join(
                        sample(['1', '2', '3', '4', '5', '6', '7', '8', '9'],
                               6))
                    cur.execute(
                        '''INSERT INTO users (username, password, email, verified, code, 
                    avatar)
                    VALUES (
                    %s,
                    %s,
                    %s,
                    False,
                    %s,
                    %s
                    );''', (user, generate_password_hash(passw), email, code,
                            'default_avatar.jpg'))
                    con.commit()
                    session['user-to-ver'] = user
                    send_message(email, code)
                    return redirect(url_for('verification'))
                return render_template('registration.html')
            else:
                return render_template('registration.html',
                                       title='Sign In',
                                       form=form)
        except email_validator.EmailSyntaxError:
            return redirect(url_for('register', title='Sign In', form=form))
    else:
        return render_template('registration.html', title='Sign In', form=form)
Ejemplo n.º 3
0
def main(_):
    #make environment of simple video game.
    env = emulator.Emulator()
    #env = gym.make('Breakout-v0')

    sess = tf.Session()

    #build network.
    q_network = Dqn(sess=sess, env=env, name="main")
    target_network = Dqn(sess=sess, env=env, name="target")

    sess.run(tf.global_variables_initializer())

    #initialize all variables, especially copy q_net weights to the target network
    copy_weights_op = train.copy_weights(q_scope_name="main", target_scope_name="target")
    sess.run(copy_weights_op)

    saver = tf.train.Saver()

    if FLAGS.model_dir != '':

        saver.restore(sess, FLAGS.model_dir + "model.ckpt")
        
        model_dir = FLAGS.model_dir
        
    else :
        print("TRAINING")
        start = time.time()
        
        train.train(env=env,
                    model=q_network,
                    target_net=target_network,
                    FLAGS=FLAGS)
        
        print_time(time.time() - start)
        
        send_message()
        
        # if not FLAGS.no_save:
        #     print("The model was not saved.")
        # else :
        model_dir = save_model.save(saver=saver, sess=q_network.sess)
 def query(self):
     print ("Querying...")
     for year, month, day, time in database.appointments:
         if str(type(database.appointments[year, month, day, time])) !="<type \'str\'>":
             if database.appointments[year, month, day, time].sent == False:                            
                 if database.appointments[year, month, day, time].email_bool == True:
                     company = database.preferences["company"]
                     sender = database.current_user
                     sender_email = "*****@*****.**"
                     password = "******"
                             
                     recipient_name = database.appointments[year, month, day, time].client
                     recipient_email = database.clients[recipient_name].email
                     
                     for i in database.possible_times:
                         ntime = database.possible_times[time]
                         if i == time:
                             time = i
                     if send_mail.send_message(company, sender, sender_email, password, recipient_email, recipient_name, year, month, day, ntime) == 0:
                         database.appointments[year, month, day, time].sent = True
                         print ("Sent message to "+recipient_name+" for appointment "+str(year)+", "+str(month)+", "+str(day)+str(time))
                     else:
                         print ("Error sending message to "+recipient_name+" for appointment "+str(year)+", "+str(month)+", "+str(day)+str(ntime))
Ejemplo n.º 5
0
def edit_profile(id):
    user = sess.query(Users).filter_by(id=int(id), verified=True).first()
    if 'user-id' in session and user:
        if request.method == "POST":
            old_email = user.email
            username = request.form['username']
            passw = request.form['password']
            email = request.form['email']
            file = request.files['file']
            try:
                if username and passw and email and len(username) <= 30 and len(email) <= 30:
                    code = ''.join(sample(['1', '2', '3', '4', '5', '6', '7', '8', '9'], 6))
                    if email_validator.validate_email(email):
                        if file and allowed_file(file.filename):
                            filename = 'username-' + secure_filename(file.filename)
                            print(filename)
                            file.save(os.path.join(UPLOAD_FOLDER, filename))
                            sess.query(Users).filter_by(id=id).update(
                                {'username': username,
                                 'password': generate_password_hash(passw),
                                 'email': email,
                                 'avatar': filename,
                                 'code': code,
                                 'verified': False
                                 }
                            )
                        else:
                            sess.query(Users).filter_by(username=username).update(
                                {'username': username,
                                 'password': generate_password_hash(passw),
                                 'email': email,
                                 'avatar': 'default_avatar.jpg',
                                 'code': code,
                                 'verified': False
                                 }
                            )
                        sess.commit()
                        print(email, old_email)
                        if email == old_email:
                            print('A')
                            sess.query(Users).filter_by(id=id).update({'verified': True})
                            sess.commit()
                            session['user-id'] = user.id
                            return redirect(url_for('home'))
                        else:
                            print('B')
                            session.pop('user-to-ver-id', None)
                            session['user-to-ver-id'] = user.id
                            send_message(email, code)
                            return redirect(url_for('verification'))
                    else:
                        return redirect(url_for('edit_profile', id=id))
                else:
                    return redirect(url_for('edit_profile', id=id))
            except email_validator.EmailSyntaxError:
                print('skdk')
                return render_template('edit.html')
        else:
            if session['user-id'] == int(id):
                return render_template('edit.html')
            return redirect(url_for('login'))
    else:
        return '<h1>Такого пользователя не существует</h1>'
Ejemplo n.º 6
0
def edit_profile(username):
    cur.execute(
        'SELECT username FROM users WHERE username = %s and verified = true',
        (username, ))
    if cur.fetchall() and 'user' in session:
        if request.method == "POST":
            cur.execute("SELECT email FROM users WHERE username = %s",
                        (username, ))
            old_email = cur.fetchall()[0][0]
            user = request.form['username']
            passw = request.form['password']
            email = request.form['email']
            file = request.files['file']
            cur.execute("SELECT * FROM users WHERE username = %s", (user, ))
            try:
                print((session['user'] == user))
                if user and passw and email_validator.validate_email(email) and \
                        (cur.fetchall() == [] or session['user'] == user) and \
                        len(user) <= 30 and len(email) <= 30:
                    code = ''.join(
                        sample(['1', '2', '3', '4', '5', '6', '7', '8', '9'],
                               6))
                    if file and allowed_file(file.filename):
                        filename = 'username-' + secure_filename(file.filename)
                        print(filename)
                        file.save(os.path.join(UPLOAD_FOLDER, filename))
                        cur.execute(
                            '''UPDATE users
                                        SET username = %s,
                                        password = %s,
                                        email = %s,
                                        avatar = %s,
                                        code = %s,
                                        verified = false
                                        WHERE username = %s;
                                        ''', (
                                user,
                                generate_password_hash(passw),
                                email,
                                filename,
                                code,
                                username,
                            ))
                    else:
                        cur.execute(
                            '''UPDATE users
                                        SET username = %s,
                                        password = %s,
                                        email = %s,
                                        avatar = %s,
                                        code = %s,
                                        verified = false
                                        WHERE username = %s;
                                        ''', (
                                user,
                                generate_password_hash(passw),
                                email,
                                code,
                                username,
                            ))
                    con.commit()
                    print(email, old_email)
                    if email == old_email:
                        print('A')
                        cur.execute(
                            '''UPDATE users
                                        SET verified = true
                                        WHERE username = %s;
                                        ''', (user, ))
                        session['user'] = user
                        return redirect(url_for('home'))
                    else:
                        print('B')
                        session.pop('user-to-ver', None)
                        session['user-to-ver'] = user
                        send_message(email, code)
                        return redirect(url_for('verification'))
                else:
                    return redirect(url_for('edit_profile', username=username))
            except email_validator.EmailSyntaxError:
                print('skdk')
                return render_template('edit.html')
        else:
            if session['user'] == username:
                return render_template('edit.html')
            return redirect(url_for('login'))
    else:
        return '<h1>Такого пользователя не существует</h1>'
 def test_send_mail(self):
     message = send_mail.create_message_with_attachment(
         SendMailTest.TEST_USER, SendMailTest.RECIPIENT, 'Test', 'Hello!',
         'files/photo.jpg')
     sent_message = send_mail.send_message(self.service, 'me', message)
     self.assertIsNotNone(sent_message)
Ejemplo n.º 8
0
model_dir = "/app/bin_op/model"
file_prefix = "GBPJPY_lstm_close_divide_2_m600_term_30_hid1_60_hid2_0_hid3_0_hid4_0_drop_0.0_bid_merg_2_set_ALL.hdf5.90*17"
model_file = os.path.join(model_dir, file_prefix)

app = Flask(__name__)

if os.path.isfile(model_file):
    model = load_model(model_file)
    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    print("load model")
else:
    msg = "the Model not exists!"
    print(msg)
    m.send_message("uwsgi " + machine + " ", msg)


def do_predict(retX):
    #print(retX.shape)
    #start = time.time()
    res = model.predict(retX, verbose=0, batch_size=1)

    #elapsed_time = time.time() - start
    #print("elapsed_time:{0}".format(elapsed_time) + "[sec]")

    #print(res)

    #K.clear_session()
    return res
Ejemplo n.º 9
0
 def send_code(self):
     send_message(self.email, self.code)