Exemplo n.º 1
0
def get_financial_information():
    chart_plot = ''
    fundamentals_company_name = ''
    fundamentals_sector = ''
    fundamentals_industry = ''
    fundamentals_marketcap = ''
    fundamentals_exchange = ''

    wiki = ''
    selected_stock = ''

    # check if logout
    logout = request.args.get('action')
    if (logout == 'logout'):
        session.clear()
        return render_template('welcome.html', web_root_path=web_root_path)

    # check if user already logged in with session user name
    if 'user_name' in session:
        user_name = session.get('user_name')
    else:
        # collect code and state from login
        code = request.args.get('code')
        user_name, is_active = IsSubscriberLoggedIn(code)
        if (is_active):
            session['user_name'] = user_name
        else:
            session.clear()
            return render_template('welcome.html', web_root_path=web_root_path)


    if (request.method == 'POST'):
        selected_stock = request.form['selected_stock']
        fundamentals = get_fundamental_information(selected_stock)

        if not  fundamentals[0] is np.NaN:
            fundamentals_company_name = Markup("<b>" + str(fundamentals[0]) + "</b><BR><BR>")
        if not fundamentals[1] is np.NaN:
            fundamentals_sector = Markup("Sector: <b>" + str(fundamentals[1]) + "</b><BR><BR>")
        if not fundamentals[2] is np.NaN:
            fundamentals_industry = Markup("Industry: <b>" + str(fundamentals[2]) + "</b><BR><BR>")
        if not fundamentals[3] is np.NaN:
            fundamentals_marketcap = Markup("MarketCap: <b>$" + str(fundamentals[3]) + "</b><BR><BR>")
        if not fundamentals[4] is np.NaN:
            fundamentals_exchange = Markup("Exchange: <b>" + str(fundamentals[4]) + "</b><BR><BR>")

        wiki = get_wikipedia_intro(selected_stock)
        chart_plot = get_plot_prediction(selected_stock)

    return render_template('stock-market-report.html',
        options_stocks=options_stocks,
        selected_stock = selected_stock,
        chart_plot=chart_plot,
        wiki = wiki,
        fundamentals_company_name = fundamentals_company_name,
        fundamentals_sector = fundamentals_sector,
        fundamentals_industry = fundamentals_industry,
        fundamentals_marketcap = fundamentals_marketcap,
        fundamentals_exchange = fundamentals_exchange,
        web_root_path=web_root_path)
