def main(): form = DateForm() dates = [] for date in Course.query.all(): if date.date not in dates: dates.append(date.date) if form.validate_on_submit(): url = f"http://www.cbr.ru/scripts/XML_daily.asp?date_req={form.date.data}" res = requests.get(url) tree = ET.fromstring(res.text) for valute in tree.findall("Valute"): course = Course(num_code=valute.find("NumCode").text, char_code=valute.find("CharCode").text, nominal=valute.find("Nominal").text, name=valute.find("Name").text, value=valute.find("Value").text, date=form.date.data) db.session.add(course) db.session.commit() return redirect(f"/{form.date.data}") return render_template("index.html", form=form, course=Course.query.all(), dates=dates)
def logs(): form = DateForm() ids = [i for i in range(len(boxes))] form.box.choices = list(zip(ids, boxes)) if form.validate_on_submit(): print("validated") dt = str(form.dt.data) date = dt.replace('-', '') box_id = form.box.data box = [f[1] for f in form.box.choices if f[0] == box_id] severity_id = form.severity.data severity = [f[1] for f in form.severity.choices if f[0] == severity_id] payload = {'date': date, 'severity': severity, 'box': box} r = requests.get('http://217.73.28.16:5002/syslog', params=payload) print(r.url) logs = json.loads(r.text) return render_template('logs.html', logs=logs, form=form, conf=conf) else: date = datetime.datetime.now().strftime("%Y%m%d") # Uncomment if you want to allow default view #severity = all #box = six #payload = { 'date':date, 'severity':severity, 'box':box } #r = requests.get('http://217.73.28.16:5002/syslog', params=payload) #logs = json.loads(r.text) logs = {} return render_template('logs.html', logs=logs, form=form, conf=conf)
def stat_players_result(request): stat_player = StatPlayerRegistration.objects.all().order_by('target_date') form = DateForm(request.GET or None) try: if form.is_valid(): from_date = form.cleaned_data['fromdate'] to_date = form.cleaned_data['todate'] date_min = stat_player.aggregate(Min('target_date')) date_max = stat_player.aggregate(Max('target_date')) date_min_data = date_min.get('target_date__min') date_max_data = date_max.get('target_date__max') if from_date is None and to_date < date_min_data: return HttpResponseRedirect('/invaild_input/') if to_date is None and from_date > date_max_data: return HttpResponseRedirect('/invaild_input/') if from_date == to_date > date_max_data: return HttpResponseRedirect('/invaild_input/') if to_date is None: stat_player = stat_player.filter(target_date__gte=from_date).order_by('target_date') return render(request, 'stat_players_result.html', {"form": form, "stat_players": stat_player}) if from_date is None: stat_player = stat_player.filter(target_date__lte=to_date).order_by('target_date') return render(request, 'stat_players_result.html', {"form": form, "stat_players": stat_player}) if from_date <= to_date > date_min_data: stat_player = stat_player.filter(target_date__gte=from_date, target_date__lte=to_date).order_by('target_date') return render(request, 'stat_players_result.html', {"form": form, "stat_players": stat_player}) else: return HttpResponseRedirect('/invaild_input/') else: return HttpResponseRedirect('/invaild_input/') except ValueError: return HttpResponseRedirect('/invaild_input/') except TypeError: return HttpResponseRedirect('/stat_players/')
def edit_date(id): if not current_user.is_admin: #throw a 403 error if the user is not an admin user abort(403) add_date = False dates = ImportantDate.query.order_by(ImportantDate.date_time) date = ImportantDate.query.get_or_404(id) form = DateForm(obj=date) if form.validate_on_submit(): date.title = form.title.data date.info = form.info.data date.date_time = form.date.data db.session.commit() flash('You have sucessfully edited the date.', 'success') return redirect(url_for('home.admin_dashboard')) form.title.data = date.title form.info.data = date.info form.date.data = date.date_time return render_template('admin/edit-dates.html', title="Edit Date", action="Edit", add_date=add_date, form=form, date=date, dates=dates)
def overview(request): if request.GET.has_key('month') and request.GET.has_key('year'): form = DateForm(request.GET) else: form = DateForm() start, end = form.get_date_range() income_list, income = detail_for_type(start, end, "INC") cogs_list, cogs = detail_for_type(start, end, "COGS") expense_list, expense = detail_for_type(start, end, "EXP") cogs_plus_expense = cogs + expense net = income - cogs_plus_expense return simple.direct_to_template(request, template='beancounter/overview.html', extra_context={ 'form': form, 'income_list': income_list, 'income': income, 'cogs_list': cogs_list, 'cogs': cogs, 'expense_list': expense_list, 'expense': expense, 'cogs_plus_expense': cogs_plus_expense, 'net': net, })
def index(): ''' index page to display the date selection form ''' form = DateForm() if form.validate_on_submit(): date = form.date.data.strftime(DATE_FORMAT) return redirect(url_for('view_prediction', pred_date=date)) return render_template('date_picker.html', form=form)
def overview(request): if request.GET.has_key('month') and request.GET.has_key('year'): form = DateForm(request.GET) else: form = DateForm() start, end = form.get_date_range() income_list,income = detail_for_type(start, end,"INC") cogs_list,cogs = detail_for_type(start, end,"COGS") expense_list,expense = detail_for_type(start, end,"EXP") cogs_plus_expense = cogs + expense net = income - cogs_plus_expense return simple.direct_to_template(request, template='beancounter/overview.html', extra_context = { 'form': form, 'income_list': income_list, 'income': income, 'cogs_list': cogs_list, 'cogs': cogs, 'expense_list': expense_list, 'expense': expense, 'cogs_plus_expense': cogs_plus_expense, 'net': net, })
def MyFiestas(request): ### --- Получение кода учетной записи --- try: kod = GetUserKod(request) except: return render_to_response("notaccess.html") if request.method == 'POST': form = DateForm(request.POST) if form.is_valid(): fiesta = form.cleaned_data['fiesta'] date = form.cleaned_data['date'] NewFiesta(kod,date,fiesta) if request.method == 'GET': try: delete_id = request.GET['delete_fiesta'] DelFiesta(delete_id) except: pass form = DateForm(None) data = GetDateList(kod) c = RequestContext(request,{'form':form,'data':data}) c.update(csrf(request)) return render_to_response("mydata/fiestas.html",c)
def DisplayTopTalkers(): form = DateForm(csrf_enabled=False) if form.validate_on_submit(): jsonChart = analytics_engine.getfwTopTalkers(form.fromdate.data.strftime('%Y-%m-%d'), form.todate.data.strftime('%Y-%m-%d')) return render_template('DisplayTableAndCharts.html', sankey=True, jsonTable=jsonChart, jsonChart=jsonChart) return render_template("dateForm.html", form=form)
def _post_result(self, request): result_xml = '' form = DateForm(request.POST) if form.is_valid(): if 'date' in request.POST and request.POST['date'] != '': role = ' role="' + request.POST['role'] + '"' if 'role' in request.POST and len( request.POST['role']) > 0 else '' return '<' + request.POST['tag'] + role + '>' + request.POST['date'] + '</' + request.POST['tag'] + '>' return '<' + request.POST['tag'] + '></' + request.POST['tag'] + '>'
def _post_result(self, request): result_xml = '' form = DateForm(request.POST) if form.is_valid(): if 'date' in request.POST and request.POST['date'] != '': role = ' role="' + request.POST[ 'role'] + '"' if 'role' in request.POST and len( request.POST['role']) > 0 else '' return '<' + request.POST['tag'] + role + '>' + request.POST[ 'date'] + '</' + request.POST['tag'] + '>' return '<' + request.POST['tag'] + '></' + request.POST['tag'] + '>'
def journal(): form = DateForm() if request.method == 'POST' and form.validate_on_submit(): spot = SpotSQL() data = spot.get_user_songs(sp.get_user_id()) return render_template('journal.html', data=generate_chart( request.cookies.get('prevEmotion')), labels=labels) return render_template('journal.html')
def income_vs_cost(request): """ Return a list of dictionaries containing COGS and related INC spending for the report time specified. """ if request.GET.has_key('month') and request.GET.has_key('year'): form = DateForm(request.GET) else: form = DateForm() start, end = form.get_date_range() cogs_categories = Category.objects.filter(type__exact='COGS') totals = [] for cat in cogs_categories: if cat.income: #this should be in the query cogs_entries = Entry.objects.filter(date__gte=start, date__lt=end, category=cat) cogs_total = decimal.Decimal('0') #total for COGS category for e in cogs_entries: cogs_total += e.amount income_total = decimal.Decimal('0') income_entries = Entry.objects.filter(date__gte=start, date__lt=end, category=cat.income) #total for associated Income category for i in income_entries: income_total += i.amount totals.append({ 'cogs_category': cat.name, 'cogs_total': cogs_total, 'income_category': cat.income, 'income_total': income_total, 'balance': income_total - cogs_total, }) return simple.direct_to_template(request, template='beancounter/incomevscost.html', extra_context={ 'form':form, 'totals': totals, })
def date(): form = DateForm() if request.method == 'POST': if form.validate() == False: return render_template('date.html', form=form) else: newdate = Date(request.form['firstname'], request.form['lastname'], request.form['email'], request.form['hobbies']) #newpost = Post(form.title.data, form.post.data) db.session.add(newdate) db.session.commit() return redirect(url_for('dateview')) elif request.method == 'GET': return render_template('date.html', form=form)
def add_date(): if not current_user.is_admin: #throw a 403 error if the user is not an admin user abort(403) add_date = True dates = ImportantDate.query.order_by(ImportantDate.date_time) form = DateForm() if request.method == 'POST': newDate = ImportantDate(title=form.title.data, info=form.info.data, date_time=form.date.data) db.session.add(newDate) db.session.commit() flash('Date successfully added!', 'success') return redirect(url_for('home.admin_dashboard')) # if request.method=="POST": # form=request.form # newDate = ImportantDate(title=form['title'],info=form['info'],date_time=form['date']) # db.session.add(newDate) # db.session.commit() # flash('Date successfully added!', 'success') # return redirect(url_for('home.admin_dashboard')) return render_template('admin/edit-dates.html', title="Add Date", action="Add", add_date=add_date, form=form, dates=dates)
def commitment(request, commitment_id): """Shows all of the details for a given commitment by a volunteer to an organisation.""" commitment = get_object_or_404(Commitment, pk=commitment_id) try: endorsement = Endorsement.objects.get(commitment=commitment) except Endorsement.DoesNotExist: endorsement = None # You may only view information about a commitment if you are the user, a representative of the company or a staff member. if request.user.is_staff: pass elif request.user == commitment.volunteer: pass elif request.user.get_profile().is_representative and request.user.get_profile().representativeprofile.organisation == commitment.organisation: pass else: raise Exception("You don't have permission to see details on this commitment. You must either be the committing volunteer, a representative of the organisation that is committed to, or a member of staff in order to view commitment details.") return render_to_response("hours/commitment.html", { 'commitment': commitment, 'v_user': commitment.volunteer, 'date_form': DateForm(), 'endorsement': endorsement, 'endorsement_form': EndorsementForm(), }, context_instance=RequestContext(request))
def show_datepicker(request): if request.method == 'POST': postform=DateForm(request.POST) if postform.is_valid() : req_date=request.POST.get('date', None) request.session['date']=req_date return HttpResponseRedirect('/onedaytmp') #return HttpResponseRedirect(reverse('show_oneday_tmp', kwargs={'date': req_date})) else: messages.error(request, "Error") #return HttpResponseRedirect('/') form=DateForm() context={'form':form} return render(request, 'datepicker.html',context)
def income_vs_cost(request): """ Return a list of dictionaries containing COGS and related INC spending for the report time specified. """ if request.GET.has_key('month') and request.GET.has_key('year'): form = DateForm(request.GET) else: form = DateForm() start, end = form.get_date_range() cogs_categories = Category.objects.filter(type__exact='COGS') totals = [] for cat in cogs_categories: if cat.income: #this should be in the query cogs_entries = Entry.objects.filter(date__gte=start, date__lt=end, category=cat) cogs_total = decimal.Decimal('0') #total for COGS category for e in cogs_entries: cogs_total += e.amount income_total = decimal.Decimal('0') income_entries = Entry.objects.filter(date__gte=start, date__lt=end, category=cat.income) #total for associated Income category for i in income_entries: income_total += i.amount totals.append({ 'cogs_category': cat.name, 'cogs_total': cogs_total, 'income_category': cat.income, 'income_total': income_total, 'balance': income_total - cogs_total, }) return simple.direct_to_template(request, template='beancounter/incomevscost.html', extra_context={ 'form': form, 'totals': totals, })
def show_datepicker(request): if request.method == 'POST': postform = DateForm(request.POST) if postform.is_valid(): req_date = request.POST.get('date', None) request.session['date'] = req_date return HttpResponseRedirect('/onedaytmp') #return HttpResponseRedirect(reverse('show_oneday_tmp', kwargs={'date': req_date})) else: messages.error(request, "Error") #return HttpResponseRedirect('/') form = DateForm() context = {'form': form} return render(request, 'datepicker.html', context)
def set_finish_date(request, commitment_id): commitment = get_object_or_404(Commitment, pk=commitment_id) if (request.user.get_profile().is_representative and request.user.get_profile().representativeprofile.organisation == commitment.organisation) or request.user.is_staff: pass else: raise Exception("Only a representative of the organisation that is committed to (or a staff member) may set a finish date on a commitment.") date_form = DateForm(request.POST) if date_form.is_valid(): date = date_form.cleaned_data['date'] commitment.finished = date commitment.save() return redirect('hours.views.commitment', commitment_id=commitment.id) else: raise Exception("Invalid form data received. Please contact support.")
def show_statistics(request, id): data = {} data['profile'] = request.session['profile'] data['showInfoToUser'] = getOutputMsg(request) try: account = Account.objects.get(pk = id) except Account.DoesNotExist: raise Http404 inicio = aweekago() fin = today() if request.POST: form = DateForm(request.POST) if form.is_valid(): inicio = form.cleaned_data['inicio'] fin = form.cleaned_data['fin'] data['form'] = form else: data['form'] = DateForm() data['datos'] = account.get_statistics(inicio, fin) return render_to_response(TEMPLATES['statistics'], data, RequestContext(request))
def stat_players(request): stat_player = StatPlayerRegistration.objects.all().order_by('target_date') form = DateForm(request.GET) paginator = Paginator(stat_player, PAGE_SIZE) page = request.GET.get('page') try: players = paginator.page(page) except PageNotAnInteger: players = paginator.page(1) except EmptyPage: players = paginator.page(paginator.num_pages) return render(request, 'stat_players.html', {"form": form, "stat_players": players})
def moneyin_moneyout(request): """ Return a list of dictionaries containing COGS and related INC spending for the report time specified. """ if request.GET.has_key('month') and request.GET.has_key('year'): form = DateForm(request.GET) else: form = DateForm() start, end = form.get_date_range() entries = Entry.objects.filter(date__gte=start, date__lt=end) income_dict = {} expense_dict = {} for e in entries: if e.category in ['EXP', 'COGS']: if expense_dict.has_key(e.name.name): expense_dict[e.name.name] += e.amount else: expense_dict[e.name.name] = e.amount elif e.category == 'INC': if income_dict.has_key(e.name.name): income_dict[e.name.name] += e.amount else: income_dict[e.name.name] = e.amount return simple.direct_to_template(request, template='beancounter/moneyin-moneyout.html', extra_context={ 'form':form, 'income': income_dict, 'expense': expense_dict, })
def moneyin_moneyout(request): """ Return a list of dictionaries containing COGS and related INC spending for the report time specified. """ if request.GET.has_key('month') and request.GET.has_key('year'): form = DateForm(request.GET) else: form = DateForm() start, end = form.get_date_range() entries = Entry.objects.filter(date__gte=start, date__lt=end) income_dict = {} expense_dict = {} for e in entries: if e.category in ['EXP', 'COGS']: if expense_dict.has_key(e.name.name): expense_dict[e.name.name] += e.amount else: expense_dict[e.name.name] = e.amount elif e.category == 'INC': if income_dict.has_key(e.name.name): income_dict[e.name.name] += e.amount else: income_dict[e.name.name] = e.amount return simple.direct_to_template( request, template='beancounter/moneyin-moneyout.html', extra_context={ 'form': form, 'income': income_dict, 'expense': expense_dict, })
def _get_module(self, request): with open(os.path.join(TEMPLATES_PATH, 'relevant_date.html'), 'r') as template_file: template_content = template_file.read() template = Template(template_content) self.params = {} if 'data' in request.GET: self.params['date'] = request.GET['data'] if 'attributes' in request.GET: if 'role' in request.GET['attributes']: self.params['role'] = request.GET['attributes']['role'] xml_xpath = request.GET['xml_xpath'] xml_xpath = xml_xpath.split('/')[-1] idx = xml_xpath.rfind("[") xml_xpath = xml_xpath[0:idx] self.params['tag'] = xml_xpath context = Context({'form': DateForm(self.params)}) return template.render(context)
def time(request): form = DateForm(request.POST) return render(request, 'time.html', {'form': form})
def show_image(request, shift=0): """ Generates the visualization page, fetching all related data (images, weather and radiosonde) """ # If there is no sky imager device installed, redirect towards the images part if not SkyPicture.objects.exists(): return redirect('pictures/') # Check if the weather station form should be shown if WeatherMeasurement.objects.exists(): weather = True else: weather = False args = {} args["title"] = "Data visualization" if request.POST or 'POST_map' in request.session: if request.POST: form_values = request.POST request.session['POST_map'] = form_values else: form_values = request.session['POST_map'] if weather: form = DateStationForm(form_values) else: form = DateForm(form_values) if form.is_valid(): queryDate = form.cleaned_data['date'] device = MeasuringDevice.objects.get( id=form.cleaned_data['imager']) if not device.skypicture_set.all() > 0: device = [ device for device in MeasuringDevice.objects.all() if ((device.type == 'W') and ( len(device.skypicture_set.all()) > 0)) ][0] queryDate = SkyPicture.objects.get_closest_to(queryDate, device) if shift == '1': queryDateNew = SkyPicture.objects.get_next(queryDate, device) if queryDateNew: queryDate = queryDateNew elif shift == '-1': queryDateNew = SkyPicture.objects.get_previous( queryDate, device) if queryDateNew: queryDate = queryDateNew if weather: station = MeasuringDevice.objects.get( id=form.cleaned_data['station']) else: device = [ device for device in MeasuringDevice.objects.all() if ((device.type == 'W') and ( len(device.skypicture_set.all()) > 0)) ][0] firstImage = SkyPicture.objects.filter(device=device).order_by( '-date', '-time')[0] queryDate = firstImage.date if weather: station = [ station for station in MeasuringDevice.objects.all() if station.type == 'S' ][0] else: form = DateStationForm() device = [ device for device in MeasuringDevice.objects.all() if ((device.type == 'W') and (len(device.skypicture_set.all()) > 0) ) ][0] firstImage = SkyPicture.objects.filter(device=device).order_by( '-date', '-time')[0] queryDate = firstImage.date if weather: station = [ station for station in MeasuringDevice.objects.all() if station.type == 'S' ][0] # Generating data for the new form with the actual retrieved data if weather: new_data = { 'date': unicode(queryDate), 'station': station.id, 'imager': device.id } form = DateStationForm(new_data) else: new_data = {'date': unicode(queryDate), 'imager': device.id} form = DateForm(new_data) request.session['POST_map'] = new_data args['form'] = form args['longCtr'] = device.location.x args['latCtr'] = device.location.y # Check if there are images before or after to show Next or Previous buttons if SkyPicture.objects.get_next(queryDate, device): args['next'] = 1 if SkyPicture.objects.get_previous(queryDate, device): args['previous'] = 1 # # Fetching images # imagesData = SkyPicture.objects.filter(device=device, date=queryDate).order_by('time') images = [] for im in imagesData: thisIm = {} thisIm['url'] = im.image.url thisIm['url_tn'] = im.image.url.replace('.jpg', '.125x125.jpg') thisIm['undistorted'] = im.undistorted.url thisIm['time'] = im.time.strftime("%H:%M:%S") thisIm['id'] = str(im.id) images.append(thisIm) args['images'] = images # # Fetching weather data # temperature = [] humidity = [] dew_point = [] wind_speed = [] wind_direction = [] pressure = [] rainfall_rate = [] solar_radiation = [] uv_index = [] cloud_height = [] if not weather: args['boolWeather'] = False else: measurementsData = WeatherMeasurement.objects.filter( date=queryDate, device=station).order_by('time') if not measurementsData: args['boolWeather'] = False else: args['boolWeather'] = True for meas in measurementsData: if meas.temperature is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.temperature temperature.append(thisMeas) if meas.humidity is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.humidity humidity.append(thisMeas) if meas.dew_point is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.dew_point dew_point.append(thisMeas) if meas.wind_speed is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.wind_speed wind_speed.append(thisMeas) if meas.wind_direction is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.wind_direction wind_direction.append(thisMeas) if meas.pressure is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.pressure pressure.append(thisMeas) if meas.rainfall_rate is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.rainfall_rate rainfall_rate.append(thisMeas) if meas.solar_radiation is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.solar_radiation solar_radiation.append(thisMeas) if meas.uv_index is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = meas.uv_index uv_index.append(thisMeas) if meas.temperature is not None and meas.dew_point is not None: thisMeas = {} thisMeas['time'] = meas.time.strftime("%H:%M:%S") thisMeas['value'] = round( 125 * (meas.temperature - meas.dew_point), 1) cloud_height.append(thisMeas) # Giving weather data (potentially empty) to the template args['temperature'] = temperature args['humidity'] = humidity args['dew_point'] = dew_point args['wind_speed'] = wind_speed args['wind_direction'] = wind_direction args['pressure'] = pressure args['rainfall_rate'] = rainfall_rate args['solar_radiation'] = solar_radiation args['uv_index'] = uv_index args['cloud_height'] = cloud_height # Items for the form items = [] if temperature: items.append(('temperature', 'Temperature (deg. C)')) if humidity: items.append(('humidity', 'Humidity (%)')) if dew_point: items.append(('dew_point', 'Dew point (deg. C)')) if cloud_height: items.append(('cloud_height', 'Cloud base height (m.)')) if wind_speed: items.append(('wind_speed', 'Wind speed (m/s)')) if wind_direction: items.append(('wind_direction', 'Wind direction azimuth (deg.)')) if pressure: items.append(('pressure', 'Pressure (hPa)')) if rainfall_rate: items.append(('rainfall_rate', 'Rainfall rate (mm/hr)')) if solar_radiation: items.append(('solar_radiation', 'Solar radiation (W/m2)')) if uv_index: items.append(('uv_index', 'UV index')) args['items'] = json.dumps(items) # # Fetching radiosonde data # altitudes = np.arange(0, 18, 0.01) radiosondeDataAM = RadiosondeMeasurement.objects.filter( date=queryDate).filter(time='AM').order_by('height') if not radiosondeDataAM: args['boolRadiosondeAM'] = False args['allValuesRadAM'] = [] args['allSamplesRadAM'] = [] else: args['boolRadiosondeAM'] = True allValuesRadAM = {} allSamplesRadAM = {} PRES_samples_AM = [] PRES_heights_AM = np.empty(radiosondeDataAM.count()) PRES_values_AM = np.empty(radiosondeDataAM.count()) PRES_counter_AM = 0 TEMP_samples_AM = [] TEMP_heights_AM = np.empty(radiosondeDataAM.count()) TEMP_values_AM = np.empty(radiosondeDataAM.count()) TEMP_counter_AM = 0 DWPT_samples_AM = [] DWPT_heights_AM = np.empty(radiosondeDataAM.count()) DWPT_values_AM = np.empty(radiosondeDataAM.count()) DWPT_counter_AM = 0 RELH_samples_AM = [] RELH_heights_AM = np.empty(radiosondeDataAM.count()) RELH_values_AM = np.empty(radiosondeDataAM.count()) RELH_counter_AM = 0 DRCT_samples_AM = [] DRCT_heights_AM = np.empty(radiosondeDataAM.count()) DRCT_values_AM = np.empty(radiosondeDataAM.count()) DRCT_counter_AM = 0 SKNT_samples_AM = [] SKNT_heights_AM = np.empty(radiosondeDataAM.count()) SKNT_values_AM = np.empty(radiosondeDataAM.count()) SKNT_counter_AM = 0 for rad in radiosondeDataAM: if rad.height: if rad.pressure: PRES_samples_AM.append(rad.height) PRES_heights_AM[PRES_counter_AM] = rad.height / 1000 PRES_values_AM[PRES_counter_AM] = rad.pressure PRES_counter_AM = PRES_counter_AM + 1 if rad.temperature: TEMP_samples_AM.append(rad.height) TEMP_heights_AM[TEMP_counter_AM] = rad.height / 1000 TEMP_values_AM[TEMP_counter_AM] = rad.temperature TEMP_counter_AM = TEMP_counter_AM + 1 if rad.dew_point: DWPT_samples_AM.append(rad.height) DWPT_heights_AM[DWPT_counter_AM] = rad.height / 1000 DWPT_values_AM[DWPT_counter_AM] = rad.dew_point DWPT_counter_AM = DWPT_counter_AM + 1 if rad.rel_humidity: RELH_samples_AM.append(rad.height) RELH_heights_AM[RELH_counter_AM] = rad.height / 1000 RELH_values_AM[RELH_counter_AM] = rad.rel_humidity RELH_counter_AM = RELH_counter_AM + 1 if rad.wind_direction: DRCT_samples_AM.append(rad.height) DRCT_heights_AM[DRCT_counter_AM] = rad.height / 1000 DRCT_values_AM[DRCT_counter_AM] = rad.wind_direction DRCT_counter_AM = DRCT_counter_AM + 1 if rad.wind_speed: SKNT_samples_AM.append(rad.height) SKNT_heights_AM[SKNT_counter_AM] = rad.height / 1000 SKNT_values_AM[SKNT_counter_AM] = rad.pressure SKNT_counter_AM = SKNT_counter_AM + 1 PRES_heights_AM.resize(len(PRES_samples_AM)) PRES_values_AM.resize(len(PRES_samples_AM)) allValuesRadAM['PRES'] = np.interp(altitudes, PRES_heights_AM, PRES_values_AM).tolist() allSamplesRadAM['PRES'] = PRES_samples_AM TEMP_heights_AM.resize(len(TEMP_samples_AM)) TEMP_values_AM.resize(len(TEMP_samples_AM)) allValuesRadAM['TEMP'] = np.interp(altitudes, TEMP_heights_AM, TEMP_values_AM).tolist() allSamplesRadAM['TEMP'] = TEMP_samples_AM DWPT_heights_AM.resize(len(DWPT_samples_AM)) DWPT_values_AM.resize(len(DWPT_samples_AM)) allValuesRadAM['DWPT'] = np.interp(altitudes, DWPT_heights_AM, DWPT_values_AM).tolist() allSamplesRadAM['DWPT'] = DWPT_samples_AM RELH_heights_AM.resize(len(RELH_samples_AM)) RELH_values_AM.resize(len(RELH_samples_AM)) allValuesRadAM['RELH'] = np.interp(altitudes, RELH_heights_AM, RELH_values_AM).tolist() allSamplesRadAM['RELH'] = RELH_samples_AM DRCT_heights_AM.resize(len(DRCT_samples_AM)) DRCT_values_AM.resize(len(DRCT_samples_AM)) allValuesRadAM['DRCT'] = np.interp(altitudes, DRCT_heights_AM, DRCT_values_AM).tolist() allSamplesRadAM['DRCT'] = DRCT_samples_AM SKNT_heights_AM.resize(len(SKNT_samples_AM)) SKNT_values_AM.resize(len(SKNT_samples_AM)) allValuesRadAM['SKNT'] = np.interp(altitudes, SKNT_heights_AM, SKNT_values_AM).tolist() allSamplesRadAM['SKNT'] = SKNT_samples_AM # Critical humidity function alpha = 1.0 beta = np.sqrt(3) sigma = np.array(allValuesRadAM['PRES']) / allValuesRadAM['PRES'][0] chum = 1 - alpha * sigma * (1 - sigma) * (1 + beta * (sigma - 0.5)) allValuesRadAM['clouds'] = np.int_( np.array(allValuesRadAM['RELH']) > chum * 100).tolist() allValuesRadAM['HGHT'] = altitudes.tolist() args['allValuesRadAM'] = allValuesRadAM args['allSamplesRadAM'] = allSamplesRadAM radiosondeDataPM = RadiosondeMeasurement.objects.filter( date=queryDate).filter(time='PM').order_by('height') if not radiosondeDataPM: args['boolRadiosondePM'] = False args['allValuesRadPM'] = [] args['allSamplesRadPM'] = [] else: args['boolRadiosondePM'] = True allValuesRadPM = {} allSamplesRadPM = {} PRES_samples_PM = [] PRES_heights_PM = np.empty(radiosondeDataPM.count()) PRES_values_PM = np.empty(radiosondeDataPM.count()) PRES_counter_PM = 0 TEMP_samples_PM = [] TEMP_heights_PM = np.empty(radiosondeDataPM.count()) TEMP_values_PM = np.empty(radiosondeDataPM.count()) TEMP_counter_PM = 0 DWPT_samples_PM = [] DWPT_heights_PM = np.empty(radiosondeDataPM.count()) DWPT_values_PM = np.empty(radiosondeDataPM.count()) DWPT_counter_PM = 0 RELH_samples_PM = [] RELH_heights_PM = np.empty(radiosondeDataPM.count()) RELH_values_PM = np.empty(radiosondeDataPM.count()) RELH_counter_PM = 0 DRCT_samples_PM = [] DRCT_heights_PM = np.empty(radiosondeDataPM.count()) DRCT_values_PM = np.empty(radiosondeDataPM.count()) DRCT_counter_PM = 0 SKNT_samples_PM = [] SKNT_heights_PM = np.empty(radiosondeDataPM.count()) SKNT_values_PM = np.empty(radiosondeDataPM.count()) SKNT_counter_PM = 0 for rad in radiosondeDataPM: if rad.height: if rad.pressure: PRES_samples_PM.append(rad.height) PRES_heights_PM[PRES_counter_PM] = rad.height / 1000 PRES_values_PM[PRES_counter_PM] = rad.pressure PRES_counter_PM = PRES_counter_PM + 1 if rad.temperature: TEMP_samples_PM.append(rad.height) TEMP_heights_PM[TEMP_counter_PM] = rad.height / 1000 TEMP_values_PM[TEMP_counter_PM] = rad.temperature TEMP_counter_PM = TEMP_counter_PM + 1 if rad.dew_point: DWPT_samples_PM.append(rad.height) DWPT_heights_PM[DWPT_counter_PM] = rad.height / 1000 DWPT_values_PM[DWPT_counter_PM] = rad.dew_point DWPT_counter_PM = DWPT_counter_PM + 1 if rad.rel_humidity: RELH_samples_PM.append(rad.height) RELH_heights_PM[RELH_counter_PM] = rad.height / 1000 RELH_values_PM[RELH_counter_PM] = rad.rel_humidity RELH_counter_PM = RELH_counter_PM + 1 if rad.wind_direction: DRCT_samples_PM.append(rad.height) DRCT_heights_PM[DRCT_counter_PM] = rad.height / 1000 DRCT_values_PM[DRCT_counter_PM] = rad.wind_direction DRCT_counter_PM = DRCT_counter_PM + 1 if rad.wind_speed: SKNT_samples_PM.append(rad.height) SKNT_heights_PM[SKNT_counter_PM] = rad.height / 1000 SKNT_values_PM[SKNT_counter_PM] = rad.pressure SKNT_counter_PM = SKNT_counter_PM + 1 PRES_heights_PM.resize(len(PRES_samples_PM)) PRES_values_PM.resize(len(PRES_samples_PM)) allValuesRadPM['PRES'] = np.interp(altitudes, PRES_heights_PM, PRES_values_PM).tolist() allSamplesRadPM['PRES'] = PRES_samples_PM TEMP_heights_PM.resize(len(TEMP_samples_PM)) TEMP_values_PM.resize(len(TEMP_samples_PM)) allValuesRadPM['TEMP'] = np.interp(altitudes, TEMP_heights_PM, TEMP_values_PM).tolist() allSamplesRadPM['TEMP'] = TEMP_samples_PM DWPT_heights_PM.resize(len(DWPT_samples_PM)) DWPT_values_PM.resize(len(DWPT_samples_PM)) allValuesRadPM['DWPT'] = np.interp(altitudes, DWPT_heights_PM, DWPT_values_PM).tolist() allSamplesRadPM['DWPT'] = DWPT_samples_PM RELH_heights_PM.resize(len(RELH_samples_PM)) RELH_values_PM.resize(len(RELH_samples_PM)) allValuesRadPM['RELH'] = np.interp(altitudes, RELH_heights_PM, RELH_values_PM).tolist() allSamplesRadPM['RELH'] = RELH_samples_PM DRCT_heights_PM.resize(len(DRCT_samples_PM)) DRCT_values_PM.resize(len(DRCT_samples_PM)) allValuesRadPM['DRCT'] = np.interp(altitudes, DRCT_heights_PM, DRCT_values_PM).tolist() allSamplesRadPM['DRCT'] = DRCT_samples_PM SKNT_heights_PM.resize(len(SKNT_samples_PM)) SKNT_values_PM.resize(len(SKNT_samples_PM)) allValuesRadPM['SKNT'] = np.interp(altitudes, SKNT_heights_PM, SKNT_values_PM).tolist() allSamplesRadPM['SKNT'] = SKNT_samples_PM # Critical humidity function alpha = 1.0 beta = np.sqrt(3) sigma = np.array(allValuesRadPM['PRES']) / allValuesRadPM['PRES'][0] chum = 1 - alpha * sigma * (1 - sigma) * (1 + beta * (sigma - 0.5)) allValuesRadPM['clouds'] = np.int_( np.array(allValuesRadPM['RELH']) > chum * 100).tolist() allValuesRadPM['HGHT'] = altitudes.tolist() args['allValuesRadPM'] = allValuesRadPM args['allSamplesRadPM'] = allSamplesRadPM args['itemsRad'] = { 'Pressure (hPa)': 'PRES', 'Temperature (deg. C)': 'TEMP', 'Dew point (deg. C)': 'DWPT', 'Rel. humidity (%)': 'RELH', 'Wind direction (deg.)': 'DRCT', 'Wind speed (knot)': 'SKNT' } args['googleKey'] = settings.GOOGLE_MAPS_API_KEY return render(request, 'visualization/index.html', args)
def vegas(): # Data Collectors mf = MonthForm() df = DateForm() cf = ContestForm() emptyList = [" "] conn = sqlite3.connect( "/Users/broeking/Desktop/T.R.E.A./src/Database/trea.db") cursor = conn.cursor() # Executes if we know contest if cf.validate_on_submit(): # Collect the Ownerships and Points for that day cursor.execute('SELECT * FROM ownerships where month = "' + session['month'] + '" AND date = "' + session['date'] + '" AND contest = "' + cf.contest.data + '"') session['contest'] = cf.contest.data ownerships = [ dict(id=row[0], player=row[1], drafted=row[2], FPTS=row[3], month=row[4], date=row[5], contest=row[6]) for row in cursor.fetchall() ] # Collect the lines for that day cursor.execute('SELECT * FROM lines where date = "' + session['date'] + '" AND year = "2017"') lines = [ dict(id=row[0], Away_Team=row[1], Home_Team=row[2], Away_Starter=row[3], Home_Starter=row[4], Start_Time=row[5], Away_Final_Score=row[6], Home_Final_Score=row[7], Away_Opening=row[8], Home_Opening=row[9], Away_Westgate=row[10], Home_Westgate=row[11], Away_Mirage=row[12], Home_Mirage=row[13], Away_Station=row[14], Home_Station=row[15], Away_Pinnacle=row[16], Home_Pinnacle=row[17], Away_SIA=row[18], Home_SIA=row[19], Away_SBG=row[20], Home_SBG=row[21], Away_BetUS=row[22], Home_BetUS=row[23], Away_BetPhoenix=row[24], Home_BetPhoenix=row[25], Away_EasyStreet=row[26], Home_EasyStreet=row[27], Away_Bovada=row[28], Home_Bovada=row[29], Away_Jazz=row[30], Home_Jazz=row[31], Away_Sportsbet=row[32], Home_Sportsbet=row[33], Away_Bookmaker=row[34], Home_Bookmaker=row[35], Away_DSI=row[36], Home_DSI=row[37], Away_AceSport=row[38], Home_AceSport=row[39], date=row[40], year=row[41]) for row in cursor.fetchall() ] # return redirect(url_for('lineup', lineps=lineups)) return render_template('vegas.html', months=emptyList, dates=emptyList, contests=emptyList, mf=None, df=None, cf=None, ownerships=ownerships, lines=lines) # Executes if we know date if df.validate_on_submit(): cursor.execute( 'SELECT DISTINCT contest FROM ownerships where month = "' + session['month'] + '" AND date = ' + df.date.data) session['date'] = df.date.data contests = [item[0] for item in cursor.fetchall()] return render_template('lines_search.html', months=emptyList, dates=emptyList, contests=contests, mf=None, df=None, cf=cf) # Executes if we know the month if mf.validate_on_submit(): cursor.execute('SELECT DISTINCT date FROM ownerships where month = "' + mf.month.data + '"') session['month'] = mf.month.data dates = [item[0] for item in cursor.fetchall()] return render_template('lines_search.html', months=emptyList, dates=dates, contests=emptyList, mf=None, df=df, cf=None) # Initial return cursor.execute('SELECT DISTINCT month FROM ownerships') months = [item[0] for item in cursor.fetchall()] return render_template('lines_search.html', months=months, dates=emptyList, contests=emptyList, mf=mf, df=None, cf=None)
def pick(): form = DateForm() return render_template('list.html', form=form)
def search(): # Data Collectors mf = MonthForm() df = DateForm() cf = ContestForm() emptyList = [" "] conn = sqlite3.connect( "/Users/broeking/Desktop/T.R.E.A./src/Database/trea.db") cursor = conn.cursor() # Executes if we know contest if cf.validate_on_submit(): cursor.execute('SELECT * FROM lineups where month = "' + session['month'] + '" AND date = "' + session['date'] + '" AND contest = "' + cf.contest.data + '"') session['contest'] = cf.contest.data lineups = [ dict(id=row[0], Rank=row[1], EntryName=row[2], Points=row[3], Lineup=row[4], SP1=row[5], SP2=row[6], C=row[7], First=row[8], Second=row[9], Third=row[10], Short=row[11], OF1=row[12], OF2=row[13], OF3=row[14], blank=row[15], month=row[16], date=row[17], contest=row[18]) for row in cursor.fetchall() ] # return redirect(url_for('lineup', lineps=lineups)) return render_template('search.html', months=emptyList, dates=emptyList, contests=emptyList, mf=None, df=None, cf=None, lineups=lineups) # Executes if we know date if df.validate_on_submit(): cursor.execute('SELECT DISTINCT contest FROM lineups where month = "' + session['month'] + '" AND date = ' + df.date.data) session['date'] = df.date.data contests = [item[0] for item in cursor.fetchall()] return render_template('search.html', months=emptyList, dates=emptyList, contests=contests, mf=None, df=None, cf=cf) # Executes if we know the month if mf.validate_on_submit(): cursor.execute('SELECT DISTINCT date FROM lineups where month = "' + mf.month.data + '"') session['month'] = mf.month.data dates = [item[0] for item in cursor.fetchall()] return render_template('search.html', months=emptyList, dates=dates, contests=emptyList, mf=None, df=df, cf=None) # Initial return cursor.execute('SELECT DISTINCT month FROM lineups') months = [item[0] for item in cursor.fetchall()] return render_template('search.html', months=months, dates=emptyList, contests=emptyList, mf=mf, df=None, cf=None)