def save(self): """Save a entrymeasure""" data = self.cleaned_data user = data['user'] profile = data['profile'] entrymeasure = EntryMeasure() if profile.measurement_system == 'METRIC': entrymeasure.bodyweight = Weight(kg=data['bodyweight']) entrymeasure.chest = Distance(cm=data['chest']) entrymeasure.waist = Distance(cm=data['waist']) entrymeasure.hip = Distance(cm=data['hip']) entrymeasure.leg = Distance(cm=data['leg']) entrymeasure.bicep = Distance(cm=data['bicep']) else: entrymeasure.bodyweight = Weight(lb=data['bodyweight']) entrymeasure.chest = Distance(inch=data['chest']) entrymeasure.waist = Distance(inch=data['waist']) entrymeasure.hip = Distance(inch=data['hip']) entrymeasure.leg = Distance(inch=data['leg']) entrymeasure.bicep = Distance(inch=data['bicep']) entrymeasure.user = user entrymeasure.profile = profile entrymeasure.date_measure = data['date_measure'] if data['front_image_url']: entrymeasure.front_image_url = data['front_image_url'] if data['side_image_url']: entrymeasure.side_image_url = data['side_image_url'] if data['back_image_url']: entrymeasure.back_image_url = data['back_image_url'] entrymeasure.save() return entrymeasure
def test_float_casting(self, caplog): m = MeasurementTestModel( measurement_distance=float(2000), measurement_distance_km=2, ) m.full_clean() assert m.measurement_distance.value == 2000 assert m.measurement_distance.unit == Distance.STANDARD_UNIT assert m.measurement_distance_km.value == 2 assert m.measurement_distance_km.unit == 'km' assert m.measurement_distance_km == Distance(km=2) m.measurement_distance_km = Distance(km=1) m.full_clean() assert m.measurement_distance_km.value == 1 assert m.measurement_distance_km.unit == 'km' assert m.measurement_distance_km == Distance(km=1) record = caplog.records[0] assert record.levelname == 'WARNING' assert record.message == ('You assigned a float instead of Distance to' ' tests.models.MeasurementTestModel.measurement_distance,' ' unit was guessed to be "m".')
def api_leaderboard(): reg_result = status.HTTP_200_OK app.logger.debug('api_leaderboard(): get leader board data called.') response = {'error': 'No data to display for the leader board.'} if request.method == 'POST' and request.headers['Content-Type'] == 'application/json': content = request.get_json() if 'number_leaders' in content.keys(): number_leaders = content['number_leaders'] else: number_leaders = 5 app.logger.debug('api_leaderboard(): get data for {} of leaders'.format(number_leaders)) total_result = {} total = DB.get_total_devices() if total > 0: total_result['total_kilometres'] = round(Distance(metre=total).km, 1) total_result['total_miles'] = round(Distance(metre=total).mi, 1) else: total_result['total_kilometres'] = 0.0 total_result['total_miles'] = 0.0 result = [] enteries = DB.get_leaderboard(number_leaders) for entry in enteries: result.append({'place': entry['place'], 'username': entry['username'], 'kilometres': round(Distance(metre=entry['mtrs']).km,1), 'miles': round(Distance(metre=entry['mtrs']).mi, 1)}) total_result['leaders'] = result response = total_result reg_result = status.HTTP_200_OK js = json.dumps(response, sort_keys=True) return Response(js, status=reg_result, mimetype='application/json')
def validate(self, data): group = self.context['request'].user.groups.values_list('name', flat=True) if 'player' not in data: raise serializers.ValidationError( 'Player id missing. Please add the player key.') if 'Club' in group: if data['player'].club != self.context['request'].user.club: raise exceptions.PermissionDenied( 'Club has no permission to access performance data of player.' ) else: measurement_system = self.context[ 'request'].user.club.measurement_system elif 'Coach' in group: if data['player'].club != self.context['request'].user.coach.club: raise exceptions.PermissionDenied( 'Coach has no permission to access performance data of player.' ) else: measurement_system = self.context[ 'request'].user.coach.club.measurement_system elif 'Player' in group: raise exceptions.PermissionDenied('Players can not post data.') else: raise exceptions.PermissionDenied('User group not selected.') try: unit = data['unit'] data.pop('unit') except KeyError: if measurement_system == 'SI': unit = 'cm' elif measurement_system == 'Imp': unit = 'inch' if unit == 'cm': if (50 <= data['fathers_height'] <= 250) and (50 <= data['mothers_height'] <= 250): fathers_height = Distance(cm=data['fathers_height']) mothers_height = Distance(cm=data['mothers_height']) else: raise serializers.ValidationError( 'Height (%s / %s) cm seems to be wrong.' % (data['fathers_height'], data['mothers_height'])) elif unit == 'inch': if (20 <= data['fathers_height'] <= 100) and (20 <= data['mothers_height'] <= 100): fathers_height = Distance(inch=data['fathers_height']) mothers_height = Distance(inch=data['mothers_height']) else: raise serializers.ValidationError( 'Height (%s / %s) inch seems to be wrong.' % (data['fathers_height'], data['mothers_height'])) else: raise serializers.ValidationError( 'Field unit needs to be cm or inch!') data['fathers_height'] = fathers_height data['mothers_height'] = mothers_height return data
def test_auto_si_kwargs(self): meters = Distance(meter=1e6) megameters = Distance(megameter=1) self.assertEqual( meters, megameters, )
class IngestSettings(NamedTuple): max_concurrent: int max_distance: Distance max_segments: int quality_settings: QualitySettings location_filter: Optional[LocationFilter] = None trailhead_distance_threshold: Distance = Distance(m=300) timeout_s: int = 10 stop_searching_cutoff: Distance = Distance(mi=8)
def api_username_data(): reg_result = status.HTTP_200_OK app.logger.debug('api_username_data(): get user data called.') response = {'error': 'No data.'} if request.method == 'POST' and request.headers['Content-Type'] == 'application/json': content = request.get_json() if not 'username' in content.keys(): response = {'error': 'Expecting key name username to get data for.', 'content': content} reg_result = status.HTTP_400_BAD_REQUEST else: username = content['username'] if 'days' in content.keys(): days = content['days'] else: days = 5 app.logger.debug( 'api_username_data(): get data for username {} for {} days'.format(username, days)) if not '@' in username: email = username + "@cmxtrackyoursteps.com" else: email = username if not DB.get_user(email): response = {'error': 'Username not found', 'username': username, 'email': email} reg_result = status.HTTP_404_NOT_FOUND else: devices = DB.get_devices_position(email) if len(devices) < 1: response = {'error': 'Could not get device for username', 'username': username, 'email': email} reg_result = status.HTTP_500_INTERNAL_SERVER_ERROR else: result = [] for device in devices: device_result = {} if 'mtrs' in device.keys(): device_result['username'] = username device_result['mac'] = device['mac'] device_result['total_kilometres'] = round(Distance(metre=device['mtrs']).km, 3) device_result['total_miles'] = round(Distance(metre=device['mtrs']).mi, 3) device_result['place'] = device['place'] if 'mac' in device.keys(): distance_days = DB.get_device_days(device['mac'], days) dst_day= [] for day in distance_days: dst_day.append({'date':'{:%m/%d/%Y}'.format(day['date']), 'km': round(Distance(metre=day['mtrs']).km,3), 'miles': round(Distance(metre=day['mtrs']).mi,3)}) device_result['distance_day'] = dst_day result.append(device_result) response = result reg_result = status.HTTP_200_OK #print(response) js = json.dumps(response, sort_keys=True) return Response(js, status=reg_result, mimetype='application/json')
def save(self, profile): """Update a profile""" data = self.cleaned_data profile.measurement_system = data['measurement_system'] if profile.measurement_system == 'METRIC': profile.height = Distance(m=data['height']) else: profile.height = Distance(ft=data['height']) profile.conuntry_code = data['country_code'] if data['picture']: profile.picture = data['picture'] profile.save()
def test_addition_subtraction(self): d = Distance(m=100) + Distance(m=200) self.assertEqual(d.m, 300) d += Distance(m=300) self.assertEqual(d.m, 600) with self.assertRaises(TypeError): d + 10 d -= Distance(m=150) self.assertEqual(d.m, 450) d = d - Distance(m=50) self.assertEqual(d.m, 400) with self.assertRaises(TypeError): d - 10
def save(self): """Update a entrymeasure""" entrymeasure = self.instance if 'delete' in self.data: entrymeasure.delete() return EntryMeasure() else: data = self.cleaned_data user = data['user'] profile = data['profile'] if profile.measurement_system == 'METRIC': entrymeasure.bodyweight = Weight(kg=data['bodyweight']) entrymeasure.chest = Distance(cm=data['chest']) entrymeasure.waist = Distance(cm=data['waist']) entrymeasure.hip = Distance(cm=data['hip']) entrymeasure.leg = Distance(cm=data['leg']) entrymeasure.bicep = Distance(cm=data['bicep']) else: entrymeasure.bodyweight = Weight(lb=data['bodyweight']) entrymeasure.chest = Distance(inch=data['chest']) entrymeasure.waist = Distance(inch=data['waist']) entrymeasure.hip = Distance(inch=data['hip']) entrymeasure.leg = Distance(inch=data['leg']) entrymeasure.bicep = Distance(inch=data['bicep']) entrymeasure.user = user entrymeasure.profile = profile if 'front_image_url' in self.changed_data: entrymeasure.front_image_url = data['front_image_url'] else: if data['clear_front_image']: entrymeasure.front_image_url = None if 'side_image_url' in self.changed_data: entrymeasure.side_image_url = data['side_image_url'] else: if data['clear_side_image']: entrymeasure.side_image_url = None if 'back_image_url' in self.changed_data: entrymeasure.back_image_url = data['back_image_url'] else: if data['clear_back_image']: entrymeasure.back_image_url = None entrymeasure.save() return entrymeasure
def _route_blocks(url, route): route_sub = { 'id': route['id'], 'timestamp': format_date(route['timestamp'], format='medium'), 'description': route['description'], 'name': route['name'], 'athlete.id': route['athlete']['id'], 'athlete.firstname': route['athlete']['firstname'], 'athlete.lastname': route['athlete']['lastname'], 'url': url, } blocks = [{ "type": "section", "text": { "type": "mrkdwn", "text": "<%(url)s|*%(name)s*> by <https://www.strava.com/athletes/%(athlete.id)s|%(athlete.firstname)s %(athlete.lastname)s>\n%(description)s\n\nCreated on %(timestamp)s" % route_sub, }, "accessory": { "type": "image", "image_url": generate_url(route), "alt_text": "route map", }, }] fields = [] if route.get('distance', None): fields.append({ "type": "mrkdwn", "text": "*Distance:* %smi" % round(Distance(m=route['distance']).mi, 2), }) if route.get('elevation_gain', None): fields.append({ "type": "mrkdwn", "text": "*Elevation:* %sft" % round(Distance(m=route['elevation_gain']).ft, 0), }) if fields: blocks.append({"type": "divider"}) blocks.append({"type": "section", "fields": fields}) return blocks
def get_network(request, network_id: str): try: network = TrailNetwork.objects.get(id=network_id) except TrailNetwork.DoesNotExist: return JsonResponse( status=404, data=dict(msg=f"Network {network_id} does not exist")) existing_circuit = Circuit.objects.filter(network=network).first() circuit = None if existing_circuit: circuit = circuit_dict(existing_circuit) if network_id in LENGTH_CACHE: print('cache hit') calculated = LENGTH_CACHE[network_id] else: graph = read_gpickle(BytesIO(network.graph.tobytes())) calculated = sum([w.length() for _, _, w in graph.edges.data('trail')], Distance(m=0)) LENGTH_CACHE[network_id] = calculated return JsonResponse(data=dict( id=network.id, name=network.name, milage=humanize(calculated.mi), circuit=circuit, trailheads=dict( type='FeatureCollection', features=[ dict(id=i, type='Feature', geometry=json.loads(trailhead.json)) for i, trailhead in enumerate(network.trailheads) ]), ))
def test_guess_distance(self): result = guess(30, 'mi') self.assertEqual( result, Distance(mi=30) )
def patient_registration(request): if request.method == 'POST': # Obtain information and create patient model try: first_name = request.POST['first-name'] last_name = request.POST['last-name'] date_of_birth = request.POST['date-of-birth'] email = request.POST['email'] sex = request.POST['sex'] race = request.POST['race'] weight = request.POST['weight'] height = request.POST['height'] # User did not fill out all fields. except KeyError: error = "Please fill out all the fields!" return render(request, 'accounts/patient-registration.html', {'error': error}) patient = Patient() patient.username = request.user patient.first_name = first_name patient.last_name = last_name patient.date_of_birth = date_of_birth patient.email = email patient.sex = sex patient.race = race patient.weight = Weight(lb=weight) patient.height = Distance(inches=height) patient.save() return redirect('health_story/set_up') else: return render(request, 'accounts/patient-registration.html')
def test_notification_device_too_fast(client): """API: send 10 test CMX notifications for a straight line, but too fast""" max_move_ft = Distance(m=cmx.app.config['MAX_MTRS_SEC']).ft * 2 x = 0 for i in range(10): x += max_move_ft json_data = json.dumps({ 'notifications': [{ 'moveDistanceInFt': max_move_ft, 'deviceId': cmx.app.config['test_mac'], 'locationCoordinate': { 'x': x, 'y': 200 + i }, 'floorId': 999 }] }) client_response = client.post('/notification', headers={ 'Authorization': 'Basic ' + cmx.app.config['valid_credentials'] }, data=json_data, content_type='application/json') sleep(1) assert client_response.status_code == 200
def recalculate_lengths(): for network in tqdm(TrailNetwork.objects.all(), total=TrailNetwork.objects.count()): graph = read_gpickle(BytesIO(network.graph.tobytes())) calculated_length = sum( [w.length_m() / 1000 for _, _, w in graph.edges.data('trail')]) network.total_length = Distance(m=calculated_length) network.save()
def test_attrib_conversion(self): kilometers = Distance(km=1) expected_meters = 1000 self.assertAlmostEqual(kilometers.m, expected_meters) with self.assertRaises(AttributeError): val = kilometers.invalid_unit
def change_units(self, measurement_system): """Change unit to new one""" if measurement_system == 'METRIC': self.bodyweight = Weight(kg=self.bodyweight.kg) self.chest = Distance(cm=self.chest.cm) self.waist = Distance(cm=self.waist.cm) self.hip = Distance(cm=self.hip.cm) self.leg = Distance(cm=self.leg.cm) self.bicep = Distance(cm=self.bicep.cm) else: self.bodyweight = Weight(lb=self.bodyweight.lb) self.chest = Distance(inch=self.chest.inch) self.waist = Distance(inch=self.waist.inch) self.hip = Distance(inch=self.hip.inch) self.leg = Distance(inch=self.leg.inch) self.bicep = Distance(inch=self.bicep.inch)
def get_context_data(self, **kwargs): """Add user and profile to context.""" context = super().get_context_data(**kwargs) context['user'] = self.request.user profile = self.request.user.profile if profile.measurement_system == 'METRIC': profile.height = Distance(m=profile.height.m) context['profile'] = profile return context
def test_measurement_json_serialize_deserialize(): from tests.models import MeasurementModel obj = MeasurementModel.objects.create(height=Distance(cm=20.0)) result = serialize_object_json(obj) obj_snapshot = deserialize_object_json(result) assert obj_snapshot assert obj_snapshot.height == obj.height
def validate(self, data): try: player = Player.objects.get(lab_key=data['player']) except Player.DoesNotExist: raise exceptions.NotFound('Player not found.') data['player'] = player data['predicted_height'] = Distance(cm=data['predicted_height']) return data
def test_multiply(self): m1 = 100 m2 = 200 d1 = Distance(m=m1) values = [150.5, Distance(m=m2)] expected_results = [150.5 * m1, m1 * m2] for value, expected_result in zip(values, expected_results): with self.subTest(value=value, type=pretty_name(value)): result = d1 * value if isinstance(value, Distance): self.assertIsInstance(result, Area) result = result.sq_m else: result = result.m self.assertAlmostEqual(result, expected_result, 6) with self.subTest(value=value, type=pretty_name(value)): mult = lambda x: x[0] * x[1] self.assertRaises(TypeError, mult, (d1, "can't multiply"))
def OnTypeHeight(self, event): value = self.height.GetValue() height = Distance(cm=value) self.heightConvert.SetLabel(str(round(height.inch, 4))) self.heightValue = value if (len(self.heightValue) > 0): self.calcButton.Enable() else: self.calcButton.Disable()
def test_model_save(): from tests.models import MeasurementModel, ExampleSnapshotModel obj = MeasurementModel.objects.create(height=Distance(cm=12.5)) snap = ExampleSnapshotModel.objects.create(snapshot=obj) assert snap.snapshot assert snap.snapshot.height == obj.height snap = ExampleSnapshotModel.objects.get() assert snap.snapshot assert snap.snapshot.height == obj.height
def SelectSAE(self, event): self.weightUnitsText.SetLabel('lbs ozs') self.heightUnitsText.SetLabel('ft in') if (len(self.weightValue) > 0): w = Weight(kg=self.weightValue) self.weightValue = w.lb self.weight.SetValue(str(self.weightValue)) if (len(self.heightValue) > 0): h = Distance(cm=self.heightValue) self.heightValue = h.ft self.height.SetValue(str(self.heightValue))
def test_set_value(self): distance = Distance(mi=10) expected_standard = 16093.44 self.assertEqual( distance.standard, expected_standard, ) distance.value = 11 expected_standard = 17702.784 self.assertEqual(distance.standard, expected_standard)
def create_circuit(self, network_id: str, circuit_id: str): network = TrailNetwork.objects.get(id=network_id) circuit = Circuit.objects.get(id=circuit_id) circuit.status = InProgress circuit.error = "" circuit.save() try: graph = read_gpickle(BytesIO(network.graph.tobytes())) with NamedTemporaryFile(suffix='.csv', mode='w') as f: writer = csv.DictWriter( f, fieldnames=['start', 'end', 'id', 'distance']) writer.writeheader() edge_map = {} for segment in segments_for_graph(graph): writer.writerow( dict(start=segment.nodes[0].derived_id, end=segment.nodes[-1].derived_id, id=segment.id, distance=segment.length_m())) edge_map[segment.id] = segment.nodes f.flush() circuit_nodes, _ = solver.cpp(f.name) stats = calculate_postman_solution_stats(circuit_nodes) walked_twice = Distance(m=stats['distance_doublebacked']) walked_total = Distance(m=stats['distance_walked_required']) line_string = circuit_to_line_string(circuit_nodes, edge_map) circuit.route = line_string circuit.total_length = walked_total circuit.status = Complete circuit.error = "" except Exception as ex: circuit.status = Error circuit.error = ex raise finally: circuit.save()
def calculate_run(act): # Get the query parameters and merge in the activity params = request.args params.update({'activity': act}) form = forms.CalculateRunForm(params) if not form.validate(): return jsonify({ 'status': 'ERROR', 'errors': form.errors }), 400 try: calories = calorie_calculator.calculate_calories_burned( activity=getattr(activity, act.capitalize())(), # Distance in miles or kilometers, depending on "units" value distance=Distance(**{'mi' if form.units.data == 'imperial' else 'km': form.distance.data}), # Bodyweight in pounds or kilograms, depending on "units" value bodyweight=Mass(**{'lb' if form.units.data == 'imperial' else 'kg': form.bodyweight.data}), # Elevation gain in meters or feet, depending on "units" value elevation_gain=Distance(**{'ft' if form.units.data == 'imperial' else 'm': form.elevation_gain.data}), duration=timedelta( hours=int(form.hours.data), minutes=int(form.minutes.data), seconds=int(form.seconds.data) ) ) except Exception as e: return jsonify({ 'status': 'ERROR', 'message': str(e), }), 500 return jsonify({ 'status': 'SUCCESS', 'calories': calories, }), 200
def postman(osm_data): Settings = IngestSettings( max_distance=Distance(km=50), max_segments=300, max_concurrent=40, quality_settings=DefaultQualitySettings, location_filter=None, ) loader = OSMIngestor(Settings) loader.load_osm(osm_data, extra_links=[(885729040, 827103027)]) # s = datetime.now() # data = write_gpickle(loader.global_graph, 'test.pickle') #nx_yaml.write_yaml(loader.global_graph, 'test.yaml') # e = datetime.now() # print(e-s) # s = datetime.now() # graph = read_gpickle('test.pickle') # e = datetime.now() # print(e-s) # import pdb; pdb.set_trace() for i, network in enumerate(loader.trail_networks()): print(network.name, network.total_length().mi) print(network.trail_names()) gmap = gmplot.GoogleMapPlotter(42.385, -71.083, 13) edge_map = {} for segment in network.trail_segments(): segment.draw(gmap) edge_map[segment.id] = segment.nodes clean_name = (network.name or f'no-name-{i}').replace(' ', '').replace("\'", '') gmap.draw(f"{clean_name}-{i}.html") with open('edges.csv', 'w') as csv_file: writer = csv.DictWriter(csv_file, fieldnames=['start', 'end', 'id', 'distance']) writer.writeheader() for segment in network.trail_segments(): writer.writerow(dict(start=segment.nodes[0].id, end=segment.nodes[-1].id, id=segment.id, distance=segment.length_m())) try: s = datetime.now() circuit, graph = cpp('edges.csv') e = datetime.now() print(f'Time: {e-s}') for k, v in calculate_postman_solution_stats(circuit).items(): print(k, v) with open(f"{clean_name}-{i}.gpx", "w") as f: f.write(circuit_to_gpx(circuit, edge_map).to_xml()) except Exception as ex: print(ex)
def get_khamis_roche(self, current_height, current_age, current_weight, fathers_height, mothers_height, gender): """ Calculates adults height based on Khamis Roche method. :param current_height: :param current_age: :param current_weight: :param fathers_height: :param mothers_height: :param gender: :return predicted_height: :return mean_absolute_deviation_50: :return mean_absolute_deviation_90: """ bash_command = " ".join([ self.khamis_roche_command, str(current_height), str(current_age), str(current_weight), str(mothers_height), str(fathers_height), gender, self.coefficients_file_khr ]) process = subprocess.Popen(bash_command.split(), stdout=subprocess.PIPE) output = str(process.communicate()[0]) results = output.split('\\n') try: predicted_height = Distance(cm=float(results[1])) meta = { 'mean_absolute_deviation_50': results[3], 'mean_absolute_deviation_90': results[5] } except IndexError: logger.error( 'Could not calculate khr with following values: ' '%s (current_height), ' '%s (current_age),' '%s (current_weight),' '%s (mothers_height),' '%s (fathers_height).' % (str(current_height), str(current_age), str(current_weight), str(mothers_height), str(fathers_height))) predicted_height = None meta = {} return predicted_height, meta