sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def split (s, delimter, trim = True, limit = 0): # pragma: no cover """ Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret ==...
Split a string using a single-character delimter @params: `s`: the string `delimter`: the single-character delimter `trim`: whether to trim each part. Default: True @examples: ```python ret = split("'a,b',c", ",") # ret == ["'a,b'", "c"] # ',' inside quotes will be recognized. ``` @returns...
entailment
def render(self, **context): """ Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string """ # Make the complete context we'll use. localns = self.envs.copy() localns.update(context) try: exec(str(se...
Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string
entailment
def addLine(self, line): """ Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add """ if not isinstance(line, LiquidLine): line = LiquidLine(line) line.ndent = self.ndent self.codes.append(line)
Add a line of source to the code. Indentation and newline will be added for you, don't provide them. @params: `line`: The line to add
entailment
def level(self, lvl=None): '''Get or set the logging level.''' if not lvl: return self._lvl self._lvl = self._parse_level(lvl) self.stream.setLevel(self._lvl) logging.root.setLevel(self._lvl)
Get or set the logging level.
entailment
def get_rate_from_db(currency: str) -> Decimal: """ Fetch currency conversion rate from the database """ from .models import ConversionRate try: rate = ConversionRate.objects.get_rate(currency) except ConversionRate.DoesNotExist: # noqa raise ValueError('No conversion rate for %...
Fetch currency conversion rate from the database
entailment
def get_conversion_rate(from_currency: str, to_currency: str) -> Decimal: """ Get conversion rate to use in exchange """ reverse_rate = False if to_currency == BASE_CURRENCY: # Fetch exchange rate for base currency and use 1 / rate for conversion rate_currency = from_currency ...
Get conversion rate to use in exchange
entailment
def exchange_currency( base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T: """ Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate """ if base....
Exchanges Money, TaxedMoney and their ranges to the specified currency. get_rate parameter is a callable taking single argument (target currency) that returns proper conversion rate
entailment
def normalize(location_name, preserve_commas=False): """Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.""" def replace(match): if preserve_commas and ',' in match.group(0): return ',' return ' ' return NORM...
Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.
entailment
def calc_precipitation_stats(self, months=None, avg_stats=True, percentile=50): """ Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of n...
Calculates precipitation statistics for the cascade model while aggregating hourly observations Parameters ---------- months : Months for each seasons to be used for statistics (array of numpy array, default=1-12, e.g., [np.arange(12) + 1]) avg_stats : average statistics for ...
entailment
def calc_wind_stats(self): """ Calculates statistics in order to derive diurnal patterns of wind speed """ a, b, t_shift = melodist.fit_cosine_function(self.data.wind) self.wind.update(a=a, b=b, t_shift=t_shift)
Calculates statistics in order to derive diurnal patterns of wind speed
entailment
def calc_humidity_stats(self): """ Calculates statistics in order to derive diurnal patterns of relative humidity. """ a1, a0 = melodist.calculate_dewpoint_regression(self.data, return_stats=False) self.hum.update(a0=a0, a1=a1) self.hum.kr = 12 self.hum.month_hou...
Calculates statistics in order to derive diurnal patterns of relative humidity.
entailment
def calc_temperature_stats(self): """ Calculates statistics in order to derive diurnal patterns of temperature """ self.temp.max_delta = melodist.get_shift_by_data(self.data.temp, self._lon, self._lat, self._timezone) self.temp.mean_course = melodist.util.calculate_mean_daily_cou...
Calculates statistics in order to derive diurnal patterns of temperature
entailment
def calc_radiation_stats(self, data_daily=None, day_length=None, how='all'): """ Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data ...
Calculates statistics in order to derive solar radiation from sunshine duration or minimum/maximum temperature. Parameters ---------- data_daily : DataFrame, optional Daily data from the associated ``Station`` object. day_length : Series, optional Day le...
entailment
def to_json(self, filename=None): """ Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data """ def json_encoder(obj): if isinstance(obj, pd.DataFrame) or isinstance(obj, pd.Series)...
Exports statistical data to a JSON formatted file Parameters ---------- filename: output file that holds statistics data
entailment
def from_json(cls, filename): """ Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data """ def json_decoder(d): if 'p01' in d and 'pxx' in d: # we assume this is a CascadeStatist...
Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data
entailment
def disaggregate_radiation(data_daily, sun_times=None, pot_rad=None, method='pot_rad', angstr_a=0.25, angstr_b=0.5, bristcamp_a=0.75, ...
general function for radiation disaggregation Args: daily_data: daily values sun_times: daily dataframe including results of the util.sun_times function pot_rad: hourly dataframe including potential radiation method: keyword specifying the disaggregation method to be used ...
entailment
def potential_radiation(dates, lon, lat, timezone, terrain_slope=0, terrain_slope_azimuth=0, cloud_fraction=0, split=False): """ Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E...
Calculate potential shortwave radiation for a specific location and time. This routine calculates global radiation as described in: Liston, G. E. and Elder, K. (2006): A Meteorological Distribution System for High-Resolution Terrestrial Modeling (MicroMet), J. Hydrometeorol., 7, 217–234. Correct...
entailment
def bristow_campbell(tmin, tmax, pot_rad_daily, A, C): """calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and ...
calculates potential shortwave radiation based on minimum and maximum temperature This routine calculates global radiation as described in: Bristow, Keith L., and Gaylon S. Campbell: On the relationship between incoming solar radiation and daily maximum and minimum temperature. Agricultural and fo...
entailment
def fit_bristow_campbell_params(tmin, tmax, pot_rad_daily, obs_rad_daily): """ Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------...
Fit the A and C parameters for the Bristow & Campbell (1984) model using observed daily minimum and maximum temperature and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- tmin : Series Observed daily minimum temperature. tmax : Series ...
entailment
def angstroem(ssd, day_length, pot_rad_daily, a, b): """ Calculate mean daily radiation from observed sunshine duration according to Angstroem (1924). Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by...
Calculate mean daily radiation from observed sunshine duration according to Angstroem (1924). Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths as calculated by ``calc_sun_times``. pot_rad_daily : Series Mean po...
entailment
def fit_angstroem_params(ssd, day_length, pot_rad_daily, obs_rad_daily): """ Fit the a and b parameters for the Angstroem (1924) model using observed daily sunshine duration and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- ssd : Series ...
Fit the a and b parameters for the Angstroem (1924) model using observed daily sunshine duration and mean daily (e.g. aggregated from hourly values) solar radiation. Parameters ---------- ssd : Series Observed daily sunshine duration. day_length : Series Day lengths a...
entailment
def register(name): """Return a decorator that registers the decorated class as a resolver with the given *name*.""" def decorator(class_): if name in known_resolvers: raise ValueError('duplicate resolver name "%s"' % name) known_resolvers[name] = class_ return decorator
Return a decorator that registers the decorated class as a resolver with the given *name*.
entailment
def get_resolver(order=None, options=None, modules=None): """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`. Th...
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...
entailment
def load_locations(self, location_file=None): """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.""" if location_fi...
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.
entailment
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: x.lower(), self.name())) except: return tuple([x.lower() for x in self.name()])
Return a tuple containing a canonicalized version of this location's country, state, county, and city names.
entailment
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'' for x in ('country', 'state', 'county', 'city')) except: return...
Return a tuple containing this location's country, state, county, and city names.
entailment
def parent(self): """Return a location representing the administrative unit above the one represented by this location.""" if self.city: return Location( country=self.country, state=self.state, county=self.county) if self.county: return Location(co...
Return a location representing the administrative unit above the one represented by this location.
entailment
def disaggregate_humidity(data_daily, method='equal', temp=None, a0=None, a1=None, kr=None, month_hour_precip_mean=None, preserve_daily_mean=False): """general function for humidity disaggregation Args: daily_data: daily values method: keyword...
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...
entailment
def _cosine_function(x, a, b, t_shift): """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...
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: ...
entailment
def disaggregate_wind(wind_daily, method='equal', a=None, b=None, t_shift=None): """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 ...
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 ...
entailment
def fit_cosine_function(wind): """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 """ wind_daily = wind.groupby(wind.index.date)....
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
entailment
def read_smet(filename, mode): """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 : "...
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 ...
entailment
def read_dwd(filename, metadata, mode="d", skip_last=True): """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 rea...
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...
entailment
def write_smet(filename, data, metadata, nodata_value=-999, mode='h', check_nan=True): """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 ...
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...
entailment
def read_single_knmi_file(filename): """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 """ hourly_data_obs_raw ...
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
entailment
def read_knmi_dataset(directory): """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: ...
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...
entailment
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)
Computes the times of sunrise, solar noon, and sunset for each day.
entailment
def disaggregate_wind(self, method='equal'): """ Disaggregate wind speed. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily wind speed is duplicated for the 24 hours of the day. (Default) ...
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...
entailment
def disaggregate_humidity(self, method='equal', preserve_daily_mean=False): """ Disaggregate relative humidity. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Mean daily humidity is duplicated for the 24 hou...
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...
entailment
def disaggregate_temperature(self, method='sine_min_max', min_max_time='fix', mod_nighttime=False): """ Disaggregate air temperature. Parameters ---------- method : str, optional Disaggregation method. ``sine_min_max`` Hourly temperatures...
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`...
entailment
def disaggregate_precipitation(self, method='equal', zerodiv='uniform', shift=0, master_precip=None): """ Disaggregate precipitation. Parameters ---------- method : str, optional Disaggregation method. ``equal`` Daily precipitation is dis...
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...
entailment
def disaggregate_radiation(self, method='pot_rad', pot_rad=None): """ Disaggregate solar radiation. Parameters ---------- method : str, optional Disaggregation method. ``pot_rad`` Calculates potential clear-sky hourly radiation and scales...
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...
entailment
def interpolate(self, column_hours, method='linear', limit=24, limit_direction='both', **kwargs): """ Wrapper function for ``pandas.Series.interpolate`` that can be used to "disaggregate" values using various interpolation methods. Parameters ---------- column_hours : di...
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...
entailment
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 THAN 1 PRIMARY KEY FOR TABLE %s. " ...
Internal helper for preparing queries.
entailment
def head(self, n=10, by=None, **kwargs): """ 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. """ col, id_col = self._query_helper(by=by) select = ("SELECT...
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.
entailment
def last(self, n=10, by=None, **kwargs): """ Alias for .tail(). """ return self.tail(n=n, by=by, **kwargs)
Alias for .tail().
entailment
def where(self, where_string, **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()...
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 ...
entailment
def query(self, sql_query, return_as="dataframe"): """ 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 accep...
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 ...
entailment
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 an inspect attribute, whose subattributes ...
Internal helper to set metadata attributes.
entailment
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_col=index_col, coer...
Internal convert-to-DataFrame convenience wrapper.
entailment
def disaggregate_temperature(data_daily, method='sine_min_max', min_max_time='fix', mod_nighttime=False, max_delta=None, mean_course=None, sun_tim...
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, ...
entailment
def get_shift_by_data(temp_hourly, lon, lat, time_zone): '''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 ''' d...
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
entailment
def distribute_equally(daily_data, divide=False): """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). ...
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.
entailment
def vapor_pressure(temp, hum): """ 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. """ i...
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.
entailment
def dewpoint_temperature(temp, hum): """computes the dewpoint temperature Parameters ---- temp : temperature [K] hum : relative humidity Returns dewpoint temperature in K """ assert(temp.shape == hum.shape) vap_press = vapor_pressure(temp, hum) positiv...
computes the dewpoint temperature Parameters ---- temp : temperature [K] hum : relative humidity Returns dewpoint temperature in K
entailment
def linregress(x, y, return_stats=False): """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 (an...
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)
entailment
def get_sun_times(dates, lon, lat, time_zone): """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,...
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
entailment
def detect_gaps(dataframe, timestep, print_all=False, print_max=5, verbose=True): """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 de...
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...
entailment
def drop_incomplete_days(dataframe, shift=0): """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 serie...
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...
entailment
def daily_from_hourly(df): """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) """ df_...
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)
entailment
def disagg_prec(dailyData, method='equal', cascade_options=None, hourly_data_obs=None, zerodiv="uniform", shift=0): """The disaggregation function for precipitation. Parameters ---------- dailyData : pd.Series daily...
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 ...
entailment
def disagg_prec_cascade(precip_daily, cascade_options, hourly=True,level=9, shift=0, test=False): """Precipitation disaggregation with cascade model (Olsson, 1998) Parameters ---------- precip_daily : pd.Series daily data ...
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...
entailment
def precip_master_station(precip_daily, master_precip_hourly, zerodiv): """Disaggregate precipitation based on the patterns of a master station Parameters ----------- precip_daily : pd.Series daily data master_precip_hourly : pd.Series ...
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...
entailment
def aggregate_precipitation(vec_data,hourly=True, percentile=50): """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 st...
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
entailment
def seasonal_subset(dataframe, months='all'): '''Get the seasonal data. Parameters ---------- dataframe : pd.DataFrame months: int, str Months to use for statistics, or 'all' for 1-12 (default='all') ''' if isinstance(months, str) and months == 'all': mo...
Get the seasonal data. Parameters ---------- dataframe : pd.DataFrame months: int, str Months to use for statistics, or 'all' for 1-12 (default='all')
entailment
def build_casc(ObsData, hourly=True,level=9, months=None, avg_stats=True, percentile=50): '''Builds the cascade statistics of observed data for disaggregation Parameters ----------- ObsData : pd.Series hourly=True -> hourly obs data else -> 5...
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...
entailment
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 # type of data will be available self.p01 = np.array...
This function fills the corresponding object with sample data.
entailment
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))): cls._files.append(os.path.sp...
A list of all emoji names without file extension.
entailment
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 e._image_string(match.group(1)) else: r...
Add in valid emojis in a string where a valid emoji is between ::
entailment
def replace_unicode(cls, replacement_string): """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``. NOT...
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...
entailment
def replace_html_entities(cls, replacement_string): """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 _h...
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).
entailment
def _convert_to_unicode(string): """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. """ codepoints = [] for character in string.sp...
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.
entailment
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
remove file and remove it's directories if empty
entailment
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 pattern = """(["']{}["']:\\s*\\[)""".format(key) r...
Insert an item in the list of an existing manifest key
entailment
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)]
Parses a file for pip installation requirements.
entailment
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 must be in" ...
Assigns a permission to a group
entailment
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 argument must be in" ...
Removes a permission from a group
entailment
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.model._meta.app_label, list.model._meta.model_name)
Returns the class to use for the passed in list. We just build something up from the object type for the list.
entailment
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=pytz.utc) user_time_zone = pytz.timezone(getattr(settings, 'USER_TIME_ZO...
Formats a date, converting the time to the user timezone if one is specified
entailment
def get_value_from_view(context, field): """ 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. """ view = context['view'] obj = Non...
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.
entailment
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)
Looks up the class for this field
entailment
def get_label(context, field, obj=None): """ 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 val...
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
entailment
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)
Determine what the field link should be for the given field, object pair
entailment
def get_permissions_app_name(): """ 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 """ global permissions_app_name if not permissions_app_name: permissions_app_nam...
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
entailment
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 permissions, granting them if necessary. """ role_permissions = [] # get all the current permissions, we'll remove these as we verif...
Checks the the passed in role (can be user, group or AnonymousUser) has all the passed in permissions, granting them if necessary.
entailment
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(settings, 'GROUP_PERMISSIONS', dict()) # for each of our items for name, permis...
Checks that all the permissions specified in our settings.py are set for our groups.
entailment
def add_permission(content_type, permission): """ 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. """ # build our permission slug codename = "%s_%s" % (content_type.model...
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.
entailment
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_app(sender): return config = getattr(settings, 'PERMISSIONS', dict()) # for each of our items ...
This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit.
entailment
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 active by default if is_new_user: user.is_ac...
Overloaded so we can save any new password that is included.
entailment
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: (args, value) = url.split('@') if args: val = getattr(obj, args, None) return rev...
URLs that start with @ are reversed, using the passed in arguments. Otherwise a straight % substitution is applied.
entailment
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) else: return r'^%s/%s/(?P<pk>\d+)/$' % (path, action)
Utility function called by class methods for single object views
entailment
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(self, 'permission', None): return True else:...
Figures out if the current user has permissions for this view.
entailment
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(request.get_full_path()) login_url...
Overloaded to check permissions if appropriate
entailment
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 with subelements if possible """ curr_field = field.encode('ascii', 'ignore').decode("utf-8") rest = None if fi...
Looks for a field's value from the passed in obj. Note that this will strip leading attributes to deal with subelements if possible
entailment
def lookup_field_value(self, context, obj, field): """ 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 ...
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 ...
entailment
def lookup_field_label(self, context, field, default=None): """ 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...
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
entailment
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_config[field]: help = self.field_config[fi...
Looks up the help text for the passed in field.
entailment
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 if field in self.field_config and 'class' in self.field_config[field]: ...
Looks up any additional class we should include when rendering this field
entailment
def get_template_names(self): """ 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 set...
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.
entailment
def derive_fields(self): """ Default implementation """ fields = [] if self.fields: fields.append(self.fields) return fields
Default implementation
entailment