Exemplo n.º 2
0
def export_posts(user_id):
    try:
        # read user posts from database 
        user = User.query.get(user_id)
        _set_task_progress(0)
        data = []
        i = 0
        total_posts = user.posts.count()
        for post in user.posts.order_by(Post.timestamp.asc()):
            data.append({'body': post.body,
                         'timestamp': post.timestamp.isoformat() + 'Z'})
            time.sleep(5)
            i += 1
            _set_task_progress(100 * i // total_posts)
        send_email('[Microblog] Your blog posts',
                sender=app.config['ADMINS'][0], recipients=[user.email],
                text_body=render_template('email/export_posts.txt', user=user),
                html_body=render_template('email/export_posts.html', user=user),
                attachments=[('posts.json', 'application/json',
                              json.dumps({'posts': data}, indent=4))],
                sync=True)
    except:
        # handle unexpected errors
        _set_task_progress(100)
        app.logger.error('Unhandled exception', exc_info=sys.exc_info())
Exemplo n.º 3
0
def index():
    form1 = EnterDBInfo(request.form)
    form2 = RetrieveDBInfo(request.form)

    if request.method == 'POST' and form1.validate():
        data_entered = Data(notes=form1.dbNotes.data)
        try:
            db.session.add(data_entered)
            db.session.commit()
            db.session.close()
        except:
            db.session.rollback()
        return render_template('thanks.html', notes=form1.dbNotes.data)

    if request.method == 'POST' and form2.validate():
        try:
            num_return = int(form2.numRetrieve.data)
            query_db = Data.query.order_by(Data.id.desc()).limit(num_return)
            for q in query_db:
                print(q.notes)
            db.session.close()
        except:
            db.session.rollback()
        return render_template('results.html',
                               results=query_db,
                               num_return=num_return)

    return render_template('index.html', form1=form1, form2=form2)
Exemplo n.º 4
0
def predict():
    Fuel_Type_Diesel=0
    if request.method == 'POST':
        Year = int(request.form['Year'])
        Present_Price=float(request.form['Present_Price'])
        Kms_Driven=int(request.form['Kms_Driven'])
        Kms_Driven2=np.log(Kms_Driven)
        Owner=int(request.form['Owner'])
        Fuel_Type_Petrol=request.form['Fuel_Type_Petrol']
        if(Fuel_Type_Petrol=='Petrol'):
                Fuel_Type_Petrol=1
                Fuel_Type_Diesel=0
        else:
            Fuel_Type_Petrol=0
            Fuel_Type_Diesel=1
        Year=2020-Year
        Seller_Type_Individual=request.form['Seller_Type_Individual']
        if(Seller_Type_Individual=='Individual'):
            Seller_Type_Individual=1
        else:
            Seller_Type_Individual=0	
        Transmission_Mannual=request.form['Transmission_Mannual']
        if(Transmission_Mannual=='Mannual'):
            Transmission_Mannual=1
        else:
            Transmission_Mannual=0
        prediction=model.predict([[Present_Price,Kms_Driven2,Owner,Year,Fuel_Type_Diesel,Fuel_Type_Petrol,Seller_Type_Individual,Transmission_Mannual]])
        output=round(prediction[0],2)
        if output<0:
            return render_template('index.html',prediction_texts="Sorry you cannot sell this car")
        else:
            return render_template('index.html',prediction_text="You Can Sell The Car at {}".format(output))
    else:
        return render_template('index.html')
Exemplo n.º 5
0
def action(changePin, action):
   # Convert the pin from the URL into an integer:
   changePin = int(changePin)
   # Get the device name for the pin being changed:
   deviceName = pins[changePin]['name']
   # If the action part of the URL is "on," execute the code indented below:
   if action == "on":
      # Set the pin high:
      GPIO.output(changePin, GPIO.HIGH)
      # Save the status message to be passed into the template:
      message = "Turned " + deviceName + " on."
   if action == "off":
      GPIO.output(changePin, GPIO.LOW)
      message = "Turned " + deviceName + " off."

   # For each pin, read the pin state and store it in the pins dictionary:
   for pin in pins:
      pins[pin]['state'] = GPIO.input(pin)

   # Along with the pin dictionary, put the message into the template data dictionary:
   templateData = {
      'pins' : pins
   }

   return render_template('main.html', **templateData)
Exemplo n.º 6
0
def home():
    if request.method == 'GET':
        return render_template ('reg.html')
    elif request.method == 'POST':
        form = request.form 
        print (form['user'], form['pass'])
        return 'POST'
Exemplo n.º 7
0
    def get(self, p=''):
        hide_dotfile = request.args.get('hide-dotfile', request.cookies.get('hide-dotfile', 'no'))

        path = os.path.join(root, p)
        files = xml_bring_names(xml_url)

        if path in get_all_folders(files):
            print(get_all_folders(files))
            contents = []
            for filename in get_files_list(files, path[:-1]):
#                print(get_files_list(files, path[:-1]))
                info = {}
                info['type'] = dir_or_file(filename)
                if info['type'] == "dir":
                    info['name'] = filename[:-1]
                else:
                    info['name'] = filename
#                print(info)
                contents.append(info)
            page = render_template('index.html', path=p, contents=contents, hide_dotfile=hide_dotfile)
            result = make_response(page, 200)
            result.set_cookie('hide-dotfile', hide_dotfile, max_age=16070400)
        elif path in files:
            download_link = 'https://%s.blob.core.windows.net/%s/%s' % (storage_name, container_name, path)
            result = redirect(download_link, 301)
        else:
            result = make_response('Not found', 404)
        return result
Exemplo n.º 8
0
def result():
   if request.method == 'POST':
      formList = []
      formList.append(str(request.form['age']))
      formList.append(str(request.form['BloodPressure']))
      formList.append(str(1.02))
      formList.append(str(request.form['albumin']))
      formList.append(str(request.form['sugar']))
      formList.append(str("normal"))
      formList.append(str("notpresent"))
      formList.append(str("notpresent"))
      formList.append(str(request.form['bloodGlucose']))
      formList.append(str(request.form['bloodUrea']))
      formList.append(str(5.23))
      formList.append(str(130))
      formList.append(str(6.5))
      formList.append(str(request.form['haemoglobin']))
      formList.append(str(request.form['packed']))
      formList.append(str(request.form['white']))
      formList.append(str(request.form['red']))
      formList.append(str(request.form['hypertension']))
      formList.append(str("no"))
      formList.append(str("no"))
      formList.append(str(request.form['appetite']))
      formList.append(str("no"))
      formList.append(str(request.form['anaemia']))

      result = azureMl(formList)

      if result == "ckd":
          result = "Chronic Kidney Disease."
      else:
          result = "Not a Chronic Kidney Disease."

      return render_template("result.html",result = result)
Exemplo n.º 9
0
def index():
    pattern = request.args.get('pattern', False)
    stocks = {}

    with open('datasets/symbols.csv') as f:
        for row in csv.reader(f):
            stocks[row[0]] = {'company': row[1]}

    if pattern:
        for filename in os.listdir('datasets/daily'):
            df = pandas.read_csv('datasets/daily/{}'.format(filename))
            pattern_function = getattr(talib, pattern)
            symbol = filename.split('.')[0]

            try:
                results = pattern_function(df['Open'], df['High'], df['Low'],
                                           df['Close'])
                last = results.tail(1).values[0]

                if last > 0:
                    stocks[symbol][pattern] = 'bullish'
                elif last < 0:
                    stocks[symbol][pattern] = 'bearish'
                else:
                    stocks[symbol][pattern] = None
            except Exception as e:
                print('failed on filename: ', filename)

    return render_template('index.html',
                           candlestick_patterns=candlestick_patterns,
                           stocks=stocks,
                           pattern=pattern)
Exemplo n.º 10
0
def sign_up():
    if request.method == 'POST':
        email = request.form.get('email')
        first_name = request.form.get('firstName')
        password1 = request.form.get('password1')
        password2 = request.form.get('password2')

        user = User.query.filter_by(email=email).first()
        if user:
            flash('Email already exists.', category='error')
        elif len(email) < 4:
            flash('Email must be greater than 3 characters.', category='error')
        elif len(first_name) < 2:
            flash('First name must be greater than 1 character.', category='error')
        elif password1 != password2:
            flash('Passwords don\'t match.', category='error')
        elif len(password1) < 7:
            flash('Password must be at least 7 characters.', category='error')
        else:
            new_user = User(email=email, first_name=first_name, password=generate_password_hash(
                password1, method='sha256'))
            db.session.add(new_user)
            db.session.commit()
            login_user(new_user, remember=True)
            flash('Account created!', category='success')
            return redirect(url_for('views.home'))

    return render_template("sign_up.html", user=current_user)
Exemplo n.º 11
0
def search():
    search_form = SearchForm()
    if request.method == 'GET':
        return render_template('search.html', form=search_form, result=None)
    else:
    return render_template('search.html', form=search_form, result=search_form.get_result())

@app.route('/dashboard', methods=['GET', 'POST'])
def dashboard():
    db = OracleDb()

query1  = (
                db.sqlalchemy_session.query(
                                            User.user_name,
                                            func.count(userSkill.news_name).label('news_count')
                                          ).\
                                    outerjoin(userSkill).\
                                    group_by(User.user_id,User.user_name)
               ).all()

query2 = (
        db.sqlalchemy_session.query(
            ormSkill.news_name,
            func.count(userSkill.user_id).label('user_count')
        ). \
            outerjoin(userSkill). \
            group_by(ormSkill.news_name)
    ).all()

    names, news_counts = zip(*query1)
    bar = go.Bar(
        x=names,
        y=news_counts
    )

    news, user_count = zip(*query2)
    pie = go.Pie(
        labels=news,
        values=user_count
    )

    data = {
                "bar":[bar],
                "pie":[pie]
           }
    graphsJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
    return render_template('dashboard.html', graphsJSON=graphsJSON)
Exemplo n.º 12
0
def index():

    '''
    View root page function that returns the index page and its data
    '''

    message = 'Hello World'
    return render_template('index.html',message = message)
Exemplo n.º 13
0
def login():
	if request.method == 'POST':
		username = request.form.get('username')
		passwd = request.form.get('passwd')
		sql = 'select * from dujiayang where username = %s and password = %s' %(username,passwd) ##查看库里有没有用户和密码
		if cur.execute(sql):
			hello = "welcom to my page"
			sql = 'select * from dujiayang where username = %s' %username
			cur.execute(sql)
			res = cur.fetchone()
			print res
			return redirect('ok.html',hello=hello,res=res)       #到ok页面
			
		else:
			error = '用户名或密码错误,please check'
			return render_template('login.html',error=error)
	return render_template('login.html')
Exemplo n.º 14
0
def login():

    form = LoginForm()
    if form.validate_on_submit():
        if form.email.data == "*****@*****.**" and form.password.data == "password":
            flash("You successfully logged in!","success")
            return redirect(url_for('home'))
        else:
            flash('Login unsuccessful, please check username and password','danger')
    return render_template('login.html',title='Login',form=form)
Exemplo n.º 15
0
def login():
    login_form = LoginForm()
    if login_form.validate_on_submit():
        user = User.query.filter_by(email = login_form.email.data).first()
        if user is not None and user.verify_password(login_form.password.data):
            login_user(user,login_form.remember.data)
            return redirect(request.args.get('next') or url_for('main.index'))

        flash('Invalid username or Password')

    title = "watchlist login"
    return render_template('auth/login.html',login_form = login_form,title=title)
Exemplo n.º 16
0
def login():
   error = None
   
   if request.method == 'POST':
      if request.form['username'] != 'admin' or \
         request.form['password'] != 'admin':
         error = 'Invalid username or password. Please try again!'
      else:
         flash('You were successfully logged in')
         return redirect(url_for('index'))
			
   return render_template('login.html', error = error)
Exemplo n.º 17
0
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email = form.email.data, username = form.username.data,password = form.password.data)
        db.session.add(user)
        db.session.commit()

        mail_message("Welcome to blogt","email/welcome_user",user.email,user=user)
        
        return redirect(url_for('auth.login'))
        title = "Account"
    return render_template('auth/register.html',registration_form = form)
