Exemplo n.º 1
0
def nearBins():
    list_of_bins = SmartBins.objects.filter(needs_to_be_collected=True)
    list_of_nbins = NormalBins.objects.all()
    Mode = "driving"  # "driving", "walking", "bicycling", "transit"
    password = ""
    lat = [15.384224]
    lng = [73.82342]
    # collec=Collector.objects.all()
    # c=collec[0]
    # lat.append(c.col_lat)
    # lng.append(lng[0])
    print(lat, lng)
    dist = []
    for k in list_of_bins:
        dist1 = haversine(lat[0], lng[0], k.latitude, k.longitude)
        print(dist1)
        if (dist1 < 15):
            lat.append(k.latitude)
            lng.append(k.longitude)
            dist.append(dist1)
    for h in list_of_nbins:
        dist2 = haversine(lat[0], lng[0], h.lat, h.lng)
        if (dist2 < 15):
            lat.append(h.lat)
            lng.append(h.lng)
            dist.append(dist2)
    lat = np.array(lat)
    lng = np.array(lng)
    lat = lat.astype(float)
    lng = lng.astype(float)
    print(dist)

    # calculate the dist_matrix
    # distance unit: meter
    gmaps = googlemaps.Client(key=password)
    dist_matrix = []
    places = len(lat)
    print(places)
    for i in range(places):
        for j in range(places):
            x = (lat[i], lng[i])
            y = (lat[j], lng[j])
            directions_result = gmaps.directions(x,
                                                 y,
                                                 mode=Mode,
                                                 avoid="ferries")
            dist_matrix.append(
                directions_result[0]['legs'][0]['distance']['value'])
    dist_matrix = np.reshape(dist_matrix, (places, places))
    # dist_matrix.astype(int)
    dist_matrix
    # convert the dist_matrix to a symmetrical matrix
    dist_matrix = np.asmatrix(dist_matrix)
    for i in range(0, places, 1):
        for j in range(i + 1, places, 1):
            dist_matrix[j, i] = dist_matrix[i, j]
    dist_matrix = np.asarray(dist_matrix)
    Index = main(places, dist_matrix, lat, lng)
    new_lat = [lat[0]]
    new_lng = [lng[0]]
    print(lat)
    print(lng)
    for i in range(places - 1):
        index = Index[i].astype(int)
        new_lat = np.append(new_lat, lat[index])
        new_lng = np.append(new_lng, lng[index])
    new_lat = np.append(new_lat, lat[0])
    new_lng = np.append(new_lng, lng[0])
    l = len(new_lat)
    # print(new_lat)
    # print(new_lng)
    data = {
        'result': [{
            "lat": new_lat[i],
            "long": new_lng[i]
        } for i in range(l)]
    }
    return str(data)
Exemplo n.º 2
0
# calculate the dist_matrix
# distance unit: meter

gmaps = googlemaps.Client(key=password)

dist_matrix = []
places = len(lat)

for i in range(places):
    for j in range(places):
        x = (lat[i], lng[i])
        y = (lat[j], lng[j])
        directions_result = gmaps.directions(
            x,
            y,
            mode=Mode,
            avoid="ferries",
        )
        dist_matrix.append(
            directions_result[0]['legs'][0]['distance']['value'])
dist_matrix = np.reshape(dist_matrix, (places, places))
# dist_matrix.astype(int)
dist_matrix

# convert the dist_matrix to a symmetrical matrix

dist_matrix = np.asmatrix(dist_matrix)

for i in range(0, places, 1):
    for j in range(i + 1, places, 1):
        dist_matrix[j, i] = dist_matrix[i, j]
Exemplo n.º 3
0
start = time.time()
shapefile = gpd.read_file('VegCover_MMB_GSR_2016.shp').to_crs(epsg=4326)
shapes = shapefile[['PerAnyVeg', 'geometry']]

heatshapefile = gpd.read_file('HVI_SA1_SUA_2016.shp').to_crs(epsg=4326)
# get the heat volunability index
heatshapes = heatshapefile[['HVI', 'geometry']]

print(time.time() - start)
# polygon_a = shapefile.geometry[0]
# polygon_a = Polygon([(151.113748,-33.893872),(151.113888,-33.891486),(151.115561,-33.891557),(151.115443,-33.893481)])
# print(polygon_a.intersects(polygon_b))

gmaps = googlemaps.Client(key='AIzaSyDVfZ9WzzPwKfQ3nudY6kELVgkaCK0cmJ4')
directions_result = gmaps.directions("Sydney Town Hall",
                                     "Sydney Central",
                                     mode="walking",
                                     alternatives=True)
results = directions_result[0]

start = time.time()
checked_points = set()
checked_heat_points = set()
print('finding shapes')
print(len(directions_result))
all_points = []
counts = []
counts_heat = []

