trying to get user location through IP - django

I am trying to locate a user through his/her IP address and then show them in a google map. what would be the best approach for this purpose. Or is there any other way to get the user lat/long and show em in a google map instead of IP address.

Your question is actually 2 questions. The first part is getting lat, lng from an ip address. AFAIK, google maps api doesnt provide for IP based geolocation. Therefore to show the IP address on a google map, you must first get the geographic location (either as an address, or as lat, lng). There are various paid and unpaid APIs on the web that allow you to do this, and django itself comes with a utility for this.
The docs are here. Your use case would be implemented as:
from django.contrib.gis.utils import GeoIP
g = GeoIP()
lat,lng = g.lat_lon(user_ip)
or
address = g.city(user_ip)
NOTE: This utility, or one of the many free IP based geolocation APIs might not be VERY accurate.
As for the second part, to show this location on a google map, you could check out this application:
http://code.google.com/p/django-googlemap/

You can use following, but I am not sure if this would work in all browsers.
if (navigator) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
do_something(position.coords.latitude, position.coords.longitude);
});
}
}

Locating a user would depend on the device you are targeting and granularity/accuracy with which you want to display his location on the map.
The ip address is more suited for laptops and other non-GPS devices. Secondly as you'd know, ip address will only pin point the user's gateway. In my case the gateway is about 8 miles from where I reside so you can imagine the accuracy is only suited for a certain class of apps such analysis tools like omniture or mixpanel.
On the other hand if you are developing your app for a mobile device you can start off reading about it in the question posed here. Using gps/agps will give you accuracy of within a few meters. This is more suited for LBS applications like gowalla or foursquare. HTML5 makes it easy for you to implement the latter especially if you are targeting iOS and Android devices.
Some off the cuff code in python is given below. Details of gmaps api v3 can be found here.
Server implementation in Python to record location and generate markers
class RecordLocation(webapp.RequestHandler):
def post(self):
session=SessionManager(self)
if session.is_set(): marker=Markers(lat=self.request.get('lat'),lon=self.request.get('lon'),user_id=self.request.get('user'))
marker.put()
self.response.out.write('<html><body>')
self.response.out.write(" Location Updated<br/>")
self.response.out.write('</body></html>')
class GenerateMarkers(webapp.RequestHandler):
def get(self):
session=SessionManager(self)
if session.is_set():
markers=db.GqlQuery("SELECT * FROM Markers")
doc='<?xml version="1.0"?>'
doc+='<markers>'
for marker in markers:
doc+='<marker '
doc+='lat="'+marker.lat+'" '
doc+='lon="'+marker.lon+'" '
doc+='type="restaurant" '
doc+='/>'
doc+='</markers>'
self.response.out.write(doc)

Related

How to provide autocomplete street addresses functionality in django?

Is there any way to provide automatic street address suggestion when user tries to enter their address in the input box using so they start getting automatic address suggestions in django.
I was searching autocomplete light but could not find specially anything related to that.
I've implemented this functionality with Google's Place Autocomplete. The sample code in the link is pretty spot on from memory.
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
You could use python to make the requests yourself and implement some light javascript to fill your inputs:
This will return you a list of predictions based on the input address you supply. You just need an address and your API key to run the query, but note in my example I'm using the components/types parameters as well.
here's the documentation: https://developers.google.com/maps/documentation/places/web-service/autocomplete
url = f'https://maps.googleapis.com/maps/api/place/autocomplete/json?input=<address>&components=country:us&types=address&key=<your key>'
r = requests.get(url)
predictions = r.json()['predictions']
for p in predictions:
print(p['description'])
print('-----------------------')

Geocoding multi-line street addresses (Address1 / Address2)