Exemplo n.º 18
0
def scores():

	if request.method == "GET":

		#return login form
		return render_template("scores.html")

	if request.method == "POST":

		#connects to collegeboard.org
		browser = RoboBrowser()
		login_url = 'https://account.collegeboard.org/login/login?appId=287&DURL=https://apscore.collegeboard.org/scores/view-your-scores'
		browser.open(login_url)

		#logs in to collegeboard.org with user credentials
		form = browser.get_form(id='loginForm')
		form['person.userName'].value = request.form.get("username")
		form['person.password'].value = request.form.get("password")
		form.serialize()
		browser.submit_form(form)

		#redirects to AP scores page on collegeboard.org
		browser.open('https://apscore.collegeboard.org/scores/view-your-scores')

		#populates exams_final with exam names scraped from collegeboard.org
		exams = browser.select(".span5 > h4")
		exams_final = []
		for exam in exams:
			exam = str(exam)
			exams_final.append(exam[4:-5])

		#populates scores_final with scores scraped from collegeboard.org
		scores = browser.select(".span5 > span > em")
		scores_final = []
		for score in scores:
			score = str(score)
			scores_final.append(score[4:-5])

		#returns scores page
		return render_template("scored.html", exams=exams_final, scores=scores_final)  
Exemplo n.º 19
0
def index():
    mars = mongo.db.mars.find()
    return render_template("index.html", mars=mars)
    @app.route("/scrape")

