desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Test that a Volunteer can get their location_id updated from a
New Home Address: with no "person_id"'
| def testVolUpdateFromPersonAddress7(self):
| current.deployment_settings.hrm.location_vol = 'site_id'
(row, address_location_id, site_location_id) = self._testVolUpdateFromPersonAddress(site=False)
self.assertEqual(row.location_id, None)
|
'Test that a Volunteer can get their location_id updated from a
New Home Address: with no "person_id"'
| def testVolUpdateFromPersonAddress8(self):
| current.deployment_settings.hrm.location_vol = 'site_id'
(row, address_location_id, site_location_id) = self._testVolUpdateFromPersonAddress(site=True)
self.assertEqual(row.location_id, site_location_id)
|
'Set up organisation records'
| def setUp(self):
| s3db = current.s3db
auth.override = True
ptable = s3db.project_project
atable = s3db.project_activity
p1 = Row(name='Test Project 1', code='TP1')
p1_id = ptable.insert(**p1)
p1.update(id=p1_id)
a1 = Row(name='Test Activity 1', project_id=p1_id)
a1_id = atable.insert(**a1)... |
'Test the root organisation is set onaccept'
| def testRootOrgOnaccept(self):
| db = current.db
s3db = current.s3db
otable = s3db.org_organisation
organisation = Storage(name='RootOrgOnacceptTest')
record_id = otable.insert(**organisation)
self.assertNotEqual(record_id, None)
organisation['id'] = record_id
s3db.update_super(otable, organisation)
s3db.onaccept(ot... |
'Test the root organisation is updated when adding a branch link'
| def testRootOrgUpdate(self):
| db = current.db
s3db = current.s3db
otable = s3db.org_organisation
ltable = s3db.org_organisation_branch
org1 = Storage(name='RootOrgUpdateTest1')
org1_id = otable.insert(**org1)
self.assertNotEqual(org1_id, None)
org1['id'] = org1_id
s3db.update_super(otable, org1)
s3db.onaccept... |
'Verify import items without name match create new records'
| def testNoNameMatch(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = (((otable.name == 'DeDupOrgD') | (otable.name == 'DeDupBranch5')) & (otable.deleted != True))
rows = db(query).select(otable.id)
assertEqual(len... |
'Test update detection for single name match with no
parent specified in import source (should always update the match)'
| def testSingleNameMatchWithoutParentItem(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = (((otable.name == 'DeDupOrgB') | (otable.name == 'DeDupBranch1')) & (otable.deleted != True))
rows = db(query).select(otable.id, otable.comments)
... |
'Test update detection for single name match with parent
specified in source (matching parent => should update branch)'
| def testSingleNameMatchWithParentItemMatch(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = (otable.name == 'DeDupBranch4')
rows = db(query).select(otable.id, otable.comments)
assertEqual(len(rows), 1)
assertEqual(rows.first().comme... |
'Test update detection for single name match with parent
specified in source (different parent => should create new branch)'
| def testSingleNameMatchWithParentItemMismatch(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = (otable.name == 'DeDupBranch4')
rows = db(query).select(otable.id, otable.comments)
assertEqual(len(rows), 1)
assertEqual(rows.first().comme... |
'Test update detection for multiple name matches with parent
specified in source (matching parent => should update branch)'
| def testMultipleNameMatchesWithParentItemMatch(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
assertTrue = self.assertTrue
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = (otable.name == 'DeDupBranch2')
rows = db(query).select(otable.id, otable.comments)
assertEqual(len(rows), 2)
... |
'Test update detection for multiple name matches with parent
specified in source (different parent => should create new branch)'
| def testMultipleNameMatchesWithParentItemMismatch(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
assertTrue = self.assertTrue
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = (otable.name == 'DeDupBranch2')
rows = db(query).select(otable.id, otable.comments)
assertEqual(len(rows), 2)
... |
'Test update detection for multiple name matches with parent
specified by source (duplicate match under the same parent =>
should reject the import item)'
| def testMultipleNameMatchesWithParentItemAmbiguous(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
assertNotEqual = self.assertNotEqual
assertTrue = self.assertTrue
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = (otable.name == 'DeDupBranch3')
rows = db(query).select(otable.id, otable.... |
'Test update detection for multiple name matches without parent
in source (single root org match => should update the root org)'
| def testMultipleNameMatchesWithoutParentItemRootMatch(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = ((otable.name == 'DeDupOrgA') & (otable.deleted != True))
rows = db(query).select(otable.id, otable.comments)
assertEqual(len(rows), 2)
for ... |
'Test update detection for multiple name matches if no parent
item has been specified in source (ambiguous => should reject
the item)'
| def testMultipleNameMatchesWithoutParentItemAmbiguous(self):
| db = current.db
s3db = current.s3db
assertEqual = self.assertEqual
assertNotEqual = self.assertNotEqual
assertTrue = self.assertTrue
otable = s3db.org_organisation
btable = s3db.org_organisation_branch
query = ((otable.name == 'DeDupBranch2') & (otable.deleted != True))
rows = db(que... |
'Set up location records'
| def setUp(self):
| auth = current.auth
auth.s3_impersonate('admin@example.com')
s3db = current.s3db
gtable = s3db.gis_location
gis0 = Storage(name='Test Country', level='L0')
gis0_id = gtable.insert(**gis0)
location_code = Storage()
location_ids = Storage()
location_code[gis0_id] = 'gis0'
locati... |
'Helper function to approve the vulnerability_data record that has
been inserted and then rebuild the relevant aggregates
@param record_id: the id of the vulnerability_data record created'
| @staticmethod
def approve_record(record_id):
| s3db = current.s3db
resource = s3db.resource('vulnerability_data', id=record_id, unapproved=True)
resource.approve()
rows = resource.select(fields=['data_id', 'parameter_id', 'date', 'location_id', 'value'], as_rows=True)
s3db.vulnerability_update_aggregates(rows)
|
'Test that the vulnerability_aggregate records are being generated correctly.
Because the vulnerability_aggregate records depend on earlier results it is
important that all these test are in the same test so that the
interdependence of the indicators can be checked.
Summary of test data:
1) Indicator 1 for gis4_1 in 20... | def testVulnerability_aggregate(self):
| from datetime import date
db = current.db
s3db = current.s3db
vtable = s3db.vulnerability_data
approve_record = self.approve_record
indicators = self.indicators
location_ids = self.location_ids
update_super = s3db.update_super
validateAggregateData = self.validateAggregateData
st... |
'We check against three rules:
1) The aggregate record that matches the newly inserted record
* Use indicator and location to find the record. It should
have a type of 1 for the actual period other periods will
have types of 1 or 3, and the data may vary
2) The records aggregate for each parent location
* The type will... | def validateAggregateData(self, step, actual_date, indicator_id, location_id, expected):
| from dateutil.rrule import rrule, YEARLY
db = current.db
s3db = current.s3db
aggregated_period = s3db.vulnerability_aggregated_period
(first_period, dummy) = aggregated_period(actual_date)
(last_period, dummy) = aggregated_period()
atable = db.vulnerability_aggregate
fields = [atable.agg... |
'Set up organisation records'
| def setUp(self):
| auth = current.auth
s3db = current.s3db
auth.override = True
otable = s3db.org_organisation
org1 = Storage(name='Test PR Organisation 1', acronym='TPO', country='UK', website='http://tpo.example.org')
org1_id = otable.insert(**org1)
org1.update(id=org1_id)
s3db.update_super(otab... |
'Construct a fake import item'
| def import_item(self, person, email=None, sms=None):
| from s3.s3import import S3ImportItem
def item(tablename, data):
return Storage(id=None, method=None, tablename=tablename, data=data, components=[], METHOD=S3ImportItem.METHOD)
import_item = item('pr_person', person)
if email:
import_item.components.append(item('pr_contact', Storage(conta... |
'Test that validator for mobile phone number is applied'
| def testMobilePhoneNumberValidationStandard(self):
| current.deployment_settings.msg.require_international_phone_numbers = False
from s3db.pr import PRContactModel
onvalidation = PRContactModel.pr_contact_onvalidation
form = Storage(vars=Storage(contact_method='SMS'))
form.errors = Storage()
form.vars.value = '0368172634'
onvalidation(form)
... |
'Test that validator for mobile phone number is applied'
| def testMobilePhoneNumberValidationInternational(self):
| current.deployment_settings.msg.require_international_phone_numbers = True
from s3db.pr import PRContactModel
onvalidation = PRContactModel.pr_contact_onvalidation
form = Storage(vars=Storage(contact_method='SMS'))
form.errors = Storage()
form.vars.value = '+46-73-3847589'
onvalidation(form)... |
'Test that validator for mobile phone number is applied during import'
| def testMobilePhoneNumberImportValidationStandard(self):
| s3db = current.s3db
current.deployment_settings.msg.require_international_phone_numbers = False
xmlstr = '\n<s3xml>\n <resource name="pr_person" uuid="CONTACTVALIDATORTESTPERSON1">\n <data field="first_name">ContactValidatorTestPerson1</data>\n ... |
'Test that validator for mobile phone number is applied during import'
| def testMobilePhoneNumberImportValidationInternational(self):
| s3db = current.s3db
current.deployment_settings.msg.require_international_phone_numbers = True
xmlstr = '\n<s3xml>\n <resource name="pr_person" uuid="CONTACTVALIDATORTESTPERSON2">\n <data field="first_name">ContactValidatorTestPerson2</data>\n ... |
'Set up location records'
| def setUp(self):
| auth = current.auth
auth.override = True
self.location_code = Storage()
self.location_ids = Storage()
s3db = current.s3db
|
'Test homepage() navigation item'
| def testHomepageFunction(self):
| hp = homepage('pr')
self.assertTrue((hp is not None))
hp = homepage('nonexistent')
self.assertTrue((hp is not None))
self.assertFalse(hp.check_active())
rendered_hp = hp.xml()
self.assertEqual(rendered_hp, '')
|
'Test S3PopupLink'
| def testPopupLink(self):
| auth = current.auth
deployment_settings = current.deployment_settings
comment = S3PopupLink(c='pr', f='person')
self.assertEqual(comment.check_active(), deployment_settings.has_module('pr'))
self.assertEqual(comment.method, 'create')
from s3.s3crud import S3CRUD
crud_string = S3CRUD.crud_str... |
'Constructor
@param channel: Facebook channel (Row) with API credentials:
{app_id=clientID, app_secret=clientSecret}'
| def __init__(self, channel):
| from facebook import GraphAPI, GraphAPIError
self.GraphAPI = GraphAPI
self.GraphAPIError = GraphAPIError
request = current.request
settings = current.deployment_settings
scope = 'email,user_about_me,user_location,user_photos,user_relationships,user_birthday,user_website,create_event,user_events,... |
'Overriding to produce a different redirect_uri'
| def login_url(self, next='/'):
| if (not self.accessToken()):
request = current.request
session = current.session
if (not request.vars.code):
session.redirect_uri = self.args['redirect_uri']
data = {'redirect_uri': session.redirect_uri, 'response_type': 'code', 'client_id': self.client_id}
... |
'Returns the user using the Graph API.'
| def get_user(self):
| token = self.accessToken()
if (not token):
return None
if (not self.graph):
self.graph = self.GraphAPI(token)
user = None
try:
user = self.graph.get_object_c('me')
except self.GraphAPIError:
current.session.token = None
self.graph = None
user_dict = No... |
'Constructor
@param channel: dict with Google API credentials:
{id=clientID, secret=clientSecret}'
| def __init__(self, channel):
| settings = current.deployment_settings
scope = 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'
user_agent = 'google-api-client-python-plus-cmdline/1.0'
redirect_uri = ('%s/%s/default/google/login' % (settings.get_base_public_url(), current.request.app... |
'Build the url opener for managing HTTP Basic Authentication'
| def __build_url_opener(self, uri):
| auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None, uri, self.client_id, self.client_secret)
opener = urllib2.build_opener(auth_handler)
return opener
|
'Return the access token generated by the authenticating server.
If token is already in the session that one will be used.
Otherwise the token is fetched from the auth server.'
| def accessToken(self):
| session = current.session
token = session.token
if (token and ('expires' in token)):
expires = token['expires']
if ((expires == 0) or (expires > time.time())):
return token['access_token']
code = session.code
if code:
data = {'client_id': self.client_id, 'client_s... |
'Overriding to produce a different redirect_uri'
| def login_url(self, next='/'):
| if (not self.accessToken()):
request = current.request
if (not request.vars.code):
session = current.session
session.redirect_uri = self.args['redirect_uri']
data = {'redirect_uri': session.redirect_uri, 'response_type': 'code', 'client_id': self.client_id}
... |
'Returns the user using the Graph API.'
| def get_user(self):
| token = self.accessToken()
if (not token):
return None
user = None
try:
user = self.call_api(token)
except Exception as e:
current.session.token = None
user_dict = None
if user:
table = current.auth.settings.table_user
query = (table.email == user['ema... |
'Get the user info from the API
@param token: the current access token
@return: user info (dict)'
| @classmethod
def call_api(cls, token):
| api_response = urllib.urlopen(('%s?access_token=%s' % (cls.API_URL, token)))
user = json.loads(api_response.read())
if (not user):
user = None
current.session.token = None
return user
|
'Constructor
@param channel: dict with Humanitarian.ID API credentials:
{id=clientID, secret=clientSecret}'
| def __init__(self, channel):
| request = current.request
settings = current.deployment_settings
scope = 'profile'
redirect_uri = ('%s/%s/default/humanitarian_id/login' % (settings.get_base_public_url(), request.application))
OAuthAccount.__init__(self, client_id=channel['id'], client_secret=channel['secret'], auth_url=self.AUTH_U... |
'Build the url opener for managing HTTP Basic Authentication'
| def __build_url_opener(self, uri):
| auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None, uri, self.client_id, self.client_secret)
opener = urllib2.build_opener(auth_handler)
return opener
|
'Return the access token generated by the authenticating server.
If token is already in the session that one will be used.
Otherwise the token is fetched from the auth server.'
| def accessToken(self):
| session = current.session
token = session.token
if (token and ('expires' in token)):
expires = token['expires']
if ((expires == 0) or (expires > time.time())):
return token['access_token']
code = session.code
if code:
data = {'client_id': self.client_id, 'client_s... |
'Overriding to produce a different redirect_uri'
| def login_url(self, next='/'):
| if (not self.accessToken()):
request = current.request
session = current.session
if (not request.vars.code):
session.redirect_uri = self.args['redirect_uri']
data = {'redirect_uri': session.redirect_uri, 'response_type': 'code', 'client_id': self.client_id}
... |
'Returns the user using the Graph API.'
| def get_user(self):
| token = self.accessToken()
if (not token):
return None
session = current.session
user = None
try:
user = self.call_api(token)
except Exception as e:
session.token = None
user_dict = None
if user:
table = current.auth.settings.table_user
query = (ta... |
'Get the user info from the API
@param token: the current access token
@return: user info (dict)'
| @classmethod
def call_api(cls, token):
| api_response = urllib.urlopen(('%s?access_token=%s' % (cls.API_URL, token)))
user = json.loads(api_response.read())
if (not user):
user = None
current.session.token = None
return user
|
'Encode a GeoJSON dict into an GeoJSON object.
Assumes the caller knows that the dict should satisfy a GeoJSON type.'
| @classmethod
def to_instance(cls, ob, default=None, strict=False):
| if ((ob is None) and (default is not None)):
instance = default()
elif isinstance(ob, GeoJSON):
instance = ob
else:
mapping = to_mapping(ob)
d = dict(((str(k), mapping[k]) for k in mapping))
try:
type_ = d.pop('type')
geojson_factory = getattr(... |
'Layout Method (Item Renderer)'
| @staticmethod
def layout(item):
| if ((not item.authorized) and (not item.opts.always_display)):
item.enabled = False
item.visible = False
elif ((item.enabled is None) or item.enabled):
item.enabled = True
item.visible = True
if (item.enabled and item.visible):
items = item.render_components()
... |
'Render special active items'
| @staticmethod
def checkbox_item(item):
| name = item.label
link = item.url()
_id = name['id']
if ('name' in name):
_name = name['name']
else:
_name = ''
if ('value' in name):
_value = name['value']
else:
_value = False
if ('request_type' in name):
_request_type = name['request_type']
... |
'Layout Method (Item Renderer)'
| @staticmethod
def layout(item):
| if (not item.authorized):
enabled = False
visible = False
elif ((item.enabled is None) or item.enabled):
enabled = True
visible = True
if (enabled and visible):
if (item.parent is not None):
if (item.enabled and item.authorized):
attr = dic... |
'Layout Method (Item Renderer)'
| @staticmethod
def layout(item):
| if item.enabled:
if (item.parent is not None):
output = A(SPAN(item.label), _class=('zocial %s' % item.opts.api), _href=item.url(), _title=item.opts.get('title', item.label))
else:
items = item.render_components()
if items:
output = DIV(items, _... |
'Layout Method (Item Renderer)'
| @staticmethod
def layout(item):
| if (item.parent is not None):
return LI(_class='divider hide-for-small')
else:
return None
|
'Layout Method (Item Renderer)'
| @staticmethod
def layout(item):
| if ((not item.authorized) and (not item.opts.always_display)):
item.enabled = False
item.visible = False
elif ((item.enabled is None) or item.enabled):
item.enabled = True
item.visible = True
if (item.enabled and item.visible):
items = item.render_components()
... |
'Constructor
@param c: the target controller
@param f: the target function
@param t: the target table (defaults to c_f)
@param m: the URL method (will be appended to args)
@param args: the argument list
@param vars: the request vars (format="popup" will be added automatically)
@param label: the link label (falls back t... | def __init__(self, label=None, c=None, f=None, t=None, m='create', args=None, vars=None, info=None, title=None, tooltip=None):
| if (label is None):
label = title
if (info is None):
info = title
if (c is None):
c = current.request.controller
if (label is None):
if (t is None):
t = ('%s_%s' % (c, f))
if (m == 'create'):
label = S3CRUD.crud_string(t, 'label_create')
... |
'Layout for popup link'
| @staticmethod
def layout(item):
| if (not item.authorized):
return None
if current.deployment_settings.get_ui_use_button_icons():
from s3.s3widgets import ICON
label = (ICON('add'), item.label)
else:
label = item.label
popup_link = A(label, _href=item.url(format='popup'), _class='s3_add_resource_link', _i... |
'Render this link for an inline component'
| @staticmethod
def inline(item):
| if (not item.authorized):
return None
popup_link = A(item.label, _href=item.url(format='popup'), _class='s3_add_resource_link action-lnk', _id=('%s_%s_add' % (item.vars['caller'], item.function)), _target='top', _title=item.opts.info)
return DIV(popup_link, _class='s3_inline_add_resource_link')
|
'Initialize an Open MapQuest geocoder with location-specific
address information, no API Key is needed by the Nominatim based
platform.
``format_string`` is a string containing \'%s\' where the string to
geocode should be interpolated before querying the geocoder.
For example: \'%s, Mountain View, CA\'. The default is ... | def __init__(self, api_key='', format_string='%s'):
| self.api_key = api_key
self.format_string = format_string
self.url = 'http://open.mapquestapi.com/nominatim/v1/search?format=json&%s'
|
'Parse display name, latitude, and longitude from an JSON response.'
| def parse_json(self, page, exactly_one=True):
| if (not isinstance(page, basestring)):
page = decode_page(page)
resources = json.loads(page)
if (exactly_one and (len(resources) != 1)):
from warnings import warn
warn(("Didn't find exactly one resource!" + ('(Found %d.), use exactly_one=False\n' % len(resources)... |
'Initialize a customized Bing geocoder with location-specific
address information and your Bing Maps API key.
``api_key`` should be a valid Bing Maps API key.
``format_string`` is a string containing \'%s\' where the string to
geocode should be interpolated before querying the geocoder.
For example: \'%s, Mountain View... | def __init__(self, api_key, format_string='%s', output_format=None):
| if (output_format != None):
from warnings import warn
warn(('geopy.geocoders.bing.Bing: The `output_format` parameter is deprecated ' + 'and ignored.'), DeprecationWarning)
self.api_key = api_key
self.format_string = format_string
self.url = 'http://dev.virtualearth.... |
'Parse a location name, latitude, and longitude from an JSON response.'
| def parse_json(self, page, exactly_one=True):
| if (not isinstance(page, basestring)):
page = decode_page(page)
doc = json.loads(page)
resources = doc['resourceSets'][0]['resources']
if (exactly_one and (len(resources) != 1)):
raise ValueError(("Didn't find exactly one resource! (Found %d.)" % len(resources)))
de... |
'Initialize a geocoder that can parse MediaWiki pages with the GIS
extension enabled.
``format_url`` is a URL string containing \'%s\' where the page name to
request will be interpolated. For example: \'http://www.wiki.com/wiki/%s\'
``transform_string`` is a callable that will make appropriate
replacements to the input... | def __init__(self, format_url, transform_string=None):
| self.format_url = format_url
if callable(transform_string):
self.transform_string = transform_string
|
'Do the WikiMedia dance: replace spaces with underscores.'
| @classmethod
def transform_string(cls, string):
| return string.replace(' ', '_')
|
'Initialize a customized Google geocoder.
API authentication is only required for Google Maps Premier customers.
``domain`` should be the localized Google Maps domain to connect to. The default
is \'maps.google.com\', but if you\'re geocoding address in the UK (for
example), you may want to set it to \'maps.google.co.u... | def __init__(self, domain='maps.googleapis.com', protocol='http', client_id=None, secret_key=None):
| super(GoogleV3, self).__init__()
if (protocol not in ('http', 'https')):
raise ValueError, 'Supported protocols are http and https.'
if (client_id and (not secret_key)):
raise ValueError, 'Must provide secret_key with client_id.'
if (secret_key and (not client_... |
'Returns a Premier account signed url.'
| def get_signed_url(self, params):
| params['client'] = self.client_id
url_params = {'protocol': self.protocol, 'domain': self.domain, 'params': urlencode(params)}
secret = base64.urlsafe_b64decode(self.secret_key)
url_params['url_part'] = ('/maps/api/geocode/json?%(params)s' % url_params)
signature = hmac.new(secret, url_params['url_p... |
'Returns a standard geocoding api url.'
| def get_url(self, params):
| return ('http://%(domain)s/maps/api/geocode/json?%(params)s' % {'domain': self.domain, 'params': urlencode(params)})
|
'Fetches the url and returns the result.'
| def geocode_url(self, url, exactly_one=True):
| util.logger.debug(('Fetching %s...' % url))
page = urlopen(url)
return self.parse_json(page, exactly_one)
|
'Geocode an address.
``string`` (required) The address that you want to geocode.
``bounds`` (optional) The bounding box of the viewport within which
to bias geocode results more prominently.
``region`` (optional) The region code, specified as a ccTLD
("top-level domain") two-character value.
``language`` (optional) The... | def geocode(self, string, bounds=None, region=None, language=None, sensor=False, exactly_one=True):
| if isinstance(string, unicode):
string = string.encode('utf-8')
params = {'address': (self.format_string % string), 'sensor': str(sensor).lower()}
if bounds:
params['bounds'] = bounds
if region:
params['region'] = region
if language:
params['language'] = language
... |
'Reverse geocode a point.
``point`` (required) The textual latitude/longitude value for which
you wish to obtain the closest, human-readable address
``language`` (optional) The language in which to return results.
See the supported list of domain languages. Note that we often update
supported languages so this list may... | def reverse(self, point, language=None, sensor=False, exactly_one=False):
| params = {'latlng': point, 'sensor': str(sensor).lower()}
if language:
params['language'] = language
if (not self.premier):
url = self.get_url(params)
else:
url = self.get_signed_url(params)
return self.geocode_url(url, exactly_one)
|
'Returns location, (latitude, longitude) from json feed.'
| def parse_json(self, page, exactly_one=True):
| if (not isinstance(page, basestring)):
page = util.decode_page(page)
self.doc = json.loads(page)
places = self.doc.get('results', [])
if (not places):
check_status(self.doc.get('status'))
return None
elif (exactly_one and (len(places) != 1)):
raise ValueError(("Didn't... |
'Initialize a customized Google geocoder with location-specific
address information and your Google Maps API key.
``api_key`` should be a valid Google Maps API key. Required as per Google Geocoding API
V2 docs, but the API works without a key in practice.
``domain`` should be the localized Google Maps domain to connect... | def __init__(self, api_key=None, domain='maps.googleapis.com', format_string='%s'):
| warn((((('geopy.geocoders.google: The `geocoders.google.Google` geocoder uses the ' + 'older "V2" API and is deprecated and may be broken at any time. A ') + 'geocoder utilizing the "V3" API is available at ') + '`geocoders.googlev3... |
'Initialize a MapQuest geocoder with address information and
MapQuest API key.'
| def __init__(self, api_key='', format_string='%s'):
| self.api_key = api_key
self.format_string = format_string
self.url = 'http://www.mapquestapi.com/geocoding/v1/address'
|
'Parse display name, latitude, and longitude from an JSON response.'
| def parse_json(self, page, exactly_one=True):
| if (not isinstance(page, basestring)):
page = decode_page(page)
resources = json.loads(page)
statuscode = resources.get('info').get('statuscode')
if (statuscode == 403):
return 'Bad API Key'
resources = resources.get('results')[0].get('locations')
if (exactly_one and (len(r... |
'Parse the URL of the RDF link from the <head> of ``page``.'
| def parse_rdf_link(self, page, mime_type='application/rdf+xml'):
| soup = BeautifulSoup(page)
link = soup.head.find('link', rel='alternate', type=mime_type)
return ((link and link['href']) or None)
|
'Normalize semantic attribute and relation names by replacing spaces
with underscores and capitalizing the result.'
| def transform_semantic(self, string):
| return string.replace(' ', '_').capitalize()
|
'Backwards compatibility with geopy 0.93 tuples.'
| def __getitem__(self, index):
| return (self.name, self.point)[index]
|
'Create and return a Point instance from a string containing latitude
and longitude, and optionally, altitude.
Latitude and longitude must be in degrees and may be in decimal form
or indicate arcminutes and arcseconds (labeled with Unicode prime and
double prime, ASCII quote and double quote or \'m\' and \'s\'). The de... | @classmethod
def from_string(cls, string):
| match = re.match(cls.POINT_PATTERN, string)
if match:
latitude = cls.parse_degrees(match.group('latitude_degrees'), match.group('latitude_arcminutes'), match.group('latitude_arcseconds'), match.group('latitude_direction'))
longitude = cls.parse_degrees(match.group('longitude_degrees'), match.gro... |
'Create and return a new Point instance from any iterable with 0 to
3 elements. The elements, if present, must be latitude, longitude,
and altitude, respectively.'
| @classmethod
def from_sequence(cls, seq):
| args = tuple(islice(seq, 4))
return cls(*args)
|
'Create and return a new Point instance from another Point instance.'
| @classmethod
def from_point(cls, point):
| return cls(point.latitude, point.longitude, point.altitude)
|
'Construct a new Waypoint from dictionaries of attribute and child
element names corresponding to GPX waypoint information, as parsed
by the `GPX` class.'
| @classmethod
def from_xml_names(cls, attrs, children):
| lat = attrs['lat']
lon = attrs['lon']
if ('ele' in children):
ele = children['ele']
else:
ele = None
w = cls(lat, lon, ele)
if ('time' in children):
w.timestamp = children['time']
if ('name' in children):
w.name = children['name']
if ('desc' in children):
... |
'Fetches the given object from the graph.'
| def get_object(self, id, **args):
| return self.request(id, args)
|
'Fetches all of the given object from the graph.
We return a map from ID to object. If any of the IDs are
invalid, we raise an exception.'
| def get_objects(self, ids, **args):
| args['ids'] = ','.join(ids)
return self.request('', args)
|
'Fetchs the connections for given object.'
| def get_connections(self, id, connection_name, **args):
| return self.request(((id + '/') + connection_name), args)
|
'Writes the given object to the graph, connected to the given parent.
For example,
graph.put_object("me", "feed", message="Hello, world")
writes "Hello, world" to the active user\'s wall. Likewise, this
will comment on a the first post of the active user\'s feed:
feed = graph.get_connections("me", "feed")
post = feed["... | def put_object(self, parent_object, connection_name, **data):
| assert self.access_token, 'Write operations require an access token'
return self.request(('%s/%s' % (parent_object, connection_name)), post_args=data, method='POST')
|
'Writes a wall post to the given profile\'s wall.
We default to writing to the authenticated user\'s wall if no
profile_id is specified.
attachment adds a structured attachment to the status message
being posted to the Wall. It should be a dictionary of the form:
{"name": "Link name"
"link": "http://www.example.com/",
... | def put_wall_post(self, message, attachment={}, profile_id='me'):
| return self.put_object(profile_id, 'feed', message=message, **attachment)
|
'Writes the given comment on the given post.'
| def put_comment(self, object_id, message):
| return self.put_object(object_id, 'comments', message=message)
|
'Likes the given post.'
| def put_like(self, object_id):
| return self.put_object(object_id, 'likes')
|
'Deletes the object with the given ID from the graph.'
| def delete_object(self, id):
| self.request(id, method='DELETE')
|
'Deletes the Request with the given ID for the given user.'
| def delete_request(self, user_id, request_id):
| self.request(('%s_%s' % (request_id, user_id)), method='DELETE')
|
'Uploads an image using multipart/form-data.
image=File like object for the image
message=Caption for your image
album_id=None posts to /me/photos which uses or creates and uses
an album for your application.'
| def put_photo(self, image, message=None, album_id=None, **kwargs):
| object_id = (album_id or 'me')
kwargs.update({'message': message})
self.request(object_id, post_args=kwargs, files={'file': image}, method='POST')
|
'Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.'
| def request(self, path, args=None, post_args=None, files=None, method=None):
| args = (args or {})
if self.access_token:
if (post_args is not None):
post_args['access_token'] = self.access_token
else:
args['access_token'] = self.access_token
try:
response = requests.request((method or 'GET'), ('https://graph.facebook.com/%s' % path), tim... |
'FQL query.
Example query: "SELECT affiliations FROM user WHERE uid = me()"'
| def fql(self, query):
| self.request('fql', {'q': query})
|
'Get the application\'s access token as a string.'
| def get_app_access_token(self, app_id, app_secret):
| args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret}
return self.request('oauth/access_token', args=args)['access_token']
|
'Get an access token from the "code" returned from an OAuth dialog.
Returns a dict containing the user-specific access token and its
expiration date (if applicable).'
| def get_access_token_from_code(self, code, redirect_uri, app_id, app_secret):
| args = {'code': code, 'redirect_uri': redirect_uri, 'client_id': app_id, 'client_secret': app_secret}
return self.request('oauth/access_token', args)
|
'Extends the expiration time of a valid OAuth access token. See
<https://developers.facebook.com/roadmap/offline-access-removal/
#extend_token>'
| def extend_access_token(self, app_id, app_secret):
| args = {'client_id': app_id, 'client_secret': app_secret, 'grant_type': 'fb_exchange_token', 'fb_exchange_token': self.access_token}
return self.request('access_token', args=args)
|
'Preparation before migration
@param moves : List of dicts {tablename: [(fieldname, new_tablename, link_fieldname)]} to move a field from 1 table to another
- fieldname can be a tuple if the fieldname changes: (fieldname, new_fieldname)
@param news : List of dicts {new_tablename: {\'lookup_field\': \'\',
\'tab... | def prep(self, moves=None, news=None, ondeletes=None, strbools=None, strints=None, add_notnulls=None, remove_foreigns=None, remove_uniques=None):
| self.moves = moves
self.news = news
self.strbools = strbools
self.strints = strints
self.backup()
if add_notnulls:
for (tablename, fieldname) in add_notnulls:
self.add_notnull(tablename, fieldname)
if remove_foreigns:
for (tablename, fieldname) in remove_foreigns:... |
'Backup the database to a local SQLite database
@ToDo: Option to use a temporary DB in Postgres/MySQL as this takes
too long for a large DB'
| def backup(self):
| moves = self.moves
news = self.news
strints = self.strints
strbools = self.strbools
if ((not moves) and (not news) and (not strbools) and (not strints)):
return
import os
db = self.db
folder = ('%s/databases/backup' % current.request.folder)
if os.path.exists(folder):
... |
'Update the Eden code'
| def pull(self, version=None):
| cwd = os.getcwd()
folder = current.request.folder
os.chdir(os.path.join(cwd, folder))
remove_compiled_application(folder)
subprocess.call(['git', 'reset', '--hard', 'HEAD'])
old_version = subprocess.check_output(['git', 'describe', '--always', 'HEAD'])
self.old_version = old_version.strip()
... |
'Find the upgrade script(s) to run'
| def find_script(self):
| old_version = self.old_version
if (not old_version):
return
new_version = subprocess.check_output(['git', 'describe', '--always', 'HEAD'])
new_version = new_version.strip()
path = os.path.join(request.folder, 'static', 'scripts', 'upgrade')
|
'Execute all the models/'
| def run_model(self):
| if (not hasattr(current, 'db')):
run_models_in(self.environment)
|
'Compile the Eden code'
| def compile(self):
| self.run_model()
from gluon.fileutils import up
request = current.request
os_path = os.path
join = os_path.join
settings = current.deployment_settings
s3 = current.response.s3
s3.views = views = {}
s3.theme = theme = settings.get_theme()
if (theme != 'default'):
folder = ... |
'Perform an automatic database migration'
| def migrate(self):
| self.run_model()
current.s3db.load_all_models()
|
'Refresh the Permissions'
| def refresh_roles(self):
| current.s3db.s3_permission.truncate()
auth = current.auth
acl = auth.permission
auth.s3_update_acls('ANONYMOUS', {'t': 'org_organisation', 'uacl': acl.READ}, {'c': 'org', 'f': 'sites_for_org', 'uacl': acl.READ})
current.response.s3.crud_strings = Storage()
from s3 import S3BulkImporter
bi = ... |
'Cleanup after migration
@param moves : List of dicts {tablename: [(fieldname, new_tablename, link_fieldname)]} to move a field from 1 table to another
- fieldname can be a tuple if the fieldname changes: (fieldname, new_fieldname)
@param news : List of dicts {new_tablename: {\'lookup_field\': \'\',
\'tables\'... | def post(self, moves=None, news=None, strbools=None, strints=None):
| db = self.db
folder = ('%s/databases/backup' % current.request.folder)
db_bak = DAL('sqlite://backup.db', folder=folder, auto_import=True, migrate=False)
if moves:
for tablename in moves:
table = db_bak[tablename]
(fieldname, new_tablename, link_fieldname) = moves[tablena... |
'Converts \'something\' to boolean. Raises exception for invalid formats
Possible True values: 1, True, "1", "TRue", "yes", "y", "t"
Possible False values: 0, False, "0", "faLse", "no", "n", "f", 0.0'
| @staticmethod
def to_bool(value):
| val = str(value).lower()
if (val in ('yes', 'y', 'true', 't', '1')):
return True
elif (val in ('no', 'n', 'false', 'f', '0', '0.0')):
return False
else:
return None
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.