Ejemplo n.º 1
0
 def fetch_routes(self, stop):
     params = {
         "filter[stop]": stop,
         "filter[type]": 2,
         "include": "stop",
     }
     routes, included = self.fetch(path="routes", params=params)
     return [Route(r) for r in routes], Stop(included[0])
Ejemplo n.º 2
0
 def __init__(self,fileName):
     self.__routes = []
     file = open(fileName,"r")
     lines = file.readlines()
     for line in lines:
         line = line.strip()
         line = line.split(',')
         self.__routes.append(Route(int(line[0]),int(line[1])))
     file.close()
Ejemplo n.º 3
0
    def post(self):
        """ User sends gold and route info to server.
        Request
            uid - user_id
            cid - channel_id
            data - message
        """
        data = json.loads(self.request.body)
        uid = data['uid']
        print uid
        cid = data['cid']
        print cid
        ucg = data['current_gold']
        print "The user's current gold is " + ucg
        r = data['route']
        print "The route is: " + r

        pointsList = r.split(";")
        ndb.GeoPoint()
        rid = uid + "-" + cid
        route = Route(route_id=rid, list_of_points=[])
        for i in range(len(pointsList)):
            lng = pointsList[i].split()[0]
            lat = pointsList[i].split()[1]
            route.list_of_points.append(ndb.GeoPoint(lng, lat))
        route.put()
        usid = uid + "-" + cid
        user_session = UserSession(user_session_id=usid, base_point="",
                                   drop_off_point="", user_current_gold=ucg, route_id=rid)
        user_session.put()
        # session = Session.query(Session.channel_id == cid).get()
        pubnub = Pubnub(publish_key=PUBLISH_KEY,
                        subscribe_key=SUBSCRIBE_KEY, ssl_on=False, uuid=str(uid))
        pubnub.subscribe(cid, callback)
        pubnub.publish(cid, uid + " has selected a route")
        response = {'user-session-id': usid}
        self.response.out.write(json.dumps(response))
Ejemplo n.º 4
0
 def get_route(self, id):
     try:
         with dbapi2.connect(self.url) as connection:
             cursor = connection.cursor()
             statement = "SELECT id, user_id, name, description, img_url FROM routes WHERE id = %s"
             data = [id]
             cursor.execute(statement, data)
             value = cursor.fetchone()
             cursor.close()
             if not value:
                 return None
             route = Route(value[0], value[1], value[2], value[3], value[4])
             return route
     except Exception as err:
         print("Get route error: ", err)
Ejemplo n.º 5
0
class Gmaps(object):
    def __init__(self):
        self.gmaps = googlemaps.Client(key=Secret.token())
        self.route_data = Route()
        self.formatter = MapFormatter()

    def lookup_travel_time(self, route_id):
        desired_route = self.route_data.get(route_id)
        now = int(time.time())

        map_data = self.gmaps.directions(
            alternatives=True,
            departure_time=now,
            destination=desired_route['destination'],
            mode='driving',
            origin=desired_route['origin'],
            units='imperial'
            )

        return self.formatter.format(content=map_data)
Ejemplo n.º 6
0
 def get_route():
     route_s = open('tests/data/route.json', 'r')
     route_j = json.load(route_s)
     route = Route()
     route.json2Obj(route_j)
     return route
Ejemplo n.º 7
0
from datetime import datetime, timedelta
from flask import Blueprint, Response
from models.route import Route
from models.timing import Timing

import json

route_data = Route()
routes_route = Blueprint('routes', __name__)

CACHE_LIFETIME = timedelta(minutes=5)
CACHE = {}


def check_cache(route_id):
    # nothing in cache
    if route_id not in CACHE:
        return None

    result = CACHE[route_id]

    # check expired value
    if datetime.now() > result['expire_time']:
        return None

    return result['data']


def save_cache(route_id, data):
    expire_time = datetime.now() + CACHE_LIFETIME
Ejemplo n.º 8
0
 def test_find_city_when_not_present(self):
     """Returns None when city is not present"""
     route_temp = Route()
     route_temp.start_address = "i live in austin"
     city_n_p = helper_functions.find_city(self.load_data(), route_temp)
     self.assertEqual(None, city_n_p)
