desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Returns country name for given code or id from L0 locations.
The key can be either location id or country code, as specified
by key_type.'
| @staticmethod
def get_country(key, key_type='id'):
| if key:
if current.gis.get_countries(key_type):
if (key_type == 'id'):
return current.session.gis.countries_by_id[key]
else:
return current.session.gis.countries_by_code[key]
return None
|
'Returns the parent country for a given record
@param: location: the location or id to search for
@param: key_type: whether to return an id or code
@ToDo: Optimise to not use try/except'
| def get_parent_country(self, location, key_type='id'):
| if (not location):
return None
db = current.db
s3db = current.s3db
try:
table = s3db.gis_location
location = db((table.id == location)).select(table.id, table.path, table.level, limitby=(0, 1), cache=s3db.cache).first()
except:
pass
if (location.level == 'L0'):
... |
'Returns the default country for the active gis_config
@param: key_type: whether to return an id or code'
| def get_default_country(self, key_type='id'):
| config = GIS.get_config()
if config.default_location_id:
return self.get_parent_country(config.default_location_id, key_type=key_type)
return None
|
'Returns a gluon.sql.Rows of Features within a Polygon.
The Polygon can be either a WKT string or the ID of a record in the
gis_location table
Currently unused.
@ToDo: Optimise to not use try/except'
| def get_features_in_polygon(self, location, tablename=None, category=None):
| from shapely.geos import ReadingError
from shapely.wkt import loads as wkt_loads
try:
from shapely import speedups
speedups.enable()
except:
current.log.info('S3GIS', 'Upgrade Shapely for Performance enhancements')
db = current.db
s3db = current.s3db
locat... |
'Given a gis_location record or a bounding box dict with keys
lon_min, lon_max, lat_min, lat_max, construct a WKT polygon with
points at the corners.'
| @staticmethod
def get_polygon_from_bounds(bbox):
| lon_min = bbox['lon_min']
lon_max = bbox['lon_max']
lat_min = bbox['lat_min']
lat_max = bbox['lat_max']
points = [(lon_min, lat_min), (lon_min, lat_max), (lon_max, lat_max), (lon_min, lat_max), (lon_min, lat_min)]
pairs = [('%s %s' % (p[0], p[1])) for p in points]
wkt = ('POLYGON ((%s)... |
'Compute a bounding box given a Radius (in km) of a LatLon Location
Note the order of the parameters.
@return a dict containing the bounds with keys min_lon, max_lon,
min_lat, max_lat
See:
http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates'
| @staticmethod
def get_bounds_from_radius(lat, lon, radius):
| import math
radians = math.radians
degrees = math.degrees
MIN_LAT = radians((-90))
MAX_LAT = radians(90)
MIN_LON = radians((-180))
MAX_LON = radians(180)
r = (float(radius) / RADIUS_EARTH)
radLat = radians(lat)
radLon = radians(lon)
minLat = (radLat - r)
maxLat = (radLat ... |
'Returns Features within a Radius (in km) of a LatLon Location
Unused'
| def get_features_in_radius(self, lat, lon, radius, tablename=None, category=None):
| import math
db = current.db
settings = current.deployment_settings
if (settings.gis.spatialdb and (settings.database.db_type == 'postgres')):
import psycopg2
import psycopg2.extras
dbname = settings.database.database
username = settings.database.username
password ... |
'Returns the Lat/Lon for a Feature
used by display_feature() in gis controller
@param feature_id: the feature ID
@param filter: Filter out results based on deployment_settings'
| def get_latlon(self, feature_id, filter=False):
| db = current.db
table = db.gis_location
feature = db((table.id == feature_id)).select(table.id, table.lat, table.lon, table.parent, table.path, limitby=(0, 1)).first()
if (('lon' in feature) and ('lat' in feature) and (feature.lat is not None) and (feature.lon is not None)):
return dict(lon=feat... |
'Returns the locations for an XML export
- used by GIS.get_location_data() and S3PivotTable.geojson()
@ToDo: Support multiple locations for a single resource
(e.g. a Project working in multiple Communities)'
| @staticmethod
def get_locations(table, query, join=True, geojson=True):
| db = current.db
tablename = table._tablename
gtable = current.s3db.gis_location
settings = current.deployment_settings
tolerance = settings.get_gis_simplify_tolerance()
output = {}
if settings.get_gis_spatialdb():
if geojson:
precision = settings.get_gis_precision()
... |
'Returns the locations, markers and popup tooltips for an XML export
e.g. Feature Layers or Search results (Feature Resources)
e.g. Exports in KML, GeoRSS or GPX format
Called by S3REST: S3Resource.export_tree()
@param: resource - S3Resource instance (required)
@param: attr_fields - list of attr_fields to use instead o... | @staticmethod
def get_location_data(resource, attr_fields=None, count=None):
| tablename = resource.tablename
if (tablename == 'gis_feature_query'):
return {}
format = current.auth.permission.format
geojson = (format == 'geojson')
if geojson:
if (count and (count > current.deployment_settings.get_gis_max_features())):
headers = {'Content-Type': 'app... |
'Returns a Marker dict
- called by xml.gis_encode() for non-geojson resources
- called by S3Map.widget() if no marker_fn supplied'
| @staticmethod
def get_marker(controller=None, function=None, filter=None):
| marker = None
if (controller and function):
db = current.db
s3db = current.s3db
ftable = s3db.gis_layer_feature
stable = s3db.gis_style
mtable = s3db.gis_marker
config = GIS.get_config()
query = (((ftable.controller == controller) & (ftable.function == fun... |
'Returns a Style dict
- called by S3Report.geojson()'
| @staticmethod
def get_style(layer_id=None, aggregate=None):
| style = None
if layer_id:
style = Style(layer_id=layer_id, aggregate=aggregate).as_dict()
if (not style):
style = Style().as_dict()
return style
|
'Save a Screenshot of a saved map
@requires:
PhantomJS http://phantomjs.org
Selenium https://pypi.python.org/pypi/selenium'
| @staticmethod
def get_screenshot(config_id, temp=True, height=None, width=None):
| map_id = 'default_map'
from webdriver import WebDriver
from selenium.common.exceptions import TimeoutException, WebDriverException
from selenium.webdriver.support.ui import WebDriverWait
request = current.request
cachepath = os.path.join(request.folder, 'static', 'cache', 'jpg')
if (not os.p... |
'Lookup Shapefile Layer polygons once per layer and not per-record
Called by S3REST: S3Resource.export_tree()
@ToDo: Vary simplification level & precision by Zoom level
- store this in the style?'
| @staticmethod
def get_shapefile_geojson(resource):
| db = current.db
tablename = resource.tablename
table = db[tablename]
query = resource.get_query()
fields = []
fappend = fields.append
for f in table.fields:
if (f not in ('layer_id', 'lat', 'lon')):
fappend(f)
attributes = {}
geojsons = {}
settings = current.d... |
'Lookup Theme Layer polygons once per layer and not per-record
Called by S3REST: S3Resource.export_tree()
@ToDo: Vary precision by Lx
- store this (& tolerance map) in the style?'
| @staticmethod
def get_theme_geojson(resource):
| s3db = current.s3db
tablename = 'gis_theme_data'
table = s3db.gis_theme_data
gtable = s3db.gis_location
query = (table.id.belongs(resource._ids) & (table.location_id == gtable.id))
geojsons = {}
rows = current.db(query).select(table.id, gtable.level, gtable.wkt)
simplify = GIS.simplify
... |
'Calculate the shortest distance (in km) over the earth\'s sphere between 2 points
Formulae from: http://www.movable-type.co.uk/scripts/latlong.html
(NB We could also use PostGIS functions, where possible, instead of this query)'
| @staticmethod
def greatCircleDistance(lat1, lon1, lat2, lon2, quick=True):
| import math
cos = math.cos
sin = math.sin
radians = math.radians
if quick:
lat1 = radians(lat1)
lat2 = radians(lat2)
lon1 = radians(lon1)
lon2 = radians(lon2)
distance = (math.acos(((sin(lat1) * sin(lat2)) + ((cos(lat1) * cos(lat2)) * cos((lon2 - lon1))))) * R... |
'Create a .poly file for OpenStreetMap exports
http://wiki.openstreetmap.org/wiki/Osmosis/Polygon_Filter_File_Format'
| @staticmethod
def create_poly(feature):
| from shapely.wkt import loads as wkt_loads
try:
from shapely import speedups
speedups.enable()
except:
current.log.info('S3GIS', 'Upgrade Shapely for Performance enhancements')
name = feature.name
if ('wkt' in feature):
wkt = feature.wkt
else:
... |
'Export admin areas to /static/cache for use by interactive web-mapping services
- designed for use by the Vulnerability Mapping
@param countries: list of ISO2 country codes
@param levels: list of which Lx levels to export
@param format: Only GeoJSON supported for now (may add KML &/or OSM later)
@param simplify: toler... | @staticmethod
def export_admin_areas(countries=[], levels=('L0', 'L1', 'L2', 'L3'), format='geojson', simplify=0.01, precision=4):
| db = current.db
s3db = current.s3db
table = s3db.gis_location
ifield = table.id
if countries:
ttable = s3db.gis_location_tag
cquery = (((((table.level == 'L0') & (table.end_date == None)) & (ttable.location_id == ifield)) & (ttable.tag == 'ISO2')) & ttable.value.belongs(countries))
... |
'Import Admin Boundaries into the Locations table
@param source - Source to get the data from.
Currently only GADM is supported: http://gadm.org
@param countries - List of ISO2 countrycodes to download data for
defaults to all countries
@param levels - Which levels of the hierarchy to import.
defaults to all 3 supporte... | def import_admin_areas(self, source='gadmv1', countries=[], levels=['L0', 'L1', 'L2']):
| if (source == 'gadmv1'):
try:
from osgeo import ogr
except:
current.log.error('Unable to import ogr. Please install python-gdal bindings: GDAL-1.8.1+')
return
if ('L0' in levels):
self.import_gadm1_L0(ogr, countries=coun... |
'Import L0 Admin Boundaries into the Locations table from GADMv1
- designed to be called from import_admin_areas()
- assumes that basic prepop has been done, so that no new records need to be created
@param ogr - The OGR Python module
@param countries - List of ISO2 countrycodes to download data for
defaults to all cou... | @staticmethod
def import_gadm1_L0(ogr, countries=[]):
| db = current.db
s3db = current.s3db
ttable = s3db.gis_location_tag
table = db.gis_location
layer = {'url': 'http://gadm.org/data/gadm_v1_lev0_shp.zip', 'zipfile': 'gadm_v1_lev0_shp.zip', 'shapefile': 'gadm1_lev0', 'codefield': 'ISO2', 'code2field': 'ISO'}
cwd = os.getcwd()
TEMP = os.path.joi... |
'Import L1 Admin Boundaries into the Locations table from GADMv1
- designed to be called from import_admin_areas()
- assumes a fresh database with just Countries imported
@param ogr - The OGR Python module
@param level - "L1" or "L2"
@param countries - List of ISO2 countrycodes to download data for
defaults to all coun... | def import_gadm1(self, ogr, level='L1', countries=[]):
| if (level == 'L1'):
layer = {'url': 'http://gadm.org/data/gadm_v1_lev1_shp.zip', 'zipfile': 'gadm_v1_lev1_shp.zip', 'shapefile': 'gadm1_lev1', 'namefield': 'NAME_1', 'sourceCodeField': 'ID_1', 'edenCodeField': 'GADM1', 'parent': 'L0', 'parentSourceCodeField': 'ISO', 'parentEdenCodeField': 'ISO3'}
elif (... |
'Import Admin Boundaries into the Locations table from GADMv2
- designed to be called from import_admin_areas()
- assumes that basic prepop has been done, so that no new L0 records need to be created
@param ogr - The OGR Python module
@param level - The OGR Python module
@param countries - List of ISO2 countrycodes to ... | @staticmethod
def import_gadm2(ogr, level='L0', countries=[]):
| if (level == 'L0'):
codeField = 'ISO2'
code2Field = 'ISO'
elif (level == 'L1'):
codeField = 'ID_1'
code2Field = 'ISO'
elif (level == 'L2'):
codeField = 'ID_2'
code2Field = 'ID_1'
else:
current.log.error(('Level %s not supported!' % level))... |
'Import Locations from the Geonames database
@param country: the 2-letter country code
@param level: the ADM level to import
Designed to be run from the CLI
Levels should be imported sequentially.
It is assumed that L0 exists in the DB already
L1-L3 may have been imported from Shapefiles with Polygon info
Geonames can ... | def import_geonames(self, country, level=None):
| import codecs
from shapely.geometry import point
from shapely.geos import ReadingError
from shapely.wkt import loads as wkt_loads
try:
from shapely import speedups
speedups.enable()
except:
current.log.info('S3GIS', 'Upgrade Shapely for Performance enhancement... |
'Convert a LatLon to a WKT string
>>> s3gis.latlon_to_wkt(6, 80)
\'POINT(80 6)\''
| @staticmethod
def latlon_to_wkt(lat, lon):
| WKT = ('POINT(%f %f)' % (lon, lat))
return WKT
|
'Parses a location from wkt, returning wkt, lat, lon, bounding box and type.
For points, wkt may be None if lat and lon are provided; wkt will be generated.
For lines and polygons, the lat, lon returned represent the shape\'s centroid.
Centroid and bounding box will be None if Shapely is not available.'
| @staticmethod
def parse_location(wkt, lon=None, lat=None):
| if (not wkt):
if ((not (lon is not None)) and (lat is not None)):
raise RuntimeError, 'Need wkt or lon+lat to parse a location'
wkt = ('POINT(%f %f)' % (lon, lat))
geom_type = GEOM_TYPES['point']
bbox = (lon, lat, lon, lat)
else:
try:
... |
'Update GIS Locations\' Materialized path, Lx locations, Lat/Lon & the_geom
@param feature: a feature dict to update the tree for
- if not provided then update the whole tree
@param all_locations: passed to recursive calls to indicate that this
is an update of the whole tree. Used to avoid repeated attempts to
update h... | @staticmethod
def update_location_tree(feature=None, all_locations=False, propagating=False):
| if GIS.disable_update_location_tree:
return None
db = current.db
try:
table = db.gis_location
except:
table = current.s3db.gis_location
spatial = current.deployment_settings.get_gis_spatialdb()
update_location_tree = GIS.update_location_tree
wkt_centroid = GIS.wkt_cen... |
'OnValidation callback:
If a WKT is defined: validate the format,
calculate the LonLat of the Centroid, and set bounds
Else if a LonLat is defined: calculate the WKT for the Point.'
| @staticmethod
def wkt_centroid(form):
| form_vars = form.vars
if (form_vars.get('gis_feature_type', None) == '1'):
lat = form_vars.get('lat', None)
lon = form_vars.get('lon', None)
if (((lon is None) and (lat is None)) or ((lon == '') and (lat == ''))):
return
elif ((lat is None) or (lat == '')):
... |
'Returns a query of all Locations inside the given bounding box'
| @staticmethod
def query_features_by_bbox(lon_min, lat_min, lon_max, lat_max):
| table = current.s3db.gis_location
query = ((((table.lat_min <= lat_max) & (table.lat_max >= lat_min)) & (table.lon_min <= lon_max)) & (table.lon_max >= lon_min))
return query
|
'Returns Rows of Locations whose shape intersects the given bbox.'
| @staticmethod
def get_features_by_bbox(lon_min, lat_min, lon_max, lat_max):
| query = current.gis.query_features_by_bbox(lon_min, lat_min, lon_max, lat_max)
return current.db(query).select()
|
'Returns Rows of locations which intersect the given shape.
Relies on Shapely for wkt parsing and intersection.
@ToDo: provide an option to use PostGIS/Spatialite'
| @staticmethod
def get_features_by_shape(shape):
| from shapely.geos import ReadingError
from shapely.wkt import loads as wkt_loads
try:
from shapely import speedups
speedups.enable()
except:
current.log.info('S3GIS', 'Upgrade Shapely for Performance enhancements')
table = current.s3db.gis_location
in_bbox = c... |
'Returns a generator of locations whose shape intersects the given LatLon.
Relies on Shapely.
@todo: provide an option to use PostGIS/Spatialite'
| @staticmethod
def get_features_by_latlon(lat, lon):
| from shapely.geometry import point
return current.gis.get_features_by_shape(point.Point(lon, lat))
|
'Returns all Locations whose geometry intersects the given feature.
Relies on Shapely.
@ToDo: provide an option to use PostGIS/Spatialite'
| @staticmethod
def get_features_by_feature(feature):
| from shapely.wkt import loads as wkt_loads
shape = wkt_loads(feature.wkt)
return current.gis.get_features_by_shape(shape)
|
'Sets bounds for all locations without them.
If shapely is present, and a location has wkt, bounds of the geometry
are used. Otherwise, the (lat, lon) are used as bounds.'
| @staticmethod
def set_all_bounds():
| try:
from shapely.wkt import loads as wkt_loads
SHAPELY = True
except:
SHAPELY = False
db = current.db
table = current.s3db.gis_location
no_bounds = ((((((table.lon_min == None) & (table.lat_min == None)) & (table.lon_max == None)) & (table.lat_max == None)) & (table.lat != N... |
'Simplify a complex Polygon using the Douglas-Peucker algorithm
- NB This uses Python, better performance will be gained by doing
this direct from the database if you are using PostGIS:
ST_Simplify() is available as
db(query).select(table.the_geom.st_simplify(tolerance).st_astext().with_alias(\'wkt\')).first().wkt
db(q... | @staticmethod
def simplify(wkt, tolerance=None, preserve_topology=True, output='wkt', precision=None):
| from shapely.geometry import Point, LineString, Polygon, MultiPolygon
from shapely.wkt import loads as wkt_loads
try:
from shapely import speedups
speedups.enable()
except:
current.log.info('S3GIS', 'Upgrade Shapely for Performance enhancements')
try:
shap... |
'Returns the HTML to display a map
Normally called in the controller as: map = gis.show_map()
In the view, put: {{=XML(map)}}
@param id: ID to uniquely identify this map if there are several on a page
@param height: Height of viewport (if not provided then the default deployment setting is used)
@param width: Width of ... | def show_map(self, id='default_map', height=None, width=None, bbox={}, lat=None, lon=None, zoom=None, projection=None, add_feature=False, add_feature_active=False, add_line=False, add_line_active=False, add_polygon=False, add_polygon_active=False, add_circle=False, add_circle_active=False, features=None, feature_querie... | return MAP(id=id, height=height, width=width, bbox=bbox, lat=lat, lon=lon, zoom=zoom, projection=projection, add_feature=add_feature, add_feature_active=add_feature_active, add_line=add_line, add_line_active=add_line_active, add_polygon=add_polygon, add_polygon_active=add_polygon_active, add_circle=add_circle, add_... |
':param **opts: options to pass to the Map for server-side processing'
| def __init__(self, **opts):
| self.setup = False
self.callback = None
self.opts = opts
self.id = map_id = opts.get('id', 'default_map')
self.options = {}
components = [DIV(DIV(_class='map_loader'), _id=('%s_panel' % map_id))]
self.components = components
for c in components:
self._setnode(c)
_class = 'map... |
'Setup the Map
- not done during init() to be as Lazy as possible
- separated from xml() in order to be able to read options to put
into scripts (callback or otherwise)'
| def _setup(self):
| config = GIS.get_config()
if (not config):
current.session.error = current.T('Map cannot display without prepop data!')
redirect(URL(c='default', f='index'))
opts = self.opts
T = current.T
db = current.db
auth = current.auth
s3db = current.s3db
request = cu... |
'Render the Map
- this is primarily done by inserting a lot of JavaScript
- CSS loaded as-standard to avoid delays in page loading
- HTML added in init() as a component'
| def xml(self):
| if (not self.setup):
self._setup()
s3_include_ext()
dumps = json.dumps
s3 = current.response.s3
js_global = s3.js_global
js_global_append = js_global.append
i18n_dict = self.i18n
i18n = []
i18n_append = i18n.append
for (key, val) in i18n_dict.items():
line = ('i18... |
'Output the Layers as a Python dict'
| def as_dict(self, options=None):
| sublayer_dicts = []
append = sublayer_dicts.append
sublayers = self.sublayers
for sublayer in sublayers:
sublayer_dict = sublayer.as_dict()
if sublayer_dict:
append(sublayer_dict)
if sublayer_dicts:
if options:
options[self.dictname] = sublayer_dicts
... |
'Output the Layers as JSON'
| def as_json(self):
| result = self.as_dict()
if result:
return json.dumps(result, separators=SEPARATORS)
|
'Output the Layers as global Javascript
- suitable for inclusion in the HTML page'
| def as_javascript(self):
| result = self.as_json()
if result:
return ('S3.gis.%s=%s\n' % (self.dictname, result))
|
'Set up the KML cache, should be done once per request'
| def __init__(self, all_layers, init=True):
| super(LayerKML, self).__init__(all_layers)
request = current.request
cachepath = os.path.join(request.folder, 'uploads', 'gis_cache')
if os.path.exists(cachepath):
cacheable = os.access(cachepath, os.W_OK)
else:
try:
os.mkdir(cachepath)
except OSError as os_error:... |
'@param marker: Storage object with image/height/width (looked-up in bulk)
@param marker_id: id of record in gis_marker
@param layer_id: layer_id to lookup marker in gis_style (unused)
@param tablename: used to identify whether to provide a default marker as fallback'
| def __init__(self, marker=None, marker_id=None, layer_id=None, tablename=None):
| no_default = False
if (not marker):
db = current.db
s3db = current.s3db
mtable = s3db.gis_marker
config = None
if marker_id:
marker = db((mtable.id == marker_id)).select(mtable.image, mtable.height, mtable.width, limitby=(0, 1), cache=s3db.cache).first()
... |
'Called by Layer.as_dict()'
| def add_attributes_to_output(self, output):
| if self.image:
output['marker'] = self.as_json_dict()
|
'Called by gis.get_marker(), feature_resources & s3profile'
| def as_dict(self):
| if self.image:
marker = Storage(image=self.image, height=self.height, width=self.width)
else:
marker = None
return marker
|
'Called by Style.as_dict() and add_attributes_to_output()'
| def as_json_dict(self):
| if self.image:
marker = dict(i=self.image, h=self.height, w=self.width)
else:
marker = None
return marker
|
''
| def as_dict(self):
| style = self.style
output = Storage()
if (not style):
return output
if hasattr(style, 'marker'):
output.marker = style.marker.as_json_dict()
opacity = style.opacity
if (opacity and (opacity not in (1, 1.0))):
output.opacity = style.opacity
if style.popup_format:
... |
'Entry point to apply map method to S3Requests
- produces a full page with S3FilterWidgets above a Map
@param r: the S3Request instance
@param attr: controller attributes for the request
@return: output object to send to the view'
| def apply_method(self, r, **attr):
| if (r.http == 'GET'):
representation = r.representation
if (representation == 'html'):
return self.page(r, **attr)
else:
r.error(405, current.ERROR.BAD_METHOD)
|
'Map page
@param r: the S3Request instance
@param attr: controller attributes for the request'
| def page(self, r, **attr):
| if (r.representation in ('html', 'iframe')):
response = current.response
resource = self.resource
get_config = resource.get_config
tablename = resource.tablename
widget_id = 'default_map'
output = {}
title = self.crud_string(tablename, 'title_map')
out... |
'Render a Map widget suitable for use in an S3Filter-based page
such as S3Summary
@param r: the S3Request
@param method: the widget method
@param widget_id: the widget ID
@param callback: None by default in case DIV is hidden
@param visible: whether the widget is initially visible
@param attr: controller attributes'
| def widget(self, r, method='map', widget_id=None, visible=True, callback=None, **attr):
| if (not widget_id):
widget_id = 'default_map'
gis = current.gis
tablename = self.tablename
ftable = current.s3db.gis_layer_feature
def lookup_layer(prefix, name):
query = ((ftable.controller == prefix) & (ftable.function == name))
layers = current.db(query).select(ftable.laye... |
'Apply method.
@param r: the S3Request
@param attr: controller options for this request'
| def apply_method(self, r, **attr):
| output = dict()
if (r.http == 'GET'):
output = self.export(r, **attr)
else:
r.error(405, current.ERROR.BAD_METHOD)
return output
|
'Export POI resources.
URL options:
- "resources" list of tablenames to export records from
- "msince" datetime in ISO format, "auto" to use the
feed\'s last update
- "update_feed" 0 to skip the update of the feed\'s last
update datetime, useful for trial exports
Supported formats:
.xml S3XML
.osm ... | def export(self, r, **attr):
| current_lx = r.record
if (not current_lx):
r.error(400, current.ERROR.BAD_REQUEST)
else:
self.lx = current_lx.id
tables = []
if ('resources' in r.get_vars):
resources = r.get_vars['resources']
else:
resources = current.deployment_settings.get_gis_poi_export_resour... |
'Export a combined tree of all records in tables, which
are in Lx, and have been updated since msince.
@param tables: list of table names
@param msince: minimum modified_on datetime, "auto" for
automatic from feed data, None to turn it off
@param update_feed: update the last_update datetime in the feed'
| def export_combined_tree(self, tables, msince=None, update_feed=True):
| db = current.db
s3db = current.s3db
ftable = s3db.gis_poi_feed
lx = self.lx
elements = []
for tablename in tables:
try:
resource = s3db.resource(tablename, components=[])
except AttributeError:
continue
if ('location_id' not in resource.fields):
... |
'Add a Lx filter for the current location to this
resource.
@param resource: the resource'
| @staticmethod
def _add_lx_filter(resource, lx):
| from s3query import FS
query = (FS('location_id$path').contains(('/%s/' % lx)) | FS('location_id$path').like(('%s/%%' % lx)))
resource.add_filter(query)
|
'Apply method.
@param r: the S3Request
@param attr: controller options for this request'
| @staticmethod
def apply_method(r, **attr):
| if (r.representation == 'html'):
T = current.T
s3db = current.s3db
request = current.request
response = current.response
settings = current.deployment_settings
s3 = current.response.s3
title = T('Import from OpenStreetMap')
resources_list = setti... |
'API entry point
@param r: the S3Request instance
@param attr: controller attributes for the request'
| def apply_method(self, r, **attr):
| if (r.http in ('GET', 'POST', 'DELETE')):
if r.record:
self.settings = current.response.s3.crud
self.sqlform = sqlform = self._config('crud_form')
if (not sqlform):
from s3forms import S3SQLDefaultForm
self.sqlform = S3SQLDefaultForm()
... |
'Generate a Profile page
@param r: the S3Request instance
@param attr: controller attributes for the request'
| def profile(self, r, **attr):
| tablename = self.tablename
get_config = current.s3db.get_config
widgets = get_config(tablename, 'profile_widgets')
if (not widgets):
if (r.representation not in ('dl', 'aadata')):
redirect(r.url(method='read'))
else:
r.error(405, current.ERROR.BAD_METHOD)
for ... |
'Resolve a context filter
@param context: the context (as a string)
@param id: the record_id'
| @staticmethod
def _resolve_context(r, tablename, context):
| record_id = r.id
if (not record_id):
return None
if (not context):
query = None
elif (type(context) is tuple):
(context, field) = context
query = (FS(context) == r.record[field])
elif (context == 'location'):
s = '(location)$path'
m = ('%(id)s,%(id)s/*... |
'Generate a Comments widget
@param r: the S3Request instance
@param widget: the widget definition as dict
@param attr: controller attributes for the request
@ToDo: Configurable to use either Disqus or internal Comments'
| def _comments(self, r, widget, **attr):
| label = widget.get('label', '')
if label:
label = current.T(label)
icon = widget.get('icon', '')
if icon:
icon = ICON(icon)
_class = self._lookup_class(r, widget)
comments = '@ToDo'
output = DIV(H4(icon, label, _class='profile-sub-header'), DIV(comments, _class='card-holder')... |
'Generate a Custom widget
@param r: the S3Request instance
@param widget: the widget definition as dict
@param attr: controller attributes for the request'
| def _custom(self, r, widget, **attr):
| label = widget.get('label', '')
if label:
label = current.T(label)
icon = widget.get('icon', '')
if icon:
icon = ICON(icon)
_class = self._lookup_class(r, widget)
contents = widget['fn'](r, **attr)
output = DIV(H4(icon, label, _class='profile-sub-header'), DIV(contents, _clas... |
'Generate a data list
@param r: the S3Request instance
@param widget: the widget definition as dict
@param attr: controller attributes for the request'
| def _datalist(self, r, widget, **attr):
| T = current.T
widget_get = widget.get
context = widget_get('context')
tablename = widget_get('tablename')
(resource, context) = self._resolve_context(r, tablename, context)
config = resource.get_config
list_fields = widget_get('list_fields', config('list_fields', None))
list_layout = wid... |
'Generate a data table.
@param r: the S3Request instance
@param widget: the widget definition as dict
@param attr: controller attributes for the request
@todo: fix export formats'
| def _datatable(self, r, widget, **attr):
| widget_get = widget.get
context = widget_get('context')
tablename = widget_get('tablename')
(resource, context) = self._resolve_context(r, tablename, context)
list_fields = widget_get('list_fields')
if (not list_fields):
list_fields = resource.list_fields()
widget_filter = widget_get... |
'Generate a Form widget
@param r: the S3Request instance
@param widget: the widget as a tuple: (label, type, icon)
@param attr: controller attributes for the request'
| def _form(self, r, widget, **attr):
| widget_get = widget.get
label = widget_get('label', '')
if label:
label = current.T(label)
icon = widget_get('icon', '')
if icon:
icon = ICON(icon)
context = widget_get('context')
tablename = widget_get('tablename')
(resource, context) = self._resolve_context(r, tablename... |
'Generate a Map widget
@param r: the S3Request instance
@param widget: the widget as a tuple: (label, type, icon)
@param attr: controller attributes for the request'
| def _map(self, r, widget, widgets, **attr):
| T = current.T
db = current.db
s3db = current.s3db
widget_get = widget.get
label = widget_get('label', '')
if (label and isinstance(label, basestring)):
label = T(label)
icon = widget_get('icon', '')
if icon:
icon = ICON(icon)
_class = self._lookup_class(r, widget)
... |
'Generate a Report widget
@param r: the S3Request instance
@param widget: the widget as a tuple: (label, type, icon)
@param attr: controller attributes for the request'
| def _report(self, r, widget, **attr):
| widget_get = widget.get
context = widget_get('context', None)
tablename = widget_get('tablename', None)
(resource, context) = self._resolve_context(r, tablename, context)
widget_filter = widget_get('filter', None)
if widget_filter:
resource.add_filter(widget_filter)
widget_id = ('pro... |
'Provide the column-width class for the widgets
@param r: the S3Request
@param widget: the widget config (dict)'
| @staticmethod
def _lookup_class(r, widget):
| page_cols = current.s3db.get_config(r.tablename, 'profile_cols')
if (not page_cols):
page_cols = 2
widget_cols = widget.get('colspan', 1)
span = (int((12 / page_cols)) * widget_cols)
formstyle = current.deployment_settings.ui.get('formstyle', 'default')
if (current.deployment_settings.ui... |
'Render an action link for a create-popup (used in data lists
and data tables).
@param r: the S3Request instance
@param widget: the widget definition as dict
@param list_id: the list ID
@param resource: the target resource
@param context: the context filter
@param numrows: the total number of rows in the list/table'
| @staticmethod
def _create_popup(r, widget, list_id, resource, context, numrows):
| create = ''
widget_get = widget.get
insert = widget_get('insert', True)
if (not insert):
return create
table = resource.table
tablename = resource.tablename
(c, f) = tablename.split('_', 1)
create_controller = widget_get('create_controller')
if create_controller:
c = ... |
'Page-render entry point for REST interface.
@param r: the S3Request instance
@param attr: controller attributes for the request'
| def apply_method(self, r, **attr):
| if (r.http == 'GET'):
output = self.timeplot(r, **attr)
else:
r.error(405, current.ERROR.BAD_METHOD)
return output
|
'Widget-render entry point for S3Summary.
@param r: the S3Request
@param method: the widget method
@param widget_id: the widget ID
@param visible: whether the widget is initially visible
@param attr: controller attributes'
| def widget(self, r, method=None, widget_id=None, visible=True, **attr):
| resource = self.get_target(r)
(report_vars, get_vars) = self.get_options(r, resource)
timestamp = get_vars.get('timestamp')
(event_start, event_end) = self.parse_timestamp(timestamp)
fact = get_vars.get('fact')
try:
facts = S3TimeSeriesFact.parse(fact)
except SyntaxError:
r.e... |
'Time plot report page
@param r: the S3Request instance
@param attr: controller attributes for the request'
| def timeplot(self, r, **attr):
| output = {}
resource = self.get_target(r)
tablename = resource.tablename
get_config = resource.get_config
show_filter_form = False
if (r.representation in ('html', 'iframe')):
filter_widgets = get_config('filter_widgets', None)
if (filter_widgets and (not self.hide_filter)):
... |
'Identify the target resource, attach component if necessary
@param r: the S3Request'
| def get_target(self, r):
| resource = self.resource
alias = r.get_vars.get('component')
if (alias and (alias not in (resource.alias, '~'))):
if (alias not in resource.components):
hook = current.s3db.get_component(resource.tablename, alias)
if hook:
resource._attach(alias, hook)
... |
'Read the relevant GET vars for the timeplot
@param r: the S3Request
@param resource: the target S3Resource'
| @staticmethod
def get_options(r, resource):
| report_vars = ('timestamp', 'start', 'end', 'slots', 'fact', 'baseline', 'rows', 'cols')
get_vars = dict(((k, v) for (k, v) in r.get_vars.iteritems() if (k in report_vars)))
report_options = resource.get_config('timeplot_options', {})
defaults = report_options.get('defaults', {})
if (not any(((k in ... |
'Parse timestamp expression
@param timestamp: the timestamp expression'
| @staticmethod
def parse_timestamp(timestamp):
| if timestamp:
fields = timestamp.split(',')
if (len(fields) > 1):
start = fields[0].strip()
end = fields[1].strip()
else:
start = fields[0].strip()
end = None
else:
start = None
end = None
return (start, end)
|
'Render the form for the report
@param get_vars: the GET vars if the request (as dict)
@param widget_id: the HTML element base ID for the widgets'
| def html(self, data, filter_widgets=None, get_vars=None, ajaxurl=None, filter_url=None, filter_form=None, filter_tab=None, widget_id=None):
| T = current.T
if (filter_widgets is not None):
filter_options = self._fieldset(T('Filter Options'), filter_widgets, _id=('%s-filters' % widget_id), _class='filter-form')
else:
filter_options = ''
report_options = self.report_options(get_vars=get_vars, widget_id=widget_id)
hidden =... |
'Render the widgets for the report options form
@param get_vars: the GET vars if the request (as dict)
@param widget_id: the HTML element base ID for the widgets'
| def report_options(self, get_vars=None, widget_id='timeplot'):
| T = current.T
timeplot_options = self.resource.get_config('timeplot_options')
selectors = []
formstyle = current.deployment_settings.get_ui_filter_formstyle()
time_selector = self.time_options(options=timeplot_options, get_vars=get_vars, widget_id=('%s-time' % widget_id))
selectors.append(formst... |
'@todo: docstring'
| def time_options(self, options=None, get_vars=None, widget_id=None):
| T = current.T
if (options and ('time' in options)):
opts = options['time']
else:
opts = (('All up to now', '', '', ''), ('Last Year', '-1year', '', 'months'), ('Last 6 Months', '-6months', '', 'weeks'), ('Last Quarter', '-3months', '', 'weeks'), ('Last Month', '-1mont... |
'Constructor
@param resource: the resource
@param start: the start of the series (datetime or string expression)
@param end: the end of the time series (datetime or string expression)
@param slots: the slot size (string expression)
@param event_start: the event start field (field selector)
@param event_end: the event e... | def __init__(self, resource, start=None, end=None, slots=None, event_start=None, event_end=None, rows=None, cols=None, facts=None, baseline=None, title=None):
| self.resource = resource
self.rfields = {}
self.title = title
self.resolve_timestamp(event_start, event_end)
self.resolve_axes(rows, cols)
if (not facts):
facts = [S3TimeSeriesFact('count', resource._id.name)]
self.facts = [fact.resolve(resource) for fact in facts]
self.resolve_b... |
'Return the time series as JSON-serializable dict'
| def as_dict(self):
| rfields = self.rfields
fact_data = []
for fact in self.facts:
fact_data.append((str(fact.label), fact.method, fact.base, fact.slope, fact.interval))
rfield = rfields.get('event_start')
if rfield:
event_start = rfield.selector
else:
event_start = None
rfield = rfields.... |
'Represent and sort the values of a pivot axis (rows or cols)
@param rfield: the axis rfield
@param values: iterable of values'
| @staticmethod
def _represent_axis(rfield, values):
| if rfield.virtual:
representations = []
append = representations.append()
stripper = S3MarkupStripper()
represent = rfield.represent
if (not represent):
represent = s3_unicode
for value in values:
if (value is None):
append((val... |
'Get the representation method for a field in the report
@param field: the field selector'
| def _represent_method(self, field):
| rfields = self.rfields
default = (lambda value: None)
if (field and (field in rfields)):
rfield = rfields[field]
if rfield.field:
def repr_method(value):
return s3_represent_value(rfield.field, value, strip_markup=True)
elif rfield.virtual:
str... |
'Create an event frame for this report
@param start: the start date/time (string, date or datetime)
@param end: the end date/time (string, date or datetime)
@param slots: the slot length (string)
@return: the event frame'
| def _event_frame(self, start=None, end=None, slots=None):
| resource = self.resource
rfields = self.rfields
STANDARD_SLOT = '1 day'
now = tp_tzsafe(datetime.datetime.utcnow())
dtparse = self.dtparse
start_dt = end_dt = None
if start:
if isinstance(start, basestring):
start_dt = dtparse(start, start=now)
elif isinstance(... |
'Select records from the resource and store them as events in
this time series'
| def _select(self):
| resource = self.resource
rfields = self.rfields
cumulative = False
event_start = rfields.get('event_start')
fields = set([event_start.selector])
event_end = rfields.get('event_end')
if event_end:
fields.add(event_end.selector)
rows_rfield = rfields.get('rows')
if rows_rfield:... |
'Resolve the event_start and event_end field selectors
@param event_start: the field selector for the event start field
@param event_end: the field selector for the event end field'
| def resolve_timestamp(self, event_start, event_end):
| resource = self.resource
rfields = self.rfields
if (not event_start):
table = resource.table
for fname in ('date', 'start_date', 'created_on'):
if (fname in table.fields):
event_start = fname
break
if (event_start and (not event_end)):
... |
'Resolve the baseline field selector
@param baseline: the baseline selector'
| def resolve_baseline(self, baseline):
| resource = self.resource
rfields = self.rfields
baseline_rfield = None
if baseline:
try:
baseline_rfield = resource.resolve_selector(baseline)
except (AttributeError, SyntaxError):
baseline_rfield = None
if (baseline_rfield and (baseline_rfield.ftype not in NU... |
'Resolve the grouping axes field selectors
@param rows: the rows field selector
@param cols: the columns field selector'
| def resolve_axes(self, rows, cols):
| resource = self.resource
rfields = self.rfields
rows_rfield = None
if rows:
try:
rows_rfield = resource.resolve_selector(rows)
except (AttributeError, SyntaxError):
rows_rfield = None
cols_rfield = None
if cols:
try:
cols_rfield = resou... |
'Parse a string for start/end date(time) of an interval
@param timestr: the time string
@param start: the start datetime to relate relative times to'
| @staticmethod
def dtparse(timestr, start=None):
| if (start is None):
start = tp_tzsafe(datetime.datetime.utcnow())
if (not timestr):
return start
match = dt_regex.DELTA.match(timestr)
if match:
groups = match.groups()
intervals = {'y': 'years', 'm': 'months', 'w': 'weeks', 'd': 'days', 'h': 'hours'}
length = int... |
'Constructor
@param event_id: a unique identifier for the event (e.g. record ID)
@param start: start time of the event (datetime.datetime)
@param end: end time of the event (datetime.datetime)
@param values: a dict of key-value pairs with the attribute
values for the event
@param row: the series row for this event
@par... | def __init__(self, event_id, start=None, end=None, values=None, row=DEFAULT, col=DEFAULT):
| self.event_id = event_id
self.start = tp_tzsafe(start)
self.end = tp_tzsafe(end)
if isinstance(values, dict):
self.values = values
else:
self.values = {}
self.row = row
self.col = col
self._rows = None
self._cols = None
|
'Get the set of row axis keys for this event'
| @property
def rows(self):
| rows = self._rows
if (rows is None):
rows = self._rows = self.series(self.row)
return rows
|
'Get the set of column axis keys for this event'
| @property
def cols(self):
| cols = self._cols
if (cols is None):
cols = self._cols = self.series(self.col)
return cols
|
'Convert a field value into a set of series keys
@param value: the field value'
| @staticmethod
def series(value):
| if (value is DEFAULT):
series = set()
elif (value is None):
series = set([None])
elif (type(value) is list):
series = set(s3_flatlist(value))
else:
series = set([value])
return series
|
'Access attribute values of this event
@param field: the attribute field name'
| def __getitem__(self, field):
| return self.values.get(field, None)
|
'Comparison method to allow sorting of events
@param other: the event to compare to'
| def __lt__(self, other):
| this = self.start
that = other.start
if (this is None):
result = (that is not None)
elif (that is None):
result = False
else:
result = (this < that)
return result
|
'Constructor
@param method: the aggregation method
@param base: column name of the (base) field
@param slope: column name of the slope field (for cumulate method)
@param interval: time interval expression for the slope'
| def __init__(self, method, base, slope=None, interval=None, label=None):
| if (method not in self.METHODS):
raise SyntaxError(('Unsupported aggregation function: %s' % method))
self.method = method
self.base = base
self.slope = slope
self.interval = interval
self.label = label
self.resource = None
self.base_rfield = None
self.base_column = ... |
'Aggregate values from events
@param period: the period
@param events: the events'
| def aggregate(self, period, events):
| values = []
append = values.append
method = self.method
base = self.base_column
if (method == 'cumulate'):
slope = self.slope_column
duration = period.duration
for event in events:
if (event.start == None):
continue
if base:
... |
'Aggregate a list of values.
@param values: iterable of values'
| def compute(self, values):
| if (values is None):
return None
method = self.method
values = [v for v in values if (v != None)]
if (method == 'count'):
return len(values)
elif (method == 'min'):
try:
return min(values)
except (TypeError, ValueError):
return None
elif (m... |
'Parse fact expression
@param fact: the fact expression'
| @classmethod
def parse(cls, fact):
| if isinstance(fact, list):
facts = []
for f in fact:
facts.extend(cls.parse(f))
if (not facts):
raise SyntaxError(('Invalid fact expression: %s' % fact))
return facts
if isinstance(fact, tuple):
(label, fact) = fact
else:
label... |
'Resolve the base and slope selectors against resource
@param resource: the resource'
| def resolve(self, resource):
| self.resource = None
base = self.base
self.base_rfield = None
self.base_column = base
slope = self.slope
self.slope_rfield = None
self.slope_column = slope
base_rfield = None
if base:
try:
base_rfield = resource.resolve_selector(base)
except (AttributeErro... |
'Lookup the fact label from the timeplot options of resource
@param resource: the resource (S3Resource)
@param method: the aggregation method (string)
@param base: the base field selector (string)
@param slope: the slope field selector (string)
@param interval: the interval expression (string)'
| @classmethod
def lookup_label(cls, resource, method, base, slope=None, interval=None):
| fact_opts = None
if resource:
config = resource.get_config('timeplot_options')
if config:
fact_opts = config.get('fact')
label = None
if fact_opts:
parse = cls.parse
for opt in fact_opts:
if isinstance(opt, tuple):
(title, facts) = ... |
'Generate a default fact label
@param rfield: the S3ResourceField (alternatively the field label)
@param method: the aggregation method'
| @classmethod
def default_label(cls, rfield, method):
| T = current.T
if (hasattr(rfield, 'ftype') and (rfield.ftype == 'id') and (method == 'count')):
field_label = T('Records')
elif hasattr(rfield, 'label'):
field_label = rfield.label
else:
field_label = rfield
method_label = cls.METHODS.get(method)
if (not method_label):
... |
'Constructor
@param start: the start of the time period (datetime)
@param end: the end of the time period (datetime)'
| def __init__(self, start, end=None):
| self.start = tp_tzsafe(start)
self.end = tp_tzsafe(end)
self.pevents = {}
self.cevents = {}
self._reset()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.