def index(): form = InputForm() if form.validate_on_submit(): session['session_id'] = unicode(uuid4()) session['state'] = form.state.data session['age'] = form.age.data session['zipcode'] = form.zipcode.data session['health'] = form.health.data session['income'] = form.income.data session['hhsize'] = form.hhsize.data if session['income'] and session['hhsize']: caps = CalcAcaSubsidy(session['income'], session['hhsize']) if caps: session['premium_cap'] = int(caps[1]) else: session['premium_cap'] = 0 else: session['premium_cap'] = 0 session['query_weights'] = get_weights(session['state'], str(session['health'])) log_query( session_id = session['session_id'], state = session['state'], age = session['age'], zipcode = session['zipcode'], health = session['health'] ) return redirect(url_for('main.results')) return render_template('index.html', form=form)
def get_profile(request): form = InputForm(request.GET) if not form.is_valid(): error_msg = "" for k, v in form.errors.items(): error_msg += "%s: %s\n" % (k, ", ".join(v)) return HttpResponse(json.dumps({ 'success': False, 'msg': error_msg }), content_type="application/json") subscriber_id = form.cleaned_data['userName'] transaction_id = form.cleaned_data['transactionId'] free_quota = form.cleaned_data['freeQuota'] pcrf_client = PCRFClient() profile_result = pcrf_client.get_profile(subscriber_id=subscriber_id, free_quota=free_quota) logger.debug("Getting profile for user (%s), transaction id: (%s)", subscriber_id, transaction_id) if not profile_result['action_result']: response = { 'success': True if profile_result.get('action_error_message').endswith( "does not exist") else profile_result['action_result'], 'msg': profile_result.get('action_error_message'), } if 'not_exist' in profile_result: response['not_exist'] = profile_result['not_exist'] log_action(inspect.stack()[0][3], request, response, transaction_id=transaction_id) return HttpResponse(json.dumps(response), content_type="application/json") topups_result = pcrf_client.get_services(subscriber_id, service_type='topup', free_quota=free_quota) response = { 'success': True if topups_result.get('action_error_message', '').endswith("does not exist") else topups_result['action_result'], 'msg': topups_result.get('action_error_message'), 'profile': profile_result.get('profile'), 'topups': topups_result.get('services') } log_action(inspect.stack()[0][3], request, response, transaction_id=transaction_id) return HttpResponse(json.dumps(response), content_type="application/json")
def blast(): form = InputForm() title = "Blast - " try: with open('content/blast_page.md', encoding='utf-8') as c: name = get_title(c) next(c) c = c.read() except Exception: abort(404) if request.method == 'POST': sequence = request.form.get('id_sequences') file = request.form.get('id_file_text') function = request.form.get('job') print(file) if form.validate() == False: flash('All fields are required.') return render_template('blast.html', content=to_md(c), name=name, form=form, title=title, description="") elif sequence == "" and file == "": flash('You need to at least have one input.') return render_template('blast.html', content=to_md(c), name=name, form=form, title=title, description="") elif sequence != "" and file != "": flash('You can only have one input.') return render_template('blast.html', content=to_md(c), name=name, form=form, title=title, description="") else: if sequence != "" and file == "": query = sequence elif sequence == '' and file != '': query = file if function == 'blastp': records = blastp(query) elif function == 'blastx': records = blastx(query) return render_template('result_blastp.html', records=records, title=title, description="") elif request.method == 'GET': return render_template('blast.html', content=to_md(c), name=name, form=form, title=title, description="")
def input(): form = InputForm() if form.validate_on_submit(): character_name = {form.character_name.data} return redirect(url_for('output', character_name=character_name)) return render_template('input.html', title='Enter Data', form=form)
def submit(): global resp form = InputForm() if form.validate_on_submit(): resp = get_atis(form.icao) return redirect('/success', ) return render_template('submit.html', form=form)
def index(): if request.method == 'GET': return render_template('index.html', params=None) if request.method == 'POST': if request.form['action'] == 'make': form = InputForm(request.form) if form.validate(): params = { 'minstr': form.data['minstr'], 'start_date': form.data['start_date'].strftime('%Y-%m-%d'), 'finish_date': form.data['finish_date'].strftime('%Y-%m-%d') } unique_incidents = get_query_results('query_1.sql', params) chart_data = get_query_results('query_2.sql', params) incidents_by_persons = get_query_results('query_3.sql', params) incidents_by_roads = get_query_results('query_4.sql', params) labels = [x['Caption'] for x in chart_data] values = [x['ver'] for x in chart_data] return render_template( 'index.html', unique_incidents=unique_incidents, labels=labels, values=values, incidents_by_persons=incidents_by_persons, incidents_by_roads=incidents_by_roads, params=params) else: errors = form.errors return render_template('error.html', errors=errors)
def get_session(request): form = InputForm(request.GET) if not form.is_valid(): error_msg = "" for k, v in form.errors.items(): error_msg += "%s: %s\n" % (k, ", ".join(v)) return HttpResponse(json.dumps({ 'success': False, 'msg': error_msg }), content_type="application/json") subscriber_id = form.cleaned_data['userName'] transaction_id = form.cleaned_data['transactionId'] logger.debug("Getting session for user (%s), transaction id: (%s)", subscriber_id, transaction_id) pcrf_client = PCRFClient() result = pcrf_client.query_session(subscriber_id=subscriber_id) response = { 'success': result['action_result'], 'msg': result.get('action_error_message'), 'session': result.get('session') } log_action(inspect.stack()[0][3], request, response, transaction_id=transaction_id) return HttpResponse(json.dumps(response), content_type="application/json")
def input_item(): form = InputForm() if form.validate_on_submit(): filename = 'default.jpg' f = form.Item_icon.data if f: filename = secure_filename(f.filename) f.save(os.path.join('static\icons', filename)) item = Item(Category=form.Category.data, Item_Title=form.Item_Title.data, Item_Description=form.Item_Description.data, Item_Price=form.Item_Price.data, image_file=url_for('static', filename='icons/' + filename)) print(url_for('static', filename='icons/' + filename)) print(item.image_file) db.session.add(item) db.session.commit() flash( f'you have added your last item with product id {item.id} successfully', 'success') return redirect(url_for('home')) Errors = [] fields = [] if form.errors: fields = form.errors.keys() Errors = form.errors.values() return render_template('input_item.html', form=form, errors=Errors)
def main(): form = InputForm() amr = request.args.get('amr') model = request.args.get('model') sent = None if form.validate_on_submit(): sent = amrtotext.run(form.input_amr.data, form.input_amr.model) elif amr is not None: sent = amrtotext.run(amr, model) if sent is not None: app.logger.info('Input: ' + amr) link = "http://bollin.inf.ed.ac.uk:9020/amrtotext?model=" + model + "&amr=" + "+".join( [t for t in amr.split()]) return jsonify( { 'sent': sent.replace("\n", "<br/>").replace(" ", " "), 'link': link }, sort_keys=True, indent=4, separators=(',', ': ')) else: return jsonify({ 'sent': 'ERROR', 'link': '' }, sort_keys=True, indent=4, separators=(',', ': '))
def inputFormDisplay(request, template='upload.html'): """Displays input form that takes fasta and ids files.""" if request.method == 'POST': form = InputForm(request.POST, request.FILES) if form.is_valid(): # create UID sym_task = symTyperTask.objects.create() sym_task.UID = str(sym_task.id) + '.' + str(time.time()) sym_task.params = form.yamlfyParams() sym_task.save() parentDir = os.path.join(settings.SYMTYPER_HOME, sym_task.UID) os.makedirs(parentDir) os.system("""chmod 775 %s"""%(parentDir)) fasta = os.path.join(parentDir, "input.fasta") samples = os.path.join(parentDir, "samples.ids") writeFile(request.FILES['fasta_File'], fasta) writeFile(request.FILES['sample_File'], samples) task = handleForm.delay(fasta, samples, "test", sym_task.UID) return HttpResponseRedirect(reverse("index", args=[sym_task.UID])) else: form = InputForm() context = {'form': form,} return render(request, template, context)
def show_board(): new_board = print_board() form=InputForm() if form.validate_on_submit(): flash("you are validated") else: flash("ehhh...ehh!, form didn't go") return render_template("board.html", form=form, board_1=new_board[0], board_2=new_board[1], board_3=new_board[2])
def input(): form = InputForm() if form.validate_on_submit(): # generate_xls(form.name_of_app.data) generate_schema(form.destinations.data, form.tabs.data) return render_template('input.html', form = form)
def input(): form = InputForm(request.form) if request.method == 'POST' and form.validate(): output = test_function(form.input1.data, form.input2.data) return render_template("output.html", output=output, title='Output') else: flash('Please enter a valid value', 'danger') return render_template("input.html", form=form, title='Input')
def index(): """Страница "Главная" """ form = InputForm() if form.validate_on_submit(): message = form.message.data answer = request.form['req'] return sent(message, answer) return render_template("main.html", title='Главная', form=form, warning='')
def hello(): form = InputForm() if form.validate_on_submit(): message = request.form["message"] name = request.form["name"] note = Note(message=message, name=name) note.add() #return redirect(url_for("success", message=message, name=name, lookupId = note.lookupId)) return render_template("success.html", message=message, name=name, lookupId = note.lookupId) return render_template("index.html", form=form)
def translate(): form = InputForm(request.form) if form.validate(): writer = WriteLike(request.values.get('style')) output_text = writer.style_convert_string(request.values.get('input_text')) return jsonify( {'output': output_text} ) return jsonify( {'errors': form.errors})
def input(): form = InputForm() if form.validate_on_submit(): response = requests.get(form.github_url.data) print(form.github_url.data) if response.status_code == 200: global soup soup = BeautifulSoup(response.text, 'html.parser') output_dict = total_issues() return render_template('output.html', output_dict=output_dict) return render_template('input.html', title='Input', form=form)
def translate(): form = InputForm(request.form) if form.validate(): writer = WriteLike(request.values.get('style')) output_text = writer.style_convert_string( request.values.get('input_text')) return jsonify({'output': output_text}) return jsonify({'errors': form.errors})
def home(): form = InputForm() prediction_message = Prediction_Message() if form.validate_on_submit(): prediction_message.initial, prediction_message.pred1, prediction_message.pred2, prediction_message.pred3 = \ predict(model, form.tweet.data, glove.get_glove_emb(), sequence_length=62, use_gpu=False) # if form.tweet.data == 'helloworld': # flash('Entered correct input!', 'success') # return redirect(url_for('home')) # else: # flash('Invalid Tweet!', 'danger') return render_template('home.html', title='DeepFeels', form = form, prediction_message = prediction_message)
def home(): form = InputForm() if form.validate_on_submit(): prediction = simulator.run_simulation([ form.num_col.data, form.num_brit.data, form.general.data, form.offensive.data, form.allies.data ]) print(prediction) flash(f'It looks like the {prediction} win this one!', 'info') # return redirect(url_for('home')) return render_template('index.html', form=form)
def char_gen_form(): form = InputForm() if form.validate_on_submit(): random.seed(form.name_input.data) char_num = "%0.16d" % random.randint(0, 9999999999999999) char_dict = char_gen.main(form.name_input.data, char_num) return render_template("char-gen-result.html", form=form, char_dict=char_dict) return render_template("char-gen-form.html", form=form)
def hello(): form = InputForm() if form.validate_on_submit(): principle = int(request.form['principle']) interestRateYear = float(request.form['interestRateYear']) periodYears = int(request.form['periodYears']) flash('Thanks for the information!') # return periodYears and principle and interestRateYear # return test(principle, interestRateYear, periodYears) return ammortization(principle, interestRateYear, periodYears) # return redirect(url_for('schedule')) return render_template('home.html', title='Input', form=form)
def show_board(): new_board = print_board() form=InputForm() print "test" if form.validate_on_submit(): flash("you are validated") print 'valid test' else: flash("ehhh...ehh!, form didn't go") print 'invalid test' return render_template("test.html", form=form, board_1=new_board[0], \ board_2=new_board[1], \ board_3=new_board[2])
def index(request): result = "" grid = "" if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): if form.cleaned_data.get('grid'): data = form.cleaned_data.get('grid') grid = eval(data) result = best_path.grid_search(grid) else: form = InputForm(initial={'text': 'text here'}) return render(request, 'index.html', {'grid': grid, 'result': result, 'form': form})
def main(): form = InputForm(request.form) if form.validate_on_submit(): contributors = [(form.name_1.data, form.val_1.data), (form.name_2.data, form.val_2.data), (form.name_3.data, form.val_3.data), (form.name_4.data, form.val_4.data)] carrot_image = generate_image(contributors) return render_template('carrot.html', form=form, img_src=convert_pil_image(carrot_image)) print(form.errors) return render_template('carrot.html', form=form, img_src=None)
def show_board(): new_board = print_board() form = InputForm() print "test" if form.validate_on_submit(): flash("you are validated") print 'valid test' else: flash("ehhh...ehh!, form didn't go") print 'invalid test' return render_template("test.html", form=form, board_1=new_board[0], \ board_2=new_board[1], \ board_3=new_board[2])
async def input(): form = InputForm() if form.validate_on_submit(): r_form = await request.form model_type = r_form['model_type'] inp_text = r_form['input_text'] div_factor = r_form['div_factor'] return redirect( url_for('result', model_type=model_type, inp_text=inp_text, div_factor=float(div_factor))) return await render_template('homepage.html', form=form)
def get_dpi_usage(request): form = InputForm(request.GET) if not form.is_valid(): error_msg = "" for k, v in form.errors.items(): error_msg += "%s: %s\n" % (k, ", ".join(v)) return HttpResponse(json.dumps({ 'success': False, 'msg': error_msg }), content_type="application/json") subscriber_id = form.cleaned_data['subscriber_id'] start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] logger.debug( "Getting Subscriber ID: (%s) , start date: (%s), end date: (%s)", subscriber_id, start_date, end_date) data = DPI_XML_REQUEST % { 'subscriber_id': subscriber_id, 'start_date': start_date, 'end_date': end_date } headers = {'Content-Type': 'text/xml'} req = urllib2.Request(DPI_URL, data, headers) response = urllib2.urlopen(req) xml = response.read() #[email protected] res = re.findall( "@example.jaxws.sun.com>\r\nContent-Type: application/x-gzip\r\nContent-Transfer-Encoding: binary\r\n\r\n(.*)\r\n--uuid", xml, re.DOTALL) if res and not res[ 0] == "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00": # gets the gzip binary data into an object to extract .gz file to plain text fio = StringIO.StringIO(res[0]) final = gzip.GzipFile(fileobj=fio) results = [] for line in final.readlines(): line = line.split(',') results.append([line[1], line[2].replace("\n", "")]) response = {"error": False, "errorMessage": "", "results": results} return HttpResponse(json.dumps(response), content_type="application/json") response = { "error": True, "type": "warning", "errorMessage": "Subscriber not found." } return HttpResponse(json.dumps(response), content_type="application/json")
def load(): form = InputForm() if request.method == 'POST': if form.validate() == False: flash ('Invalid entry.') return render_template("load.html", form = form) else: newitem = Item(form.item.data) db.session.add(newitem) db.session.commit() flash ('Added' + " " + '"' + form.item.data + '"' + " to the swotpad.") return redirect('/load') elif request.method == 'GET': return render_template("load.html", form = form)
def index(): cookie_secret = init_secret() cookie = Cookie() form = InputForm() pic = str(random.randint(1, 5)) + ".png" if form.validate_on_submit(): data = form.name.data datas = {'name': data, 'pic': pic} flash('Guk guk, namaku {}!!!'.format(datas['name'])) cookie_ = cookie.set_cookie(data, cookie_secret) response = redirect(url_for('index')) response.set_cookie('data', cookie_) return response data = cookie.get_cookie(cookie_secret) return render_template('index.html', form=form, pic=pic)
def hello_world(): form = InputForm() if form.city.data is None: return render_template('input.html', title='Input Data for Bikeshare', form=form) elif form.submit(): df = bs.load_data(form.city.data, form.month.data, form.day_of_week.data) results = bs.render_result(df) return render_template('result.html', title='Results', results=results) else: return render_template('input.html', title='Input Data for Bikeshare', form=form)
def tan(request): t = None # initial value of result if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): form = form.save(commit=False) radianos = form.radianos t = calculate_tan(radianos) else: form = InputForm() return render_to_response('tan.html', {'form': form, 't': '%.5f' % t if isinstance(t, float) else '' }, context_instance=RequestContext(request))
def index(): form = InputForm(request.form) # tags = [] tags = set() empty = 1 if form.validate_on_submit(): for description in form.desList: fData = description.data['des'] if fData and fData != 'None' and fData not in tags: empty = 0 # tags.append(fData) tags.add(fData) if not empty: title, TagDic, score = ComputeMatch(tags) return render_template('index.html', results=[title, TagDic, score], form=form) return render_template('index.html', form=form)
def submitform(): form = InputForm() user_id = current_user.id user_kategori_wbs = current_user.kategori_wbs user_wbs_spesifik = current_user.wbs_spesifik if request.method == 'POST': file_name = files.save(form.upload_file.data) file_url = files.url(file_name) new_post = Post(user_id=user_id, post_kategori_wbs=user_kategori_wbs, post_wbs_spesifik=current_user.wbs_spesifik, post_wbs_level2=form.select_wbs_level2.data, post_wbs_level3=form.select_wbs_level3.data, post_judul=form.judul.data, post_deskripsi=form.deskripsi.data, post_jenis_toppgun=form.select_jenis_toppgun.data, post_kategori_lean=form.select_kategori_lean.data, post_file_url=file_url, post_wbs_terkait=form.sebutkan.data, post_date=datetime.now()) db.session.add(new_post) db.session.commit() return redirect('profile') return render_template('profile.html', form=form)
def index(params = None): form = InputForm() user = g.user if form.validate_on_submit(): return redirect(url_for('results')) # if form.queryType.data == "vin_query": # return redirect(url_for('results')) if form.queryType.data == "pop_query": form = PopForm() # return redirect(url_for('results')) # return render_template("index.html", # form = pop_form, # user = user) return render_template("index.html", form = form, user = user)
def index(): form = InputForm() #if request.method == 'POST' and form.validate(): if request.method == 'POST': if validate_date(request.form['date']) != 0: #datetime_object = datetime.strptime(request.form['date'], '%Y-%m-%d') print(request.form['city']) print(request.form['date']) city = request.form['city'] date = request.form['date'] if city in image_cities: file = 'images/' + city + '.jpg' table1 = 'images/' + city + ' Temp.jpg' table2 = 'images/' + city + ' Combo.jpg' table3 = 'images/' + city + ' Humidity.jpg' all_images = [file, table1, table2, table3] else: file = 'images/default.jpg' all_images = [file, file, file, file] results = predict_all_attrib(city, date) return render_template('submission.html', city=request.form['city'], date=request.form['date'], all_images=all_images, results=results) else: return render_template('errorindex.html', form=form) return render_template('index.html', form=form)
def main(): form = InputForm() sent = request.args.get('sent') lang = request.args.get('lang') graph = None if form.validate_on_submit(): if hasattr(form.input_sent, 'lang'): graph = parse_sent.run(form.input_sent.data, form.input_sent.lang) else: #compatability with older site graph = parse_sent.run(form.input_sent.data) elif sent is not None: if lang is None: lang = 'en' graph = parse_sent.run(sent, lang) if graph is not None: app.logger.info('Input: ' + sent) hash.update(str(time.time())) hash.update(sent) last = hash.hexdigest() AMRICA.disagree.run("# ::id 1\n" + graph, "tmp" + last + ".png") binpng = open("tmp" + last + ".png", "rb").read() os.remove("tmp" + last + ".png") link = "http://bollin.inf.ed.ac.uk:9010/amreager?lang=" + lang + "&sent=" + "+".join( [t for t in sent.split()]) return jsonify( { 'graph': graph.replace("\n", "<br/>").replace( " ", " "), 'png': base64.b64encode(binpng), 'link': link }, sort_keys=True, indent=4, separators=(',', ': ')) else: return jsonify({ 'graph': 'ERROR', 'png': '', 'link': '' }, sort_keys=True, indent=4, separators=(',', ': ')) return render_template('sentence.html', form=form)
def fetch(): form = InputForm() if request.method == 'POST': if not form.validate(): return render_template('test.html', form=form) else: register_no = form.register_no.data dob = datetime.datetime.strptime(str(form.dob.data), '%Y-%m-%d').strftime('%d-%m-%Y') # # return "Form posted {0} {1}".format(register_no, dob) # # fetch_details(register_no, dob) # s = Scrapper(register_no, dob) # json_data = s.get_json() # return render_template('test.html', form=form, data=json_data) return render_template('test.html', form=form, valid=True) elif request.method == 'GET': return render_template('test.html', form=form)
def populate_from_instance(instance): form = InputForm() for field in form: try: field.data = getattr(instance, field.name) except AttributeError: continue return form
def sent(message, answer): """Обработка запросов с "Главной" """ answers = [ 'Вывод пользователей (введите users)', 'Книга(введите название)', 'Автор(введите имя и фамилию)' ] a = answers.index(answer) form = InputForm() if a == 0: if current_user.id == 1: return redirect('/request/users') else: return render_template("main.html", title='Главная', form=form, warning='Недостаточно прав') elif a == 1: session = db_session.create_session() book = session.query(Books).filter(Books.title == message).first() if book: author = session.query(Author).filter( Author.id == book.author_id).first() genre = session.query(Genre).filter( Genre.id == book.genre_id).first().genre b = "_".join(book.title.strip().split()) url = f'https://ru.wikipedia.org/wiki/{b}' return render_template('books.html', title='Книга', books=[book], names=[author.name], surnames=[author.surname], extra_info=[url], genres=[genre], err='') return render_template('books.html', title='Книга', err='Данной книги у нас нет в наличии') elif a == 2: session = db_session.create_session() try: name, surname = message.split() except ValueError: return render_template( 'authors.html', title='Автор', err='Вы нарушили формат. Напишите только имя и фамилию') author = session.query(Author).filter( Author.name == name, Author.surname == surname).first() if author: url = f'https://ru.wikipedia.org/wiki/{author.name} {author.surname}' return render_template('authors.html', title='Автор', authors=[author], extra_info=[url], err='') return render_template('authors.html', title='Автор', err='Книг данного писателя у нас нет в наличии')
def initiate(request): """Request user's phone number. This would ordinarily be provided by the mobile operator; we need it to correctly simulate interaction .""" data = {} data.update(csrf(request)) if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): request.session['phone_number'] = form.cleaned_data['input'] return HttpResponseRedirect(reverse('interact')) else: form = InputForm() data['form'] = form return render_to_response('initiate.html', data, context_instance=RequestContext(request))
def interact(request): """Accept input from user and display menus from the application""" if 'phone_number' not in request.session: return HttpResponseRedirect(reverse('initiate')) data = {} data.update(csrf(request)) user_input = INITIAL_INPUT if request.method == 'POST': form = InputForm(request.POST) if form.is_valid(): user_input = form.cleaned_data['input'] # Always create a new unbound form (so that previous inputs don't # show up in current form fields) form = InputForm() args = { 'EXTRA': request.session.get('extra', ''), 'LEVEL': request.session.get('level', INITIAL_LEVEL), 'MSISDN': request.session['phone_number'], 'SESSIONID': '1', 'INPUT': user_input } base_url = 'http://wezatele.webfactional.com/maji/maji.php' # base_url = request.build_absolute_uri(reverse('dispatch')) url = '%s?%s' % (base_url, urlencode(args)) response = urlopen(url).read() data['response'] = response level, data['message'], status, extra = response.split('^') request.session['level'] = level request.session['extra'] = extra data['form'] = form data['status'] = status return render_to_response('interact.html', data, context_instance=RequestContext(request))
def index(): #b20 = get_highest_returns() #b20ticks = b20.index last_update_query = cur.execute("""SELECT last_update FROM daily_price ORDER BY date desc LIMIT 1;""") last_update = (cur.fetchall())[0][0] # best_query = cur.execute("""SELECT ticker, ret FROM best_stocks \ # WHERE date_added='%s' ORDER BY ret desc;""" % last_update) # best_sql = cur.fetchall() # best = [d for d in best_sql] best_crisis_query = cur.execute("""SELECT ticker, ret, ret_spy FROM best_crisis \ ORDER BY date_added desc, ret desc LIMIT 4;""" ) best_crisis_sql = cur.fetchall() best_crisis = [b for b in best_crisis_sql] rec_query = cur.execute("""SELECT ticker, date_recommended, type FROM recommended_trades \ ORDER BY date_recommended desc LIMIT 1;""") rec_sql = cur.fetchall() notifications = [rec for rec in rec_sql] recommend = [] for notif in notifications: if (notif[1].year == last_update.year) & (notif[1].month == last_update.month) & (notif[1].day == last_update.day): recommend.append(notif) #ev, rec_ev, rec_trans, rec_trans_p, prof_trans = fetch_events() form = InputForm(request.form) if form.validate_on_submit(): stock = form.stock.data strategy = form.strategy.data email = form.email.data if email: insert = """INSERT INTO notifications (email) VALUES ('%s') """ % email cur.execute(insert) con.commit() kalman = kalman_stock([stock]) if stock == "FB": startdate = dt.date(2012,05,18) enddate =dt.datetime.now() elif stock == "TRIP": startdate = dt.date(2011,12,21) enddate =dt.datetime.now() elif stock == "ABBV": startdate = dt.date(2013,01,01) enddate =dt.datetime.now() else: startdate=dt.date(2008,01,01) enddate = dt.date(2009,05,01) data_df = get_data(symbols=[stock], startdate=startdate, enddate=enddate) return_holding = (data_df.values[-1]-data_df.values[0])*100./data_df.values[0] dat = parseDFdata(data_df, stock) ev, rec_ev, rec_trans, rec_trans_p, prof_trans = fetch_events(symbols=[stock], startdate=startdate, enddate=enddate) buy, sell = parseEvents(ev,data_df, stock) pos = [b[2] for b in rec_trans_p if b[2] > 0] if len(rec_trans_p): percent_correct_trans = len(pos)*100./float(len(rec_trans_p)) last_trans = rec_trans_p[-1] else: percent_correct_trans = 0 stats = analysis() return render_template('results.html', stock=stock, n_events=len(ev), \ stats=stats, strategy=strategy, kalman=kalman, percent_correct_trans=percent_correct_trans, \ last_trans=last_trans, dat=dat, buy=buy, sell=sell, return_holding = return_holding, \ startdate=startdate, enddate=enddate) return render_template('index.html', form=form,recommend=recommend, notifications=notifications, best_crisis = best_crisis)
def team(): form = InputForm() global catcher catcher = 'empty' global firstb firstb = 'empty' global secondb secondb = 'empty' global thirdb thirdb = 'empty' global ss ss = 'empty' global outfieldone outfieldone = 'empty' global outfieldtwo outfieldtwo = 'empty' global outfieldthree outfieldthree = 'empty' global utilone utilone = 'empty' global utiltwo utiltwo = 'empty' global benchone benchone = 'empty' global benchtwo benchtwo = 'empty' global benchthree benchthree = 'empty' listofcatchers = [] listoffbasemen = [] listofsbasemen = [] listofss = [] listoftbasemen = [] listofoutfielders = [] if form.validate_on_submit(): stringofcatchers = form.catchernames.data numberofcatchers = stringofcatchers.count(',')+1 listofcatchers = stringofcatchers.split(', ') try: catchersratingslist = getratingslist(listofcatchers, numberofcatchers) except: return redirect('/inputerror') catchersmaxindex = returnbestone(catchersratingslist, numberofcatchers) catcher = listofcatchers[catchersmaxindex] stringoffbasemen = form.firstbnames.data numberoffbasemen = stringoffbasemen.count(',')+1 listoffbasemen = stringoffbasemen.split(', ') try: fbasemenratingslist = getratingslist(listoffbasemen, numberoffbasemen) except: return redirect('/inputerror') fbasemenmaxindex = returnbestone(fbasemenratingslist, numberoffbasemen) firstb = listoffbasemen[fbasemenmaxindex] stringofsbasemen = form.secondbnames.data numberofsbasemen = stringofsbasemen.count(',')+1 listofsbasemen = stringofsbasemen.split(', ') try: sbasemenratingslist = getratingslist(listofsbasemen, numberofsbasemen) except: return redirect('/inputerror') sbasemenmaxindex = returnbestone(fbasemenratingslist, numberofsbasemen) secondb = listofsbasemen[sbasemenmaxindex] stringofss = form.ssnames.data numberofss = stringofss.count(',')+1 listofss = stringofss.split(', ') try: ssratingslist = getratingslist(listofss, numberofss) except: return redirect('/inputerror') ssmaxindex = returnbestone(ssratingslist, numberofss) ss = listofss[ssmaxindex] stringoftbasemen = form.thirdbnames.data numberoftbasemen = stringoftbasemen.count(',')+1 listoftbasemen = stringoftbasemen.split(', ') try: tbasemenratingslist = getratingslist(listoftbasemen, numberoftbasemen) except: return redirect('/inputerror') tbasemenmaxindex = returnbestone(tbasemenratingslist, numberoftbasemen) thirdb = listoftbasemen[tbasemenmaxindex] stringofoutfielders = form.outfieldnames.data numberofoutfielders = stringofoutfielders.count(',')+1 if numberofoutfielders < 3: return redirect('/inputerror') listofoutfielders = stringofoutfielders.split(', ') try: outfieldersratingslist = getratingslist(listofoutfielders, numberofoutfielders) except: return redirect('/inputerror') ofmaxindexone, ofmaxindextwo, ofmaxindexthree = returnbestthree(outfieldersratingslist, numberofoutfielders) outfieldone = listofoutfielders[ofmaxindexone] outfieldtwo = listofoutfielders[ofmaxindextwo] outfieldthree = listofoutfielders[ofmaxindexthree] total = numberofcatchers + numberoffbasemen + numberofsbasemen + numberofss + numberoftbasemen + numberofoutfielders if total < 10 or total > 13: return redirect('/inputerror') listoftherest = [] ratingsoftherest = [] posoftherest = [] for c in range(0, numberofcatchers): if c != catchersmaxindex: listoftherest.append(listofcatchers[c]) ratingsoftherest.append(catchersratingslist[c]) posoftherest.append('C ') for c in range(0, numberoffbasemen): if c != fbasemenmaxindex: listoftherest.append(listoffbasemen[c]) ratingsoftherest.append(fbasemenratingslist[c]) posoftherest.append('1B') for c in range(0, numberofsbasemen): if c != sbasemenmaxindex: listoftherest.append(listofsbasemen[c]) ratingsoftherest.append(sbasemenratingslist[c]) posoftherest.append('2B') for c in range(0, numberofss): if c != ssmaxindex: listoftherest.append(listofss[c]) ratingsoftherest.append(ssratingslist[c]) posoftherest.append('SS') for c in range(0, numberoftbasemen): if c != tbasemenmaxindex: listoftherest.append(listoftbasemen[c]) ratingsoftherest.append(tbasemenratingslist[c]) posoftherest.append('3B') for c in range(0, numberofoutfielders): if (c != ofmaxindexone and c != ofmaxindextwo and c!=ofmaxindexthree): listoftherest.append(listofoutfielders[c]) ratingsoftherest.append(outfieldersratingslist[c]) posoftherest.append('OF') utilmaxindexone, utilmaxindextwo, restoftherestindices = returnbesttwo(ratingsoftherest) utilone = posoftherest[utilmaxindexone] + ': ' + listoftherest[utilmaxindexone] utiltwo = posoftherest[utilmaxindextwo] + ': ' + listoftherest[utilmaxindextwo] if len(restoftherestindices)==5: if restoftherestindices[2] is not None: benchone = posoftherest[restoftherestindices[2]] + ': ' + listoftherest[restoftherestindices[2]] if restoftherestindices[1] is not None: benchtwo = posoftherest[restoftherestindices[1]] + ': ' + listoftherest[restoftherestindices[1]] if restoftherestindices[0] is not None: benchthree = posoftherest[restoftherestindices[0]] + ': ' + listoftherest[restoftherestindices[0]] elif len(restoftherestindices)==4: if restoftherestindices[1] is not None: benchtwo = posoftherest[restoftherestindices[1]] + ': ' + listoftherest[restoftherestindices[1]] if restoftherestindices[0] is not None: benchthree = posoftherest[restoftherestindices[0]] + ': ' + listoftherest[restoftherestindices[0]] elif len(restoftherestindices)==3: if restoftherestindices[0] is not None: benchthree = posoftherest[restoftherestindices[0]] + ': ' + listoftherest[restoftherestindices[0]] return redirect('/lineup') return render_template('team.html', form=form)