nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/location.py
Location.__repr__
(self)
return "Location(%s, (%s, %s, %s))" % ( self._address, self.latitude, self.longitude, self.altitude )
113
116
def __repr__(self): return "Location(%s, (%s, %s, %s))" % ( self._address, self.latitude, self.longitude, self.altitude )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/location.py#L113-L116
31
[ 0, 1 ]
50
[]
0
false
96.551724
4
1
100
0
def __repr__(self): return "Location(%s, (%s, %s, %s))" % ( self._address, self.latitude, self.longitude, self.altitude )
21,013
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/location.py
Location.__iter__
(self)
return iter(self._tuple)
118
119
def __iter__(self): return iter(self._tuple)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/location.py#L118-L119
31
[ 0, 1 ]
100
[]
0
true
96.551724
2
1
100
0
def __iter__(self): return iter(self._tuple)
21,014
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/location.py
Location.__getstate__
(self)
return self._address, self._point, self._raw
121
122
def __getstate__(self): return self._address, self._point, self._raw
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/location.py#L121-L122
31
[ 0, 1 ]
100
[]
0
true
96.551724
2
1
100
0
def __getstate__(self): return self._address, self._point, self._raw
21,015
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/location.py
Location.__setstate__
(self, state)
124
126
def __setstate__(self, state): self._address, self._point, self._raw = state self._tuple = _location_tuple(self)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/location.py#L124-L126
31
[ 0, 1, 2 ]
100
[]
0
true
96.551724
3
1
100
0
def __setstate__(self, state): self._address, self._point, self._raw = state self._tuple = _location_tuple(self)
21,016
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/location.py
Location.__eq__
(self, other)
return ( isinstance(other, Location) and self._address == other._address and self._point == other._point and self.raw == other.raw )
128
134
def __eq__(self, other): return ( isinstance(other, Location) and self._address == other._address and self._point == other._point and self.raw == other.raw )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/location.py#L128-L134
31
[ 0, 1 ]
28.571429
[]
0
false
96.551724
7
4
100
0
def __eq__(self, other): return ( isinstance(other, Location) and self._address == other._address and self._point == other._point and self.raw == other.raw )
21,017
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/location.py
Location.__ne__
(self, other)
return not (self == other)
136
137
def __ne__(self, other): return not (self == other)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/location.py#L136-L137
31
[ 0, 1 ]
100
[]
0
true
96.551724
2
1
100
0
def __ne__(self, other): return not (self == other)
21,018
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/location.py
Location.__len__
(self)
return len(self._tuple)
139
140
def __len__(self): return len(self._tuple)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/location.py#L139-L140
31
[ 0, 1 ]
100
[]
0
true
96.551724
2
1
100
0
def __len__(self): return len(self._tuple)
21,019
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu.__init__
( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, security_key=None )
:param str api_key: The API key (AK) required by Baidu Map to perform geocoding requests. API keys are managed through the Baidu APIs console (http://lbsyun.baidu.com/apiconsole/key). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str security_key: The security key (SK) to calculate the SN parameter in request if authentication setting requires (http://lbsyun.baidu.com/index.php?title=lbscloud/api/appendix).
32
86
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, security_key=None ): """ :param str api_key: The API key (AK) required by Baidu Map to perform geocoding requests. API keys are managed through the Baidu APIs console (http://lbsyun.baidu.com/apiconsole/key). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str security_key: The security key (SK) to calculate the SN parameter in request if authentication setting requires (http://lbsyun.baidu.com/index.php?title=lbscloud/api/appendix). """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.api = '%s://api.map.baidu.com%s' % (self.scheme, self.api_path) self.reverse_api = '%s://api.map.baidu.com%s' % (self.scheme, self.reverse_path) self.security_key = security_key
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L32-L86
31
[ 0 ]
1.818182
[ 43, 51, 52, 53, 54 ]
9.090909
false
23.913043
55
1
90.909091
28
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, security_key=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.api = '%s://api.map.baidu.com%s' % (self.scheme, self.api_path) self.reverse_api = '%s://api.map.baidu.com%s' % (self.scheme, self.reverse_path) self.security_key = security_key
21,020
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu._format_components_param
(self, components)
return "|".join( (":".join(item) for item in components.items()) )
Format the components dict to something Baidu understands.
Format the components dict to something Baidu understands.
88
94
def _format_components_param(self, components): """ Format the components dict to something Baidu understands. """ return "|".join( (":".join(item) for item in components.items()) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L88-L94
31
[ 0, 1, 2, 3 ]
57.142857
[ 4 ]
14.285714
false
23.913043
7
1
85.714286
1
def _format_components_param(self, components): return "|".join( (":".join(item) for item in components.items()) )
21,021
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
96
130
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'ak': self.api_key, 'output': 'json', 'address': query, } url = self._construct_url(self.api, self.api_path, params) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L96-L130
31
[ 0 ]
2.857143
[ 24, 30, 32, 33, 34 ]
14.285714
false
23.913043
35
1
85.714286
14
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = { 'ak': self.api_key, 'output': 'json', 'address': query, } url = self._construct_url(self.api, self.api_path, params) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,022
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu.reverse
(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL)
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. Baidu's API will always return at most one result. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
132
163
def reverse(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. Baidu's API will always return at most one result. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'ak': self.api_key, 'output': 'json', 'location': self._coerce_point_to_string(query), } url = self._construct_url(self.reverse_api, self.reverse_path, params) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L132-L163
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
65.625
[ 21, 27, 29, 30, 31 ]
15.625
false
23.913043
32
1
84.375
17
def reverse(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL): params = { 'ak': self.api_key, 'output': 'json', 'location': self._coerce_point_to_string(query), } url = self._construct_url(self.reverse_api, self.reverse_path, params) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,023
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu._parse_reverse_json
(self, page, exactly_one=True)
Parses a location from a single-result reverse API call.
Parses a location from a single-result reverse API call.
165
183
def _parse_reverse_json(self, page, exactly_one=True): """ Parses a location from a single-result reverse API call. """ place = page.get('result') if not place: self._check_status(page.get('status')) return None location = place.get('formatted_address').encode('utf-8') latitude = place['location']['lat'] longitude = place['location']['lng'] location = Location(location, (latitude, longitude), place) if exactly_one: return location else: return [location]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L165-L183
31
[ 0, 1, 2, 3 ]
21.052632
[ 4, 6, 7, 8, 10, 11, 12, 14, 15, 16, 18 ]
57.894737
false
23.913043
19
3
42.105263
1
def _parse_reverse_json(self, page, exactly_one=True): place = page.get('result') if not place: self._check_status(page.get('status')) return None location = place.get('formatted_address').encode('utf-8') latitude = place['location']['lat'] longitude = place['location']['lng'] location = Location(location, (latitude, longitude), place) if exactly_one: return location else: return [location]
21,024
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu._parse_json
(self, page, exactly_one=True)
Returns location, (latitude, longitude) from JSON feed.
Returns location, (latitude, longitude) from JSON feed.
185
208
def _parse_json(self, page, exactly_one=True): """ Returns location, (latitude, longitude) from JSON feed. """ place = page.get('result') if not place: self._check_status(page.get('status')) return None def parse_place(place): """ Get the location, lat, lng from a single JSON place. """ location = place.get('level') latitude = place['location']['lat'] longitude = place['location']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(place) else: return [parse_place(item) for item in place]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L185-L208
31
[ 0, 1, 2, 3, 4 ]
20.833333
[ 5, 7, 8, 9, 11, 15, 16, 17, 18, 20, 21, 23 ]
50
false
23.913043
24
5
50
1
def _parse_json(self, page, exactly_one=True): place = page.get('result') if not place: self._check_status(page.get('status')) return None def parse_place(place): location = place.get('level') latitude = place['location']['lat'] longitude = place['location']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(place) else: return [parse_place(item) for item in place]
21,025
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu._check_status
(self, status)
Validates error statuses.
Validates error statuses.
210
262
def _check_status(self, status): """ Validates error statuses. """ if status == 0: # When there are no results, just return. return if status == 1: raise GeocoderServiceError( 'Internal server error.' ) elif status == 2: raise GeocoderQueryError( 'Invalid request.' ) elif status == 3: raise GeocoderAuthenticationFailure( 'Authentication failure.' ) elif status == 4: raise GeocoderQuotaExceeded( 'Quota validate failure.' ) elif status == 5: raise GeocoderQueryError( 'AK Illegal or Not Exist.' ) elif status == 101: raise GeocoderAuthenticationFailure( 'No AK' ) elif status == 102: raise GeocoderAuthenticationFailure( 'MCODE Error' ) elif status == 200: raise GeocoderAuthenticationFailure( 'Invalid AK' ) elif status == 211: raise GeocoderAuthenticationFailure( 'Invalid SN' ) elif 200 <= status < 300: raise GeocoderAuthenticationFailure( 'Authentication Failure' ) elif 300 <= status < 500: raise GeocoderQuotaExceeded( 'Quota Error.' ) else: raise GeocoderQueryError('Unknown error. Status: %r' % status)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L210-L262
31
[ 0, 1, 2, 3 ]
7.54717
[ 4, 6, 7, 8, 11, 12, 15, 16, 19, 20, 23, 24, 27, 28, 31, 32, 35, 36, 39, 40, 43, 44, 47, 48, 52 ]
47.169811
false
23.913043
53
13
52.830189
1
def _check_status(self, status): if status == 0: # When there are no results, just return. return if status == 1: raise GeocoderServiceError( 'Internal server error.' ) elif status == 2: raise GeocoderQueryError( 'Invalid request.' ) elif status == 3: raise GeocoderAuthenticationFailure( 'Authentication failure.' ) elif status == 4: raise GeocoderQuotaExceeded( 'Quota validate failure.' ) elif status == 5: raise GeocoderQueryError( 'AK Illegal or Not Exist.' ) elif status == 101: raise GeocoderAuthenticationFailure( 'No AK' ) elif status == 102: raise GeocoderAuthenticationFailure( 'MCODE Error' ) elif status == 200: raise GeocoderAuthenticationFailure( 'Invalid AK' ) elif status == 211: raise GeocoderAuthenticationFailure( 'Invalid SN' ) elif 200 <= status < 300: raise GeocoderAuthenticationFailure( 'Authentication Failure' ) elif 300 <= status < 500: raise GeocoderQuotaExceeded( 'Quota Error.' ) else: raise GeocoderQueryError('Unknown error. Status: %r' % status)
21,026
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/baidu.py
Baidu._construct_url
(self, url, path, params)
264
272
def _construct_url(self, url, path, params): query_string = urlencode(params) if self.security_key is None: return "%s?%s" % (url, query_string) else: # http://lbsyun.baidu.com/index.php?title=lbscloud/api/appendix raw = "%s?%s%s" % (path, query_string, self.security_key) sn = hashlib.md5(quote_plus(raw).encode('utf-8')).hexdigest() return "%s?%s&sn=%s" % (url, query_string, sn)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/baidu.py#L264-L272
31
[ 0 ]
11.111111
[ 1, 2, 3, 6, 7, 8 ]
66.666667
false
23.913043
9
2
33.333333
0
def _construct_url(self, url, path, params): query_string = urlencode(params) if self.security_key is None: return "%s?%s" % (url, query_string) else: # http://lbsyun.baidu.com/index.php?title=lbscloud/api/appendix raw = "%s?%s%s" % (path, query_string, self.security_key) sn = hashlib.md5(quote_plus(raw).encode('utf-8')).hexdigest() return "%s?%s&sn=%s" % (url, query_string, sn)
21,027
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geocodeearth.py
GeocodeEarth.__init__
( self, api_key, *, domain='api.geocode.earth', timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: Geocode.earth API key, required. :param str domain: Specify a custom domain for Pelias API. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
:param str api_key: Geocode.earth API key, required.
18
66
def __init__( self, api_key, *, domain='api.geocode.earth', timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: Geocode.earth API key, required. :param str domain: Specify a custom domain for Pelias API. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( api_key=api_key, domain=domain, timeout=timeout, proxies=proxies, user_agent=user_agent, scheme=scheme, ssl_context=ssl_context, adapter_factory=adapter_factory, )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geocodeearth.py#L18-L66
31
[ 0 ]
2.040816
[ 39 ]
2.040816
false
83.333333
49
1
97.959184
24
def __init__( self, api_key, *, domain='api.geocode.earth', timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, scheme=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( api_key=api_key, domain=domain, timeout=timeout, proxies=proxies, user_agent=user_agent, scheme=scheme, ssl_context=ssl_context, adapter_factory=adapter_factory, )
21,028
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
_check_query
(query)
Check query validity with regex
Check query validity with regex
17
24
def _check_query(query): """ Check query validity with regex """ if not _MULTIPLE_WORD_RE.match(query): return False else: return True
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L17-L24
31
[ 0, 1, 2, 3, 4, 6, 7 ]
87.5
[ 5 ]
12.5
false
30.555556
8
2
87.5
1
def _check_query(query): if not _MULTIPLE_WORD_RE.match(query): return False else: return True
21,029
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3Words.__init__
( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: Key provided by What3Words (https://accounts.what3words.com/register). :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
40
85
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: Key provided by What3Words (https://accounts.what3words.com/register). :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme='https', timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'api.what3words.com' self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path) self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L40-L85
31
[ 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 ]
32.608696
[]
0
false
30.555556
46
1
100
20
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme='https', timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'api.what3words.com' self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path) self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path)
21,030
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3Words.geocode
( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown. :param str query: The 3-word address you wish to geocode. :param str lang: two character language code as supported by the API (https://docs.what3words.com/api/v2/#lang). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown.
87
134
def geocode( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown. :param str query: The 3-word address you wish to geocode. :param str lang: two character language code as supported by the API (https://docs.what3words.com/api/v2/#lang). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if not _check_query(query): raise exc.GeocoderQueryError( "Search string must be 'word.word.word'" ) params = { 'addr': query, 'lang': lang.lower(), 'key': self.api_key, } url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L87-L134
31
[ 0 ]
2.083333
[ 33, 34, 38, 44, 45, 46, 47 ]
14.583333
false
30.555556
48
2
85.416667
21
def geocode( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL ): if not _check_query(query): raise exc.GeocoderQueryError( "Search string must be 'word.word.word'" ) params = { 'addr': query, 'lang': lang.lower(), 'key': self.api_key, } url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,031
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3Words._parse_json
(self, resources, exactly_one=True)
Parse type, words, latitude, and longitude and language from a JSON response.
Parse type, words, latitude, and longitude and language from a JSON response.
136
173
def _parse_json(self, resources, exactly_one=True): """ Parse type, words, latitude, and longitude and language from a JSON response. """ code = resources['status'].get('code') if code: # https://docs.what3words.com/api/v2/#errors exc_msg = "Error returned by What3Words: %s" % resources['status']['message'] if code == 401: raise exc.GeocoderAuthenticationFailure(exc_msg) raise exc.GeocoderQueryError(exc_msg) def parse_resource(resource): """ Parse record. """ if 'geometry' in resource: words = resource['words'] position = resource['geometry'] latitude, longitude = position['lat'], position['lng'] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) else: raise exc.GeocoderParseError('Error parsing result.') location = parse_resource(resources) if exactly_one: return location else: return [location]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L136-L173
31
[ 0, 1, 2, 3, 4, 5 ]
15.789474
[ 6, 8, 10, 11, 12, 14, 16, 21, 22, 23, 24, 25, 26, 27, 29, 31, 33, 34, 35, 37 ]
52.631579
false
30.555556
38
8
47.368421
2
def _parse_json(self, resources, exactly_one=True): code = resources['status'].get('code') if code: # https://docs.what3words.com/api/v2/#errors exc_msg = "Error returned by What3Words: %s" % resources['status']['message'] if code == 401: raise exc.GeocoderAuthenticationFailure(exc_msg) raise exc.GeocoderQueryError(exc_msg) def parse_resource(resource): if 'geometry' in resource: words = resource['words'] position = resource['geometry'] latitude, longitude = position['lat'], position['lng'] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) else: raise exc.GeocoderParseError('Error parsing result.') location = parse_resource(resources) if exactly_one: return location else: return [location]
21,032
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3Words.reverse
( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response. :param query: The coordinates for which you wish to obtain the 3 word address. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str lang: two character language code as supported by the API (https://docs.what3words.com/api/v2/#lang). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response.
175
221
def reverse( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response. :param query: The coordinates for which you wish to obtain the 3 word address. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str lang: two character language code as supported by the API (https://docs.what3words.com/api/v2/#lang). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ lang = lang.lower() params = { 'coords': self._coerce_point_to_string(query), 'lang': lang.lower(), 'key': self.api_key, } url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L175-L221
31
[ 0 ]
2.12766
[ 34, 36, 42, 44, 45, 46 ]
12.765957
false
30.555556
47
1
87.234043
23
def reverse( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL ): lang = lang.lower() params = { 'coords': self._coerce_point_to_string(query), 'lang': lang.lower(), 'key': self.api_key, } url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,033
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3Words._parse_reverse_json
(self, resources, exactly_one=True)
return self._parse_json(resources, exactly_one)
Parses a location from a single-result reverse API call.
Parses a location from a single-result reverse API call.
223
227
def _parse_reverse_json(self, resources, exactly_one=True): """ Parses a location from a single-result reverse API call. """ return self._parse_json(resources, exactly_one)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L223-L227
31
[ 0, 1, 2, 3 ]
80
[ 4 ]
20
false
30.555556
5
1
80
1
def _parse_reverse_json(self, resources, exactly_one=True): return self._parse_json(resources, exactly_one)
21,034
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3WordsV3.__init__
( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: Key provided by What3Words (https://accounts.what3words.com/register). :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`.
242
285
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: Key provided by What3Words (https://accounts.what3words.com/register). :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. """ super().__init__( scheme='https', timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'api.what3words.com' self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path) self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L242-L285
31
[ 0 ]
2.272727
[ 31, 40, 41, 42, 43 ]
11.363636
false
30.555556
44
1
88.636364
18
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme='https', timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'api.what3words.com' self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path) self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path)
21,035
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3WordsV3.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown. :param str query: The 3-word address you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown.
287
329
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point for a `3 words` query. If the `3 words` address doesn't exist, a :class:`geopy.exc.GeocoderQueryError` exception will be thrown. :param str query: The 3-word address you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if not _check_query(query): raise exc.GeocoderQueryError( "Search string must be 'word.word.word'" ) params = { 'words': query, 'key': self.api_key, } url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L287-L329
31
[ 0 ]
2.325581
[ 29, 30, 34, 39, 40, 41, 42 ]
16.27907
false
30.555556
43
2
83.72093
18
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): if not _check_query(query): raise exc.GeocoderQueryError( "Search string must be 'word.word.word'" ) params = { 'words': query, 'key': self.api_key, } url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,036
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3WordsV3._parse_json
(self, resources, exactly_one=True)
Parse type, words, latitude, and longitude and language from a JSON response.
Parse type, words, latitude, and longitude and language from a JSON response.
331
369
def _parse_json(self, resources, exactly_one=True): """ Parse type, words, latitude, and longitude and language from a JSON response. """ error = resources.get('error') if error is not None: # https://developer.what3words.com/public-api/docs#error-handling exc_msg = "Error returned by What3Words: %s" % resources["error"]["message"] exc_code = error.get('code') if exc_code in ['MissingKey', 'InvalidKey']: raise exc.GeocoderAuthenticationFailure(exc_msg) raise exc.GeocoderQueryError(exc_msg) def parse_resource(resource): """ Parse record. """ if 'coordinates' in resource: words = resource['words'] position = resource['coordinates'] latitude, longitude = position['lat'], position['lng'] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) else: raise exc.GeocoderParseError('Error parsing result.') location = parse_resource(resources) if exactly_one: return location else: return [location]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L331-L369
31
[ 0, 1, 2, 3, 4, 5 ]
15.384615
[ 6, 8, 10, 11, 12, 13, 15, 17, 22, 23, 24, 25, 26, 27, 28, 30, 32, 34, 35, 36, 38 ]
53.846154
false
30.555556
39
8
46.153846
2
def _parse_json(self, resources, exactly_one=True): error = resources.get('error') if error is not None: # https://developer.what3words.com/public-api/docs#error-handling exc_msg = "Error returned by What3Words: %s" % resources["error"]["message"] exc_code = error.get('code') if exc_code in ['MissingKey', 'InvalidKey']: raise exc.GeocoderAuthenticationFailure(exc_msg) raise exc.GeocoderQueryError(exc_msg) def parse_resource(resource): if 'coordinates' in resource: words = resource['words'] position = resource['coordinates'] latitude, longitude = position['lat'], position['lng'] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(words, (latitude, longitude), resource) else: raise exc.GeocoderParseError('Error parsing result.') location = parse_resource(resources) if exactly_one: return location else: return [location]
21,037
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3WordsV3.reverse
( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response. :param query: The coordinates for which you wish to obtain the 3 word address. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str lang: two character language code as supported by the API (https://developer.what3words.com/public-api/docs#available-languages). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response.
371
417
def reverse( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a `3 words` address by location point. Each point on surface has a `3 words` address, so there's always a non-empty response. :param query: The coordinates for which you wish to obtain the 3 word address. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str lang: two character language code as supported by the API (https://developer.what3words.com/public-api/docs#available-languages). :param bool exactly_one: Return one result or a list of results, if available. Due to the address scheme there is always exactly one result for each `3 words` address, so this parameter is rather useless for this geocoder. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ lang = lang.lower() params = { 'coordinates': self._coerce_point_to_string(query), 'language': lang.lower(), 'key': self.api_key, } url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L371-L417
31
[ 0 ]
2.12766
[ 34, 36, 42, 44, 45, 46 ]
12.765957
false
30.555556
47
1
87.234043
23
def reverse( self, query, *, lang='en', exactly_one=True, timeout=DEFAULT_SENTINEL ): lang = lang.lower() params = { 'coordinates': self._coerce_point_to_string(query), 'language': lang.lower(), 'key': self.api_key, } url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,038
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/what3words.py
What3WordsV3._parse_reverse_json
(self, resources, exactly_one=True)
return self._parse_json(resources, exactly_one)
Parses a location from a single-result reverse API call.
Parses a location from a single-result reverse API call.
419
423
def _parse_reverse_json(self, resources, exactly_one=True): """ Parses a location from a single-result reverse API call. """ return self._parse_json(resources, exactly_one)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/what3words.py#L419-L423
31
[ 0, 1, 2, 3 ]
80
[ 4 ]
20
false
30.555556
5
1
80
1
def _parse_reverse_json(self, resources, exactly_one=True): return self._parse_json(resources, exactly_one)
21,039
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/openmapquest.py
OpenMapQuest.__init__
( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='open.mapquestapi.com', scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: API key provided by MapQuest, required. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Domain where the target Nominatim service is hosted. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
24
73
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='open.mapquestapi.com', scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: API key provided by MapQuest, required. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Domain where the target Nominatim service is hosted. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( timeout=timeout, proxies=proxies, domain=domain, scheme=scheme, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/openmapquest.py#L24-L73
31
[ 0, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 ]
24
[]
0
false
83.333333
50
1
100
25
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='open.mapquestapi.com', scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( timeout=timeout, proxies=proxies, domain=domain, scheme=scheme, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key
21,040
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/openmapquest.py
OpenMapQuest._construct_url
(self, base_api, params)
return super()._construct_url(base_api, params)
Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL.
Construct geocoding request url. Overridden.
75
87
def _construct_url(self, base_api, params): """ Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL. """ params['key'] = self.api_key return super()._construct_url(base_api, params)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/openmapquest.py#L75-L87
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
84.615385
[ 11, 12 ]
15.384615
false
83.333333
13
1
84.615385
8
def _construct_url(self, base_api, params): params['key'] = self.api_key return super()._construct_url(base_api, params)
21,041
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom.__init__
( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.tomtom.com' )
:param str api_key: TomTom API key. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: Domain where the target TomTom service is hosted.
:param str api_key: TomTom API key.
23
72
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.tomtom.com' ): """ :param str api_key: TomTom API key. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: Domain where the target TomTom service is hosted. """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.api = "%s://%s%s" % (self.scheme, domain, self.geocode_path) self.api_reverse = "%s://%s%s" % (self.scheme, domain, self.reverse_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L23-L72
31
[ 0 ]
2
[ 39, 47, 48, 49 ]
8
false
30.555556
50
1
92
25
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='api.tomtom.com' ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.api = "%s://%s%s" % (self.scheme, domain, self.geocode_path) self.api_reverse = "%s://%s%s" % (self.scheme, domain, self.reverse_path)
21,042
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, typeahead=False, language=None )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Maximum amount of results to return from the service. Unless exactly_one is set to False, limit will always be 1. :param bool typeahead: If the "typeahead" flag is set, the query will be interpreted as a partial input and the search will enter predictive mode. :param str language: Language in which search results should be returned. When data in specified language is not available for a specific field, default language is used. List of supported languages (case-insensitive): https://developer.tomtom.com/online-search/online-search-documentation/supported-languages :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
74
129
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, typeahead=False, language=None ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Maximum amount of results to return from the service. Unless exactly_one is set to False, limit will always be 1. :param bool typeahead: If the "typeahead" flag is set, the query will be interpreted as a partial input and the search will enter predictive mode. :param str language: Language in which search results should be returned. When data in specified language is not available for a specific field, default language is used. List of supported languages (case-insensitive): https://developer.tomtom.com/online-search/online-search-documentation/supported-languages :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = self._geocode_params(query) params['typeahead'] = self._boolean_value(typeahead) if limit: params['limit'] = str(int(limit)) if exactly_one: params['limit'] = '1' if language: params['language'] = language quoted_query = quote(query.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L74-L129
31
[ 0 ]
1.785714
[ 39, 40, 42, 43, 44, 45, 47, 48, 50, 51, 53, 54, 55 ]
23.214286
false
30.555556
56
4
76.785714
27
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, typeahead=False, language=None ): params = self._geocode_params(query) params['typeahead'] = self._boolean_value(typeahead) if limit: params['limit'] = str(int(limit)) if exactly_one: params['limit'] = '1' if language: params['language'] = language quoted_query = quote(query.encode('utf-8')) url = "?".join((self.api % dict(query=quoted_query), urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,043
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Language in which search results should be returned. When data in specified language is not available for a specific field, default language is used. List of supported languages (case-insensitive): https://developer.tomtom.com/online-search/online-search-documentation/supported-languages :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
131
175
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Language in which search results should be returned. When data in specified language is not available for a specific field, default language is used. List of supported languages (case-insensitive): https://developer.tomtom.com/online-search/online-search-documentation/supported-languages :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ position = self._coerce_point_to_string(query) params = self._reverse_params(position) if language: params['language'] = language quoted_position = quote(position.encode('utf-8')) url = "?".join((self.api_reverse % dict(position=quoted_position), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L131-L175
31
[ 0 ]
2.222222
[ 33, 34, 36, 37, 39, 40, 42, 43, 44 ]
20
false
30.555556
45
2
80
23
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None ): position = self._coerce_point_to_string(query) params = self._reverse_params(position) if language: params['language'] = language quoted_position = quote(position.encode('utf-8')) url = "?".join((self.api_reverse % dict(position=quoted_position), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,044
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._boolean_value
(self, bool_value)
return 'true' if bool_value else 'false'
177
178
def _boolean_value(self, bool_value): return 'true' if bool_value else 'false'
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L177-L178
31
[ 0 ]
50
[ 1 ]
50
false
30.555556
2
1
50
0
def _boolean_value(self, bool_value): return 'true' if bool_value else 'false'
21,045
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._geocode_params
(self, formatted_query)
return { 'key': self.api_key, }
180
183
def _geocode_params(self, formatted_query): return { 'key': self.api_key, }
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L180-L183
31
[ 0 ]
25
[ 1 ]
25
false
30.555556
4
1
75
0
def _geocode_params(self, formatted_query): return { 'key': self.api_key, }
21,046
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._reverse_params
(self, position)
return { 'key': self.api_key, }
185
188
def _reverse_params(self, position): return { 'key': self.api_key, }
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L185-L188
31
[ 0 ]
25
[ 1 ]
25
false
30.555556
4
1
75
0
def _reverse_params(self, position): return { 'key': self.api_key, }
21,047
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._parse_json
(self, resources, exactly_one)
190
198
def _parse_json(self, resources, exactly_one): if not resources or not resources['results']: return None if exactly_one: return self._parse_search_result(resources['results'][0]) else: return [self._parse_search_result(result) for result in resources['results']]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L190-L198
31
[ 0 ]
11.111111
[ 1, 2, 4, 5, 7 ]
55.555556
false
30.555556
9
5
44.444444
0
def _parse_json(self, resources, exactly_one): if not resources or not resources['results']: return None if exactly_one: return self._parse_search_result(resources['results'][0]) else: return [self._parse_search_result(result) for result in resources['results']]
21,048
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._parse_search_result
(self, result)
return Location(result['address']['freeformAddress'], (latitude, longitude), result)
200
204
def _parse_search_result(self, result): latitude = result['position']['lat'] longitude = result['position']['lon'] return Location(result['address']['freeformAddress'], (latitude, longitude), result)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L200-L204
31
[ 0 ]
20
[ 1, 2, 3 ]
60
false
30.555556
5
1
40
0
def _parse_search_result(self, result): latitude = result['position']['lat'] longitude = result['position']['lon'] return Location(result['address']['freeformAddress'], (latitude, longitude), result)
21,049
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._parse_reverse_json
(self, resources, exactly_one)
206
214
def _parse_reverse_json(self, resources, exactly_one): if not resources or not resources['addresses']: return None if exactly_one: return self._parse_reverse_result(resources['addresses'][0]) else: return [self._parse_reverse_result(result) for result in resources['addresses']]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L206-L214
31
[ 0 ]
11.111111
[ 1, 2, 4, 5, 7 ]
55.555556
false
30.555556
9
5
44.444444
0
def _parse_reverse_json(self, resources, exactly_one): if not resources or not resources['addresses']: return None if exactly_one: return self._parse_reverse_result(resources['addresses'][0]) else: return [self._parse_reverse_result(result) for result in resources['addresses']]
21,050
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._parse_reverse_result
(self, result)
return Location(result['address']['freeformAddress'], (latitude, longitude), result)
216
219
def _parse_reverse_result(self, result): latitude, longitude = result['position'].split(',') return Location(result['address']['freeformAddress'], (latitude, longitude), result)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L216-L219
31
[ 0 ]
25
[ 1, 2 ]
50
false
30.555556
4
1
50
0
def _parse_reverse_result(self, result): latitude, longitude = result['position'].split(',') return Location(result['address']['freeformAddress'], (latitude, longitude), result)
21,051
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/tomtom.py
TomTom._geocoder_exception_handler
(self, error)
221
227
def _geocoder_exception_handler(self, error): if not isinstance(error, AdapterHTTPError): return if error.status_code is None or error.text is None: return if error.status_code >= 400 and "Developer Over Qps" in error.text: raise GeocoderQuotaExceeded("Developer Over Qps") from error
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/tomtom.py#L221-L227
31
[ 0 ]
14.285714
[ 1, 2, 3, 4, 5, 6 ]
85.714286
false
30.555556
7
6
14.285714
0
def _geocoder_exception_handler(self, error): if not isinstance(error, AdapterHTTPError): return if error.status_code is None or error.text is None: return if error.status_code >= 400 and "Developer Over Qps" in error.text: raise GeocoderQuotaExceeded("Developer Over Qps") from error
21,052
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3.__init__
( self, api_key=None, *, domain='maps.googleapis.com', scheme=None, client_id=None, secret_key=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, channel='' )
:param str api_key: The API key required by Google to perform geocoding requests, mandatory (unless premier is used, then both ``client_id`` and ``secret_key`` must be specified instead). API keys are managed through the Google APIs console (https://code.google.com/apis/console). Make sure to have both ``Geocoding API`` and ``Time Zone API`` services enabled for this API key. .. versionchanged:: 2.1 Previously a warning has been emitted when neither ``api_key`` nor premier were specified. Now a :class:`geopy.exc.ConfigurationError` is raised. :param str domain: Should be the localized Google Maps domain to connect to. The default is 'maps.googleapis.com', but if you're geocoding address in the UK (for example), you may want to set it to 'maps.google.co.uk' to properly bias results. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str client_id: If using premier, the account client id. :param str secret_key: If using premier, the account secret key. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str channel: If using premier, the channel identifier.
38
131
def __init__( self, api_key=None, *, domain='maps.googleapis.com', scheme=None, client_id=None, secret_key=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, channel='' ): """ :param str api_key: The API key required by Google to perform geocoding requests, mandatory (unless premier is used, then both ``client_id`` and ``secret_key`` must be specified instead). API keys are managed through the Google APIs console (https://code.google.com/apis/console). Make sure to have both ``Geocoding API`` and ``Time Zone API`` services enabled for this API key. .. versionchanged:: 2.1 Previously a warning has been emitted when neither ``api_key`` nor premier were specified. Now a :class:`geopy.exc.ConfigurationError` is raised. :param str domain: Should be the localized Google Maps domain to connect to. The default is 'maps.googleapis.com', but if you're geocoding address in the UK (for example), you may want to set it to 'maps.google.co.uk' to properly bias results. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str client_id: If using premier, the account client id. :param str secret_key: If using premier, the account secret key. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str channel: If using premier, the channel identifier. """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) if client_id and not secret_key: raise ConfigurationError('Must provide secret_key with client_id.') if secret_key and not client_id: raise ConfigurationError('Must provide client_id with secret_key.') self.premier = bool(client_id and secret_key) self.client_id = client_id self.secret_key = secret_key if not self.premier and not api_key: raise ConfigurationError( 'Since July 2018 Google requires each request to have an API key. ' 'Pass a valid `api_key` to GoogleV3 geocoder to fix this error. ' 'See https://developers.google.com/maps/documentation/geocoding/usage-and-billing' # noqa ) self.api_key = api_key self.domain = domain.strip('/') self.channel = channel self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path) self.tz_api = '%s://%s%s' % (self.scheme, self.domain, self.timezone_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L38-L131
31
[ 0 ]
1.06383
[ 63, 71, 72, 73, 74, 76, 77, 78, 80, 81, 87, 88, 90, 92, 93 ]
15.957447
false
19.42446
94
8
84.042553
45
def __init__( self, api_key=None, *, domain='maps.googleapis.com', scheme=None, client_id=None, secret_key=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, channel='' ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) if client_id and not secret_key: raise ConfigurationError('Must provide secret_key with client_id.') if secret_key and not client_id: raise ConfigurationError('Must provide client_id with secret_key.') self.premier = bool(client_id and secret_key) self.client_id = client_id self.secret_key = secret_key if not self.premier and not api_key: raise ConfigurationError( 'Since July 2018 Google requires each request to have an API key. ' 'Pass a valid `api_key` to GoogleV3 geocoder to fix this error. ' 'See https://developers.google.com/maps/documentation/geocoding/usage-and-billing' # noqa ) self.api_key = api_key self.domain = domain.strip('/') self.channel = channel self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path) self.tz_api = '%s://%s%s' % (self.scheme, self.domain, self.timezone_path)
21,053
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3._get_signed_url
(self, params)
return '%s://%s%s&signature=%s' % ( self.scheme, self.domain, path, signature )
Returns a Premier account signed url. Docs on signature: https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures
Returns a Premier account signed url. Docs on signature: https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures
133
154
def _get_signed_url(self, params): """ Returns a Premier account signed url. Docs on signature: https://developers.google.com/maps/documentation/business/webservices/auth#digital_signatures """ params['client'] = self.client_id if self.channel: params['channel'] = self.channel path = "?".join((self.api_path, urlencode(params))) signature = hmac.new( base64.urlsafe_b64decode(self.secret_key), path.encode('utf-8'), hashlib.sha1 ) signature = base64.urlsafe_b64encode( signature.digest() ).decode('utf-8') return '%s://%s%s&signature=%s' % ( self.scheme, self.domain, path, signature )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L133-L154
31
[ 0, 1, 2, 3, 4 ]
22.727273
[ 5, 7, 8, 10, 11, 16, 19 ]
31.818182
false
19.42446
22
2
68.181818
2
def _get_signed_url(self, params): params['client'] = self.client_id if self.channel: params['channel'] = self.channel path = "?".join((self.api_path, urlencode(params))) signature = hmac.new( base64.urlsafe_b64decode(self.secret_key), path.encode('utf-8'), hashlib.sha1 ) signature = base64.urlsafe_b64encode( signature.digest() ).decode('utf-8') return '%s://%s%s&signature=%s' % ( self.scheme, self.domain, path, signature )
21,054
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3._format_components_param
(self, components)
return "|".join( ":".join(item) for item in component_items )
Format the components dict to something Google understands.
Format the components dict to something Google understands.
156
175
def _format_components_param(self, components): """ Format the components dict to something Google understands. """ component_items = [] if isinstance(components, collections.abc.Mapping): component_items = components.items() elif ( isinstance(components, collections.abc.Sequence) and not isinstance(components, (str, bytes)) ): component_items = components else: raise ValueError( '`components` parameter must be of type `dict` or `list`') return "|".join( ":".join(item) for item in component_items )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L156-L175
31
[ 0, 1, 2, 3 ]
20
[ 4, 6, 7, 8, 12, 14, 17 ]
35
false
19.42446
20
4
65
1
def _format_components_param(self, components): component_items = [] if isinstance(components, collections.abc.Mapping): component_items = components.items() elif ( isinstance(components, collections.abc.Sequence) and not isinstance(components, (str, bytes)) ): component_items = components else: raise ValueError( '`components` parameter must be of type `dict` or `list`') return "|".join( ":".join(item) for item in component_items )
21,055
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3.geocode
( self, query=None, *, exactly_one=True, timeout=DEFAULT_SENTINEL, bounds=None, region=None, components=None, place_id=None, language=None, sensor=False )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. Optional, if ``components`` param is set:: >>> g.geocode(components={"city": "Paris", "country": "FR"}) Location(France, (46.227638, 2.213749, 0.0)) :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :type bounds: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param bounds: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :param str region: The region code, specified as a ccTLD ("top-level domain") two-character value. :type components: dict or list :param components: Restricts to an area. Can use any combination of: `route`, `locality`, `administrative_area`, `postal_code`, `country`. Pass a list of tuples if you want to specify multiple components of the same type, e.g.: >>> [('administrative_area', 'VA'), ('administrative_area', 'Arlington')] :param str place_id: Retrieve a Location using a Place ID. Cannot be not used with ``query`` or ``bounds`` parameters. >>> g.geocode(place_id='ChIJOcfP0Iq2j4ARDrXUa7ZWs34') :param str language: The language in which to return results. :param bool sensor: Whether the geocoding request comes from a device with a location sensor. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
177
276
def geocode( self, query=None, *, exactly_one=True, timeout=DEFAULT_SENTINEL, bounds=None, region=None, components=None, place_id=None, language=None, sensor=False ): """ Return a location point by address. :param str query: The address or query you wish to geocode. Optional, if ``components`` param is set:: >>> g.geocode(components={"city": "Paris", "country": "FR"}) Location(France, (46.227638, 2.213749, 0.0)) :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :type bounds: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param bounds: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :param str region: The region code, specified as a ccTLD ("top-level domain") two-character value. :type components: dict or list :param components: Restricts to an area. Can use any combination of: `route`, `locality`, `administrative_area`, `postal_code`, `country`. Pass a list of tuples if you want to specify multiple components of the same type, e.g.: >>> [('administrative_area', 'VA'), ('administrative_area', 'Arlington')] :param str place_id: Retrieve a Location using a Place ID. Cannot be not used with ``query`` or ``bounds`` parameters. >>> g.geocode(place_id='ChIJOcfP0Iq2j4ARDrXUa7ZWs34') :param str language: The language in which to return results. :param bool sensor: Whether the geocoding request comes from a device with a location sensor. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'sensor': str(sensor).lower() } if place_id and (bounds or query): raise ValueError( 'Only one of the `query` or `place id` or `bounds` ' ' parameters must be entered.') if place_id is not None: params['place_id'] = place_id if query is not None: params['address'] = query if query is None and place_id is None and not components: raise ValueError('Either `query` or `components` or `place_id` ' 'must be set.') if self.api_key: params['key'] = self.api_key if bounds: params['bounds'] = self._format_bounding_box( bounds, "%(lat1)s,%(lon1)s|%(lat2)s,%(lon2)s") if region: params['region'] = region if components: params['components'] = self._format_components_param(components) if language: params['language'] = language if self.premier: url = self._get_signed_url(params) else: url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L177-L276
31
[ 0 ]
1
[ 62, 65, 66, 70, 71, 73, 74, 76, 77, 80, 81, 82, 83, 85, 86, 87, 88, 89, 90, 92, 93, 95, 97, 98, 99 ]
25
false
19.42446
100
15
75
47
def geocode( self, query=None, *, exactly_one=True, timeout=DEFAULT_SENTINEL, bounds=None, region=None, components=None, place_id=None, language=None, sensor=False ): params = { 'sensor': str(sensor).lower() } if place_id and (bounds or query): raise ValueError( 'Only one of the `query` or `place id` or `bounds` ' ' parameters must be entered.') if place_id is not None: params['place_id'] = place_id if query is not None: params['address'] = query if query is None and place_id is None and not components: raise ValueError('Either `query` or `components` or `place_id` ' 'must be set.') if self.api_key: params['key'] = self.api_key if bounds: params['bounds'] = self._format_bounding_box( bounds, "%(lat1)s,%(lon1)s|%(lat2)s,%(lon2)s") if region: params['region'] = region if components: params['components'] = self._format_components_param(components) if language: params['language'] = language if self.premier: url = self._get_signed_url(params) else: url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,056
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None, sensor=False )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: The language in which to return results. :param bool sensor: Whether the geocoding request comes from a device with a location sensor. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
278
328
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None, sensor=False ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: The language in which to return results. :param bool sensor: Whether the geocoding request comes from a device with a location sensor. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'latlng': self._coerce_point_to_string(query), 'sensor': str(sensor).lower() } if language: params['language'] = language if self.api_key: params['key'] = self.api_key if not self.premier: url = "?".join((self.api, urlencode(params))) else: url = self._get_signed_url(params) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L278-L328
31
[ 0 ]
1.960784
[ 34, 38, 39, 40, 41, 43, 44, 46, 48, 49, 50 ]
21.568627
false
19.42446
51
4
78.431373
22
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=None, sensor=False ): params = { 'latlng': self._coerce_point_to_string(query), 'sensor': str(sensor).lower() } if language: params['language'] = language if self.api_key: params['key'] = self.api_key if not self.premier: url = "?".join((self.api, urlencode(params))) else: url = self._get_signed_url(params) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,057
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3.reverse_timezone
(self, query, *, at_time=None, timeout=DEFAULT_SENTINEL)
return self._call_geocoder(url, self._parse_json_timezone, timeout=timeout)
Find the timezone a point in `query` was in for a specified `at_time`. `None` will be returned for points without an assigned Olson timezone id (e.g. for Antarctica). :param query: The coordinates for which you want a timezone. :type query: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param at_time: The time at which you want the timezone of this location. This is optional, and defaults to the time that the function is called in UTC. Timezone-aware datetimes are correctly handled and naive datetimes are silently treated as UTC. :type at_time: :class:`datetime.datetime` or None :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None`` or :class:`geopy.timezone.Timezone`.
Find the timezone a point in `query` was in for a specified `at_time`.
330
369
def reverse_timezone(self, query, *, at_time=None, timeout=DEFAULT_SENTINEL): """ Find the timezone a point in `query` was in for a specified `at_time`. `None` will be returned for points without an assigned Olson timezone id (e.g. for Antarctica). :param query: The coordinates for which you want a timezone. :type query: :class:`geopy.point.Point`, list or tuple of (latitude, longitude), or string as "%(latitude)s, %(longitude)s" :param at_time: The time at which you want the timezone of this location. This is optional, and defaults to the time that the function is called in UTC. Timezone-aware datetimes are correctly handled and naive datetimes are silently treated as UTC. :type at_time: :class:`datetime.datetime` or None :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None`` or :class:`geopy.timezone.Timezone`. """ ensure_pytz_is_installed() location = self._coerce_point_to_string(query) timestamp = self._normalize_timezone_at_time(at_time) params = { "location": location, "timestamp": timestamp, } if self.api_key: params['key'] = self.api_key url = "?".join((self.tz_api, urlencode(params))) logger.debug("%s.reverse_timezone: %s", self.__class__.__name__, url) return self._call_geocoder(url, self._parse_json_timezone, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L330-L369
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
60
[ 24, 26, 28, 30, 34, 35, 36, 38, 39 ]
22.5
false
19.42446
40
2
77.5
21
def reverse_timezone(self, query, *, at_time=None, timeout=DEFAULT_SENTINEL): ensure_pytz_is_installed() location = self._coerce_point_to_string(query) timestamp = self._normalize_timezone_at_time(at_time) params = { "location": location, "timestamp": timestamp, } if self.api_key: params['key'] = self.api_key url = "?".join((self.tz_api, urlencode(params))) logger.debug("%s.reverse_timezone: %s", self.__class__.__name__, url) return self._call_geocoder(url, self._parse_json_timezone, timeout=timeout)
21,058
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3._parse_json_timezone
(self, response)
return from_timezone_name(timezone_id, raw=response)
371
381
def _parse_json_timezone(self, response): self._check_status(response) timezone_id = response.get("timeZoneId") if timezone_id is None: # Google returns `status: ZERO_RESULTS` for uncovered # points (e.g. for Antarctica), so there's nothing # meaningful to be returned as the `raw` response, # hence we return `None`. return None return from_timezone_name(timezone_id, raw=response)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L371-L381
31
[ 0 ]
9.090909
[ 1, 3, 4, 9, 10 ]
45.454545
false
19.42446
11
2
54.545455
0
def _parse_json_timezone(self, response): self._check_status(response) timezone_id = response.get("timeZoneId") if timezone_id is None: # Google returns `status: ZERO_RESULTS` for uncovered # points (e.g. for Antarctica), so there's nothing # meaningful to be returned as the `raw` response, # hence we return `None`. return None return from_timezone_name(timezone_id, raw=response)
21,059
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3._normalize_timezone_at_time
(self, at_time)
return timestamp
383
394
def _normalize_timezone_at_time(self, at_time): if at_time is None: timestamp = timegm(datetime.utcnow().utctimetuple()) elif isinstance(at_time, datetime): # Naive datetimes are silently treated as UTC. # Timezone-aware datetimes are handled correctly. timestamp = timegm(at_time.utctimetuple()) else: raise GeocoderQueryError( "`at_time` must be an instance of `datetime.datetime`" ) return timestamp
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L383-L394
31
[ 0 ]
8.333333
[ 1, 2, 3, 6, 8, 11 ]
50
false
19.42446
12
3
50
0
def _normalize_timezone_at_time(self, at_time): if at_time is None: timestamp = timegm(datetime.utcnow().utctimetuple()) elif isinstance(at_time, datetime): # Naive datetimes are silently treated as UTC. # Timezone-aware datetimes are handled correctly. timestamp = timegm(at_time.utctimetuple()) else: raise GeocoderQueryError( "`at_time` must be an instance of `datetime.datetime`" ) return timestamp
21,060
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3._parse_json
(self, page, exactly_one=True)
Returns location, (latitude, longitude) from json feed.
Returns location, (latitude, longitude) from json feed.
396
414
def _parse_json(self, page, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' places = page.get('results', []) self._check_status(page) if not places: return None def parse_place(place): '''Get the location, lat, lng from a single json place.''' location = place.get('formatted_address') latitude = place['geometry']['location']['lat'] longitude = place['geometry']['location']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(places[0]) else: return [parse_place(place) for place in places]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L396-L414
31
[ 0 ]
5.263158
[ 3, 4, 5, 6, 8, 10, 11, 12, 13, 15, 16, 18 ]
63.157895
false
19.42446
19
5
36.842105
1
def _parse_json(self, page, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' places = page.get('results', []) self._check_status(page) if not places: return None def parse_place(place): '''Get the location, lat, lng from a single json place.''' location = place.get('formatted_address') latitude = place['geometry']['location']['lat'] longitude = place['geometry']['location']['lng'] return Location(location, (latitude, longitude), place) if exactly_one: return parse_place(places[0]) else: return [parse_place(place) for place in places]
21,061
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/google.py
GoogleV3._check_status
(self, response)
416
447
def _check_status(self, response): # https://developers.google.com/maps/documentation/geocoding/requests-geocoding#StatusCodes status = response.get('status') if status == 'OK': return if status == 'ZERO_RESULTS': return error_message = response.get('error_message') # https://developers.google.com/maps/documentation/geocoding/requests-geocoding#ErrorMessages # When the geocoder returns a status code other than OK, there *may* # be an additional error_message field within the Geocoding response # object. if status in ('OVER_QUERY_LIMIT', 'OVER_DAILY_LIMIT'): raise GeocoderQuotaExceeded( error_message or 'The given key has gone over the requests limit in the 24' ' hour period or has submitted too many requests in too' ' short a period of time' ) elif status == 'REQUEST_DENIED': raise GeocoderQueryError(error_message or 'Your request was denied') elif status == 'INVALID_REQUEST': raise GeocoderQueryError( error_message or 'Probably missing address or latlng' ) elif status == 'UNKNOWN_ERROR': raise GeocoderUnavailable(error_message or 'Server error') else: # Unknown (undocumented) status. raise GeocoderServiceError(error_message or 'Unknown error')
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/google.py#L416-L447
31
[ 0, 1 ]
6.25
[ 2, 3, 4, 5, 6, 8, 14, 15, 21, 22, 23, 24, 27, 28, 31 ]
46.875
false
19.42446
32
12
53.125
0
def _check_status(self, response): # https://developers.google.com/maps/documentation/geocoding/requests-geocoding#StatusCodes status = response.get('status') if status == 'OK': return if status == 'ZERO_RESULTS': return error_message = response.get('error_message') # https://developers.google.com/maps/documentation/geocoding/requests-geocoding#ErrorMessages # When the geocoder returns a status code other than OK, there *may* # be an additional error_message field within the Geocoding response # object. if status in ('OVER_QUERY_LIMIT', 'OVER_DAILY_LIMIT'): raise GeocoderQuotaExceeded( error_message or 'The given key has gone over the requests limit in the 24' ' hour period or has submitted too many requests in too' ' short a period of time' ) elif status == 'REQUEST_DENIED': raise GeocoderQueryError(error_message or 'Your request was denied') elif status == 'INVALID_REQUEST': raise GeocoderQueryError( error_message or 'Probably missing address or latlng' ) elif status == 'UNKNOWN_ERROR': raise GeocoderUnavailable(error_message or 'Server error') else: # Unknown (undocumented) status. raise GeocoderServiceError(error_message or 'Unknown error')
21,062
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapquest.py
MapQuest.__init__
( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='www.mapquestapi.com' )
:param str api_key: The API key required by Mapquest to perform geocoding requests. API keys are managed through MapQuest's "Manage Keys" page (https://developer.mapquest.com/user/me/apps). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: base api domain for mapquest
:param str api_key: The API key required by Mapquest to perform geocoding requests. API keys are managed through MapQuest's "Manage Keys" page (https://developer.mapquest.com/user/me/apps).
28
85
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='www.mapquestapi.com' ): """ :param str api_key: The API key required by Mapquest to perform geocoding requests. API keys are managed through MapQuest's "Manage Keys" page (https://developer.mapquest.com/user/me/apps). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str domain: base api domain for mapquest """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapquest.py#L28-L85
31
[ 0 ]
1.724138
[ 40, 49, 50, 52, 55 ]
8.62069
false
24.074074
58
1
91.37931
26
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, domain='www.mapquestapi.com' ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
21,063
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapquest.py
MapQuest._parse_json
(self, json, exactly_one=True)
Returns location, (latitude, longitude) from json feed.
Returns location, (latitude, longitude) from json feed.
87
118
def _parse_json(self, json, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' features = json['results'][0]['locations'] if features == []: return None def parse_location(feature): addr_keys = [ 'street', 'adminArea6', 'adminArea5', 'adminArea4', 'adminArea3', 'adminArea2', 'adminArea1', 'postalCode' ] location = [feature[k] for k in addr_keys if feature.get(k)] return ", ".join(location) def parse_feature(feature): location = parse_location(feature) longitude = feature['latLng']['lng'] latitude = feature['latLng']['lat'] return Location(location, (latitude, longitude), feature) if exactly_one: return parse_feature(features[0]) else: return [parse_feature(feature) for feature in features]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapquest.py#L87-L118
31
[ 0 ]
3.125
[ 2, 4, 5, 7, 8, 19, 20, 22, 23, 24, 25, 26, 28, 29, 31 ]
46.875
false
24.074074
32
7
53.125
1
def _parse_json(self, json, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' features = json['results'][0]['locations'] if features == []: return None def parse_location(feature): addr_keys = [ 'street', 'adminArea6', 'adminArea5', 'adminArea4', 'adminArea3', 'adminArea2', 'adminArea1', 'postalCode' ] location = [feature[k] for k in addr_keys if feature.get(k)] return ", ".join(location) def parse_feature(feature): location = parse_location(feature) longitude = feature['latLng']['lng'] latitude = feature['latLng']['lat'] return Location(location, (latitude, longitude), feature) if exactly_one: return parse_feature(features[0]) else: return [parse_feature(feature) for feature in features]
21,064
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapquest.py
MapQuest.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, bounds=None )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Limit the maximum number of items in the response. This will be reset to one if ``exactly_one`` is True. :param bounds: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bounds: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
120
173
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, bounds=None ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int limit: Limit the maximum number of items in the response. This will be reset to one if ``exactly_one`` is True. :param bounds: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bounds: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {} params['key'] = self.api_key params['location'] = query if limit is not None: params['maxResults'] = limit if exactly_one: params["maxResults"] = 1 if bounds: params['boundingBox'] = self._format_bounding_box( bounds, "%(lat2)s,%(lon1)s,%(lat1)s,%(lon2)s" ) url = '?'.join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapquest.py#L120-L173
31
[ 0 ]
1.851852
[ 34, 35, 36, 38, 39, 41, 42, 44, 45, 49, 51, 52, 53 ]
24.074074
false
24.074074
54
4
75.925926
23
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, limit=None, bounds=None ): params = {} params['key'] = self.api_key params['location'] = query if limit is not None: params['maxResults'] = limit if exactly_one: params["maxResults"] = 1 if bounds: params['boundingBox'] = self._format_bounding_box( bounds, "%(lat2)s,%(lon1)s,%(lat1)s,%(lon2)s" ) url = '?'.join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,065
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/mapquest.py
MapQuest.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
175
211
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {} params['key'] = self.api_key point = self._coerce_point_to_string(query, "%(lat)s,%(lon)s") params['location'] = point url = '?'.join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/mapquest.py#L175-L211
31
[ 0 ]
2.702703
[ 26, 27, 29, 30, 32, 34, 35, 36 ]
21.621622
false
24.074074
37
1
78.378378
17
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = {} params['key'] = self.api_key point = self._coerce_point_to_string(query, "%(lat)s,%(lon)s") params['location'] = point url = '?'.join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,066
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
Here.__init__
( self, *, app_id=None, app_code=None, apikey=None, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str app_id: Should be a valid HERE Maps APP ID. Will eventually be replaced with APIKEY. See https://developer.here.com/authenticationpage. .. attention:: App ID and App Code are being replaced by API Keys and OAuth 2.0 by HERE. Consider getting an ``apikey`` instead of using ``app_id`` and ``app_code``. :param str app_code: Should be a valid HERE Maps APP CODE. Will eventually be replaced with APIKEY. See https://developer.here.com/authenticationpage. .. attention:: App ID and App Code are being replaced by API Keys and OAuth 2.0 by HERE. Consider getting an ``apikey`` instead of using ``app_id`` and ``app_code``. :param str apikey: Should be a valid HERE Maps APIKEY. These keys were introduced in December 2019 and will eventually replace the legacy APP CODE/APP ID pairs which are already no longer available for new accounts (but still work for old accounts). More authentication details are available at https://developer.here.com/blog/announcing-two-new-authentication-types. See https://developer.here.com/authenticationpage. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
49
144
def __init__( self, *, app_id=None, app_code=None, apikey=None, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str app_id: Should be a valid HERE Maps APP ID. Will eventually be replaced with APIKEY. See https://developer.here.com/authenticationpage. .. attention:: App ID and App Code are being replaced by API Keys and OAuth 2.0 by HERE. Consider getting an ``apikey`` instead of using ``app_id`` and ``app_code``. :param str app_code: Should be a valid HERE Maps APP CODE. Will eventually be replaced with APIKEY. See https://developer.here.com/authenticationpage. .. attention:: App ID and App Code are being replaced by API Keys and OAuth 2.0 by HERE. Consider getting an ``apikey`` instead of using ``app_id`` and ``app_code``. :param str apikey: Should be a valid HERE Maps APIKEY. These keys were introduced in December 2019 and will eventually replace the legacy APP CODE/APP ID pairs which are already no longer available for new accounts (but still work for old accounts). More authentication details are available at https://developer.here.com/blog/announcing-two-new-authentication-types. See https://developer.here.com/authenticationpage. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) is_apikey = bool(apikey) is_app_code = app_id and app_code if not is_apikey and not is_app_code: raise ConfigurationError( "HERE geocoder requires authentication, either `apikey` " "or `app_id`+`app_code` must be set" ) if is_app_code: warnings.warn( 'Since December 2019 HERE provides two new authentication ' 'methods `API Key` and `OAuth 2.0`. `app_id`+`app_code` ' 'is deprecated and might eventually be phased out. ' 'Consider switching to `apikey`, which geopy supports. ' 'See https://developer.here.com/blog/announcing-two-new-authentication-types', # noqa UserWarning, stacklevel=2 ) self.app_id = app_id self.app_code = app_code self.apikey = apikey domain = "ls.hereapi.com" if is_apikey else "api.here.com" self.api = "%s://geocoder.%s%s" % (self.scheme, domain, self.geocode_path) self.reverse_api = ( "%s://reverse.geocoder.%s%s" % (self.scheme, domain, self.reverse_path) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L49-L144
31
[ 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95 ]
37.5
[]
0
false
22.043011
96
5
100
46
def __init__( self, *, app_id=None, app_code=None, apikey=None, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) is_apikey = bool(apikey) is_app_code = app_id and app_code if not is_apikey and not is_app_code: raise ConfigurationError( "HERE geocoder requires authentication, either `apikey` " "or `app_id`+`app_code` must be set" ) if is_app_code: warnings.warn( 'Since December 2019 HERE provides two new authentication ' 'methods `API Key` and `OAuth 2.0`. `app_id`+`app_code` ' 'is deprecated and might eventually be phased out. ' 'Consider switching to `apikey`, which geopy supports. ' 'See https://developer.here.com/blog/announcing-two-new-authentication-types', # noqa UserWarning, stacklevel=2 ) self.app_id = app_id self.app_code = app_code self.apikey = apikey domain = "ls.hereapi.com" if is_apikey else "api.here.com" self.api = "%s://geocoder.%s%s" % (self.scheme, domain, self.geocode_path) self.reverse_api = ( "%s://reverse.geocoder.%s%s" % (self.scheme, domain, self.reverse_path) )
21,067
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
Here.geocode
( self, query, *, bbox=None, mapview=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, additional_data=False, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-geocode.html :param query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `city`, `county`, `district`, `country`, `state`, `street`, `housenumber`, or `postalcode`. :type query: str or dict :param bbox: A type of spatial filter, limits the search for any other attributes in the request. Specified by two coordinate (lat/lon) pairs -- corners of the box. `The bbox search is currently similar to mapview but it is not extended` (cited from the REST API docs). Relevant global results are also returned. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param mapview: The app's viewport, given as two coordinate pairs, specified by two lat/lon pairs -- corners of the bounding box, respectively. Matches from within the set map view plus an extended area are ranked highest. Relevant global results are also returned. Example: ``[Point(22, 180), Point(-22, -180)]``. :type mapview: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int maxresults: Defines the maximum number of items in the response structure. If not provided and there are multiple results the HERE API will return 10 results by default. This will be reset to one if ``exactly_one`` is True. :param int pageinformation: A key which identifies the page to be returned when the response is separated into multiple pages. Only useful when ``maxresults`` is also provided. :param str language: Affects the language of the response, must be a RFC 4647 language code, e.g. 'en-US'. :param str additional_data: A string with key-value pairs as described on https://developer.here.com/documentation/geocoder/topics/resource-params-additional.html. These will be added as one query parameter to the URL. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
146
251
def geocode( self, query, *, bbox=None, mapview=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, additional_data=False, timeout=DEFAULT_SENTINEL ): """ Return a location point by address. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-geocode.html :param query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `city`, `county`, `district`, `country`, `state`, `street`, `housenumber`, or `postalcode`. :type query: str or dict :param bbox: A type of spatial filter, limits the search for any other attributes in the request. Specified by two coordinate (lat/lon) pairs -- corners of the box. `The bbox search is currently similar to mapview but it is not extended` (cited from the REST API docs). Relevant global results are also returned. Example: ``[Point(22, 180), Point(-22, -180)]``. :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param mapview: The app's viewport, given as two coordinate pairs, specified by two lat/lon pairs -- corners of the bounding box, respectively. Matches from within the set map view plus an extended area are ranked highest. Relevant global results are also returned. Example: ``[Point(22, 180), Point(-22, -180)]``. :type mapview: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int maxresults: Defines the maximum number of items in the response structure. If not provided and there are multiple results the HERE API will return 10 results by default. This will be reset to one if ``exactly_one`` is True. :param int pageinformation: A key which identifies the page to be returned when the response is separated into multiple pages. Only useful when ``maxresults`` is also provided. :param str language: Affects the language of the response, must be a RFC 4647 language code, e.g. 'en-US'. :param str additional_data: A string with key-value pairs as described on https://developer.here.com/documentation/geocoder/topics/resource-params-additional.html. These will be added as one query parameter to the URL. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } else: params = {'searchtext': query} if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lat2)s,%(lon1)s;%(lat1)s,%(lon2)s") if mapview: params['mapview'] = self._format_bounding_box( mapview, "%(lat2)s,%(lon1)s;%(lat1)s,%(lon2)s") if pageinformation: params['pageinformation'] = pageinformation if maxresults: params['maxresults'] = maxresults if exactly_one: params['maxresults'] = 1 if language: params['language'] = language if additional_data: params['additionaldata'] = additional_data if self.apikey: params['apiKey'] = self.apikey else: params['app_id'] = self.app_id params['app_code'] = self.app_code url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L146-L251
31
[ 0 ]
0.943396
[ 71, 72, 79, 80, 81, 83, 84, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 99, 100, 102, 103, 104, 105 ]
23.584906
false
22.043011
106
10
76.415094
56
def geocode( self, query, *, bbox=None, mapview=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, additional_data=False, timeout=DEFAULT_SENTINEL ): if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } else: params = {'searchtext': query} if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lat2)s,%(lon1)s;%(lat1)s,%(lon2)s") if mapview: params['mapview'] = self._format_bounding_box( mapview, "%(lat2)s,%(lon1)s;%(lat1)s,%(lon2)s") if pageinformation: params['pageinformation'] = pageinformation if maxresults: params['maxresults'] = maxresults if exactly_one: params['maxresults'] = 1 if language: params['language'] = language if additional_data: params['additionaldata'] = additional_data if self.apikey: params['apiKey'] = self.apikey else: params['app_id'] = self.app_id params['app_code'] = self.app_code url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,068
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
Here.reverse
( self, query, *, radius=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, mode='retrieveAddresses', timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-reverse-geocode.html :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param float radius: Proximity radius in meters. :param bool exactly_one: Return one result or a list of results, if available. :param int maxresults: Defines the maximum number of items in the response structure. If not provided and there are multiple results the HERE API will return 10 results by default. This will be reset to one if ``exactly_one`` is True. :param int pageinformation: A key which identifies the page to be returned when the response is separated into multiple pages. Only useful when ``maxresults`` is also provided. :param str language: Affects the language of the response, must be a RFC 4647 language code, e.g. 'en-US'. :param str mode: Affects the type of returned response items, must be one of: 'retrieveAddresses' (default), 'retrieveAreas', 'retrieveLandmarks', 'retrieveAll', or 'trackPosition'. See online documentation for more information. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
253
330
def reverse( self, query, *, radius=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, mode='retrieveAddresses', timeout=DEFAULT_SENTINEL ): """ Return an address by location point. This implementation supports only a subset of all available parameters. A list of all parameters of the pure REST API is available here: https://developer.here.com/documentation/geocoder/topics/resource-reverse-geocode.html :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param float radius: Proximity radius in meters. :param bool exactly_one: Return one result or a list of results, if available. :param int maxresults: Defines the maximum number of items in the response structure. If not provided and there are multiple results the HERE API will return 10 results by default. This will be reset to one if ``exactly_one`` is True. :param int pageinformation: A key which identifies the page to be returned when the response is separated into multiple pages. Only useful when ``maxresults`` is also provided. :param str language: Affects the language of the response, must be a RFC 4647 language code, e.g. 'en-US'. :param str mode: Affects the type of returned response items, must be one of: 'retrieveAddresses' (default), 'retrieveAreas', 'retrieveLandmarks', 'retrieveAll', or 'trackPosition'. See online documentation for more information. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ point = self._coerce_point_to_string(query) params = { 'mode': mode, 'prox': point, } if radius is not None: params['prox'] = '%s,%s' % (params['prox'], float(radius)) if pageinformation: params['pageinformation'] = pageinformation if maxresults: params['maxresults'] = maxresults if exactly_one: params['maxresults'] = 1 if language: params['language'] = language if self.apikey: params['apiKey'] = self.apikey else: params['app_id'] = self.app_id params['app_code'] = self.app_code url = "%s?%s" % (self.reverse_api, urlencode(params)) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L253-L330
31
[ 0 ]
1.282051
[ 54, 55, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 74, 75, 76, 77 ]
25.641026
false
22.043011
78
7
74.358974
40
def reverse( self, query, *, radius=None, exactly_one=True, maxresults=None, pageinformation=None, language=None, mode='retrieveAddresses', timeout=DEFAULT_SENTINEL ): point = self._coerce_point_to_string(query) params = { 'mode': mode, 'prox': point, } if radius is not None: params['prox'] = '%s,%s' % (params['prox'], float(radius)) if pageinformation: params['pageinformation'] = pageinformation if maxresults: params['maxresults'] = maxresults if exactly_one: params['maxresults'] = 1 if language: params['language'] = language if self.apikey: params['apiKey'] = self.apikey else: params['app_id'] = self.app_id params['app_code'] = self.app_code url = "%s?%s" % (self.reverse_api, urlencode(params)) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,069
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
Here._parse_json
(self, doc, exactly_one=True)
Parse a location name, latitude, and longitude from an JSON response.
Parse a location name, latitude, and longitude from an JSON response.
332
383
def _parse_json(self, doc, exactly_one=True): """ Parse a location name, latitude, and longitude from an JSON response. """ status_code = doc.get("statusCode", 200) if status_code != 200: err = doc.get("errorDetails", "") if status_code == 401: raise GeocoderAuthenticationFailure(err) elif status_code == 403: raise GeocoderInsufficientPrivileges(err) elif status_code == 429: raise GeocoderRateLimited(err) elif status_code == 503: raise GeocoderUnavailable(err) else: raise GeocoderServiceError(err) try: resources = doc['Response']['View'][0]['Result'] except IndexError: resources = None if not resources: return None def parse_resource(resource): """ Parse each return object. """ stripchars = ", \n" addr = resource['Location']['Address'] address = addr.get('Label', '').strip(stripchars) city = addr.get('City', '').strip(stripchars) state = addr.get('State', '').strip(stripchars) zipcode = addr.get('PostalCode', '').strip(stripchars) country = addr.get('Country', '').strip(stripchars) city_state = join_filter(", ", [city, state]) place = join_filter(" ", [city_state, zipcode]) location = join_filter(", ", [address, place, country]) display_pos = resource['Location']['DisplayPosition'] latitude = float(display_pos['Latitude']) longitude = float(display_pos['Longitude']) return Location(location, (latitude, longitude), resource) if exactly_one: return parse_resource(resources[0]) else: return [parse_resource(resource) for resource in resources]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L332-L383
31
[ 0, 1, 2, 3 ]
7.692308
[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 19, 20, 21, 22, 23, 25, 29, 30, 32, 33, 34, 35, 36, 38, 39, 40, 42, 43, 44, 46, 48, 49, 51 ]
69.230769
false
22.043011
52
11
30.769231
1
def _parse_json(self, doc, exactly_one=True): status_code = doc.get("statusCode", 200) if status_code != 200: err = doc.get("errorDetails", "") if status_code == 401: raise GeocoderAuthenticationFailure(err) elif status_code == 403: raise GeocoderInsufficientPrivileges(err) elif status_code == 429: raise GeocoderRateLimited(err) elif status_code == 503: raise GeocoderUnavailable(err) else: raise GeocoderServiceError(err) try: resources = doc['Response']['View'][0]['Result'] except IndexError: resources = None if not resources: return None def parse_resource(resource): stripchars = ", \n" addr = resource['Location']['Address'] address = addr.get('Label', '').strip(stripchars) city = addr.get('City', '').strip(stripchars) state = addr.get('State', '').strip(stripchars) zipcode = addr.get('PostalCode', '').strip(stripchars) country = addr.get('Country', '').strip(stripchars) city_state = join_filter(", ", [city, state]) place = join_filter(" ", [city_state, zipcode]) location = join_filter(", ", [address, place, country]) display_pos = resource['Location']['DisplayPosition'] latitude = float(display_pos['Latitude']) longitude = float(display_pos['Longitude']) return Location(location, (latitude, longitude), resource) if exactly_one: return parse_resource(resources[0]) else: return [parse_resource(resource) for resource in resources]
21,070
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
HereV7.__init__
( self, apikey, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str apikey: Should be a valid HERE Maps apikey. A project can be created at https://developer.here.com/projects. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`.
412
463
def __init__( self, apikey, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str apikey: Should be a valid HERE Maps apikey. A project can be created at https://developer.here.com/projects. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) domain = "search.hereapi.com" self.apikey = apikey self.api = "%s://geocode.%s%s" % (self.scheme, domain, self.geocode_path) self.reverse_api = ( "%s://revgeocode.%s%s" % (self.scheme, domain, self.reverse_path) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L412-L463
31
[ 0 ]
1.923077
[ 36, 45, 47, 48, 49 ]
9.615385
false
22.043011
52
1
90.384615
22
def __init__( self, apikey, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) domain = "search.hereapi.com" self.apikey = apikey self.api = "%s://geocode.%s%s" % (self.scheme, domain, self.geocode_path) self.reverse_api = ( "%s://revgeocode.%s%s" % (self.scheme, domain, self.reverse_path) )
21,071
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
HereV7.geocode
( self, query=None, *, components=None, at=None, countries=None, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. Optional, if ``components`` param is set. :param dict components: A structured query. Can be used along with the free-text ``query``. Should be a dictionary whose keys are one of: `country`, `state`, `county`, `city`, `district`, `street`, `houseNumber`, `postalCode`. :param at: The center of the search context. :type at: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param list countries: A list of country codes specified in `ISO 3166-1 alpha-3 <https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3>`_ format, e.g. ``['USA', 'CAN']``. This is a hard filter. :param str language: Affects the language of the response, must be a BCP 47 compliant language code, e.g. ``en-US``. :param int limit: Defines the maximum number of items in the response structure. If not provided and there are multiple results the HERE API will return 20 results by default. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
465
559
def geocode( self, query=None, *, components=None, at=None, countries=None, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point by address. :param str query: The address or query you wish to geocode. Optional, if ``components`` param is set. :param dict components: A structured query. Can be used along with the free-text ``query``. Should be a dictionary whose keys are one of: `country`, `state`, `county`, `city`, `district`, `street`, `houseNumber`, `postalCode`. :param at: The center of the search context. :type at: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param list countries: A list of country codes specified in `ISO 3166-1 alpha-3 <https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3>`_ format, e.g. ``['USA', 'CAN']``. This is a hard filter. :param str language: Affects the language of the response, must be a BCP 47 compliant language code, e.g. ``en-US``. :param int limit: Defines the maximum number of items in the response structure. If not provided and there are multiple results the HERE API will return 20 results by default. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'apiKey': self.apikey, } if query: params['q'] = query if components: parts = [ "{}={}".format(key, val) for key, val in components.items() if key in self.structured_query_params ] if not parts: raise GeocoderQueryError("`components` dict must not be empty") for pair in parts: if ';' in pair: raise GeocoderQueryError( "';' must not be used in values of the structured query. " "Offending pair: {!r}".format(pair) ) params['qq'] = ';'.join(parts) if at: point = self._coerce_point_to_string(at, output_format="%(lat)s,%(lon)s") params['at'] = point if countries: params['in'] = 'countryCode:' + ','.join(countries) if language: params['lang'] = language if limit: params['limit'] = limit if exactly_one: params['limit'] = 1 url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L465-L559
31
[ 0 ]
1.052632
[ 52, 56, 57, 59, 60, 66, 67, 68, 69, 70, 74, 76, 77, 78, 80, 81, 83, 84, 86, 87, 88, 89, 91, 92, 93, 94 ]
27.368421
false
22.043011
95
12
72.631579
38
def geocode( self, query=None, *, components=None, at=None, countries=None, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = { 'apiKey': self.apikey, } if query: params['q'] = query if components: parts = [ "{}={}".format(key, val) for key, val in components.items() if key in self.structured_query_params ] if not parts: raise GeocoderQueryError("`components` dict must not be empty") for pair in parts: if ';' in pair: raise GeocoderQueryError( "';' must not be used in values of the structured query. " "Offending pair: {!r}".format(pair) ) params['qq'] = ';'.join(parts) if at: point = self._coerce_point_to_string(at, output_format="%(lat)s,%(lon)s") params['at'] = point if countries: params['in'] = 'countryCode:' + ','.join(countries) if language: params['lang'] = language if limit: params['limit'] = limit if exactly_one: params['limit'] = 1 url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,072
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
HereV7.reverse
( self, query, *, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str language: Affects the language of the response, must be a BCP 47 compliant language code, e.g. ``en-US``. :param int limit: Maximum number of results to be returned. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
561
612
def reverse( self, query, *, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str language: Affects the language of the response, must be a BCP 47 compliant language code, e.g. ``en-US``. :param int limit: Maximum number of results to be returned. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'at': self._coerce_point_to_string(query, output_format="%(lat)s,%(lon)s"), 'apiKey': self.apikey, } if language: params['lang'] = language if limit: params['limit'] = limit if exactly_one: params['limit'] = 1 url = "%s?%s" % (self.reverse_api, urlencode(params)) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L561-L612
31
[ 0 ]
1.923077
[ 35, 40, 41, 43, 44, 45, 46, 48, 49, 50, 51 ]
21.153846
false
22.043011
52
4
78.846154
23
def reverse( self, query, *, language=None, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = { 'at': self._coerce_point_to_string(query, output_format="%(lat)s,%(lon)s"), 'apiKey': self.apikey, } if language: params['lang'] = language if limit: params['limit'] = limit if exactly_one: params['limit'] = 1 url = "%s?%s" % (self.reverse_api, urlencode(params)) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,073
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
HereV7._parse_json
(self, doc, exactly_one=True)
614
633
def _parse_json(self, doc, exactly_one=True): resources = doc['items'] if not resources: return None def parse_resource(resource): """ Parse each return object. """ location = resource['title'] position = resource['position'] latitude, longitude = position['lat'], position['lng'] return Location(location, (latitude, longitude), resource) if exactly_one: return parse_resource(resources[0]) else: return [parse_resource(resource) for resource in resources]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L614-L633
31
[ 0 ]
5
[ 1, 2, 3, 5, 9, 10, 12, 14, 16, 17, 19 ]
55
false
22.043011
20
5
45
0
def _parse_json(self, doc, exactly_one=True): resources = doc['items'] if not resources: return None def parse_resource(resource): location = resource['title'] position = resource['position'] latitude, longitude = position['lat'], position['lng'] return Location(location, (latitude, longitude), resource) if exactly_one: return parse_resource(resources[0]) else: return [parse_resource(resource) for resource in resources]
21,074
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/here.py
HereV7._geocoder_exception_handler
(self, error)
635
649
def _geocoder_exception_handler(self, error): if not isinstance(error, AdapterHTTPError): return if error.status_code is None or error.text is None: return try: body = json.loads(error.text) except ValueError: message = error.text else: # `title`: https://developer.here.com/documentation/geocoding-search-api/api-reference-swagger.html # noqa # `error_description`: returned for queries without apiKey. message = body.get('title') or body.get('error_description') or error.text exc_cls = ERROR_CODE_MAP.get(error.status_code, GeocoderServiceError) raise exc_cls(message) from error
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/here.py#L635-L649
31
[ 0 ]
6.666667
[ 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14 ]
73.333333
false
22.043011
15
7
26.666667
0
def _geocoder_exception_handler(self, error): if not isinstance(error, AdapterHTTPError): return if error.status_code is None or error.text is None: return try: body = json.loads(error.text) except ValueError: message = error.text else: # `title`: https://developer.here.com/documentation/geocoding-search-api/api-reference-swagger.html # noqa # `error_description`: returned for queries without apiKey. message = body.get('title') or body.get('error_description') or error.text exc_cls = ERROR_CODE_MAP.get(error.status_code, GeocoderServiceError) raise exc_cls(message) from error
21,075
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/banfrance.py
BANFrance.__init__
( self, *, domain='api-adresse.data.gouv.fr', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str domain: Currently it is ``'api-adresse.data.gouv.fr'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
21
74
def __init__( self, *, domain='api-adresse.data.gouv.fr', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str domain: Currently it is ``'api-adresse.data.gouv.fr'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/banfrance.py#L21-L74
31
[ 0 ]
1.851852
[ 38, 46, 48, 51 ]
7.407407
false
30.434783
54
1
92.592593
23
def __init__( self, *, domain='api-adresse.data.gouv.fr', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') self.geocode_api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) )
21,076
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/banfrance.py
BANFrance.geocode
( self, query, *, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param int limit: Defines the maximum number of items in the response structure. If not provided and there are multiple results the BAN API will return 5 results by default. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
76
118
def geocode( self, query, *, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param int limit: Defines the maximum number of items in the response structure. If not provided and there are multiple results the BAN API will return 5 results by default. This will be reset to one if ``exactly_one`` is True. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'q': query, } if limit is not None: params['limit'] = limit url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/banfrance.py#L76-L118
31
[ 0 ]
2.325581
[ 31, 35, 36, 38, 40, 41, 42 ]
16.27907
false
30.434783
43
2
83.72093
19
def geocode( self, query, *, limit=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): params = { 'q': query, } if limit is not None: params['limit'] = limit url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,077
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/banfrance.py
BANFrance.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
120
161
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'lat': lat, 'lon': lon, } url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/banfrance.py#L120-L161
31
[ 0 ]
2.380952
[ 28, 29, 30, 31, 33, 38, 39, 40, 41 ]
21.428571
false
30.434783
42
2
78.571429
17
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL ): try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'lat': lat, 'lon': lon, } url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,078
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/banfrance.py
BANFrance._parse_feature
(self, feature)
return Location(placename, (latitude, longitude), feature)
163
169
def _parse_feature(self, feature): # Parse each resource. latitude = feature.get('geometry', {}).get('coordinates', [])[1] longitude = feature.get('geometry', {}).get('coordinates', [])[0] placename = feature.get('properties', {}).get('label') return Location(placename, (latitude, longitude), feature)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/banfrance.py#L163-L169
31
[ 0, 1 ]
28.571429
[ 2, 3, 4, 6 ]
57.142857
false
30.434783
7
1
42.857143
0
def _parse_feature(self, feature): # Parse each resource. latitude = feature.get('geometry', {}).get('coordinates', [])[1] longitude = feature.get('geometry', {}).get('coordinates', [])[0] placename = feature.get('properties', {}).get('label') return Location(placename, (latitude, longitude), feature)
21,079
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/banfrance.py
BANFrance._parse_json
(self, response, exactly_one)
171
180
def _parse_json(self, response, exactly_one): if response is None or 'features' not in response: return None features = response['features'] if not len(features): return None if exactly_one: return self._parse_feature(features[0]) else: return [self._parse_feature(feature) for feature in features]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/banfrance.py#L171-L180
31
[ 0 ]
10
[ 1, 2, 3, 4, 5, 6, 7, 9 ]
80
false
30.434783
10
6
20
0
def _parse_json(self, response, exactly_one): if response is None or 'features' not in response: return None features = response['features'] if not len(features): return None if exactly_one: return self._parse_feature(features[0]) else: return [self._parse_feature(feature) for feature in features]
21,080
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/arcgis.py
ArcGIS.__init__
( self, username=None, password=None, *, referer=None, token_lifetime=60, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, auth_domain='www.arcgis.com', domain='geocode.arcgis.com' )
:param str username: ArcGIS username. Required if authenticated mode is desired. :param str password: ArcGIS password. Required if authenticated mode is desired. :param str referer: Required if authenticated mode is desired. `Referer` HTTP header to send with each request, e.g., ``'http://www.example.com'``. This is tied to an issued token, so fielding queries for multiple referrers should be handled by having multiple ArcGIS geocoder instances. :param int token_lifetime: Desired lifetime, in minutes, of an ArcGIS-issued token. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. If authenticated mode is in use, it must be ``'https'``. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str auth_domain: Domain where the target ArcGIS auth service is hosted. Used only in authenticated mode (i.e. username, password and referer are set). :param str domain: Domain where the target ArcGIS service is hosted.
33
134
def __init__( self, username=None, password=None, *, referer=None, token_lifetime=60, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, auth_domain='www.arcgis.com', domain='geocode.arcgis.com' ): """ :param str username: ArcGIS username. Required if authenticated mode is desired. :param str password: ArcGIS password. Required if authenticated mode is desired. :param str referer: Required if authenticated mode is desired. `Referer` HTTP header to send with each request, e.g., ``'http://www.example.com'``. This is tied to an issued token, so fielding queries for multiple referrers should be handled by having multiple ArcGIS geocoder instances. :param int token_lifetime: Desired lifetime, in minutes, of an ArcGIS-issued token. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. If authenticated mode is in use, it must be ``'https'``. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str auth_domain: Domain where the target ArcGIS auth service is hosted. Used only in authenticated mode (i.e. username, password and referer are set). :param str domain: Domain where the target ArcGIS service is hosted. """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) if username or password or referer: if not (username and password and referer): raise ConfigurationError( "Authenticated mode requires username," " password, and referer" ) if self.scheme != 'https': raise ConfigurationError( "Authenticated mode requires scheme of 'https'" ) self.username = username self.password = password self.referer = referer self.auth_domain = auth_domain.strip('/') self.auth_api = ( '%s://%s%s' % (self.scheme, self.auth_domain, self.auth_path) ) self.token_lifetime = token_lifetime * 60 # store in seconds self.domain = domain.strip('/') self.api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) ) # Mutable state self.token = None self.token_expiry = None
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/arcgis.py#L33-L134
31
[ 0, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101 ]
32.352941
[ 71, 72, 76, 77 ]
3.921569
false
30.508475
102
8
96.078431
43
def __init__( self, username=None, password=None, *, referer=None, token_lifetime=60, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, auth_domain='www.arcgis.com', domain='geocode.arcgis.com' ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) if username or password or referer: if not (username and password and referer): raise ConfigurationError( "Authenticated mode requires username," " password, and referer" ) if self.scheme != 'https': raise ConfigurationError( "Authenticated mode requires scheme of 'https'" ) self.username = username self.password = password self.referer = referer self.auth_domain = auth_domain.strip('/') self.auth_api = ( '%s://%s%s' % (self.scheme, self.auth_domain, self.auth_path) ) self.token_lifetime = token_lifetime * 60 # store in seconds self.domain = domain.strip('/') self.api = ( '%s://%s%s' % (self.scheme, self.domain, self.geocode_path) ) self.reverse_api = ( '%s://%s%s' % (self.scheme, self.domain, self.reverse_path) ) # Mutable state self.token = None self.token_expiry = None
21,081
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/arcgis.py
ArcGIS.geocode
(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, out_fields=None)
return self._authenticated_call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param out_fields: A list of output fields to be returned in the attributes field of the raw data. This can be either a python list/tuple of fields or a comma-separated string. See https://developers.arcgis.com/rest/geocode/api-reference/geocoding-service-output.htm for a list of supported output fields. If you want to return all supported output fields, set ``out_fields="*"``. :type out_fields: str or iterable :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
136
173
def geocode(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, out_fields=None): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param out_fields: A list of output fields to be returned in the attributes field of the raw data. This can be either a python list/tuple of fields or a comma-separated string. See https://developers.arcgis.com/rest/geocode/api-reference/geocoding-service-output.htm for a list of supported output fields. If you want to return all supported output fields, set ``out_fields="*"``. :type out_fields: str or iterable :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {'singleLine': query, 'f': 'json'} if exactly_one: params['maxLocations'] = 1 if out_fields is not None: if isinstance(out_fields, str): params['outFields'] = out_fields else: params['outFields'] = ",".join(out_fields) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_geocode, exactly_one=exactly_one) return self._authenticated_call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/arcgis.py#L136-L173
31
[ 0 ]
2.631579
[ 26, 27, 28, 29, 30, 31, 33, 34, 35, 36, 37 ]
28.947368
false
30.508475
38
4
71.052632
22
def geocode(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, out_fields=None): params = {'singleLine': query, 'f': 'json'} if exactly_one: params['maxLocations'] = 1 if out_fields is not None: if isinstance(out_fields, str): params['outFields'] = out_fields else: params['outFields'] = ",".join(out_fields) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_geocode, exactly_one=exactly_one) return self._authenticated_call_geocoder(url, callback, timeout=timeout)
21,082
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/arcgis.py
ArcGIS._parse_geocode
(self, response, exactly_one)
return geocoded
175
192
def _parse_geocode(self, response, exactly_one): if 'error' in response: raise GeocoderServiceError(str(response['error'])) # Success; convert from the ArcGIS JSON format. if not len(response['candidates']): return None geocoded = [] for resource in response['candidates']: geometry = resource['location'] geocoded.append( Location( resource['address'], (geometry['y'], geometry['x']), resource ) ) if exactly_one: return geocoded[0] return geocoded
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/arcgis.py#L175-L192
31
[ 0 ]
5.555556
[ 1, 2, 5, 6, 7, 8, 9, 10, 15, 16, 17 ]
61.111111
false
30.508475
18
5
38.888889
0
def _parse_geocode(self, response, exactly_one): if 'error' in response: raise GeocoderServiceError(str(response['error'])) # Success; convert from the ArcGIS JSON format. if not len(response['candidates']): return None geocoded = [] for resource in response['candidates']: geometry = resource['location'] geocoded.append( Location( resource['address'], (geometry['y'], geometry['x']), resource ) ) if exactly_one: return geocoded[0] return geocoded
21,083
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/arcgis.py
ArcGIS.reverse
(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, distance=None)
return self._authenticated_call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int distance: Distance from the query location, in meters, within which to search. ArcGIS has a default of 100 meters, if not specified. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
194
227
def reverse(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, distance=None): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int distance: Distance from the query location, in meters, within which to search. ArcGIS has a default of 100 meters, if not specified. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ location = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") wkid = DEFAULT_WKID params = {'location': location, 'f': 'json', 'outSR': wkid} if distance is not None: params['distance'] = distance url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse, exactly_one=exactly_one) return self._authenticated_call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/arcgis.py#L194-L227
31
[ 0 ]
2.941176
[ 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
26.470588
false
30.508475
34
2
73.529412
21
def reverse(self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, distance=None): location = self._coerce_point_to_string(query, "%(lon)s,%(lat)s") wkid = DEFAULT_WKID params = {'location': location, 'f': 'json', 'outSR': wkid} if distance is not None: params['distance'] = distance url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_reverse, exactly_one=exactly_one) return self._authenticated_call_geocoder(url, callback, timeout=timeout)
21,084
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/arcgis.py
ArcGIS._parse_reverse
(self, response, exactly_one)
229
259
def _parse_reverse(self, response, exactly_one): if not len(response): return None if 'error' in response: # https://developers.arcgis.com/rest/geocode/api-reference/geocoding-service-output.htm if response['error']['code'] == 400: # 'details': ['Unable to find address for the specified location.']} try: if 'Unable to find' in response['error']['details'][0]: return None except (KeyError, IndexError): pass raise GeocoderServiceError(str(response['error'])) if response['address'].get('Address'): address = ( "%(Address)s, %(City)s, %(Region)s %(Postal)s," " %(CountryCode)s" % response['address'] ) else: address = response['address']['LongLabel'] location = Location( address, (response['location']['y'], response['location']['x']), response['address'] ) if exactly_one: return location else: return [location]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/arcgis.py#L229-L259
31
[ 0 ]
3.225806
[ 1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 14, 15, 20, 22, 27, 28, 30 ]
54.83871
false
30.508475
31
8
45.16129
0
def _parse_reverse(self, response, exactly_one): if not len(response): return None if 'error' in response: # https://developers.arcgis.com/rest/geocode/api-reference/geocoding-service-output.htm if response['error']['code'] == 400: # 'details': ['Unable to find address for the specified location.']} try: if 'Unable to find' in response['error']['details'][0]: return None except (KeyError, IndexError): pass raise GeocoderServiceError(str(response['error'])) if response['address'].get('Address'): address = ( "%(Address)s, %(City)s, %(Region)s %(Postal)s," " %(CountryCode)s" % response['address'] ) else: address = response['address']['LongLabel'] location = Location( address, (response['location']['y'], response['location']['x']), response['address'] ) if exactly_one: return location else: return [location]
21,085
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/arcgis.py
ArcGIS._authenticated_call_geocoder
( self, url, parse_callback, *, timeout=DEFAULT_SENTINEL )
261
297
def _authenticated_call_geocoder( self, url, parse_callback, *, timeout=DEFAULT_SENTINEL ): if not self.username: return self._call_geocoder(url, parse_callback, timeout=timeout) def query_callback(): call_url = "&".join((url, urlencode({"token": self.token}))) headers = {"Referer": self.referer} return self._call_geocoder( call_url, partial(maybe_reauthenticate_callback, from_token=self.token), timeout=timeout, headers=headers, ) def maybe_reauthenticate_callback(response, *, from_token): if "error" in response: if response["error"]["code"] == self._TOKEN_EXPIRED: return self._refresh_authentication_token( query_retry_callback, timeout=timeout, from_token=from_token ) return parse_callback(response) def query_retry_callback(): call_url = "&".join((url, urlencode({"token": self.token}))) headers = {"Referer": self.referer} return self._call_geocoder( call_url, parse_callback, timeout=timeout, headers=headers ) if self.token is None or int(time()) > self.token_expiry: return self._refresh_authentication_token( query_callback, timeout=timeout, from_token=self.token ) else: return query_callback()
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/arcgis.py#L261-L297
31
[ 0 ]
2.702703
[ 3, 4, 6, 7, 8, 9, 16, 17, 18, 19, 22, 24, 25, 26, 27, 31, 32, 36 ]
48.648649
false
30.508475
37
9
51.351351
0
def _authenticated_call_geocoder( self, url, parse_callback, *, timeout=DEFAULT_SENTINEL ): if not self.username: return self._call_geocoder(url, parse_callback, timeout=timeout) def query_callback(): call_url = "&".join((url, urlencode({"token": self.token}))) headers = {"Referer": self.referer} return self._call_geocoder( call_url, partial(maybe_reauthenticate_callback, from_token=self.token), timeout=timeout, headers=headers, ) def maybe_reauthenticate_callback(response, *, from_token): if "error" in response: if response["error"]["code"] == self._TOKEN_EXPIRED: return self._refresh_authentication_token( query_retry_callback, timeout=timeout, from_token=from_token ) return parse_callback(response) def query_retry_callback(): call_url = "&".join((url, urlencode({"token": self.token}))) headers = {"Referer": self.referer} return self._call_geocoder( call_url, parse_callback, timeout=timeout, headers=headers ) if self.token is None or int(time()) > self.token_expiry: return self._refresh_authentication_token( query_callback, timeout=timeout, from_token=self.token ) else: return query_callback()
21,086
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/arcgis.py
ArcGIS._refresh_authentication_token
(self, callback_success, *, timeout, from_token)
return self._call_geocoder(url, cb, timeout=timeout)
300
328
def _refresh_authentication_token(self, callback_success, *, timeout, from_token): if from_token != self.token: # Token has already been updated by a concurrent call. return callback_success() token_request_arguments = { 'username': self.username, 'password': self.password, 'referer': self.referer, 'expiration': self.token_lifetime, 'f': 'json' } url = "?".join((self.auth_api, urlencode(token_request_arguments))) logger.debug( "%s._refresh_authentication_token: %s", self.__class__.__name__, url ) def cb(response): if "token" not in response: raise GeocoderAuthenticationFailure( "Missing token in auth request." "Request URL: %s; response JSON: %s" % (url, json.dumps(response)) ) self.token = response["token"] self.token_expiry = int(time()) + self.token_lifetime return callback_success() return self._call_geocoder(url, cb, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/arcgis.py#L300-L328
31
[ 0 ]
3.448276
[ 1, 3, 5, 12, 13, 18, 19, 20, 24, 25, 26, 28 ]
41.37931
false
30.508475
29
4
58.62069
0
def _refresh_authentication_token(self, callback_success, *, timeout, from_token): if from_token != self.token: # Token has already been updated by a concurrent call. return callback_success() token_request_arguments = { 'username': self.username, 'password': self.password, 'referer': self.referer, 'expiration': self.token_lifetime, 'f': 'json' } url = "?".join((self.auth_api, urlencode(token_request_arguments))) logger.debug( "%s._refresh_authentication_token: %s", self.__class__.__name__, url ) def cb(response): if "token" not in response: raise GeocoderAuthenticationFailure( "Missing token in auth request." "Request URL: %s; response JSON: %s" % (url, json.dumps(response)) ) self.token = response["token"] self.token_expiry = int(time()) + self.token_lifetime return callback_success() return self._call_geocoder(url, cb, timeout=timeout)
21,087
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geolake.py
Geolake.__init__
( self, api_key, *, domain='api.geolake.com', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: The API key required by Geolake to perform geocoding requests. You can get your key here: https://geolake.com/ :param str domain: Currently it is ``'api.geolake.com'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
35
89
def __init__( self, api_key, *, domain='api.geolake.com', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: The API key required by Geolake to perform geocoding requests. You can get your key here: https://geolake.com/ :param str domain: Currently it is ``'api.geolake.com'``, can be changed for testing purposes. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geolake.py#L35-L89
31
[ 0, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 ]
25.454545
[]
0
false
39.130435
55
1
100
27
def __init__( self, api_key, *, domain='api.geolake.com', scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key self.domain = domain.strip('/') self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path)
21,088
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geolake.py
Geolake.geocode
( self, query, *, country_codes=None, exactly_one=True, timeout=DEFAULT_SENTINEL )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `country`, `state`, `city`, `zipcode`, `street`, `address`, `houseNumber` or `subNumber`. :type query: str or dict :param country_codes: Provides the geocoder with a list of country codes that the query may reside in. This value will limit the geocoder to the supplied countries. The country code is a 2 character code as defined by the ISO-3166-1 alpha-2 standard (e.g. ``FR``). Multiple countries can be specified with a Python list. :type country_codes: str or list :param bool exactly_one: Return one result or a list of one result. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
91
155
def geocode( self, query, *, country_codes=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): """ Return a location point by address. :param query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `country`, `state`, `city`, `zipcode`, `street`, `address`, `houseNumber` or `subNumber`. :type query: str or dict :param country_codes: Provides the geocoder with a list of country codes that the query may reside in. This value will limit the geocoder to the supplied countries. The country code is a 2 character code as defined by the ISO-3166-1 alpha-2 standard (e.g. ``FR``). Multiple countries can be specified with a Python list. :type country_codes: str or list :param bool exactly_one: Return one result or a list of one result. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } params['api_key'] = self.api_key else: params = { 'api_key': self.api_key, 'q': query, } if not country_codes: country_codes = [] if isinstance(country_codes, str): country_codes = [country_codes] if country_codes: params['countryCodes'] = ",".join(country_codes) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geolake.py#L91-L155
31
[ 0 ]
1.538462
[ 39, 40, 46, 48, 53, 54, 55, 56, 57, 58, 60, 62, 63, 64 ]
21.538462
false
39.130435
65
5
78.461538
27
def geocode( self, query, *, country_codes=None, exactly_one=True, timeout=DEFAULT_SENTINEL ): if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } params['api_key'] = self.api_key else: params = { 'api_key': self.api_key, 'q': query, } if not country_codes: country_codes = [] if isinstance(country_codes, str): country_codes = [country_codes] if country_codes: params['countryCodes'] = ",".join(country_codes) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,089
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geolake.py
Geolake._parse_json
(self, page, exactly_one)
Returns location, (latitude, longitude) from json feed.
Returns location, (latitude, longitude) from json feed.
157
171
def _parse_json(self, page, exactly_one): """Returns location, (latitude, longitude) from json feed.""" if not page.get('success'): return None latitude = page['latitude'] longitude = page['longitude'] address = self._get_address(page) result = Location(address, (latitude, longitude), page) if exactly_one: return result else: return [result]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geolake.py#L157-L171
31
[ 0, 1, 2 ]
20
[ 3, 4, 6, 7, 9, 10, 11, 12, 14 ]
60
false
39.130435
15
3
40
1
def _parse_json(self, page, exactly_one): if not page.get('success'): return None latitude = page['latitude'] longitude = page['longitude'] address = self._get_address(page) result = Location(address, (latitude, longitude), page) if exactly_one: return result else: return [result]
21,090
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geolake.py
Geolake._get_address
(self, page)
return address
Returns address string from page dictionary :param page: dict :return: str
Returns address string from page dictionary :param page: dict :return: str
173
183
def _get_address(self, page): """ Returns address string from page dictionary :param page: dict :return: str """ place = page.get('place') address_city = place.get('city') address_country_code = place.get('countryCode') address = join_filter(', ', [address_city, address_country_code]) return address
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geolake.py#L173-L183
31
[ 0, 1, 2, 3, 4, 5 ]
54.545455
[ 6, 7, 8, 9, 10 ]
45.454545
false
39.130435
11
1
54.545455
3
def _get_address(self, page): place = page.get('place') address_city = place.get('city') address_country_code = place.get('countryCode') address = join_filter(', ', [address_city, address_country_code]) return address
21,091
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/photon.py
Photon.__init__
( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='photon.komoot.io', user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Should be the localized Photon domain to connect to. The default is ``'photon.komoot.io'``, but you can change it to a domain of your own. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
30
78
def __init__( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='photon.komoot.io', user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Should be the localized Photon domain to connect to. The default is ``'photon.komoot.io'``, but you can change it to a domain of your own. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') self.api = "%s://%s%s" % (self.scheme, self.domain, self.geocode_path) self.reverse_api = "%s://%s%s" % (self.scheme, self.domain, self.reverse_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/photon.py#L30-L78
31
[ 0 ]
2.040816
[ 38, 46, 47, 48 ]
8.163265
false
20.833333
49
1
91.836735
24
def __init__( self, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='photon.komoot.io', user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.domain = domain.strip('/') self.api = "%s://%s%s" % (self.scheme, self.domain, self.geocode_path) self.reverse_api = "%s://%s%s" % (self.scheme, self.domain, self.reverse_path)
21,092
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/photon.py
Photon.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, location_bias=None, language=False, limit=None, osm_tag=None, bbox=None )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param location_bias: The coordinates to use as location bias. :type location_bias: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str language: Preferred language in which to return results. :param int limit: Limit the number of returned results, defaults to no limit. :param osm_tag: The expression to filter (include/exclude) by key and/ or value, str as ``'key:value'`` or list/set of str if multiple filters are required as ``['key:!val', '!key', ':!value']``. :type osm_tag: str or list or set :param bbox: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. .. versionadded:: 2.2 :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
80
166
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, location_bias=None, language=False, limit=None, osm_tag=None, bbox=None ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param location_bias: The coordinates to use as location bias. :type location_bias: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param str language: Preferred language in which to return results. :param int limit: Limit the number of returned results, defaults to no limit. :param osm_tag: The expression to filter (include/exclude) by key and/ or value, str as ``'key:value'`` or list/set of str if multiple filters are required as ``['key:!val', '!key', ':!value']``. :type osm_tag: str or list or set :param bbox: The bounding box of the viewport within which to bias geocode results more prominently. Example: ``[Point(22, 180), Point(-22, -180)]``. .. versionadded:: 2.2 :type bbox: list or tuple of 2 items of :class:`geopy.point.Point` or ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'q': query } if limit: params['limit'] = int(limit) if exactly_one: params['limit'] = 1 if language: params['lang'] = language if location_bias: try: lat, lon = self._coerce_point_to_string(location_bias).split(',') params['lon'] = lon params['lat'] = lat except ValueError: raise ValueError("Location bias must be a coordinate pair or Point") if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if osm_tag: if isinstance(osm_tag, str): params['osm_tag'] = [osm_tag] else: if not isinstance(osm_tag, collections.abc.Iterable): raise ValueError( "osm_tag must be a string or " "an iterable of strings" ) params['osm_tag'] = list(osm_tag) url = "?".join((self.api, urlencode(params, doseq=True))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/photon.py#L80-L166
31
[ 0 ]
1.149425
[ 52, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 69, 70, 73, 74, 75, 77, 78, 82, 83, 84, 85, 86 ]
29.885057
false
20.833333
87
10
70.114943
37
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, location_bias=None, language=False, limit=None, osm_tag=None, bbox=None ): params = { 'q': query } if limit: params['limit'] = int(limit) if exactly_one: params['limit'] = 1 if language: params['lang'] = language if location_bias: try: lat, lon = self._coerce_point_to_string(location_bias).split(',') params['lon'] = lon params['lat'] = lat except ValueError: raise ValueError("Location bias must be a coordinate pair or Point") if bbox: params['bbox'] = self._format_bounding_box( bbox, "%(lon1)s,%(lat1)s,%(lon2)s,%(lat2)s") if osm_tag: if isinstance(osm_tag, str): params['osm_tag'] = [osm_tag] else: if not isinstance(osm_tag, collections.abc.Iterable): raise ValueError( "osm_tag must be a string or " "an iterable of strings" ) params['osm_tag'] = list(osm_tag) url = "?".join((self.api, urlencode(params, doseq=True))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,093
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/photon.py
Photon.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=False, limit=None )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Preferred language in which to return results. :param int limit: Limit the number of returned results, defaults to no limit. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
168
218
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=False, limit=None ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str language: Preferred language in which to return results. :param int limit: Limit the number of returned results, defaults to no limit. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'lat': lat, 'lon': lon, } if limit: params['limit'] = int(limit) if exactly_one: params['limit'] = 1 if language: params['lang'] = language url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/photon.py#L168-L218
31
[ 0 ]
1.960784
[ 33, 34, 35, 36, 37, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50 ]
29.411765
false
20.833333
51
5
70.588235
22
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, language=False, limit=None ): try: lat, lon = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") params = { 'lat': lat, 'lon': lon, } if limit: params['limit'] = int(limit) if exactly_one: params['limit'] = 1 if language: params['lang'] = language url = "?".join((self.reverse_api, urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,094
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/photon.py
Photon._parse_json
(self, resources, exactly_one=True)
Parse display name, latitude, and longitude from a JSON response.
Parse display name, latitude, and longitude from a JSON response.
220
230
def _parse_json(self, resources, exactly_one=True): """ Parse display name, latitude, and longitude from a JSON response. """ if not len(resources['features']): # pragma: no cover return None if exactly_one: return self._parse_resource(resources['features'][0]) else: return [self._parse_resource(resource) for resource in resources['features']]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/photon.py#L220-L230
31
[ 0, 1, 2, 3, 4, 5 ]
66.666667
[ 6, 7, 9 ]
33.333333
false
20.833333
11
4
66.666667
1
def _parse_json(self, resources, exactly_one=True): if not len(resources['features']): # pragma: no cover return None if exactly_one: return self._parse_resource(resources['features'][0]) else: return [self._parse_resource(resource) for resource in resources['features']]
21,095
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/photon.py
Photon._parse_resource
(self, resource)
return Location(location, (latitude, longitude), resource)
232
247
def _parse_resource(self, resource): # Return location and coordinates tuple from dict. name_elements = ['name', 'housenumber', 'street', 'postcode', 'street', 'city', 'state', 'country'] name = [resource['properties'].get(k) for k in name_elements if resource['properties'].get(k)] location = ', '.join(name) latitude = resource['geometry']['coordinates'][1] longitude = resource['geometry']['coordinates'][0] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(location, (latitude, longitude), resource)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/photon.py#L232-L247
31
[ 0, 1 ]
12.5
[ 2, 5, 7, 9, 10, 11, 12, 13, 15 ]
56.25
false
20.833333
16
4
43.75
0
def _parse_resource(self, resource): # Return location and coordinates tuple from dict. name_elements = ['name', 'housenumber', 'street', 'postcode', 'street', 'city', 'state', 'country'] name = [resource['properties'].get(k) for k in name_elements if resource['properties'].get(k)] location = ', '.join(name) latitude = resource['geometry']['coordinates'][1] longitude = resource['geometry']['coordinates'][0] if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(location, (latitude, longitude), resource)
21,096
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/bing.py
Bing.__init__
( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: Should be a valid Bing Maps API key (https://www.microsoft.com/en-us/maps/create-a-bing-maps-key). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
37
85
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: Should be a valid Bing Maps API key (https://www.microsoft.com/en-us/maps/create-a-bing-maps-key). :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'dev.virtualearth.net' self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path) self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/bing.py#L37-L85
31
[ 0, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48 ]
28.571429
[]
0
false
24.705882
49
1
100
23
def __init__( self, api_key, *, scheme=None, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key domain = 'dev.virtualearth.net' self.geocode_api = '%s://%s%s' % (self.scheme, domain, self.geocode_path) self.reverse_api = '%s://%s%s' % (self.scheme, domain, self.reverse_path)
21,097
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/bing.py
Bing.geocode
( self, query, *, exactly_one=True, user_location=None, timeout=DEFAULT_SENTINEL, culture=None, include_neighborhood=None, include_country_code=False )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `addressLine`, `locality` (city), `adminDistrict` (state), `countryRegion`, or `postalCode`. :type query: str or dict :param bool exactly_one: Return one result or a list of results, if available. :param user_location: Prioritize results closer to this location. :type user_location: :class:`geopy.point.Point` :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str culture: Affects the language of the response, must be a two-letter country code. :param bool include_neighborhood: Sets whether to include the neighborhood field in the response. :param bool include_country_code: Sets whether to include the two-letter ISO code of the country in the response (field name 'countryRegionIso2'). :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
87
162
def geocode( self, query, *, exactly_one=True, user_location=None, timeout=DEFAULT_SENTINEL, culture=None, include_neighborhood=None, include_country_code=False ): """ Return a location point by address. :param query: The address or query you wish to geocode. For a structured query, provide a dictionary whose keys are one of: `addressLine`, `locality` (city), `adminDistrict` (state), `countryRegion`, or `postalCode`. :type query: str or dict :param bool exactly_one: Return one result or a list of results, if available. :param user_location: Prioritize results closer to this location. :type user_location: :class:`geopy.point.Point` :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str culture: Affects the language of the response, must be a two-letter country code. :param bool include_neighborhood: Sets whether to include the neighborhood field in the response. :param bool include_country_code: Sets whether to include the two-letter ISO code of the country in the response (field name 'countryRegionIso2'). :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } params['key'] = self.api_key else: params = { 'query': query, 'key': self.api_key } if user_location: params['userLocation'] = ",".join( (str(user_location.latitude), str(user_location.longitude)) ) if exactly_one: params['maxResults'] = 1 if culture: params['culture'] = culture if include_neighborhood is not None: params['includeNeighborhood'] = include_neighborhood if include_country_code: params['include'] = 'ciso2' # the only acceptable value url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/bing.py#L87-L162
31
[ 0 ]
1.315789
[ 46, 47, 53, 55, 59, 60, 63, 64, 65, 66, 67, 68, 69, 70, 72, 73, 74, 75 ]
23.684211
false
24.705882
76
7
76.315789
33
def geocode( self, query, *, exactly_one=True, user_location=None, timeout=DEFAULT_SENTINEL, culture=None, include_neighborhood=None, include_country_code=False ): if isinstance(query, collections.abc.Mapping): params = { key: val for key, val in query.items() if key in self.structured_query_params } params['key'] = self.api_key else: params = { 'query': query, 'key': self.api_key } if user_location: params['userLocation'] = ",".join( (str(user_location.latitude), str(user_location.longitude)) ) if exactly_one: params['maxResults'] = 1 if culture: params['culture'] = culture if include_neighborhood is not None: params['includeNeighborhood'] = include_neighborhood if include_country_code: params['include'] = 'ciso2' # the only acceptable value url = "?".join((self.geocode_api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,098
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/bing.py
Bing.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, culture=None, include_country_code=False )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str culture: Affects the language of the response, must be a two-letter country code. :param bool include_country_code: Sets whether to include the two-letter ISO code of the country in the response (field name 'countryRegionIso2'). :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
164
212
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, culture=None, include_country_code=False ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str culture: Affects the language of the response, must be a two-letter country code. :param bool include_country_code: Sets whether to include the two-letter ISO code of the country in the response (field name 'countryRegionIso2'). :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ point = self._coerce_point_to_string(query) params = {'key': self.api_key} if culture: params['culture'] = culture if include_country_code: params['include'] = 'ciso2' # the only acceptable value quoted_point = quote(point.encode('utf-8')) url = "?".join((self.reverse_api % dict(point=quoted_point), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/bing.py#L164-L212
31
[ 0 ]
2.040816
[ 35, 36, 37, 38, 39, 40, 42, 43, 46, 47, 48 ]
22.44898
false
24.705882
49
3
77.55102
24
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, culture=None, include_country_code=False ): point = self._coerce_point_to_string(query) params = {'key': self.api_key} if culture: params['culture'] = culture if include_country_code: params['include'] = 'ciso2' # the only acceptable value quoted_point = quote(point.encode('utf-8')) url = "?".join((self.reverse_api % dict(point=quoted_point), urlencode(params))) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,099
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/bing.py
Bing._parse_json
(self, doc, exactly_one=True)
Parse a location name, latitude, and longitude from an JSON response.
Parse a location name, latitude, and longitude from an JSON response.
214
264
def _parse_json(self, doc, exactly_one=True): """ Parse a location name, latitude, and longitude from an JSON response. """ status_code = doc.get("statusCode", 200) if status_code != 200: err = doc.get("errorDetails", "") if status_code == 401: raise GeocoderAuthenticationFailure(err) elif status_code == 403: raise GeocoderInsufficientPrivileges(err) elif status_code == 429: raise GeocoderRateLimited(err) elif status_code == 503: raise GeocoderUnavailable(err) else: raise GeocoderServiceError(err) resources = doc['resourceSets'][0]['resources'] if resources is None or not len(resources): return None def parse_resource(resource): """ Parse each return object. """ stripchars = ", \n" addr = resource['address'] address = addr.get('addressLine', '').strip(stripchars) city = addr.get('locality', '').strip(stripchars) state = addr.get('adminDistrict', '').strip(stripchars) zipcode = addr.get('postalCode', '').strip(stripchars) country = addr.get('countryRegion', '').strip(stripchars) city_state = join_filter(", ", [city, state]) place = join_filter(" ", [city_state, zipcode]) location = join_filter(", ", [address, place, country]) latitude = resource['point']['coordinates'][0] or None longitude = resource['point']['coordinates'][1] or None if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(location, (latitude, longitude), resource) if exactly_one: return parse_resource(resources[0]) else: return [parse_resource(resource) for resource in resources]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/bing.py#L214-L264
31
[ 0, 1, 2, 3 ]
7.843137
[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 18, 19, 20, 22, 26, 27, 29, 30, 31, 32, 33, 35, 36, 37, 39, 40, 41, 42, 43, 45, 47, 48, 50 ]
68.627451
false
24.705882
51
15
31.372549
1
def _parse_json(self, doc, exactly_one=True): status_code = doc.get("statusCode", 200) if status_code != 200: err = doc.get("errorDetails", "") if status_code == 401: raise GeocoderAuthenticationFailure(err) elif status_code == 403: raise GeocoderInsufficientPrivileges(err) elif status_code == 429: raise GeocoderRateLimited(err) elif status_code == 503: raise GeocoderUnavailable(err) else: raise GeocoderServiceError(err) resources = doc['resourceSets'][0]['resources'] if resources is None or not len(resources): return None def parse_resource(resource): stripchars = ", \n" addr = resource['address'] address = addr.get('addressLine', '').strip(stripchars) city = addr.get('locality', '').strip(stripchars) state = addr.get('adminDistrict', '').strip(stripchars) zipcode = addr.get('postalCode', '').strip(stripchars) country = addr.get('countryRegion', '').strip(stripchars) city_state = join_filter(", ", [city, state]) place = join_filter(" ", [city_state, zipcode]) location = join_filter(", ", [address, place, country]) latitude = resource['point']['coordinates'][0] or None longitude = resource['point']['coordinates'][1] or None if latitude and longitude: latitude = float(latitude) longitude = float(longitude) return Location(location, (latitude, longitude), resource) if exactly_one: return parse_resource(resources[0]) else: return [parse_resource(resource) for resource in resources]
21,100
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/smartystreets.py
LiveAddress.__init__
( self, auth_id, auth_token, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str auth_id: Valid `Auth ID` from SmartyStreets. :param str auth_token: Valid `Auth Token` from SmartyStreets. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
22
69
def __init__( self, auth_id, auth_token, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str auth_id: Valid `Auth ID` from SmartyStreets. :param str auth_token: Valid `Auth Token` from SmartyStreets. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( scheme='https', timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.auth_id = auth_id self.auth_token = auth_token domain = 'api.smartystreets.com' self.api = '%s://%s%s' % (self.scheme, domain, self.geocode_path)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/smartystreets.py#L22-L69
31
[ 0, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47 ]
31.25
[]
0
false
48.780488
48
1
100
21
def __init__( self, auth_id, auth_token, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( scheme='https', timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.auth_id = auth_id self.auth_token = auth_token domain = 'api.smartystreets.com' self.api = '%s://%s%s' % (self.scheme, domain, self.geocode_path)
21,101
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/smartystreets.py
LiveAddress.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, candidates=1 )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int candidates: An integer between 1 and 10 indicating the max number of candidate addresses to return if a valid address could be found. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
71
113
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, candidates=1 ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param int candidates: An integer between 1 and 10 indicating the max number of candidate addresses to return if a valid address could be found. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ if not (1 <= candidates <= 10): raise ValueError('candidates must be between 1 and 10') query = { 'auth-id': self.auth_id, 'auth-token': self.auth_token, 'street': query, 'candidates': candidates, } url = '{url}?{query}'.format(url=self.api, query=urlencode(query)) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/smartystreets.py#L71-L113
31
[ 0 ]
2.325581
[ 29, 30, 32, 38, 40, 41, 42 ]
16.27907
false
48.780488
43
2
83.72093
18
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, candidates=1 ): if not (1 <= candidates <= 10): raise ValueError('candidates must be between 1 and 10') query = { 'auth-id': self.auth_id, 'auth-token': self.auth_token, 'street': query, 'candidates': candidates, } url = '{url}?{query}'.format(url=self.api, query=urlencode(query)) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,102
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/smartystreets.py
LiveAddress._geocoder_exception_handler
(self, error)
115
121
def _geocoder_exception_handler(self, error): search = "no active subscriptions found" if isinstance(error, AdapterHTTPError): if search in str(error).lower(): raise GeocoderQuotaExceeded(str(error)) from error if search in (error.text or "").lower(): raise GeocoderQuotaExceeded(error.text) from error
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/smartystreets.py#L115-L121
31
[ 0 ]
14.285714
[ 1, 2, 3, 4, 5, 6 ]
85.714286
false
48.780488
7
5
14.285714
0
def _geocoder_exception_handler(self, error): search = "no active subscriptions found" if isinstance(error, AdapterHTTPError): if search in str(error).lower(): raise GeocoderQuotaExceeded(str(error)) from error if search in (error.text or "").lower(): raise GeocoderQuotaExceeded(error.text) from error
21,103
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/smartystreets.py
LiveAddress._parse_json
(self, response, exactly_one=True)
Parse responses as JSON objects.
Parse responses as JSON objects.
123
132
def _parse_json(self, response, exactly_one=True): """ Parse responses as JSON objects. """ if not len(response): return None if exactly_one: return self._format_structured_address(response[0]) else: return [self._format_structured_address(c) for c in response]
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/smartystreets.py#L123-L132
31
[ 0, 1, 2, 3 ]
40
[ 4, 5, 6, 7, 9 ]
50
false
48.780488
10
4
50
1
def _parse_json(self, response, exactly_one=True): if not len(response): return None if exactly_one: return self._format_structured_address(response[0]) else: return [self._format_structured_address(c) for c in response]
21,104
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/smartystreets.py
LiveAddress._format_structured_address
(self, address)
return Location( ", ".join((address['delivery_line_1'], address['last_line'])), (latitude, longitude) if latitude and longitude else None, address )
Pretty-print address and return lat, lon tuple.
Pretty-print address and return lat, lon tuple.
134
144
def _format_structured_address(self, address): """ Pretty-print address and return lat, lon tuple. """ latitude = address['metadata'].get('latitude') longitude = address['metadata'].get('longitude') return Location( ", ".join((address['delivery_line_1'], address['last_line'])), (latitude, longitude) if latitude and longitude else None, address )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/smartystreets.py#L134-L144
31
[ 0, 1, 2, 3 ]
36.363636
[ 4, 5, 6 ]
27.272727
false
48.780488
11
2
72.727273
1
def _format_structured_address(self, address): latitude = address['metadata'].get('latitude') longitude = address['metadata'].get('longitude') return Location( ", ".join((address['delivery_line_1'], address['last_line'])), (latitude, longitude) if latitude and longitude else None, address )
21,105
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/pickpoint.py
PickPoint.__init__
( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='api.pickpoint.io', scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None )
:param str api_key: PickPoint API key obtained at https://pickpoint.io. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Domain where the target Nominatim service is hosted. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0
17
68
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='api.pickpoint.io', scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): """ :param str api_key: PickPoint API key obtained at https://pickpoint.io. :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str domain: Domain where the target Nominatim service is hosted. :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 """ super().__init__( timeout=timeout, proxies=proxies, domain=domain, scheme=scheme, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/pickpoint.py#L17-L68
31
[ 0 ]
1.923077
[ 42, 51 ]
3.846154
false
66.666667
52
1
96.153846
26
def __init__( self, api_key, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, domain='api.pickpoint.io', scheme=None, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None ): super().__init__( timeout=timeout, proxies=proxies, domain=domain, scheme=scheme, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.api_key = api_key
21,106
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/pickpoint.py
PickPoint._construct_url
(self, base_api, params)
return super()._construct_url(base_api, params)
Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL.
Construct geocoding request url. Overridden.
70
82
def _construct_url(self, base_api, params): """ Construct geocoding request url. Overridden. :param str base_api: Geocoding function base address - self.api or self.reverse_api. :param dict params: Geocoding params. :return: string URL. """ params['key'] = self.api_key return super()._construct_url(base_api, params)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/pickpoint.py#L70-L82
31
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
84.615385
[ 11, 12 ]
15.384615
false
66.666667
13
1
84.615385
8
def _construct_url(self, base_api, params): params['key'] = self.api_key return super()._construct_url(base_api, params)
21,107
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames.__init__
( self, username, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, scheme='http' )
:param str username: GeoNames username, required. Sign up here: http://www.geonames.org/login :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. Note that at the time of writing GeoNames doesn't support `https`, so the default scheme is `http`. The value of :attr:`geopy.geocoders.options.default_scheme` is not respected. This parameter is present to make it possible to switch to `https` once GeoNames adds support for it.
38
102
def __init__( self, username, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, scheme='http' ): """ :param str username: GeoNames username, required. Sign up here: http://www.geonames.org/login :param int timeout: See :attr:`geopy.geocoders.options.default_timeout`. :param dict proxies: See :attr:`geopy.geocoders.options.default_proxies`. :param str user_agent: See :attr:`geopy.geocoders.options.default_user_agent`. :type ssl_context: :class:`ssl.SSLContext` :param ssl_context: See :attr:`geopy.geocoders.options.default_ssl_context`. :param callable adapter_factory: See :attr:`geopy.geocoders.options.default_adapter_factory`. .. versionadded:: 2.0 :param str scheme: See :attr:`geopy.geocoders.options.default_scheme`. Note that at the time of writing GeoNames doesn't support `https`, so the default scheme is `http`. The value of :attr:`geopy.geocoders.options.default_scheme` is not respected. This parameter is present to make it possible to switch to `https` once GeoNames adds support for it. """ super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.username = username domain = 'api.geonames.org' self.api = ( "%s://%s%s" % (self.scheme, domain, self.geocode_path) ) self.api_reverse = ( "%s://%s%s" % (self.scheme, domain, self.reverse_path) ) self.api_reverse_nearby = ( "%s://%s%s" % (self.scheme, domain, self.reverse_nearby_path) ) self.api_timezone = ( "%s://%s%s" % (self.scheme, domain, self.timezone_path) )
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L38-L102
31
[ 0, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64 ]
38.461538
[]
0
false
25.217391
65
1
100
28
def __init__( self, username, *, timeout=DEFAULT_SENTINEL, proxies=DEFAULT_SENTINEL, user_agent=None, ssl_context=DEFAULT_SENTINEL, adapter_factory=None, scheme='http' ): super().__init__( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=adapter_factory, ) self.username = username domain = 'api.geonames.org' self.api = ( "%s://%s%s" % (self.scheme, domain, self.geocode_path) ) self.api_reverse = ( "%s://%s%s" % (self.scheme, domain, self.reverse_path) ) self.api_reverse_nearby = ( "%s://%s%s" % (self.scheme, domain, self.reverse_nearby_path) ) self.api_timezone = ( "%s://%s%s" % (self.scheme, domain, self.timezone_path) )
21,108
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames.geocode
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, country=None, country_bias=None )
return self._call_geocoder(url, callback, timeout=timeout)
Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param country: Limit records to the specified countries. Two letter country code ISO-3166 (e.g. ``FR``). Might be a single string or a list of strings. :type country: str or list :param str country_bias: Records from the country_bias are listed first. Two letter country code ISO-3166. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return a location point by address.
104
157
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, country=None, country_bias=None ): """ Return a location point by address. :param str query: The address or query you wish to geocode. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param country: Limit records to the specified countries. Two letter country code ISO-3166 (e.g. ``FR``). Might be a single string or a list of strings. :type country: str or list :param str country_bias: Records from the country_bias are listed first. Two letter country code ISO-3166. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = [ ('q', query), ('username', self.username), ] if country_bias: params.append(('countryBias', country_bias)) if not country: country = [] if isinstance(country, str): country = [country] for country_item in country: params.append(('country', country_item)) if exactly_one: params.append(('maxRows', 1)) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L104-L157
31
[ 0 ]
1.851852
[ 33, 38, 39, 41, 42, 43, 44, 45, 46, 48, 49, 50, 51, 52, 53 ]
27.777778
false
25.217391
54
6
72.222222
22
def geocode( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, country=None, country_bias=None ): params = [ ('q', query), ('username', self.username), ] if country_bias: params.append(('countryBias', country_bias)) if not country: country = [] if isinstance(country, str): country = [country] for country_item in country: params.append(('country', country_item)) if exactly_one: params.append(('maxRows', 1)) url = "?".join((self.api, urlencode(params))) logger.debug("%s.geocode: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,109
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames.reverse
( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, feature_code=None, lang=None, find_nearby_type='findNearbyPlaceName' )
return self._call_geocoder(url, callback, timeout=timeout)
Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str feature_code: A GeoNames feature code :param str lang: language of the returned ``name`` element (the pseudo language code 'local' will return it in local language) Full list of supported languages can be found here: https://www.geonames.org/countries/ :param str find_nearby_type: A flag to switch between different GeoNames API endpoints. The default value is ``findNearbyPlaceName`` which returns the closest populated place. Another currently implemented option is ``findNearby`` which returns the closest toponym for the lat/lng query. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``.
Return an address by location point.
159
238
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, feature_code=None, lang=None, find_nearby_type='findNearbyPlaceName' ): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :param str feature_code: A GeoNames feature code :param str lang: language of the returned ``name`` element (the pseudo language code 'local' will return it in local language) Full list of supported languages can be found here: https://www.geonames.org/countries/ :param str find_nearby_type: A flag to switch between different GeoNames API endpoints. The default value is ``findNearbyPlaceName`` which returns the closest populated place. Another currently implemented option is ``findNearby`` which returns the closest toponym for the lat/lng query. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ try: lat, lng = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") if find_nearby_type == 'findNearbyPlaceName': # default if feature_code: raise ValueError( "find_nearby_type=findNearbyPlaceName doesn't support " "the `feature_code` param" ) params = self._reverse_find_nearby_place_name_params( lat=lat, lng=lng, lang=lang, ) url = "?".join((self.api_reverse, urlencode(params))) elif find_nearby_type == 'findNearby': if lang: raise ValueError( "find_nearby_type=findNearby doesn't support the `lang` param" ) params = self._reverse_find_nearby_params( lat=lat, lng=lng, feature_code=feature_code, ) url = "?".join((self.api_reverse_nearby, urlencode(params))) else: raise GeocoderQueryError( '`%s` find_nearby_type is not supported by geopy' % find_nearby_type ) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L159-L238
31
[ 0 ]
1.25
[ 44, 45, 46, 47, 49, 50, 51, 55, 60, 61, 62, 63, 66, 71, 73, 77, 78, 79 ]
22.5
false
25.217391
80
6
77.5
30
def reverse( self, query, *, exactly_one=True, timeout=DEFAULT_SENTINEL, feature_code=None, lang=None, find_nearby_type='findNearbyPlaceName' ): try: lat, lng = self._coerce_point_to_string(query).split(',') except ValueError: raise ValueError("Must be a coordinate pair or Point") if find_nearby_type == 'findNearbyPlaceName': # default if feature_code: raise ValueError( "find_nearby_type=findNearbyPlaceName doesn't support " "the `feature_code` param" ) params = self._reverse_find_nearby_place_name_params( lat=lat, lng=lng, lang=lang, ) url = "?".join((self.api_reverse, urlencode(params))) elif find_nearby_type == 'findNearby': if lang: raise ValueError( "find_nearby_type=findNearby doesn't support the `lang` param" ) params = self._reverse_find_nearby_params( lat=lat, lng=lng, feature_code=feature_code, ) url = "?".join((self.api_reverse_nearby, urlencode(params))) else: raise GeocoderQueryError( '`%s` find_nearby_type is not supported by geopy' % find_nearby_type ) logger.debug("%s.reverse: %s", self.__class__.__name__, url) callback = partial(self._parse_json, exactly_one=exactly_one) return self._call_geocoder(url, callback, timeout=timeout)
21,110
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames._reverse_find_nearby_params
(self, lat, lng, feature_code)
return params
240
248
def _reverse_find_nearby_params(self, lat, lng, feature_code): params = { 'lat': lat, 'lng': lng, 'username': self.username, } if feature_code: params['featureCode'] = feature_code return params
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L240-L248
31
[ 0 ]
11.111111
[ 1, 6, 7, 8 ]
44.444444
false
25.217391
9
2
55.555556
0
def _reverse_find_nearby_params(self, lat, lng, feature_code): params = { 'lat': lat, 'lng': lng, 'username': self.username, } if feature_code: params['featureCode'] = feature_code return params
21,111
geopy/geopy
ef48a8cbb85f842c0820333e53e7ebde7db382a3
geopy/geocoders/geonames.py
GeoNames._reverse_find_nearby_place_name_params
(self, lat, lng, lang)
return params
250
258
def _reverse_find_nearby_place_name_params(self, lat, lng, lang): params = { 'lat': lat, 'lng': lng, 'username': self.username, } if lang: params['lang'] = lang return params
https://github.com/geopy/geopy/blob/ef48a8cbb85f842c0820333e53e7ebde7db382a3/project31/geopy/geocoders/geonames.py#L250-L258
31
[ 0 ]
11.111111
[ 1, 6, 7, 8 ]
44.444444
false
25.217391
9
2
55.555556
0
def _reverse_find_nearby_place_name_params(self, lat, lng, lang): params = { 'lat': lat, 'lng': lng, 'username': self.username, } if lang: params['lang'] = lang return params
21,112