# start_location_lat = directions_result[0]['legs']['start_location']['lat']
# start_location_lng = directions_result[0]['legs']['start_location']['lng']
#
Exemplo n.º 4
0
def abcd_abc():
    ### Get all the form data
    source = request.form['start']
    dest = request.form['end']

    now = datetime.now()
    t1 = datetime.now()
    ###Check if the same request exists in the databse
    if (mapdata.find_one({"startpos": source, "endpos": dest})):
        ###Obtain the request from the database and compare timestamp to present time
        ob_json = mapdata.find_one({"startpos": source, "endpos": dest})
        timediff = ob_json["uptimestamp"] - now
        time_diff_hours = timediff / timedelta(hours=1)
        ###If the same request has been made in less than 24 hours than return the database request
        if (time_diff_hours < 24):
            dir_json = ob_json["dir_json"]
        else:
            ### If the time is greater than 24 hours, update databse by making a new api call
            mapdata.delete_one({"startpos": source, "endpos": dest})
            dir_json = gmaps.directions(str(source),
                                        str(dest),
                                        mode="driving",
                                        departure_time=now)
            dir_json = dir_json[0]
            myparam = {
                "startpos": source,
                "endpos": dest,
                "uptimestamp": now,
                "dir_json": dir_json
            }
            result = mapdata.insert_one(myparam)

    else:
        ###If the request is not present in the databse then make a new call
        dir_json = gmaps.directions(str(source),
                                    str(dest),
                                    mode="driving",
                                    departure_time=now)
        dir_json = dir_json[0]
        myparam = {
            "startpos": source,
            "endpos": dest,
            "uptimestamp": now,
            "dir_json": dir_json
        }

        result = mapdata.insert_one(myparam)

    ###Extract polyline from the maps respose
    poly = dir_json['overview_polyline']['points']
    coordinates = polyline.decode(poly)

    ###Since the response contains a lot of latlong pairs only 8 equispaced points will be used
    ### Reducing the space
    neededlen = math.floor(len(coordinates) / 8)
    startcoord = coordinates[1]
    endcoord = coordinates[-1]
    counter = 1
    redcoord = []
    redcoord.append(startcoord)
    for coord in coordinates:
        if (counter % neededlen == 0):
            redcoord.append(coord)
        counter = counter + 1
    redcoord.append(endcoord)
    temparr = []
    tempplace = []

    ### Weather API hit by checking the databse
    for coord in redcoord:
        latdb = round(coord[0], 1)
        londb = round(coord[1], 1)
        ### If presesnt in database
        if (wedata.find_one({'lat': latdb, 'lon': londb})):
            we_json_temp = wedata.find_one({'lat': latdb, 'lon': londb})
            timediff = we_json_temp["uptimestamp"] - now
            time_diff_hours = timediff / timedelta(hours=1)
            ### If the response has been made in last 6 hours return databse response
            if (time_diff_hours < 6):
                temp = we_json_temp['temp']
                place_name = we_json_temp['name']
                temparr.append(temp)
                tempplace.append(place_name)
            else:
                ### Make new request and update in the databse
                wedata.delete_one({'lat': latdb, 'lon': londb})
                params = {
                    'lat': coord[0],
                    'lon': coord[1],
                    'appid': weatherapi
                }
                call = weathercall + urlencode(params)
                weather = requests.get(call).json()

                temp = weather['main']['temp']
                place_name = weather['name']
                temparr.append(temp)
                tempplace.append(place_name)

                myparams = {
                    "lat": latdb,
                    "lon": londb,
                    "name": place_name,
                    "temp": temp,
                    "uptimestamp": now
                }

                result = wedata.insert_one(myparams)

        else:
            ###Make new request and update in the databse
            params = {'lat': coord[0], 'lon': coord[1], 'appid': weatherapi}
            call = weathercall + urlencode(params)
            # return call
            weather = requests.get(call).json()

            temp = weather['main']['temp']
            place_name = weather['name']
            temparr.append(temp)
            tempplace.append(place_name)

            myparams = {
                "lat": latdb,
                "lon": londb,
                "name": place_name,
                "temp": temp,
                "uptimestamp": now
            }

            result = wedata.insert_one(myparams)

    check = "True"

    ###Update the entry in the databse
    myparams = {
        "source": source,
        "destination": dest,
        "place_name": tempplace,
        "temprature": temparr,
        "coordinates": redcoord,
        "reqtimestamp": now
    }
    result = arrreq.insert_one(myparams)

    t2 = datetime.now()
    cost = (t2 - t1).microseconds
    ### Pass all the variables to the frontend
    return render_template("index.html",
                           origin=source,
                           destination=dest,
                           temps=temparr,
                           places=tempplace,
                           coordarr=redcoord,
                           check=check,
                           serverjson=dir_json,
                           cost=cost)
