repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
pwwang/liquidpy
liquid/__init__.py
Liquid.split
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 ==...
python
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 ==...
[ "def", "split", "(", "s", ",", "delimter", ",", "trim", "=", "True", ",", "limit", "=", "0", ")", ":", "# pragma: no cover", "ret", "=", "[", "]", "special1", "=", "[", "'('", ",", "')'", ",", "'['", ",", "']'", ",", "'{'", ",", "'}'", "]", "sp...
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...
[ "Split", "a", "string", "using", "a", "single", "-", "character", "delimter" ]
train
https://github.com/pwwang/liquidpy/blob/f422af836740b7facfbc6b89e5162a17d619dd07/liquid/__init__.py#L367-L421
pwwang/liquidpy
liquid/__init__.py
Liquid.render
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...
python
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...
[ "def", "render", "(", "self", ",", "*", "*", "context", ")", ":", "# Make the complete context we'll use.", "localns", "=", "self", ".", "envs", ".", "copy", "(", ")", "localns", ".", "update", "(", "context", ")", "try", ":", "exec", "(", "str", "(", ...
Render this template by applying it to `context`. @params: `context`: a dictionary of values to use in this rendering. @returns: The rendered string
[ "Render", "this", "template", "by", "applying", "it", "to", "context", "." ]
train
https://github.com/pwwang/liquidpy/blob/f422af836740b7facfbc6b89e5162a17d619dd07/liquid/__init__.py#L575-L624
pwwang/liquidpy
liquid/builder.py
LiquidCode.addLine
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)
python
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)
[ "def", "addLine", "(", "self", ",", "line", ")", ":", "if", "not", "isinstance", "(", "line", ",", "LiquidLine", ")", ":", "line", "=", "LiquidLine", "(", "line", ")", "line", ".", "ndent", "=", "self", ".", "ndent", "self", ".", "codes", ".", "app...
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
[ "Add", "a", "line", "of", "source", "to", "the", "code", ".", "Indentation", "and", "newline", "will", "be", "added", "for", "you", "don", "t", "provide", "them", "." ]
train
https://github.com/pwwang/liquidpy/blob/f422af836740b7facfbc6b89e5162a17d619dd07/liquid/builder.py#L57-L67
ManufacturaInd/python-zenlog
zenlog/__init__.py
Log.level
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)
python
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)
[ "def", "level", "(", "self", ",", "lvl", "=", "None", ")", ":", "if", "not", "lvl", ":", "return", "self", ".", "_lvl", "self", ".", "_lvl", "=", "self", ".", "_parse_level", "(", "lvl", ")", "self", ".", "stream", ".", "setLevel", "(", "self", "...
Get or set the logging level.
[ "Get", "or", "set", "the", "logging", "level", "." ]
train
https://github.com/ManufacturaInd/python-zenlog/blob/8f4ddf281287c99e286b78ef2d0d949a7172ba4c/zenlog/__init__.py#L90-L96
mirumee/django-prices-openexchangerates
django_prices_openexchangerates/__init__.py
get_rate_from_db
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 %...
python
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 %...
[ "def", "get_rate_from_db", "(", "currency", ":", "str", ")", "->", "Decimal", ":", "from", ".", "models", "import", "ConversionRate", "try", ":", "rate", "=", "ConversionRate", ".", "objects", ".", "get_rate", "(", "currency", ")", "except", "ConversionRate", ...
Fetch currency conversion rate from the database
[ "Fetch", "currency", "conversion", "rate", "from", "the", "database" ]
train
https://github.com/mirumee/django-prices-openexchangerates/blob/3f633ad20f62dce03c526e9af93335f2b6b1a950/django_prices_openexchangerates/__init__.py#L15-L24
mirumee/django-prices-openexchangerates
django_prices_openexchangerates/__init__.py
get_conversion_rate
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 ...
python
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 ...
[ "def", "get_conversion_rate", "(", "from_currency", ":", "str", ",", "to_currency", ":", "str", ")", "->", "Decimal", ":", "reverse_rate", "=", "False", "if", "to_currency", "==", "BASE_CURRENCY", ":", "# Fetch exchange rate for base currency and use 1 / rate for conversi...
Get conversion rate to use in exchange
[ "Get", "conversion", "rate", "to", "use", "in", "exchange" ]
train
https://github.com/mirumee/django-prices-openexchangerates/blob/3f633ad20f62dce03c526e9af93335f2b6b1a950/django_prices_openexchangerates/__init__.py#L27-L44
mirumee/django-prices-openexchangerates
django_prices_openexchangerates/__init__.py
exchange_currency
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....
python
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....
[ "def", "exchange_currency", "(", "base", ":", "T", ",", "to_currency", ":", "str", ",", "*", ",", "conversion_rate", ":", "Decimal", "=", "None", ")", "->", "T", ":", "if", "base", ".", "currency", "==", "to_currency", ":", "return", "base", "if", "bas...
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
[ "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", "r...
train
https://github.com/mirumee/django-prices-openexchangerates/blob/3f633ad20f62dce03c526e9af93335f2b6b1a950/django_prices_openexchangerates/__init__.py#L47-L85
mdredze/carmen-python
carmen/resolvers/profile.py
normalize
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...
python
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...
[ "def", "normalize", "(", "location_name", ",", "preserve_commas", "=", "False", ")", ":", "def", "replace", "(", "match", ")", ":", "if", "preserve_commas", "and", "','", "in", "match", ".", "group", "(", "0", ")", ":", "return", "','", "return", "' '", ...
Normalize *location_name* by stripping punctuation and collapsing runs of whitespace, and return the normalized name.
[ "Normalize", "*", "location_name", "*", "by", "stripping", "punctuation", "and", "collapsing", "runs", "of", "whitespace", "and", "return", "the", "normalized", "name", "." ]
train
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolvers/profile.py#L15-L22
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_precipitation_stats
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...
python
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...
[ "def", "calc_precipitation_stats", "(", "self", ",", "months", "=", "None", ",", "avg_stats", "=", "True", ",", "percentile", "=", "50", ")", ":", "if", "months", "is", "None", ":", "months", "=", "[", "np", ".", "arange", "(", "12", ")", "+", "1", ...
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 ...
[ "Calculates", "precipitation", "statistics", "for", "the", "cascade", "model", "while", "aggregating", "hourly", "observations" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L77-L92
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_wind_stats
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)
python
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)
[ "def", "calc_wind_stats", "(", "self", ")", ":", "a", ",", "b", ",", "t_shift", "=", "melodist", ".", "fit_cosine_function", "(", "self", ".", "data", ".", "wind", ")", "self", ".", "wind", ".", "update", "(", "a", "=", "a", ",", "b", "=", "b", "...
Calculates statistics in order to derive diurnal patterns of wind speed
[ "Calculates", "statistics", "in", "order", "to", "derive", "diurnal", "patterns", "of", "wind", "speed" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L94-L99
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_humidity_stats
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...
python
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...
[ "def", "calc_humidity_stats", "(", "self", ")", ":", "a1", ",", "a0", "=", "melodist", ".", "calculate_dewpoint_regression", "(", "self", ".", "data", ",", "return_stats", "=", "False", ")", "self", ".", "hum", ".", "update", "(", "a0", "=", "a0", ",", ...
Calculates statistics in order to derive diurnal patterns of relative humidity.
[ "Calculates", "statistics", "in", "order", "to", "derive", "diurnal", "patterns", "of", "relative", "humidity", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L101-L109
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_temperature_stats
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...
python
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...
[ "def", "calc_temperature_stats", "(", "self", ")", ":", "self", ".", "temp", ".", "max_delta", "=", "melodist", ".", "get_shift_by_data", "(", "self", ".", "data", ".", "temp", ",", "self", ".", "_lon", ",", "self", ".", "_lat", ",", "self", ".", "_tim...
Calculates statistics in order to derive diurnal patterns of temperature
[ "Calculates", "statistics", "in", "order", "to", "derive", "diurnal", "patterns", "of", "temperature" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L111-L116
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.calc_radiation_stats
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 ...
python
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 ...
[ "def", "calc_radiation_stats", "(", "self", ",", "data_daily", "=", "None", ",", "day_length", "=", "None", ",", "how", "=", "'all'", ")", ":", "assert", "how", "in", "(", "'all'", ",", "'seasonal'", ",", "'monthly'", ")", "self", ".", "glob", ".", "me...
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...
[ "Calculates", "statistics", "in", "order", "to", "derive", "solar", "radiation", "from", "sunshine", "duration", "or", "minimum", "/", "maximum", "temperature", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L118-L186
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.to_json
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)...
python
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)...
[ "def", "to_json", "(", "self", ",", "filename", "=", "None", ")", ":", "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
[ "Exports", "statistical", "data", "to", "a", "JSON", "formatted", "file" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L188-L223
kristianfoerster/melodist
melodist/stationstatistics.py
StationStatistics.from_json
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...
python
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...
[ "def", "from_json", "(", "cls", ",", "filename", ")", ":", "def", "json_decoder", "(", "d", ")", ":", "if", "'p01'", "in", "d", "and", "'pxx'", "in", "d", ":", "# we assume this is a CascadeStatistics object", "return", "melodist", ".", "cascade", ".", "Casc...
Imports statistical data from a JSON formatted file Parameters ---------- filename: input file that holds statistics data
[ "Imports", "statistical", "data", "from", "a", "JSON", "formatted", "file" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/stationstatistics.py#L226-L272
kristianfoerster/melodist
melodist/radiation.py
disaggregate_radiation
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, ...
python
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, ...
[ "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", ",", "bristcamp_c", ...
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 ...
[ "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"...
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L37-L93
kristianfoerster/melodist
melodist/radiation.py
potential_radiation
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...
python
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...
[ "def", "potential_radiation", "(", "dates", ",", "lon", ",", "lat", ",", "timezone", ",", "terrain_slope", "=", "0", ",", "terrain_slope_azimuth", "=", "0", ",", "cloud_fraction", "=", "0", ",", "split", "=", "False", ")", ":", "solar_constant", "=", "1367...
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...
[ "Calculate", "potential", "shortwave", "radiation", "for", "a", "specific", "location", "and", "time", ".", "This", "routine", "calculates", "global", "radiation", "as", "described", "in", ":", "Liston", "G", ".", "E", ".", "and", "Elder", "K", ".", "(", "...
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L96-L177
kristianfoerster/melodist
melodist/radiation.py
bristow_campbell
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 ...
python
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 ...
[ "def", "bristow_campbell", "(", "tmin", ",", "tmax", ",", "pot_rad_daily", ",", "A", ",", "C", ")", ":", "assert", "tmin", ".", "index", ".", "equals", "(", "tmax", ".", "index", ")", "temp", "=", "pd", ".", "DataFrame", "(", "data", "=", "dict", "...
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...
[ "calculates", "potential", "shortwave", "radiation", "based", "on", "minimum", "and", "maximum", "temperature", "This", "routine", "calculates", "global", "radiation", "as", "described", "in", ":", "Bristow", "Keith", "L", ".", "and", "Gaylon", "S", ".", "Campbe...
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L180-L221
kristianfoerster/melodist
melodist/radiation.py
fit_bristow_campbell_params
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 ---------...
python
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 ---------...
[ "def", "fit_bristow_campbell_params", "(", "tmin", ",", "tmax", ",", "pot_rad_daily", ",", "obs_rad_daily", ")", ":", "def", "bc_absbias", "(", "ac", ")", ":", "return", "np", ".", "abs", "(", "np", ".", "mean", "(", "bristow_campbell", "(", "df", ".", "...
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 ...
[ "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", "fr...
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L224-L250
kristianfoerster/melodist
melodist/radiation.py
angstroem
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...
python
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...
[ "def", "angstroem", "(", "ssd", ",", "day_length", ",", "pot_rad_daily", ",", "a", ",", "b", ")", ":", "if", "isinstance", "(", "a", ",", "pd", ".", "Series", ")", ":", "months", "=", "ssd", ".", "index", ".", "month", "a", "=", "a", ".", "loc", ...
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...
[ "Calculate", "mean", "daily", "radiation", "from", "observed", "sunshine", "duration", "according", "to", "Angstroem", "(", "1924", ")", ".", "Parameters", "----------", "ssd", ":", "Series", "Observed", "daily", "sunshine", "duration", ".", "day_length", ":", "...
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L253-L281
kristianfoerster/melodist
melodist/radiation.py
fit_angstroem_params
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 ...
python
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 ...
[ "def", "fit_angstroem_params", "(", "ssd", ",", "day_length", ",", "pot_rad_daily", ",", "obs_rad_daily", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "data", "=", "dict", "(", "ssd", "=", "ssd", ",", "day_length", "=", "day_length", ",", "pot", "="...
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...
[ "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", ")", "sola...
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/radiation.py#L284-L312
mdredze/carmen-python
carmen/resolver.py
register
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
python
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
[ "def", "register", "(", "name", ")", ":", "def", "decorator", "(", "class_", ")", ":", "if", "name", "in", "known_resolvers", ":", "raise", "ValueError", "(", "'duplicate resolver name \"%s\"'", "%", "name", ")", "known_resolvers", "[", "name", "]", "=", "cl...
Return a decorator that registers the decorated class as a resolver with the given *name*.
[ "Return", "a", "decorator", "that", "registers", "the", "decorated", "class", "as", "a", "resolver", "with", "the", "given", "*", "name", "*", "." ]
train
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolver.py#L105-L112
mdredze/carmen-python
carmen/resolver.py
get_resolver
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...
python
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...
[ "def", "get_resolver", "(", "order", "=", "None", ",", "options", "=", "None", ",", "modules", "=", "None", ")", ":", "if", "not", "known_resolvers", ":", "from", ".", "import", "resolvers", "as", "carmen_resolvers", "modules", "=", "[", "carmen_resolvers", ...
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...
[ "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...
train
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolver.py#L115-L149
mdredze/carmen-python
carmen/resolver.py
AbstractResolver.load_locations
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...
python
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...
[ "def", "load_locations", "(", "self", ",", "location_file", "=", "None", ")", ":", "if", "location_file", "is", "None", ":", "contents", "=", "pkgutil", ".", "get_data", "(", "__package__", ",", "'data/locations.json'", ")", "contents_string", "=", "contents", ...
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.
[ "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", "spe...
train
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/resolver.py#L22-L40
mdredze/carmen-python
carmen/location.py
Location.canonical
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()])
python
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()])
[ "def", "canonical", "(", "self", ")", ":", "try", ":", "return", "tuple", "(", "map", "(", "lambda", "x", ":", "x", ".", "lower", "(", ")", ",", "self", ".", "name", "(", ")", ")", ")", "except", ":", "return", "tuple", "(", "[", "x", ".", "l...
Return a tuple containing a canonicalized version of this location's country, state, county, and city names.
[ "Return", "a", "tuple", "containing", "a", "canonicalized", "version", "of", "this", "location", "s", "country", "state", "county", "and", "city", "names", "." ]
train
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/location.py#L79-L85
mdredze/carmen-python
carmen/location.py
Location.name
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...
python
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...
[ "def", "name", "(", "self", ")", ":", "try", ":", "return", "tuple", "(", "getattr", "(", "self", ",", "x", ")", "if", "getattr", "(", "self", ",", "x", ")", "else", "u''", "for", "x", "in", "(", "'country'", ",", "'state'", ",", "'county'", ",",...
Return a tuple containing this location's country, state, county, and city names.
[ "Return", "a", "tuple", "containing", "this", "location", "s", "country", "state", "county", "and", "city", "names", "." ]
train
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/location.py#L87-L97
mdredze/carmen-python
carmen/location.py
Location.parent
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...
python
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...
[ "def", "parent", "(", "self", ")", ":", "if", "self", ".", "city", ":", "return", "Location", "(", "country", "=", "self", ".", "country", ",", "state", "=", "self", ".", "state", ",", "county", "=", "self", ".", "county", ")", "if", "self", ".", ...
Return a location representing the administrative unit above the one represented by this location.
[ "Return", "a", "location", "representing", "the", "administrative", "unit", "above", "the", "one", "represented", "by", "this", "location", "." ]
train
https://github.com/mdredze/carmen-python/blob/070b974222b5407f7aae2518ffbdf9df198b8e96/carmen/location.py#L99-L109
kristianfoerster/melodist
melodist/humidity.py
disaggregate_humidity
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...
python
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...
[ "def", "disaggregate_humidity", "(", "data_daily", ",", "method", "=", "'equal'", ",", "temp", "=", "None", ",", "a0", "=", "None", ",", "a1", "=", "None", ",", "kr", "=", "None", ",", "month_hour_precip_mean", "=", "None", ",", "preserve_daily_mean", "=",...
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...
[ "general", "function", "for", "humidity", "disaggregation" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/humidity.py#L33-L109
kristianfoerster/melodist
melodist/wind.py
_cosine_function
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...
python
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...
[ "def", "_cosine_function", "(", "x", ",", "a", ",", "b", ",", "t_shift", ")", ":", "mean_wind", ",", "t", "=", "x", "return", "a", "*", "mean_wind", "*", "np", ".", "cos", "(", "np", ".", "pi", "*", "(", "t", "-", "t_shift", ")", "/", "12", "...
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: ...
[ "genrates", "a", "diurnal", "course", "of", "windspeed", "accroding", "to", "the", "cosine", "function" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/wind.py#L33-L47
kristianfoerster/melodist
melodist/wind.py
disaggregate_wind
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 ...
python
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 ...
[ "def", "disaggregate_wind", "(", "wind_daily", ",", "method", "=", "'equal'", ",", "a", "=", "None", ",", "b", "=", "None", ",", "t_shift", "=", "None", ")", ":", "assert", "method", "in", "(", "'equal'", ",", "'cosine'", ",", "'random'", ")", ",", "...
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 ...
[ "general", "function", "for", "windspeed", "disaggregation" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/wind.py#L50-L75
kristianfoerster/melodist
melodist/wind.py
fit_cosine_function
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)....
python
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)....
[ "def", "fit_cosine_function", "(", "wind", ")", ":", "wind_daily", "=", "wind", ".", "groupby", "(", "wind", ".", "index", ".", "date", ")", ".", "mean", "(", ")", "wind_daily_hourly", "=", "pd", ".", "Series", "(", "index", "=", "wind", ".", "index", ...
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
[ "fits", "a", "cosine", "function", "to", "observed", "hourly", "windspeed", "data" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/wind.py#L78-L94
kristianfoerster/melodist
melodist/data_io.py
read_smet
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 : "...
python
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 : "...
[ "def", "read_smet", "(", "filename", ",", "mode", ")", ":", "# dictionary", "# based on smet spec V.1.1 and self defined", "# daily data", "dict_d", "=", "{", "'TA'", ":", "'tmean'", ",", "'TMAX'", ":", "'tmax'", ",", "# no spec", "'TMIN'", ":", "'tmin'", ",", "...
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", "smet", "data", "and", "returns", "the", "data", "in", "required", "dataformat", "(", "pd", "df", ")" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L33-L113
kristianfoerster/melodist
melodist/data_io.py
read_dwd
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...
python
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...
[ "def", "read_dwd", "(", "filename", ",", "metadata", ",", "mode", "=", "\"d\"", ",", "skip_last", "=", "True", ")", ":", "def", "read_single_dwd", "(", "filename", ",", "metadata", ",", "mode", ",", "skip_last", ")", ":", "# Param names {'DWD':'dissag_def'}", ...
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...
[ "Reads", "dwd", "(", "German", "Weather", "Service", ")", "data", "and", "returns", "the", "data", "in", "required", "dataformat", "(", "pd", "df", ")" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L116-L233
kristianfoerster/melodist
melodist/data_io.py
write_smet
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 ...
python
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 ...
[ "def", "write_smet", "(", "filename", ",", "data", ",", "metadata", ",", "nodata_value", "=", "-", "999", ",", "mode", "=", "'h'", ",", "check_nan", "=", "True", ")", ":", "# dictionary", "# based on smet spec V.1.1 and selfdefined", "# daily data", "dict_d", "=...
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...
[ "writes", "smet", "files" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L236-L320
kristianfoerster/melodist
melodist/data_io.py
read_single_knmi_file
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 ...
python
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 ...
[ "def", "read_single_knmi_file", "(", "filename", ")", ":", "hourly_data_obs_raw", "=", "pd", ".", "read_csv", "(", "filename", ",", "parse_dates", "=", "[", "[", "'YYYYMMDD'", ",", "'HH'", "]", "]", ",", "date_parser", "=", "lambda", "yyyymmdd", ",", "hh", ...
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
[ "reads", "a", "single", "file", "of", "KNMI", "s", "meteorological", "time", "series" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L323-L367
kristianfoerster/melodist
melodist/data_io.py
read_knmi_dataset
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: ...
python
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: ...
[ "def", "read_knmi_dataset", "(", "directory", ")", ":", "filemask", "=", "'%s*.txt'", "%", "directory", "filelist", "=", "glob", ".", "glob", "(", "filemask", ")", "columns_hourly", "=", "[", "'temp'", ",", "'precip'", ",", "'glob'", ",", "'hum'", ",", "'w...
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...
[ "Reads", "files", "from", "a", "directory", "and", "merges", "the", "time", "series" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/data_io.py#L370-L397
kristianfoerster/melodist
melodist/station.py
Station.calc_sun_times
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)
python
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)
[ "def", "calc_sun_times", "(", "self", ")", ":", "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.
[ "Computes", "the", "times", "of", "sunrise", "solar", "noon", "and", "sunset", "for", "each", "day", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L174-L179
kristianfoerster/melodist
melodist/station.py
Station.disaggregate_wind
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) ...
python
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) ...
[ "def", "disaggregate_wind", "(", "self", ",", "method", "=", "'equal'", ")", ":", "self", ".", "data_disagg", ".", "wind", "=", "melodist", ".", "disaggregate_wind", "(", "self", ".", "data_daily", ".", "wind", ",", "method", "=", "method", ",", "*", "*"...
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", "wind", "speed", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L181-L201
kristianfoerster/melodist
melodist/station.py
Station.disaggregate_humidity
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...
python
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...
[ "def", "disaggregate_humidity", "(", "self", ",", "method", "=", "'equal'", ",", "preserve_daily_mean", "=", "False", ")", ":", "self", ".", "data_disagg", ".", "hum", "=", "melodist", ".", "disaggregate_humidity", "(", "self", ".", "data_daily", ",", "temp", ...
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", "relative", "humidity", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L203-L243
kristianfoerster/melodist
melodist/station.py
Station.disaggregate_temperature
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...
python
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...
[ "def", "disaggregate_temperature", "(", "self", ",", "method", "=", "'sine_min_max'", ",", "min_max_time", "=", "'fix'", ",", "mod_nighttime", "=", "False", ")", ":", "self", ".", "data_disagg", ".", "temp", "=", "melodist", ".", "disaggregate_temperature", "(",...
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", "air", "temperature", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L245-L296
kristianfoerster/melodist
melodist/station.py
Station.disaggregate_precipitation
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...
python
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...
[ "def", "disaggregate_precipitation", "(", "self", ",", "method", "=", "'equal'", ",", "zerodiv", "=", "'uniform'", ",", "shift", "=", "0", ",", "master_precip", "=", "None", ")", ":", "if", "method", "==", "'equal'", ":", "precip_disagg", "=", "melodist", ...
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", "precipitation", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L298-L338
kristianfoerster/melodist
melodist/station.py
Station.disaggregate_radiation
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...
python
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...
[ "def", "disaggregate_radiation", "(", "self", ",", "method", "=", "'pot_rad'", ",", "pot_rad", "=", "None", ")", ":", "if", "self", ".", "sun_times", "is", "None", ":", "self", ".", "calc_sun_times", "(", ")", "if", "pot_rad", "is", "None", "and", "metho...
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...
[ "Disaggregate", "solar", "radiation", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L340-L383
kristianfoerster/melodist
melodist/station.py
Station.interpolate
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...
python
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...
[ "def", "interpolate", "(", "self", ",", "column_hours", ",", "method", "=", "'linear'", ",", "limit", "=", "24", ",", "limit_direction", "=", "'both'", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "dict", "(", "kwargs", ",", "method", "=", "method...
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...
[ "Wrapper", "function", "for", "pandas", ".", "Series", ".", "interpolate", "that", "can", "be", "used", "to", "disaggregate", "values", "using", "various", "interpolation", "methods", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/station.py#L385-L412
boydgreenfield/query
query/core.py
QueryDbOrm._query_helper
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. " ...
python
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. " ...
[ "def", "_query_helper", "(", "self", ",", "by", "=", "None", ")", ":", "if", "by", "is", "None", ":", "primary_keys", "=", "self", ".", "table", ".", "primary_key", ".", "columns", ".", "keys", "(", ")", "if", "len", "(", "primary_keys", ")", ">", ...
Internal helper for preparing queries.
[ "Internal", "helper", "for", "preparing", "queries", "." ]
train
https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L72-L99
boydgreenfield/query
query/core.py
QueryDbOrm.head
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...
python
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...
[ "def", "head", "(", "self", ",", "n", "=", "10", ",", "by", "=", "None", ",", "*", "*", "kwargs", ")", ":", "col", ",", "id_col", "=", "self", ".", "_query_helper", "(", "by", "=", "by", ")", "select", "=", "(", "\"SELECT %s FROM %s ORDER BY %s ASC L...
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.
[ "Get", "the", "first", "n", "entries", "for", "a", "given", "Table", "/", "Column", ".", "Additional", "keywords", "passed", "to", "QueryDb", ".", "query", "()", "." ]
train
https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L101-L113
boydgreenfield/query
query/core.py
QueryDbOrm.last
def last(self, n=10, by=None, **kwargs): """ Alias for .tail(). """ return self.tail(n=n, by=by, **kwargs)
python
def last(self, n=10, by=None, **kwargs): """ Alias for .tail(). """ return self.tail(n=n, by=by, **kwargs)
[ "def", "last", "(", "self", ",", "n", "=", "10", ",", "by", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "tail", "(", "n", "=", "n", ",", "by", "=", "by", ",", "*", "*", "kwargs", ")" ]
Alias for .tail().
[ "Alias", "for", ".", "tail", "()", "." ]
train
https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L134-L138
boydgreenfield/query
query/core.py
QueryDbOrm.where
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()...
python
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()...
[ "def", "where", "(", "self", ",", "where_string", ",", "*", "*", "kwargs", ")", ":", "col", ",", "id_col", "=", "self", ".", "_query_helper", "(", "by", "=", "None", ")", "where_string", "=", "str", "(", "where_string", ")", "# Coerce here, for .__contains...
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 ...
[ "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", ...
train
https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L140-L170
boydgreenfield/query
query/core.py
QueryDb.query
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...
python
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...
[ "def", "query", "(", "self", ",", "sql_query", ",", "return_as", "=", "\"dataframe\"", ")", ":", "if", "isinstance", "(", "sql_query", ",", "str", ")", ":", "pass", "elif", "isinstance", "(", "sql_query", ",", "unicode", ")", ":", "sql_query", "=", "str"...
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 ...
[ "Execute", "a", "raw", "SQL", "query", "against", "the", "the", "SQL", "DB", "." ]
train
https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L298-L335
boydgreenfield/query
query/core.py
QueryDb._set_metadata
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 ...
python
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 ...
[ "def", "_set_metadata", "(", "self", ")", ":", "meta", "=", "QueryDbMeta", "(", ")", "with", "self", ".", "_engine", ".", "connect", "(", ")", "as", "conn", ":", "meta", ".", "bind", "=", "conn", "meta", ".", "reflect", "(", ")", "self", ".", "_met...
Internal helper to set metadata attributes.
[ "Internal", "helper", "to", "set", "metadata", "attributes", "." ]
train
https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L337-L373
boydgreenfield/query
query/core.py
QueryDb._to_df
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...
python
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...
[ "def", "_to_df", "(", "self", ",", "query", ",", "conn", ",", "index_col", "=", "None", ",", "coerce_float", "=", "True", ",", "params", "=", "None", ",", "parse_dates", "=", "None", ",", "columns", "=", "None", ")", ":", "return", "pd", ".", "io", ...
Internal convert-to-DataFrame convenience wrapper.
[ "Internal", "convert", "-", "to", "-", "DataFrame", "convenience", "wrapper", "." ]
train
https://github.com/boydgreenfield/query/blob/03aa43b746b43832af3f0403265e648a5617b62b/query/core.py#L375-L382
kristianfoerster/melodist
melodist/temperature.py
disaggregate_temperature
def disaggregate_temperature(data_daily, method='sine_min_max', min_max_time='fix', mod_nighttime=False, max_delta=None, mean_course=None, sun_tim...
python
def disaggregate_temperature(data_daily, method='sine_min_max', min_max_time='fix', mod_nighttime=False, max_delta=None, mean_course=None, sun_tim...
[ "def", "disaggregate_temperature", "(", "data_daily", ",", "method", "=", "'sine_min_max'", ",", "min_max_time", "=", "'fix'", ",", "mod_nighttime", "=", "False", ",", "max_delta", "=", "None", ",", "mean_course", "=", "None", ",", "sun_times", "=", "None", ")...
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, ...
[ "The", "disaggregation", "function", "for", "temperature" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/temperature.py#L33-L212
kristianfoerster/melodist
melodist/temperature.py
get_shift_by_data
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...
python
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...
[ "def", "get_shift_by_data", "(", "temp_hourly", ",", "lon", ",", "lat", ",", "time_zone", ")", ":", "daily_index", "=", "temp_hourly", ".", "resample", "(", "'D'", ")", ".", "mean", "(", ")", ".", "index", "sun_times", "=", "melodist", ".", "util", ".", ...
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
[ "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_z...
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/temperature.py#L215-L235
kristianfoerster/melodist
melodist/util/util.py
distribute_equally
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). ...
python
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). ...
[ "def", "distribute_equally", "(", "daily_data", ",", "divide", "=", "False", ")", ":", "index", "=", "hourly_index", "(", "daily_data", ".", "index", ")", "hourly_data", "=", "daily_data", ".", "reindex", "(", "index", ")", "hourly_data", "=", "hourly_data", ...
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.
[ "Obtains", "hourly", "values", "by", "equally", "distributing", "the", "daily", "values", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L50-L70
kristianfoerster/melodist
melodist/util/util.py
vapor_pressure
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...
python
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...
[ "def", "vapor_pressure", "(", "temp", ",", "hum", ")", ":", "if", "np", ".", "isscalar", "(", "hum", ")", ":", "hum", "=", "np", ".", "zeros", "(", "temp", ".", "shape", ")", "+", "hum", "assert", "(", "temp", ".", "shape", "==", "hum", ".", "s...
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.
[ "Calculates", "vapor", "pressure", "from", "temperature", "and", "humidity", "after", "Sonntag", "(", "1990", ")", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L73-L95
kristianfoerster/melodist
melodist/util/util.py
dewpoint_temperature
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...
python
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...
[ "def", "dewpoint_temperature", "(", "temp", ",", "hum", ")", ":", "assert", "(", "temp", ".", "shape", "==", "hum", ".", "shape", ")", "vap_press", "=", "vapor_pressure", "(", "temp", ",", "hum", ")", "positives", "=", "np", ".", "array", "(", "temp", ...
computes the dewpoint temperature Parameters ---- temp : temperature [K] hum : relative humidity Returns dewpoint temperature in K
[ "computes", "the", "dewpoint", "temperature" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L98-L119
kristianfoerster/melodist
melodist/util/util.py
linregress
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...
python
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...
[ "def", "linregress", "(", "x", ",", "y", ",", "return_stats", "=", "False", ")", ":", "a1", ",", "a0", ",", "r_value", ",", "p_value", ",", "stderr", "=", "scipy", ".", "stats", ".", "linregress", "(", "x", ",", "y", ")", "retval", "=", "a1", ","...
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)
[ "linear", "regression", "calculation" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L122-L142
kristianfoerster/melodist
melodist/util/util.py
get_sun_times
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,...
python
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,...
[ "def", "get_sun_times", "(", "dates", ",", "lon", ",", "lat", ",", "time_zone", ")", ":", "df", "=", "pd", ".", "DataFrame", "(", "index", "=", "dates", ",", "columns", "=", "[", "'sunrise'", ",", "'sunnoon'", ",", "'sunset'", ",", "'daylength'", "]", ...
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
[ "Computes", "the", "times", "of", "sunrise", "solar", "noon", "and", "sunset", "for", "each", "day", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L145-L221
kristianfoerster/melodist
melodist/util/util.py
detect_gaps
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...
python
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...
[ "def", "detect_gaps", "(", "dataframe", ",", "timestep", ",", "print_all", "=", "False", ",", "print_max", "=", "5", ",", "verbose", "=", "True", ")", ":", "gcount", "=", "0", "msg_counter", "=", "0", "warning_printed", "=", "False", "try", ":", "n", "...
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...
[ "checks", "if", "a", "given", "dataframe", "contains", "gaps", "and", "returns", "the", "number", "of", "gaps" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L224-L265
kristianfoerster/melodist
melodist/util/util.py
drop_incomplete_days
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...
python
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...
[ "def", "drop_incomplete_days", "(", "dataframe", ",", "shift", "=", "0", ")", ":", "dropped", "=", "0", "if", "shift", ">", "23", "or", "shift", "<", "0", ":", "print", "(", "\"Invalid shift parameter setting! Using defaults.\"", ")", "shift", "=", "0", "fir...
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...
[ "truncates", "a", "given", "dataframe", "to", "full", "days", "only" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L268-L320
kristianfoerster/melodist
melodist/util/util.py
daily_from_hourly
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_...
python
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_...
[ "def", "daily_from_hourly", "(", "df", ")", ":", "df_daily", "=", "pd", ".", "DataFrame", "(", ")", "if", "'temp'", "in", "df", ":", "df_daily", "[", "'temp'", "]", "=", "df", ".", "temp", ".", "resample", "(", "'D'", ")", ".", "mean", "(", ")", ...
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)
[ "Aggregates", "data", "(", "hourly", "to", "daily", "values", ")", "according", "to", "the", "characteristics", "of", "each", "variable", "(", "e", ".", "g", ".", "average", "for", "temperature", "sum", "for", "precipitation", ")" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/util/util.py#L340-L380
kristianfoerster/melodist
melodist/precipitation.py
disagg_prec
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...
python
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...
[ "def", "disagg_prec", "(", "dailyData", ",", "method", "=", "'equal'", ",", "cascade_options", "=", "None", ",", "hourly_data_obs", "=", "None", ",", "zerodiv", "=", "\"uniform\"", ",", "shift", "=", "0", ")", ":", "if", "method", "not", "in", "(", "'equ...
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 ...
[ "The", "disaggregation", "function", "for", "precipitation", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L45-L87
kristianfoerster/melodist
melodist/precipitation.py
disagg_prec_cascade
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 ...
python
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 ...
[ "def", "disagg_prec_cascade", "(", "precip_daily", ",", "cascade_options", ",", "hourly", "=", "True", ",", "level", "=", "9", ",", "shift", "=", "0", ",", "test", "=", "False", ")", ":", "if", "len", "(", "precip_daily", ")", "<", "2", ":", "raise", ...
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...
[ "Precipitation", "disaggregation", "with", "cascade", "model", "(", "Olsson", "1998", ")" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L90-L357
kristianfoerster/melodist
melodist/precipitation.py
precip_master_station
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 ...
python
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 ...
[ "def", "precip_master_station", "(", "precip_daily", ",", "master_precip_hourly", ",", "zerodiv", ")", ":", "precip_hourly", "=", "pd", ".", "Series", "(", "index", "=", "melodist", ".", "util", ".", "hourly_index", "(", "precip_daily", ".", "index", ")", ")",...
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...
[ "Disaggregate", "precipitation", "based", "on", "the", "patterns", "of", "a", "master", "station" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L359-L400
kristianfoerster/melodist
melodist/precipitation.py
aggregate_precipitation
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...
python
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...
[ "def", "aggregate_precipitation", "(", "vec_data", ",", "hourly", "=", "True", ",", "percentile", "=", "50", ")", ":", "cascade_opt", "=", "cascade", ".", "CascadeStatistics", "(", ")", "cascade_opt", ".", "percentile", "=", "percentile", "# length of input time s...
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
[ "Aggregates", "highly", "resolved", "precipitation", "data", "and", "creates", "statistics" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L403-L586
kristianfoerster/melodist
melodist/precipitation.py
seasonal_subset
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...
python
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...
[ "def", "seasonal_subset", "(", "dataframe", ",", "months", "=", "'all'", ")", ":", "if", "isinstance", "(", "months", ",", "str", ")", "and", "months", "==", "'all'", ":", "months", "=", "np", ".", "arange", "(", "12", ")", "+", "1", "for", "month_nu...
Get the seasonal data. Parameters ---------- dataframe : pd.DataFrame months: int, str Months to use for statistics, or 'all' for 1-12 (default='all')
[ "Get", "the", "seasonal", "data", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L589-L611
kristianfoerster/melodist
melodist/precipitation.py
build_casc
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...
python
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...
[ "def", "build_casc", "(", "ObsData", ",", "hourly", "=", "True", ",", "level", "=", "9", ",", "months", "=", "None", ",", "avg_stats", "=", "True", ",", "percentile", "=", "50", ")", ":", "list_seasonal_casc", "=", "list", "(", ")", "if", "months", "...
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...
[ "Builds", "the", "cascade", "statistics", "of", "observed", "data", "for", "disaggregation" ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/precipitation.py#L614-L690
kristianfoerster/melodist
melodist/cascade.py
CascadeStatistics.fill_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 # type of data will be available self.p01 = np.array...
python
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...
[ "def", "fill_with_sample_data", "(", "self", ")", ":", "# 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.
[ "This", "function", "fills", "the", "corresponding", "object", "with", "sample", "data", "." ]
train
https://github.com/kristianfoerster/melodist/blob/ddc155c77b65f791be0021dbbaf68c6bac42ecbd/melodist/cascade.py#L54-L81
gaqzi/django-emoji
emoji/models.py
Emoji.names
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...
python
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...
[ "def", "names", "(", "cls", ")", ":", "if", "not", "cls", ".", "_files", ":", "for", "f", "in", "os", ".", "listdir", "(", "cls", ".", "_image_path", ")", ":", "if", "(", "not", "f", ".", "startswith", "(", "'.'", ")", "and", "os", ".", "path",...
A list of all emoji names without file extension.
[ "A", "list", "of", "all", "emoji", "names", "without", "file", "extension", "." ]
train
https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L114-L122
gaqzi/django-emoji
emoji/models.py
Emoji.replace
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...
python
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...
[ "def", "replace", "(", "cls", ",", "replacement_string", ")", ":", "e", "=", "cls", "(", ")", "def", "_replace_emoji", "(", "match", ")", ":", "val", "=", "match", ".", "group", "(", "1", ")", "if", "val", "in", "e", ":", "return", "e", ".", "_im...
Add in valid emojis in a string where a valid emoji is between ::
[ "Add", "in", "valid", "emojis", "in", "a", "string", "where", "a", "valid", "emoji", "is", "between", "::" ]
train
https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L125-L136
gaqzi/django-emoji
emoji/models.py
Emoji.replace_unicode
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...
python
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...
[ "def", "replace_unicode", "(", "cls", ",", "replacement_string", ")", ":", "e", "=", "cls", "(", ")", "output", "=", "[", "]", "surrogate_character", "=", "None", "if", "settings", ".", "EMOJI_REPLACE_HTML_ENTITIES", ":", "replacement_string", "=", "cls", ".",...
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...
[ "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", "replac...
train
https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L139-L188
gaqzi/django-emoji
emoji/models.py
Emoji.replace_html_entities
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...
python
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...
[ "def", "replace_html_entities", "(", "cls", ",", "replacement_string", ")", ":", "def", "_hex_to_unicode", "(", "hex_code", ")", ":", "if", "PYTHON3", ":", "hex_code", "=", "'{0:0>8}'", ".", "format", "(", "hex_code", ")", "as_int", "=", "struct", ".", "unpa...
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).
[ "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", "(", ...
train
https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/emoji/models.py#L198-L234
gaqzi/django-emoji
bin/generate-unicode-aliases.py
_convert_to_unicode
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...
python
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...
[ "def", "_convert_to_unicode", "(", "string", ")", ":", "codepoints", "=", "[", "]", "for", "character", "in", "string", ".", "split", "(", "'-'", ")", ":", "if", "character", "in", "BLACKLIST_UNICODE", ":", "next", "codepoints", ".", "append", "(", "'\\U{0...
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.
[ "This", "method", "should", "work", "with", "both", "Python", "2", "and", "3", "with", "the", "caveat", "that", "they", "need", "to", "be", "compiled", "with", "wide", "unicode", "character", "support", "." ]
train
https://github.com/gaqzi/django-emoji/blob/08625d14f5b4251f4784bb5abf2620cb46bbdcab/bin/generate-unicode-aliases.py#L32-L49
acsone/bobtemplates.odoo
bobtemplates/odoo/hooks.py
_delete_file
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
python
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
[ "def", "_delete_file", "(", "configurator", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "configurator", ".", "target_directory", ",", "path", ")", "os", ".", "remove", "(", "path", ")", "try", ":", "os", ".", "removedirs", ...
remove file and remove it's directories if empty
[ "remove", "file", "and", "remove", "it", "s", "directories", "if", "empty" ]
train
https://github.com/acsone/bobtemplates.odoo/blob/6e8c3cb12747d8b5af5a9821f995f285251e4d4d/bobtemplates/odoo/hooks.py#L34-L41
acsone/bobtemplates.odoo
bobtemplates/odoo/hooks.py
_insert_manifest_item
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...
python
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...
[ "def", "_insert_manifest_item", "(", "configurator", ",", "key", ",", "item", ")", ":", "with", "_open_manifest", "(", "configurator", ")", "as", "f", ":", "manifest", "=", "f", ".", "read", "(", ")", "if", "item", "in", "ast", ".", "literal_eval", "(", ...
Insert an item in the list of an existing manifest key
[ "Insert", "an", "item", "in", "the", "list", "of", "an", "existing", "manifest", "key" ]
train
https://github.com/acsone/bobtemplates.odoo/blob/6e8c3cb12747d8b5af5a9821f995f285251e4d4d/bobtemplates/odoo/hooks.py#L58-L68
nyaruka/smartmin
setup.py
_read_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)]
python
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)]
[ "def", "_read_requirements", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "requirements_file", ":", "contents", "=", "requirements_file", ".", "read", "(", ")", "return", "[", "line", ".", "strip", "(", ")", "for", "line", "in", ...
Parses a file for pip installation requirements.
[ "Parses", "a", "file", "for", "pip", "installation", "requirements", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/setup.py#L17-L21
nyaruka/smartmin
smartmin/perms.py
assign_perm
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" ...
python
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" ...
[ "def", "assign_perm", "(", "perm", ",", "group", ")", ":", "if", "not", "isinstance", "(", "perm", ",", "Permission", ")", ":", "try", ":", "app_label", ",", "codename", "=", "perm", ".", "split", "(", "'.'", ",", "1", ")", "except", "ValueError", ":...
Assigns a permission to a group
[ "Assigns", "a", "permission", "to", "a", "group" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/perms.py#L4-L17
nyaruka/smartmin
smartmin/perms.py
remove_perm
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" ...
python
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" ...
[ "def", "remove_perm", "(", "perm", ",", "group", ")", ":", "if", "not", "isinstance", "(", "perm", ",", "Permission", ")", ":", "try", ":", "app_label", ",", "codename", "=", "perm", ".", "split", "(", "'.'", ",", "1", ")", "except", "ValueError", ":...
Removes a permission from a group
[ "Removes", "a", "permission", "from", "a", "group" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/perms.py#L20-L33
nyaruka/smartmin
smartmin/templatetags/smartmin.py
get_list_class
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)
python
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)
[ "def", "get_list_class", "(", "context", ",", "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.
[ "Returns", "the", "class", "to", "use", "for", "the", "passed", "in", "list", ".", "We", "just", "build", "something", "up", "from", "the", "object", "type", "for", "the", "list", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L24-L29
nyaruka/smartmin
smartmin/templatetags/smartmin.py
format_datetime
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...
python
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...
[ "def", "format_datetime", "(", "time", ")", ":", "user_time_zone", "=", "timezone", ".", "get_current_timezone", "(", ")", "if", "time", ".", "tzinfo", "is", "None", ":", "time", "=", "time", ".", "replace", "(", "tzinfo", "=", "pytz", ".", "utc", ")", ...
Formats a date, converting the time to the user timezone if one is specified
[ "Formats", "a", "date", "converting", "the", "time", "to", "the", "user", "timezone", "if", "one", "is", "specified" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L32-L42
nyaruka/smartmin
smartmin/templatetags/smartmin.py
get_value_from_view
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...
python
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...
[ "def", "get_value_from_view", "(", "context", ",", "field", ")", ":", "view", "=", "context", "[", "'view'", "]", "obj", "=", "None", "if", "'object'", "in", "context", ":", "obj", "=", "context", "[", "'object'", "]", "value", "=", "view", ".", "looku...
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.
[ "Responsible", "for", "deriving", "the", "displayed", "value", "for", "the", "passed", "in", "field", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L46-L64
nyaruka/smartmin
smartmin/templatetags/smartmin.py
get_class
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)
python
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)
[ "def", "get_class", "(", "context", ",", "field", ",", "obj", "=", "None", ")", ":", "view", "=", "context", "[", "'view'", "]", "return", "view", ".", "lookup_field_class", "(", "field", ",", "obj", ",", "\"field_\"", "+", "field", ")" ]
Looks up the class for this field
[ "Looks", "up", "the", "class", "for", "this", "field" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L84-L89
nyaruka/smartmin
smartmin/templatetags/smartmin.py
get_label
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...
python
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...
[ "def", "get_label", "(", "context", ",", "field", ",", "obj", "=", "None", ")", ":", "view", "=", "context", "[", "'view'", "]", "return", "view", ".", "lookup_field_label", "(", "context", ",", "field", ",", "obj", ")" ]
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
[ "Responsible", "for", "figuring", "out", "the", "right", "label", "for", "the", "passed", "in", "field", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L93-L102
nyaruka/smartmin
smartmin/templatetags/smartmin.py
get_field_link
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)
python
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)
[ "def", "get_field_link", "(", "context", ",", "field", ",", "obj", "=", "None", ")", ":", "view", "=", "context", "[", "'view'", "]", "return", "view", ".", "lookup_field_link", "(", "context", ",", "field", ",", "obj", ")" ]
Determine what the field link should be for the given field, object pair
[ "Determine", "what", "the", "field", "link", "should", "be", "for", "the", "given", "field", "object", "pair" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/templatetags/smartmin.py#L106-L111
nyaruka/smartmin
smartmin/management/__init__.py
get_permissions_app_name
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...
python
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...
[ "def", "get_permissions_app_name", "(", ")", ":", "global", "permissions_app_name", "if", "not", "permissions_app_name", ":", "permissions_app_name", "=", "getattr", "(", "settings", ",", "'PERMISSIONS_APP'", ",", "None", ")", "if", "not", "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
[ "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" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L15-L30
nyaruka/smartmin
smartmin/management/__init__.py
check_role_permissions
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...
python
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...
[ "def", "check_role_permissions", "(", "role", ",", "permissions", ",", "current_permissions", ")", ":", "role_permissions", "=", "[", "]", "# get all the current permissions, we'll remove these as we verify they should still be granted", "for", "permission", "in", "permissions", ...
Checks the the passed in role (can be user, group or AnonymousUser) has all the passed in permissions, granting them if necessary.
[ "Checks", "the", "the", "passed", "in", "role", "(", "can", "be", "user", "group", "or", "AnonymousUser", ")", "has", "all", "the", "passed", "in", "permissions", "granting", "them", "if", "necessary", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L40-L95
nyaruka/smartmin
smartmin/management/__init__.py
check_all_group_permissions
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...
python
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...
[ "def", "check_all_group_permissions", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_permissions_app", "(", "sender", ")", ":", "return", "config", "=", "getattr", "(", "settings", ",", "'GROUP_PERMISSIONS'", ",", "dict", "(", ")", ")", ...
Checks that all the permissions specified in our settings.py are set for our groups.
[ "Checks", "that", "all", "the", "permissions", "specified", "in", "our", "settings", ".", "py", "are", "set", "for", "our", "groups", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L98-L114
nyaruka/smartmin
smartmin/management/__init__.py
add_permission
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...
python
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...
[ "def", "add_permission", "(", "content_type", ",", "permission", ")", ":", "# build our permission slug", "codename", "=", "\"%s_%s\"", "%", "(", "content_type", ".", "model", ",", "permission", ")", "# sys.stderr.write(\"Checking %s permission for %s\\n\" % (permission, cont...
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.
[ "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"...
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L117-L131
nyaruka/smartmin
smartmin/management/__init__.py
check_all_permissions
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 ...
python
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 ...
[ "def", "check_all_permissions", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "is_permissions_app", "(", "sender", ")", ":", "return", "config", "=", "getattr", "(", "settings", ",", "'PERMISSIONS'", ",", "dict", "(", ")", ")", "# for each...
This syncdb checks our PERMISSIONS setting in settings.py and makes sure all those permissions actually exit.
[ "This", "syncdb", "checks", "our", "PERMISSIONS", "setting", "in", "settings", ".", "py", "and", "makes", "sure", "all", "those", "permissions", "actually", "exit", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/management/__init__.py#L135-L164
nyaruka/smartmin
smartmin/users/views.py
UserForm.save
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...
python
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...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "is_new_user", "=", "self", ".", "instance", ".", "pk", "is", "None", "user", "=", "super", "(", "UserForm", ",", "self", ")", ".", "save", "(", "commit", ")", "# new users should be mad...
Overloaded so we can save any new password that is included.
[ "Overloaded", "so", "we", "can", "save", "any", "new", "password", "that", "is", "included", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/users/views.py#L39-L58
nyaruka/smartmin
smartmin/views.py
smart_url
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...
python
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...
[ "def", "smart_url", "(", "url", ",", "obj", "=", "None", ")", ":", "if", "url", ".", "find", "(", "\"@\"", ")", ">=", "0", ":", "(", "args", ",", "value", ")", "=", "url", ".", "split", "(", "'@'", ")", "if", "args", ":", "val", "=", "getattr...
URLs that start with @ are reversed, using the passed in arguments. Otherwise a straight % substitution is applied.
[ "URLs", "that", "start", "with", "@", "are", "reversed", "using", "the", "passed", "in", "arguments", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L31-L49
nyaruka/smartmin
smartmin/views.py
derive_single_object_url_pattern
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)
python
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)
[ "def", "derive_single_object_url_pattern", "(", "slug_url_kwarg", ",", "path", ",", "action", ")", ":", "if", "slug_url_kwarg", ":", "return", "r'^%s/%s/(?P<%s>[^/]+)/$'", "%", "(", "path", ",", "action", ",", "slug_url_kwarg", ")", "else", ":", "return", "r'^%s/%...
Utility function called by class methods for single object views
[ "Utility", "function", "called", "by", "class", "methods", "for", "single", "object", "views" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L390-L397
nyaruka/smartmin
smartmin/views.py
SmartView.has_permission
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:...
python
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:...
[ "def", "has_permission", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "kwargs", "=", "kwargs", "self", ".", "args", "=", "args", "self", ".", "request", "=", "request", "if", "not", "getattr", "(", ...
Figures out if the current user has permissions for this view.
[ "Figures", "out", "if", "the", "current", "user", "has", "permissions", "for", "this", "view", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L88-L99
nyaruka/smartmin
smartmin/views.py
SmartView.dispatch
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...
python
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...
[ "def", "dispatch", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "wrapper", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "has_permission", "(", "request", ...
Overloaded to check permissions if appropriate
[ "Overloaded", "to", "check", "permissions", "if", "appropriate" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L101-L118
nyaruka/smartmin
smartmin/views.py
SmartView.lookup_obj_attribute
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...
python
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...
[ "def", "lookup_obj_attribute", "(", "self", ",", "obj", ",", "field", ")", ":", "curr_field", "=", "field", ".", "encode", "(", "'ascii'", ",", "'ignore'", ")", ".", "decode", "(", "\"utf-8\"", ")", "rest", "=", "None", "if", "field", ".", "find", "(",...
Looks for a field's value from the passed in obj. Note that this will strip leading attributes to deal with subelements if possible
[ "Looks", "for", "a", "field", "s", "value", "from", "the", "passed", "in", "obj", ".", "Note", "that", "this", "will", "strip", "leading", "attributes", "to", "deal", "with", "subelements", "if", "possible" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L130-L152
nyaruka/smartmin
smartmin/views.py
SmartView.lookup_field_value
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 ...
python
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 ...
[ "def", "lookup_field_value", "(", "self", ",", "context", ",", "obj", ",", "field", ")", ":", "curr_field", "=", "field", ".", "encode", "(", "'ascii'", ",", "'ignore'", ")", ".", "decode", "(", "\"utf-8\"", ")", "# if this isn't a subfield, check the view to se...
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 ...
[ "Looks", "up", "the", "field", "value", "for", "the", "passed", "in", "object", "and", "field", "name", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L154-L173
nyaruka/smartmin
smartmin/views.py
SmartView.lookup_field_label
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...
python
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...
[ "def", "lookup_field_label", "(", "self", ",", "context", ",", "field", ",", "default", "=", "None", ")", ":", "# if this is a subfield, strip off everything but the last field name", "if", "field", ".", "find", "(", "'.'", ")", ">=", "0", ":", "return", "self", ...
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
[ "Figures", "out", "what", "the", "field", "label", "should", "be", "for", "the", "passed", "in", "field", "name", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L175-L207
nyaruka/smartmin
smartmin/views.py
SmartView.lookup_field_help
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...
python
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...
[ "def", "lookup_field_help", "(", "self", ",", "field", ",", "default", "=", "None", ")", ":", "help", "=", "None", "# is there a label specified for this field", "if", "field", "in", "self", ".", "field_config", "and", "'help'", "in", "self", ".", "field_config"...
Looks up the help text for the passed in field.
[ "Looks", "up", "the", "help", "text", "for", "the", "passed", "in", "field", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L209-L230
nyaruka/smartmin
smartmin/views.py
SmartView.lookup_field_class
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]: ...
python
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]: ...
[ "def", "lookup_field_class", "(", "self", ",", "field", ",", "obj", "=", "None", ",", "default", "=", "None", ")", ":", "css", "=", "\"\"", "# is there a class specified for this field", "if", "field", "in", "self", ".", "field_config", "and", "'class'", "in",...
Looks up any additional class we should include when rendering this field
[ "Looks", "up", "any", "additional", "class", "we", "should", "include", "when", "rendering", "this", "field" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L232-L246
nyaruka/smartmin
smartmin/views.py
SmartView.get_template_names
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...
python
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...
[ "def", "get_template_names", "(", "self", ")", ":", "templates", "=", "[", "]", "if", "getattr", "(", "self", ",", "'template_name'", ",", "None", ")", ":", "templates", ".", "append", "(", "self", ".", "template_name", ")", "if", "getattr", "(", "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 setting a 'template_name' variable on the class.
[ "Returns", "the", "name", "of", "the", "template", "to", "use", "to", "render", "this", "request", "." ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L263-L281
nyaruka/smartmin
smartmin/views.py
SmartView.derive_fields
def derive_fields(self): """ Default implementation """ fields = [] if self.fields: fields.append(self.fields) return fields
python
def derive_fields(self): """ Default implementation """ fields = [] if self.fields: fields.append(self.fields) return fields
[ "def", "derive_fields", "(", "self", ")", ":", "fields", "=", "[", "]", "if", "self", ".", "fields", ":", "fields", ".", "append", "(", "self", ".", "fields", ")", "return", "fields" ]
Default implementation
[ "Default", "implementation" ]
train
https://github.com/nyaruka/smartmin/blob/488a676a4960555e4d216a7b95d6e01a4ad4efd8/smartmin/views.py#L283-L291