text
stringlengths
81
112k
Return a location resolver. The *order* argument, if given, should be a list of resolver names; results from resolvers named earlier in the list are preferred over later ones. For a list of built-in resolver names, see :doc:`/resolvers`. The *options* argument can be used to pass configuration option...
Load locations into this resolver from the given *location_file*, which should contain one JSON object per line representing a location. If *location_file* is not specified, an internal location database is used. def load_locations(self, location_file=None): """Load locations into this...
Return a tuple containing a canonicalized version of this location's country, state, county, and city names. def canonical(self): """Return a tuple containing a canonicalized version of this location's country, state, county, and city names.""" try: return tuple(map(lambda x...
Return a tuple containing this location's country, state, county, and city names. def name(self): """Return a tuple containing this location's country, state, county, and city names.""" try: return tuple( getattr(self, x) if getattr(self, x) else u'' ...
Return a location representing the administrative unit above the one represented by this location. def parent(self): """Return a location representing the administrative unit above the one represented by this location.""" if self.city: return Location( countr...
general function for humidity disaggregation Args: daily_data: daily values method: keyword specifying the disaggregation method to be used temp: hourly temperature time series (necessary for some methods) kr: parameter for linear_dewpoint_variation method (6 or 12) month_ho...
genrates a diurnal course of windspeed accroding to the cosine function Args: x: series of euqally distributed windspeed values a: parameter a for the cosine function b: parameter b for the cosine function t_shift: parameter t_shift for the cosine function Returns: ...
general function for windspeed disaggregation Args: wind_daily: daily values method: keyword specifying the disaggregation method to be used a: parameter a for the cosine function b: parameter b for the cosine function t_shift: parameter t_shift for the cosine function ...
fits a cosine function to observed hourly windspeed data Args: wind: observed hourly windspeed data Returns: parameters needed to generate diurnal features of windspeed using a cosine function def fit_cosine_function(wind): """fits a cosine function to observed hourly windspeed da...
Reads smet data and returns the data in required dataformat (pd df) See https://models.slf.ch/docserver/meteoio/SMET_specifications.pdf for further details on the specifications of this file format. Parameters ---- filename : SMET file to read mode : "d" for daily and "h" for hourly input ...
Reads dwd (German Weather Service) data and returns the data in required dataformat (pd df) Parameters ---- filename : DWD file to read (full path) / list of hourly files (RR+TU+FF) metadata : corresponding DWD metadata file to read mode : "d" for daily and "h" for hourly input skip_las...
writes smet files Parameters ---- filename : filename/loction of output data : data to write as pandas df metadata: header to write input as dict nodata_value: Nodata Value to write/use mode: defines if to write daily ("d") or continuos data (default 'h') check_nan...
reads a single file of KNMI's meteorological time series data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: filename: the file to be opened Returns: pandas data frame including time series def read_single_knmi_file(filename): """reads a single file of KNMI's m...
Reads files from a directory and merges the time series Please note: For each station, a separate directory must be provided! data availability: www.knmi.nl/nederland-nu/klimatologie/uurgegevens Args: directory: directory including the files Returns: pandas data frame including time s...
Computes the times of sunrise, solar noon, and sunset for each day. def calc_sun_times(self): """ Computes the times of sunrise, solar noon, and sunset for each day. """ self.sun_times = melodist.util.get_sun_times(self.data_daily.index, self.lon, self.lat, self.timezone)
Disaggregate wind speed. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily wind speed is duplicated for the 24 hours of the day. (Default) ``cosine`` Distributes daily mean wind speed us...
Disaggregate relative humidity. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily humidity is duplicated for the 24 hours of the day. (Default) ``minimal``: Calculates humidity from dail...
Disaggregate air temperature. Parameters ---------- method : str, optional Disaggregation method. ``sine_min_max`` Hourly temperatures follow a sine function preserving daily minimum and maximum values. (Default) ``sine_mean`...
Disaggregate precipitation. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Daily precipitation is distributed equally over the 24 hours of the day. (Default) ``cascade`` Hourly precipitation val...
Disaggregate solar radiation. Parameters ---------- method : str, optional Disaggregation method. ``pot_rad`` Calculates potential clear-sky hourly radiation and scales it according to the mean daily radiation. (Default) ``po...
Wrapper function for ``pandas.Series.interpolate`` that can be used to "disaggregate" values using various interpolation methods. Parameters ---------- column_hours : dict Dictionary containing column names in ``data_daily`` and the hour values they should be ass...
Internal helper for preparing queries. def _query_helper(self, by=None): """ Internal helper for preparing queries. """ if by is None: primary_keys = self.table.primary_key.columns.keys() if len(primary_keys) > 1: warnings.warn("WARNING: MORE THA...
Get the first n entries for a given Table/Column. Additional keywords passed to QueryDb.query(). Requires that the given table has a primary key specified. def head(self, n=10, by=None, **kwargs): """ Get the first n entries for a given Table/Column. Additional keywords passed ...
Alias for .tail(). def last(self, n=10, by=None, **kwargs): """ Alias for .tail(). """ return self.tail(n=n, by=by, **kwargs)
Select from a given Table or Column with the specified WHERE clause string. Additional keywords are passed to ExploreSqlDB.query(). For convenience, if there is no '=', '>', '<', 'like', or 'LIKE' clause in the WHERE statement .where() tries to match the input string against the primary ...
Execute a raw SQL query against the the SQL DB. Args: sql_query (str): A raw SQL query to execute. Kwargs: return_as (str): Specify what type of object should be returned. The following are acceptable types: - "dataframe": pandas.DataFrame or None if no ...
Internal helper to set metadata attributes. def _set_metadata(self): """ Internal helper to set metadata attributes. """ meta = QueryDbMeta() with self._engine.connect() as conn: meta.bind = conn meta.reflect() self._meta = meta # Set...
Internal convert-to-DataFrame convenience wrapper. def _to_df(self, query, conn, index_col=None, coerce_float=True, params=None, parse_dates=None, columns=None): """ Internal convert-to-DataFrame convenience wrapper. """ return pd.io.sql.read_sql(str(query), conn, index_c...
The disaggregation function for temperature Parameters ---- data_daily : daily data method : method to disaggregate min_max_time: "fix" - min/max temperature at fixed times 7h/14h, "sun_loc" - min/max calculated by sunrise/sunnoon + 2h, ...
function to get max temp shift (monthly) by hourly data Parameters ---- hourly_data_obs : observed hourly data lat : latitude in DezDeg lon : longitude in DezDeg time_zone: timezone def get_shift_by_data(temp_hourly, lon, lat, time_zone): '''function to ...
Obtains hourly values by equally distributing the daily values. Args: daily_data: daily values divide: if True, divide resulting values by the number of hours in order to preserve the daily sum (required e.g. for precipitation). Returns: Equally distributed hourly values. ...
Calculates vapor pressure from temperature and humidity after Sonntag (1990). Args: temp: temperature values hum: humidity value(s). Can be scalar (e.g. for calculating saturation vapor pressure). Returns: Vapor pressure in hPa. def vapor_pressure(temp, hum): """ Calculates va...
computes the dewpoint temperature Parameters ---- temp : temperature [K] hum : relative humidity Returns dewpoint temperature in K def dewpoint_temperature(temp, hum): """computes the dewpoint temperature Parameters ---- temp : temperature [K] hum...
linear regression calculation Parameters ---- x : independent variable (series) y : dependent variable (series) return_stats : returns statistical values as well if required (bool) Returns ---- list of parameters (and statistics) def linregress(x, y, return_stats=...
Computes the times of sunrise, solar noon, and sunset for each day. Parameters ---- dates: datetime lat : latitude in DecDeg lon : longitude in DecDeg time_zone : timezone Returns ---- DataFrame: [sunrise, sunnoon, sunset, day length] in dec hours def get_su...
checks if a given dataframe contains gaps and returns the number of gaps This funtion checks if a dataframe contains any gaps for a given temporal resolution that needs to be specified in seconds. The number of gaps detected in the dataframe is returned. Args: dataframe: A pandas dataframe obj...
truncates a given dataframe to full days only This funtion truncates a given pandas dataframe (time series) to full days only, thus dropping leading and tailing hours of incomplete days. Please note that this methodology only applies to hourly time series. Args: dataframe: A pandas dataframe o...
Aggregates data (hourly to daily values) according to the characteristics of each variable (e.g., average for temperature, sum for precipitation) Args: df: dataframe including time series with one hour time steps Returns: dataframe (daily) def daily_from_hourly(df): """Aggregates data...
The disaggregation function for precipitation. Parameters ---------- dailyData : pd.Series daily data method : str method to disaggregate cascade_options : cascade object including statistical parameters for the cascade model hourly_data_obs : pd.Series observed ...
Precipitation disaggregation with cascade model (Olsson, 1998) Parameters ---------- precip_daily : pd.Series daily data hourly: Boolean (for an hourly resolution disaggregation) if False, then returns 5-min disaggregated precipitation (disaggregation level depending on the "le...
Disaggregate precipitation based on the patterns of a master station Parameters ----------- precip_daily : pd.Series daily data master_precip_hourly : pd.Series observed hourly data of the master station zerodiv : str method to deal with zero division by key "uniform" --> u...
Aggregates highly resolved precipitation data and creates statistics Parameters ---------- vec_data : pd.Series hourly (hourly=True) OR 5-min values Returns ------- output : cascade object representing statistics of the cascade model def aggregate_precipitation(vec_data,hourl...
Get the seasonal data. Parameters ---------- dataframe : pd.DataFrame months: int, str Months to use for statistics, or 'all' for 1-12 (default='all') def seasonal_subset(dataframe, months='all'): '''Get the seasonal data. Parameters ---------- dataframe : ...
Builds the cascade statistics of observed data for disaggregation Parameters ----------- ObsData : pd.Series hourly=True -> hourly obs data else -> 5min data (disaggregation level=9 (default), 10, 11) months : numpy array of ints Months for each seasons to be used for stati...
This function fills the corresponding object with sample data. def fill_with_sample_data(self): """This function fills the corresponding object with sample data.""" # replace these sample data with another dataset later # this function is deprecated as soon as a common file format for this ...
A list of all emoji names without file extension. def names(cls): """A list of all emoji names without file extension.""" if not cls._files: for f in os.listdir(cls._image_path): if(not f.startswith('.') and os.path.isfile(os.path.join(cls._image_path, f))...
Add in valid emojis in a string where a valid emoji is between :: def replace(cls, replacement_string): """Add in valid emojis in a string where a valid emoji is between ::""" e = cls() def _replace_emoji(match): val = match.group(1) if val in e: return ...
This method will iterate over every character in ``replacement_string`` and see if it mathces any of the unicode codepoints that we recognize. If it does then it will replace that codepoint with an image just like ``replace``. NOTE: This will only work with Python versions built with wi...
Replaces HTML escaped unicode entities with their unicode equivalent. If the setting `EMOJI_REPLACE_HTML_ENTITIES` is `True` then this conversation will always be done in `replace_unicode` (default: True). def replace_html_entities(cls, replacement_string): """Replaces HTML escaped unic...
This method should work with both Python 2 and 3 with the caveat that they need to be compiled with wide unicode character support. If there isn't wide unicode character support it'll blow up with a warning. def _convert_to_unicode(string): """This method should work with both Python 2 and 3 with the ...
remove file and remove it's directories if empty def _delete_file(configurator, path): """ remove file and remove it's directories if empty """ path = os.path.join(configurator.target_directory, path) os.remove(path) try: os.removedirs(os.path.dirname(path)) except OSError: pass
Insert an item in the list of an existing manifest key def _insert_manifest_item(configurator, key, item): """ Insert an item in the list of an existing manifest key """ with _open_manifest(configurator) as f: manifest = f.read() if item in ast.literal_eval(manifest).get(key, []): return ...
Parses a file for pip installation requirements. def _read_requirements(filename): """Parses a file for pip installation requirements.""" with open(filename) as requirements_file: contents = requirements_file.read() return [line.strip() for line in contents.splitlines() if _is_requirement(line)]
Assigns a permission to a group def assign_perm(perm, group): """ Assigns a permission to a group """ if not isinstance(perm, Permission): try: app_label, codename = perm.split('.', 1) except ValueError: raise ValueError("For global permissions, first argument mu...
Removes a permission from a group def remove_perm(perm, group): """ Removes a permission from a group """ if not isinstance(perm, Permission): try: app_label, codename = perm.split('.', 1) except ValueError: raise ValueError("For global permissions, first argumen...
Returns the class to use for the passed in list. We just build something up from the object type for the list. def get_list_class(context, list): """ Returns the class to use for the passed in list. We just build something up from the object type for the list. """ return "list_%s_%s" % (list....
Formats a date, converting the time to the user timezone if one is specified def format_datetime(time): """ Formats a date, converting the time to the user timezone if one is specified """ user_time_zone = timezone.get_current_timezone() if time.tzinfo is None: time = time.replace(tzinfo=py...
Responsible for deriving the displayed value for the passed in 'field'. This first checks for a particular method on the ListView, then looks for a method on the object, then finally treats it as an attribute. def get_value_from_view(context, field): """ Responsible for deriving the displayed value fo...
Looks up the class for this field def get_class(context, field, obj=None): """ Looks up the class for this field """ view = context['view'] return view.lookup_field_class(field, obj, "field_" + field)
Responsible for figuring out the right label for the passed in field. The order of precedence is: 1) if the view has a field_config and a label specified there, use that label 2) check for a form in the view, if it contains that field, use it's value def get_label(context, field, obj=None): """ ...
Determine what the field link should be for the given field, object pair def get_field_link(context, field, obj=None): """ Determine what the field link should be for the given field, object pair """ view = context['view'] return view.lookup_field_link(context, field, obj)
Gets the app after which smartmin permissions should be installed. This can be specified by PERMISSIONS_APP in the Django settings or defaults to the last app with models def get_permissions_app_name(): """ Gets the app after which smartmin permissions should be installed. This can be specified by PERMISSI...
Checks the the passed in role (can be user, group or AnonymousUser) has all the passed in permissions, granting them if necessary. def check_role_permissions(role, permissions, current_permissions): """ Checks the the passed in role (can be user, group or AnonymousUser) has all the passed in permissi...
Checks that all the permissions specified in our settings.py are set for our groups. def check_all_group_permissions(sender, **kwargs): """ Checks that all the permissions specified in our settings.py are set for our groups. """ if not is_permissions_app(sender): return config = getattr(se...
Adds the passed in permission to that content type. Note that the permission passed in should be a single word, or verb. The proper 'codename' will be generated from that. def add_permission(content_type, permission): """ Adds the passed in permission to that content type. Note that the permission passe...
This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit. def check_all_permissions(sender, **kwargs): """ This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit. """ if not is_permissions_...
Overloaded so we can save any new password that is included. def save(self, commit=True): """ Overloaded so we can save any new password that is included. """ is_new_user = self.instance.pk is None user = super(UserForm, self).save(commit) # new users should be made ac...
URLs that start with @ are reversed, using the passed in arguments. Otherwise a straight % substitution is applied. def smart_url(url, obj=None): """ URLs that start with @ are reversed, using the passed in arguments. Otherwise a straight % substitution is applied. """ if url.find("@") >= 0: ...
Utility function called by class methods for single object views def derive_single_object_url_pattern(slug_url_kwarg, path, action): """ Utility function called by class methods for single object views """ if slug_url_kwarg: return r'^%s/%s/(?P<%s>[^/]+)/$' % (path, action, slug_url_kwarg) ...
Figures out if the current user has permissions for this view. def has_permission(self, request, *args, **kwargs): """ Figures out if the current user has permissions for this view. """ self.kwargs = kwargs self.args = args self.request = request if not getattr(...
Overloaded to check permissions if appropriate def dispatch(self, request, *args, **kwargs): """ Overloaded to check permissions if appropriate """ def wrapper(request, *args, **kwargs): if not self.has_permission(request, *args, **kwargs): path = urlquote(re...
Looks for a field's value from the passed in obj. Note that this will strip leading attributes to deal with subelements if possible def lookup_obj_attribute(self, obj, field): """ Looks for a field's value from the passed in obj. Note that this will strip leading attributes to deal wi...
Looks up the field value for the passed in object and field name. Note that this method is actually called from a template, but this provides a hook for subclasses to modify behavior if they wish to do so. This may be used for example to change the display value of a variable depending on ...
Figures out what the field label should be for the passed in field name. Our heuristic is as follows: 1) we check to see if our field_config has a label specified 2) if not, then we derive a field value from the field name def lookup_field_label(self, context, field, default=None): ...
Looks up the help text for the passed in field. def lookup_field_help(self, field, default=None): """ Looks up the help text for the passed in field. """ help = None # is there a label specified for this field if field in self.field_config and 'help' in self.field_confi...
Looks up any additional class we should include when rendering this field def lookup_field_class(self, field, obj=None, default=None): """ Looks up any additional class we should include when rendering this field """ css = "" # is there a class specified for this field ...
Returns the name of the template to use to render this request. Smartmin provides default templates as fallbacks, so appends it's own templates names to the end of whatever list is built by the generic views. Subclasses can override this by setting a 'template_name' variable on the class. def...
Default implementation def derive_fields(self): """ Default implementation """ fields = [] if self.fields: fields.append(self.fields) return fields
We supplement the normal context data by adding our fields and labels. def get_context_data(self, **kwargs): """ We supplement the normal context data by adding our fields and labels. """ context = super(SmartView, self).get_context_data(**kwargs) # derive our field config ...
Overloaded to deal with _format arguments. def render_to_response(self, context, **response_kwargs): """ Overloaded to deal with _format arguments. """ # should we actually render in json? if '_format' in self.request.GET and self.request.GET['_format'] == 'json': re...
Derives our fields. We first default to using our 'fields' variable if available, otherwise we figure it out from our object. def derive_fields(self): """ Derives our fields. We first default to using our 'fields' variable if available, otherwise we figure it out from our object. ...
Add in the field to use for the name field def get_context_data(self, **kwargs): """ Add in the field to use for the name field """ context = super(SmartDeleteView, self).get_context_data(**kwargs) context['name_field'] = self.name_field context['cancel_url'] = self.get_cancel_url() ...
Derives our title from our list def derive_title(self): """ Derives our title from our list """ title = super(SmartListView, self).derive_title() if not title: return force_text(self.model._meta.verbose_name_plural).title() else: return title
Used to derive which fields should be linked. This should return a set() containing the names of those fields which should be linkable. def derive_link_fields(self, context): """ Used to derive which fields should be linked. This should return a set() containing the names of those fie...
Returns whether the passed in field is sortable or not, by default all 'raw' fields, that is fields that are part of the model are sortable. def lookup_field_orderable(self, field): """ Returns whether the passed in field is sortable or not, by default all 'raw' fields, that is fields t...
Add in what fields are linkable def get_context_data(self, **kwargs): """ Add in what fields are linkable """ context = super(SmartListView, self).get_context_data(**kwargs) # our linkable fields self.link_fields = self.derive_link_fields(context) # stuff it al...
Derives our queryset. def derive_queryset(self, **kwargs): """ Derives our queryset. """ # get our parent queryset queryset = super(SmartListView, self).get_queryset(**kwargs) # apply any filtering search_fields = self.derive_search_fields() search_query...
Gets our queryset. This takes care of filtering if there are any fields to filter by. def get_queryset(self, **kwargs): """ Gets our queryset. This takes care of filtering if there are any fields to filter by. """ queryset = self.derive_queryset(**kwargs) retu...
Returns what field should be used for ordering (using a prepended '-' to indicate descending sort). If the default order of the queryset should be used, returns None def derive_ordering(self): """ Returns what field should be used for ordering (using a prepended '-' to indicate descending sort...
Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter. def order_queryset(self, queryset): """ Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter. """ ...
Derives our fields. def derive_fields(self): """ Derives our fields. """ if self.fields: return self.fields else: fields = [] for field in self.object_list.model._meta.fields: if field.name != 'id': fields....
Overloaded to deal with _format arguments. def render_to_response(self, context, **response_kwargs): """ Overloaded to deal with _format arguments. """ # is this a select2 format response? if self.request.GET.get('_format', 'html') == 'select2': results = [] ...
Returns an instance of the form to be used in this view. def get_form(self): """ Returns an instance of the form to be used in this view. """ self.form = super(SmartFormMixin, self).get_form() fields = list(self.derive_fields()) # apply our field filtering on our form ...
Allows views to customize their form fields. By default, Smartmin replaces the plain textbox date input with it's own DatePicker implementation. def customize_form_field(self, name, field): """ Allows views to customize their form fields. By default, Smartmin replaces the plain textbox ...
Figures out what the field label should be for the passed in field name. We overload this so as to use our form to see if there is label set there. If so then we'll pass that as the default instead of having our parent derive the field from the name. def lookup_field_label(self, context, fiel...
Looks up the help text for the passed in field. This is overloaded so that we can check whether our form has help text set explicitely. If so, we will pass this as the default to our parent function. def lookup_field_help(self, field, default=None): """ Looks up the help text for the ...
Figures out what fields should be readonly. We iterate our field_config to find all that have a readonly of true def derive_readonly(self): """ Figures out what fields should be readonly. We iterate our field_config to find all that have a readonly of true """ readonly...
Derives our fields. def derive_fields(self): """ Derives our fields. """ if self.fields is not None: fields = list(self.fields) else: form = self.form fields = [] for field in form: fields.append(field.name) ...
Returns the form class to use in this view def get_form_class(self): """ Returns the form class to use in this view """ if self.form_class: form_class = self.form_class else: if self.model is not None: # If a model has been explicitly pro...
Let's us specify any extra parameters we might want to call for our form factory. These can include: 'form', 'fields', 'exclude' or 'formfield_callback' def get_factory_kwargs(self): """ Let's us specify any extra parameters we might want to call for our form factory. These can includ...