def _open_model_trend(request): queryset = TemperatureReading.objects.all() data = [ ] dateSeen = {} for t in queryset: day = t.datetime.day month = t.datetime.month year = t.datetime.year if year in dateSeen: if month in dateSeen[year]: if day in dateSeen[year][month]: continue else: dateSeen[year][month].append(day) else: dateSeen[year] = {month: [day,]} else: dateSeen[year] = {month: [day,]} data.append([int(t.datetime.strftime('%Y%m%d')), float(t.value)]) data = sorted(data, key=lambda x: x[0]) data.insert(0, ['Date', 'Value']) chart = LineChart(SimpleDataSource(data=data), html_id="line_chart") data = {'chart': chart} s = chart.as_html() return render(template_name='model_popup.html', context=data, request=request)
def get_chart(qs, data_source_class, title, vmax, vmin): vaxisoptions = {'viewWindow': {'max': vmax, 'min': vmin}} chartareaoptions = {'left':60,'right':20, 'top':50, 'bottom':100}#{'width': '80%', 'height': '80%'} legendoptions = {'position': 'bottom'} options = {'height':'100%', 'width':'100%', 'vAxis':vaxisoptions, 'title':title, 'chartArea':chartareaoptions, 'legend':legendoptions} try: chart = LineChart(data_source_class(queryset=qs, fields=['stamp','value']), options=options)#, height=1000, width=1500) except TypeError: chart = LineChart(data_source_class(data=qs), options=options) return chart
def vertical(request): data = [ ['Time', 'V1', 'V2', 'VD'] # create a list to hold the column names and data for the axis names ] minstringint = datetime.strptime(request.GET.get('min','2000-01-01T10:00:00'),"%Y-%m-%dT%H:%M:%S").replace(tzinfo=dt.timezone.utc) maxstringint = datetime.strptime(request.GET.get('max','2020-12-25T10:00:00'),"%Y-%m-%dT%H:%M:%S").replace(tzinfo=dt.timezone.utc) ordered_fastmeasurements = models.FastMeasurement.objects.filter(global_id__global_id__transmit_time__gte=minstringint).filter(global_id__global_id__transmit_time__lte=maxstringint).order_by('global_id', 'sub_id') #print(len(ordered_fastmeasurements)) scalar = 0.000125 if request.GET.get('volts','') == 'True' else 1 top = 99999 if not request.GET.get('top','') else float(request.GET.get('top','')) bottom = -99999 if not request.GET.get('bottom','') else float(request.GET.get('bottom','')) onlyWantedData = [] wantedimei = request.GET.get('imei','*') if(wantedimei == "CollinsLaptop"): wantedimei = "888888888888888" for x in ordered_fastmeasurements: if(wantedimei == '*' or wantedimei == str(x.global_id.global_id.imei)): onlyWantedData.append([x.global_id.global_id.transmit_time+x.sub_id*timedelta(seconds=5),x.vert1*scalar if x.vert1*scalar <= top and x.vert1*scalar >= bottom else top if x.vert1*scalar > top else bottom,x.vert2*scalar if x.vert2*scalar <= top and x.vert2*scalar >= bottom else top if x.vert2*scalar > top else bottom,x.vertD*scalar if x.vertD*scalar <= top and x.vertD*scalar >= bottom else top if x.vertD*scalar > top else bottom]) #minstringint = int(request.GET.get('min','0')) #maxstringint = int(request.GET.get('max','999999')) wantedimei = request.GET.get('imei','*') onlyReallyWantedData = [] for x in onlyWantedData: if True: #if(x[0] >= minstringint and x[0] <= maxstringint): onlyReallyWantedData.append(x) data = data + onlyReallyWantedData chartTitle = "Vertical Measurements" chartDescription = "This is a test graph generated from all of the fast measurement data.\n This is mostly for demonstration.\n Please enjoy." data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': chartTitle}) # Creating a line chart context = {'chart': chart, 'title': chartTitle, 'description': chartDescription} return render(request, 'groundstation/graph.html', context)
def Graphos(request): data = [ ['Year', 'Sales', 'Expenses', 'Items Sold', 'Net Profit', 'All'], ['2004', 1000, 400, 100, 600, 100], ['2005', 1170, 460, 120, 310, 100], ['2006', 660, 1120, 50, -460, 100], ['2007', 1030, 540, 100, 200, 100], ] from graphos.sources.simple import SimpleDataSource from graphos.renderers.gchart import LineChart from graphos.renderers.gchart import ColumnChart from graphos.renderers.gchart import BarChart from graphos.renderers.gchart import PieChart from graphos.renderers.gchart import AreaChart from graphos.renderers.gchart import TreeMapChart from graphos.renderers.gchart import CandlestickChart from graphos.renderers.gchart import GaugeChart # from graphos.renderers.highcharts import LineChart # DataSource object data_source = SimpleDataSource(data=data) # Chart object chart = LineChart(data_source) chart1 = BarChart(data_source) context = {'chart': chart, 'chart1': chart1 } return render(request, 'char.html', context)
def professorResults(request): tempFinishedAssignment = FinishedAssignment.objects.all() tempAssignment = Assignment.objects.all() scoreList = [] data = [['Ă˜ving', 'Gruppens Resultat']] #Sorts by assignment. Finds all answered assignments. Tallies scores and adds to graph if request.user.groups.filter(name="Professors").exists(): for assignment in tempAssignment: scoreTotal = 0 for finishedAssignment in tempFinishedAssignment: if finishedAssignment.assignment.assignmentName == assignment.assignmentName: scoreTotal = +finishedAssignment.score data.append([assignment.assignmentName, scoreTotal]) scoreList.append(scoreTotal) studentScore = SimpleDataSource(data=data) chart = LineChart(studentScore, options={'title': "Resultater"}) return render(request, 'professorResults.html', { 'results': tempAssignment, 'score': scoreList, 'chart': chart }) if request.user.groups.filter(name="Students").exists(): return redirect('results') else: return redirect('index')
def conductivity(request): data = [['DayTime', 'ConductivityProbe1', 'ConductivityProbe2']] db = MySQLdb.connect(host="localhost", user="******", passwd="raspberry", db="myproject") cur = db.cursor() cur.execute('SELECT * FROM myproject.tutorialapp_conductivity') for row in cur.fetchall(): l = [] l.append(row[0]) s = 0.0 for i in range(1, 15 + 1): s += row[i] l.append(s / 15.0) s1 = 0.0 for i in range(16, 30 + 1): s1 += row[i] l.append(s1 / 15.0) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Conductivity"}) context = {'chart': chart} return render(request, 'tutorial/conductivity.html', context)
def get_module_line_chart(lecture_attendances, num_students): """Get line chart for module, showing attendance per lecture over time. :param lecture_attendances: lecture attendances for module :param num_students: number of students for lecture attendances :return: line chart object to pass to template """ # Title data for chart: what is shown, and value used title_data = ['Lecture', '% Attendance'] lecture_attendance_map = OrderedDict() for lecture_attendance in lecture_attendances: # Unique lecture identifier to group lectures, and also to display on chart lecture_key = str(lecture_attendance.lecture.date) + ': \n' + lecture_attendance.lecture.session_id attendance_val = 1 if lecture_attendance.attended else 0 lecture_attendance_map.setdefault(lecture_key, 0) lecture_attendance_map[lecture_key] = lecture_attendance_map[lecture_key] + attendance_val # Build up chart data in format expected by Graphos DataSource - starting with the title data chart_data = [title_data] for lecture_key, attendance_val in lecture_attendance_map.items(): percentage_val = (attendance_val / num_students) * 100 chart_data.append([lecture_key, percentage_val]) # Return line chart with some styling configuration return LineChart(SimpleDataSource(data=chart_data), options={'title': 'Attendance per Lecture', 'pieHole': 0.4, 'colors': ['#3498db'], 'hAxis': { 'title': "Lectures", 'titleTextStyle': {'bold': True, 'italic': False} }} )
def gauge_chart(gauge, days, resolution): now = timezone.now() yesterday = now - timezone.timedelta(hours=24 * days) queryset = GaugeValue.objects.filter(gauge=gauge)\ .filter(created_at__range=(yesterday, now))\ .extra({resolution: "date_trunc('"+resolution+"', created_at)"})\ .values(resolution).order_by().annotate(avg=Avg('value'))\ .order_by(resolution).all() if len(queryset) == 0: return None unit = gauge.unit if gauge.unit else "missing" a = [['Time', unit]] for row in queryset: a.append([row[resolution], row['avg']]) data_source = SimpleDataSource(data=a) title = "{} - {} dager ({:4.2f})".format(gauge.title, days, queryset.reverse()[0]['avg']) chart = LineChart(data_source, options={ 'title': title, 'curveType': 'function', }) return chart
def plots(request, data_id): vs = VoltageSample.objects.all().filter(id=data_id)[0] if vs: if vs.raw: data = [['Time(seconds)', 'ADC Output']] vaxis = {'title': 'ADC Output'} else: data = [['Time(seconds)', 'Voltage']] vaxis = {'title': 'Volts'} samples = [] i = 0 for d in vs.data: val = [str(i), d] samples.append(val) i = round(i + (1 / vs.freq), 2) data.append(val) # DataSource object data_source = SimpleDataSource(data=data) # Chart object options = { 'title': 'Voltage vs Time', 'vAxis': vaxis, 'hAxis': { 'title': 'Seconds', 'minValue': 0, 'viewWindowMode': 'maximized' } } chart = LineChart(data_source, height=500, width=1000, options=options) context = {'chart': chart, 'points': vs.data, 'freq': vs.freq} return render(request, 'plot.html', context)
def mapPlot(request): # Change to google maps data = [[ 'Daytime', 'Longitude', 'Latitude' ] # create a list to hold the column names and data for the axis names ] db = MySQLdb.connect( host="localhost", user="******", passwd="raspberry", db="myproject") # Access the database to get all the current data cur = db.cursor() cur.execute('SELECT * FROM myproject.tutorialapp_table_gps') for row in cur.fetchall(): # going through each row l = [] l.append( row[0] ) # append each row to the data, only get the columns that we want l.append(row[4]) l.append(row[5]) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Coordinates"}) # Creating a line chart context = {'chart': chart} return render( request, 'tutorial/mapPlot.html', context ) # rendering the chart when a request has gone through for this page, and using the mapPlot.html to render it
def graphoo(request): queryset = Price.objects.all() data_source = ModelDataSource(queryset, fields=['entry', 'xbt']) # Chart object chart = LineChart(data_source) context = {'chart': chart} return render(request, 'graph/price_list.html', context)
def payout_report(request, ark_address): context = sidebar_context(request) context.update({'error': False}) request.session['current_wallet'] = ark_address # check if we have a wallet tag request.session['current_tag'] = None if ark_address == request.session['arkmainwallet']: request.session['current_tag'] = request.session['arkmaintag'] elif request.session['arksecwallet']: request.session['current_tag'] = request.session['arksectag'] res = ark_analytics.analytic_functions.gen_payout_report(ark_address) context.update(res) try: voter = ark_delegate_manager.models.VotePool.objects.get( ark_address=ark_address) status = voter.status if voter.blacklisted: return render(request, 'console/blacklisted.html', {'address': voter.address}) builduppayout = voter.payout_amount / arkinfo.ARK context.update({'builduppayout': builduppayout, 'status': status}) except django_exceptions.ObjectDoesNotExist: context.update({'error': True}) data_list = [['date', 'Payout Amount']] # converting context variables to correct units for i in context['payout_history']: i['time'] = arktool.utils.arkt_to_datetime(i['timestamp']) i['amount'] = i['amount'] / arkinfo.ARK data_list.append([i['time'], i['amount']]) if type(i['share']) == float or type(i['share']) == int: i['share'] = str(i['share'] * 100) + '%' # incase no payouts have occured yet, this will render an empty graph if len(data_list) == 1: data_list.append([datetime.datetime.today(), 0]) data = SimpleDataSource(data=data_list) chart = LineChart(data, options={'title': 'Payout History'}) context.update({'chart': chart}) try: context['payout_history'].reverse() context['balance'] = context['balance'] / arkinfo.ARK context[ 'total_stake_reward'] = context['total_stake_reward'] / arkinfo.ARK context['error'] = False except Exception: context['error'] = True return render(request, "console/console_wallet_statistics.html", context)
def dashboard(request): data = [['Ports', 'ThreatIP', 'greg'], [2004, 1000, 400], [2005, 1170, 460], [2006, 660, 1120], [2007, 1030, 540]] # DataSource object data_source = SimpleDataSource(data=data) # Chart object chart = LineChart(data_source) context = {'chart': chart} return render(request, 'dashboard.html', context)
def import_sheet(request): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): user_id = get_current_user() abc_multiloc.objects.filter(creator=user_id).delete() request.FILES['file'].save_to_database(name_columns_by_row=2, model=abc_multiloc, mapdict=[ 'item_id', 'item_desc', 'loc_id', 'loc_desc', 'loc_type', 'sales' ]) data_table = abc(user_id) data_graph_x = abc_graph_x(user_id) if data_table: data = [['Year', 'Sales', 'Expenses'], [2004, 1000, 400], [2005, 1170, 460], [2006, 660, 1120], [2007, 1030, 540]] data1 = data_graph_x print(data1) # DataSource object data_source = SimpleDataSource(data=data1) # Chart object chart = LineChart(data_source) #context = {'chart': chart} return render( request, 'pareto/results.html', #context, { 'form': form, 'title': 'Excel file upload and download example', 'header': ('Please choose input excel file:'), 'data_table': data_table, 'chart': chart }) else: return HttpResponse("Something is Wrong") else: return HttpResponseBadRequest() else: form = UploadFileForm() return render( request, 'pareto/abc.html', { 'form': form, 'title': 'Excel file upload and download example', 'header': ('Please choose any excel file:') })
def termStatus(getParams): #signal signal = getParams['signal'] #imei imei = getParams['imei'] #maxTime maxTime = getParams['maxTime'] #minTime minTime = getParams['minTime'] #maxVal maxVal = getParams['maxVal'] #minVal minVal = getParams['minVal'] #volts volts = getParams['volts'] chart = None chartTitle = "Termination Status" chartDescription = "This is a test graph generated from terminate status data.\n This is mostly for demonstration.\n Please enjoy." chartOptions = {'title': chartTitle} onlyWantedData = [] dataHeader = [[ { 'type': 'datetime', 'label': 'Time' }, 'ballast', 'cutdown' ] # create a list to hold the column names and data for the axis names ] stati = models.Status.objects.filter( global_id__global_id__transmit_time__gte=minTime).filter( global_id__global_id__transmit_time__lte=maxTime).order_by( 'global_id') #print(ordered_fastmeasurements.query) top = 99999 if not maxVal else float(maxVal) bottom = -99999 if not minVal else float(minVal) wantedimei = imei if (imei in imeiNames): wantedimei = imeiNames[imei] for x in stati: if (wantedimei == '*' or wantedimei == str(x.global_id.global_id.imei)): tempDateTime = x.global_id.global_id.transmit_time tDTS = tempDateTime.strftime("Date(%Y, %m, %d, %H, %M, %S, %f)") tempDateString = tDTS[:11] + '{0:02d}'.format( int(tDTS[11:13]) - 1) + tDTS[13:31] + '{0:03d}'.format( int(tDTS[31:37]) // 1000) + tDTS[37:] onlyWantedData.append([tempDateString, x.ballast, x.cutdown]) data = dataHeader + onlyWantedData data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options=chartOptions) # Creating a line chart return chart, chartTitle, chartDescription, chartOptions
def set_passed(since, x_axis, title, context, context_key, graph_display, bins): p, f, s = get_stats(since, graph_display, bins) if p: p.insert(0, [x_axis, "passed"]) options = { "title": title, "hAxis": { "title": x_axis }, "vAxis": { "title": "Number of Tests" }, } context[context_key] = LineChart(SimpleDataSource(data=p), options=options) return p
def entry(request, entry_id): """Show an entry""" entry = get_object_or_404(Entry, id=entry_id) # Make sure the entry belongs to the current user. if entry.owner != request.user: raise Http404 prices = entry.price_set.order_by('date') data_source = ModelDataSource(prices, fields=['date', 'price']) chart = LineChart(data_source) context = {'entry': entry, 'prices': prices, 'chart': chart} return render(request, "pt/entry.html", context)
def graphos_test(request): #q = Tracker.objects.all() #data_source = ModelDataSource(q, fields = ['type', 'contract_value']) data = [ ['Year', 'Sales'], [2010, 150], [2011, 200], [2012, 300], ] data_source = SimpleDataSource(data=data) chart = LineChart(data_source) context = {'chart': chart} return render(request, 'reports/g_test.html', context)
def _open_model_trend(request): queryset = TemperatureReading.objects.all() data = [] dateSeen = {} for t in queryset: day = t.datetime.day month = t.datetime.month year = t.datetime.year if year in dateSeen: if month in dateSeen[year]: if day in dateSeen[year][month]: continue else: dateSeen[year][month].append(day) else: dateSeen[year] = { month: [ day, ] } else: dateSeen[year] = { month: [ day, ] } data.append([int(t.datetime.strftime('%Y%m%d')), float(t.value)]) data = sorted(data, key=lambda x: x[0]) data.insert(0, ['Date', 'Value']) chart = LineChart(SimpleDataSource(data=data), html_id="line_chart") data = {'chart': chart} s = chart.as_html() return render(template_name='model_popup.html', context=data, request=request)
def create_repo_pr_graph(repo, since, x_axis, title, graph_display, bins): q = models.PullRequest.objects.filter(repository__pk=repo["id"], created__gte=since).values("created") if not q.count(): return data = sort_stats_by_bin(q, "created", bins) all_data = [ [x_axis, repo["name"] ] ] for key in bins: display = key.strftime(graph_display) count = len(data.get(key, [])) row = [display, count] all_data.append(row) options = { "title": title, "hAxis": { "title": x_axis }, "vAxis": { "title": "%s new PRs" % repo["name"] }, } return LineChart(SimpleDataSource(data=all_data), options=options)
def depth_chart(request): request.session['alldata']={} request.session['dataname'] = "LEDE_depth_measurements" seshdata = request.session['alldata'] #start_time, chart_form = get_start_time(request) start_time, end_time, chart_form = get_startend_time(request) #qs = DepthMeasurement.objects.filter(stamp__gt=start_time).order_by('stamp') end_time = end_time + timedelta(0, 0, 0, 0, 59, 23) print(start_time, end_time) qs = DepthMeasurement.objects.filter(stamp__gt=start_time, stamp__lte=end_time).order_by('stamp') for dm in qs: seshdata.update({dm.stamp.strftime('%x %X'): dm.value}) #for k, v in seshdata.items(): #print('seshdata', k, v) #print(len(request.session['alldata'])) vmax = max([dm.value for dm in qs])#max_height + SENSOR_ELEVATION #print('vmax', vmax) vmin = min([dm.value for dm in qs])#math.floor(earliest_height + SENSOR_ELEVATION) vdiff = vmax - vmin vmax = math.ceil(vmax + 0.05*vdiff + SENSOR_ELEVATION) vmin = math.floor(vmin - 0.05*vdiff + SENSOR_ELEVATION) vaxisoptions = {'viewWindow': {'max': vmax, 'min': vmin}, 'title': 'Feet'} chartareaoptions = {}#{'left':60,'right':20, 'top':50, 'bottom':100}#{'width': '80%', 'height': '80%'} legendoptions = {'position': 'bottom'} themeoptions = None options = { 'height':'100%', 'width':'100%', 'vAxis':vaxisoptions, 'title':'Reservoir Surface Elevation', 'chartArea':chartareaoptions, 'legend':legendoptions, 'theme':themeoptions } chart = LineChart(DepthMeasurementDataSource(queryset=qs, fields=['stamp','value']), options=options)#, height=1000, width=1500) #chart = get_chart(qs, DepthMeasurementDataSource, 'Reservoir Surface Elevation', vmax=max_height + SENSOR_ELEVATION, vmin=math.floor(earliest_height + SENSOR_ELEVATION)) context = { 'chart': chart, 'form':chart_form, 'current_date':start_time.strftime('%m/%d/%Y'), 'end_date':end_time.strftime('%m/%d/%Y'), } template = 'datafetch/depth_chart.html' return render(request, template, context)
def conductivity(request): data = [ ['Time', 'V1', 'V2' ] # create a list to hold the column names and data for the axis names ] ordered_condmeasurements = models.ConductivityData.objects.order_by('global_id', 'sub_id') print(len(ordered_condmeasurements)) onlyWantedData = [[x.global_id.id*12+x.sub_id,x.vert1,x.vert2] for x in ordered_condmeasurements] data = data + onlyWantedData chartTitle = "Conductivity Measurements" chartDescription = "This is a test graph generated from all of the conductivity measurement data.\n This is mostly for demonstration.\n Please enjoy." data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': chartTitle}) # Creating a line chart context = {'chart': chart, 'title': chartTitle, 'description': chartDescription} return render(request, 'groundstation/graph.html',context)
def draw(request): queryset = Location.objects.filter(user__pk=request.user.id) data_source = ModelDataSource(queryset, fields=['place', 'population']) if request.method == 'GET' and not 'charts' in request.GET: chart = BarChart(data_source) elif request.GET['charts'] == "BarChart": chart = BarChart(data_source) elif request.GET['charts'] == "LineChart": chart = LineChart(data_source) elif request.GET['charts'] == "PieChart": chart = PieChart(data_source) elif request.GET['charts'] == "ColumnChart": chart = ColumnChart(data_source) context = {'chart': chart} return render(request, 'my_charts/draw.html', context)
def viewChartData(request, files_name="1"): startP = 0 data = [['Theta', 'Intensities']] upl_gr = '' xml_files = [] try: name = request.POST.get('retreive_elements') if request.method == 'GET': static_xml_obj = upload.objects.last() intens_1 = xml_intensities.objects.get( upload_xml=static_xml_obj.id) startP = intens_1.startPosition # apache spark paralellize func data1 = apache_separate_data(intens_1) # data list for the Chart data.extend(data1) else: xml_obj = upload.objects.get(name_of_file=name) intens_1 = xml_intensities.objects.get(upload_xml=xml_obj.id) startP = intens_1.startPosition # apache spark paralellize func data1 = apache_separate_data(intens_1) data.extend(data1) except Exception as e: template = 'data/viewChartsError.html' return render(request, template) # DataSource object data_source = SimpleDataSource(data=data) # Chart object chart = LineChart(data_source, width='950px', options={'title': 'XRD: Theth2 / Intensities'}) template = 'data/viewCharts.html' context = {'chart': chart, 'name': name, 'startP': startP} return render(request, template, context)
def subject_detail(request, subject_id): """ Get general statistics for a determined subject, displaying average grade, total questions answered, etc. :param request: Request :param subject_id: int :return: View """ user = request.user subject = models.Subject.objects.get(id=subject_id) user_exams = models.Exam.objects.filter(user=user, subject=subject) subject_title = subject.subject_title exams = dict() avg = 0 taken = 0 questions = 0 correct = 0 data = [ ['Time', 'Result'], ] for e in user_exams: taken += 1 exams[e.id] = "Exam " + str(taken) avg += e.exam_result data.append([taken, e.exam_result * 10]) questions += e.exam_quantity_questions correct += e.amount_correct exams_general = ("{0:.2f}".format( (avg / taken) * 10), taken, questions, correct, questions - correct) data_source = SimpleDataSource(data=data) chart = LineChart(data_source) context = dict() context['subject_title'] = subject_title context['exams_general'] = exams_general context['exams'] = exams context['chart'] = chart return render(request, 'choicemaster/statistics/subject_detail.html', context)
def altitude(request): data = [['DayTime', 'Altitude']] db = MySQLdb.connect(host="localhost", user="******", passwd="raspberry", db="myproject") cur = db.cursor() cur.execute('SELECT * FROM myproject.tutorialapp_table_gps') for row in cur.fetchall(): l = [] l.append(row[0]) l.append(row[6]) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Altitude"}) context = {'chart': chart} return render(request, 'tutorial/altitude.html', context)
def gps(request): # Change to google maps data = [ ['Time', 'Latitude', 'Longitude'] # create a list to hold the column names and data for the axis names ] db = MySQLdb.connect(host="localhost", user=secrets.sqluser,passwd=secrets.sqlpassword, db="groundstation") # Access the database to get all the current data cur = db.cursor() cur.execute('SELECT i.transmit_time,d.gps_latitude,d.gps_longitude,gps_altitude FROM groundstation.groundstationapp_slowmeasurement AS d INNER JOIN groundstationapp_iridiumdata AS i on i.global_id_id = d.global_id_id' ) for row in cur.fetchall(): # going through each row l = [] l.append(row[0]) # append each row to the data, only get the columns that we want l.append(row[1]) l.append(row[2]) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Coordinates"}) # Creating a line chart context = {'chart': chart} return render(request, 'groundstation/gps.html', context) # rendering the chart when a request has gone through for this page, and using the mapPlot.html to render it
def viewChart(request): intens = xml_intensities.objects.last() xml_files = upload.objects.all() name = request.POST.get('dropdown1') # apache spark paralellize func paralel_data = sc.parallelize(intens.intensities, 12) pd_count = paralel_data.count() pd_count /= 5 numbers = paralel_data.map(lambda line: re.split(' ', line.strip())) theta2_difer = (intens.endPosition - intens.startPosition) / (pd_count) theta = theta2.startPosition count_ch = 1 i_char = '' data = [['Theta', 'Intensities']] for i in intens.intensities: if i == " ": theta += theta2_difer d = [theta, int(i_char)] data.append(d) i_char = '' pd_count -= 1 count_ch += 1 i_char += i # DataSource object data_source = SimpleDataSource(data=data) # Chart object chart = LineChart(data_source) template = 'data/viewChats.html' context = { 'chart': chart, 'xml_files': xml_files, 'pd_count': pd_count, 'count_ch': count_ch, 'name': name } return render(request, 'data/viewCharts.html', context)
def index(request): print('POST:', request.POST) if request.POST.get('flag'): toggle_flag(request) time.sleep(1) return redirect('index', permanent=False) result = refresh_values(request) sensor_data = {} for sensor in result.get('sensor_data'): name = sensor.get('name').split(' ')[0] if name not in sensor_data.keys(): sensor_data[name] = [] sensor_data[name].append(sensor) system = System.objects.get(id=1) # XXX: hard-coding data = [ ['DateTime', 'Water_Level'], [2004, 100], [2005, 117], [2006, 660], [2007, 103], [2008, 100], [2009, 117], [2010, 660], [2011, 103], ] # DataSource object data_source = SimpleDataSource(data=data) # Chart object chart = LineChart(data_source, height=300, width=1000) context = { 'errors': result.get('errors'), 'sensor_data': sensor_data, 'system_name': system.name, 'chart': chart, } return render(request, 'sensor_list.html', context)
def vertical(request): data = [['DayTime', 'Vertical1', 'Vertical2', 'Vertical3']] db = MySQLdb.connect(host="localhost", user="******", passwd="raspberry", db="myproject") cur = db.cursor() cur.execute('SELECT * FROM myproject.tutorialapp_vertical') for row in cur.fetchall(): l = [] l.append(row[0]) l.append(row[1]) l.append(row[2]) l.append(row[3]) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Vertical"}) context = {'chart': chart} return render(request, 'tutorial/vertical.html', context)
def horizontal(request): data = [['DayTime', 'Horizontal1', 'Horizontal2', 'HorizontalDelta']] db = MySQLdb.connect(host="localhost", user="******", passwd="raspberry", db="myproject") cur = db.cursor() cur.execute('SELECT * FROM myproject.tutorialapp_horizontal') for row in cur.fetchall(): l = [] l.append(row[0]) s = 0.0 # Averaging the data, not plotting all 12 points for the Horiz1, Horiz2, and HorizD for i in range(1, 12 + 1): s += row[i] l.append(s / 12.0) s1 = 0.0 for i in range(13, 24 + 1): s1 += row[i] l.append(s1 / 12.0) s2 = 0.0 for i in range(24, 36 + 1): s2 += row[i] l.append(s2 / 12.0) data.append(l) db.close() data_source = SimpleDataSource(data=data) chart = LineChart(data_source, options={'title': "Horizontal"}) context = {'chart': chart} return render(request, 'tutorial/horizontal.html', context)