Our app's postal-address entry UI is a two-line Address1/Address2 field like this (borrowing screenshot from Amazon.com).
But real users' data entry is always messy. Some users will ignore our directions and will sometimes put the street address in Address1 and sometimes put it in Address2. Other users will import lists of addresses from external sources (like an existing mailing list), which will also likely cause some cases where the street address is unpredictably in Address1 or Address2.
When it comes time to geocode the address, what's a good algorithm to maximize the chance of successful geocoding if we're not sure whether the street address is in Address1 or Address2? A naive approach could be to try Address1, and if it fails then try Address2. But I'm sure I'm not the first person to try geo-coding real-world messy data entry... how is this problem usually solved?
We're using the Google Maps Geocoding API, if it matters.
I believe Google recommends using the autocomplete widget.
Have a look at the best practices document:
https://developers.google.com/maps/documentation/geocoding/best-practices
It says
Respond, in real time, to user input (includes ambiguous, incomplete, poorly formatted, or misspelled addresses entered by a user)
Use the Places API Place Autocomplete service to obtain a place ID, then the Geocoding API to geocode the place ID into a latlng.
Apartment, suite, unit etc. typically is not present in Google database. So you can bind the autocomplete to the first input where the user selects address and you can get corresponding place ID, the rest of information the user can enter in the second field which is not relevant for Google Geocoding API.
There are several examples of place autocomplete in the official documentation.
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
https://developers.google.com/maps/documentation/javascript/examples/places-placeid-geocoder
I hope this helps!

Connectwise REST API Implementation using python

