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 |
|---|---|---|---|---|---|---|---|---|---|---|
Cognexa/cxflow | cxflow/hooks/save.py | SaveBest.after_epoch | def after_epoch(self, epoch_data: EpochData, **_) -> None:
"""
Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed
"""
new_value = self._get_value(epoch_data)
if self._is_value_bet... | python | def after_epoch(self, epoch_data: EpochData, **_) -> None:
"""
Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed
"""
new_value = self._get_value(epoch_data)
if self._is_value_bet... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
",",
"*",
"*",
"_",
")",
"->",
"None",
":",
"new_value",
"=",
"self",
".",
"_get_value",
"(",
"epoch_data",
")",
"if",
"self",
".",
"_is_value_better",
"(",
"new_value",
")",
":",
... | Save the model if the new value of the monitored variable is better than the best value so far.
:param epoch_data: epoch data to be processed | [
"Save",
"the",
"model",
"if",
"the",
"new",
"value",
"of",
"the",
"monitored",
"variable",
"is",
"better",
"than",
"the",
"best",
"value",
"so",
"far",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/save.py#L175-L185 |
Cognexa/cxflow | cxflow/hooks/show_progress.py | print_progress_bar | def print_progress_bar(done: int, total: int, prefix: str = '', suffix: str = '') -> None:
"""
Print a progressbar with the given prefix and suffix, without newline at the end.
param done: current step in computation
param total: total count of steps in computation
param prefix: info text displayed... | python | def print_progress_bar(done: int, total: int, prefix: str = '', suffix: str = '') -> None:
"""
Print a progressbar with the given prefix and suffix, without newline at the end.
param done: current step in computation
param total: total count of steps in computation
param prefix: info text displayed... | [
"def",
"print_progress_bar",
"(",
"done",
":",
"int",
",",
"total",
":",
"int",
",",
"prefix",
":",
"str",
"=",
"''",
",",
"suffix",
":",
"str",
"=",
"''",
")",
"->",
"None",
":",
"percent",
"=",
"'{0:.1f}'",
".",
"format",
"(",
"100",
"*",
"(",
... | Print a progressbar with the given prefix and suffix, without newline at the end.
param done: current step in computation
param total: total count of steps in computation
param prefix: info text displayed before the progress bar
param suffix: info text displayed after the progress bar | [
"Print",
"a",
"progressbar",
"with",
"the",
"given",
"prefix",
"and",
"suffix",
"without",
"newline",
"at",
"the",
"end",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/show_progress.py#L14-L39 |
Cognexa/cxflow | cxflow/hooks/show_progress.py | get_formatted_time | def get_formatted_time(seconds: float) -> str:
"""
Convert seconds to the time format ``H:M:S.UU``.
:param seconds: time in seconds
:return: formatted human-readable time
"""
seconds = round(seconds)
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return '{:d}:{:02d}:{:02d}'.format(... | python | def get_formatted_time(seconds: float) -> str:
"""
Convert seconds to the time format ``H:M:S.UU``.
:param seconds: time in seconds
:return: formatted human-readable time
"""
seconds = round(seconds)
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return '{:d}:{:02d}:{:02d}'.format(... | [
"def",
"get_formatted_time",
"(",
"seconds",
":",
"float",
")",
"->",
"str",
":",
"seconds",
"=",
"round",
"(",
"seconds",
")",
"m",
",",
"s",
"=",
"divmod",
"(",
"seconds",
",",
"60",
")",
"h",
",",
"m",
"=",
"divmod",
"(",
"m",
",",
"60",
")",
... | Convert seconds to the time format ``H:M:S.UU``.
:param seconds: time in seconds
:return: formatted human-readable time | [
"Convert",
"seconds",
"to",
"the",
"time",
"format",
"H",
":",
"M",
":",
"S",
".",
"UU",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/show_progress.py#L47-L57 |
Cognexa/cxflow | cxflow/hooks/show_progress.py | ShowProgress.after_batch | def after_batch(self, stream_name: str, batch_data: Batch) -> None:
"""
Display the progress and ETA for the current stream in the epoch.
If the stream size (total batch count) is unknown (1st epoch), print only the number of processed batches.
"""
if self._current_stream_name is... | python | def after_batch(self, stream_name: str, batch_data: Batch) -> None:
"""
Display the progress and ETA for the current stream in the epoch.
If the stream size (total batch count) is unknown (1st epoch), print only the number of processed batches.
"""
if self._current_stream_name is... | [
"def",
"after_batch",
"(",
"self",
",",
"stream_name",
":",
"str",
",",
"batch_data",
":",
"Batch",
")",
"->",
"None",
":",
"if",
"self",
".",
"_current_stream_name",
"is",
"None",
"or",
"self",
".",
"_current_stream_name",
"!=",
"stream_name",
":",
"self",
... | Display the progress and ETA for the current stream in the epoch.
If the stream size (total batch count) is unknown (1st epoch), print only the number of processed batches. | [
"Display",
"the",
"progress",
"and",
"ETA",
"for",
"the",
"current",
"stream",
"in",
"the",
"epoch",
".",
"If",
"the",
"stream",
"size",
"(",
"total",
"batch",
"count",
")",
"is",
"unknown",
"(",
"1st",
"epoch",
")",
"print",
"only",
"the",
"number",
"... | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/show_progress.py#L98-L132 |
Cognexa/cxflow | cxflow/hooks/show_progress.py | ShowProgress.after_epoch | def after_epoch(self, **_) -> None:
"""
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
"""
if not self._total_batch_count_saved:
self._total_batch_count = self._current_batch_count.copy()
self._total_batch_count_saved = True
self.... | python | def after_epoch(self, **_) -> None:
"""
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
"""
if not self._total_batch_count_saved:
self._total_batch_count = self._current_batch_count.copy()
self._total_batch_count_saved = True
self.... | [
"def",
"after_epoch",
"(",
"self",
",",
"*",
"*",
"_",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_total_batch_count_saved",
":",
"self",
".",
"_total_batch_count",
"=",
"self",
".",
"_current_batch_count",
".",
"copy",
"(",
")",
"self",
".",
"_t... | Reset progress counters. Save ``total_batch_count`` after the 1st epoch. | [
"Reset",
"progress",
"counters",
".",
"Save",
"total_batch_count",
"after",
"the",
"1st",
"epoch",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/show_progress.py#L134-L144 |
Cognexa/cxflow | cxflow/hooks/log_profile.py | LogProfile.after_epoch_profile | def after_epoch_profile(self, epoch_id, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
Summarize and log the given epoch profile.
The profile is expected to contain at least:
- ``read_data_train``, ``eval_batch_train`` and ``after_batch_hook... | python | def after_epoch_profile(self, epoch_id, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
Summarize and log the given epoch profile.
The profile is expected to contain at least:
- ``read_data_train``, ``eval_batch_train`` and ``after_batch_hook... | [
"def",
"after_epoch_profile",
"(",
"self",
",",
"epoch_id",
",",
"profile",
":",
"TimeProfile",
",",
"train_stream_name",
":",
"str",
",",
"extra_streams",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"read_data_total",
"=",
"0",
"eval_total",
"... | Summarize and log the given epoch profile.
The profile is expected to contain at least:
- ``read_data_train``, ``eval_batch_train`` and ``after_batch_hooks_train`` entries produced by the train
stream (if train stream name is `train`)
- ``after_epoch_hooks`` entry
... | [
"Summarize",
"and",
"log",
"the",
"given",
"epoch",
"profile",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/log_profile.py#L27-L54 |
Cognexa/cxflow | cxflow/utils/confusion_matrix.py | confusion_matrix | def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray:
"""
Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classe... | python | def confusion_matrix(expected: np.ndarray, predicted: np.ndarray, num_classes: int) -> np.ndarray:
"""
Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classe... | [
"def",
"confusion_matrix",
"(",
"expected",
":",
"np",
".",
"ndarray",
",",
"predicted",
":",
"np",
".",
"ndarray",
",",
"num_classes",
":",
"int",
")",
"->",
"np",
".",
"ndarray",
":",
"assert",
"np",
".",
"issubclass_",
"(",
"expected",
".",
"dtype",
... | Calculate and return confusion matrix for the predicted and expected labels
:param expected: array of expected classes (integers) with shape `[num_of_data]`
:param predicted: array of predicted classes (integers) with shape `[num_of_data]`
:param num_classes: number of classification classes
:return: c... | [
"Calculate",
"and",
"return",
"confusion",
"matrix",
"for",
"the",
"predicted",
"and",
"expected",
"labels"
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/confusion_matrix.py#L4-L22 |
Cognexa/cxflow | cxflow/cli/grid_search.py | _build_grid_search_commands | def _build_grid_search_commands(script: str, params: typing.Iterable[str]) -> typing.Iterable[typing.List[str]]:
"""
Build all grid search parameter configurations.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | python | def _build_grid_search_commands(script: str, params: typing.Iterable[str]) -> typing.Iterable[typing.List[str]]:
"""
Build all grid search parameter configurations.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | [
"def",
"_build_grid_search_commands",
"(",
"script",
":",
"str",
",",
"params",
":",
"typing",
".",
"Iterable",
"[",
"str",
"]",
")",
"->",
"typing",
".",
"Iterable",
"[",
"typing",
".",
"List",
"[",
"str",
"]",
"]",
":",
"param_space",
"=",
"OrderedDict... | Build all grid search parameter configurations.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxflow** param form, e.g. ``'numerical_param=[1, 2]'``
or ``'text_param=["hello", "cio"]'``. | [
"Build",
"all",
"grid",
"search",
"parameter",
"configurations",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/grid_search.py#L13-L41 |
Cognexa/cxflow | cxflow/cli/grid_search.py | grid_search | def grid_search(script: str, params: typing.Iterable[str], dry_run: bool=False) -> None:
"""
Build all grid search parameter configurations and optionally run them.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | python | def grid_search(script: str, params: typing.Iterable[str], dry_run: bool=False) -> None:
"""
Build all grid search parameter configurations and optionally run them.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxfl... | [
"def",
"grid_search",
"(",
"script",
":",
"str",
",",
"params",
":",
"typing",
".",
"Iterable",
"[",
"str",
"]",
",",
"dry_run",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"commands",
"=",
"_build_grid_search_commands",
"(",
"script",
"=",
"scrip... | Build all grid search parameter configurations and optionally run them.
:param script: String of command prefix, e.g. ``cxflow train -v -o log``.
:param params: Iterable collection of strings in standard **cxflow** param form, e.g. ``'numerical_param=[1, 2]'``
or ``'text_param=["hello", "cio... | [
"Build",
"all",
"grid",
"search",
"parameter",
"configurations",
"and",
"optionally",
"run",
"them",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/grid_search.py#L44-L66 |
Cognexa/cxflow | cxflow/datasets/base_dataset.py | BaseDataset.stream_info | def stream_info(self) -> None:
"""Check and report source names, dtypes and shapes of all the streams available."""
stream_names = [stream_name for stream_name in dir(self)
if 'stream' in stream_name and stream_name != 'stream_info']
logging.info('Found %s stream candidat... | python | def stream_info(self) -> None:
"""Check and report source names, dtypes and shapes of all the streams available."""
stream_names = [stream_name for stream_name in dir(self)
if 'stream' in stream_name and stream_name != 'stream_info']
logging.info('Found %s stream candidat... | [
"def",
"stream_info",
"(",
"self",
")",
"->",
"None",
":",
"stream_names",
"=",
"[",
"stream_name",
"for",
"stream_name",
"in",
"dir",
"(",
"self",
")",
"if",
"'stream'",
"in",
"stream_name",
"and",
"stream_name",
"!=",
"'stream_info'",
"]",
"logging",
".",
... | Check and report source names, dtypes and shapes of all the streams available. | [
"Check",
"and",
"report",
"source",
"names",
"dtypes",
"and",
"shapes",
"of",
"all",
"the",
"streams",
"available",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/base_dataset.py#L52-L86 |
Cognexa/cxflow | cxflow/utils/config.py | parse_arg | def parse_arg(arg: str) -> typing.Tuple[str, typing.Any]:
"""
Parse CLI argument in format ``key=value`` to ``(key, value)``
:param arg: CLI argument string
:return: tuple (key, value)
:raise: yaml.ParserError: on yaml parse error
"""
assert '=' in arg, 'Unrecognized argument `{}`. [name]=[... | python | def parse_arg(arg: str) -> typing.Tuple[str, typing.Any]:
"""
Parse CLI argument in format ``key=value`` to ``(key, value)``
:param arg: CLI argument string
:return: tuple (key, value)
:raise: yaml.ParserError: on yaml parse error
"""
assert '=' in arg, 'Unrecognized argument `{}`. [name]=[... | [
"def",
"parse_arg",
"(",
"arg",
":",
"str",
")",
"->",
"typing",
".",
"Tuple",
"[",
"str",
",",
"typing",
".",
"Any",
"]",
":",
"assert",
"'='",
"in",
"arg",
",",
"'Unrecognized argument `{}`. [name]=[value] expected.'",
".",
"format",
"(",
"arg",
")",
"ke... | Parse CLI argument in format ``key=value`` to ``(key, value)``
:param arg: CLI argument string
:return: tuple (key, value)
:raise: yaml.ParserError: on yaml parse error | [
"Parse",
"CLI",
"argument",
"in",
"format",
"key",
"=",
"value",
"to",
"(",
"key",
"value",
")"
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/config.py#L11-L24 |
Cognexa/cxflow | cxflow/utils/config.py | load_config | def load_config(config_file: str, additional_args: typing.Iterable[str]=()) -> dict:
"""
Load config from YAML ``config_file`` and extend/override it with the given ``additional_args``.
:param config_file: path the YAML config file to be loaded
:param additional_args: additional args which may extend o... | python | def load_config(config_file: str, additional_args: typing.Iterable[str]=()) -> dict:
"""
Load config from YAML ``config_file`` and extend/override it with the given ``additional_args``.
:param config_file: path the YAML config file to be loaded
:param additional_args: additional args which may extend o... | [
"def",
"load_config",
"(",
"config_file",
":",
"str",
",",
"additional_args",
":",
"typing",
".",
"Iterable",
"[",
"str",
"]",
"=",
"(",
")",
")",
"->",
"dict",
":",
"config",
"=",
"load_yaml",
"(",
"config_file",
")",
"for",
"key_full",
",",
"value",
... | Load config from YAML ``config_file`` and extend/override it with the given ``additional_args``.
:param config_file: path the YAML config file to be loaded
:param additional_args: additional args which may extend or override the config loaded from the file.
:return: configuration as dict | [
"Load",
"config",
"from",
"YAML",
"config_file",
"and",
"extend",
"/",
"override",
"it",
"with",
"the",
"given",
"additional_args",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/config.py#L27-L48 |
Cognexa/cxflow | cxflow/cli/util.py | find_config | def find_config(config_path: str) -> str:
"""
Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the conf... | python | def find_config(config_path: str) -> str:
"""
Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the conf... | [
"def",
"find_config",
"(",
"config_path",
":",
"str",
")",
"->",
"str",
":",
"if",
"path",
".",
"isdir",
"(",
"config_path",
")",
":",
"# dir specified instead of config file",
"config_path",
"=",
"path",
".",
"join",
"(",
"config_path",
",",
"CXF_CONFIG_FILE",
... | Derive configuration file path from the given path and check its existence.
The given path is expected to be either
1. path to the file
2. path to a dir, in such case the path is joined with ``CXF_CONFIG_FILE``
:param config_path: path to the configuration file or its parent directory
:return: va... | [
"Derive",
"configuration",
"file",
"path",
"from",
"the",
"given",
"path",
"and",
"check",
"its",
"existence",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/util.py#L8-L23 |
Cognexa/cxflow | cxflow/cli/util.py | fallback | def fallback(message: str, ex: Exception) -> None:
"""
Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure
"""
logging.error('%s', message)
logging.exception('%s', ex)
sys.exit(1) | python | def fallback(message: str, ex: Exception) -> None:
"""
Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure
"""
logging.error('%s', message)
logging.exception('%s', ex)
sys.exit(1) | [
"def",
"fallback",
"(",
"message",
":",
"str",
",",
"ex",
":",
"Exception",
")",
"->",
"None",
":",
"logging",
".",
"error",
"(",
"'%s'",
",",
"message",
")",
"logging",
".",
"exception",
"(",
"'%s'",
",",
"ex",
")",
"sys",
".",
"exit",
"(",
"1",
... | Fallback procedure when a cli command fails.
:param message: message to be logged
:param ex: Exception which caused the failure | [
"Fallback",
"procedure",
"when",
"a",
"cli",
"command",
"fails",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/util.py#L40-L49 |
Cognexa/cxflow | cxflow/datasets/downloadable_dataset.py | DownloadableDataset._configure_dataset | def _configure_dataset(self, data_root: str=None, download_urls: Iterable[str]=None, **kwargs) -> None:
"""
Save the passed values and use them as a default property implementation.
:param data_root: directory to which the files will be downloaded
:param download_urls: list of URLs to b... | python | def _configure_dataset(self, data_root: str=None, download_urls: Iterable[str]=None, **kwargs) -> None:
"""
Save the passed values and use them as a default property implementation.
:param data_root: directory to which the files will be downloaded
:param download_urls: list of URLs to b... | [
"def",
"_configure_dataset",
"(",
"self",
",",
"data_root",
":",
"str",
"=",
"None",
",",
"download_urls",
":",
"Iterable",
"[",
"str",
"]",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"self",
".",
"_data_root",
"=",
"data_root",
"sel... | Save the passed values and use them as a default property implementation.
:param data_root: directory to which the files will be downloaded
:param download_urls: list of URLs to be downloaded | [
"Save",
"the",
"passed",
"values",
"and",
"use",
"them",
"as",
"a",
"default",
"property",
"implementation",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/datasets/downloadable_dataset.py#L23-L31 |
Cognexa/cxflow | cxflow/cli/resume.py | resume | def resume(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config from the directory specified and start the training.
:param config_path: path to the config file or the directory in which it is stored
:param restore_from: backend-specific... | python | def resume(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config from the directory specified and start the training.
:param config_path: path to the config file or the directory in which it is stored
:param restore_from: backend-specific... | [
"def",
"resume",
"(",
"config_path",
":",
"str",
",",
"restore_from",
":",
"Optional",
"[",
"str",
"]",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
",",
"output_root",
":",
"str",
")",
"->",
"None",
":",
"config",
"=",
"None",
"try",
":",
... | Load config from the directory specified and start the training.
:param config_path: path to the config file or the directory in which it is stored
:param restore_from: backend-specific path to the already trained model to be restored from.
If ``None`` is passed, it is inferred from th... | [
"Load",
"config",
"from",
"the",
"directory",
"specified",
"and",
"start",
"the",
"training",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/resume.py#L11-L35 |
Cognexa/cxflow | cxflow/hooks/abstract_hook.py | AbstractHook.after_epoch_profile | def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
After epoch profile event.
This event provides opportunity to process time profile of the finished epoch.
:param epoch_id: finished epoch id
:pa... | python | def after_epoch_profile(self, epoch_id: int, profile: TimeProfile, train_stream_name: str, extra_streams: Iterable[str]) -> None:
"""
After epoch profile event.
This event provides opportunity to process time profile of the finished epoch.
:param epoch_id: finished epoch id
:pa... | [
"def",
"after_epoch_profile",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"profile",
":",
"TimeProfile",
",",
"train_stream_name",
":",
"str",
",",
"extra_streams",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"pass"
] | After epoch profile event.
This event provides opportunity to process time profile of the finished epoch.
:param epoch_id: finished epoch id
:param profile: dictionary of lists of event timings that were measured during the epoch
:param extra_streams: enumeration of additional stream n... | [
"After",
"epoch",
"profile",
"event",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/abstract_hook.py#L84-L94 |
Cognexa/cxflow | cxflow/utils/yaml.py | load_yaml | def load_yaml(yaml_file: str) -> Any:
"""
Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list
"""
with open(yaml_file, 'r') as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader) | python | def load_yaml(yaml_file: str) -> Any:
"""
Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list
"""
with open(yaml_file, 'r') as file:
return ruamel.yaml.load(file, ruamel.yaml.RoundTripLoader) | [
"def",
"load_yaml",
"(",
"yaml_file",
":",
"str",
")",
"->",
"Any",
":",
"with",
"open",
"(",
"yaml_file",
",",
"'r'",
")",
"as",
"file",
":",
"return",
"ruamel",
".",
"yaml",
".",
"load",
"(",
"file",
",",
"ruamel",
".",
"yaml",
".",
"RoundTripLoade... | Load YAML from file.
:param yaml_file: path to YAML file
:return: content of the YAML as dict/list | [
"Load",
"YAML",
"from",
"file",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L11-L19 |
Cognexa/cxflow | cxflow/utils/yaml.py | yaml_to_file | def yaml_to_file(data: Mapping, output_dir: str, name: str) -> str:
"""
Save the given object to the given path in YAML.
:param data: dict/list to be dumped
:param output_dir: target output directory
:param name: target filename
:return: target path
"""
dumped_config_f = path.join(outpu... | python | def yaml_to_file(data: Mapping, output_dir: str, name: str) -> str:
"""
Save the given object to the given path in YAML.
:param data: dict/list to be dumped
:param output_dir: target output directory
:param name: target filename
:return: target path
"""
dumped_config_f = path.join(outpu... | [
"def",
"yaml_to_file",
"(",
"data",
":",
"Mapping",
",",
"output_dir",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"str",
":",
"dumped_config_f",
"=",
"path",
".",
"join",
"(",
"output_dir",
",",
"name",
")",
"with",
"open",
"(",
"dumped_config_f",
... | Save the given object to the given path in YAML.
:param data: dict/list to be dumped
:param output_dir: target output directory
:param name: target filename
:return: target path | [
"Save",
"the",
"given",
"object",
"to",
"the",
"given",
"path",
"in",
"YAML",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L22-L34 |
Cognexa/cxflow | cxflow/utils/yaml.py | yaml_to_str | def yaml_to_str(data: Mapping) -> str:
"""
Return the given given config as YAML str.
:param data: configuration dict
:return: given configuration as yaml str
"""
return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper) | python | def yaml_to_str(data: Mapping) -> str:
"""
Return the given given config as YAML str.
:param data: configuration dict
:return: given configuration as yaml str
"""
return yaml.dump(data, Dumper=ruamel.yaml.RoundTripDumper) | [
"def",
"yaml_to_str",
"(",
"data",
":",
"Mapping",
")",
"->",
"str",
":",
"return",
"yaml",
".",
"dump",
"(",
"data",
",",
"Dumper",
"=",
"ruamel",
".",
"yaml",
".",
"RoundTripDumper",
")"
] | Return the given given config as YAML str.
:param data: configuration dict
:return: given configuration as yaml str | [
"Return",
"the",
"given",
"given",
"config",
"as",
"YAML",
"str",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L37-L44 |
Cognexa/cxflow | cxflow/utils/yaml.py | make_simple | def make_simple(data: Any) -> Any:
"""
Substitute all the references in the given data (typically a mapping or sequence) with the actual values.
This is useful, if you loaded a yaml with RoundTripLoader and you need to dump part of it safely.
:param data: data to be made simple (dict instead of Comment... | python | def make_simple(data: Any) -> Any:
"""
Substitute all the references in the given data (typically a mapping or sequence) with the actual values.
This is useful, if you loaded a yaml with RoundTripLoader and you need to dump part of it safely.
:param data: data to be made simple (dict instead of Comment... | [
"def",
"make_simple",
"(",
"data",
":",
"Any",
")",
"->",
"Any",
":",
"return",
"yaml",
".",
"load",
"(",
"yaml",
".",
"dump",
"(",
"data",
",",
"Dumper",
"=",
"ruamel",
".",
"yaml",
".",
"RoundTripDumper",
")",
",",
"Loader",
"=",
"ruamel",
".",
"... | Substitute all the references in the given data (typically a mapping or sequence) with the actual values.
This is useful, if you loaded a yaml with RoundTripLoader and you need to dump part of it safely.
:param data: data to be made simple (dict instead of CommentedMap etc.)
:return: simplified data | [
"Substitute",
"all",
"the",
"references",
"in",
"the",
"given",
"data",
"(",
"typically",
"a",
"mapping",
"or",
"sequence",
")",
"with",
"the",
"actual",
"values",
".",
"This",
"is",
"useful",
"if",
"you",
"loaded",
"a",
"yaml",
"with",
"RoundTripLoader",
... | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L47-L55 |
Cognexa/cxflow | cxflow/utils/yaml.py | reload | def reload(data: Any) -> Any:
"""
Dump and load yaml data.
This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure
the changes are propagated to anchor expansions.
:param data: data to be reloaded
:return: reloaded data
"""
return yaml.load(... | python | def reload(data: Any) -> Any:
"""
Dump and load yaml data.
This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure
the changes are propagated to anchor expansions.
:param data: data to be reloaded
:return: reloaded data
"""
return yaml.load(... | [
"def",
"reload",
"(",
"data",
":",
"Any",
")",
"->",
"Any",
":",
"return",
"yaml",
".",
"load",
"(",
"yaml",
".",
"dump",
"(",
"data",
",",
"Dumper",
"=",
"ruamel",
".",
"yaml",
".",
"RoundTripDumper",
")",
",",
"Loader",
"=",
"ruamel",
".",
"yaml"... | Dump and load yaml data.
This is useful to avoid many anchor parsing bugs. When you edit a yaml config, reload it to make sure
the changes are propagated to anchor expansions.
:param data: data to be reloaded
:return: reloaded data | [
"Dump",
"and",
"load",
"yaml",
"data",
".",
"This",
"is",
"useful",
"to",
"avoid",
"many",
"anchor",
"parsing",
"bugs",
".",
"When",
"you",
"edit",
"a",
"yaml",
"config",
"reload",
"it",
"to",
"make",
"sure",
"the",
"changes",
"are",
"propagated",
"to",
... | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/yaml.py#L58-L67 |
Cognexa/cxflow | cxflow/hooks/on_plateau.py | OnPlateau.after_epoch | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Call :py:meth:`_on_plateau_action` if the ``long_term``
variable mean is lower/greater than the ``short_term`` mean.
"""
super().after_epoch(epoch_id=epoch_id, epoch_data=epoch_data)
self._saved_lo... | python | def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Call :py:meth:`_on_plateau_action` if the ``long_term``
variable mean is lower/greater than the ``short_term`` mean.
"""
super().after_epoch(epoch_id=epoch_id, epoch_data=epoch_data)
self._saved_lo... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"after_epoch",
"(",
"epoch_id",
"=",
"epoch_id",
",",
"epoch_data",
"=",
"epoch_data",
")",
"self",
".",
... | Call :py:meth:`_on_plateau_action` if the ``long_term``
variable mean is lower/greater than the ``short_term`` mean. | [
"Call",
":",
"py",
":",
"meth",
":",
"_on_plateau_action",
"if",
"the",
"long_term",
"variable",
"mean",
"is",
"lower",
"/",
"greater",
"than",
"the",
"short_term",
"mean",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/on_plateau.py#L64-L79 |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN._is_nan | def _is_nan(self, variable: str, data) -> bool:
"""
Recursively search passed data and find NaNs.
:param variable: name of variable to be checked
:param data: data object (dict, list, scalar)
:return: `True` if there is a NaN value in the data; `False` otherwise.
:raise ... | python | def _is_nan(self, variable: str, data) -> bool:
"""
Recursively search passed data and find NaNs.
:param variable: name of variable to be checked
:param data: data object (dict, list, scalar)
:return: `True` if there is a NaN value in the data; `False` otherwise.
:raise ... | [
"def",
"_is_nan",
"(",
"self",
",",
"variable",
":",
"str",
",",
"data",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"data",
",",
"np",
".",
"ndarray",
")",
"or",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"any",
"(",
"np",
... | Recursively search passed data and find NaNs.
:param variable: name of variable to be checked
:param data: data object (dict, list, scalar)
:return: `True` if there is a NaN value in the data; `False` otherwise.
:raise ValueError: if the variable value is of unsupported type and ``on_un... | [
"Recursively",
"search",
"passed",
"data",
"and",
"find",
"NaNs",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L60-L81 |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN._check_nan | def _check_nan(self, epoch_data: EpochData) -> None:
"""
Raise an exception when some of the monitored data is NaN.
:param epoch_data: epoch data checked
:raise KeyError: if the specified variable is not found in the stream
:raise ValueError: if the variable value is of unsuppor... | python | def _check_nan(self, epoch_data: EpochData) -> None:
"""
Raise an exception when some of the monitored data is NaN.
:param epoch_data: epoch data checked
:raise KeyError: if the specified variable is not found in the stream
:raise ValueError: if the variable value is of unsuppor... | [
"def",
"_check_nan",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
"->",
"None",
":",
"for",
"stream_name",
"in",
"epoch_data",
".",
"keys",
"(",
")",
":",
"stream_data",
"=",
"epoch_data",
"[",
"stream_name",
"]",
"variables",
"=",
"self",
".",
... | Raise an exception when some of the monitored data is NaN.
:param epoch_data: epoch data checked
:raise KeyError: if the specified variable is not found in the stream
:raise ValueError: if the variable value is of unsupported type and ``self._on_unknown_type`` is set to ``error`` | [
"Raise",
"an",
"exception",
"when",
"some",
"of",
"the",
"monitored",
"data",
"is",
"NaN",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L83-L101 |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN.after_epoch | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
If initialized to check after each epoch, stop the training once the epoch data contains a monitored
variable equal to NaN.
:param epoch_data: epoch data to be checked
"""
if self._after_epoch:
... | python | def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
If initialized to check after each epoch, stop the training once the epoch data contains a monitored
variable equal to NaN.
:param epoch_data: epoch data to be checked
"""
if self._after_epoch:
... | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"self",
".",
"_after_epoch",
":",
"self",
".",
"_check_nan",
"(",
"epoch_data",
")"
] | If initialized to check after each epoch, stop the training once the epoch data contains a monitored
variable equal to NaN.
:param epoch_data: epoch data to be checked | [
"If",
"initialized",
"to",
"check",
"after",
"each",
"epoch",
"stop",
"the",
"training",
"once",
"the",
"epoch",
"data",
"contains",
"a",
"monitored",
"variable",
"equal",
"to",
"NaN",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L103-L112 |
Cognexa/cxflow | cxflow/hooks/stop_on_nan.py | StopOnNaN.after_batch | def after_batch(self, stream_name: str, batch_data) -> None:
"""
If initialized to check after each batch, stop the training once the batch data contains a monitored
variable equal to NaN.
:param stream_name: name of the stream to be checked
:param batch_data: batch data to be c... | python | def after_batch(self, stream_name: str, batch_data) -> None:
"""
If initialized to check after each batch, stop the training once the batch data contains a monitored
variable equal to NaN.
:param stream_name: name of the stream to be checked
:param batch_data: batch data to be c... | [
"def",
"after_batch",
"(",
"self",
",",
"stream_name",
":",
"str",
",",
"batch_data",
")",
"->",
"None",
":",
"if",
"self",
".",
"_after_batch",
":",
"self",
".",
"_check_nan",
"(",
"{",
"stream_name",
":",
"batch_data",
"}",
")"
] | If initialized to check after each batch, stop the training once the batch data contains a monitored
variable equal to NaN.
:param stream_name: name of the stream to be checked
:param batch_data: batch data to be checked | [
"If",
"initialized",
"to",
"check",
"after",
"each",
"batch",
"stop",
"the",
"training",
"once",
"the",
"batch",
"data",
"contains",
"a",
"monitored",
"variable",
"equal",
"to",
"NaN",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/stop_on_nan.py#L114-L124 |
Cognexa/cxflow | cxflow/hooks/every_n_epoch.py | EveryNEpoch.after_epoch | def after_epoch(self, epoch_id: int, **kwargs) -> None:
"""
Call ``_after_n_epoch`` method every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
if epoch_id % self._n_epochs == 0:
self._after_n_epoch(epoch_id=epoch_id, **kwargs) | python | def after_epoch(self, epoch_id: int, **kwargs) -> None:
"""
Call ``_after_n_epoch`` method every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch
"""
if epoch_id % self._n_epochs == 0:
self._after_n_epoch(epoch_id=epoch_id, **kwargs) | [
"def",
"after_epoch",
"(",
"self",
",",
"epoch_id",
":",
"int",
",",
"*",
"*",
"kwargs",
")",
"->",
"None",
":",
"if",
"epoch_id",
"%",
"self",
".",
"_n_epochs",
"==",
"0",
":",
"self",
".",
"_after_n_epoch",
"(",
"epoch_id",
"=",
"epoch_id",
",",
"*... | Call ``_after_n_epoch`` method every ``n_epochs`` epoch.
:param epoch_id: number of the processed epoch | [
"Call",
"_after_n_epoch",
"method",
"every",
"n_epochs",
"epoch",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/every_n_epoch.py#L33-L40 |
Cognexa/cxflow | cxflow/cli/ls.py | path_total_size | def path_total_size(path_: str) -> int:
"""Compute total size of the given file/dir."""
if path.isfile(path_):
return path.getsize(path_)
total_size = 0
for root_dir, _, files in os.walk(path_):
for file_ in files:
total_size += path.getsize(path.join(root_dir, file_))
re... | python | def path_total_size(path_: str) -> int:
"""Compute total size of the given file/dir."""
if path.isfile(path_):
return path.getsize(path_)
total_size = 0
for root_dir, _, files in os.walk(path_):
for file_ in files:
total_size += path.getsize(path.join(root_dir, file_))
re... | [
"def",
"path_total_size",
"(",
"path_",
":",
"str",
")",
"->",
"int",
":",
"if",
"path",
".",
"isfile",
"(",
"path_",
")",
":",
"return",
"path",
".",
"getsize",
"(",
"path_",
")",
"total_size",
"=",
"0",
"for",
"root_dir",
",",
"_",
",",
"files",
... | Compute total size of the given file/dir. | [
"Compute",
"total",
"size",
"of",
"the",
"given",
"file",
"/",
"dir",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L24-L32 |
Cognexa/cxflow | cxflow/cli/ls.py | humanize_filesize | def humanize_filesize(filesize: int) -> Tuple[str, str]:
"""Return human readable pair of size and unit from the given filesize in bytes."""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if filesize < 1024.0:
return '{:3.1f}'.format(filesize), unit+'B'
filesize /= 1024.0 | python | def humanize_filesize(filesize: int) -> Tuple[str, str]:
"""Return human readable pair of size and unit from the given filesize in bytes."""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if filesize < 1024.0:
return '{:3.1f}'.format(filesize), unit+'B'
filesize /= 1024.0 | [
"def",
"humanize_filesize",
"(",
"filesize",
":",
"int",
")",
"->",
"Tuple",
"[",
"str",
",",
"str",
"]",
":",
"for",
"unit",
"in",
"[",
"''",
",",
"'K'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
",",
"'P'",
",",
"'E'",
",",
"'Z'",
"]",
":",
"if",
... | Return human readable pair of size and unit from the given filesize in bytes. | [
"Return",
"human",
"readable",
"pair",
"of",
"size",
"and",
"unit",
"from",
"the",
"given",
"filesize",
"in",
"bytes",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L35-L40 |
Cognexa/cxflow | cxflow/cli/ls.py | is_train_dir | def is_train_dir(dir_: str) -> bool:
"""Test if the given dir contains training artifacts."""
return path.exists(path.join(dir_, CXF_CONFIG_FILE)) and \
path.exists(path.join(dir_, CXF_TRACE_FILE)) and \
path.exists(path.join(dir_, CXF_LOG_FILE)) | python | def is_train_dir(dir_: str) -> bool:
"""Test if the given dir contains training artifacts."""
return path.exists(path.join(dir_, CXF_CONFIG_FILE)) and \
path.exists(path.join(dir_, CXF_TRACE_FILE)) and \
path.exists(path.join(dir_, CXF_LOG_FILE)) | [
"def",
"is_train_dir",
"(",
"dir_",
":",
"str",
")",
"->",
"bool",
":",
"return",
"path",
".",
"exists",
"(",
"path",
".",
"join",
"(",
"dir_",
",",
"CXF_CONFIG_FILE",
")",
")",
"and",
"path",
".",
"exists",
"(",
"path",
".",
"join",
"(",
"dir_",
"... | Test if the given dir contains training artifacts. | [
"Test",
"if",
"the",
"given",
"dir",
"contains",
"training",
"artifacts",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L43-L47 |
Cognexa/cxflow | cxflow/cli/ls.py | walk_train_dirs | def walk_train_dirs(root_dir: str) -> Iterable[Tuple[str, Iterable[str]]]:
"""
Modify os.walk with the following:
- return only root_dir and sub-dirs
- return only training sub-dirs
- stop recursion at training dirs
:param root_dir: root dir to be walked
:return: generator of (r... | python | def walk_train_dirs(root_dir: str) -> Iterable[Tuple[str, Iterable[str]]]:
"""
Modify os.walk with the following:
- return only root_dir and sub-dirs
- return only training sub-dirs
- stop recursion at training dirs
:param root_dir: root dir to be walked
:return: generator of (r... | [
"def",
"walk_train_dirs",
"(",
"root_dir",
":",
"str",
")",
"->",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"Iterable",
"[",
"str",
"]",
"]",
"]",
":",
"if",
"is_train_dir",
"(",
"root_dir",
")",
":",
"yield",
"''",
",",
"[",
"root_dir",
"]",
"retur... | Modify os.walk with the following:
- return only root_dir and sub-dirs
- return only training sub-dirs
- stop recursion at training dirs
:param root_dir: root dir to be walked
:return: generator of (root_dir, training sub-dirs) pairs | [
"Modify",
"os",
".",
"walk",
"with",
"the",
"following",
":",
"-",
"return",
"only",
"root_dir",
"and",
"sub",
"-",
"dirs",
"-",
"return",
"only",
"training",
"sub",
"-",
"dirs",
"-",
"stop",
"recursion",
"at",
"training",
"dirs"
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L50-L71 |
Cognexa/cxflow | cxflow/cli/ls.py | _print_trainings_long | def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print a plain table with the details of the given trainings.
:param trainings: iterable of tuples (train_dir, configuration dict, trace)
"""
long_table = []
for train_dir, config, trace in trainings:
... | python | def _print_trainings_long(trainings: Iterable[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print a plain table with the details of the given trainings.
:param trainings: iterable of tuples (train_dir, configuration dict, trace)
"""
long_table = []
for train_dir, config, trace in trainings:
... | [
"def",
"_print_trainings_long",
"(",
"trainings",
":",
"Iterable",
"[",
"Tuple",
"[",
"str",
",",
"dict",
",",
"TrainingTrace",
"]",
"]",
")",
"->",
"None",
":",
"long_table",
"=",
"[",
"]",
"for",
"train_dir",
",",
"config",
",",
"trace",
"in",
"trainin... | Print a plain table with the details of the given trainings.
:param trainings: iterable of tuples (train_dir, configuration dict, trace) | [
"Print",
"a",
"plain",
"table",
"with",
"the",
"details",
"of",
"the",
"given",
"trainings",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L89-L114 |
Cognexa/cxflow | cxflow/cli/ls.py | _ls_print_listing | def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]:
"""
Print names of the train dirs contained in the given dir.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
... | python | def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]:
"""
Print names of the train dirs contained in the given dir.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
... | [
"def",
"_ls_print_listing",
"(",
"dir_",
":",
"str",
",",
"recursive",
":",
"bool",
",",
"all_",
":",
"bool",
",",
"long",
":",
"bool",
")",
"->",
"List",
"[",
"Tuple",
"[",
"str",
",",
"dict",
",",
"TrainingTrace",
"]",
"]",
":",
"all_trainings",
"=... | Print names of the train dirs contained in the given dir.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
:param all_: include train dirs with no epochs done (--all option)
:param long: list more details including model name, ... | [
"Print",
"names",
"of",
"the",
"train",
"dirs",
"contained",
"in",
"the",
"given",
"dir",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L117-L152 |
Cognexa/cxflow | cxflow/cli/ls.py | _ls_print_summary | def _ls_print_summary(all_trainings: List[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print trainings summary.
In particular print tables summarizing the number of trainings with
- particular model names
- particular combinations of models and datasets
:param all_trainings: a list of... | python | def _ls_print_summary(all_trainings: List[Tuple[str, dict, TrainingTrace]]) -> None:
"""
Print trainings summary.
In particular print tables summarizing the number of trainings with
- particular model names
- particular combinations of models and datasets
:param all_trainings: a list of... | [
"def",
"_ls_print_summary",
"(",
"all_trainings",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"dict",
",",
"TrainingTrace",
"]",
"]",
")",
"->",
"None",
":",
"counts_by_name",
"=",
"defaultdict",
"(",
"int",
")",
"counts_by_classes",
"=",
"defaultdict",
"(",... | Print trainings summary.
In particular print tables summarizing the number of trainings with
- particular model names
- particular combinations of models and datasets
:param all_trainings: a list of training tuples (train_dir, configuration dict, trace) | [
"Print",
"trainings",
"summary",
".",
"In",
"particular",
"print",
"tables",
"summarizing",
"the",
"number",
"of",
"trainings",
"with",
"-",
"particular",
"model",
"names",
"-",
"particular",
"combinations",
"of",
"models",
"and",
"datasets"
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L155-L179 |
Cognexa/cxflow | cxflow/cli/ls.py | _ls_print_verbose | def _ls_print_verbose(training: Tuple[str, dict, str]) -> None:
"""
Print config and artifacts info from the given training tuple (train_dir, configuration dict, trace).
:param training: training tuple (train_dir, configuration dict, trace)
"""
train_dir, config, _ = training
print_boxed('confi... | python | def _ls_print_verbose(training: Tuple[str, dict, str]) -> None:
"""
Print config and artifacts info from the given training tuple (train_dir, configuration dict, trace).
:param training: training tuple (train_dir, configuration dict, trace)
"""
train_dir, config, _ = training
print_boxed('confi... | [
"def",
"_ls_print_verbose",
"(",
"training",
":",
"Tuple",
"[",
"str",
",",
"dict",
",",
"str",
"]",
")",
"->",
"None",
":",
"train_dir",
",",
"config",
",",
"_",
"=",
"training",
"print_boxed",
"(",
"'config'",
")",
"print",
"(",
"yaml_to_str",
"(",
"... | Print config and artifacts info from the given training tuple (train_dir, configuration dict, trace).
:param training: training tuple (train_dir, configuration dict, trace) | [
"Print",
"config",
"and",
"artifacts",
"info",
"from",
"the",
"given",
"training",
"tuple",
"(",
"train_dir",
"configuration",
"dict",
"trace",
")",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L182-L200 |
Cognexa/cxflow | cxflow/cli/ls.py | list_train_dirs | def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None:
"""
List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.
The function is accessible through cxflow CLI `cxflow ls`.
:param dir_: dir to be listed
:p... | python | def list_train_dirs(dir_: str, recursive: bool, all_: bool, long: bool, verbose: bool) -> None:
"""
List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.
The function is accessible through cxflow CLI `cxflow ls`.
:param dir_: dir to be listed
:p... | [
"def",
"list_train_dirs",
"(",
"dir_",
":",
"str",
",",
"recursive",
":",
"bool",
",",
"all_",
":",
"bool",
",",
"long",
":",
"bool",
",",
"verbose",
":",
"bool",
")",
"->",
"None",
":",
"if",
"verbose",
":",
"long",
"=",
"True",
"if",
"dir_",
"=="... | List training dirs contained in the given dir with options and outputs similar to the regular `ls` command.
The function is accessible through cxflow CLI `cxflow ls`.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
:param all_... | [
"List",
"training",
"dirs",
"contained",
"in",
"the",
"given",
"dir",
"with",
"options",
"and",
"outputs",
"similar",
"to",
"the",
"regular",
"ls",
"command",
".",
"The",
"function",
"is",
"accessible",
"through",
"cxflow",
"CLI",
"cxflow",
"ls",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/ls.py#L203-L238 |
Cognexa/cxflow | cxflow/hooks/accumulate_variables.py | AccumulateVariables.after_batch | def after_batch(self, stream_name: str, batch_data: Batch):
"""
Extend the accumulated variables with the given batch data.
:param stream_name: stream name; e.g. ``train`` or any other...
:param batch_data: batch data = stream sources + model outputs
:raise KeyError: if the vari... | python | def after_batch(self, stream_name: str, batch_data: Batch):
"""
Extend the accumulated variables with the given batch data.
:param stream_name: stream name; e.g. ``train`` or any other...
:param batch_data: batch data = stream sources + model outputs
:raise KeyError: if the vari... | [
"def",
"after_batch",
"(",
"self",
",",
"stream_name",
":",
"str",
",",
"batch_data",
":",
"Batch",
")",
":",
"for",
"variable",
"in",
"self",
".",
"_variables",
":",
"if",
"variable",
"in",
"batch_data",
":",
"value",
"=",
"batch_data",
"[",
"variable",
... | Extend the accumulated variables with the given batch data.
:param stream_name: stream name; e.g. ``train`` or any other...
:param batch_data: batch data = stream sources + model outputs
:raise KeyError: if the variables to be aggregated are missing
:raise TypeError: if the variable val... | [
"Extend",
"the",
"accumulated",
"variables",
"with",
"the",
"given",
"batch",
"data",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/accumulate_variables.py#L40-L57 |
Cognexa/cxflow | cxflow/cli/dataset.py | invoke_dataset_method | def invoke_dataset_method(config_path: str, method_name: str, output_root: str, cl_arguments: Iterable[str]) -> None:
"""
Create the specified dataset and invoke its specified method.
:param config_path: path to the config file or the directory in which it is stored
:param method_name: name of the meth... | python | def invoke_dataset_method(config_path: str, method_name: str, output_root: str, cl_arguments: Iterable[str]) -> None:
"""
Create the specified dataset and invoke its specified method.
:param config_path: path to the config file or the directory in which it is stored
:param method_name: name of the meth... | [
"def",
"invoke_dataset_method",
"(",
"config_path",
":",
"str",
",",
"method_name",
":",
"str",
",",
"output_root",
":",
"str",
",",
"cl_arguments",
":",
"Iterable",
"[",
"str",
"]",
")",
"->",
"None",
":",
"config",
"=",
"dataset",
"=",
"method",
"=",
"... | Create the specified dataset and invoke its specified method.
:param config_path: path to the config file or the directory in which it is stored
:param method_name: name of the method to be invoked on the specified dataset
:param cl_arguments: additional command line arguments which will update the configu... | [
"Create",
"the",
"specified",
"dataset",
"and",
"invoke",
"its",
"specified",
"method",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/dataset.py#L11-L44 |
Cognexa/cxflow | cxflow/utils/misc.py | CaughtInterrupts._signal_handler | def _signal_handler(self, *_) -> None:
"""
On the first signal, increase the ``self._num_signals`` counter.
Call ``sys.exit`` on any subsequent signal.
"""
if self._num_signals == 0:
logging.warning('Interrupt signal caught - training will be terminated')
... | python | def _signal_handler(self, *_) -> None:
"""
On the first signal, increase the ``self._num_signals`` counter.
Call ``sys.exit`` on any subsequent signal.
"""
if self._num_signals == 0:
logging.warning('Interrupt signal caught - training will be terminated')
... | [
"def",
"_signal_handler",
"(",
"self",
",",
"*",
"_",
")",
"->",
"None",
":",
"if",
"self",
".",
"_num_signals",
"==",
"0",
":",
"logging",
".",
"warning",
"(",
"'Interrupt signal caught - training will be terminated'",
")",
"logging",
".",
"warning",
"(",
"'A... | On the first signal, increase the ``self._num_signals`` counter.
Call ``sys.exit`` on any subsequent signal. | [
"On",
"the",
"first",
"signal",
"increase",
"the",
"self",
".",
"_num_signals",
"counter",
".",
"Call",
"sys",
".",
"exit",
"on",
"any",
"subsequent",
"signal",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/utils/misc.py#L95-L106 |
Cognexa/cxflow | cxflow/cli/common.py | create_output_dir | def create_output_dir(config: dict, output_root: str, default_model_name: str='Unnamed') -> str:
"""
Create output_dir under the given ``output_root`` and
- dump the given config to YAML file under this dir
- register a file logger logging to a file under this dir
:param config: config to b... | python | def create_output_dir(config: dict, output_root: str, default_model_name: str='Unnamed') -> str:
"""
Create output_dir under the given ``output_root`` and
- dump the given config to YAML file under this dir
- register a file logger logging to a file under this dir
:param config: config to b... | [
"def",
"create_output_dir",
"(",
"config",
":",
"dict",
",",
"output_root",
":",
"str",
",",
"default_model_name",
":",
"str",
"=",
"'Unnamed'",
")",
"->",
"str",
":",
"logging",
".",
"info",
"(",
"'Creating output dir'",
")",
"# create output dir",
"model_name"... | Create output_dir under the given ``output_root`` and
- dump the given config to YAML file under this dir
- register a file logger logging to a file under this dir
:param config: config to be dumped
:param output_root: dir wherein output_dir shall be created
:param default_model_name: name ... | [
"Create",
"output_dir",
"under",
"the",
"given",
"output_root",
"and",
"-",
"dump",
"the",
"given",
"config",
"to",
"YAML",
"file",
"under",
"this",
"dir",
"-",
"register",
"a",
"file",
"logger",
"logging",
"to",
"a",
"file",
"under",
"this",
"dir"
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L21-L63 |
Cognexa/cxflow | cxflow/cli/common.py | create_dataset | def create_dataset(config: dict, output_dir: Optional[str]=None) -> AbstractDataset:
"""
Create a dataset object according to the given config.
Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string.
:param config: config dict with dataset config
... | python | def create_dataset(config: dict, output_dir: Optional[str]=None) -> AbstractDataset:
"""
Create a dataset object according to the given config.
Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string.
:param config: config dict with dataset config
... | [
"def",
"create_dataset",
"(",
"config",
":",
"dict",
",",
"output_dir",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"AbstractDataset",
":",
"logging",
".",
"info",
"(",
"'Creating dataset'",
")",
"dataset_config",
"=",
"make_simple",
"(",
"conf... | Create a dataset object according to the given config.
Dataset config section and the `output_dir` are passed to the constructor in a single YAML-encoded string.
:param config: config dict with dataset config
:param output_dir: path to the training output dir or None
:return: dataset object | [
"Create",
"a",
"dataset",
"object",
"according",
"to",
"the",
"given",
"config",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L66-L90 |
Cognexa/cxflow | cxflow/cli/common.py | create_model | def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset,
restore_from: Optional[str]=None) -> AbstractModel:
"""
Create a model object either from scratch of from the checkpoint in ``resume_dir``.
Cxflow allows the following scenarios
1. Create model: leave ... | python | def create_model(config: dict, output_dir: Optional[str], dataset: AbstractDataset,
restore_from: Optional[str]=None) -> AbstractModel:
"""
Create a model object either from scratch of from the checkpoint in ``resume_dir``.
Cxflow allows the following scenarios
1. Create model: leave ... | [
"def",
"create_model",
"(",
"config",
":",
"dict",
",",
"output_dir",
":",
"Optional",
"[",
"str",
"]",
",",
"dataset",
":",
"AbstractDataset",
",",
"restore_from",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"AbstractModel",
":",
"logging",
... | Create a model object either from scratch of from the checkpoint in ``resume_dir``.
Cxflow allows the following scenarios
1. Create model: leave ``restore_from=None`` and specify ``class``;
2. Restore model: specify ``restore_from`` which is a backend-specific path to (a directory with) the saved model.
... | [
"Create",
"a",
"model",
"object",
"either",
"from",
"scratch",
"of",
"from",
"the",
"checkpoint",
"in",
"resume_dir",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L93-L146 |
Cognexa/cxflow | cxflow/cli/common.py | create_hooks | def create_hooks(config: dict, model: AbstractModel,
dataset: AbstractDataset, output_dir: str) -> Iterable[AbstractHook]:
"""
Create hooks specified in ``config['hooks']`` list.
Hook config entries may be one of the following types:
.. code-block:: yaml
:caption: A hook with ... | python | def create_hooks(config: dict, model: AbstractModel,
dataset: AbstractDataset, output_dir: str) -> Iterable[AbstractHook]:
"""
Create hooks specified in ``config['hooks']`` list.
Hook config entries may be one of the following types:
.. code-block:: yaml
:caption: A hook with ... | [
"def",
"create_hooks",
"(",
"config",
":",
"dict",
",",
"model",
":",
"AbstractModel",
",",
"dataset",
":",
"AbstractDataset",
",",
"output_dir",
":",
"str",
")",
"->",
"Iterable",
"[",
"AbstractHook",
"]",
":",
"logging",
".",
"info",
"(",
"'Creating hooks'... | Create hooks specified in ``config['hooks']`` list.
Hook config entries may be one of the following types:
.. code-block:: yaml
:caption: A hook with default args specified only by its name as a string; e.g.
hooks:
- LogVariables
- cxflow_tensorflow.WriteTensorBoard
.... | [
"Create",
"hooks",
"specified",
"in",
"config",
"[",
"hooks",
"]",
"list",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L149-L212 |
Cognexa/cxflow | cxflow/cli/common.py | run | def run(config: dict, output_root: str, restore_from: str=None, eval: Optional[str]=None) -> None:
"""
Run **cxflow** training configured by the passed `config`.
Unique ``output_dir`` for this training is created under the given ``output_root`` dir
wherein all the training outputs are saved. The output... | python | def run(config: dict, output_root: str, restore_from: str=None, eval: Optional[str]=None) -> None:
"""
Run **cxflow** training configured by the passed `config`.
Unique ``output_dir`` for this training is created under the given ``output_root`` dir
wherein all the training outputs are saved. The output... | [
"def",
"run",
"(",
"config",
":",
"dict",
",",
"output_root",
":",
"str",
",",
"restore_from",
":",
"str",
"=",
"None",
",",
"eval",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
"->",
"None",
":",
"output_dir",
"=",
"dataset",
"=",
"model",
... | Run **cxflow** training configured by the passed `config`.
Unique ``output_dir`` for this training is created under the given ``output_root`` dir
wherein all the training outputs are saved. The output dir name will be roughly ``[model.name]_[time]``.
The training procedure consists of the following steps:... | [
"Run",
"**",
"cxflow",
"**",
"training",
"configured",
"by",
"the",
"passed",
"config",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/common.py#L215-L309 |
Cognexa/cxflow | cxflow/cli/prune.py | _safe_rmtree | def _safe_rmtree(dir_: str):
"""Wrap ``shutil.rmtree`` to inform user about (un)success."""
try:
rmtree(dir_)
except OSError:
logging.warning('\t\t Skipping %s due to OSError', dir_)
else:
logging.debug('\t\t Deleted %s', dir_) | python | def _safe_rmtree(dir_: str):
"""Wrap ``shutil.rmtree`` to inform user about (un)success."""
try:
rmtree(dir_)
except OSError:
logging.warning('\t\t Skipping %s due to OSError', dir_)
else:
logging.debug('\t\t Deleted %s', dir_) | [
"def",
"_safe_rmtree",
"(",
"dir_",
":",
"str",
")",
":",
"try",
":",
"rmtree",
"(",
"dir_",
")",
"except",
"OSError",
":",
"logging",
".",
"warning",
"(",
"'\\t\\t Skipping %s due to OSError'",
",",
"dir_",
")",
"else",
":",
"logging",
".",
"debug",
"(",
... | Wrap ``shutil.rmtree`` to inform user about (un)success. | [
"Wrap",
"shutil",
".",
"rmtree",
"to",
"inform",
"user",
"about",
"(",
"un",
")",
"success",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/prune.py#L13-L20 |
Cognexa/cxflow | cxflow/cli/prune.py | _prune_subdirs | def _prune_subdirs(dir_: str) -> None:
"""
Delete all subdirs in training log dirs.
:param dir_: dir with training log dirs
"""
for logdir in [path.join(dir_, f) for f in listdir(dir_) if is_train_dir(path.join(dir_, f))]:
for subdir in [path.join(logdir, f) for f in listdir(logdir) if path... | python | def _prune_subdirs(dir_: str) -> None:
"""
Delete all subdirs in training log dirs.
:param dir_: dir with training log dirs
"""
for logdir in [path.join(dir_, f) for f in listdir(dir_) if is_train_dir(path.join(dir_, f))]:
for subdir in [path.join(logdir, f) for f in listdir(logdir) if path... | [
"def",
"_prune_subdirs",
"(",
"dir_",
":",
"str",
")",
"->",
"None",
":",
"for",
"logdir",
"in",
"[",
"path",
".",
"join",
"(",
"dir_",
",",
"f",
")",
"for",
"f",
"in",
"listdir",
"(",
"dir_",
")",
"if",
"is_train_dir",
"(",
"path",
".",
"join",
... | Delete all subdirs in training log dirs.
:param dir_: dir with training log dirs | [
"Delete",
"all",
"subdirs",
"in",
"training",
"log",
"dirs",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/prune.py#L23-L31 |
Cognexa/cxflow | cxflow/cli/prune.py | _prune | def _prune(dir_: str, epochs: int) -> None:
"""
Delete all training dirs with incomplete training artifacts or with less than specified epochs done.
:param dir_: dir with training log dirs
:param epochs: minimum number of finished epochs to keep the training logs
:return: number of log dirs pruned
... | python | def _prune(dir_: str, epochs: int) -> None:
"""
Delete all training dirs with incomplete training artifacts or with less than specified epochs done.
:param dir_: dir with training log dirs
:param epochs: minimum number of finished epochs to keep the training logs
:return: number of log dirs pruned
... | [
"def",
"_prune",
"(",
"dir_",
":",
"str",
",",
"epochs",
":",
"int",
")",
"->",
"None",
":",
"for",
"logdir",
"in",
"[",
"path",
".",
"join",
"(",
"dir_",
",",
"f",
")",
"for",
"f",
"in",
"listdir",
"(",
"dir_",
")",
"if",
"path",
".",
"isdir",... | Delete all training dirs with incomplete training artifacts or with less than specified epochs done.
:param dir_: dir with training log dirs
:param epochs: minimum number of finished epochs to keep the training logs
:return: number of log dirs pruned | [
"Delete",
"all",
"training",
"dirs",
"with",
"incomplete",
"training",
"artifacts",
"or",
"with",
"less",
"than",
"specified",
"epochs",
"done",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/prune.py#L34-L52 |
Cognexa/cxflow | cxflow/cli/prune.py | prune_train_dirs | def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None:
"""
Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`.
:param dir_: dir to be pruned
:param epochs: minimum number of finished epochs to keep the training logs
:param ... | python | def prune_train_dirs(dir_: str, epochs: int, subdirs: bool) -> None:
"""
Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`.
:param dir_: dir to be pruned
:param epochs: minimum number of finished epochs to keep the training logs
:param ... | [
"def",
"prune_train_dirs",
"(",
"dir_",
":",
"str",
",",
"epochs",
":",
"int",
",",
"subdirs",
":",
"bool",
")",
"->",
"None",
":",
"if",
"dir_",
"==",
"CXF_DEFAULT_LOG_DIR",
"and",
"not",
"path",
".",
"exists",
"(",
"CXF_DEFAULT_LOG_DIR",
")",
":",
"pri... | Prune training log dirs contained in the given dir. The function is accessible through cxflow CLI `cxflow prune`.
:param dir_: dir to be pruned
:param epochs: minimum number of finished epochs to keep the training logs
:param subdirs: delete subdirs in training log dirs | [
"Prune",
"training",
"log",
"dirs",
"contained",
"in",
"the",
"given",
"dir",
".",
"The",
"function",
"is",
"accessible",
"through",
"cxflow",
"CLI",
"cxflow",
"prune",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/cli/prune.py#L55-L75 |
Cognexa/cxflow | cxflow/models/sequence.py | Sequence.output_names | def output_names(self) -> Iterable[str]:
"""List of model output names."""
self._load_models()
return chain.from_iterable(map(lambda m: m.output_names, self._models)) | python | def output_names(self) -> Iterable[str]:
"""List of model output names."""
self._load_models()
return chain.from_iterable(map(lambda m: m.output_names, self._models)) | [
"def",
"output_names",
"(",
"self",
")",
"->",
"Iterable",
"[",
"str",
"]",
":",
"self",
".",
"_load_models",
"(",
")",
"return",
"chain",
".",
"from_iterable",
"(",
"map",
"(",
"lambda",
"m",
":",
"m",
".",
"output_names",
",",
"self",
".",
"_models",... | List of model output names. | [
"List",
"of",
"model",
"output",
"names",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/sequence.py#L89-L92 |
Cognexa/cxflow | cxflow/models/sequence.py | Sequence.run | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run all the models in-order and return accumulated outputs.
N-th model is fed with the original inputs and outputs of all the models that were run before it.
.. warning::
:py:class:`Seq... | python | def run(self, batch: Batch, train: bool=False, stream: StreamWrapper=None) -> Batch:
"""
Run all the models in-order and return accumulated outputs.
N-th model is fed with the original inputs and outputs of all the models that were run before it.
.. warning::
:py:class:`Seq... | [
"def",
"run",
"(",
"self",
",",
"batch",
":",
"Batch",
",",
"train",
":",
"bool",
"=",
"False",
",",
"stream",
":",
"StreamWrapper",
"=",
"None",
")",
"->",
"Batch",
":",
"if",
"train",
":",
"raise",
"ValueError",
"(",
"'Ensemble model cannot be trained.'"... | Run all the models in-order and return accumulated outputs.
N-th model is fed with the original inputs and outputs of all the models that were run before it.
.. warning::
:py:class:`Sequence` model can not be trained.
:param batch: batch to be processed
:param train: ``Tru... | [
"Run",
"all",
"the",
"models",
"in",
"-",
"order",
"and",
"return",
"accumulated",
"outputs",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/models/sequence.py#L94-L118 |
Cognexa/cxflow | cxflow/hooks/log_variables.py | LogVariables._log_variables | def _log_variables(self, epoch_data: EpochData):
"""
Log variables from the epoch data.
.. warning::
At the moment, only scalars and dicts of scalars are properly formatted and logged.
Other value types are ignored by default.
One may set ``on_unknown_type`` to ... | python | def _log_variables(self, epoch_data: EpochData):
"""
Log variables from the epoch data.
.. warning::
At the moment, only scalars and dicts of scalars are properly formatted and logged.
Other value types are ignored by default.
One may set ``on_unknown_type`` to ... | [
"def",
"_log_variables",
"(",
"self",
",",
"epoch_data",
":",
"EpochData",
")",
":",
"for",
"stream_name",
"in",
"epoch_data",
".",
"keys",
"(",
")",
":",
"stream_data",
"=",
"epoch_data",
"[",
"stream_name",
"]",
"variables",
"=",
"self",
".",
"_variables",... | Log variables from the epoch data.
.. warning::
At the moment, only scalars and dicts of scalars are properly formatted and logged.
Other value types are ignored by default.
One may set ``on_unknown_type`` to ``str`` in order to log all the variables anyways.
:param ep... | [
"Log",
"variables",
"from",
"the",
"epoch",
"data",
"."
] | train | https://github.com/Cognexa/cxflow/blob/dd609e6b0bd854424a8f86781dd77801a13038f9/cxflow/hooks/log_variables.py#L56-L96 |
hall-lab/svtyper | svtyper/parsers.py | SplitRead.get_reference_end_from_cigar | def get_reference_end_from_cigar(reference_start, cigar):
'''
This returns the coordinate just past the last aligned base.
This matches the behavior of pysam's reference_end method
'''
reference_end = reference_start
# iterate through cigartuple
for i in ... | python | def get_reference_end_from_cigar(reference_start, cigar):
'''
This returns the coordinate just past the last aligned base.
This matches the behavior of pysam's reference_end method
'''
reference_end = reference_start
# iterate through cigartuple
for i in ... | [
"def",
"get_reference_end_from_cigar",
"(",
"reference_start",
",",
"cigar",
")",
":",
"reference_end",
"=",
"reference_start",
"# iterate through cigartuple",
"for",
"i",
"in",
"xrange",
"(",
"len",
"(",
"cigar",
")",
")",
":",
"k",
",",
"n",
"=",
"cigar",
"[... | This returns the coordinate just past the last aligned base.
This matches the behavior of pysam's reference_end method | [
"This",
"returns",
"the",
"coordinate",
"just",
"past",
"the",
"last",
"aligned",
"base",
".",
"This",
"matches",
"the",
"behavior",
"of",
"pysam",
"s",
"reference_end",
"method"
] | train | https://github.com/hall-lab/svtyper/blob/5fc30763fd3025793ee712a563de800c010f6bea/svtyper/parsers.py#L1089-L1101 |
hall-lab/svtyper | svtyper/parsers.py | SplitRead.set_order_by_clip | def set_order_by_clip(self, a, b):
'''
Determine which SplitPiece is the leftmost based
on the side of the longest clipping operation
'''
if self.is_left_clip(a.cigar):
self.query_left = b
self.query_right = a
else:
self.query_left = a
... | python | def set_order_by_clip(self, a, b):
'''
Determine which SplitPiece is the leftmost based
on the side of the longest clipping operation
'''
if self.is_left_clip(a.cigar):
self.query_left = b
self.query_right = a
else:
self.query_left = a
... | [
"def",
"set_order_by_clip",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"if",
"self",
".",
"is_left_clip",
"(",
"a",
".",
"cigar",
")",
":",
"self",
".",
"query_left",
"=",
"b",
"self",
".",
"query_right",
"=",
"a",
"else",
":",
"self",
".",
"query_... | Determine which SplitPiece is the leftmost based
on the side of the longest clipping operation | [
"Determine",
"which",
"SplitPiece",
"is",
"the",
"leftmost",
"based",
"on",
"the",
"side",
"of",
"the",
"longest",
"clipping",
"operation"
] | train | https://github.com/hall-lab/svtyper/blob/5fc30763fd3025793ee712a563de800c010f6bea/svtyper/parsers.py#L1230-L1240 |
hall-lab/svtyper | svtyper/parsers.py | SplitRead.is_left_clip | def is_left_clip(self, cigar):
'''
whether the left side of the read (w/ respect to reference) is clipped.
Clipping side is determined as the side with the longest clip.
Adjacent clipping operations are not considered
'''
left_tuple = cigar[0]
right_tuple = cigar[... | python | def is_left_clip(self, cigar):
'''
whether the left side of the read (w/ respect to reference) is clipped.
Clipping side is determined as the side with the longest clip.
Adjacent clipping operations are not considered
'''
left_tuple = cigar[0]
right_tuple = cigar[... | [
"def",
"is_left_clip",
"(",
"self",
",",
"cigar",
")",
":",
"left_tuple",
"=",
"cigar",
"[",
"0",
"]",
"right_tuple",
"=",
"cigar",
"[",
"-",
"1",
"]",
"left_clipped",
"=",
"self",
".",
"is_clip_op",
"(",
"left_tuple",
"[",
"0",
"]",
")",
"right_clippe... | whether the left side of the read (w/ respect to reference) is clipped.
Clipping side is determined as the side with the longest clip.
Adjacent clipping operations are not considered | [
"whether",
"the",
"left",
"side",
"of",
"the",
"read",
"(",
"w",
"/",
"respect",
"to",
"reference",
")",
"is",
"clipped",
".",
"Clipping",
"side",
"is",
"determined",
"as",
"the",
"side",
"with",
"the",
"longest",
"clip",
".",
"Adjacent",
"clipping",
"op... | train | https://github.com/hall-lab/svtyper/blob/5fc30763fd3025793ee712a563de800c010f6bea/svtyper/parsers.py#L1242-L1253 |
hall-lab/svtyper | scripts/sv_classifier.py | mad | def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays.
med = np.median(arr)
... | python | def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays.
med = np.median(arr)
... | [
"def",
"mad",
"(",
"arr",
")",
":",
"arr",
"=",
"np",
".",
"ma",
".",
"array",
"(",
"arr",
")",
".",
"compressed",
"(",
")",
"# should be faster to not use masked arrays.",
"med",
"=",
"np",
".",
"median",
"(",
"arr",
")",
"return",
"np",
".",
"median"... | Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation | [
"Median",
"Absolute",
"Deviation",
":",
"a",
"Robust",
"version",
"of",
"standard",
"deviation",
".",
"Indices",
"variabililty",
"of",
"the",
"sample",
".",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Median_absolute_deviation"
] | train | https://github.com/hall-lab/svtyper/blob/5fc30763fd3025793ee712a563de800c010f6bea/scripts/sv_classifier.py#L278-L285 |
uber/tchannel-python | tchannel/tornado/request.py | Request._is_streaming_request | def _is_streaming_request(self):
"""check request is stream request or not"""
arg2 = self.argstreams[1]
arg3 = self.argstreams[2]
return not (isinstance(arg2, InMemStream) and
isinstance(arg3, InMemStream) and
((arg2.auto_close and arg3.auto_close)... | python | def _is_streaming_request(self):
"""check request is stream request or not"""
arg2 = self.argstreams[1]
arg3 = self.argstreams[2]
return not (isinstance(arg2, InMemStream) and
isinstance(arg3, InMemStream) and
((arg2.auto_close and arg3.auto_close)... | [
"def",
"_is_streaming_request",
"(",
"self",
")",
":",
"arg2",
"=",
"self",
".",
"argstreams",
"[",
"1",
"]",
"arg3",
"=",
"self",
".",
"argstreams",
"[",
"2",
"]",
"return",
"not",
"(",
"isinstance",
"(",
"arg2",
",",
"InMemStream",
")",
"and",
"isins... | check request is stream request or not | [
"check",
"request",
"is",
"stream",
"request",
"or",
"not"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/request.py#L155-L163 |
uber/tchannel-python | tchannel/tornado/request.py | Request.should_retry_on_error | def should_retry_on_error(self, error):
"""rules for retry
:param error:
ProtocolException that returns from Server
"""
if self.is_streaming_request:
# not retry for streaming request
return False
retry_flag = self.headers.get('re', retry.DE... | python | def should_retry_on_error(self, error):
"""rules for retry
:param error:
ProtocolException that returns from Server
"""
if self.is_streaming_request:
# not retry for streaming request
return False
retry_flag = self.headers.get('re', retry.DE... | [
"def",
"should_retry_on_error",
"(",
"self",
",",
"error",
")",
":",
"if",
"self",
".",
"is_streaming_request",
":",
"# not retry for streaming request",
"return",
"False",
"retry_flag",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"'re'",
",",
"retry",
".",
... | rules for retry
:param error:
ProtocolException that returns from Server | [
"rules",
"for",
"retry"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/request.py#L165-L196 |
uber/tchannel-python | tchannel/sync/thrift.py | client_for | def client_for(service, service_module, thrift_service_name=None):
"""Build a synchronous client class for the given Thrift service.
The generated class accepts a TChannelSyncClient and an optional
hostport as initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registe... | python | def client_for(service, service_module, thrift_service_name=None):
"""Build a synchronous client class for the given Thrift service.
The generated class accepts a TChannelSyncClient and an optional
hostport as initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registe... | [
"def",
"client_for",
"(",
"service",
",",
"service_module",
",",
"thrift_service_name",
"=",
"None",
")",
":",
"assert",
"service_module",
",",
"'service_module is required'",
"service",
"=",
"service",
"or",
"''",
"# may be blank for non-hyperbahn use cases",
"if",
"no... | Build a synchronous client class for the given Thrift service.
The generated class accepts a TChannelSyncClient and an optional
hostport as initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered
with Hyperbahn under the name "comment", here's how this might be ... | [
"Build",
"a",
"synchronous",
"client",
"class",
"for",
"the",
"given",
"Thrift",
"service",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/sync/thrift.py#L27-L106 |
uber/tchannel-python | tchannel/sync/thrift.py | generate_method | def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
... | python | def generate_method(method_name):
"""Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient
"""
... | [
"def",
"generate_method",
"(",
"method_name",
")",
":",
"def",
"call",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Forward RPC call to TChannelSyncClient\n\n :return concurrent.futures.Future:\n \"\"\"",
"if",
"not",
"self",
".... | Generate a method for a given Thrift service.
Uses the provided TChannelSyncClient's threadloop in order
to convert RPC calls to concurrent.futures
:param method_name: Method being called.
:return: A method that invokes the RPC using TChannelSyncClient | [
"Generate",
"a",
"method",
"for",
"a",
"given",
"Thrift",
"service",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/sync/thrift.py#L109-L131 |
uber/tchannel-python | tchannel/tornado/stream.py | read_full | def read_full(stream):
"""Read the full contents of the given stream into memory.
:return:
A future containing the complete stream contents.
"""
assert stream, "stream is required"
chunks = []
chunk = yield stream.read()
while chunk:
chunks.append(chunk)
chunk = yi... | python | def read_full(stream):
"""Read the full contents of the given stream into memory.
:return:
A future containing the complete stream contents.
"""
assert stream, "stream is required"
chunks = []
chunk = yield stream.read()
while chunk:
chunks.append(chunk)
chunk = yi... | [
"def",
"read_full",
"(",
"stream",
")",
":",
"assert",
"stream",
",",
"\"stream is required\"",
"chunks",
"=",
"[",
"]",
"chunk",
"=",
"yield",
"stream",
".",
"read",
"(",
")",
"while",
"chunk",
":",
"chunks",
".",
"append",
"(",
"chunk",
")",
"chunk",
... | Read the full contents of the given stream into memory.
:return:
A future containing the complete stream contents. | [
"Read",
"the",
"full",
"contents",
"of",
"the",
"given",
"stream",
"into",
"memory",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/stream.py#L37-L52 |
uber/tchannel-python | tchannel/tornado/stream.py | maybe_stream | def maybe_stream(s):
"""Ensure that the given argument is a stream."""
if isinstance(s, Stream):
return s
if s is None:
stream = InMemStream()
stream.close() # we don't intend to write anything
return stream
if isinstance(s, unicode):
s = s.encode('utf-8')
... | python | def maybe_stream(s):
"""Ensure that the given argument is a stream."""
if isinstance(s, Stream):
return s
if s is None:
stream = InMemStream()
stream.close() # we don't intend to write anything
return stream
if isinstance(s, unicode):
s = s.encode('utf-8')
... | [
"def",
"maybe_stream",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"Stream",
")",
":",
"return",
"s",
"if",
"s",
"is",
"None",
":",
"stream",
"=",
"InMemStream",
"(",
")",
"stream",
".",
"close",
"(",
")",
"# we don't intend to write anything"... | Ensure that the given argument is a stream. | [
"Ensure",
"that",
"the",
"given",
"argument",
"is",
"a",
"stream",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/stream.py#L259-L280 |
uber/tchannel-python | tchannel/tornado/message_factory.py | build_raw_error_message | def build_raw_error_message(protocol_exception):
"""build protocol level error message based on Error object"""
message = ErrorMessage(
id=protocol_exception.id,
code=protocol_exception.code,
tracing=protocol_exception.tracing,
description=protocol_exception.description,
)
... | python | def build_raw_error_message(protocol_exception):
"""build protocol level error message based on Error object"""
message = ErrorMessage(
id=protocol_exception.id,
code=protocol_exception.code,
tracing=protocol_exception.tracing,
description=protocol_exception.description,
)
... | [
"def",
"build_raw_error_message",
"(",
"protocol_exception",
")",
":",
"message",
"=",
"ErrorMessage",
"(",
"id",
"=",
"protocol_exception",
".",
"id",
",",
"code",
"=",
"protocol_exception",
".",
"code",
",",
"tracing",
"=",
"protocol_exception",
".",
"tracing",
... | build protocol level error message based on Error object | [
"build",
"protocol",
"level",
"error",
"message",
"based",
"on",
"Error",
"object"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L49-L58 |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_raw_request_message | def build_raw_request_message(self, request, args, is_completed=False):
"""build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the messa... | python | def build_raw_request_message(self, request, args, is_completed=False):
"""build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the messa... | [
"def",
"build_raw_request_message",
"(",
"self",
",",
"request",
",",
"args",
",",
"is_completed",
"=",
"False",
")",
":",
"request",
".",
"flags",
"=",
"FlagsType",
".",
"none",
"if",
"is_completed",
"else",
"FlagsType",
".",
"fragment",
"# TODO decide what nee... | build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the message
:param request: Request
:param args: array of arg streams
... | [
"build",
"protocol",
"level",
"message",
"based",
"on",
"request",
"and",
"args",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L76-L113 |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_raw_response_message | def build_raw_response_message(self, response, args, is_completed=False):
"""build protocol level message based on response and args.
response object contains meta information about outgoing response.
args are the currently chunk data from argstreams
is_completed tells the flags of the ... | python | def build_raw_response_message(self, response, args, is_completed=False):
"""build protocol level message based on response and args.
response object contains meta information about outgoing response.
args are the currently chunk data from argstreams
is_completed tells the flags of the ... | [
"def",
"build_raw_response_message",
"(",
"self",
",",
"response",
",",
"args",
",",
"is_completed",
"=",
"False",
")",
":",
"response",
".",
"flags",
"=",
"FlagsType",
".",
"none",
"if",
"is_completed",
"else",
"FlagsType",
".",
"fragment",
"# TODO decide what ... | build protocol level message based on response and args.
response object contains meta information about outgoing response.
args are the currently chunk data from argstreams
is_completed tells the flags of the message
:param response: Response
:param args: array of arg streams
... | [
"build",
"protocol",
"level",
"message",
"based",
"on",
"response",
"and",
"args",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L115-L151 |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_request | def build_request(self, message):
"""Build inbound request object from protocol level message info.
It is allowed to take incompleted CallRequestMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallRequestMessage
:return: request obj... | python | def build_request(self, message):
"""Build inbound request object from protocol level message info.
It is allowed to take incompleted CallRequestMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallRequestMessage
:return: request obj... | [
"def",
"build_request",
"(",
"self",
",",
"message",
")",
":",
"args",
"=",
"self",
".",
"prepare_args",
"(",
"message",
")",
"# TODO decide what to pass to Request from message",
"req",
"=",
"Request",
"(",
"flags",
"=",
"message",
".",
"flags",
",",
"ttl",
"... | Build inbound request object from protocol level message info.
It is allowed to take incompleted CallRequestMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallRequestMessage
:return: request object | [
"Build",
"inbound",
"request",
"object",
"from",
"protocol",
"level",
"message",
"info",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L172-L195 |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build_response | def build_response(self, message):
"""Build response object from protocol level message info
It is allowed to take incompleted CallResponseMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallResponseMessage
:return: response object
... | python | def build_response(self, message):
"""Build response object from protocol level message info
It is allowed to take incompleted CallResponseMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallResponseMessage
:return: response object
... | [
"def",
"build_response",
"(",
"self",
",",
"message",
")",
":",
"args",
"=",
"self",
".",
"prepare_args",
"(",
"message",
")",
"# TODO decide what to pass to Response from message",
"res",
"=",
"Response",
"(",
"flags",
"=",
"message",
".",
"flags",
",",
"code",... | Build response object from protocol level message info
It is allowed to take incompleted CallResponseMessage. Therefore the
created request may not contain whole three arguments.
:param message: CallResponseMessage
:return: response object | [
"Build",
"response",
"object",
"from",
"protocol",
"level",
"message",
"info"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L197-L218 |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.build | def build(self, message):
"""buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done
"""
context = None
... | python | def build(self, message):
"""buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done
"""
context = None
... | [
"def",
"build",
"(",
"self",
",",
"message",
")",
":",
"context",
"=",
"None",
"if",
"message",
".",
"message_type",
"in",
"[",
"Types",
".",
"CALL_REQ",
",",
"Types",
".",
"CALL_RES",
"]",
":",
"self",
".",
"verify_message",
"(",
"message",
")",
"cont... | buffer all the streaming messages based on the
message id. Reconstruct all fragments together.
:param message:
incoming message
:return: next complete message or None if streaming
is not done | [
"buffer",
"all",
"the",
"streaming",
"messages",
"based",
"on",
"the",
"message",
"id",
".",
"Reconstruct",
"all",
"fragments",
"together",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L226-L309 |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.fragment | def fragment(self, message):
"""Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
... | python | def fragment(self, message):
"""Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
... | [
"def",
"fragment",
"(",
"self",
",",
"message",
")",
":",
"if",
"message",
".",
"message_type",
"in",
"[",
"Types",
".",
"CALL_RES",
",",
"Types",
".",
"CALL_REQ",
",",
"Types",
".",
"CALL_REQ_CONTINUE",
",",
"Types",
".",
"CALL_RES_CONTINUE",
"]",
":",
... | Fragment message based on max payload size
note: if the message doesn't need to fragment,
it will return a list which only contains original
message itself.
:param message: raw message
:return: list of messages whose sizes <= max
payload size | [
"Fragment",
"message",
"based",
"on",
"max",
"payload",
"size"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L311-L345 |
uber/tchannel-python | tchannel/tornado/message_factory.py | MessageFactory.verify_message | def verify_message(self, message):
"""Verify the checksum of the message."""
if verify_checksum(
message,
self.in_checksum.get(message.id, 0),
):
self.in_checksum[message.id] = message.checksum[1]
if message.flags == FlagsType.none:
... | python | def verify_message(self, message):
"""Verify the checksum of the message."""
if verify_checksum(
message,
self.in_checksum.get(message.id, 0),
):
self.in_checksum[message.id] = message.checksum[1]
if message.flags == FlagsType.none:
... | [
"def",
"verify_message",
"(",
"self",
",",
"message",
")",
":",
"if",
"verify_checksum",
"(",
"message",
",",
"self",
".",
"in_checksum",
".",
"get",
"(",
"message",
".",
"id",
",",
"0",
")",
",",
")",
":",
"self",
".",
"in_checksum",
"[",
"message",
... | Verify the checksum of the message. | [
"Verify",
"the",
"checksum",
"of",
"the",
"message",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/message_factory.py#L359-L374 |
uber/tchannel-python | tchannel/rw.py | chain | def chain(*rws):
"""Build a ReadWriter from the given list of ReadWriters.
.. code-block:: python
chain(
number(1),
number(8),
len_prefixed_string(number(2)),
) # == n1:1 n2:8 s~2
Reads/writes from the given ReadWriters in-order. Returns lists of value... | python | def chain(*rws):
"""Build a ReadWriter from the given list of ReadWriters.
.. code-block:: python
chain(
number(1),
number(8),
len_prefixed_string(number(2)),
) # == n1:1 n2:8 s~2
Reads/writes from the given ReadWriters in-order. Returns lists of value... | [
"def",
"chain",
"(",
"*",
"rws",
")",
":",
"assert",
"rws",
"is",
"not",
"None",
"if",
"len",
"(",
"rws",
")",
"==",
"1",
"and",
"isinstance",
"(",
"rws",
"[",
"0",
"]",
",",
"list",
")",
":",
"# In case someone does chain([l0, l1, ...])",
"rws",
"=",
... | Build a ReadWriter from the given list of ReadWriters.
.. code-block:: python
chain(
number(1),
number(8),
len_prefixed_string(number(2)),
) # == n1:1 n2:8 s~2
Reads/writes from the given ReadWriters in-order. Returns lists of values
in the same order ... | [
"Build",
"a",
"ReadWriter",
"from",
"the",
"given",
"list",
"of",
"ReadWriters",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/rw.py#L82-L103 |
uber/tchannel-python | tchannel/rw.py | ReadWriter.take | def take(self, stream, num):
"""Read the given number of bytes from the stream.
:param stream:
stream to read from
:param num:
number of bytes to read
:raises ReadError:
if the stream did not yield the exact number of bytes expected
"""
... | python | def take(self, stream, num):
"""Read the given number of bytes from the stream.
:param stream:
stream to read from
:param num:
number of bytes to read
:raises ReadError:
if the stream did not yield the exact number of bytes expected
"""
... | [
"def",
"take",
"(",
"self",
",",
"stream",
",",
"num",
")",
":",
"s",
"=",
"stream",
".",
"read",
"(",
"num",
")",
"slen",
"=",
"len",
"(",
"s",
")",
"if",
"slen",
"!=",
"num",
":",
"raise",
"ReadError",
"(",
"\"Expected %d bytes but got %d bytes.\"",
... | Read the given number of bytes from the stream.
:param stream:
stream to read from
:param num:
number of bytes to read
:raises ReadError:
if the stream did not yield the exact number of bytes expected | [
"Read",
"the",
"given",
"number",
"of",
"bytes",
"from",
"the",
"stream",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/rw.py#L266-L282 |
uber/tchannel-python | tchannel/thrift/reflection.py | get_service_methods | def get_service_methods(iface):
"""Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service.
"""
methods... | python | def get_service_methods(iface):
"""Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service.
"""
methods... | [
"def",
"get_service_methods",
"(",
"iface",
")",
":",
"methods",
"=",
"inspect",
".",
"getmembers",
"(",
"iface",
",",
"predicate",
"=",
"inspect",
".",
"ismethod",
")",
"return",
"set",
"(",
"name",
"for",
"(",
"name",
",",
"method",
")",
"in",
"methods... | Get a list of methods defined in the interface for a Thrift service.
:param iface:
The Thrift-generated Iface class defining the interface for the
service.
:returns:
A set containing names of the methods defined for the service. | [
"Get",
"a",
"list",
"of",
"methods",
"defined",
"in",
"the",
"interface",
"for",
"a",
"Thrift",
"service",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/reflection.py#L27-L40 |
uber/tchannel-python | tchannel/deprecate.py | deprecate | def deprecate(message):
"""Loudly prints warning."""
warnings.simplefilter('default')
warnings.warn(message, category=DeprecationWarning)
warnings.resetwarnings() | python | def deprecate(message):
"""Loudly prints warning."""
warnings.simplefilter('default')
warnings.warn(message, category=DeprecationWarning)
warnings.resetwarnings() | [
"def",
"deprecate",
"(",
"message",
")",
":",
"warnings",
".",
"simplefilter",
"(",
"'default'",
")",
"warnings",
".",
"warn",
"(",
"message",
",",
"category",
"=",
"DeprecationWarning",
")",
"warnings",
".",
"resetwarnings",
"(",
")"
] | Loudly prints warning. | [
"Loudly",
"prints",
"warning",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/deprecate.py#L29-L33 |
uber/tchannel-python | tchannel/deprecate.py | deprecated | def deprecated(message):
"""Warn every time a fn is called."""
def decorator(fn):
@functools.wraps(fn)
def new_fn(*args, **kwargs):
deprecate(message)
return fn(*args, **kwargs)
return new_fn
return decorator | python | def deprecated(message):
"""Warn every time a fn is called."""
def decorator(fn):
@functools.wraps(fn)
def new_fn(*args, **kwargs):
deprecate(message)
return fn(*args, **kwargs)
return new_fn
return decorator | [
"def",
"deprecated",
"(",
"message",
")",
":",
"def",
"decorator",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"new_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"deprecate",
"(",
"message",
")",
"return"... | Warn every time a fn is called. | [
"Warn",
"every",
"time",
"a",
"fn",
"is",
"called",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/deprecate.py#L36-L44 |
uber/tchannel-python | tchannel/thrift/rw.py | load | def load(path, service=None, hostport=None, module_name=None):
"""Loads the Thrift file at the specified path.
The file is compiled in-memory and a Python module containing the result
is returned. It may be used with ``TChannel.thrift``. For example,
.. code-block:: python
from tchannel impor... | python | def load(path, service=None, hostport=None, module_name=None):
"""Loads the Thrift file at the specified path.
The file is compiled in-memory and a Python module containing the result
is returned. It may be used with ``TChannel.thrift``. For example,
.. code-block:: python
from tchannel impor... | [
"def",
"load",
"(",
"path",
",",
"service",
"=",
"None",
",",
"hostport",
"=",
"None",
",",
"module_name",
"=",
"None",
")",
":",
"# TODO replace with more specific exceptions",
"# assert service, 'service is required'",
"# assert path, 'path is required'",
"# Backwards com... | Loads the Thrift file at the specified path.
The file is compiled in-memory and a Python module containing the result
is returned. It may be used with ``TChannel.thrift``. For example,
.. code-block:: python
from tchannel import TChannel, thrift
# Load our server's interface definition.
... | [
"Loads",
"the",
"Thrift",
"file",
"at",
"the",
"specified",
"path",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/rw.py#L40-L154 |
uber/tchannel-python | tchannel/thrift/rw.py | register | def register(dispatcher, service, handler=None, method=None):
"""
:param dispatcher:
RequestDispatcher against which the new endpoint will be registered.
:param Service service:
Service object representing the service whose endpoint is being
registered.
:param handler:
A ... | python | def register(dispatcher, service, handler=None, method=None):
"""
:param dispatcher:
RequestDispatcher against which the new endpoint will be registered.
:param Service service:
Service object representing the service whose endpoint is being
registered.
:param handler:
A ... | [
"def",
"register",
"(",
"dispatcher",
",",
"service",
",",
"handler",
"=",
"None",
",",
"method",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"method",
",",
"handler",
")",
":",
"if",
"not",
"method",
":",
"method",
"=",
"handler",
".",
"__name__",... | :param dispatcher:
RequestDispatcher against which the new endpoint will be registered.
:param Service service:
Service object representing the service whose endpoint is being
registered.
:param handler:
A function implementing the given Thrift function.
:param method:
... | [
":",
"param",
"dispatcher",
":",
"RequestDispatcher",
"against",
"which",
"the",
"new",
"endpoint",
"will",
"be",
"registered",
".",
":",
"param",
"Service",
"service",
":",
"Service",
"object",
"representing",
"the",
"service",
"whose",
"endpoint",
"is",
"being... | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/rw.py#L294-L329 |
uber/tchannel-python | tchannel/net.py | interface_ip | def interface_ip(interface):
"""Determine the IP assigned to us by the given network interface."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl.ioctl(
sock.fileno(), 0x8915, struct.pack('256s', interface[:15])
)[20:24]
) | python | def interface_ip(interface):
"""Determine the IP assigned to us by the given network interface."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl.ioctl(
sock.fileno(), 0x8915, struct.pack('256s', interface[:15])
)[20:24]
) | [
"def",
"interface_ip",
"(",
"interface",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"return",
"socket",
".",
"inet_ntoa",
"(",
"fcntl",
".",
"ioctl",
"(",
"sock",
".",
"fileno",
... | Determine the IP assigned to us by the given network interface. | [
"Determine",
"the",
"IP",
"assigned",
"to",
"us",
"by",
"the",
"given",
"network",
"interface",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/net.py#L31-L38 |
uber/tchannel-python | tchannel/net.py | local_ip | def local_ip():
"""Get the local network IP of this machine"""
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith('127.'):
# Check eth0, eth1, eth2, en0, ...
interfaces = [
i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
] # :(
for inte... | python | def local_ip():
"""Get the local network IP of this machine"""
ip = socket.gethostbyname(socket.gethostname())
if ip.startswith('127.'):
# Check eth0, eth1, eth2, en0, ...
interfaces = [
i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3)
] # :(
for inte... | [
"def",
"local_ip",
"(",
")",
":",
"ip",
"=",
"socket",
".",
"gethostbyname",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"if",
"ip",
".",
"startswith",
"(",
"'127.'",
")",
":",
"# Check eth0, eth1, eth2, en0, ...",
"interfaces",
"=",
"[",
"i",
"+",
... | Get the local network IP of this machine | [
"Get",
"the",
"local",
"network",
"IP",
"of",
"this",
"machine"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/net.py#L44-L58 |
uber/tchannel-python | tchannel/thrift/client.py | client_for | def client_for(service, service_module, thrift_service_name=None):
"""Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn... | python | def client_for(service, service_module, thrift_service_name=None):
"""Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn... | [
"def",
"client_for",
"(",
"service",
",",
"service_module",
",",
"thrift_service_name",
"=",
"None",
")",
":",
"assert",
"service_module",
",",
"'service_module is required'",
"service",
"=",
"service",
"or",
"''",
"# may be blank for non-hyperbahn use cases",
"if",
"no... | Build a client class for the given Thrift service.
The generated class accepts a TChannel and an optional hostport as
initialization arguments.
Given ``CommentService`` defined in ``comment.thrift`` and registered with
Hyperbahn under the name "comment", here's how this may be used:
.. code-block... | [
"Build",
"a",
"client",
"class",
"for",
"the",
"given",
"Thrift",
"service",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/client.py#L48-L114 |
uber/tchannel-python | tchannel/thrift/client.py | generate_method | def generate_method(service_module, service_name, method_name):
"""Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called
"""
assert se... | python | def generate_method(service_module, service_name, method_name):
"""Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called
"""
assert se... | [
"def",
"generate_method",
"(",
"service_module",
",",
"service_name",
",",
"method_name",
")",
":",
"assert",
"service_module",
"assert",
"service_name",
"assert",
"method_name",
"args_type",
"=",
"getattr",
"(",
"service_module",
",",
"method_name",
"+",
"'_args'",
... | Generate a method for the given Thrift service.
:param service_module:
Thrift-generated service module
:param service_name:
Name of the Thrift service
:param method_name:
Method being called | [
"Generate",
"a",
"method",
"for",
"the",
"given",
"Thrift",
"service",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/thrift/client.py#L117-L242 |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.connect | def connect(self):
"""Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host.
... | python | def connect(self):
"""Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host.
... | [
"def",
"connect",
"(",
"self",
")",
":",
"# Prefer incoming connections over outgoing connections.",
"if",
"self",
".",
"connections",
":",
"# First value is an incoming connection",
"future",
"=",
"gen",
".",
"Future",
"(",
")",
"future",
".",
"set_result",
"(",
"sel... | Get a connection to this peer.
If an connection to the peer already exists (either incoming or
outgoing), that's returned. Otherwise, a new outgoing connection to
this peer is created.
:return:
A future containing a connection to this host. | [
"Get",
"a",
"connection",
"to",
"this",
"peer",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L135-L174 |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.register_outgoing_conn | def register_outgoing_conn(self, conn):
"""Add outgoing connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.append(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | python | def register_outgoing_conn(self, conn):
"""Add outgoing connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.append(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | [
"def",
"register_outgoing_conn",
"(",
"self",
",",
"conn",
")",
":",
"assert",
"conn",
",",
"\"conn is required\"",
"conn",
".",
"set_outbound_pending_change_callback",
"(",
"self",
".",
"_on_conn_change",
")",
"self",
".",
"connections",
".",
"append",
"(",
"conn... | Add outgoing connection into the heap. | [
"Add",
"outgoing",
"connection",
"into",
"the",
"heap",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L188-L194 |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.register_incoming_conn | def register_incoming_conn(self, conn):
"""Add incoming connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.appendleft(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | python | def register_incoming_conn(self, conn):
"""Add incoming connection into the heap."""
assert conn, "conn is required"
conn.set_outbound_pending_change_callback(self._on_conn_change)
self.connections.appendleft(conn)
self._set_on_close_cb(conn)
self._on_conn_change() | [
"def",
"register_incoming_conn",
"(",
"self",
",",
"conn",
")",
":",
"assert",
"conn",
",",
"\"conn is required\"",
"conn",
".",
"set_outbound_pending_change_callback",
"(",
"self",
".",
"_on_conn_change",
")",
"self",
".",
"connections",
".",
"appendleft",
"(",
"... | Add incoming connection into the heap. | [
"Add",
"incoming",
"connection",
"into",
"the",
"heap",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L196-L202 |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.outgoing_connections | def outgoing_connections(self):
"""Returns a list of all outgoing connections for this peer."""
# Outgoing connections are on the right
return list(
dropwhile(lambda c: c.direction != OUTGOING, self.connections)
) | python | def outgoing_connections(self):
"""Returns a list of all outgoing connections for this peer."""
# Outgoing connections are on the right
return list(
dropwhile(lambda c: c.direction != OUTGOING, self.connections)
) | [
"def",
"outgoing_connections",
"(",
"self",
")",
":",
"# Outgoing connections are on the right",
"return",
"list",
"(",
"dropwhile",
"(",
"lambda",
"c",
":",
"c",
".",
"direction",
"!=",
"OUTGOING",
",",
"self",
".",
"connections",
")",
")"
] | Returns a list of all outgoing connections for this peer. | [
"Returns",
"a",
"list",
"of",
"all",
"outgoing",
"connections",
"for",
"this",
"peer",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L215-L221 |
uber/tchannel-python | tchannel/tornado/peer.py | Peer.incoming_connections | def incoming_connections(self):
"""Returns a list of all incoming connections for this peer."""
# Incoming connections are on the left.
return list(
takewhile(lambda c: c.direction == INCOMING, self.connections)
) | python | def incoming_connections(self):
"""Returns a list of all incoming connections for this peer."""
# Incoming connections are on the left.
return list(
takewhile(lambda c: c.direction == INCOMING, self.connections)
) | [
"def",
"incoming_connections",
"(",
"self",
")",
":",
"# Incoming connections are on the left.",
"return",
"list",
"(",
"takewhile",
"(",
"lambda",
"c",
":",
"c",
".",
"direction",
"==",
"INCOMING",
",",
"self",
".",
"connections",
")",
")"
] | Returns a list of all incoming connections for this peer. | [
"Returns",
"a",
"list",
"of",
"all",
"incoming",
"connections",
"for",
"this",
"peer",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L224-L230 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerClientOperation._get_peer_connection | def _get_peer_connection(self, blacklist=None):
"""Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try.
"... | python | def _get_peer_connection(self, blacklist=None):
"""Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try.
"... | [
"def",
"_get_peer_connection",
"(",
"self",
",",
"blacklist",
"=",
"None",
")",
":",
"blacklist",
"=",
"blacklist",
"or",
"set",
"(",
")",
"peer",
"=",
"None",
"connection",
"=",
"None",
"while",
"connection",
"is",
"None",
":",
"peer",
"=",
"self",
".",... | Find a peer and connect to it.
Returns a ``(peer, connection)`` tuple.
Raises ``NoAvailablePeerError`` if no healthy peers are found.
:param blacklist:
If given, a set of hostports for peers that we must not try. | [
"Find",
"a",
"peer",
"and",
"connect",
"to",
"it",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L314-L349 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerClientOperation.send | def send(
self, arg1, arg2, arg3,
headers=None,
retry_limit=None,
ttl=None,
):
"""Make a request to the Peer.
:param arg1:
String or Stream containing the contents of arg1. If None, an empty
stream is used.
:param arg2:
Str... | python | def send(
self, arg1, arg2, arg3,
headers=None,
retry_limit=None,
ttl=None,
):
"""Make a request to the Peer.
:param arg1:
String or Stream containing the contents of arg1. If None, an empty
stream is used.
:param arg2:
Str... | [
"def",
"send",
"(",
"self",
",",
"arg1",
",",
"arg2",
",",
"arg3",
",",
"headers",
"=",
"None",
",",
"retry_limit",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
")",
":",
"# find a peer connection",
"# If we can't find available peer at the first time, we throw",
... | Make a request to the Peer.
:param arg1:
String or Stream containing the contents of arg1. If None, an empty
stream is used.
:param arg2:
String or Stream containing the contents of arg2. If None, an empty
stream is used.
:param arg3:
... | [
"Make",
"a",
"request",
"to",
"the",
"Peer",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L352-L442 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup.clear | def clear(self):
"""Reset this PeerGroup.
This closes all connections to all known peers and forgets about
these peers.
:returns:
A Future that resolves with a value of None when the operation
has finished
"""
try:
for peer in self._p... | python | def clear(self):
"""Reset this PeerGroup.
This closes all connections to all known peers and forgets about
these peers.
:returns:
A Future that resolves with a value of None when the operation
has finished
"""
try:
for peer in self._p... | [
"def",
"clear",
"(",
"self",
")",
":",
"try",
":",
"for",
"peer",
"in",
"self",
".",
"_peers",
".",
"values",
"(",
")",
":",
"peer",
".",
"close",
"(",
")",
"finally",
":",
"self",
".",
"_peers",
"=",
"{",
"}",
"self",
".",
"_resetting",
"=",
"... | Reset this PeerGroup.
This closes all connections to all known peers and forgets about
these peers.
:returns:
A Future that resolves with a value of None when the operation
has finished | [
"Reset",
"this",
"PeerGroup",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L592-L607 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup.remove | def remove(self, hostport):
"""Delete the Peer for the given host port.
Does nothing if a matching Peer does not exist.
:returns: The removed Peer
"""
assert hostport, "hostport is required"
peer = self._peers.pop(hostport, None)
peer_in_heap = peer and peer.ind... | python | def remove(self, hostport):
"""Delete the Peer for the given host port.
Does nothing if a matching Peer does not exist.
:returns: The removed Peer
"""
assert hostport, "hostport is required"
peer = self._peers.pop(hostport, None)
peer_in_heap = peer and peer.ind... | [
"def",
"remove",
"(",
"self",
",",
"hostport",
")",
":",
"assert",
"hostport",
",",
"\"hostport is required\"",
"peer",
"=",
"self",
".",
"_peers",
".",
"pop",
"(",
"hostport",
",",
"None",
")",
"peer_in_heap",
"=",
"peer",
"and",
"peer",
".",
"index",
"... | Delete the Peer for the given host port.
Does nothing if a matching Peer does not exist.
:returns: The removed Peer | [
"Delete",
"the",
"Peer",
"for",
"the",
"given",
"host",
"port",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L617-L629 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup.get | def get(self, hostport):
"""Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned.
"""
assert hostport, "hostport is required"
assert... | python | def get(self, hostport):
"""Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned.
"""
assert hostport, "hostport is required"
assert... | [
"def",
"get",
"(",
"self",
",",
"hostport",
")",
":",
"assert",
"hostport",
",",
"\"hostport is required\"",
"assert",
"isinstance",
"(",
"hostport",
",",
"basestring",
")",
",",
"\"hostport must be a string\"",
"if",
"hostport",
"not",
"in",
"self",
".",
"_peer... | Get a Peer for the given destination.
A new Peer is added to the peer heap and returned if one does
not already exist for the given host-port. Otherwise, the
existing Peer is returned. | [
"Get",
"a",
"Peer",
"for",
"the",
"given",
"destination",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L631-L644 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup._add | def _add(self, hostport):
"""Creates a peer from the hostport and adds it to the peer heap"""
peer = self.peer_class(
tchannel=self.tchannel,
hostport=hostport,
on_conn_change=self._update_heap,
)
peer.rank = self.rank_calculator.get_rank(peer)
... | python | def _add(self, hostport):
"""Creates a peer from the hostport and adds it to the peer heap"""
peer = self.peer_class(
tchannel=self.tchannel,
hostport=hostport,
on_conn_change=self._update_heap,
)
peer.rank = self.rank_calculator.get_rank(peer)
... | [
"def",
"_add",
"(",
"self",
",",
"hostport",
")",
":",
"peer",
"=",
"self",
".",
"peer_class",
"(",
"tchannel",
"=",
"self",
".",
"tchannel",
",",
"hostport",
"=",
"hostport",
",",
"on_conn_change",
"=",
"self",
".",
"_update_heap",
",",
")",
"peer",
"... | Creates a peer from the hostport and adds it to the peer heap | [
"Creates",
"a",
"peer",
"from",
"the",
"hostport",
"and",
"adds",
"it",
"to",
"the",
"peer",
"heap"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L646-L656 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup._update_heap | def _update_heap(self, peer):
"""Recalculate the peer's rank and update itself in the peer heap."""
rank = self.rank_calculator.get_rank(peer)
if rank == peer.rank:
return
peer.rank = rank
self.peer_heap.update_peer(peer) | python | def _update_heap(self, peer):
"""Recalculate the peer's rank and update itself in the peer heap."""
rank = self.rank_calculator.get_rank(peer)
if rank == peer.rank:
return
peer.rank = rank
self.peer_heap.update_peer(peer) | [
"def",
"_update_heap",
"(",
"self",
",",
"peer",
")",
":",
"rank",
"=",
"self",
".",
"rank_calculator",
".",
"get_rank",
"(",
"peer",
")",
"if",
"rank",
"==",
"peer",
".",
"rank",
":",
"return",
"peer",
".",
"rank",
"=",
"rank",
"self",
".",
"peer_he... | Recalculate the peer's rank and update itself in the peer heap. | [
"Recalculate",
"the",
"peer",
"s",
"rank",
"and",
"update",
"itself",
"in",
"the",
"peer",
"heap",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L658-L665 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup._get_isolated | def _get_isolated(self, hostport):
"""Get a Peer for the given destination for a request.
A new Peer is added and returned if one does not already exist for the
given host-port. Otherwise, the existing Peer is returned.
**NOTE** new peers will not be added to the peer heap.
"""... | python | def _get_isolated(self, hostport):
"""Get a Peer for the given destination for a request.
A new Peer is added and returned if one does not already exist for the
given host-port. Otherwise, the existing Peer is returned.
**NOTE** new peers will not be added to the peer heap.
"""... | [
"def",
"_get_isolated",
"(",
"self",
",",
"hostport",
")",
":",
"assert",
"hostport",
",",
"\"hostport is required\"",
"if",
"hostport",
"not",
"in",
"self",
".",
"_peers",
":",
"# Add a peer directly from a hostport, do NOT add it to the peer",
"# heap",
"peer",
"=",
... | Get a Peer for the given destination for a request.
A new Peer is added and returned if one does not already exist for the
given host-port. Otherwise, the existing Peer is returned.
**NOTE** new peers will not be added to the peer heap. | [
"Get",
"a",
"Peer",
"for",
"the",
"given",
"destination",
"for",
"a",
"request",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L667-L685 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup.request | def request(self, service, hostport=None, **kwargs):
"""Initiate a new request through this PeerGroup.
:param hostport:
If specified, requests will be sent to the specific host.
Otherwise, a known peer will be picked at random.
:param service:
Name of the ser... | python | def request(self, service, hostport=None, **kwargs):
"""Initiate a new request through this PeerGroup.
:param hostport:
If specified, requests will be sent to the specific host.
Otherwise, a known peer will be picked at random.
:param service:
Name of the ser... | [
"def",
"request",
"(",
"self",
",",
"service",
",",
"hostport",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"PeerClientOperation",
"(",
"peer_group",
"=",
"self",
",",
"service",
"=",
"service",
",",
"hostport",
"=",
"hostport",
",",
"*",
... | Initiate a new request through this PeerGroup.
:param hostport:
If specified, requests will be sent to the specific host.
Otherwise, a known peer will be picked at random.
:param service:
Name of the service being called. Defaults to an empty string. | [
"Initiate",
"a",
"new",
"request",
"through",
"this",
"PeerGroup",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L697-L710 |
uber/tchannel-python | tchannel/tornado/peer.py | PeerGroup.choose | def choose(self, hostport=None, blacklist=None):
"""Choose a Peer that matches the given criteria.
:param hostport:
Specifies that the returned Peer must be for the given host-port.
Without this, all peers managed by this PeerGroup are
candidates.
:param blac... | python | def choose(self, hostport=None, blacklist=None):
"""Choose a Peer that matches the given criteria.
:param hostport:
Specifies that the returned Peer must be for the given host-port.
Without this, all peers managed by this PeerGroup are
candidates.
:param blac... | [
"def",
"choose",
"(",
"self",
",",
"hostport",
"=",
"None",
",",
"blacklist",
"=",
"None",
")",
":",
"blacklist",
"=",
"blacklist",
"or",
"set",
"(",
")",
"if",
"hostport",
":",
"return",
"self",
".",
"_get_isolated",
"(",
"hostport",
")",
"return",
"s... | Choose a Peer that matches the given criteria.
:param hostport:
Specifies that the returned Peer must be for the given host-port.
Without this, all peers managed by this PeerGroup are
candidates.
:param blacklist:
Peers on the blacklist won't be chosen.
... | [
"Choose",
"a",
"Peer",
"that",
"matches",
"the",
"given",
"criteria",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/peer.py#L712-L732 |
uber/tchannel-python | tchannel/_future.py | fail_to | def fail_to(future):
"""A decorator for function callbacks to catch uncaught non-async
exceptions and forward them to the given future.
The primary use for this is to catch exceptions in async callbacks and
propagate them to futures. For example, consider,
.. code-block:: python
answer = ... | python | def fail_to(future):
"""A decorator for function callbacks to catch uncaught non-async
exceptions and forward them to the given future.
The primary use for this is to catch exceptions in async callbacks and
propagate them to futures. For example, consider,
.. code-block:: python
answer = ... | [
"def",
"fail_to",
"(",
"future",
")",
":",
"assert",
"is_future",
"(",
"future",
")",
",",
"'you forgot to pass a future'",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"new_f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
... | A decorator for function callbacks to catch uncaught non-async
exceptions and forward them to the given future.
The primary use for this is to catch exceptions in async callbacks and
propagate them to futures. For example, consider,
.. code-block:: python
answer = Future()
def on_don... | [
"A",
"decorator",
"for",
"function",
"callbacks",
"to",
"catch",
"uncaught",
"non",
"-",
"async",
"exceptions",
"and",
"forward",
"them",
"to",
"the",
"given",
"future",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/_future.py#L31-L78 |
uber/tchannel-python | tchannel/tornado/util.py | get_arg | def get_arg(context, index):
"""get value from arg stream in async way"""
if index < len(context.argstreams):
arg = ""
chunk = yield context.argstreams[index].read()
while chunk:
arg += chunk
chunk = yield context.argstreams[index].read()
raise tornado.ge... | python | def get_arg(context, index):
"""get value from arg stream in async way"""
if index < len(context.argstreams):
arg = ""
chunk = yield context.argstreams[index].read()
while chunk:
arg += chunk
chunk = yield context.argstreams[index].read()
raise tornado.ge... | [
"def",
"get_arg",
"(",
"context",
",",
"index",
")",
":",
"if",
"index",
"<",
"len",
"(",
"context",
".",
"argstreams",
")",
":",
"arg",
"=",
"\"\"",
"chunk",
"=",
"yield",
"context",
".",
"argstreams",
"[",
"index",
"]",
".",
"read",
"(",
")",
"wh... | get value from arg stream in async way | [
"get",
"value",
"from",
"arg",
"stream",
"in",
"async",
"way"
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/tornado/util.py#L30-L41 |
uber/tchannel-python | tchannel/_queue.py | Queue.put | def put(self, value):
"""Puts an item into the queue.
Returns a Future that resolves to None once the value has been
accepted by the queue.
"""
io_loop = IOLoop.current()
new_hole = Future()
new_put = Future()
new_put.set_result(new_hole)
with s... | python | def put(self, value):
"""Puts an item into the queue.
Returns a Future that resolves to None once the value has been
accepted by the queue.
"""
io_loop = IOLoop.current()
new_hole = Future()
new_put = Future()
new_put.set_result(new_hole)
with s... | [
"def",
"put",
"(",
"self",
",",
"value",
")",
":",
"io_loop",
"=",
"IOLoop",
".",
"current",
"(",
")",
"new_hole",
"=",
"Future",
"(",
")",
"new_put",
"=",
"Future",
"(",
")",
"new_put",
".",
"set_result",
"(",
"new_hole",
")",
"with",
"self",
".",
... | Puts an item into the queue.
Returns a Future that resolves to None once the value has been
accepted by the queue. | [
"Puts",
"an",
"item",
"into",
"the",
"queue",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/_queue.py#L107-L133 |
uber/tchannel-python | tchannel/_queue.py | Queue.get_nowait | def get_nowait(self):
"""Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now.
"""
new_get = Future()
with self._lock:
if not self._get.done():
raise QueueEmpty
get, self._get = self._... | python | def get_nowait(self):
"""Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now.
"""
new_get = Future()
with self._lock:
if not self._get.done():
raise QueueEmpty
get, self._get = self._... | [
"def",
"get_nowait",
"(",
"self",
")",
":",
"new_get",
"=",
"Future",
"(",
")",
"with",
"self",
".",
"_lock",
":",
"if",
"not",
"self",
".",
"_get",
".",
"done",
"(",
")",
":",
"raise",
"QueueEmpty",
"get",
",",
"self",
".",
"_get",
"=",
"self",
... | Returns a value from the queue without waiting.
Raises ``QueueEmpty`` if no values are available right now. | [
"Returns",
"a",
"value",
"from",
"the",
"queue",
"without",
"waiting",
"."
] | train | https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/_queue.py#L135-L157 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.