Ejemplo n.º 9
0
def get_price_by_days(departure_date, start_point, end_points, transport_type, count_of_persons):
    # start_city_name = start_point
    id_to_name = {1: 'челябинск', 2: 'москва', 3: 'милан', 4: 'берлин', 5: 'рим', 6: 'сочи', 0: 'казань'}
    # try:
    #     resp = http.request('GET', URL_CITY + 'cities/{}'.format(start_point))
    #     LOGGER.info(resp.data)
    #
    #     start_city = json.loads(resp.data.decode('utf-8')).replace('\'', '"')
    #     # LOGGER.info(data)
    #     # data2 = json.loads(data)
    #     # data2 = json.loads(data)
    #     # print(data2['CityName'].lower())
    #     start_city = json.loads(start_city)
    #     if start_city:
    #         start_city_name = start_city['CityName'].lower()
    #     else:
    #         LOGGER.error('no city with such id')
    #         return None
    # except:
    #     LOGGER.error(traceback.format_exc())
    #     return None
    # end_city_names = {}
    # for point in end_points:
    #     try:
    #         res = http.request('GET', URL_CITY + 'cities/{}'.format(point))
    #         end_city = json.loads(res.data.decode('utf-8')).replace('\'', '"')
    #         end_city = json.loads(end_city)
    #         if end_city:
    #             end_city_names[end_city['CityName'].lower()] = point
    #         else:
    #             LOGGER.error('no city with such id')
    #             return None
    #     except:
    #         LOGGER.error(traceback.format_exc())
    #         return None
    # end_city_names = {}
    # for c in end_points:
    #     end_city_names[c] = c

    start_city_name = id_to_name[start_point]
    end_city_names = {}
    for i in end_points:
        end_city_names[id_to_name[i]] = i
    sql_select_start_point = 'select "Id" from "Cities" ' \
                             'where lower("Name") = %s'
    sql_select_end_points = 'select "Id", lower("Name") from "Cities" ' \
                            'where lower("Name") = %s '
    for i in range(len(end_city_names) - 1):
        sql_select_end_points += 'or lower("Name") = %s '
    with get_db_connection() as connection:
        with connection.cursor() as cursor:
            cursor.execute(sql_select_start_point, (start_city_name,))
            start_point_id = cursor.fetchone()[0]
            if not start_point:
                LOGGER.error('No such city in db')
                return None
            cursor.execute(sql_select_end_points, [k for k in end_city_names.keys()])
            end_points_data = cursor.fetchall()
            if not end_points_data:
                LOGGER.error('No such cities in db')
    print(start_point_id, end_points_data)
    sql_get_routes_by_end_point = 'select "Routes"."Id", "Routes"."Name", ' \
                                  '"Departure_Time", "Arrive_Time", "Price" ' \
                                  'from "Routes", "Types" ' \
                                  'where "Start_Point" = %s and "End_Point" = %s ' \
                                  'and "Types"."Id" = "Routes"."Transport_Type" ' \
                                  'and "Departure_Time"::date >= %s and "Departure_Time"::date <= %s ' \
                                  'and "Types"."Name" = %s and "Price" = (' \
                                  'select min("Price") from "Routes", "Types" ' \
                                  'where "Start_Point" = %s and "End_Point" = %s ' \
                                  'and "Types"."Id" = "Routes"."Transport_Type" ' \
                                  'and "Departure_Time"::date >= %s and "Departure_Time"::date <= %s ' \
                                  'and "Types"."Name" = %s)'
    routes_resp = []
    with get_db_connection() as connection:
        with connection.cursor() as cursor:
            for p in end_points_data:
                for t_type in transport_type:
                    query_params = [start_point_id, p[0], departure_date, departure_date, t_type]
                    cursor.execute(sql_get_routes_by_end_point, query_params + query_params)
                    route_data = cursor.fetchone()
                    if route_data:
                        routes_resp.append(Route(transport_id=route_data[0],
                                                 transport_type=t_type,
                                                 name=route_data[1],
                                                 start_point=start_point,
                                                 end_point=end_city_names[p[1]],
                                                 departure_time=int(route_data[2].timestamp()),
                                                 arrive_time=int(route_data[3].timestamp()),
                                                 price=route_data[4],
                                                 sits=None).to_dict())
                    else:
                        routes_resp.append(Route(transport_id=-1,
                                                 start_point=start_point,
                                                 end_point=end_city_names[p[1]],
                                                 transport_type=t_type).to_dict())
    return routes_resp