In my application , I am going to use connectwise API , but I can't figure out how to call their API, like
How to connect
How to pass header (json data)
How to authentication (I have company id , public and private key)
How to make call and take response
I am Python guy
Thanks in advance
This question is quite broad, and you'll need to get familiar with something such as the Requests module if you aren't already.
Also, ConnectWise has a lot of documents at their developer site and registration is free and easy.
However I went through this journey myself over the last few weeks and learnt a lot so I'll share it with you.
Authentication
Authentication is done by creating an API user. In CW Manage you can create a member user with the API license class.
In ConnectWise Manage:
Go to System => Members
Go to the API Members tab.
Create a new API member that gives the API access to the areas that you need it, such as corporate/territorial levels. Note the username, amd that you cannot specify a password. Complete all the mandatory fields (owner ID, system default, group, approvers, etc).
When you have made this user go to the API keys tab. Enter a description for your new set of keys, and save it. When you do this you'll see the public and private keys once (and once only). Note them down.
Authorisation Header
In Python:
>>> import base64
>>> base64.b64encode("a+b:c")
...where a is your ConnectWise company name (what you type in in the login box), b is your public key, and c is your private key. This will return something which will be what you use to access the system. Copy it.
Making your first request
Now in Python make a new file and put this in it (this is quick and dirty but it should get you started):
import requests
cwToken = ""
# This is the ConnectWise access code generated earlier
cwUrl = "https://api-eu.myconnectwise.net/v4_6_release/apis/3.0/"
# check the URL matches your region, look at your CW Manage login box if not
cwHeaders = {"Authorization":"Basic " + cwToken,
"clientID":"<insertyoursecretClientIDhere>",
"Content-Type":"application/json"}
# this is your authorisation payload
try:
r = requests.get(cwUrl + "company/companies?pageSize=1000&conditions=type/id==1", headers=cwHeaders)
# request has been made
r.raise_for_status()
except:
print(r.text)
raise
companies = r.json()
The companies object now contains a list of your first 1,000 clients (type is ID 1 -- client). I've included an example of the conditions string because it took me a while to work out what it is and how to use it. But just take it off if you don't want the server to do your filtering for you.
You'll then be able to modify the above, or turn it into a module (which is what I did) to then make quick and portable calls, something like
cw.getCompanies()
which would simply return you a JSON object with all your companies in.
Going further
Study the documentation!! It is comprehensive enough to get you started. And the forums are actively monitored by staff (although they help mostly with C# queries and not scripting).
Just an update for 2020 since Daniel's response was incredibly helpful, but is missing a change Connectwise made in 2019 that now requires ClientIDs in order to auth.
Make a client ID here (scroll to bottom, although it's quick and useful to read all of it):
https://developer.connectwise.com/ClientID#What_is_a_clientId.3F
Daniel's code should then look like:
cwHeaders = {"Authorization":"Basic " + cwToken,
"clientID":"<insertyoursecretClientIDhere>",
"Content-Type":"application/json"}

Trying to get one cell to populate based off another cell's input.

having issues with this formula.
=(EXACT(E2;”Spoofing”);“Impersonates user or system to gain elevated privileges.”;"";IF(EXACT(E2;”Tampering”);”Integrity issues that can modify data or code or configuration files or DLL files.”;"";IF(EXACT(E2;”Repudiation”);”Something claims to have performed an action and did not”;"";IF(EXACT(E2;”Information Disclosure”);“Disclosure of sensitive information”;"";IF(EXACT(E2;”Denial of Service”);”Affects the availability of the network or server and causes the server or website to crash or send information anywhere.”;"";IF(EXACT(E2;”Elevation of Privilege”);”Authorization issue and gains access to a higher user like the Root password”;"";IF(EXACT(E2;”Parameter Manipulation”);”Parameters in URL or Web page form field data entered by a user are changed without that user's authorization.”;"";IF(EXACT(E2;”Cross-site Scripting”);”Exploits a vulnerability to place malicious code on a web server which then collects some type of data”;"";IF(EXACT(E2;”Buffer Overflow”);”Sends data to adjacent buffer in which codes can be executed”;""; IF(EXACT(E2;”SQL Injections”);”Attacker adds code to a Web form input box to gain access to resources or make changes to data.”;"";IF(EXACT(E2;”Password Guessing”);”Brute forcing or the use of a small executable file that keeps guessing randomly until it’s correct.”;"";IF(EXACT(E2;”IT Sabotage”);”Insider threat where the insider use of information technology to direct harm at an organization or individual”;"";IF(EXACT(E2;”Theft”);”Insider threat that uses the network and masks as a specific IP address to steal intellectual property or sensitive information.”;"";IF(EXACT(E2;”Fraud”);”Insider threat that uses the network for the unauthorized modification or addition or deletion of an organization’s data.”;"")))))))))))))
IF(EXACT(E2;”Tampering”); 'boolean value
”Integrity issues that can modify data or code or configuration files or DLL files.”; 'true case
""; 'false case
IF(EXACT(E2;”Repudiation”); 'SMH case
You have one too many arguments in each of the if functions you have.
Even if this could be solved I still highly recommend placing the matching values in a table and then using VLOOKUP to retrieve the description to the articles.

Bing geocoding web service bad results

I'm trying to use the Bing Geocoding web service in order to convert adresses to Location in order to add on the Bing WPF Control in my WinForm Application.
My problem is that somes adresses are correctly found by geocoding and some other adresses no !
If i search this adress directly on tha bing maps website it's found.
Here is my sample :
public static GeocodeResponse GetGeocodeResponse(string appId, string address)
{
GeocodeRequest geocodeRequest = new GeocodeRequest
{
Credentials = new Credentials {ApplicationId = appId},
Query = address
};
ConfidenceFilter[] filters = new ConfidenceFilter[1];
filters[0] = new ConfidenceFilter { MinimumConfidence = Confidence.High };
GeocodeOptions geocodeOptions = new GeocodeOptions { Filters = filters };
geocodeRequest.Options = geocodeOptions;
GeocodeServiceClient geocodeServiceClient = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
return geocodeServiceClient.Geocode(geocodeRequest);
}
Anyone have same tips in order to solve this ?
Thanks a lot :)
There are several possible things that can be causing this. The first is that you are using a basic or trial account and your requests are being rate limited. This occurs when the servers are under a lot of load or when you make a lot of requests at a frequency that would exceed the free terms of use. This is done to ensure that Enterprise accounts are not affected by the usage of basic or trial users. When rate limiting occurs a flag is added to the header of the response to indicate this:
You are using the old legacy Bing Maps SOAP service which has not been updated in over 4 years. It is generally not recommended to do any new development against those services as they are much slower, have less features and generally return less accurate results than the Bing Maps REST services. I would recommend moving over to the Bing Maps REST services. You can find documentation on how to use them in .NET here:
http://msdn.microsoft.com/en-us/library/ff701713.aspx
http://msdn.microsoft.com/en-us/library/jj819168.aspx
Also, take a look at this blog post:
http://rbrundritt.wordpress.com/2013/02/14/bing-maps-rest-service-tips-amp-tricks-2/
I also cover how to use the REST services in depth in my free eBook in Chapter 5:
http://rbrundritt.wordpress.com/my-book/