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_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 post(): if 'token' in request.headers: parser.add_argument('emp_email', help='This field cannot be empty', required=True) data = parser.parse_args() validate_admin = User.validate_token(request.headers['token'], True) if validate_admin: response = Location.get_locations(data) else: validate = User.validate_token(request.headers['token'], False, data['emp_email']) if validate: response = Location.get_locations(data) else: response = { "status": "success", "code": 200, "message": "Either Token Mismatched or token of " "respective email not matched." } return response else: return { "status": "error", "code": 401, "message": "Token is required in headers." }
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 get_costs(args): try: center = Location.get(Location.name == args.center) except pw.DoesNotExist: print('Location by the name {} is not known'.format(args.center)) return locations = [ util.random_location_in_circle(center, args.radius) for i in range(2 * args.samples) ] trips = zip(*[iter(locations)] * 2) for start, end in trips: cost_json = lyft.get_cost(ride_type='lyft', **start.as_start(), **end.as_end()) cost = Cost.create(**cost_json.__dict__['__data__']) start = Location.create(**start.__dict__['__data__']) end = Location.create(**end.__dict__['__data__']) CostEstimate.create(cost=cost, start_location=start, end_location=end, time=datetime.now())
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 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 test_get_block(self): dao = Dao(db_file='c:/bench/bluestreets/data/26161.db', stateful=True) contact = Contact() contact.address = Address({'address': '3000 Newcastle Rd'}) contact.zipcode = '48105' block = Location.get_block(dao, contact) contact.zipcode = '' contact.city = 'ANN ARBOR' block = Location.get_block(dao, contact) dao.close()
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 test_extract_geohash(self): """Assert the geohash extraction is done correctly""" location = Location(lat=4.718400, lng=-74.027692) self.assertEqual( location.extract_geohash(6), 'd2g6g6', msg='Geohash of precision 6 is extracted incorrectly.') self.assertEqual( location.extract_geohash(8), 'd2g6g6yw', msg='Geohash of precision 8 is extracted incorrectly.')
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 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 update_names(self): for loc in Location.find(): loc.nursing_home_name = util.unescape(loc.nursing_home_name) loc.save() return u"Success!"
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 get(self, device_id): locations = Location.get_locations_by_device_id(device_id) result = [] if locations: for location in locations: result.append(json.loads(location_schema.dumps(location))) return result, 200
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 locationValidate(lat_lng): lat = lat_lng.split(',')[0].strip() lng = lat_lng.split(',')[1].strip() locationModel = Location() inlocation = locationModel.getLocationFromPosition({'lat':lat, 'lng':lng}) print inlocation # Now allowing posts from all location # if inlocation is None: # raise ValueError("This is an invalid location.") if inlocation is None: inlocation = dict() inlocation['id'] = 0 data = dict() data['lat_lng'] = lat_lng data['data'] = inlocation return data
def location_generate(self): city = "" state = "" zip = "" location = Location(city, zip, state) return vars(location)
def location(self): loc = Location.get_by_key_name(self.location_id) if loc: return loc.name else: return ""
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 find_weathers_data(): query = request.values['location'] weather = Weather(Location(query)) db.session.add(weather) db.session.commit() return jsonify(weather.data())
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 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 __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 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 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 do_i_need_umbrella(location: Location = fastapi.Depends()): print(location.city) # print(location['city']) -> TypeError: 'Location' object is not subscriptable loc = location.dict() print(loc['city']) return loc
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 add_location(name) -> Location: """ :param name: :return: """ newloc = Location(name) commit(newloc) return newloc
def create(self, facebook): me = facebook.api(u'/me', {u'fields': USER_FIELDS}) friends = [user[u'id'] for user in me[u'friends'][u'data']] location = me.get(u'location') hometown = me.get(u'hometown') if location: location_id = int(location[u'id']) elif hometown: location_id = int(hometown[u'id']) else: location_id = 0 location_id = str(location_id) if location_id != "0" and not Location.get_by_key_name(location_id): Location.create(location_id, facebook) user = User( key_name=facebook.user_id, user_id=facebook.user_id, dirty=False, name=me.get(u'name'), first_name=me.get(u'first_name'), last_name=me.get(u'last_name'), gender=me.get(u'gender'), username=me.get(u'username'), email=me.get(u'email'), picture=me.get(u'picture'), link=me.get(u'link'), friends=friends, location_id=location_id, access_token=facebook.access_token, ) user.put() return user
def post(self): city = self.request.get("city") country = self.request.get("country") result = Location.create_from_string(user=self.user, location_name="%s, %s" % (city, country)) if result: message = "Thank you for providing your location" else: message = "We could not find your location. Please check your spelling and try again" # return simplejson.dumps({"result": result, "message": message}) self.redirect("/geo?message=%s" % message)
def get_all_locations(self): locations = [] points = [] for user in User.all(): if user.location_id != 0 and not user.location_id in locations: locations.append(str(user.location_id)) locations = [loc for loc in Location.get_by_key_name(locations) if loc != None] for location in locations: points.append({ "point": [location.lat(), location.lng()], "name": location.name }) return simplejson.dumps(points)
def update_info(self, email, location): Location.create_from_string(user=self, location_name=location) if email and email != "" and self.email != email: self.email = email self.put()
def page(self, start=0, limit=10): locations = Location.find(query={"city":"Chicago"}).skip(int(start)).limit(int(limit)).sort("nursing_home_name", 1) return JSONObject(success=True, action="replace", html=self.render("locations.html", args={"locations":locations}), identifier="#locations", data={"next":start})
def tab_details(self, id): ob = Location(id=id) return JSONObject(success=True, html=ob.render_form())