コード例 #1
0
ファイル: compute.py プロジェクト: tolejnic/tsp
def getLatLng(addresses):
    from GoogleMaps import GoogleMaps
    latlng=[]
    gmaps = GoogleMaps('ABQIAAAA3IBuOitfkPwNDWiqqQcHCBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxSfoUckXCUPUmN3veq7-AVDtPiLIA')
    for address in addresses:
        lat, lng = gmaps.address_to_latlng(address) 
        latlng.append((float(lat),float(lng)))
    return latlng
コード例 #2
0
    def __init__(self):
        configs = json.load(open(f'./config.json'))
        # print(configs)

        self.base_url = configs['base_url']
        self.gmap = GoogleMaps(configs['googlemap_api_key'])
        self.db = Firestorage(configs['firebase_url'])

        self.machine = GraphMachine(
            model=self,
            states=["user", "postback", "nearby", "favorlist", "graph"],
            transitions=[
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "postback",
                    "conditions": "is_going_to_postback",
                },
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "nearby",
                    "conditions": "is_going_to_nearby",
                },
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "favorlist",
                    "conditions": "is_going_to_favorlist",
                },
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "graph",
                    "conditions": "is_going_to_graph",
                },
                {
                    "trigger": "go_back",
                    "source": ["postback", "nearby", "favorlist", "graph"],
                    "dest": "user"
                },
            ],
            initial="user",
            auto_transitions=False,
            show_conditions=True,
        )