def scraper():
    mars = mongo.db.mars
    mars_data = scrape_mars.scrape()
    mars.update({}, mars_data, upsert=True)
    return redirect("/", code=302)

if __name__ == "__main__":
    app.run(debug=True)
Exemplo n.º 20
0
def newOnlineshopping():
    if 'username' not in login_session:
        return redirect('/login')
    if request.method == 'POST':
        newOnlineshopping = Onlineshopping(
            name=request.form['name'])
        session.add(newOnlineshopping)
        flash
        ('New Onlineshopping %s Successfully Created' % newOnlineshopping.name)
        session.commit()
        return redirect(url_for('showshoppingwebsites'))
    else:
        return render_template('newshoppingwebsite.html')
Exemplo n.º 21
0
def main(): 
   with open('config.config') as f:
      for token in read_by_tokens(f):
         print(token)
         
   # For each pin, read the pin state and store it in the pins dictionary:
  
   # Put the pin dictionary into the template data dictionary:
   templateData = {
      'config' : config
      }
   # Pass the template data into the template main.html and return it to the user
   return render_template('main.html', **templateData)
Exemplo n.º 22
0
def register():
	if request.method == 'POST':
		users = mongo.db.users
		existing_user = users.find_one({'name':request.form['username']})

		if existing_user is None:
			hashpwd = bcrypt.hashpw(request.form['pass'].encode('UTF-8'),bcrypt.gensalt())
			users.insert({'name':request.form['username'],'password':hashpwd})
			session['username'] = request.form['username']
			return url_for('index')

		return 'username already exist'

	return render_template('register.html')