Ejemplo n.º 10
0
def get_transport_by_id(transport_id):
    """Find transport by ID

    Returns a single transport # noqa: E501

    :param transportId: ID of transport
    :type transportId: int

    :rtype: Route
    """
    sql_get_transport = 'select "Routes"."Id", "Types"."Name", "Routes"."Name", ' \
                        '"Start_Point", "End_Point", "Departure_Time", "Arrive_Time", "Price" ' \
                        'from "Routes", "Types" ' \
                        'where "Routes"."Id" = %s and "Routes"."Transport_Type" = "Types"."Id";'
    sql_get_cities = 'select lower("Name") from "Cities" where "Id" = %s or "Id" = %s'
    sql_get_sits = 'select "Transport_Id", "State", "Sit_Number" ' \
                   'from "Sits" where "Transport_Id" = %s'

    try:
        with get_db_connection() as connecton:
            with connecton.cursor() as cursor:
                cursor.execute(sql_get_transport, (transport_id,))
                route_data = cursor.fetchone()
                if not route_data:
                    LOGGER.error('Route not found')
                    return None
                cursor.execute(sql_get_cities, (route_data[3], route_data[4]))
                cities = cursor.fetchall()
                if not cities or len(cities) < 2:
                    LOGGER.error('Cities not found')
                    return None
                cursor.execute(sql_get_sits, (transport_id,))
                sits = cursor.fetchall()
                if not sits:
                    LOGGER.error('Sits not found')
                    return None
    except:
        LOGGER.error(traceback.format_exc())
        return None

    start_city = cities[0][0]
    end_city = cities[0][0]
    start_point = route_data[3]
    end_point = route_data[4]
    try:
        resp = http.request('POST', URL_CITY + 'cityitem',
                            body=json.dumps({'Name': start_city.title()}),
                            headers={'Content-type': 'application/json'})
        data = json.loads(resp.data)
        # data2 = json.loads(data)
        start_city = json.loads(data)
        if start_city and isinstance(start_city, list):
            start_point = start_city[0]['cityId']
        else:
            raise Exception
        resp = http.request('POST', URL_CITY + 'cityitem',
                            body=json.dumps({'Name': end_city.title()}),
                            headers={'Content-type': 'application/json'})
        data = json.loads(resp.data)
        end_city = json.loads(data)
        if end_city and isinstance(end_city, list):
            end_point = end_city[0]['cityId']
        else:
            raise Exception
    except:
        LOGGER.error(traceback.format_exc())
        return None

    sits_list = []
    for sit in sits:
        sits_list.append(Sit(state=sit[1],
                             sit_number=sit[2]))

    route = Route(transport_id=transport_id,
                  transport_type=route_data[1],
                  name=route_data[2],
                  start_point=start_point,
                  end_point=end_point,
                  departure_time=int(route_data[5].timestamp()),
                  arrive_time=int(route_data[6].timestamp()),
                  price=route_data[7],
                  sits=sits_list)
    return route.to_dict()
Ejemplo n.º 11
0
 def __init__(self):
     self.gmaps = googlemaps.Client(key=Secret.token())
     self.route_data = Route()
     self.formatter = MapFormatter()
Ejemplo n.º 12
0
def chromosome_to_routes(chromosome):
    routes = []
    aux_retailers = [(i, r.demand)
                     for i, r in enumerate(chromosome.gene_vans.ordered_nodes)
                     if r.demand > 0]

    for orig_idx, origin in enumerate(chromosome.gene_vans.origins):
        nodes = [origin]
        acc_cargo = 0
        while len(aux_retailers) > 0:
            current_index, current_demand = aux_retailers[0]
            del aux_retailers[0]

            if acc_cargo + current_demand < van.capacity:
                acc_cargo += current_demand
                nodes.append(chromosome.gene_vans.ordered_nodes[current_index])
                continue
            elif acc_cargo + current_demand == van.capacity:
                nodes.append(chromosome.gene_vans.ordered_nodes[current_index])
            else:
                delivered = van.capacity - acc_cargo
                nodes.append(chromosome.gene_vans.ordered_nodes[current_index])
                new_demand = current_demand - delivered
                new_element = current_index, new_demand
                insert_index = chromosome.gene_vans.offsets[orig_idx]
                if insert_index > len(aux_retailers):
                    insert_index = len(aux_retailers)
                aux_retailers.insert(insert_index, new_element)
            break

        new_route = Route(nodes, True)
        routes.append(new_route)

    aux_wholesales = []
    for i, wholesale in enumerate(chromosome.gene_trucks.ordered_nodes):
        demand = 0
        for r_idx, route in enumerate(routes):
            if route.origin == wholesale:
                if r_idx < len(routes) - 1:
                    demand += van.capacity
                else:
                    total_demand = sum(
                        map(lambda r: r.demand,
                            chromosome.gene_vans.ordered_nodes))
                    additional_demand = total_demand % van.capacity
                    if additional_demand == 0:
                        additional_demand = van.capacity
                    demand += additional_demand
        if demand > 0:
            new_element = i, demand
            aux_wholesales.append(new_element)

    for orig_idx, origin in enumerate(chromosome.gene_trucks.origins):
        nodes = [origin]
        acc_cargo = 0
        while len(aux_wholesales) > 0:
            current_index, current_demand = aux_wholesales[0]
            del aux_wholesales[0]

            if acc_cargo + current_demand < truck.capacity:
                acc_cargo += current_demand
                nodes.append(
                    chromosome.gene_trucks.ordered_nodes[current_index])
                continue

            elif acc_cargo + current_demand == truck.capacity:
                nodes.append(
                    chromosome.gene_trucks.ordered_nodes[current_index])
            else:
                delivered = truck.capacity - acc_cargo
                nodes.append(
                    chromosome.gene_trucks.ordered_nodes[current_index])
                new_demand = current_demand - delivered
                new_element = current_index, new_demand
                insert_index = chromosome.gene_trucks.offsets[orig_idx]
                if insert_index > len(aux_wholesales):
                    insert_index = len(aux_wholesales)
                aux_wholesales.insert(insert_index, new_element)
            break
        new_route = Route(nodes, False)
        routes.append(new_route)
    return routes
Ejemplo n.º 13
0
from models.route import Route

prefix = "/timeline"

index = Route.get(f"{prefix}/<string:ids>")
new_index = Route.get(f"{prefix}")


def custom_index(ids):
    return str(index.route_path).replace("<string:ids>", ids)