コード例 #3
0
ファイル: compute.py プロジェクト: tolejnic/tsp
def cartesian_matrix(coords):
    '''create a distance matrix for the city coords that uses straight line distance'''
    from GoogleMaps import GoogleMaps
    gmaps = GoogleMaps('AIzaSyAVbFFRee1cluzDx2G3aTBvpmgeN1glxbI')
    
    matrix={}
    
    for i,(x1,y1) in enumerate(coords):
        for j,(x2,y2) in enumerate(coords):
            x = str(x1)+', '+str(y1)
            y = str(x2)+', '+str(y2)
            dirs = gmaps.directions(x, y)                  
            distance  = dirs['Directions']['Distance']['meters']           # get distance in meters
            distance = round(distance/1609.344)                            # convert to miles   
            matrix[i,j]=distance
    return matrix
    
    '''
コード例 #4
0
ファイル: geotag.py プロジェクト: imolloy/gpx_geotagger
 def __init__(self, **kwargs):
     self.gpx_file = kwargs['gpx_file']
     self.verbose = kwargs['verbose']
     self.xmp = kwargs['xmp']
     self.hours = kwargs['hours']
     self.minutes = kwargs['minutes']
     self.seconds = kwargs['seconds']
     self.execute = kwargs['execute']
     self.exiftool = kwargs['exiftool']
     self.process_timestamps()
     self.files_read = 0
     self.files_tagged = 0
     self.GM = GoogleMaps(kwargs['maps'])
コード例 #5
0
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 02 00:12:19 2017

@author: Ruo Xi
"""

from GoogleMaps import GoogleMaps

g = GoogleMaps()

locations = dict()

f = open("EntertainmentLatlongs.txt", "w")

for l in open("EntertainmentLocations.txt"):
    r = g.getLatLong(l)["results"]
    if len(r) == 0:
        print "Couldnt find " + l
        continue
    r = r[0]["geometry"]["location"]
    locations[l] = str(r["lat"]) + "," + str(r["lng"])
    f.write(l[:len(l) - 1] + "|" + locations[l] + "\n")
    f.flush()
コード例 #6
0
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 02 00:31:21 2017

@author: Ruo Xi
"""

from GoogleMaps import GoogleMaps

g = GoogleMaps()

locations = []

for l in open('EntertainmentLatlongs.txt'):
    arr = l.split("|")
    locations.append((arr[0], arr[1]))

d = open("taxiDistanceE.csv", "w")
t = open("taxiTimeE.csv", "w")

taxiTimes = []
taxiDistances = []

for i in range(len(locations)):
    taxiTimes.append([])
    taxiDistances.append([])
    for j in range(len(locations)):
        taxiTimes[i].append(0)
        taxiDistances[i].append(0)

for i in range(len(locations)):
コード例 #7
0
class TocMachine(GraphMachine):
    def __init__(self):
        configs = json.load(open(f'./config.json'))
        # print(configs)

        self.base_url = configs['base_url']
        self.gmap = GoogleMaps(configs['googlemap_api_key'])
        self.db = Firestorage(configs['firebase_url'])

        self.machine = GraphMachine(
            model=self,
            states=["user", "postback", "nearby", "favorlist", "graph"],
            transitions=[
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "postback",
                    "conditions": "is_going_to_postback",
                },
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "nearby",
                    "conditions": "is_going_to_nearby",
                },
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "favorlist",
                    "conditions": "is_going_to_favorlist",
                },
                {
                    "trigger": "advance",
                    "source": "user",
                    "dest": "graph",
                    "conditions": "is_going_to_graph",
                },
                {
                    "trigger": "go_back",
                    "source": ["postback", "nearby", "favorlist", "graph"],
                    "dest": "user"
                },
            ],
            initial="user",
            auto_transitions=False,
            show_conditions=True,
        )

    def is_going_to_postback(self, event):
        return isinstance(event, PostbackEvent)

    def is_going_to_nearby(self, event):
        return isinstance(event,
                          MessageEvent) and event.message.type == "location"

    def is_going_to_favorlist(self, event):
        return isinstance(
            event, MessageEvent
        ) and event.message.type == "text" and event.message.text.lower(
        ) == "list"

    def is_going_to_graph(self, event):
        return isinstance(
            event, MessageEvent
        ) and event.message.type == "text" and event.message.text.lower(
        ) == "graph"

    def on_enter_postback(self, event):
        print("I'm entering postback")

        place_id = event.postback.data.split(',')[0]
        place_name = event.postback.data.split(',')[1]
        mode = event.postback.data.split(',')[2]

        reply_token = event.reply_token
        print(mode)

        if mode == "put":
            self.db.add_to_favorite(event.source.user_id, place_id)
            send_text_message(reply_token, f"已將「{place_name}」加到我的最愛")
        else:
            self.db.remove_from_favorite(event.source.user_id, place_id)
            send_text_message(reply_token, f"已將「{place_name}」從我的最愛移除")

        self.go_back()

    def on_enter_nearby(self, event):
        print("I'm entering nearby")

        reply_token = event.reply_token
        send_carousel(
            reply_token,
            self.gmap.get_info(event.message.latitude,
                               event.message.longitude))

        self.go_back()

    def on_enter_favorlist(self, event):
        print("I'm entering favorlist")

        favorites = self.db.get_user_favorite(event.source.user_id)
        carousel_list = [
            self.gmap.get_place_by_id(favorite) for favorite in favorites
        ]

        reply_token = event.reply_token
        send_carousel(reply_token, carousel_list, True)

        self.go_back()

    def on_enter_graph(self, event):
        reply_token = event.reply_token
        send_image_url(reply_token, self.base_url + '/show-fsm')
        self.go_back()

    def on_exit_postback(self):
        print("Leaving postback")

    def on_exit_nearby(self):
        print("Leaving nearby")

    def on_exit_favorlist(self):
        print("Leaving favorlist")

    def on_exit_graph(self):
        print("Leaving graph")
コード例 #8
0
from GoogleMaps import GoogleMaps
import urllib2
import json

g = GoogleMaps()

response = urllib2.urlopen(
    'http://devostrum.no-ip.info/lilo-backend/GetDestinations.php')
result = json.loads(response.read())

destinations = result['destinations']

prices = []

for line in open('bus-price-table.txt'):
    arr = line.split(' ')
    prices.append((float(arr[0]), float(arr[1]), float(arr[2][1:])))

matrix = [[0] * len(destinations) for _ in xrange(len(destinations))]

for i in range(len(destinations)):
    for j in range(len(destinations)):
        if i == j:
            matrix[i][j] = (0, 0, 0)
            continue
        distance = g.getDistanceDataBus(
            str(destinations[i]['lat']) + "," + str(destinations[i]['lon']),
            str(destinations[j]['lat']) + "," +
            str(destinations[j]['lon']))['rows'][0]['elements'][0]
        distVal = distance['distance']['value'] / 1000.0
        cost = 0.77
コード例 #9
0
ファイル: apitest.py プロジェクト: ashiswin/lilo-backend
from APIConnector import TaxiAPIConnector
from GoogleMaps import GoogleMaps
import urllib2
import json

a = TaxiAPIConnector()
g = GoogleMaps()

response = urllib2.urlopen(
    'http://devostrum.no-ip.info/lilo-backend/GetDestinations.php')
result = json.loads(response.read())

destinations = []

for d in result['destinations']:
    destinations.append((d['id'], a.searchAddress(d['lat'], d['lon'])))

matrix = [[0] * len(destinations) for _ in xrange(len(destinations))]

for i in range(len(destinations)):
    for j in range(len(destinations)):
        if i == j:
            matrix[i][j] = (0, 0, 0)
            continue
        distance = g.getDistanceData(
            str(destinations[i][1]['address']['addressLat']) + "," +
            str(destinations[i][1]['address']['addressLng']),
            str(destinations[j][1]['address']['addressLat']) + "," +
            str(destinations[j][1]['address']['addressLng'])
        )['rows'][0]['elements'][0]
        matrix[i][j] = (a.getTravelCost(destinations[i][1],
コード例 #10
0
ファイル: app.py プロジェクト: kevinwang97/HelpBot
def receive_and_respond():
    sender = request.values.get('From')

    logger.debug("[App] - Received request from " + sender)

    if request.values.get('Body') == None:
        logger.debug("[App] - Message was empty")
        return "No Message"

    request_body = request.values.get('Body').lower()

    message_parser = MessageParser()

    if request_body == 'commands':
        body = """
        To get directions:
        <method> directions from <origin> to <destination> <'depart at' or 'arrive by'> <when>
        """
    elif 'directions' in request_body:
        try:
            if request_body.strip() == 'directions':
                with conn.cursor() as curs:
                    curs.execute(
                        "SELECT last_gmaps_query FROM textinfo WHERE sender = %s",
                        (sender, ))
                    request_body = curs.fetchone()[0]
                    logger.debug("[app] - Google Mapsgit p last request: " +
                                 request_body)
                    if request_body is None:
                        raise BadMessage("No previous request")

            parameters = message_parser.parse_directions(request_body)
            logger.debug("[App] - Google Maps Parameters: " + str(parameters))
            gmaps = GoogleMaps(os.environ['GOOGLE_MAPS_API_KEY'])
            if parameters['time_modifier'].lower() == 'depart at':
                directions = gmaps.get_directions(
                    origin=parameters['origin'],
                    destination=parameters['destination'],
                    mode=parameters['mode'],
                    departure_time=parameters['time'])
            elif parameters['time_modifier'].lower() == 'arrive by':
                directions = gmaps.get_directions(
                    origin=parameters['origin'],
                    destination=parameters['destination'],
                    mode=parameters['mode'],
                    arrival_time=parameters['time'])
            body = str(directions)
            logger.debug("[App] - Google Maps Response: " + body)

            with conn.cursor() as curs:
                vals = {
                    "sender": sender,
                    "last_weather_query": "",
                    "last_gmaps_query": request_body
                }
                query = "INSERT INTO textinfo (sender, last_weather_query, last_gmaps_query) VALUES (%(sender)s, %(last_weather_query)s, %(last_gmaps_query)s) ON CONFLICT (sender) DO UPDATE SET last_gmaps_query = %(last_gmaps_query)s"
                curs.execute(query, vals)
                conn.commit()

        except Exception as e:
            logger.error("[App] - Google Maps Exception: " + str(e))
            body = "Please follow message format: <method> directions from <origin> to <destination> <'depart at' or 'arrive by'> <when>"

    elif 'weather' in request_body:
        try:
            if request_body.strip() == 'weather':
                with conn.cursor() as curs:
                    curs.execute(
                        "SELECT last_weather_query FROM textinfo WHERE sender = %s",
                        (sender, ))
                    request_body = curs.fetchone()[0]
                    logger.debug("[app] - Weather last request: " +
                                 request_body)
                    if request_body is None:
                        raise BadMessage("No previous request")

            weather_location = message_parser.parse_weather_string(
                request_body)
            logger.debug("[App] - Weather Location: " +
                         weather_location['location'])
            owm = pyowm.OWM(os.environ['WEATHER_API'])
            observation = owm.weather_at_place(weather_location['location'])
            weather = observation.get_weather()
            temperature = weather.get_temperature(unit='celsius')
            location = observation.get_location()
            body = "Currently, in {}, it is {} degrees ({} degrees - {} degrees) with {}.".format(
                location.get_name(), temperature['temp'],
                temperature['temp_min'], temperature['temp_max'],
                weather.get_detailed_status())

            with conn.cursor() as curs:
                vals = {
                    "sender": sender,
                    "last_weather_query": request_body,
                    "last_gmaps_query": ""
                }
                query = "INSERT INTO textinfo (sender, last_weather_query, last_gmaps_query) VALUES (%(sender)s, %(last_weather_query)s, %(last_gmaps_query)s) ON CONFLICT (sender) DO UPDATE SET last_weather_query = %(last_weather_query)s"
                curs.execute(query, vals)
                conn.commit()

        except Exception as e:
            logger.error("[App] - Weather: " + str(e))
            body = "Please follow message format: weather in <location>"

        logger.debug("[App] - Weather Response: " + body)

    else:
        body = "Invalid command. Text 'commands' for list of all commands"

    resp = twiml.Response()
    resp.message(body)
    return str(resp)
コード例 #11
0
ファイル: geotag.py プロジェクト: imolloy/gpx_geotagger
class GeoTagImage(object):
    """GeoTagImage Class"""
    def __init__(self, **kwargs):
        self.gpx_file = kwargs['gpx_file']
        self.verbose = kwargs['verbose']
        self.xmp = kwargs['xmp']
        self.hours = kwargs['hours']
        self.minutes = kwargs['minutes']
        self.seconds = kwargs['seconds']
        self.execute = kwargs['execute']
        self.exiftool = kwargs['exiftool']
        self.process_timestamps()
        self.files_read = 0
        self.files_tagged = 0
        self.GM = GoogleMaps(kwargs['maps'])
    
    def process_timestamps(self):
        """
        Inserts the timestamps from the GPX file into an SQLite DB
        Returns a cursor to the DB
        """
        self.conn = sqlite3.connect(':memory:')
        self.cursor = self.conn.cursor()
        self.cursor.execute('CREATE TABLE tracklog(dt PRIMARY KEY, lat REAL, lon REAL, elev REAL)')
        num_points = 0
        for d in gps.parse_gpx_iter(self.gpx_file):
            self.cursor.execute('INSERT INTO tracklog VALUES(?,?,?,?)', d)
            num_points += 1
        sys.stderr.write('The GPX file contained %d Points\n' % num_points)
        self.conn.commit()
    
    def nearest_time_sql(self, t):
        """
        Uses the Database to search for the nearest two points
        """
        if self.verbose:
            sys.stderr.write('SQL Time %s' % t)
        self.cursor.execute('SELECT * FROM tracklog WHERE dt <= ? ORDER BY dt DESC LIMIT 1', (t,))
        d = self.cursor.fetchone()
        if d != None:
            t0 = [datetime.strptime(d[0],'%Y-%m-%d %H:%M:%S')]
            t0.extend(d[1:])
        else:
            t0 = None
        self.cursor.fetchall()
        self.cursor.execute('SELECT * FROM tracklog WHERE dt >= ? ORDER BY dt LIMIT 1', (t,))
        d2 = self.cursor.fetchone()
        if d2 != None:
            t1 = [datetime.strptime(d2[0],'%Y-%m-%d %H:%M:%S')]
            t1.extend(d2[1:])
        else:
            t1 = None
        self.cursor.fetchall()
        if self.verbose:
            sys.stderr.write('SQL Resuls %s %s' % (t0,t1))
        if t0 == None or t1 == None:
            return None
        return t0,t1
    
    def interpolate(self, a, b, t):
        """
        Does the actual interpolation work between two points
        """
        d1 = (t - a[0]).seconds
        d2 = (b[0] - t).seconds
        # The total time difference
        d = float(d1 + d2)
        point = []
        # Need to return a (time, lat, lon, elev) point
        point.append(t)
        # Linear interpolation of the latitude, longitude, and elevation
        point.append(float(a[1])*(d2/d) + float(b[1])*(d1/d))
        point.append(float(a[2])*(d2/d) + float(b[2])*(d1/d))
        point.append(float(a[3])*(d2/d) + float(b[3])*(d1/d))
        if self.verbose:
            sys.stderr.write('Interpolate:\n')
            sys.stderr.write('\t%s\n' % repr(a))
            sys.stderr.write('\t%s\n' % repr(point))
            sys.stderr.write('\t%s\n' % repr(b))
        return point
    
    def interpolate_time(self, a, b, t, tolerance=100):
        """
        Calcultes the difference between two timestamps.
        If the difference is greater than a threshold, returns None
        Otherwise, interpolates the GPS Coordinates between the two points.
        """
        if self.verbose:
            sys.stderr.write('Interpolate:\t%s\t%s\t%s\n' % (a[0], t, b[0]))
        # First, ensure the timestamps are in fact correctly formatted
        assert(a[0].toordinal() <= t.toordinal())
        assert(b[0].toordinal() >= t.toordinal())
        # The difference in time between the two points
        delta = b[0] - a[0]
        if delta.seconds > tolerance:
            # We could interpolate, but the error is too large
            return None
        if delta.seconds == 0:
            # No need to interpolate
            return a
        # Otherwise, we need to interpolate the time
        return self.interpolate(a, b, t)
    
    def image_time(self, path_name, timezone='GMT', delta_hours=0, delta_minutes=0, delta_seconds=0):
        """
        Opens an image, and returns the timestamp from the EXIF tags
        offset by delta_hours, delta_minutes, and delta_seconds
        """
        # Open the file for reading
        f = open(path_name, 'r')
        # And extract the tags
        tags = EXIF.process_file(f)
        f.close()
        if len(tags) == 0 or 'Image DateTime' not in tags:
            return None
        capture_time = tags['Image DateTime']
        # Add the timezone the camera time is set to
        img_time = capture_time.printable + timezone
        # Parse the timestap
        cdt = datetime.strptime(img_time, '%Y:%m:%d %H:%M:%S%Z')
        # And process the offset for clock skew
        delta = timedelta(hours=delta_hours, minutes=delta_minutes, seconds=delta_seconds)
        cdt = cdt - delta
        self.files_read += 1
        return cdt
    
    def add_track(self, precision=0):
        self.cursor.execute('SELECT dt, lat, lon FROM tracklog ORDER BY dt')
        last_time = None
        for (dt, x, y) in self.cursor:
            dt = datetime.strptime(dt,'%Y-%m-%d %H:%M:%S')
            if last_time == None:
                last_time = dt
            elif dt -  last_time < timedelta(seconds=precision):
                continue
            last_time = dt
            self.GM.add_track(x, y)
    
    def correlate_timestamp(self, *args):
        # if os.isatty(1):
        #     pbar = progressbar.ProgressBar(len(args), widgets=[progressbar.ETA(), ' ', progressbar.Percentage(), ' ', progressbar.Bar()]).start()
        total_files = len(args)
        for i,path_name in enumerate(args):
            # if os.isatty(1):
            #     pbar.update(i)
            sys.stdout.write('%f\n' % (float(i)/total_files))
            if path_name[-len('_original'):] == '_original':
                continue
            img_time = self.image_time(path_name, delta_hours=self.hours, delta_minutes=self.minutes, delta_seconds=self.seconds)
            if img_time is None:
                if self.verbose:
                    sys.stderr.write('%s\n\tNo Time...Not an image?\n' % path_name)
                continue
            nearest = self.nearest_time_sql(img_time)
            if nearest is None:
                if self.verbose:
                    sys.stderr.write('%s\n\tSkipping. Not in range. %s\n' % (path_name, img_time))
                continue
            point = self.interpolate_time(nearest[0], nearest[1], img_time)
            if point == None:
                if self.verbose:
                    sys.stderr.write('%s\n\tSkipping. Too much time between data points.\n' % path_name)
                continue
            if self.verbose:
                sys.stderr.write('%s\n\tCapture:\t%s\n\tMatch:\t\t%s\n\tLocation:\t%f %f %0.3f\n' % (path_name, img_time, point[0], float(point[1]), float(point[2]), float(point[3])))
            cmd = [self.exiftool, path_name, '-GPSLatitude=%f' % float(point[1]), '-GPSLatitudeRef=N', '-GPSLongitude=%f' % float(point[2]), '-GPSLongitudeRef=W', '-GPSAltitude=%f' %  float(point[3])]
            if self.xmp:
                # xmp_file = '"%s.XMP"' % path_name[:path_name.rfind('.')]
                cmd.append('"%s.XMP"' % path_name[:path_name.rfind('.')])
            # else: xmp_file = ''
            # cmd = '%s "%s" -GPSLatitude=%f -GPSLatitudeRef=N -GPSLongitude=%f -GPSLongitudeRef=W -GPSAltitude=%f %s > /dev/null' % (self.exiftool, path_name, float(point[1]), float(point[2]), float(point[3]), xmp_file)
            self.GM.add_point(lat=point[1], lon=point[2], name=os.path.split(path_name)[1], time=img_time, exif=EXIF.process_file(open(path_name, 'r')))
            if self.execute:
                # retval = os.system(cmd)
                retval = subprocess.call(cmd)
                if retval != 0:
                    sys.stderr.write("Error Processing Last Command:\n\t%s\n" % cmd)
                else:
                    self.files_tagged += 1
        sys.stdout.write('1.0\n')
コード例 #12
0
ファイル: __init__.py プロジェクト: tokar86a/PokeAlarm
def location_service_factory(kind, api_key, locale, units):
    if kind == "GoogleMaps":
        return GoogleMaps(api_key, locale, units)
    else:
        raise ValueError("%s is not a valid location service!".format(kind))