Exemplo n.º 23
0
def reg():
	if request.method == 'POST':
		username = request.form.get('username') 
		passwd = request.form.get('password')
		cpasswd = request.form.get('cpassword')
		sex = request.form.get('sex')
		age = request.form.get('age')
		phone = request.form.get('phone')
		email = request.form.get('email')
		if passwd == cpasswd:
			utils.signin(username,passwd,sex,age,phone,email,role)
		else:
			error = '2次密码不一致,please input again'
			return render_template('register.html',error=error)
	return renden_template('register.html',error=error)
Exemplo n.º 24
0
def register():
    
    form = RegistrationForm()
    
    # if form.validate_on_submit():
    #     flash(f'Accout created for {form.username.data}!',"success")
    #     return redirect(url_for('home'))
    if form.validate_on_submit():
        hashed_password = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user = User(username=form.username.data,email=form.email.data,password=hashed_password)   
        db.session.add(user)
        db.session.commit()
        flash('Your account has been created successfully! You are now able to login','success')
        return redirect(url_for('login'))
    return render_template('register.html',title='Register',form=form)
Exemplo n.º 25
0
def home():
    t = str(request.form.get('topic')) #, 'technology and robots'
    t = list(eval('["' + t + '"]'))
    vt = vectorizer_TF_IDF.transform(t)
    tt = nmf_model.transform(vt)
    dist_order = pairwise_distances(tt,doc_topic,metric='cosine').argsort()
    sorted_ind = list(chain(*dist_order.tolist()))

    with open('/Users/elena/Desktop/Metis/Project_4_Ted/Project-4-Ted/df.pkl', 'rb') as picklefile:
        df = pickle.load(picklefile)
    #df = df.dropna()
    df = df.reindex(columns=['Video ID', 'Title', 'Year', 'Positive Comments Score'])
    df = df.reindex(index=sorted_ind).head(5).sort_values('Positive Comments Score', ascending=False)
    #emb = 'https://www.youtube.com/watch?v=' + str(df['Video ID'][0])

    return render_template('index.html', recommendation=df.to_html()) #emb=emb