Exemplo n.º 5
0
def hello_monkey():
    body = str(request.form['Body'])
    if body.lower() == 'pls dont do this I hate you':
        resp = twilio.twiml.Response()
        resp.message("We hate you too")
        return str(resp)
    else:
        write = True
        filename = 'whitelist.txt'
        fnumber = str(request.form['From'])
        tnumber = str(request.form['To'])
        incoming = str("To: " + tnumber + " From: " + fnumber + "\n")

        with open(filename) as f:
            for line in f:
                print incoming
                print line
                line = str(line)
                if line == incoming:
                    write = False

        if body.lower() == 'pls verify':
            phonelist = open(filename, 'a')
            phonelist.write("To: " + tnumber + " From: " + fnumber + "\n")
            phonelist.close()
            Popen([executable, 'quickstart.py'], creationflags=CREATE_NEW_CONSOLE)
            resp = twilio.twiml.Response()
            resp.message("You have been verified, you will now receive alerts for your Google Calendar events")
            return str(resp)
        if body.lower() == 'pls dont':
            resp = twilio.twiml.Response()
            resp.message("We will not verify you")
            return str(resp)

        if write == True:
            resp = twilio.twiml.Response()
            resp.message("You are not on our Whitelist would you like to Verify? Responses are 'pls verify' and 'pls dont' ")
            return str(resp)






        """Respond to incoming calls with a simple text message."""
        print body
        if write == False:
            if body.lower() == 'hello':
                resp = twilio.twiml.Response()
                resp.message("Nice you found an easter egg :), Hello to you!")
                return str(resp)
            if body.lower() == 'directions':
                resp = twilio.twiml.Response()
                resp.message("Text us     'S: #startlocation            D: #endlocation' and we will send directions")
                return str(resp)
            if 's:' in body.lower():
                startbegin = 's:'
                endbegin = 'd:'

                beginindex = body.lower().find(startbegin) + 2    ###getting locations out of text body
                endindex = body.lower().find(endbegin)
                startlocation = body[beginindex:endindex]
                endlocation = body[endindex+2:]

                directions = gmaps.directions(startlocation,endlocation)

                steps = len(directions)
                finaldir = ''
                for i in range(1,steps):
                    finaldir += '\n' + str(i) + ". " + directions[i] + '\n'
                resp = twilio.twiml.Response()
                resp.message(finaldir)
                return str(resp)
            else:
                resp = twilio.twiml.Response()
                resp.message("Sorry, we dont know what to say :(")
                return str(resp)
Exemplo n.º 6
0
def hello_monkey():
    body = str(request.form['Body'])
    if body.lower() == 'pls dont do this I hate you':
        resp = twilio.twiml.Response()
        resp.message("We hate you too")
        return str(resp)
    else:
        write = True
        filename = 'whitelist.txt'
        fnumber = str(request.form['From'])
        tnumber = str(request.form['To'])
        incoming = str("To: " + tnumber + " From: " + fnumber + "\n")

        with open(filename) as f:
            for line in f:
                print incoming
                print line
                line = str(line)
                if line == incoming:
                    write = False

        if body.lower() == 'pls verify':
            phonelist = open(filename, 'a')
            phonelist.write("To: " + tnumber + " From: " + fnumber + "\n")
            phonelist.close()
            Popen([executable, 'quickstart.py'],
                  creationflags=CREATE_NEW_CONSOLE)
            resp = twilio.twiml.Response()
            resp.message(
                "You have been verified, you will now receive alerts for your Google Calendar events"
            )
            return str(resp)
        if body.lower() == 'pls dont':
            resp = twilio.twiml.Response()
            resp.message("We will not verify you")
            return str(resp)

        if write == True:
            resp = twilio.twiml.Response()
            resp.message(
                "You are not on our Whitelist would you like to Verify? Responses are 'pls verify' and 'pls dont' "
            )
            return str(resp)
        """Respond to incoming calls with a simple text message."""
        print body
        if write == False:
            if body.lower() == 'hello':
                resp = twilio.twiml.Response()
                resp.message("Nice you found an easter egg :), Hello to you!")
                return str(resp)
            if body.lower() == 'directions':
                resp = twilio.twiml.Response()
                resp.message(
                    "Text us     'S: #startlocation            D: #endlocation' and we will send directions"
                )
                return str(resp)
            if 's:' in body.lower():
                startbegin = 's:'
                endbegin = 'd:'

                beginindex = body.lower().find(
                    startbegin) + 2  ###getting locations out of text body
                endindex = body.lower().find(endbegin)
                startlocation = body[beginindex:endindex]
                endlocation = body[endindex + 2:]

                directions = gmaps.directions(startlocation, endlocation)

                steps = len(directions)
                finaldir = ''
                for i in range(1, steps):
                    finaldir += '\n' + str(i) + ". " + directions[i] + '\n'
                resp = twilio.twiml.Response()
                resp.message(finaldir)
                return str(resp)
            else:
                resp = twilio.twiml.Response()
                resp.message("Sorry, we dont know what to say :(")
                return str(resp)