def on_post(self, request, response, rider_id=None): if not rider_id: raise falcon.HTTPPreconditionFailed("Rider id not provided") rider = helpers.get_rider(rider_id) if not rider: raise falcon.HTTPPreconditionFailed("Rider with id: {} not found".format(rider_id)) if rider.riding: raise falcon.HTTPUnprocessableEntity("Rider is already riding") body = json.load(request.stream) pickup_location = body.get("pickup_location") drop_location = body.get("drop_location") if not pickup_location or not drop_location: raise falcon.HTTPPreconditionFailed("Pickup or Drop location not specified") try: ride = Ride(Location(**pickup_location), Location(**drop_location), rider) except Exception as e: raise falcon.HTTPUnprocessableEntity(e) taxi_category = body.get("category") taxi = helpers.get_nearest_available_taxi(Location(**pickup_location), taxi_category) if not taxi: ride.set_taxi_unavailable() raise falcon.HTTPUnprocessableEntity("Taxi is unavailable") ride.start(taxi) RIDES.append(ride) response.body = json.dumps({"message": "Ride registered.", "data": ride.to_dict()}) response.status = falcon.HTTP_201
def test_to_dict(self): """Asserts the Stop is correctly parsed to a Dict""" depot_stop = Stop(depot_id='my_depot', location=Location(lat=1.23, lng=4.56)) depot_stop_dict = depot_stop.to_dict() self.assertEqual( depot_stop.depot_id, depot_stop_dict['depot_id'], msg='Depot stop has incorrect depot_id after parsing.') self.assertEqual( depot_stop.location.coordinates, depot_stop_dict['location'], msg='Depot stop has incorrect location after parsing.') self.assertIsNone(depot_stop_dict['riders'], msg='Depot stop has non-null riders.') riders_stop = Stop( riders={ 'my_rider': Rider(location=Location(lat=1.23, lng=4.56), rider_id='my_rider') }) riders_stop_dict = riders_stop.to_dict() self.assertIsNone(riders_stop_dict['depot_id'], msg='Riders stop has non-null depot_id.') self.assertEqual( depot_stop.location.coordinates, riders_stop_dict['location'], msg='Riders stop has incorrect location after parsing.') self.assertIsNotNone(riders_stop_dict['riders'], msg='Riders stop has null riders.')
def test_build_stops_absent_depots(self): """Asserts depots are excluded if no vehicle starts or ends there""" params = get_params() estimator = LinearEstimator() builder = ProblemBuilder(params=params, estimator=estimator) rider_1 = Rider(location=Location(lat=1.234, lng=5.678), rider_id='rider_1') rider_2 = Rider(location=Location(lat=5.678, lng=1.234), rider_id='rider_2') depot_1 = Depot(depot_id='depot_1', location=Location(lat=0, lng=0)) depot_2 = Depot(depot_id='depot_2', location=Location(lat=0, lng=0)) riders = {rider_1.rider_id: rider_1, rider_2.rider_id: rider_2} depots = {depot_1.depot_id: depot_1, depot_2.depot_id: depot_2} # Case 1: all depots are needed starts = [0, 0] ends = [0, 1] stops = builder._build_stops(riders, depots, starts, ends) self.assertEqual(len(stops), 4, msg='Wrong number of stops when all depots are used.') # Case 2: some depots are needed starts = [0, 0] ends = [0, 0] stops = builder._build_stops(riders, depots, starts, ends) self.assertEqual( len(stops), 3, msg='Wrong number of stops when some depots are used.')
def test_build_starts_ends(self): """Asserts start and end locations are correctly created""" vehicle_1 = Vehicle(capacity=0, start='depot_1', end='depot_1', vehicle_id='vehicle_1') vehicle_2 = Vehicle(capacity=0, start='depot_1', end='depot_2', vehicle_id='vehicle_2') depot_1 = Depot(depot_id='depot_1', location=Location(lat=0, lng=0)) depot_2 = Depot(depot_id='depot_2', location=Location(lat=0, lng=0)) vehicles = { vehicle_1.vehicle_id: vehicle_1, vehicle_2.vehicle_id: vehicle_2 } depots = {depot_1.depot_id: depot_1, depot_2.depot_id: depot_2} starts, ends = ProblemBuilder._build_vehicles_starts_ends( vehicles, depots) self.assertTrue(starts, msg='Empty start locations.') self.assertTrue(ends, msg='Empty ends locations.') self.assertEqual( len(starts), len(vehicles), msg='Starts list differs from length to vehicles list.') self.assertEqual(len(starts), len(ends), msg='Starts list differs from length to ends list.') self.assertEqual(starts, [0, 0], msg='Starts list does not match.') self.assertEqual(ends, [0, 1], msg='Ends list does not match.')
def test_linear_estimator_estimate(self): """Asserts linear estimations are correctly calculated""" stop_1 = Stop( depot_id='depot_1', location=Location(lat=4.720634, lng=-74.037228) ) stop_2 = Stop( depot_id='depot_2', location=Location(lat=4.708958, lng=-74.035172) ) estimator = LinearEstimator() estimations = estimator.estimate(stops=[stop_1, stop_2]) self.assertEqual( len(estimations), 4, msg='Number of estimations incorrect.' ) expected_estimation = round( haversine( point1=stop_1.location.coordinates, point2=stop_2.location.coordinates ) / DEFAULT_VELOCITY ) for (origin, destination), est in estimations.items(): if origin == destination: self.assertEqual( est, 0., msg='Same origin and destination has non-zero estimation.' ) else: self.assertEqual( round(est), expected_estimation, msg='Estimated linear time differs to distance / velocity.' )
def setUp(self): self.europe = Continent("Europe", 2) self.scotland = Country("Scotland", self.europe, 1) self.iceland = Country("Iceland", self.europe, 3) self.glencoe = Location("Glencoe", "This is stunning location, i need to see it", False, self.scotland, 1) self.godafoss = Location("Godafoss", "The most amazing waterfall i have ever seen", True, self.iceland, 2) self.no_id = Location("No id", "locaiton without id", True,self.scotland)
def __init__(self, origin, destination, partnerReferenceId, desiredDeliveryDate, trailerType, vehicles, hasInOpVehicle: bool, availableDate, price, **kwargs): self.origin = Location(**origin) self.destination = Location(**destination) self.partnerReferenceId = partnerReferenceId self.desiredDeliveryDate = desiredDeliveryDate self.trailerType = trailerType self.vehicles = [Vehicle(**x) for x in vehicles] self.hasInOpVehicle = hasInOpVehicle self.availableDate = availableDate self.price = Price(**price)
def configure_fake_data(): # This was added to make it easier to test the weather event reporting # We have /api/reports but until you submit new data each run, it's missing # So this will give us something to start from. loop = None try: loop = asyncio.get_running_loop() print("got loop!", loop) except RuntimeError: pass # Boo, why can't I just get nothing back? if not loop: loop = asyncio.get_event_loop() try: loc = Location(city="Portland", state="OR", country="US") loop.run_until_complete( report_service.add_report("Misty sunrise today, beautiful!", loc)) loop.run_until_complete( report_service.add_report("Clouds over downtown.", loc)) except RuntimeError: print( "Note: Could not import starter date, this fails on some systems and " "some ways of running the app under uvicorn.") print("Fake starter data will no appear on home page.") print("Once you add data with the client, it will appear properly.")
def location_generate(self): city = "" state = "" zip = "" location = Location(city, zip, state) return vars(location)
def get_all_locations(): with sqlite3.connect("./kennel.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() db_cursor.execute(""" SELECT l.id, l.name, l.address FROM Location l """) locations = [] dataset = db_cursor.fetchall() for row in dataset: location = Location(row['id'], row['name'], row['address']) locations.append(location.__dict__) return json.dumps(locations)
def post(self, username): target = User.find(username) # Currently only authorised to update your own location if request.user != target: raise UnauthorisedError() parser = reqparse.RequestParser() parser.add_argument('lat', required=True, type=float, help='lat required') parser.add_argument('lon', required=True, type=float, help='lon required') args = parser.parse_args() # Comparision with 0.5 due to floating point error. if args['lat'] < 0.5 and args['lon'] < 0.5: db.session.delete(target.location) db.session.commit() else: location = target.location if location == None: location = Location() location.lat = args.lat location.lon = args.lon location.user_id = target.id location.updated = datetime.utcnow() db.session.add(location) db.session.commit() return {},200
def locations_add(): new_location = Location( request.form['name'], request.form['description'], request.form['visited'], country_repository.select(request.form['country_id'])) location_repository.save(new_location) return redirect('/locations/view')
def on_post(self, request, response): body = json.load(request.stream) taxi_location = None location = body.get("location") if location: try: taxi_location = Location(**location) except Exception as e: raise falcon.HTTPBadRequest("Taxi Location is invalid") try: taxi = Taxi(body.get("license_no"), body.get("color"), taxi_location) except InvalidTaxiColorException as e: raise falcon.HTTPBadRequest("Taxi color is not valid") except InvalidTaxiLicenseNumberException as e: raise falcon.HTTP.BadRequest("Taxi License number is invalid") TAXIS.append(taxi) response.body = json.dumps({ "message": "Taxi registered.", "data": taxi.to_dict() }) response.status = falcon.HTTP_201
def get_sensor_by_tag_name(self, data, values): if isinstance(data, dict): lat = lon = -1 temp = None for key in data: if isinstance(data[key], dict): self.get_sensor_by_tag_name(data[key], values) elif isinstance(data[key], list): self.get_sensor_by_tag_name(data[key], values) else: if key == self.tag: temp = data[key] elif key == self.location[0]: lat = float(data[key]) elif key == self.location[1]: lon = float(data[key]) if temp is not None and lat != -1 and lon != -1: values[temp] = Location(lat, lon) temp = None lat = lon = -1 elif isinstance(data, list): for key in data: if isinstance(key, dict): self.get_sensor_by_tag_name(key, values) elif isinstance(key, list): self.get_sensor_by_tag_name(key, values)
def create_location(): location = Location( request.form['room_name'], request.form['capacity'] ) location_repository.save(location) return redirect('/locations')
def post(self): from app import db args = parser.parse_args() business_hour = ', '.join(args.pop('business_hour')) new_location = Location(**args, business_hour=business_hour) db.session.add(new_location) db.session.commit() return marshal_location(new_location, business_hour)
def configure_fake_data(): # This was added to make it easier to test the weather event reporting # We have /api/reports but until you submit new data each run, it's missing # So this will give us something to start from. loc = Location(city="Portland", state="OR", country="US") asyncio.run( report_service.add_report("Misty sunrise today, beautiful!", loc)) asyncio.run(report_service.add_report("Clouds over downtown.", loc))
def setUp(self): self.europe = Continent("Europe", 2) self.scotland = Country("Scotland", self.europe, 1) self.iceland = Country("Iceland", self.europe, 3) self.glencoe = Location("Glencoe", "This is stunning location, i need to see it", False, self.scotland, 1) self.godafoss = Location( "Godafoss", "The most amazing waterfall i have ever seen", True, self.iceland, 2) self.glencoe_photo = Photo("devils_pulpit.jpg", True, self.glencoe, 1) self.godafoss_photo_01 = Photo("marina_sands01.jpg", True, self.godafoss, 2) self.godafoss_photo_02 = Photo("marina_sands01.jpg", True, self.godafoss)
def update_location(id, updated_location): # Iterate the ANIMALS list, but use enumerate() so that # you can access the index value of each item. for index, location in enumerate(LOCATIONS): if location["id"] == id: # Found the animal. Update the value. LOCATIONS[index] = Location(updated_location['id'], updated_location['name'], updated_location['address']) break
def locations_update(): country = country_repository.select(request.form['country_id']) updated_location = Location(request.form['location_name'], request.form['location_description'], request.form['location_visited'], country, request.form['location_id']) location_repository.update(updated_location) return redirect('/locations/view')
def find_weathers_data(): query = request.values['location'] weather = Weather(Location(query)) db.session.add(weather) db.session.commit() return jsonify(weather.data())
def __post_init__(self): """Procedures to be completed after the Stop is instantiated""" self.demand = len(self.riders) if not self.depot_id else self.demand if self.location is None: lat = mean([rider.location.lat for rider in self.riders.values()]) lng = mean([rider.location.lng for rider in self.riders.values()]) self.location = Location(lat=lat, lng=lng)
def add_location(name) -> Location: """ :param name: :return: """ newloc = Location(name) commit(newloc) return newloc
def select_all(): # working locations = [] sql = "SELECT * FROM locations" results = run_sql(sql) for row in results: country = country_repository.select(row['country_id']) location = Location(row['name'], country, row['id']) locations.append(location) return locations
def get_location(self, location_id, system_id): """ :param system_id :param location_id :return: location object """ url = "{}/systems/{}/locations/{}/".format(BASE_URL, system_id, location_id) results = self.r.get(url, headers=self._get_auth_header()).json() return Location(**results['locations'])
def select(id): location = None sql = "SELECT * FROM locations WHERE id = %s" values = [id] result = run_sql(sql, values)[0] if result is not None: location = Location(result['name'], result['category'], result['id']) return location
def _prepare_data_for_db(self, hash_tag, amount, like, comment, follow, split_comment, to_distribution, group_name, failed_posts_num, time_schedule): join_comment = ','.join(split_comment) hashtag = Location(self.username, hash_tag, amount, like, follow, comment, to_distribution, group_name, join_comment, failed_posts_num, time_schedule) LocationDB().save_in_db(hashtag)
def select(id): # working locations = None sql = "SELECT * FROM locations WHERE id = (%s)" values = [id] result = run_sql(sql, values)[0] if result is not None: country = country_repository.select(result['country_id']) location = Location(result['name'], country, result['id']) return location
def find_location_details(self, search_term): location = None try: result = self.client.geocode(search_term) location = Location(result[0]) except Exception as ex: print('Unable to get location details - {0}'.format(ex)) location = None finally: return location
def select_all(): locations = [] sql = "SELECT * FROM locations" results = run_sql(sql) for row in results: location = Location(row['name'], row['category'], row['id']) locations.append(location) return locations