_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q271900 | CursesMenu.draw | test | def draw(self):
"""
Redraws the menu and refreshes the screen. Should be called whenever something changes that needs to be redrawn.
"""
self.screen.border(0)
if self.title is not None:
self.screen.addstr(2, 2, self.title, curses.A_STANDOUT)
if self.subtitle is not None:
self.screen.addstr(4, 2, self.subtitle, curses.A_BOLD)
for index, item in enumerate(self.items):
if self.current_option == index:
text_style = self.highlight
else:
text_style = self.normal
| python | {
"resource": ""
} |
q271901 | CursesMenu.process_user_input | test | def process_user_input(self):
"""
Gets the next single character and decides what to do with it
"""
user_input = self.get_input()
go_to_max = ord("9") if len(self.items) >= 9 else ord(str(len(self.items)))
if ord('1') <= user_input <= go_to_max:
self.go_to(user_input - ord('0') - 1)
| python | {
"resource": ""
} |
q271902 | CursesMenu.select | test | def select(self):
"""
Select the current item and run it
"""
self.selected_option = self.current_option
self.selected_item.set_up()
self.selected_item.action()
self.selected_item.clean_up() | python | {
"resource": ""
} |
q271903 | parse_old_menu | test | def parse_old_menu(menu_data):
"""
Take an old-style menuData dictionary and return a CursesMenu
:param dict menu_data:
:return: A new CursesMenu
:rtype: CursesMenu
"""
menu_title = menu_data['title']
menu = CursesMenu(menu_title)
for item in menu_data["options"]:
item_type = item["type"]
item_title = item["title"]
if item_type == menuItem.COMMAND:
item_command = item["command"]
menu.append_item(CommandItem(item_title, item_command, menu))
elif item_type == menuItem.FUNCTION:
item_function = item["function"]
menu.append_item(FunctionItem(item_title, item_function, menu))
elif item_type == menuItem.EXITMENU:
| python | {
"resource": ""
} |
q271904 | top | test | def top(
df,
value: str,
limit: int,
order: str = 'asc',
group: Union[str, List[str]] = None
):
"""
Get the top or flop N results based on a column value for each specified group columns
---
### Parameters
*mandatory :*
- `value` (*str*): column name on which you will rank the results
- `limit` (*int*): Number to specify the N results you want to retrieve.
Use a positive number x to retrieve the first x results.
Use a negative number -x to retrieve the last x results.
*optional :*
- `order` (*str*): `"asc"` or `"desc"` to sort by ascending ou descending order. By default : `"asc"`.
- `group` (*str*, *list of str*): name(s) of columns on which you want to perform the group operation.
---
### Example
**Input**
| variable | Category | value |
|:--------:|:--------:|:-----:|
| lili | 1 | 50 |
| lili | 1 | 20 |
| toto | 1 | 100 |
| toto | 1 | 200 |
| toto | 1 | 300 |
| lala | 1 | 100 |
| lala | 1 | 150 |
| lala | 1 | 250 |
| lala | 2 | 350 |
| lala | 2 | 450 |
```cson
top:
value: 'value'
limit: 4 | python | {
"resource": ""
} |
q271905 | top_group | test | def top_group(
df,
aggregate_by: List[str],
value: str,
limit: int,
order: str = 'asc',
function: str = 'sum',
group: Union[str, List[str]] = None
):
"""
Get the top or flop N results based on a function and a column value that agregates the input.
The result is composed by all the original lines including only lines corresponding
to the top groups
---
### Parameters
*mandatory :*
- `value` (*str*): Name of the column name on which you will rank the results.
- `limit` (*int*): Number to specify the N results you want to retrieve from the sorted values.
- Use a positive number x to retrieve the first x results.
- Use a negative number -x to retrieve the last x results.
- `aggregate_by` (*list of str*)): name(s) of columns you want to aggregate
*optional :*
- `order` (*str*): `"asc"` or `"desc"` to sort by ascending ou descending order. By default : `"asc"`.
- `group` (*str*, *list of str*): name(s) of columns on which you want to perform the group operation.
- `function` : Function to use to group over the group column
---
### Example
**Input**
| variable | Category | value |
|:--------:|:--------:|:-----:|
| lili | 1 | 50 |
| lili | 1 | 20 |
| toto | 1 | 100 |
| toto | 1 | 200 |
| toto | 1 | 300 |
| lala | 1 | 100 |
| lala | 1 | 150 |
| lala | 1 | 250 |
| lala | 2 | 350 |
| lala | python | {
"resource": ""
} |
q271906 | convert_str_to_datetime | test | def convert_str_to_datetime(df, *, column: str, format: str):
"""
Convert string column into datetime column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to format
- `format` (*str*): current format of the values | python | {
"resource": ""
} |
q271907 | convert_datetime_to_str | test | def convert_datetime_to_str(df, *, column: str, format: str, new_column: str = None):
"""
Convert datetime column into string column
---
### Parameters
*mandatory :*
- column (*str*): name of the column to format
- format (*str*): format of the result values (see [available formats](
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))
| python | {
"resource": ""
} |
q271908 | change_date_format | test | def change_date_format(
df, *,
column: str,
output_format: str,
input_format: str = None,
new_column: str = None,
new_time_zone=None
):
"""
Convert the format of a date
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to change the format
- `output_format` (*str*): format of the output values (see [available formats](
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))
*optional :*
- `input_format` (*str*): format of the input values (by default let the parser detect it)
- `new_column` (*str*): name of the output column (by default overwrite `column`)
- `new_time_zone` (*str*): name of new time zone (by default no time zone conversion is done)
---
### Example
**Input**
label | python | {
"resource": ""
} |
q271909 | cast | test | def cast(df, column: str, type: str, new_column=None):
"""
Convert column's type into type
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to convert
- `type` (*str*): output type. It can be :
- `"int"` : integer type
- `"float"` : general number type
- `"str"` : text type
*optional :*
- `new_column` (*str*): name of the output column.
By default the `column` arguments is modified.
---
### Example
**Input**
| Column 1 | Column 2 | Column 3 |
|:-------:|:--------:|:--------:|
| 'one' | '2014' | 30.0 |
| 'two' | 2015.0 | '1' |
| 3.1 | 2016 | 450 |
```cson
postprocess: [
cast:
column: 'Column 1'
type: 'str'
cast:
| python | {
"resource": ""
} |
q271910 | rank | test | def rank(
df,
value_cols: Union[str, List[str]],
group_cols: List[str] = None,
rank_cols_names: List[str] = None,
method='min',
ascending: bool = True
):
"""
This function creates rank columns based on numeric values to be ranked.
---
### Parameters
*mandatory :*
- `value_cols` (*list*): name(s) of the columns used
*optional :*
- `group_cols` (*list*): name(s) of the column(s) used to
create each group inside which independent ranking needs to be applied
- `rank_cols_names` (*list*): the names of the added ranking columns.
If not filled, the ranking will be named after the value_cols with a '_rank' suffix
- `method` (*str*): method to use when encountering equal values:
- `'min'` (default): lowest rank in group
- `'max'`: highest rank in group
- `'average'`: average rank of group
- `'first'`: ranks assigned in order the values appear in the series
- `'dense'`: like 'min', but rank always increases by 1 between groups
- `ascending` (*boolean*): whether the rank should be determined based on
ascending (default) or descending order
---
### Example
**Input**
| ENTITY | YEAR | VALUE_1 | VALUE_2 |
| :---: | :---: | :---: | :---: |
| A | 2017 | 10 | 3 |
| A | 2017 | 20 | 1 |
| A | 2018 | 10 | 5 |
| A | 2018 | 30 | 4 |
| B | 2017 | 60 | 4 |
| B | 2017 | 40 | 3 |
| B | 2018 | 50 | 7 |
| B | 2018 | 50 | 6 |
```cson
rank :
value_cols: 'VALUE_1'
```
**Output**
| ENTITY | YEAR | VALUE_1 | VALUE_2 | VALUE_1_rank
| :---: | :---: | :---: | :---: | :---: |
| A | 2017 | 10 | 3 | 1 |
| A | 2017 | 20 | 1 | 3 |
| A | 2018 | 10 | 5 | 1 |
| A | 2018 | | python | {
"resource": ""
} |
q271911 | waterfall | test | def waterfall(
df,
date: str,
value: str,
start: Dict[str, str],
end: Dict[str, str],
upperGroup: Dict[str, str],
insideGroup: Dict[str, str] = None,
filters: List[str] = None
):
"""
Return a line for each bars of a waterfall chart, totals, groups, subgroups.
Compute the variation and variation rate for each line.
---
### Parameters
*mandatory :*
- `date` (*str*): name of the column that id the period of each lines
- `value` (*str*): name of the column that contains the vaue for each lines
- `start` (*dict*):
- `label`: text displayed under the first master column
- `id`: value in the date col that id lines for the first period
- `end` (*dict*):
- `label`: text displayed under the last master column
- `id`: value in the date col that id lines for the second period
*optional :*
- `upperGroup` (*dict*):
- `id`: name of the column that contains upperGroups unique IDs
- `label`: not required, text displayed under each upperGroups bars,
using ID when it's absent
- `groupsOrder`: not required, order of upperGroups
- `insideGroup` (*dict*):
- `id`: name of the column that contains insideGroups unique IDs
- `label`: not required, text displayed under each insideGroups bars,
using ID when it's absent
- `groupsOrder`: not required, order of insideGroups
- `filters` (*list*): columns to filters on
---
### Example
**Input**
| product_id | played | date | ord | category_id | category_name |
|:------------:|:--------:|:------:|:-----:|:-------------:|:---------------:|
| super clap | 12 | t1 | 1 | clap | Clap |
| clap clap | 1 | t1 | 10 | clap | Clap |
| tac | 1 | t1 | 1 | snare | Snare |
| super clap | 10 | t2 | 1 | clap | Clap |
| tac | 100 | t2 | 1 | snare | Snare |
| bom | 1 | t2 | 1 | tom | Tom |
```cson
waterfall:
upperGroup:
id: 'category_id'
label: 'category_name'
insideGroup:
id: 'product_id'
groupsOrder: 'ord'
date: 'date'
value: 'played'
start:
label: 'Trimestre 1'
id: 't1'
end:
label: 'Trimester 2'
id: 't2'
```
**Output**
| value | label | variation | groups | type | order |
|:-------:|:-----------:|:-----------:|:--------:|:------:|:-------:|
| 14 | Trimestre 1 | NaN | NaN | NaN | NaN |
| -3 | Clap | -0.230769 | clap | parent | NaN |
| -2 | super clap | -0.166667 | clap | child | 1 |
| -1 | clap clap | -1 | clap | child | 10 |
| 99 | Snare | 99 | snare | parent | NaN |
| 99 | tac | 99 | snare | child | 1 |
| 1 | Tom | inf | tom | parent | NaN |
| 1 | bom | python | {
"resource": ""
} |
q271912 | _basic_math_operation | test | def _basic_math_operation(df, new_column, column_1, column_2, op):
"""
Basic mathematical operation to apply operator on `column_1` and `column_2`
Both can be either a number or the name of a column of `df`
Will create a new column named `new_column`
"""
if not isinstance(column_1, (str, int, float)):
raise TypeError(f'column_1 must be a string, an integer or a float')
if not isinstance(column_2, (str, int, float)):
| python | {
"resource": ""
} |
q271913 | round_values | test | def round_values(df, *, column: str, decimals: int, new_column: str = None):
"""
Round each value of a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to round
- `decimals` (*int*): number of decimal to keeep
*optional :*
- `new_column` (*str*): name of the new column to create.
By default, no new column will be created and `column` will be replaced
---
### Example
** Input**
ENTITY|VALUE_1|VALUE_2
:-----:|:-----:|:-----:
A|-1.512|-1.504
A|0.432|0.14
```cson
round_values:
column: 'VALUE_1'
| python | {
"resource": ""
} |
q271914 | absolute_values | test | def absolute_values(df, *, column: str, new_column: str = None):
"""
Get the absolute numeric value of each element of a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column
*optional :*
- `new_column` (*str*): name of the column containing the result.
By default, no new column will be created and `column` will be replaced.
---
### Example
**Input**
| ENTITY | VALUE_1 | VALUE_2 |
|:------:|:-------:|:-------:|
| A | -1.512 | -1.504 |
| A | 0.432 | 0.14 | python | {
"resource": ""
} |
q271915 | pivot | test | def pivot(df, index: List[str], column: str, value: str, agg_function: str = 'mean'):
"""
Pivot the data. Reverse operation of melting
---
### Parameters
*mandatory :*
- `index` (*list*): names of index columns.
- `column` (*str*): column name to pivot on
- `value` (*str*): column name containing the value to fill the pivoted df
*optional :*
- `agg_function` (*str*): aggregation function to use among 'mean' (default), 'count', 'mean', 'max', 'min'
---
### Example
**Input**
| variable | wave | year | value |
|:--------:|:-------:|:--------:|:-----:|
| toto | wave 1 | 2014 | 300 |
| toto | wave 1 | 2015 | 250 |
| toto | wave 1 | 2016 | 450 |
```cson
pivot:
index: ['variable','wave']
column: 'year'
value: 'value'
```
**Output**
| variable | wave | 2014 | 2015 | 2015 |
| python | {
"resource": ""
} |
q271916 | pivot_by_group | test | def pivot_by_group(
df,
variable,
value,
new_columns,
groups,
id_cols=None
):
"""
Pivot a dataframe by group of variables
---
### Parameters
*mandatory :*
* `variable` (*str*): name of the column used to create the groups.
* `value` (*str*): name of the column containing the value to fill the pivoted df.
* `new_columns` (*list of str*): names of the new columns.
* `groups` (*dict*): names of the groups with their corresponding variables.
**Warning**: the list of variables must have the same order as `new_columns`
*optional :*
* `id_cols` (*list of str*) : names of other columns to keep, default `None`.
---
### Example
**Input**
| type | variable | montant |
|:----:|:----------:|:-------:|
| A | var1 | 5 |
| A | var1_evol | 0.3 |
| A | var2 | 6 |
| A | var2_evol | 0.2 |
```cson
pivot_by_group :
id_cols: ['type']
variable: 'variable'
value: 'montant'
new_columns: ['value', 'variation']
groups: | python | {
"resource": ""
} |
q271917 | groupby | test | def groupby(df, *, group_cols: Union[str, List[str]],
aggregations: Dict[str, Union[str, List[str]]]):
"""
Aggregate values by groups.
---
### Parameters
*mandatory :*
- `group_cols` (*list*): list of columns used to group data
- `aggregations` (*dict*): dictionnary of values columns to group as keys and aggregation
function to use as values (See the [list of aggregation functions](
https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html#aggregation))
---
### Example
**Input**
| ENTITY | YEAR | VALUE_1 | VALUE_2 |
|:------:|:----:|:-------:|:-------:|
| A | 2017 | 10 | 3 |
| A | 2017 | 20 | 1 |
| A | 2018 | 10 | 5 |
| A | 2018 | 30 | 4 |
| B | 2017 | 60 | 4 |
| B | 2017 | 40 | 3 |
| B | 2018 | 50 | 7 |
| B | 2018 | 60 | 6 |
```cson
groupby:
group_cols: ['ENTITY', 'YEAR']
aggregations:
'VALUE_1': 'sum',
'VALUE_2': 'mean'
```
**Output**
| ENTITY | YEAR | VALUE_1 | VALUE_2 |
|:------:|:----:|:-------:|:-------:|
| A | 2017 | 30 | 2.0 |
| A | 2018 | 40 | 4.5 |
| B | 2017 | 100 | | python | {
"resource": ""
} |
q271918 | cumsum | test | def cumsum(df, new_column: str, column: str, index: list, date_column: str, date_format: str):
"""
DEPRECATED - please use `compute_cumsum` instead
"""
logging.getLogger(__name__).warning(f"DEPRECATED: use compute_cumsum")
date_temp = '__date_temp__'
if isinstance(index, str):
index = [index]
levels = list(range(0, len(index)))
df[date_temp] = pd.to_datetime(df[date_column], format=date_format)
| python | {
"resource": ""
} |
q271919 | add_missing_row | test | def add_missing_row(
df: pd.DataFrame,
id_cols: List[str],
reference_col: str,
complete_index: Union[Dict[str, str], List[str]] = None,
method: str = None,
cols_to_keep: List[str] = None
) -> pd.DataFrame:
"""
Add missing row to a df base on a reference column
---
### Parameters
*mandatory :*
- `id_cols` (*list of str*): names of the columns used to create each group
- `reference_col` (*str*): name of the column used to identify missing rows
*optional :*
- `complete_index` (*list* or *dict*): [A, B, C] a list of values used to add missing rows.
It can also be a dict to declare a date range.
By default, use all values of reference_col.
- `method` (*str*): by default all missing rows are added. The possible values are :
- `"between"` : add missing rows having their value between min and max values for each group,
- `"between_and_after"` : add missing rows having their value bigger than min value for each group.
- `"between_and_before"` : add missing rows having their value smaller than max values for each group.
- `cols_to_keep` (*list of str*): name of other columns to keep, linked to the reference_col.
---
### Example
**Input**
YEAR | MONTH | NAME
:---:|:---:|:--:
2017|1|A
2017|2|A
2017|3|A
2017|1|B
2017|3|B
```cson
add_missing_row:
id_cols: ['NAME']
reference_col: 'MONTH'
```
**Output**
YEAR | MONTH | NAME
:---:|:---:|:--:
2017|1|A
2017|2|A
| python | {
"resource": ""
} |
q271920 | catch | test | def catch(logger):
"""
Decorator to catch an exception and don't raise it.
Logs information if a decorator failed.
Note:
We don't want possible exceptions during logging to be raised.
This is used to decorate any function that gets executed
| python | {
"resource": ""
} |
q271921 | log_message | test | def log_message(logger, message=""):
"""
Decorator to log a message before executing a function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
| python | {
"resource": ""
} |
q271922 | log_time | test | def log_time(logger):
"""
Decorator to log the execution time of a function
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
| python | {
"resource": ""
} |
q271923 | log_shapes | test | def log_shapes(logger):
"""
Decorator to log the shapes of input and output dataframes
It considers all the dataframes passed either as arguments or keyword arguments as inputs
and all the dataframes returned as outputs.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
input_shapes = _get_dfs_shapes(*args, | python | {
"resource": ""
} |
q271924 | rename | test | def rename(
df,
values: Dict[str, Dict[str, str]] = None,
columns: Dict[str, Dict[str, str]] = None,
locale: str = None
):
"""
Replaces data values and column names according to the locale
---
### Parameters
- `values` (optional: dict):
- key: term to be replaced
- value:
- key: the locale e.g. 'en' or 'fr'
- value: term's translation
- `columns` (optional: dict):
- key: columns name to be replaced
- value:
- key: the locale e.g. 'en' or 'fr'
- value: column name's translation
- `locale` (optional: str): the locale you want to use.
By default the client locale is used.
---
### Example
**Input**
| label | value |
|:----------------:|:-----:|
| France | 100 |
| Europe wo France | 500 |
```cson
rename:
values:
'Europe wo France':
'en': 'Europe excl. France'
'fr': 'Europe excl. France'
columns:
'value':
| python | {
"resource": ""
} |
q271925 | compute_cumsum | test | def compute_cumsum(
df,
id_cols: List[str],
reference_cols: List[str],
value_cols: List[str],
new_value_cols: List[str] = None,
cols_to_keep: List[str] = None
):
"""
Compute cumsum for a group of columns.
---
### Parameters
*mandatory :*
- `id_cols` (*list*): the columns id to create each group
- `reference_cols` (*list*): the columns to order the cumsum
- `value_cols` (*list*): the columns to cumsum
*optional :*
- `new_value_cols` (*list*): the new columns with the result cumsum
- `cols_to_keep` (*list*): other columns to keep in the dataset.
This option can be used if there is only one row by group [id_cols + reference_cols]
---
### Example
**Input**
MONTH | DAY | NAME | VALUE | X
:---:|:---:|:--:|:---:|:---:
1 | | python | {
"resource": ""
} |
q271926 | combine_columns_aggregation | test | def combine_columns_aggregation(
df,
id_cols: List[str],
cols_for_combination: Dict[str, str],
agg_func: Union[str, List[str], Dict[str, str]] = 'sum'
):
"""
Aggregates data to reproduce "All" category for requester
---
### Parameters
*mandatory :*
- `id_cols` (*list*): the columns id to group
- `cols_for_combination` (*dict*): colums corresponding to
the filters as key and their default value as value
*optional :*
- `agg_func` (*str*, *list* or *dict*): the function(s) to use for aggregating the data.
Accepted combinations are:
- string function name
- list of functions and/or function names, e.g. [np.sum, 'mean']
- dict of axis labels -> functions, function names or list of such.
"""
| python | {
"resource": ""
} |
q271927 | get_param_value_from_func_call | test | def get_param_value_from_func_call(param_name, func, call_args, call_kwargs):
"""
Get the value of a function's parameter based on its signature
and the call's args and kwargs.
Example:
>>> def foo(a, b, c=3, d=4):
... pass
...
>>> # what would be the value of "c" when calling foo(1, b=2, c=33) ?
>>> get_param_value_from_func_call('c', foo, [1], {'b': 2, 'c': 33})
33
"""
| python | {
"resource": ""
} |
q271928 | clean_cachedir_old_entries | test | def clean_cachedir_old_entries(cachedir: StoreBackendBase, func_name: str, limit: int) -> int:
"""Remove old entries from the cache"""
if limit < 1:
raise ValueError("'limit' must be greater or equal to 1")
cache_entries = get_cachedir_entries(cachedir, func_name)
cache_entries = sorted(cache_entries, key=lambda e: e.last_access, | python | {
"resource": ""
} |
q271929 | roll_up | test | def roll_up(
df,
levels: List[str],
groupby_vars: List[str],
extra_groupby_cols: List[str] = None,
var_name: str = 'type',
value_name: str = 'value',
agg_func: str = 'sum',
drop_levels: List[str] = None
):
"""
Creates aggregates following a given hierarchy
---
### Parameters
*mandatory :*
- `levels` (*list of str*): name of the columns composing the hierarchy (from the top to the bottom level).
- `groupby_vars` (*list of str*): name of the columns with value to aggregate.
- `extra_groupby_cols` (*list of str*) optional: other columns used to group in each level.
*optional :*
- `var_name` (*str*) : name of the result variable column. By default, `“type”`.
- `value_name` (*str*): name of the result value column. By default, `“value”`.
- `agg_func` (*str*): name of the aggregation operation. By default, `“sum”`.
- `drop_levels` (*list of str*): the names of the levels that you may want to discard from the output.
---
### Example
**Input**
| Region | City | Population |
|:---------:|:--------:|:-----------:|
| Idf | Panam| 200 |
| Idf | Antony | 50 |
| Nord | Lille | 20 |
```cson
roll_up:
levels: ["Region", "City"]
groupby_vars: "Population"
```
**Output**
| Region | City | Population | value | type |
|:---------:|:--------:|:-----------:|:--------:|:------:|
| Idf | Panam| 200 | Panam | City |
| Idf | Antony | 50 | Antony | City |
| Nord | Lille | 20 | Lille | City |
| Idf | Nan | | python | {
"resource": ""
} |
q271930 | argmax | test | def argmax(df, column: str, groups: Union[str, List[str]] = None):
"""
Keep the row of the data corresponding to the maximal value in a column
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column containing the value you want to keep the maximum
*optional :*
- `groups` (*str or list(str)*): name of the column(s) used for 'groupby' logic
(the function will return the argmax by group)
---
### Example
**Input**
| variable | wave | year | value |
|:--------:|:-------:|:--------:|:-----:|
| toto | wave 1 | 2014 | 300 |
| toto | wave 1 | 2015 | 250 |
| toto | wave 1 | 2016 | 450 |
```cson
argmax:
column: 'year'
```
**Output**
| variable | wave | year | value |
|:--------:|:-------:|:--------:|:-----:| | python | {
"resource": ""
} |
q271931 | argmin | test | def argmin(df, column: str, groups: Union[str, List[str]] = None):
"""
Keep the row of the data corresponding to the minimal value in a column
---
### Parameters
*mandatory :*
- `column` (str): name of the column containing the value you want to keep the minimum
*optional :*
- `groups` (*str or list(str)*): name of the column(s) used for 'groupby' logic
(the function will return the argmax by group)
---
### Example
**Input**
| variable | wave | year | value |
|:--------:|:-------:|:--------:|:-----:|
| toto | wave 1 | 2014 | 300 |
| toto | wave 1 | 2015 | 250 |
| toto | wave 1 | 2016 | 450 |
```cson
argmin:
column: 'year'
]
```
**Output**
| variable | wave | year | value | | python | {
"resource": ""
} |
q271932 | fillna | test | def fillna(df, column: str, value=None, column_value=None):
"""
Can fill NaN values from a column with a given value or a column
---
### Parameters
- `column` (*str*): name of column you want to fill
- `value`: NaN will be replaced by this value
- `column_value`: NaN will be replaced by value from this column
*NOTE*: You must set either the 'value' parameter or the 'column_value' parameter
---
### Example
**Input**
| variable | wave | year | my_value |
|:--------:|:-------:|:--------:|:--------:|
| toto | wave 1 | 2014 | 300 |
| toto | wave 1 | 2015 | |
| toto | wave 1 | 2016 | 450 |
```cson
fillna:
column: 'my_value'
value: 0
```
**Output**
| variable | wave | year | my_value |
|:--------:|:-------:|:--------:|:--------:|
| toto | wave 1 | 2014 | 300 | | python | {
"resource": ""
} |
q271933 | add_offset | test | def add_offset(dateobj, hr_offset: str, sign: str):
"""add a human readable offset to `dateobj` and return corresponding date.
rely on `pandas.Timedelta` and add the following extra shortcuts:
- "w", "week" and "weeks" for a week (i.e. 7days)
- "month', "months" for a month (i.e. no day computation, just increment the month)
- "y", "year', "years" for a year (i.e. no day computation, just increment the year)
"""
sign_coeff = 1 if sign == '+' else -1
try:
return dateobj + sign_coeff * pd.Timedelta(hr_offset)
except ValueError:
# pd.Timedelta could not parse the offset, let's try harder
match = TIMEDELTA_RGX.match(hr_offset)
if match is not None:
groups = match.groupdict()
| python | {
"resource": ""
} |
q271934 | add_months | test | def add_months(dateobj, nb_months: int):
"""return `dateobj` + `nb_months`
If landing date doesn't exist (e.g. february, 30th), return the last
day of the landing month.
>>> add_months(date(2018, 1, 1), 1)
datetime.date(2018, 1, 1)
>>> add_months(date(2018, 1, 1), -1)
datetime.date(2017, 12, 1)
>>> add_months(date(2018, 1, 1), 25)
datetime.date(2020, 2, 1)
>>> add_months(date(2018, 1, 1), -25)
datetime.date(2015, 12, 1)
>>> add_months(date(2018, 1, 31), 1)
| python | {
"resource": ""
} |
q271935 | add_years | test | def add_years(dateobj, nb_years):
"""return `dateobj` + `nb_years`
If landing date doesn't exist (e.g. february, 30th), return the last
day of the landing month.
>>> add_years(date(2018, 1, 1), 1)
datetime.date(2019, 1, 1)
>>> add_years(date(2018, 1, 1), -1)
datetime.date(2017, 1, 1)
>>> add_years(date(2020, 2, 29), 1)
datetime.date(2021, 2, 28)
>>> add_years(date(2020, 2, | python | {
"resource": ""
} |
q271936 | parse_date | test | def parse_date(datestr: str, date_fmt: str) -> date:
"""parse `datestr` and return corresponding date object.
`datestr` should be a string matching `date_fmt` and parseable by `strptime`
but some offset can also be added using `(datestr) + OFFSET` or `(datestr) -
OFFSET` syntax. When using this syntax, `OFFSET` should be understable by
`pandas.Timedelta` (cf.
http://pandas.pydata.org/pandas-docs/stable/timedeltas.html) and `w`, `week`
`month` and `year` offset keywords are also accepted. `datestr` MUST be wrapped
with parenthesis.
Additionally, the following symbolic names are supported: `TODAY`,
`YESTERDAY`, `TOMORROW`.
Example usage:
>>> parse_date('2018-01-01', '%Y-%m-%d') datetime.date(2018, 1, 1)
parse_date('(2018-01-01) + 1day', '%Y-%m-%d') datetime.date(2018, 1, 2)
parse_date('(2018-01-01) + 2weeks', '%Y-%m-%d') datetime.date(2018, 1, 15)
Parameters: `datestr`: the date to parse, formatted as `date_fmt`
`date_fmt`: expected date format
Returns: | python | {
"resource": ""
} |
q271937 | filter_by_date | test | def filter_by_date(
df,
date_col: str,
date_format: str = '%Y-%m-%d',
start: str = None,
stop: str = None,
atdate: str = None
):
"""
Filter dataframe your data by date.
This function will interpret `start`, `stop` and `atdate` and build
the corresponding date range. The caller must specify either:
- `atdate`: keep all rows matching this date exactly,
- `start`: keep all rows matching this date onwards.
- `stop`: keep all rows matching dates before this one.
- `start` and `stop`: keep all rows between `start` and `stop`,
Any other combination will raise an error. The lower bound of the date range
will be included, the upper bound will be excluded.
When specified, `start`, `stop` and `atdate` values are expected to match the
`date_format` format or a known symbolic value (i.e. 'TODAY', 'YESTERDAY' or 'TOMORROW').
Additionally, the offset syntax "(date) + offset" is also supported (Mind
the parenthesis around the date string). In that case, the offset must be
one of the syntax supported by `pandas.Timedelta` (see [pandas doc](
http://pandas.pydata.org/pandas-docs/stable/timedeltas.html))
---
### Parameters
*mandatory :*
- `date_col` (*str*): the name of the dataframe's column to filter on
*optional :*
- `date_format` (*str*): expected date format in column `date_col` (see [available formats](
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior)
- `start` (*str*): if specified, lower bound (included) of the date range
- `stop` (*str*): if specified, upper bound (excluded) of the date range
- `atdate` (*str*): if specified, the exact date we're filtering on
"""
mask = None
if start is None and stop is None and atdate is None:
| python | {
"resource": ""
} |
q271938 | percentage | test | def percentage(
df,
column: str,
group_cols: Union[str, List[str]] = None,
new_column: str = None
):
"""
Add a column to the dataframe according to the groupby logic on group_cols
---
### Parameters
*mandatory :*
- `column` (*str*): name of the desired column you need percentage on
*optional :*
- `group_cols` (*list*): names of columns for the groupby logic
- `new_column` (*str*): name of the output column. By default `column` will be overwritten.
---
**Input**
| gender | sport | number |
|:------:|:----------:|:------:|
| male | bicycle | 17 |
| female | basketball | 17 |
| male | basketball | 3 |
| female | football | 7 |
| female | running | 30 |
| male | running | 20 |
| male | football | 21 |
| female | bicycle | 17 |
```cson
percentage:
new_column: 'number_percentage'
column: 'number'
group_cols: ['sport']
```
**Output**
| gender | sport | number | python | {
"resource": ""
} |
q271939 | ada_family_core | test | def ada_family_core(params, gparams, learning_rate = 0.01, eps= 1e-6, rho=0.95, method="ADADELTA",
beta=0.0, gsum_regularization = 0.0001):
"""
Optimize by SGD, AdaGrad, or AdaDelta.
"""
_, _, _, args = inspect.getargvalues(inspect.currentframe())
logging.info("ada_family_core: %s" % str(args.items()))
free_parameters = []
if method == "FINETUNING_ADAGRAD":
method = "ADAGRAD"
gsum_regularization = 0
oneMinusBeta = 1 - beta
gsums = [theano.shared(np.zeros_like(param.get_value(borrow=True), dtype=FLOATX), name="gsum_%s" % param.name) if (method == 'ADADELTA' or method == 'ADAGRAD') else None for param in params]
xsums = [theano.shared(np.zeros_like(param.get_value(borrow=True), dtype=FLOATX), name="xsum_%s" % param.name) if method == 'ADADELTA' else None for param in params]
# Fix for AdaGrad, init gsum to 1
if method == 'ADAGRAD':
for gsum in gsums:
gsum.set_value(gsum.get_value() ** 0)
updates = OrderedDict()
# Updates
for gparam, param, gsum, xsum in zip(gparams, params, gsums, xsums):
if method == 'ADADELTA':
updates[gsum] = rho * gsum + (1. - rho) * (gparam **2)
dparam = -T.sqrt((xsum + eps) / (updates[gsum] + eps)) * gparam
| python | {
"resource": ""
} |
q271940 | GeneralNeuralTrainer._learning_updates | test | def _learning_updates(self):
"""
Return updates in the training.
"""
params = self.training_params()
gradients = | python | {
"resource": ""
} |
q271941 | GeneralNeuralTrainer.training_params | test | def training_params(self):
"""
Get parameters to be optimized.
"""
params = self.network.parameters
# Freeze parameters
if self.config.fixed_parameters:
| python | {
"resource": ""
} |
q271942 | GeneralNeuralTrainer.optimization_updates | test | def optimization_updates(self, params, gradients):
"""
Return updates from optimization.
"""
updates, free_parameters = optimize_updates(params, gradients, self.config)
| python | {
"resource": ""
} |
q271943 | FirstGlimpseLayer._first_glimpse_sensor | test | def _first_glimpse_sensor(self, x_t):
"""
Compute first glimpse position using down-sampled image.
"""
downsampled_img = theano.tensor.signal.downsample.max_pool_2d(x_t, (4,4))
downsampled_img = downsampled_img.flatten()
first_l = T.dot(downsampled_img, self.W_f)
if self.disable_reinforce:
wf_grad = self.W_f
if self.random_glimpse:
first_l = self.srng.uniform((2,), low=-1.7, high=1.7)
else:
| python | {
"resource": ""
} |
q271944 | MyJointTrainingModel.prepare | test | def prepare(self):
"""
All codes that create parameters should be put into 'setup' function.
"""
self.output_dim = 10
self.encoder = Chain(self.input_dim).stack(Dense(self.internal_layer_size, 'tanh'))
self.decoder = Chain(self.internal_layer_size).stack(Dense(self.input_dim))
self.classifier = Chain(self.internal_layer_size).stack(Dense(50, 'tanh'),
Dense(self.output_dim),
| python | {
"resource": ""
} |
q271945 | MyJointTrainingModel.compute_tensor | test | def compute_tensor(self, x):
"""
Build the computation graph here.
"""
internal_variable = self.encoder.compute_tensor(x)
decoding_output = self.decoder.compute_tensor(internal_variable)
classification_output = self.classifier.compute_tensor(internal_variable)
auto_encoder_cost = AutoEncoderCost(decoding_output, x).get()
classification_cost = CrossEntropyCost(classification_output, self.target_input).get()
final_cost = 0.01 * auto_encoder_cost + classification_cost
| python | {
"resource": ""
} |
q271946 | BasicDataset.map | test | def map(self, func):
"""
Process all data with given function.
The scheme of function should be x,y -> x,y.
"""
if self._train_set:
self._train_set = map(func, self._train_set)
if self._valid_set:
| python | {
"resource": ""
} |
q271947 | BasicDataset.vectorize_target | test | def vectorize_target(self, size):
"""
Make targets be one-hot vectors.
"""
if self._train_set:
self._train_set = self._vectorize_set(self._train_set, size)
if self._valid_set:
| python | {
"resource": ""
} |
q271948 | BasicDataset.report | test | def report(self):
"""
Print dataset statistics.
"""
logging.info("%s train=%d valid=%d test=%d" % (self.__class__.__name__,
len(list(self._train_set)) if self._train_set else 0,
| python | {
"resource": ""
} |
q271949 | CustomizeTrainer.train | test | def train(self, train_set, valid_set=None, test_set=None, train_size=None):
'''We train over mini-batches and evaluate periodically.'''
iteration = 0
while True:
if not iteration % self.config.test_frequency and test_set:
try:
self.test(iteration, test_set)
except KeyboardInterrupt:
logging.info('interrupted!')
break
if not iteration % self.validation_frequency and valid_set:
try:
if not self.evaluate(iteration, valid_set):
logging.info('patience elapsed, bailing out')
break
except KeyboardInterrupt:
logging.info('interrupted!')
break
train_message = ""
try:
| python | {
"resource": ""
} |
q271950 | NeuralLM.sample | test | def sample(self, input, steps):
"""
Sample outputs from LM.
"""
inputs = [[onehot(self.input_dim, x) for x in input]]
for _ in range(steps):
target = self.compute(inputs)[0,-1].argmax()
| python | {
"resource": ""
} |
q271951 | Attention.compute_alignments | test | def compute_alignments(self, prev_state, precomputed_values, mask=None):
"""
Compute the alignment weights based on the previous state.
"""
WaSp = T.dot(prev_state, self.Wa)
UaH = precomputed_values
# For test time the UaH will be (time, output_dim)
if UaH.ndim == 2:
preact = WaSp[:, None, :] + UaH[None, :, :]
else:
preact = WaSp[:, None, :] + UaH
act = T.activate(preact, 'tanh')
align_scores = T.dot(act, self.Va) # ~ | python | {
"resource": ""
} |
q271952 | Attention.compute_context_vector | test | def compute_context_vector(self, prev_state, inputs, precomputed_values=None, mask=None):
"""
Compute the context vector with soft attention.
"""
precomputed_values = | python | {
"resource": ""
} |
q271953 | concatenate | test | def concatenate(vars, axis=-1):
"""
A utility function of concatenate.
"""
from deepy.core.neural_var import NeuralVariable
if isinstance(vars[0], NeuralVariable):
concat_var = Concatenate(axis=axis).compute(*vars)
if axis == -1 or axis == vars[0].tensor.ndim - 1:
| python | {
"resource": ""
} |
q271954 | SequentialDataset._pad | test | def _pad(self, side, length):
"""
Pad sequences to given length in the left or right side.
"""
if self._train_set:
self._train_set = pad_dataset(self._train_set, side, length)
if self._valid_set:
| python | {
"resource": ""
} |
q271955 | rmsprop_core | test | def rmsprop_core(params, gradients, momentum=0.9, learning_rate=0.01):
"""
RMSPROP optimization core.
"""
for param, grad in zip(params, gradients):
| python | {
"resource": ""
} |
q271956 | Timer.report | test | def report(self):
"""
Report elapsed time.
"""
if not self.end_time:
self.end()
| python | {
"resource": ""
} |
q271957 | TrainingValidator.run | test | def run(self, data_x):
"""
Run the model with validation data and return costs.
"""
| python | {
"resource": ""
} |
q271958 | TrainingValidator.invoke | test | def invoke(self):
"""
This function will be called after each iteration.
"""
self._counter += 1
if self._counter % self._freq == 0:
cnt = 0.
sum_map = defaultdict(float)
for x in self._trainer.get_data(self._data_split):
val_map = self.run(x)
if not isinstance(val_map, dict):
raise Exception("Monitor.run must return a dict.")
for k, val in val_map.items():
| python | {
"resource": ""
} |
q271959 | Loop._build_loop_vars | test | def _build_loop_vars(self):
"""
Create inner loop variables.
"""
from theano.tensor.var import TensorVariable
from deepy.core.neural_var import NeuralVariable
if not self._loop_vars:
self._ordered_out_keys = self._outputs.keys()
seq_keys = self._sequences.keys()
filled_out_keys = [k for k in self._ordered_out_keys if self._outputs[k]]
nonseq_keys = self._non_sequences.keys()
dummy_tensors, self._scan_local_vars = get_dummy_args(
sequences=[self._sequences[k].tensor for k in seq_keys],
outputs_info=[self._outputs[k].tensor for k in self._ordered_out_keys],
non_sequences=[self._non_sequences[k].tensor for k in nonseq_keys],
| python | {
"resource": ""
} |
q271960 | Loop._scan_step | test | def _scan_step(self, vars):
"""
Internal scan with dummy input variables.
"""
from neural_var import NeuralVariable
if not self._loop_vars:
raise Exception("The loop is not initialized. To initialize the loop, use `with loop as vars`")
replace_map = {}
for k, var in vars.items():
if var is not None:
replace_map[self._dummy_nodes[k].tensor] = var.tensor
outputs = {}
for k in self._outputs:
| python | {
"resource": ""
} |
q271961 | momentum_core | test | def momentum_core(params, gradients, momentum=0.9, learning_rate=0.01):
"""
Momentum SGD optimization core.
"""
free_parameters = []
updates = []
for param, grad in zip(params, gradients):
delta = learning_rate * grad
velocity = theano.shared(np.zeros_like(param.get_value()), name=param.name + '_vel')
| python | {
"resource": ""
} |
q271962 | Runtime.iftrain | test | def iftrain(self, then_branch, else_branch):
"""
Execute `then_branch` when training.
"""
| python | {
"resource": ""
} |
q271963 | NeuralTrainer.skip | test | def skip(self, n_batches, n_epochs=0):
"""
Skip N batches in the training.
"""
| python | {
"resource": ""
} |
q271964 | NeuralTrainer.load_params | test | def load_params(self, path, exclude_free_params=False):
"""
Load parameters for the training.
This method can load free parameters and resume the training progress.
"""
self.network.load_params(path, exclude_free_params=exclude_free_params)
| python | {
"resource": ""
} |
q271965 | NeuralTrainer.train | test | def train(self, train_set, valid_set=None, test_set=None, train_size=None):
"""
Train the model and return costs.
"""
self._epoch = 0
while True:
if self._skip_epochs > 0:
logging.info("skipping one epoch ...")
self._skip_epochs -= 1
self._epoch += 1
yield None
continue
# Test
if not self._epoch % self.config.test_frequency and test_set:
try:
self._run_test(self._epoch, test_set)
except KeyboardInterrupt:
logging.info('interrupted!')
break
# Validate
if not self._epoch % self.validation_frequency and valid_set:
try:
if not self._run_valid(self._epoch, valid_set):
logging.info('patience elapsed, bailing out')
break
except KeyboardInterrupt:
logging.info('interrupted!')
| python | {
"resource": ""
} |
q271966 | NeuralTrainer._run_train | test | def _run_train(self, epoch, train_set, train_size=None):
"""
Run one training iteration.
"""
self.network.train_logger.record_epoch(epoch + 1)
costs = self.train_step(train_set, train_size)
| python | {
"resource": ""
} |
q271967 | NeuralTrainer._run_valid | test | def _run_valid(self, epoch, valid_set, dry_run=False, save_path=None):
"""
Run one valid iteration, return true if to continue training.
"""
costs = self.valid_step(valid_set)
# this is the same as: (J_i - J_f) / J_i > min improvement
_, J = costs[0]
new_best = False
if self.best_cost - J > self.best_cost * self.min_improvement:
# save the best cost and parameters
self.best_params = self.copy_params()
new_best = True
if not dry_run:
| python | {
"resource": ""
} |
q271968 | NeuralTrainer.report | test | def report(self, score_map, type="valid", epoch=-1, new_best=False):
"""
Report the scores and record them in the log.
"""
type_str = type
if len(type_str) < 5:
type_str += " " * (5 - len(type_str))
info = " ".join("%s=%.2f" % el for el in score_map.items())
| python | {
"resource": ""
} |
q271969 | NeuralTrainer.get_data | test | def get_data(self, data_split="train"):
"""
Get specified split of data.
"""
if data_split == 'train':
return self._current_train_set
elif data_split == 'valid':
| python | {
"resource": ""
} |
q271970 | NeuralVariable.apply | test | def apply(self, func, dim=None):
"""
Apply a function to tensors.
"""
output_dim = | python | {
"resource": ""
} |
q271971 | GeneralConfig.report | test | def report(self):
"""
Report usage of training parameters.
"""
if self.logger:
self.logger.info("accessed parameters:")
| python | {
"resource": ""
} |
q271972 | GraphBuilder.var | test | def var(self, tensor_type, last_dim=0, test_shape=None):
"""
An alias of deepy.tensor.var.
"""
from | python | {
"resource": ""
} |
q271973 | GraphBuilder.create_vars_from_data | test | def create_vars_from_data(self, dataset, split="train"):
"""
Create vars given a dataset and set test values.
Useful when dataset is already defined.
"""
from deepy.core.neural_var import NeuralVariable
vars = []
if split == "valid":
data_split = dataset.valid_set()
elif split == "test":
data_split = dataset.test_set()
else:
data_split = dataset.train_set()
first_data_piece = list(data_split)[0]
for i, numpy_tensor in enumerate(first_data_piece):
if numpy_tensor.dtype == "int64":
numpy_tensor = numpy_tensor.astype("int32")
if numpy_tensor.dtype == "float64":
numpy_tensor = numpy_tensor.astype(env.FLOATX)
type_map = {
0: "scalar",
1: "vector",
2: "matrix",
3: "tensor3",
| python | {
"resource": ""
} |
q271974 | GraphBuilder.shared | test | def shared(self, value, name=None):
"""
Create a shared theano scalar value.
"""
if type(value) == int:
final_value = np.array(value, dtype="int32")
elif type(value) == float:
| python | {
"resource": ""
} |
q271975 | AutoEncoder.stack_encoders | test | def stack_encoders(self, *layers):
"""
Stack encoding layers, this must be done before stacking decoding layers.
"""
| python | {
"resource": ""
} |
q271976 | AutoEncoder.stack_decoders | test | def stack_decoders(self, *layers):
"""
Stack decoding layers.
"""
| python | {
"resource": ""
} |
q271977 | AutoEncoder.encode | test | def encode(self, x):
"""
Encode given input.
"""
if not self.encoding_network:
self.encoding_network = NeuralNetwork(self.input_dim, self.input_tensor)
| python | {
"resource": ""
} |
q271978 | AutoEncoder.decode | test | def decode(self, x):
"""
Decode given representation.
"""
if not self.rep_dim:
raise Exception("rep_dim must be set to decode.")
if not self.decoding_network:
self.decoding_network = NeuralNetwork(self.rep_dim)
for layer | python | {
"resource": ""
} |
q271979 | create_2d_gaussian | test | def create_2d_gaussian(dim, sigma):
"""
This function creates a 2d gaussian kernel with the standard deviation
denoted by sigma
:param dim: integer denoting a side (1-d) of gaussian kernel
:param sigma: floating point indicating the standard deviation
:returns: a numpy 2d array
"""
# check if the dimension is odd
if dim % 2 == 0:
raise ValueError("Kernel dimension should be odd")
# initialize the kernel
kernel = np.zeros((dim, dim), dtype=np.float16)
# calculate the center point
center = dim/2
# calculate the variance
variance = sigma ** 2
# calculate the normalization coefficeint
coeff = 1. | python | {
"resource": ""
} |
q271980 | NeuralNetwork.register_layer | test | def register_layer(self, layer):
"""
Register the layer so that it's param will be trained.
But the output of the layer will not be stacked.
"""
if type(layer) == Block:
layer.fix()
self.parameter_count += layer.parameter_count
self.parameters.extend(layer.parameters)
self.free_parameters.extend(layer.free_parameters)
self.training_monitors.extend(layer.training_monitors)
self.testing_monitors.extend(layer.testing_monitors)
self.updates.extend(layer.updates)
self.training_updates.extend(layer.training_updates) | python | {
"resource": ""
} |
q271981 | NeuralNetwork.monitor_layer_outputs | test | def monitor_layer_outputs(self):
"""
Monitoring the outputs of each layer.
Useful for troubleshooting convergence problems.
"""
| python | {
"resource": ""
} |
q271982 | NeuralNetwork.all_parameters | test | def all_parameters(self):
"""
Return all parameters.
"""
params = []
params.extend(self.parameters) | python | {
"resource": ""
} |
q271983 | NeuralNetwork.setup_variables | test | def setup_variables(self):
"""
Set up variables.
"""
if self.input_tensor:
if type(self.input_tensor) == int:
x = dim_to_var(self.input_tensor, name="x")
else:
| python | {
"resource": ""
} |
q271984 | NeuralNetwork.compute | test | def compute(self, *x):
"""
Return network output.
"""
self._compile()
outs = self._compute(*x)
if self._output_keys:
| python | {
"resource": ""
} |
q271985 | NeuralNetwork.save_params | test | def save_params(self, path, new_thread=False):
"""
Save parameters to file.
"""
save_logger.info(path)
param_variables = self.all_parameters
params | python | {
"resource": ""
} |
q271986 | NeuralNetwork.load_params | test | def load_params(self, path, exclude_free_params=False):
"""
Load parameters from file.
"""
if not os.path.exists(path): return;
logging.info("loading parameters from %s" % path)
# Decide which parameters to load
if exclude_free_params:
params_to_load = self.parameters
else:
params_to_load = self.all_parameters
# Load parameters
if path.endswith(".gz"):
opener = gzip.open if path.lower().endswith('.gz') else open
handle = opener(path, 'rb')
| python | {
"resource": ""
} |
q271987 | NeuralNetwork.report | test | def report(self):
"""
Print network statistics.
"""
logging.info("network inputs: %s", " ".join(map(str, self.input_variables)))
logging.info("network targets: %s", " ".join(map(str, self.target_variables)))
| python | {
"resource": ""
} |
q271988 | NeuralLayer.register_parameters | test | def register_parameters(self, *parameters):
"""
Register parameters.
"""
for param in parameters:
| python | {
"resource": ""
} |
q271989 | NeuralLayer.register_updates | test | def register_updates(self, *updates):
"""
Register updates that will be executed in each iteration.
"""
| python | {
"resource": ""
} |
q271990 | NeuralLayer.register_training_updates | test | def register_training_updates(self, *updates):
"""
Register updates that will only be executed in training phase.
"""
for key, node in updates:
if key not in self._registered_training_updates:
| python | {
"resource": ""
} |
q271991 | NeuralLayer.register_monitors | test | def register_monitors(self, *monitors):
"""
Register monitors they should be tuple of name and Theano variable.
"""
for key, node in monitors:
if key not in self._registered_monitors:
node *= 1.0 # Avoid CudaNdarray | python | {
"resource": ""
} |
q271992 | multiple_l2_norm | test | def multiple_l2_norm(tensors):
"""
Get the L2 norm of multiple tensors.
This function is taken from blocks.
"""
# Another way for doing this, I don't know which one is fast
# return T.sqrt(sum(T.sum(t ** 2) for t in tensors))
flattened = [T.as_tensor_variable(t).flatten() | python | {
"resource": ""
} |
q271993 | StreamPickler.dump_one | test | def dump_one(elt_to_pickle, file_obj):
"""
dumps one element to file_obj, a file opened in write mode
"""
pickled_elt_str = dumps(elt_to_pickle)
file_obj.write(pickled_elt_str)
| python | {
"resource": ""
} |
q271994 | StreamPickler.load | test | def load(file_obj):
"""
load contents from file_obj, returning a generator that yields one
element at a time
"""
cur_elt = []
for line in file_obj:
cur_elt.append(line)
if line == '\n':
| python | {
"resource": ""
} |
q271995 | Block.load_params | test | def load_params(self, path, exclude_free_params=False):
from deepy.core import graph
"""
Load parameters to the block.
| python | {
"resource": ""
} |
q271996 | OAuth2.create_request_elements | test | def create_request_elements(
cls, request_type, credentials, url, method='GET', params=None,
headers=None, body='', secret=None, redirect_uri='', scope='',
csrf='', user_state=''
):
"""
Creates |oauth2| request elements.
"""
headers = headers or {}
params = params or {}
consumer_key = credentials.consumer_key or ''
consumer_secret = credentials.consumer_secret or ''
token = credentials.token or ''
refresh_token = credentials.refresh_token or credentials.token or ''
# Separate url base and query parameters.
url, base_params = cls._split_url(url)
# Add params extracted from URL.
params.update(dict(base_params))
if request_type == cls.USER_AUTHORIZATION_REQUEST_TYPE:
# User authorization request.
# TODO: Raise error for specific message for each missing argument.
if consumer_key and redirect_uri and (
csrf or not cls.supports_csrf_protection):
params['client_id'] = consumer_key
params['redirect_uri'] = redirect_uri
params['scope'] = scope
if cls.supports_user_state:
params['state'] = base64.urlsafe_b64encode(
json.dumps(
{"csrf": csrf, "user_state": user_state}
).encode('utf-8')
)
else:
params['state'] = csrf
params['response_type'] = 'code'
# Add authorization header
headers.update(cls._authorization_header(credentials))
else:
raise OAuth2Error(
'Credentials with valid consumer_key and arguments '
'redirect_uri, scope and state are required to create '
'OAuth 2.0 user authorization request elements!')
elif request_type == cls.ACCESS_TOKEN_REQUEST_TYPE:
# Access token request.
if consumer_key and consumer_secret:
params['code'] = token
params['client_id'] = consumer_key
params['client_secret'] = consumer_secret
params['redirect_uri'] = redirect_uri
params['grant_type'] = 'authorization_code'
# TODO: Check whether all providers accept it
headers.update(cls._authorization_header(credentials))
else:
| python | {
"resource": ""
} |
q271997 | OAuth2.decode_state | test | def decode_state(cls, state, param='user_state'):
"""
Decode state and return param.
:param str state:
state parameter passed through by provider
:param str param:
key to query from decoded state variable. Options include 'csrf'
and 'user_state'.
:returns:
string value from decoded state
"""
if state and cls.supports_user_state:
# urlsafe_b64 may include = which the browser quotes so must
| python | {
"resource": ""
} |
q271998 | Facebook._x_credentials_parser | test | def _x_credentials_parser(credentials, data):
"""
We need to override this method to fix Facebooks naming deviation.
"""
# Facebook returns "expires" instead of | python | {
"resource": ""
} |
q271999 | Google._x_request_elements_filter | test | def _x_request_elements_filter(cls, request_type, request_elements,
credentials):
"""
Google doesn't accept client ID and secret to be at the same time in
request parameters and in the basic authorization header in the access
token request.
"""
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.