def fill_squere_points(self): """ Function to calculate the geolocation points (North-East, South-East, South-West, North-West) in base a geolocation point in the earth where is create a classroom with dimension NxN. Then the classroom know their points in the earth wich represent a square. """ meters = self.dimention / 2 # 1 degree in google map is equal to 111.32 Km. 1Degree = 111.32KM. # 1KM in Degree = 1 / 111.32 = 0.008983. 1M in Degree = 0.000008983 # 0.0000089 ~= coefficient of variation coefficient_variation = 0.0000089 coef = meters * coefficient_variation divLat = math.cos(math.radians(self.geolocation.latitude)) ne = Geolocation(self.geolocation.latitude + coef, self.geolocation.longitude + coef / divLat) se = Geolocation(self.geolocation.latitude - coef, self.geolocation.longitude + coef / divLat) sw = Geolocation(self.geolocation.latitude - coef, self.geolocation.longitude - coef / divLat) nw = Geolocation(self.geolocation.latitude + coef, self.geolocation.longitude - coef / divLat) self.square_points.append(ne) self.square_points.append(se) self.square_points.append(sw) self.square_points.append(nw)
def __init__(self, path: str, json_data: dict): self.path = path self.size = os.path.getsize(path) self.action_type = json_data.get('actionType', 'unknown') self.sensor_location = json_data.get('sensorLocation', 'unknown') self.note = json_data.get('note', '') self.start_time = json_data.get('startTime', '') self.end_time = json_data.get('endTime', '') self.handedness = json_data.get('handedness', '') self.sampling_frequency = json_data.get('samplingFrequency', 0) self.sampling_period = json_data.get('samplingPeriod', 0) self.watch_model = json_data.get('watchModel', '') self.distance = json_data.get('distance', '') self.phone = json_data.get('phone', '') geolocation = json_data.get('geolocation') if geolocation: lat = geolocation.get('latitude', 0.0) lon = geolocation.get('longitude', 0.0) alt = geolocation.get('altitude', 0.0) self.geolocation = Geolocation(lat, lon, alt) else: self.geolocation = Geolocation() self.gyro_sample_count = 0 gyro_data = json_data.get('gyroData') if gyro_data: self.gyro_sample_count = len(gyro_data) self.accel_sample_count = 0 accel_data = json_data.get('accelData') if accel_data: self.accel_sample_count = len(accel_data)
def main(): zoom = 15 tft = m5stack.Display() tft.text(10, 10, "> Reading settings.\n") with open("/flash/settings.json") as fp: settings = json.loads(fp.read()) tft.text(10, tft.LASTY, "> Connecting to wifi.\n") wifi = Wifi(settings["username"], settings["password"]) tft.text(10, tft.LASTY, "> Scanning networks.\n") networks = wifi.scan() tft.text(10, tft.LASTY, "> Locating current position.\n") geolocation = Geolocation(settings["api_key"], networks) coordinates = geolocation.coordinates() tft.text(10, tft.LASTY, "> Downloading the map.\n") map = Map(coordinates) map.save("/flash/map.jpg") tft.image(0, 0, "/flash/map.jpg") button_a = DigitalInput(Pin(m5stack.BUTTON_A_PIN, Pin.IN), callback=lambda pin: zoom_in_handler(map, tft)) button_c = DigitalInput(Pin(m5stack.BUTTON_C_PIN, Pin.IN), callback=lambda pin: zoom_out_handler(map, tft))
def find_routes_given_ingredients(user_location, ingredients): """ Finds the best driving routes for the user to purchase all the needed ingredients. :param user_location: the user's starting location - Location :param ingredients: a comma-separated list of the ingredients the user needs - string :return a list of routes, sorted best to worst """ Geolocation.load_lat_long_for_location(user_location) planner = TripPlanner(user_location) needed_items = ingredients.split(',') needed_items = [item.strip() for item in needed_items] print('Planning route from {} to get {}'.format(user_location, ', '.join(needed_items))) stores = get_stores_near_me(user_location, 20, 10) plans = planner.find_routes(needed_items, stores, 20, False) return plans
def test_construct_geolocation(self): location = Geolocation(47, -122, 535, 'Terry Ave N', 'South Lake Union', None, 'Seattle', 'Washington', 'United States', '98109') self.assertEqual(location.latitude, 47) self.assertEqual(location.longitude, -122) self.assertEqual(location.street_name, 'Terry Ave N') self.assertEqual(location.lv1_district, 'South Lake Union') self.assertEqual(location.city, 'Seattle') self.assertEqual(location.state, 'Washington') self.assertEqual(location.zipcode, '98109') locationJson = location.to_json(); self.assertEqual(locationJson['latitude'], 47) self.assertEqual(locationJson['longitude'], -122) self.assertEqual(locationJson['street_name'], 'Terry Ave N') self.assertEqual(locationJson['lv1_district'], 'South Lake Union') self.assertEqual(locationJson['city'], 'Seattle') self.assertEqual(locationJson['state'], 'Washington') self.assertEqual(locationJson['zipcode'], '98109')
def __parse_minibus(minibus: str): route_number, longitude, latitude, speed, heading, car_id = minibus.split(',')[1:-1] speed, heading = int(speed), int(heading) longitude, latitude = int(longitude) / 1000000, int(latitude) / 1000000 location = Geolocation(latitude=latitude, longitude=longitude) return car_id, Minibus(route_number=route_number, location=location, speed=speed, heading=heading)
def find_routes(self, needed_items, nearby_stores, max_distance, use_api=True): """ Finds all the possible routes to purchase the needed items within the specified search radius. NOTE: The list of stores passed may include stores outside the search radius. This method will filter the list based on search radius before finding routes. :param needed_items: list of grocery items needed - [str] :param nearby_stores: list of nearby stores - [Store] :param max_distance: maximum distance (in miles) of stores from starting location to include in route - int :param use_api: whether or not to use the Supermarket API - bool :return a list of TripPlans sorted best to worst - [TripPlan] """ # Filter the stores to only include stores with a Euclidean distance within the specified search radius self.stores = [ store for store in nearby_stores if Geolocation.get_euclidean_dist( self.starting_location, store.location) <= max_distance ] print('Checking nearest {} stores for the needed items...'.format( len(self.stores))) # Load items at stores found_all_items, missing_item = StoreItemFetcher( use_api).check_stores_for_ingredients(needed_items, self.stores) if not found_all_items: print('Could not find item {} anywhere. Aborting.'.format( missing_item)) return False, missing_item print('Calculating the distances between places...') # Get distances between places locations = [store.location for store in self.stores] locations.insert(0, self.starting_location) self.distance_mapper.load_distances(locations, locations) print('Planning...') base_plan = TripPlan(first_stop=self.starting_location) routes = self.__find_path_continuations( base_plan, [], needed_items, 2 * max_distance) # Max distance is the diameter of the circle # Add returning to the starting point for route in routes: dist_home = self.distance_mapper.get_distance( route.last_stop.location, self.starting_location) home_stop = TripStop(route.last_stop, None, self.starting_location, dist_home, None, 0) route.add_stop(home_stop) # Sort stores best to worst routes.sort(key=lambda r: r.last_stop.dist_from_start) return True, routes
def gtfs_stops(): with open('gtfs/stops.txt', mode='r', encoding='utf-8-sig', newline='') as file: delimiter = ',' fieldnames = file.readline().strip().split(delimiter) stop_reader = csv.DictReader(file, delimiter=delimiter, quotechar='"', fieldnames=fieldnames) for row in stop_reader: stop_id, name, longitude, latitude = row['stop_id'], row['stop_name'], row['stop_lon'], row['stop_lat'] longitude, latitude = float(longitude), float(latitude) location = Geolocation(longitude=longitude, latitude=latitude) yield stop_id, MinibusStop(location=location, name=name)
def test_closest(): stops = MinibusRoutes()[RouteID(route_number='246', type='a1-b')].stops minibus = Minibus(route_number='246', location=Geolocation(latitude=56.965532, longitude=24.167770), speed=0, heading=0) index, stop = closest_stop(minibus=minibus, stops=stops) assert_equal(index, 11)
def test_slack_attachments(self): minibuses = [ Minibus(route_number='224', speed=45, departure=35, heading=4, stop_index=3, stop=MinibusStop(location=Geolocation(latitude=56.945, longitude=24.195), name='Progresa iela'), location=Geolocation(latitude=56.946, longitude=24.196)), Minibus(route_number='224', speed=45, departure=35, heading=4, stop_index=7, stop=MinibusStop(location=Geolocation(latitude=56.945, longitude=24.195), name='Airītes iela'), location=Geolocation(latitude=56.946, longitude=24.196)), Minibus(route_number='224', speed=45, departure=35, heading=4, stop_index=0, stop=MinibusStop(location=Geolocation(latitude=56.9, longitude=24.1), name='Dubultu iela'), location=Geolocation(latitude=56.946, longitude=24.196)) ] attachments = self.app.format_for_slack(minibuses=minibuses) assert_is_not_none(attachments)
def online_stops(): csv_data = get_stops() delimiter = ';' fieldnames = csv_data.readline().strip().lower().split(delimiter) stop_reader = csv.DictReader(csv_data, delimiter=delimiter, fieldnames=fieldnames) for row in stop_reader: stop_id, name, longitude, latitude = row['id'], row['name'], row['lng'], row['lat'] longitude, latitude = int(longitude) / 100000, int(latitude) / 100000 location = Geolocation(longitude=longitude, latitude=latitude) yield stop_id, MinibusStop(location=location, name=name)
def getting_food(location=None, stops=None, cuisine=None, src=None): error = None if request.method == 'POST': if request.form['type'] and request.form['street'] and request.form[ 'city'] and request.form['state'] and request.form['zip']: zipcode = int(request.form['zip']) cuisine = str(request.form['type']) street_address = str(request.form['street']) city = str(request.form['city']) state = str(request.form['state']) # format ingredients ingredients = request.form['ingredients'] loc = Location(street_address, city, state, zipcode) did_find_items, results = find_routes_given_ingredients( loc, ingredients) print('Found {} possible routes'.format(len(results))) if not did_find_items: stops_html = '<p>Could not find item "{}" anywhere.'.format( results) elif len(results) > 0: stops = results[0].get_stops_as_list() num_stops = len(stops) if num_stops > 0: src = Geolocation.get_directions_request_url(loc, stops) stops_html = '' for i in range(1, num_stops): stop_html = get_html_for_stop(stops[i], i) stops_html = '{}{}\n'.format( stops_html, stop_html) # Append stop HTML else: stops_html = '<p>No viable routes found</p>' src = '' else: stops_html = '<p>No viable routes found</p>' return render_template('results_cuisine.html', location=loc, stops=stops_html, cuisine=cuisine, src=src) else: return render_template('food_input.html')
def get_stores_near_me(my_loc, radius, number): """ Get stores within a certain radius of user location. :param my_loc: location of the user - Location :param radius: search radius (miles) :param number: maximum number of stores to return """ sia = StoreInfoAccessor() stores = sia.get_stores_in_zip_range(my_loc.zipcode - 200, my_loc.zipcode + 200) stores_in_range = [] euc_dists = {} for s in stores: dist = Geolocation.get_euclidean_dist(my_loc, s.location) if dist <= radius: euc_dists[s.store_id] = dist stores_in_range.append(s) # Sort according to Euclidean distance stores_in_range.sort(key=lambda store: euc_dists[store.store_id]) # Return the top _number_ of stores return stores_in_range[:number]
from calendar_adt import Calendar from geolocation import Geolocation from telegram.ext import Updater, CommandHandler, MessageHandler, Filters update = Updater(token='1134...6r64') dispatcher = update.dispatcher if __name__ == '__main__': c = Calendar() g = Geolocation() dispatcher.add_handler(CommandHandler('start', c.startCommand)) dispatcher.add_handler(CommandHandler('add', c.AddMessage)) dispatcher.add_handler(CommandHandler('delete', c.DeleteMessage)) dispatcher.add_handler(CommandHandler('change', c.ChangeMessage)) dispatcher.add_handler(CommandHandler('check_daily', c.CheckDailyMessage)) dispatcher.add_handler(CommandHandler('check_next_events', c.CheckNextEventsMessage)) dispatcher.add_handler(CommandHandler('route', g.DirectionMessage)) dispatcher.add_handler(CommandHandler('transport', g.TransportMessage)) update.start_polling() update.idle()
def __init__(self, name, latitude, longitude): self.name = name self.position = Geolocation(latitude, longitude)
def __init__(self, name, latitude, longitude): self.name = name self.geolocation = Geolocation(latitude, longitude) self.square_points = [] self.dimention = 20 self.fill_squere_points()
import webapp2 import urllib, urllib2, requests import markupsafe import os, json, datetime, logging import model from webapp2_extras import sessions from google.appengine.api import channel from searchimagery import ScriptEngine from searchEngine import SearchEngine from geolocation import Geolocation from YoutubeSearch import YtubeSearch geolocation = Geolocation() searchEngine = SearchEngine() dbWrapper = model.DataStoreWrapper class QueryHandler(webapp2.RequestHandler): def dispatch(self): # Get a session store for this request. self.session_store = sessions.get_store(request=self.request) try: # Dispatch the request. webapp2.RequestHandler.dispatch(self) finally: # Save all sessions. self.session_store.save_sessions(self.response)
import asyncio import websockets from geolocation import Geolocation import json geolocation = Geolocation() geolocation.connect_to_base() '''Класс Websocket''' class Websocket(): timeout = 1 client_imei = [] USERS = set() host = "127.0.0.1" port = 3000 async def addUser(self, websocket): self.USERS.add(websocket) async def removeUser(self, websocket): self.USERS.remove(websocket) def start(self): start_ws = websockets.serve(self.main, self.host, self.port) asyncio.get_event_loop().run_until_complete(start_ws) asyncio.get_event_loop().run_forever() '''Опрос базы данных и отправка клиенту локации тс с запрошенными imei с интервалом timeout'''
food = "&ItemName=" + food return base_url + SUPERMARKET_API_KEY + store + food if __name__ == '__main__': from flask import Flask, g from main import get_stores_near_me from models import Location from geolocation import Geolocation from planning import TripPlanner app = Flask(__name__) with app.app_context(): needed_items = ['apples', 'cashews', 'butternut squash'] try: user_loc = Location('1000 Olin Way', 'Needham', 'MA', 2492) Geolocation.load_lat_long_for_location(user_loc) stores = get_stores_near_me(user_loc, 10, 20) # sif = StoreItemFetcher(False) # sif.check_stores_for_ingredients(needed_items, stores) planner = TripPlanner(user_loc) plans = planner.find_routes(needed_items, stores, 20, False) for plan in plans: print(plan) finally: db = getattr(g, '_database', None) if db: db.close()
def test_distance_calculations(): distance = Geolocation(1.006, 1) - Geolocation(1, 1) assert_equals(int(distance), 667)