Exemplo n.º 26
0
def future():
    crop = "NONE"
    #forces conditional loop to run
    if crop == 'NONE':
        crop = request.form.get('crop')
        if crop == 'Corn':
            ans = cornFuture()
        elif crop == 'Cotton':
            ans = cottonFuture()
        elif crop == 'Soybeans':
            ans = soybeanFuture()
        else:
            ans = "Error Unknown!"
    else:
        print("Error Unknown!")
    return render_template('future.html', crop = crop, ans = ans, corn=cornFuture, cotton=cottonFuture, soybean=soybeanFuture, get_future=get_future)
Exemplo n.º 27
0
def login():
    if request.method == 'POST':
        email = request.form.get('email')
        password = request.form.get('password')

        user = User.query.filter_by(email=email).first()
        if user:
            if check_password_hash(user.password, password):
                flash('Logged in successfully!', category='success')
                login_user(user, remember=True)
                return redirect(url_for('views.home'))
            else:
                flash('Incorrect password, try again.', category='error')
        else:
            flash('Email does not exist.', category='error')

    return render_template("login.html", user=current_user)
Exemplo n.º 28
0
def index():

    form=NameForm()
    if form.validate_on_submit():
        user=User.query.filter_by(username=form.name.data).first()
        if user is None:#is null create
            user=User(username=form.name.data)
            db.session.add(user)
            db.session.commit()
            session['known']=False
        else:
            session['known']=True

        session['name']=form.name.data
        form.name.data=''
        # name=form.name.data
        return redirect(url_for('index'))#get

    return render_template('index.html',form=form,name=session.get('name'),known=session.get('known',False))
Exemplo n.º 29
0
def hello():
    voter_id = request.cookies.get('voter_id')
    if not voter_id:
        voter_id = hex(random.getrandbits(64))[2:-1]

    vote = None

    if request.method == 'POST':
        redis = get_redis()
        vote = request.form['vote']
        data = json.dumps({'voter_id': voter_id, 'vote': vote})
        redis.rpush('votes', data)

    resp = make_response(render_template(
        'index.html',
        option_a=option_a,
        option_b=option_b,
        hostname=hostname,
        vote=vote,
    ))
    resp.set_cookie('voter_id', voter_id)
    return resp
Exemplo n.º 30
0
def result():
    prompt_text = request.args['text']
    num_results = int(request.args['number'])

    encoded_prompt = tokenizer.encode(prompt_text, add_special_tokens=False, return_tensors="pt")
    prediction_scores, past = model.forward(encoded_prompt)
    
    batch_size, num_input_words, vocabulary_size = prediction_scores.shape
    assert batch_size == 1
    assert vocabulary_size == 50257
    
    list_of_dicts = []

    input_tuples = []
    #add first input word to tuple with no highlight
    first_word = tokenizer.decode(encoded_prompt[0, 0].item())
    input_tuples.append((first_word, "white"))

    predictability = 0

    #loop through input text word by word
    for x in range(0, encoded_prompt.numel()-1):
        prediction_list = [(index.item()) for index in prediction_scores[0, x].topk(100).indices]
        prediction_dict = {}

        predictability = get_predictability_score(num_results, x, prediction_scores, 
                                                    prediction_list, encoded_prompt, 
                                                    vocabulary_size, prediction_dict, predictability)
        list_of_dicts.append(prediction_dict)
        highlight_words(x, prediction_list, input_tuples, encoded_prompt)

    final_score = str(predictability/(encoded_prompt.numel()-1))

    return render_template("home.html", 
                            predictions = list_of_dicts,  
                            usertext = prompt_text, 
                            score = final_score,
                            inputwords = input_tuples)
Exemplo n.º 31
0
def index():
  return render_template('template.html')
Exemplo n.º 32
0
def hello():
  return render_template("index.html")
Exemplo n.º 33
0
def graph():
  return render_template("graph_query.html")