Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
test_gradient_clipping
(tmpdir)
Test gradient clipping
Test gradient clipping
def test_gradient_clipping(tmpdir): """ Test gradient clipping """ tutils.reset_seed() model = EvalModelTemplate() trainer = Trainer( max_steps=1, max_epochs=1, gradient_clip_val=1.0, default_root_dir=tmpdir, ) trainer.train_loop.old_training_step_and_b...
[ "def", "test_gradient_clipping", "(", "tmpdir", ")", ":", "tutils", ".", "reset_seed", "(", ")", "model", "=", "EvalModelTemplate", "(", ")", "trainer", "=", "Trainer", "(", "max_steps", "=", "1", ",", "max_epochs", "=", "1", ",", "gradient_clip_val", "=", ...
[ 958, 0 ]
[ 991, 22 ]
python
en
['en', 'error', 'th']
False
test_gradient_clipping_fp16
(tmpdir)
Test gradient clipping with fp16
Test gradient clipping with fp16
def test_gradient_clipping_fp16(tmpdir): """ Test gradient clipping with fp16 """ tutils.reset_seed() model = EvalModelTemplate() trainer = Trainer( max_steps=1, max_epochs=1, precision=16, gpus=1, gradient_clip_val=1.0, default_root_dir=tmpdir, ...
[ "def", "test_gradient_clipping_fp16", "(", "tmpdir", ")", ":", "tutils", ".", "reset_seed", "(", ")", "model", "=", "EvalModelTemplate", "(", ")", "trainer", "=", "Trainer", "(", "max_steps", "=", "1", ",", "max_epochs", "=", "1", ",", "precision", "=", "1...
[ 996, 0 ]
[ 1030, 22 ]
python
en
['en', 'error', 'th']
False
test_num_sanity_val_steps
(tmpdir, limit_val_batches)
Test that the number of sanity check batches is clipped to `limit_val_batches`.
Test that the number of sanity check batches is clipped to `limit_val_batches`.
def test_num_sanity_val_steps(tmpdir, limit_val_batches): """ Test that the number of sanity check batches is clipped to `limit_val_batches`. """ model = EvalModelTemplate() model.validation_step = model.validation_step__multiple_dataloaders model.validation_epoch_end = model.validation_epoch_en...
[ "def", "test_num_sanity_val_steps", "(", "tmpdir", ",", "limit_val_batches", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "model", ".", "validation_step", "=", "model", ".", "validation_step__multiple_dataloaders", "model", ".", "validation_epoch_end", "=", ...
[ 1056, 0 ]
[ 1081, 9 ]
python
en
['en', 'error', 'th']
False
test_num_sanity_val_steps_neg_one
(tmpdir, limit_val_batches)
Test that `num_sanity_val_steps=-1` runs through all validation data once, and as many batches as limited by `limit_val_batches` Trainer argument.
Test that `num_sanity_val_steps=-1` runs through all validation data once, and as many batches as limited by `limit_val_batches` Trainer argument.
def test_num_sanity_val_steps_neg_one(tmpdir, limit_val_batches): """ Test that `num_sanity_val_steps=-1` runs through all validation data once, and as many batches as limited by `limit_val_batches` Trainer argument. """ model = EvalModelTemplate() model.validation_step = model.validation_step__...
[ "def", "test_num_sanity_val_steps_neg_one", "(", "tmpdir", ",", "limit_val_batches", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "model", ".", "validation_step", "=", "model", ".", "validation_step__multiple_dataloaders", "model", ".", "validation_epoch_end", ...
[ 1093, 0 ]
[ 1115, 64 ]
python
en
['en', 'error', 'th']
False
test_trainer_setup_call
(tmpdir)
Test setup call with fit and test call.
Test setup call with fit and test call.
def test_trainer_setup_call(tmpdir): """Test setup call with fit and test call.""" class CurrentModel(EvalModelTemplate): def setup(self, stage): self.stage = stage class TrainerSubclass(Trainer): def setup(self, model, stage): assert model is not None ...
[ "def", "test_trainer_setup_call", "(", "tmpdir", ")", ":", "class", "CurrentModel", "(", "EvalModelTemplate", ")", ":", "def", "setup", "(", "self", ",", "stage", ")", ":", "self", ".", "stage", "=", "stage", "class", "TrainerSubclass", "(", "Trainer", ")", ...
[ 1402, 0 ]
[ 1427, 51 ]
python
en
['en', 'en', 'en']
True
test_pytorch_profiler_describe
(pytorch_profiler)
Ensure the profiler won't fail when reporting the summary.
Ensure the profiler won't fail when reporting the summary.
def test_pytorch_profiler_describe(pytorch_profiler): """Ensure the profiler won't fail when reporting the summary.""" with pytorch_profiler.profile("test_step"): pass # log to stdout and print to file pytorch_profiler.describe() data = Path(pytorch_profiler.output_fname).read_text() as...
[ "def", "test_pytorch_profiler_describe", "(", "pytorch_profiler", ")", ":", "with", "pytorch_profiler", ".", "profile", "(", "\"test_step\"", ")", ":", "pass", "# log to stdout and print to file", "pytorch_profiler", ".", "describe", "(", ")", "data", "=", "Path", "("...
[ 1579, 0 ]
[ 1587, 24 ]
python
en
['en', 'en', 'en']
True
test_pytorch_profiler_value_errors
(pytorch_profiler)
Ensure errors are raised where expected.
Ensure errors are raised where expected.
def test_pytorch_profiler_value_errors(pytorch_profiler): """Ensure errors are raised where expected.""" action = "test_step" with pytest.raises(ValueError): pytorch_profiler.stop(action) pytorch_profiler.start(action) pytorch_profiler.stop(action)
[ "def", "test_pytorch_profiler_value_errors", "(", "pytorch_profiler", ")", ":", "action", "=", "\"test_step\"", "with", "pytest", ".", "raises", "(", "ValueError", ")", ":", "pytorch_profiler", ".", "stop", "(", "action", ")", "pytorch_profiler", ".", "start", "("...
[ 1590, 0 ]
[ 1598, 33 ]
python
en
['en', 'en', 'en']
True
test_pytorch_profiler_trainer_ddp
(tmpdir, use_output_filename)
Ensure that the profiler can be given to the training and default step are properly recorded.
Ensure that the profiler can be given to the training and default step are properly recorded.
def test_pytorch_profiler_trainer_ddp(tmpdir, use_output_filename): """Ensure that the profiler can be given to the training and default step are properly recorded. """ if use_output_filename: output_filename = os.path.join(tmpdir, "profiler.txt") else: output_filename = None profiler ...
[ "def", "test_pytorch_profiler_trainer_ddp", "(", "tmpdir", ",", "use_output_filename", ")", ":", "if", "use_output_filename", ":", "output_filename", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "\"profiler.txt\"", ")", "else", ":", "output_filename", ...
[ 1606, 0 ]
[ 1637, 28 ]
python
en
['en', 'en', 'en']
True
test_pytorch_profiler_nested
(tmpdir)
Ensure that the profiler handles nested context
Ensure that the profiler handles nested context
def test_pytorch_profiler_nested(tmpdir): """Ensure that the profiler handles nested context""" pytorch_profiler = PyTorchProfiler( profiled_functions=["a", "b", "c"], use_cuda=False, output_filename=os.path.join(tmpdir, "profiler.txt") ) with pytorch_profiler.profile("a"): a = torch.o...
[ "def", "test_pytorch_profiler_nested", "(", "tmpdir", ")", ":", "pytorch_profiler", "=", "PyTorchProfiler", "(", "profiled_functions", "=", "[", "\"a\"", ",", "\"b\"", ",", "\"c\"", "]", ",", "use_cuda", "=", "False", ",", "output_filename", "=", "os", ".", "p...
[ 1640, 0 ]
[ 1681, 36 ]
python
en
['en', 'en', 'en']
True
test_disabled_training_for_insufficient_limit_train_batches
( tmpdir, limit_train_batches, global_step, num_training_batches, current_epoch, should_train )
Verify when `limit_train_batches` is float & between [0.0, 1.0] and `int(self.num_training_batches * self.limit_train_batches) == 0`, the training loop is disabled.
Verify when `limit_train_batches` is float & between [0.0, 1.0] and `int(self.num_training_batches * self.limit_train_batches) == 0`, the training loop is disabled.
def test_disabled_training_for_insufficient_limit_train_batches( tmpdir, limit_train_batches, global_step, num_training_batches, current_epoch, should_train ): """ Verify when `limit_train_batches` is float & between [0.0, 1.0] and `int(self.num_training_batches * self.limit_train_batches) == 0`, the tr...
[ "def", "test_disabled_training_for_insufficient_limit_train_batches", "(", "tmpdir", ",", "limit_train_batches", ",", "global_step", ",", "num_training_batches", ",", "current_epoch", ",", "should_train", ")", ":", "class", "CurrentModel", "(", "BoringModel", ")", ":", "t...
[ 1688, 0 ]
[ 1738, 99 ]
python
en
['en', 'error', 'th']
False
test_repeated_fit_calls_with_max_epochs_and_steps
(tmpdir, max_steps, max_epochs, global_step)
Ensure that the training loop is bound by `max_steps` and `max_epochs` for repeated calls of `trainer.fit`, and disabled if the limit is reached
Ensure that the training loop is bound by `max_steps` and `max_epochs` for repeated calls of `trainer.fit`, and disabled if the limit is reached
def test_repeated_fit_calls_with_max_epochs_and_steps(tmpdir, max_steps, max_epochs, global_step): """ Ensure that the training loop is bound by `max_steps` and `max_epochs` for repeated calls of `trainer.fit`, and disabled if the limit is reached """ dataset_len = 200 batch_size = 10 ...
[ "def", "test_repeated_fit_calls_with_max_epochs_and_steps", "(", "tmpdir", ",", "max_steps", ",", "max_epochs", ",", "global_step", ")", ":", "dataset_len", "=", "200", "batch_size", "=", "10", "train_data", "=", "DataLoader", "(", "RandomDataset", "(", "32", ",", ...
[ 1742, 0 ]
[ 1764, 45 ]
python
en
['en', 'error', 'th']
False
test_trainer_access_in_configure_optimizers
(tmpdir)
Verify that the configure optimizer function can reference the trainer.
Verify that the configure optimizer function can reference the trainer.
def test_trainer_access_in_configure_optimizers(tmpdir): """ Verify that the configure optimizer function can reference the trainer. """ class TestModel(BoringModel): def configure_optimizers(self): assert self.trainer is not None, "Expect to have access to the trainer within `conf...
[ "def", "test_trainer_access_in_configure_optimizers", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "configure_optimizers", "(", "self", ")", ":", "assert", "self", ".", "trainer", "is", "not", "None", ",", "\"Expect to have a...
[ 1767, 0 ]
[ 1781, 34 ]
python
en
['en', 'error', 'th']
False
test_setup_hook_move_to_device_correctly
(tmpdir)
Verify that if a user defines a layer in the setup hook function, this is moved to the correct device.
Verify that if a user defines a layer in the setup hook function, this is moved to the correct device.
def test_setup_hook_move_to_device_correctly(tmpdir): """ Verify that if a user defines a layer in the setup hook function, this is moved to the correct device. """ class TestModel(BoringModel): def setup(self, stage: str) -> None: self.new_layer = torch.nn.Linear(2, 2) de...
[ "def", "test_setup_hook_move_to_device_correctly", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "setup", "(", "self", ",", "stage", ":", "str", ")", "->", "None", ":", "self", ".", "new_layer", "=", "torch", ".", "nn"...
[ 1785, 0 ]
[ 1808, 34 ]
python
en
['en', 'error', 'th']
False
binaryToDecimal
(binary)
>>> binaryToDecimal(111110000) 496 >>> binaryToDecimal(10100) 20 >>> binaryToDecimal(101011) 43
>>> binaryToDecimal(111110000) 496 >>> binaryToDecimal(10100) 20 >>> binaryToDecimal(101011) 43
def binaryToDecimal(binary): """ >>> binaryToDecimal(111110000) 496 >>> binaryToDecimal(10100) 20 >>> binaryToDecimal(101011) 43 """ decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary % 10 decimal = decimal + dec * pow(2, i) binary = binary//10 i += 1 print(decimal)
[ "def", "binaryToDecimal", "(", "binary", ")", ":", "decimal", ",", "i", ",", "n", "=", "0", ",", "0", ",", "0", "while", "(", "binary", "!=", "0", ")", ":", "dec", "=", "binary", "%", "10", "decimal", "=", "decimal", "+", "dec", "*", "pow", "("...
[ 2, 0 ]
[ 17, 15 ]
python
en
['en', 'error', 'th']
False
PrecisionPlugin.master_params
(self, optimizer: Optimizer)
The master params of the model. Returns the plain model params here. Maybe different in other precision plugins.
The master params of the model. Returns the plain model params here. Maybe different in other precision plugins.
def master_params(self, optimizer: Optimizer) -> Generator[torch.Tensor, None, None]: """The master params of the model. Returns the plain model params here. Maybe different in other precision plugins. """ for group in optimizer.param_groups: for p in group["params"]: ...
[ "def", "master_params", "(", "self", ",", "optimizer", ":", "Optimizer", ")", "->", "Generator", "[", "torch", ".", "Tensor", ",", "None", ",", "None", "]", ":", "for", "group", "in", "optimizer", ".", "param_groups", ":", "for", "p", "in", "group", "[...
[ 32, 4 ]
[ 39, 23 ]
python
en
['en', 'en', 'en']
True
PrecisionPlugin.connect
(self, model: Module, optimizers: Sequence, lr_schedulers: Sequence)
Connects this plugin to the accelerator and the training process
Connects this plugin to the accelerator and the training process
def connect(self, model: Module, optimizers: Sequence, lr_schedulers: Sequence) -> Tuple[Module, Sequence, Sequence]: """Connects this plugin to the accelerator and the training process""" return model, optimizers, lr_schedulers
[ "def", "connect", "(", "self", ",", "model", ":", "Module", ",", "optimizers", ":", "Sequence", ",", "lr_schedulers", ":", "Sequence", ")", "->", "Tuple", "[", "Module", ",", "Sequence", ",", "Sequence", "]", ":", "return", "model", ",", "optimizers", ",...
[ 41, 4 ]
[ 44, 47 ]
python
en
['en', 'en', 'en']
True
PrecisionPlugin.backward
( self, model: LightningModule, closure_loss: torch.Tensor, optimizer: Optimizer, opt_idx: int, should_accumulate: bool, *args: Any, **kwargs: Any, )
performs the actual backpropagation Args: model: the model to be optimized closure_loss: the loss value obtained from the closure optimizer: the optimizer to perform the step lateron opt_idx: the optimizer's index should_accumulate: whether to accumul...
performs the actual backpropagation
def backward( self, model: LightningModule, closure_loss: torch.Tensor, optimizer: Optimizer, opt_idx: int, should_accumulate: bool, *args: Any, **kwargs: Any, ) -> torch.Tensor: """performs the actual backpropagation Args: ...
[ "def", "backward", "(", "self", ",", "model", ":", "LightningModule", ",", "closure_loss", ":", "torch", ".", "Tensor", ",", "optimizer", ":", "Optimizer", ",", "opt_idx", ":", "int", ",", "should_accumulate", ":", "bool", ",", "*", "args", ":", "Any", "...
[ 46, 4 ]
[ 77, 27 ]
python
en
['en', 'en', 'en']
True
PrecisionPlugin.pre_optimizer_step
( self, pl_module: LightningModule, optimizer: Optimizer, optimizer_idx: int, closure: Callable, **kwargs )
Hook to do something before each optimizer step.
Hook to do something before each optimizer step.
def pre_optimizer_step( self, pl_module: LightningModule, optimizer: Optimizer, optimizer_idx: int, closure: Callable, **kwargs ) -> bool: """Hook to do something before each optimizer step.""" return True
[ "def", "pre_optimizer_step", "(", "self", ",", "pl_module", ":", "LightningModule", ",", "optimizer", ":", "Optimizer", ",", "optimizer_idx", ":", "int", ",", "closure", ":", "Callable", ",", "*", "*", "kwargs", ")", "->", "bool", ":", "return", "True" ]
[ 79, 4 ]
[ 83, 19 ]
python
en
['en', 'en', 'en']
True
PrecisionPlugin.post_optimizer_step
(self, optimizer: Optimizer, optimizer_idx: int)
Hook to do something after each optimizer step.
Hook to do something after each optimizer step.
def post_optimizer_step(self, optimizer: Optimizer, optimizer_idx: int) -> None: """Hook to do something after each optimizer step."""
[ "def", "post_optimizer_step", "(", "self", ",", "optimizer", ":", "Optimizer", ",", "optimizer_idx", ":", "int", ")", "->", "None", ":" ]
[ 85, 4 ]
[ 86, 61 ]
python
en
['en', 'en', 'en']
True
PrecisionPlugin.clip_gradients
(self, optimizer: Optimizer, clip_val: Union[int, float], norm_type: float = float(2.0))
Clips the gradients to a specific value
Clips the gradients to a specific value
def clip_gradients(self, optimizer: Optimizer, clip_val: Union[int, float], norm_type: float = float(2.0)) -> None: """Clips the gradients to a specific value""" # TODO: separate TPU case from here if clip_val is None: return grad_clip_val = float(clip_val) if grad_...
[ "def", "clip_gradients", "(", "self", ",", "optimizer", ":", "Optimizer", ",", "clip_val", ":", "Union", "[", "int", ",", "float", "]", ",", "norm_type", ":", "float", "=", "float", "(", "2.0", ")", ")", "->", "None", ":", "# TODO: separate TPU case from h...
[ 88, 4 ]
[ 122, 62 ]
python
en
['en', 'en', 'en']
True
ImageNetLightningModel.__accuracy
(output, target, topk=(1, ))
Computes the accuracy over the k top predictions for the specified values of k
Computes the accuracy over the k top predictions for the specified values of k
def __accuracy(output, target, topk=(1, )): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() ...
[ "def", "__accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "with", "torch", ".", "no_grad", "(", ")", ":", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_...
[ 111, 4 ]
[ 125, 22 ]
python
en
['en', 'en', 'en']
True
term_all_children
()
Iterate through all known child processes, send a TERM signal to each of them, and then wait up to TERM_WAIT_SECONDS for them to exit gracefully, exiting early if all children go away. If one or more children have not exited after TERM_WAIT_SECONDS, they will be forcibly killed
Iterate through all known child processes, send a TERM signal to each of them, and then wait up to TERM_WAIT_SECONDS for them to exit gracefully, exiting early if all children go away. If one or more children have not exited after TERM_WAIT_SECONDS, they will be forcibly killed
def term_all_children(): """ Iterate through all known child processes, send a TERM signal to each of them, and then wait up to TERM_WAIT_SECONDS for them to exit gracefully, exiting early if all children go away. If one or more children have not exited after TERM_WAIT_SECONDS, they will be forcibly killed ""...
[ "def", "term_all_children", "(", ")", ":", "# First uninstall the SIGCHLD handler so that we don't get called again.", "signal", ".", "signal", "(", "signal", ".", "SIGCHLD", ",", "signal", ".", "SIG_DFL", ")", "global", "pid_list", "for", "pid", "in", "pid_list", ":"...
[ 19, 0 ]
[ 61, 19 ]
python
en
['en', 'en', 'en']
True
force_kill_all_children
()
Iterate through all known child processes and force kill them. Typically term_all_children() should be attempted first to give child processes an opportunity to clean up state before exiting
Iterate through all known child processes and force kill them. Typically term_all_children() should be attempted first to give child processes an opportunity to clean up state before exiting
def force_kill_all_children(): """ Iterate through all known child processes and force kill them. Typically term_all_children() should be attempted first to give child processes an opportunity to clean up state before exiting """ global pid_list for pid in pid_list: print("force killing PID={}"...
[ "def", "force_kill_all_children", "(", ")", ":", "global", "pid_list", "for", "pid", "in", "pid_list", ":", "print", "(", "\"force killing PID={}\"", ".", "format", "(", "pid", ")", ")", "try", ":", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIG...
[ 64, 0 ]
[ 77, 17 ]
python
en
['en', 'en', 'en']
True
shutdown
()
Attempt to gracefully shutdown all child Envoy processes and then exit. See term_all_children() for further discussion.
Attempt to gracefully shutdown all child Envoy processes and then exit. See term_all_children() for further discussion.
def shutdown(): """ Attempt to gracefully shutdown all child Envoy processes and then exit. See term_all_children() for further discussion. """ term_all_children() sys.exit(0)
[ "def", "shutdown", "(", ")", ":", "term_all_children", "(", ")", "sys", ".", "exit", "(", "0", ")" ]
[ 80, 0 ]
[ 84, 15 ]
python
en
['en', 'en', 'en']
True
sigterm_handler
(signum, frame)
Handler for SIGTERM.
Handler for SIGTERM.
def sigterm_handler(signum, frame): """ Handler for SIGTERM. """ print("got SIGTERM") shutdown()
[ "def", "sigterm_handler", "(", "signum", ",", "frame", ")", ":", "print", "(", "\"got SIGTERM\"", ")", "shutdown", "(", ")" ]
[ 87, 0 ]
[ 90, 14 ]
python
da
['da', 'da', 'en']
True
sigint_handler
(signum, frame)
Handler for SIGINT (ctrl-c). The same as the SIGTERM handler.
Handler for SIGINT (ctrl-c). The same as the SIGTERM handler.
def sigint_handler(signum, frame): """ Handler for SIGINT (ctrl-c). The same as the SIGTERM handler. """ print("got SIGINT") shutdown()
[ "def", "sigint_handler", "(", "signum", ",", "frame", ")", ":", "print", "(", "\"got SIGINT\"", ")", "shutdown", "(", ")" ]
[ 93, 0 ]
[ 96, 14 ]
python
en
['en', 'en', 'en']
True
sighup_handler
(signum, frame)
Handler for SIGHUP. This signal is used to cause the restarter to fork and exec a new child.
Handler for SIGHUP. This signal is used to cause the restarter to fork and exec a new child.
def sighup_handler(signum, frame): """ Handler for SIGHUP. This signal is used to cause the restarter to fork and exec a new child. """ print("got SIGHUP") fork_and_exec()
[ "def", "sighup_handler", "(", "signum", ",", "frame", ")", ":", "print", "(", "\"got SIGHUP\"", ")", "fork_and_exec", "(", ")" ]
[ 99, 0 ]
[ 104, 19 ]
python
en
['en', 'en', 'en']
True
sigusr1_handler
(signum, frame)
Handler for SIGUSR1. Propagate SIGUSR1 to all of the child processes
Handler for SIGUSR1. Propagate SIGUSR1 to all of the child processes
def sigusr1_handler(signum, frame): """ Handler for SIGUSR1. Propagate SIGUSR1 to all of the child processes """ global pid_list for pid in pid_list: print("sending SIGUSR1 to PID={}".format(pid)) try: os.kill(pid, signal.SIGUSR1) except OSError: print("error...
[ "def", "sigusr1_handler", "(", "signum", ",", "frame", ")", ":", "global", "pid_list", "for", "pid", "in", "pid_list", ":", "print", "(", "\"sending SIGUSR1 to PID={}\"", ".", "format", "(", "pid", ")", ")", "try", ":", "os", ".", "kill", "(", "pid", ","...
[ 107, 0 ]
[ 116, 70 ]
python
en
['en', 'en', 'en']
True
sigchld_handler
(signum, frame)
Handler for SIGCHLD. Iterates through all of our known child processes and figures out whether the signal/exit was expected or not. Python doesn't have any of the native signal handlers ability to get the child process info directly from the signal handler so we need to iterate through all child proc...
Handler for SIGCHLD. Iterates through all of our known child processes and figures out whether the signal/exit was expected or not. Python doesn't have any of the native signal handlers ability to get the child process info directly from the signal handler so we need to iterate through all child proc...
def sigchld_handler(signum, frame): """ Handler for SIGCHLD. Iterates through all of our known child processes and figures out whether the signal/exit was expected or not. Python doesn't have any of the native signal handlers ability to get the child process info directly from the signal handler so we n...
[ "def", "sigchld_handler", "(", "signum", ",", "frame", ")", ":", "print", "(", "\"got SIGCHLD\"", ")", "kill_all_and_exit", "=", "False", "global", "pid_list", "pid_list_copy", "=", "list", "(", "pid_list", ")", "for", "pid", "in", "pid_list_copy", ":", "ret_p...
[ 119, 0 ]
[ 166, 47 ]
python
en
['en', 'en', 'en']
True
fork_and_exec
()
This routine forks and execs a new child process and keeps track of its PID. Before we fork, set the current restart epoch in an env variable that processes can read if they care.
This routine forks and execs a new child process and keeps track of its PID. Before we fork, set the current restart epoch in an env variable that processes can read if they care.
def fork_and_exec(): """ This routine forks and execs a new child process and keeps track of its PID. Before we fork, set the current restart epoch in an env variable that processes can read if they care. """ global restart_epoch os.environ['RESTART_EPOCH'] = str(restart_epoch) print("forking and...
[ "def", "fork_and_exec", "(", ")", ":", "global", "restart_epoch", "os", ".", "environ", "[", "'RESTART_EPOCH'", "]", "=", "str", "(", "restart_epoch", ")", "print", "(", "\"forking and execing new child process at epoch {}\"", ".", "format", "(", "restart_epoch", ")...
[ 169, 0 ]
[ 185, 34 ]
python
en
['en', 'en', 'en']
True
main
()
Script main. This script is designed so that a process watcher like runit or monit can watch this process and take corrective action if it ever goes away.
Script main. This script is designed so that a process watcher like runit or monit can watch this process and take corrective action if it ever goes away.
def main(): """ Script main. This script is designed so that a process watcher like runit or monit can watch this process and take corrective action if it ever goes away. """ print("starting hot-restarter with target: {}".format(sys.argv[1])) signal.signal(signal.SIGTERM, sigterm_handler) signal...
[ "def", "main", "(", ")", ":", "print", "(", "\"starting hot-restarter with target: {}\"", ".", "format", "(", "sys", ".", "argv", "[", "1", "]", ")", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "sigterm_handler", ")", "signal", ".", ...
[ 188, 0 ]
[ 204, 22 ]
python
en
['en', 'en', 'en']
True
test_optimizer_with_scheduling
(tmpdir)
Verify that learning rate scheduling is working
Verify that learning rate scheduling is working
def test_optimizer_with_scheduling(tmpdir): """ Verify that learning rate scheduling is working """ hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) model.configure_optimizers = model.configure_optimizers__single_scheduler # fit model trainer = Trainer( ...
[ "def", "test_optimizer_with_scheduling", "(", "tmpdir", ")", ":", "hparams", "=", "EvalModelTemplate", ".", "get_default_hparams", "(", ")", "model", "=", "EvalModelTemplate", "(", "*", "*", "hparams", ")", "model", ".", "configure_optimizers", "=", "model", ".", ...
[ 23, 0 ]
[ 52, 90 ]
python
en
['en', 'en', 'en']
True
test_multi_optimizer_with_scheduling
(tmpdir)
Verify that learning rate scheduling is working
Verify that learning rate scheduling is working
def test_multi_optimizer_with_scheduling(tmpdir): """ Verify that learning rate scheduling is working """ hparams = EvalModelTemplate.get_default_hparams() model = EvalModelTemplate(**hparams) model.configure_optimizers = model.configure_optimizers__multiple_schedulers # fit model trainer = Tr...
[ "def", "test_multi_optimizer_with_scheduling", "(", "tmpdir", ")", ":", "hparams", "=", "EvalModelTemplate", ".", "get_default_hparams", "(", ")", "model", "=", "EvalModelTemplate", "(", "*", "*", "hparams", ")", "model", ".", "configure_optimizers", "=", "model", ...
[ 55, 0 ]
[ 88, 91 ]
python
en
['en', 'en', 'en']
True
test_reducelronplateau_with_no_monitor_raises
(tmpdir)
Test exception when a ReduceLROnPlateau is used with no monitor
Test exception when a ReduceLROnPlateau is used with no monitor
def test_reducelronplateau_with_no_monitor_raises(tmpdir): """ Test exception when a ReduceLROnPlateau is used with no monitor """ model = EvalModelTemplate() optimizer = torch.optim.Adam(model.parameters()) model.configure_optimizers = lambda: ([optimizer], [torch.optim.lr_scheduler.ReduceLROnP...
[ "def", "test_reducelronplateau_with_no_monitor_raises", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "optimizer", "=", "torch", ".", "optim", ".", "Adam", "(", "model", ".", "parameters", "(", ")", ")", "model", ".", "configure_optimizer...
[ 130, 0 ]
[ 141, 26 ]
python
en
['en', 'error', 'th']
False
test_reducelronplateau_with_no_monitor_in_lr_scheduler_dict_raises
(tmpdir)
Test exception when lr_scheduler dict has a ReduceLROnPlateau with no monitor
Test exception when lr_scheduler dict has a ReduceLROnPlateau with no monitor
def test_reducelronplateau_with_no_monitor_in_lr_scheduler_dict_raises(tmpdir): """ Test exception when lr_scheduler dict has a ReduceLROnPlateau with no monitor """ model = EvalModelTemplate() optimizer = torch.optim.Adam(model.parameters()) model.configure_optimizers = lambda: { 'optim...
[ "def", "test_reducelronplateau_with_no_monitor_in_lr_scheduler_dict_raises", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "optimizer", "=", "torch", ".", "optim", ".", "Adam", "(", "model", ".", "parameters", "(", ")", ")", "model", ".", ...
[ 144, 0 ]
[ 158, 26 ]
python
en
['en', 'error', 'th']
False
test_configure_optimizer_from_dict
(tmpdir)
Tests if `configure_optimizer` method could return a dictionary with `optimizer` field only.
Tests if `configure_optimizer` method could return a dictionary with `optimizer` field only.
def test_configure_optimizer_from_dict(tmpdir): """Tests if `configure_optimizer` method could return a dictionary with `optimizer` field only.""" class CurrentModel(EvalModelTemplate): def configure_optimizers(self): config = {'optimizer': torch.optim.SGD(params=self.parameters(), lr=1e-0...
[ "def", "test_configure_optimizer_from_dict", "(", "tmpdir", ")", ":", "class", "CurrentModel", "(", "EvalModelTemplate", ")", ":", "def", "configure_optimizers", "(", "self", ")", ":", "config", "=", "{", "'optimizer'", ":", "torch", ".", "optim", ".", "SGD", ...
[ 317, 0 ]
[ 335, 90 ]
python
en
['en', 'en', 'en']
True
test_configure_optimizers_with_frequency
(tmpdir)
Test that multiple optimizers work when corresponding frequency is set.
Test that multiple optimizers work when corresponding frequency is set.
def test_configure_optimizers_with_frequency(tmpdir): """ Test that multiple optimizers work when corresponding frequency is set. """ model = EvalModelTemplate() model.configure_optimizers = model.configure_optimizers__multiple_optimizers_frequency trainer = Trainer(default_root_dir=tmpdir, max...
[ "def", "test_configure_optimizers_with_frequency", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "model", ".", "configure_optimizers", "=", "model", ".", "configure_optimizers__multiple_optimizers_frequency", "trainer", "=", "Trainer", "(", "defaul...
[ 338, 0 ]
[ 347, 90 ]
python
en
['en', 'error', 'th']
False
test_init_optimizers_during_testing
(tmpdir)
Test that optimizers is an empty list during testing.
Test that optimizers is an empty list during testing.
def test_init_optimizers_during_testing(tmpdir): """ Test that optimizers is an empty list during testing. """ model = EvalModelTemplate() model.configure_optimizers = model.configure_optimizers__multiple_schedulers trainer = Trainer(default_root_dir=tmpdir, limit_test_batches=10) trainer.t...
[ "def", "test_init_optimizers_during_testing", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "model", ".", "configure_optimizers", "=", "model", ".", "configure_optimizers__multiple_schedulers", "trainer", "=", "Trainer", "(", "default_root_dir", ...
[ 350, 0 ]
[ 362, 50 ]
python
en
['en', 'error', 'th']
False
test_multiple_optimizers_callbacks
(tmpdir)
Tests that multiple optimizers can be used with callbacks
Tests that multiple optimizers can be used with callbacks
def test_multiple_optimizers_callbacks(tmpdir): """ Tests that multiple optimizers can be used with callbacks """ class CB(Callback): def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): pass def on_train_epoch_start(self, trainer, p...
[ "def", "test_multiple_optimizers_callbacks", "(", "tmpdir", ")", ":", "class", "CB", "(", "Callback", ")", ":", "def", "on_train_batch_end", "(", "self", ",", "trainer", ",", "pl_module", ",", "outputs", ",", "batch", ",", "batch_idx", ",", "dataloader_idx", "...
[ 365, 0 ]
[ 411, 22 ]
python
en
['en', 'error', 'th']
False
test_lr_scheduler_strict
(tmpdir)
Test "strict" support in lr_scheduler dict
Test "strict" support in lr_scheduler dict
def test_lr_scheduler_strict(tmpdir): """ Test "strict" support in lr_scheduler dict """ model = EvalModelTemplate() optimizer = torch.optim.Adam(model.parameters()) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer) trainer = Trainer(default_root_dir=tmpdir, max_epochs=1) ...
[ "def", "test_lr_scheduler_strict", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "optimizer", "=", "torch", ".", "optim", ".", "Adam", "(", "model", ".", "parameters", "(", ")", ")", "scheduler", "=", "torch", ".", "optim", ".", "...
[ 414, 0 ]
[ 448, 33 ]
python
en
['en', 'error', 'th']
False
test_unknown_configure_optimizers_raises
(tmpdir)
Test exception with an unsupported configure_optimizers return
Test exception with an unsupported configure_optimizers return
def test_unknown_configure_optimizers_raises(tmpdir): """ Test exception with an unsupported configure_optimizers return """ model = EvalModelTemplate() model.configure_optimizers = lambda: 1 trainer = Trainer(default_root_dir=tmpdir, fast_dev_run=True) with pytest.raises(MisconfigurationExc...
[ "def", "test_unknown_configure_optimizers_raises", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "model", ".", "configure_optimizers", "=", "lambda", ":", "1", "trainer", "=", "Trainer", "(", "default_root_dir", "=", "tmpdir", ",", "fast_de...
[ 451, 0 ]
[ 459, 26 ]
python
en
['en', 'error', 'th']
False
test_lr_scheduler_with_unknown_interval_raises
(tmpdir)
Test exception when lr_scheduler dict has unknown interval param value
Test exception when lr_scheduler dict has unknown interval param value
def test_lr_scheduler_with_unknown_interval_raises(tmpdir): """ Test exception when lr_scheduler dict has unknown interval param value """ model = BoringModel() optimizer = torch.optim.Adam(model.parameters()) model.configure_optimizers = lambda: { 'optimizer': optimizer, 'lr_sch...
[ "def", "test_lr_scheduler_with_unknown_interval_raises", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "optimizer", "=", "torch", ".", "optim", ".", "Adam", "(", "model", ".", "parameters", "(", ")", ")", "model", ".", "configure_optimizers", ...
[ 462, 0 ]
[ 477, 26 ]
python
en
['en', 'error', 'th']
False
test_lr_scheduler_with_extra_keys_warns
(tmpdir)
Test warning when lr_scheduler dict has extra keys
Test warning when lr_scheduler dict has extra keys
def test_lr_scheduler_with_extra_keys_warns(tmpdir): """ Test warning when lr_scheduler dict has extra keys """ model = EvalModelTemplate() optimizer = torch.optim.Adam(model.parameters()) model.configure_optimizers = lambda: { 'optimizer': optimizer, 'lr_scheduler': { ...
[ "def", "test_lr_scheduler_with_extra_keys_warns", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "optimizer", "=", "torch", ".", "optim", ".", "Adam", "(", "model", ".", "parameters", "(", ")", ")", "model", ".", "configure_optimizers", ...
[ 480, 0 ]
[ 496, 26 ]
python
en
['en', 'error', 'th']
False
test_lr_scheduler_with_no_actual_scheduler_raises
(tmpdir)
Test exception when lr_scheduler dict has no scheduler
Test exception when lr_scheduler dict has no scheduler
def test_lr_scheduler_with_no_actual_scheduler_raises(tmpdir): """ Test exception when lr_scheduler dict has no scheduler """ model = EvalModelTemplate() model.configure_optimizers = lambda: { 'optimizer': torch.optim.Adam(model.parameters()), 'lr_scheduler': {}, } trainer = ...
[ "def", "test_lr_scheduler_with_no_actual_scheduler_raises", "(", "tmpdir", ")", ":", "model", "=", "EvalModelTemplate", "(", ")", "model", ".", "configure_optimizers", "=", "lambda", ":", "{", "'optimizer'", ":", "torch", ".", "optim", ".", "Adam", "(", "model", ...
[ 499, 0 ]
[ 510, 26 ]
python
en
['en', 'error', 'th']
False
test_invalid_optimizer_in_scheduler
(tmpdir)
Test exception when optimizer attatched to lr_schedulers wasn't returned
Test exception when optimizer attatched to lr_schedulers wasn't returned
def test_invalid_optimizer_in_scheduler(tmpdir): """ Test exception when optimizer attatched to lr_schedulers wasn't returned """ class InvalidOptimizerModel(BoringModel): def configure_optimizers(self): opt1 = torch.optim.SGD(self.layer.parameters(), lr=0.1) opt2 = tor...
[ "def", "test_invalid_optimizer_in_scheduler", "(", "tmpdir", ")", ":", "class", "InvalidOptimizerModel", "(", "BoringModel", ")", ":", "def", "configure_optimizers", "(", "self", ")", ":", "opt1", "=", "torch", ".", "optim", ".", "SGD", "(", "self", ".", "laye...
[ 513, 0 ]
[ 529, 26 ]
python
en
['en', 'error', 'th']
False
uses_accelerate_framework
(info)
Returns True if Accelerate framework is used for BLAS/LAPACK
Returns True if Accelerate framework is used for BLAS/LAPACK
def uses_accelerate_framework(info): """ Returns True if Accelerate framework is used for BLAS/LAPACK """ # If we're not building on Darwin (macOS), don't use Accelerate if sys.platform != "darwin": return False # If we're building on macOS, but targeting a different platform, # don't use Ac...
[ "def", "uses_accelerate_framework", "(", "info", ")", ":", "# If we're not building on Darwin (macOS), don't use Accelerate", "if", "sys", ".", "platform", "!=", "\"darwin\"", ":", "return", "False", "# If we're building on macOS, but targeting a different platform,", "# don't use ...
[ 8, 0 ]
[ 22, 16 ]
python
en
['en', 'en', 'en']
True
get_sgemv_fix
()
Returns source file needed to correct SGEMV
Returns source file needed to correct SGEMV
def get_sgemv_fix(): """ Returns source file needed to correct SGEMV """ path = os.path.abspath(os.path.dirname(__file__)) return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
[ "def", "get_sgemv_fix", "(", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "return", "[", "os", ".", "path", ".", "join", "(", "path", ",", "'src'", ",", "'apple_sgemv_f...
[ 24, 0 ]
[ 27, 59 ]
python
en
['en', 'en', 'en']
True
load_all_fcompiler_classes
()
Cache all the FCompiler classes found in modules in the numpy.distutils.fcompiler package.
Cache all the FCompiler classes found in modules in the numpy.distutils.fcompiler package.
def load_all_fcompiler_classes(): """Cache all the FCompiler classes found in modules in the numpy.distutils.fcompiler package. """ from glob import glob global fcompiler_class, fcompiler_aliases if fcompiler_class is not None: return pys = os.path.join(os.path.dirname(__file__), '*....
[ "def", "load_all_fcompiler_classes", "(", ")", ":", "from", "glob", "import", "glob", "global", "fcompiler_class", ",", "fcompiler_aliases", "if", "fcompiler_class", "is", "not", "None", ":", "return", "pys", "=", "os", ".", "path", ".", "join", "(", "os", "...
[ 766, 0 ]
[ 792, 51 ]
python
en
['en', 'en', 'en']
True
get_default_fcompiler
(osname=None, platform=None, requiref90=False, c_compiler=None)
Determine the default Fortran compiler to use for the given platform.
Determine the default Fortran compiler to use for the given platform.
def get_default_fcompiler(osname=None, platform=None, requiref90=False, c_compiler=None): """Determine the default Fortran compiler to use for the given platform.""" matching_compiler_types = available_fcompilers_for_platform(osname, ...
[ "def", "get_default_fcompiler", "(", "osname", "=", "None", ",", "platform", "=", "None", ",", "requiref90", "=", "False", ",", "c_compiler", "=", "None", ")", ":", "matching_compiler_types", "=", "available_fcompilers_for_platform", "(", "osname", ",", "platform"...
[ 846, 0 ]
[ 859, 24 ]
python
en
['en', 'en', 'en']
True
new_fcompiler
(plat=None, compiler=None, verbose=0, dry_run=0, force=0, requiref90=False, c_compiler = None)
Generate an instance of some FCompiler subclass for the supplied platform/compiler combination.
Generate an instance of some FCompiler subclass for the supplied platform/compiler combination.
def new_fcompiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0, requiref90=False, c_compiler = None): """Generate an instance of some FCompiler subclass for the supplied platform/compiler combi...
[ "def", "new_fcompiler", "(", "plat", "=", "None", ",", "compiler", "=", "None", ",", "verbose", "=", "0", ",", "dry_run", "=", "0", ",", "force", "=", "0", ",", "requiref90", "=", "False", ",", "c_compiler", "=", "None", ")", ":", "global", "failed_f...
[ 864, 0 ]
[ 901, 19 ]
python
en
['en', 'en', 'en']
True
show_fcompilers
(dist=None)
Print list of available compilers (used by the "--help-fcompiler" option to "config_fc").
Print list of available compilers (used by the "--help-fcompiler" option to "config_fc").
def show_fcompilers(dist=None): """Print list of available compilers (used by the "--help-fcompiler" option to "config_fc"). """ if dist is None: from distutils.dist import Distribution from numpy.distutils.command.config_compiler import config_fc dist = Distribution() di...
[ "def", "show_fcompilers", "(", "dist", "=", "None", ")", ":", "if", "dist", "is", "None", ":", "from", "distutils", ".", "dist", "import", "Distribution", "from", "numpy", ".", "distutils", ".", "command", ".", "config_compiler", "import", "config_fc", "dist...
[ 903, 0 ]
[ 961, 75 ]
python
en
['en', 'en', 'en']
True
is_free_format
(file)
Check if file is in free format Fortran.
Check if file is in free format Fortran.
def is_free_format(file): """Check if file is in free format Fortran.""" # f90 allows both fixed and free format, assuming fixed unless # signs of free format are detected. result = 0 f = open_latin1(file, 'r') line = f.readline() n = 10000 # the number of non-comment lines to scan for hints...
[ "def", "is_free_format", "(", "file", ")", ":", "# f90 allows both fixed and free format, assuming fixed unless", "# signs of free format are detected.", "result", "=", "0", "f", "=", "open_latin1", "(", "file", ",", "'r'", ")", "line", "=", "f", ".", "readline", "(",...
[ 977, 0 ]
[ 999, 17 ]
python
en
['en', 'en', 'en']
True
get_f77flags
(src)
Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}.
Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}.
def get_f77flags(src): """ Search the first 20 lines of fortran 77 code for line pattern `CF77FLAGS(<fcompiler type>)=<f77 flags>` Return a dictionary {<fcompiler type>:<f77 flags>}. """ flags = {} f = open_latin1(src, 'r') i = 0 for line in f: i += 1 if i>20: break...
[ "def", "get_f77flags", "(", "src", ")", ":", "flags", "=", "{", "}", "f", "=", "open_latin1", "(", "src", ",", "'r'", ")", "i", "=", "0", "for", "line", "in", "f", ":", "i", "+=", "1", "if", "i", ">", "20", ":", "break", "m", "=", "_f77flags_...
[ 1008, 0 ]
[ 1026, 16 ]
python
en
['en', 'error', 'th']
False
FCompiler.find_executables
(self)
Go through the self.executables dictionary, and attempt to find and assign appropriate executables. Executable names are looked for in the environment (environment variables, the distutils.cfg, and command line), the 0th-element of the command list, and the self.possible_executables lis...
Go through the self.executables dictionary, and attempt to find and assign appropriate executables.
def find_executables(self): """Go through the self.executables dictionary, and attempt to find and assign appropriate executables. Executable names are looked for in the environment (environment variables, the distutils.cfg, and command line), the 0th-element of the command list...
[ "def", "find_executables", "(", "self", ")", ":", "assert", "self", ".", "_is_customised", "exe_cache", "=", "self", ".", "_exe_cache", "def", "cached_find_executable", "(", "exe", ")", ":", "if", "exe", "in", "exe_cache", ":", "return", "exe_cache", "[", "e...
[ 285, 4 ]
[ 362, 25 ]
python
en
['en', 'en', 'en']
True
FCompiler.update_executables
(self)
Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary. Note that self.find_executables() is run afterwards, so the self.executables dictionary values can contain <F77> or <F90> as the command, which will be replaced b...
Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary.
def update_executables(self): """Called at the beginning of customisation. Subclasses should override this if they need to set up the executables dictionary. Note that self.find_executables() is run afterwards, so the self.executables dictionary values can contain <F77> or <F90> as ...
[ "def", "update_executables", "(", "self", ")", ":", "pass" ]
[ 364, 4 ]
[ 373, 12 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags
(self)
List of flags common to all compiler types.
List of flags common to all compiler types.
def get_flags(self): """List of flags common to all compiler types.""" return [] + self.pic_flags
[ "def", "get_flags", "(", "self", ")", ":", "return", "[", "]", "+", "self", ".", "pic_flags" ]
[ 375, 4 ]
[ 377, 34 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_f77
(self)
List of Fortran 77 specific flags.
List of Fortran 77 specific flags.
def get_flags_f77(self): """List of Fortran 77 specific flags.""" return self._get_command_flags('compiler_f77')
[ "def", "get_flags_f77", "(", "self", ")", ":", "return", "self", ".", "_get_command_flags", "(", "'compiler_f77'", ")" ]
[ 385, 4 ]
[ 387, 54 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_f90
(self)
List of Fortran 90 specific flags.
List of Fortran 90 specific flags.
def get_flags_f90(self): """List of Fortran 90 specific flags.""" return self._get_command_flags('compiler_f90')
[ "def", "get_flags_f90", "(", "self", ")", ":", "return", "self", ".", "_get_command_flags", "(", "'compiler_f90'", ")" ]
[ 388, 4 ]
[ 390, 54 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_free
(self)
List of Fortran 90 free format specific flags.
List of Fortran 90 free format specific flags.
def get_flags_free(self): """List of Fortran 90 free format specific flags.""" return []
[ "def", "get_flags_free", "(", "self", ")", ":", "return", "[", "]" ]
[ 391, 4 ]
[ 393, 17 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_fix
(self)
List of Fortran 90 fixed format specific flags.
List of Fortran 90 fixed format specific flags.
def get_flags_fix(self): """List of Fortran 90 fixed format specific flags.""" return self._get_command_flags('compiler_fix')
[ "def", "get_flags_fix", "(", "self", ")", ":", "return", "self", ".", "_get_command_flags", "(", "'compiler_fix'", ")" ]
[ 394, 4 ]
[ 396, 54 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_linker_so
(self)
List of linker flags to build a shared library.
List of linker flags to build a shared library.
def get_flags_linker_so(self): """List of linker flags to build a shared library.""" return self._get_command_flags('linker_so')
[ "def", "get_flags_linker_so", "(", "self", ")", ":", "return", "self", ".", "_get_command_flags", "(", "'linker_so'", ")" ]
[ 397, 4 ]
[ 399, 51 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_linker_exe
(self)
List of linker flags to build an executable.
List of linker flags to build an executable.
def get_flags_linker_exe(self): """List of linker flags to build an executable.""" return self._get_command_flags('linker_exe')
[ "def", "get_flags_linker_exe", "(", "self", ")", ":", "return", "self", ".", "_get_command_flags", "(", "'linker_exe'", ")" ]
[ 400, 4 ]
[ 402, 52 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_ar
(self)
List of archiver flags.
List of archiver flags.
def get_flags_ar(self): """List of archiver flags. """ return self._get_command_flags('archiver')
[ "def", "get_flags_ar", "(", "self", ")", ":", "return", "self", ".", "_get_command_flags", "(", "'archiver'", ")" ]
[ 403, 4 ]
[ 405, 50 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_opt
(self)
List of architecture independent compiler flags.
List of architecture independent compiler flags.
def get_flags_opt(self): """List of architecture independent compiler flags.""" return []
[ "def", "get_flags_opt", "(", "self", ")", ":", "return", "[", "]" ]
[ 406, 4 ]
[ 408, 17 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_arch
(self)
List of architecture dependent compiler flags.
List of architecture dependent compiler flags.
def get_flags_arch(self): """List of architecture dependent compiler flags.""" return []
[ "def", "get_flags_arch", "(", "self", ")", ":", "return", "[", "]" ]
[ 409, 4 ]
[ 411, 17 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_flags_debug
(self)
List of compiler flags to compile with debugging information.
List of compiler flags to compile with debugging information.
def get_flags_debug(self): """List of compiler flags to compile with debugging information.""" return []
[ "def", "get_flags_debug", "(", "self", ")", ":", "return", "[", "]" ]
[ 412, 4 ]
[ 414, 17 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_libraries
(self)
List of compiler libraries.
List of compiler libraries.
def get_libraries(self): """List of compiler libraries.""" return self.libraries[:]
[ "def", "get_libraries", "(", "self", ")", ":", "return", "self", ".", "libraries", "[", ":", "]" ]
[ 420, 4 ]
[ 422, 32 ]
python
en
['en', 'en', 'en']
True
FCompiler.get_library_dirs
(self)
List of compiler library directories.
List of compiler library directories.
def get_library_dirs(self): """List of compiler library directories.""" return self.library_dirs[:]
[ "def", "get_library_dirs", "(", "self", ")", ":", "return", "self", ".", "library_dirs", "[", ":", "]" ]
[ 423, 4 ]
[ 425, 35 ]
python
en
['en', 'en', 'en']
True
FCompiler.customize
(self, dist = None)
Customize Fortran compiler. This method gets Fortran compiler specific information from (i) class definition, (ii) environment, (iii) distutils config files, and (iv) command line (later overrides earlier). This method should be always called after constructing a compiler insta...
Customize Fortran compiler.
def customize(self, dist = None): """Customize Fortran compiler. This method gets Fortran compiler specific information from (i) class definition, (ii) environment, (iii) distutils config files, and (iv) command line (later overrides earlier). This method should be always calle...
[ "def", "customize", "(", "self", ",", "dist", "=", "None", ")", ":", "log", ".", "info", "(", "'customize %s'", "%", "(", "self", ".", "__class__", ".", "__name__", ")", ")", "self", ".", "_is_customised", "=", "True", "self", ".", "distutils_vars", "....
[ 439, 4 ]
[ 548, 48 ]
python
en
['es', 'su', 'en']
False
FCompiler.dump_properties
(self)
Print out the attributes of a compiler instance.
Print out the attributes of a compiler instance.
def dump_properties(self): """Print out the attributes of a compiler instance.""" props = [] for key in list(self.executables.keys()) + \ ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch']: if hasattr(self, key): ...
[ "def", "dump_properties", "(", "self", ")", ":", "props", "=", "[", "]", "for", "key", "in", "list", "(", "self", ".", "executables", ".", "keys", "(", ")", ")", "+", "[", "'version'", ",", "'libraries'", ",", "'library_dirs'", ",", "'object_switch'", ...
[ 550, 4 ]
[ 566, 20 ]
python
en
['en', 'en', 'en']
True
FCompiler._compile
(self, obj, src, ext, cc_args, extra_postargs, pp_opts)
Compile 'src' to product 'obj'.
Compile 'src' to product 'obj'.
def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts): """Compile 'src' to product 'obj'.""" src_flags = {} if is_f_file(src) and not has_f90_header(src): flavor = ':f77' compiler = self.compiler_f77 src_flags = get_f77flags(src) extr...
[ "def", "_compile", "(", "self", ",", "obj", ",", "src", ",", "ext", ",", "cc_args", ",", "extra_postargs", ",", "pp_opts", ")", ":", "src_flags", "=", "{", "}", "if", "is_f_file", "(", "src", ")", "and", "not", "has_f90_header", "(", "src", ")", ":",...
[ 570, 4 ]
[ 618, 35 ]
python
en
['en', 'en', 'en']
True
FCompiler.can_ccompiler_link
(self, ccompiler)
Check if the given C compiler can link objects produced by this compiler.
Check if the given C compiler can link objects produced by this compiler.
def can_ccompiler_link(self, ccompiler): """ Check if the given C compiler can link objects produced by this compiler. """ return True
[ "def", "can_ccompiler_link", "(", "self", ",", "ccompiler", ")", ":", "return", "True" ]
[ 712, 4 ]
[ 717, 19 ]
python
en
['en', 'error', 'th']
False
FCompiler.wrap_unlinkable_objects
(self, objects, output_dir, extra_dll_dir)
Convert a set of object files that are not compatible with the default linker, to a file that is compatible. Parameters ---------- objects : list List of object files to include. output_dir : str Output directory to place generated object files. ...
Convert a set of object files that are not compatible with the default linker, to a file that is compatible.
def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): """ Convert a set of object files that are not compatible with the default linker, to a file that is compatible. Parameters ---------- objects : list List of object files to include. ...
[ "def", "wrap_unlinkable_objects", "(", "self", ",", "objects", ",", "output_dir", ",", "extra_dll_dir", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 719, 4 ]
[ 742, 35 ]
python
en
['en', 'error', 'th']
False
test_trainer_callback_system
(torch_save, tmpdir)
Test the callback system.
Test the callback system.
def test_trainer_callback_system(torch_save, tmpdir): """Test the callback system.""" model = BoringModel() callback_mock = MagicMock() trainer_options = dict( default_root_dir=tmpdir, callbacks=[callback_mock], max_epochs=1, limit_val_batches=1, limit_train_ba...
[ "def", "test_trainer_callback_system", "(", "torch_save", ",", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "callback_mock", "=", "MagicMock", "(", ")", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "callbacks", "=", ...
[ 21, 0 ]
[ 128, 5 ]
python
en
['en', 'en', 'en']
True
test_callbacks_configured_in_model
(tmpdir)
Test the callback system with callbacks added through the model hook.
Test the callback system with callbacks added through the model hook.
def test_callbacks_configured_in_model(tmpdir): """ Test the callback system with callbacks added through the model hook. """ model_callback_mock = Mock() trainer_callback_mock = Mock() class TestModel(BoringModel): def configure_callbacks(self): return [model_callback_mock] ...
[ "def", "test_callbacks_configured_in_model", "(", "tmpdir", ")", ":", "model_callback_mock", "=", "Mock", "(", ")", "trainer_callback_mock", "=", "Mock", "(", ")", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "configure_callbacks", "(", "self", ")", ...
[ 131, 0 ]
[ 182, 78 ]
python
en
['en', 'en', 'en']
True
test_configure_callbacks_hook_multiple_calls
(tmpdir)
Test that subsequent calls to `configure_callbacks` do not change the callbacks list.
Test that subsequent calls to `configure_callbacks` do not change the callbacks list.
def test_configure_callbacks_hook_multiple_calls(tmpdir): """ Test that subsequent calls to `configure_callbacks` do not change the callbacks list. """ model_callback_mock = Mock() class TestModel(BoringModel): def configure_callbacks(self): return [model_callback_mock] model = Te...
[ "def", "test_configure_callbacks_hook_multiple_calls", "(", "tmpdir", ")", ":", "model_callback_mock", "=", "Mock", "(", ")", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "configure_callbacks", "(", "self", ")", ":", "return", "[", "model_callback_mock...
[ 185, 0 ]
[ 215, 54 ]
python
en
['en', 'en', 'en']
True
PytestRunner.cov_collect
(self)
The path to a file to collect coverage in
The path to a file to collect coverage in
def cov_collect(self) -> str: """The path to a file to collect coverage in""" return self.args.cov_collect
[ "def", "cov_collect", "(", "self", ")", "->", "str", ":", "return", "self", ".", "args", ".", "cov_collect" ]
[ 24, 4 ]
[ 26, 36 ]
python
en
['en', 'en', 'en']
True
PytestRunner.add_arguments
(self, parser: argparse.ArgumentParser)
Add arguments to the arg parser
Add arguments to the arg parser
def add_arguments(self, parser: argparse.ArgumentParser) -> None: """Add arguments to the arg parser""" parser.add_argument("--cov-collect", default=None, help="Collect coverage data to path")
[ "def", "add_arguments", "(", "self", ",", "parser", ":", "argparse", ".", "ArgumentParser", ")", "->", "None", ":", "parser", ".", "add_argument", "(", "\"--cov-collect\"", ",", "default", "=", "None", ",", "help", "=", "\"Collect coverage data to path\"", ")" ]
[ 28, 4 ]
[ 30, 96 ]
python
en
['en', 'en', 'en']
True
Log.good
(self, msg, *args)
If we log WARN messages, log this message as a 'nice' anti-warn message.
If we log WARN messages, log this message as a 'nice' anti-warn message.
def good(self, msg, *args): """ If we log WARN messages, log this message as a 'nice' anti-warn message. """ if WARN >= self.threshold: if args: print(green_text(msg % _fix_args(args))) else: print(green_text(msg)) ...
[ "def", "good", "(", "self", ",", "msg", ",", "*", "args", ")", ":", "if", "WARN", ">=", "self", ".", "threshold", ":", "if", "args", ":", "print", "(", "green_text", "(", "msg", "%", "_fix_args", "(", "args", ")", ")", ")", "else", ":", "print", ...
[ 37, 4 ]
[ 48, 30 ]
python
en
['en', 'error', 'th']
False
Interrupt.wait_for
(self, timeout: int)
Returns True if the interrupt happened and false if timeout milliseconds passed without an interrupt
Returns True if the interrupt happened and false if timeout milliseconds passed without an interrupt
def wait_for(self, timeout: int) -> bool: """Returns True if the interrupt happened and false if timeout milliseconds passed without an interrupt""" pass
[ "def", "wait_for", "(", "self", ",", "timeout", ":", "int", ")", "->", "bool", ":", "pass" ]
[ 5, 4 ]
[ 8, 12 ]
python
en
['en', 'en', 'en']
True
Interrupt.close
(self)
Releases any resources held by the interrupt
Releases any resources held by the interrupt
def close(self): """Releases any resources held by the interrupt""" pass
[ "def", "close", "(", "self", ")", ":", "pass" ]
[ 11, 4 ]
[ 13, 12 ]
python
en
['en', 'en', 'en']
True
EarlyStopping._run_early_stopping_check
(self, trainer, pl_module)
Checks whether the early stopping condition is met and if so tells the trainer to stop the training.
Checks whether the early stopping condition is met and if so tells the trainer to stop the training.
def _run_early_stopping_check(self, trainer, pl_module): """ Checks whether the early stopping condition is met and if so tells the trainer to stop the training. """ logs = trainer.callback_metrics if ( trainer.fast_dev_run # disable early_stopping with fast...
[ "def", "_run_early_stopping_check", "(", "self", ",", "trainer", ",", "pl_module", ")", ":", "logs", "=", "trainer", ".", "callback_metrics", "if", "(", "trainer", ".", "fast_dev_run", "# disable early_stopping with fast_dev_run", "or", "not", "self", ".", "_validat...
[ 162, 4 ]
[ 194, 41 ]
python
en
['en', 'error', 'th']
False
RPCSequentialPlugin.__init__
( self, balance: Optional[List[int]] = None, microbatches: int = 8, checkpoint: str = 'except_last', balance_mode: str = "balance_by_size", pipelined_backward: Optional[bool] = True, rpc_timeout_sec: float = DEFAULT_RPC_TIMEOUT_SEC, **kwargs )
Provides sequential model parallelism for :class:`nn.Sequential <torch.nn.Sequential>` module. If the module requires lots of memory, Pipe can be used to reduce this by leveraging multiple GPUs. .. _RPCSequentialPlugin: https://arxiv.org/abs/1811.06965 Pipeline parallelism comes with ...
Provides sequential model parallelism for :class:`nn.Sequential <torch.nn.Sequential>` module. If the module requires lots of memory, Pipe can be used to reduce this by leveraging multiple GPUs.
def __init__( self, balance: Optional[List[int]] = None, microbatches: int = 8, checkpoint: str = 'except_last', balance_mode: str = "balance_by_size", pipelined_backward: Optional[bool] = True, rpc_timeout_sec: float = DEFAULT_RPC_TIMEOUT_SEC, **kwargs ...
[ "def", "__init__", "(", "self", ",", "balance", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ",", "microbatches", ":", "int", "=", "8", ",", "checkpoint", ":", "str", "=", "'except_last'", ",", "balance_mode", ":", "str", "=", "\"...
[ 42, 4 ]
[ 98, 37 ]
python
en
['en', 'error', 'th']
False
RPCSequentialPlugin._sync_balance_to_all_parallel_groups
(self, main_rank=0)
Ensures that we sync the balance to all main processes, so that the balance is the same per replica. Args: main_rank: The rank with the balance we'd like to replicate.
Ensures that we sync the balance to all main processes, so that the balance is the same per replica. Args: main_rank: The rank with the balance we'd like to replicate.
def _sync_balance_to_all_parallel_groups(self, main_rank=0): """ Ensures that we sync the balance to all main processes, so that the balance is the same per replica. Args: main_rank: The rank with the balance we'd like to replicate. """ self.balance = torch.tensor(sel...
[ "def", "_sync_balance_to_all_parallel_groups", "(", "self", ",", "main_rank", "=", "0", ")", ":", "self", ".", "balance", "=", "torch", ".", "tensor", "(", "self", ".", "balance", ",", "dtype", "=", "torch", ".", "int", ",", "device", "=", "'cuda'", ")",...
[ 149, 4 ]
[ 159, 41 ]
python
en
['en', 'error', 'th']
False
RPCSequentialPlugin._skip_init_connections
(self)
Skip initialization if torch is already initialized and we're in testing. Returns: Whether to skip initialization
Skip initialization if torch is already initialized and we're in testing. Returns: Whether to skip initialization
def _skip_init_connections(self): """ Skip initialization if torch is already initialized and we're in testing. Returns: Whether to skip initialization """ return torch_distrib.is_initialized() and self.lightning_module.running_stage == RunningStage.TESTING
[ "def", "_skip_init_connections", "(", "self", ")", ":", "return", "torch_distrib", ".", "is_initialized", "(", ")", "and", "self", ".", "lightning_module", ".", "running_stage", "==", "RunningStage", ".", "TESTING" ]
[ 204, 4 ]
[ 210, 109 ]
python
en
['en', 'error', 'th']
False
RPCSequentialPlugin._infer_check_num_gpus
(self)
Infer the number of GPUs per model. Returns: The appropriate balance for the model
Infer the number of GPUs per model.
def _infer_check_num_gpus(self): """ Infer the number of GPUs per model. Returns: The appropriate balance for the model """ if isinstance(self.balance, list): if len(self.balance) != (self.world_size / self.num_nodes): raise MisconfigurationException(...
[ "def", "_infer_check_num_gpus", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "balance", ",", "list", ")", ":", "if", "len", "(", "self", ".", "balance", ")", "!=", "(", "self", ".", "world_size", "/", "self", ".", "num_nodes", ")", ":...
[ 216, 4 ]
[ 230, 30 ]
python
en
['en', 'error', 'th']
False
RPCSequentialPlugin.pre_backward
(self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int)
Run before precision plugin executes backward
Run before precision plugin executes backward
def pre_backward(self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int): """Run before precision plugin executes backward"""
[ "def", "pre_backward", "(", "self", ",", "closure_loss", ":", "torch", ".", "Tensor", ",", "should_accumulate", ":", "bool", ",", "optimizer", ":", "Optimizer", ",", "opt_idx", ":", "int", ")", ":" ]
[ 251, 4 ]
[ 252, 59 ]
python
en
['eu', 'gl', 'en']
False
RPCSequentialPlugin.post_optimizer_step
(self, optimizer: Optimizer, optimizer_idx: int, **kwargs)
Hook to do something after each optimizer step.
Hook to do something after each optimizer step.
def post_optimizer_step(self, optimizer: Optimizer, optimizer_idx: int, **kwargs) -> None: """Hook to do something after each optimizer step.""" if self.rpc_enabled and self.main_rpc_process: # Initialize optimizer step on main process self.worker_optimizer_step(model=self.lightn...
[ "def", "post_optimizer_step", "(", "self", ",", "optimizer", ":", "Optimizer", ",", "optimizer_idx", ":", "int", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "self", ".", "rpc_enabled", "and", "self", ".", "main_rpc_process", ":", "# Initialize opt...
[ 321, 4 ]
[ 325, 100 ]
python
en
['en', 'en', 'en']
True
extract_clang_proto_style
(clang_format_text)
Extract a key:value dictionary for proto formatting. Args: clang_format_text: text from a .clang-format file. Returns: key:value dictionary suitable for passing to clang-format --style.
Extract a key:value dictionary for proto formatting.
def extract_clang_proto_style(clang_format_text): """Extract a key:value dictionary for proto formatting. Args: clang_format_text: text from a .clang-format file. Returns: key:value dictionary suitable for passing to clang-format --style. """ lang = None format_dict = {} fo...
[ "def", "extract_clang_proto_style", "(", "clang_format_text", ")", ":", "lang", "=", "None", "format_dict", "=", "{", "}", "for", "line", "in", "clang_format_text", ".", "split", "(", "'\\n'", ")", ":", "if", "lang", "is", "None", "or", "lang", "!=", "'Pro...
[ 45, 0 ]
[ 68, 27 ]
python
en
['en', 'en', 'en']
True
clang_format
(contents)
Run proto-style oriented clang-format over given string. Args: contents: a string with proto contents. Returns: clang-formatted string
Run proto-style oriented clang-format over given string.
def clang_format(contents): """Run proto-style oriented clang-format over given string. Args: contents: a string with proto contents. Returns: clang-formatted string """ return subprocess.run( ['clang-format', '--style=%s' % CLANG_FORMAT_STYLE, '--assume-filename=....
[ "def", "clang_format", "(", "contents", ")", ":", "return", "subprocess", ".", "run", "(", "[", "'clang-format'", ",", "'--style=%s'", "%", "CLANG_FORMAT_STYLE", ",", "'--assume-filename=.proto'", "]", ",", "input", "=", "contents", ".", "encode", "(", "'utf-8'"...
[ 75, 0 ]
[ 88, 38 ]
python
en
['da', 'en', 'en']
True
format_block
(block)
Append \n to a .proto section (e.g. comment, message definition, etc.) if non-empty. Args: block: a string representing the section. Returns: A string with appropriate whitespace.
Append \n to a .proto section (e.g.
def format_block(block): """Append \n to a .proto section (e.g. comment, message definition, etc.) if non-empty. Args: block: a string representing the section. Returns: A string with appropriate whitespace. """ if block.strip(): return block + '\n' return ''
[ "def", "format_block", "(", "block", ")", ":", "if", "block", ".", "strip", "(", ")", ":", "return", "block", "+", "'\\n'", "return", "''" ]
[ 91, 0 ]
[ 104, 13 ]
python
en
['en', 'en', 'sw']
True
format_comments
(comments)
Format a list of comment blocks from SourceCodeInfo. Prefixes // to each line, separates blocks by spaces. Args: comments: a list of blocks, each block is a list of strings representing lines in each block. Returns: A string reprenting the formatted comment blocks.
Format a list of comment blocks from SourceCodeInfo.
def format_comments(comments): """Format a list of comment blocks from SourceCodeInfo. Prefixes // to each line, separates blocks by spaces. Args: comments: a list of blocks, each block is a list of strings representing lines in each block. Returns: A string reprenting the ...
[ "def", "format_comments", "(", "comments", ")", ":", "# TODO(htuch): not sure why this is needed, but clang-format does some weird", "# stuff with // comment indents when we have these trailing \\", "def", "fixup_trailing_backslash", "(", "s", ")", ":", "return", "s", "[", ":", "...
[ 107, 0 ]
[ 129, 33 ]
python
en
['en', 'en', 'en']
True
create_next_free_field_xform
(msg_proto)
Return the next free field number annotation transformer of a message. Args: msg_proto: DescriptorProto for message. Returns: the next free field number annotation transformer.
Return the next free field number annotation transformer of a message.
def create_next_free_field_xform(msg_proto): """Return the next free field number annotation transformer of a message. Args: msg_proto: DescriptorProto for message. Returns: the next free field number annotation transformer. """ next_free = max( sum([ [f.number ...
[ "def", "create_next_free_field_xform", "(", "msg_proto", ")", ":", "next_free", "=", "max", "(", "sum", "(", "[", "[", "f", ".", "number", "+", "1", "for", "f", "in", "msg_proto", ".", "field", "]", ",", "[", "rr", ".", "end", "for", "rr", "in", "m...
[ 132, 0 ]
[ 147, 75 ]
python
en
['en', 'en', 'en']
True
format_type_context_comments
(type_context, annotation_xforms=None)
Format the leading/trailing comments in a given TypeContext. Args: type_context: contextual information for message/enum/field. annotation_xforms: a dict of transformers for annotations in leading comment. Returns: Tuple of formatted leading and trailing comment blocks.
Format the leading/trailing comments in a given TypeContext.
def format_type_context_comments(type_context, annotation_xforms=None): """Format the leading/trailing comments in a given TypeContext. Args: type_context: contextual information for message/enum/field. annotation_xforms: a dict of transformers for annotations in leading comment. ...
[ "def", "format_type_context_comments", "(", "type_context", ",", "annotation_xforms", "=", "None", ")", ":", "leading_comment", "=", "type_context", ".", "leading_comment", "if", "annotation_xforms", ":", "leading_comment", "=", "leading_comment", ".", "get_comment_with_t...
[ 150, 0 ]
[ 166, 28 ]
python
en
['en', 'en', 'en']
True
format_header_from_file
( source_code_info, file_proto, empty_file, requires_deprecation_annotation)
Format proto header. Args: source_code_info: SourceCodeInfo object. file_proto: FileDescriptorProto for file. empty_file: are there no message/enum/service defs in file? requires_deprecation_annotation: does the proto have the deprecated version annotation or ...
Format proto header.
def format_header_from_file( source_code_info, file_proto, empty_file, requires_deprecation_annotation): """Format proto header. Args: source_code_info: SourceCodeInfo object. file_proto: FileDescriptorProto for file. empty_file: are there no message/enum/service defs in file? ...
[ "def", "format_header_from_file", "(", "source_code_info", ",", "file_proto", ",", "empty_file", ",", "requires_deprecation_annotation", ")", ":", "# Load the type database.", "typedb", "=", "utils", ".", "get_type_db", "(", ")", "# Figure out type dependencies in this .proto...
[ 169, 0 ]
[ 308, 95 ]
python
en
['en', 'sv', 'it']
False
normalize_field_type_name
(type_context, field_fqn)
Normalize a fully qualified field type name, e.g. .envoy.foo.bar is normalized to foo.bar. Considers type context to minimize type prefix. Args: field_fqn: a fully qualified type name from FieldDescriptorProto.type_name. type_context: contextual information for message/enum/field. Re...
Normalize a fully qualified field type name, e.g.
def normalize_field_type_name(type_context, field_fqn): """Normalize a fully qualified field type name, e.g. .envoy.foo.bar is normalized to foo.bar. Considers type context to minimize type prefix. Args: field_fqn: a fully qualified type name from FieldDescriptorProto.type_name. type_...
[ "def", "normalize_field_type_name", "(", "type_context", ",", "field_fqn", ")", ":", "if", "field_fqn", ".", "startswith", "(", "'.'", ")", ":", "# Let's say we have type context namespace a.b.c.d.e and the type we're", "# trying to normalize is a.b.d.e. We take (from the end) on p...
[ 311, 0 ]
[ 390, 20 ]
python
en
['en', 'en', 'en']
True
format_field_type
(type_context, field)
Format a FieldDescriptorProto type description. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Returns: Formatted proto field type as string.
Format a FieldDescriptorProto type description.
def format_field_type(type_context, field): """Format a FieldDescriptorProto type description. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Returns: Formatted proto field type as string. """ label = 'repeated ' if field.la...
[ "def", "format_field_type", "(", "type_context", ",", "field", ")", ":", "label", "=", "'repeated '", "if", "field", ".", "label", "==", "field", ".", "LABEL_REPEATED", "else", "''", "type_name", "=", "label", "+", "normalize_field_type_name", "(", "type_context...
[ 397, 0 ]
[ 440, 66 ]
python
en
['it', 'fy', 'en']
False
format_service_method
(type_context, method)
Format a service MethodDescriptorProto. Args: type_context: contextual information for method. method: MethodDescriptorProto proto. Returns: Formatted service method as string.
Format a service MethodDescriptorProto.
def format_service_method(type_context, method): """Format a service MethodDescriptorProto. Args: type_context: contextual information for method. method: MethodDescriptorProto proto. Returns: Formatted service method as string. """ def format_streaming(s): return ...
[ "def", "format_service_method", "(", "type_context", ",", "method", ")", ":", "def", "format_streaming", "(", "s", ")", ":", "return", "'stream '", "if", "s", "else", "''", "leading_comment", ",", "trailing_comment", "=", "format_type_context_comments", "(", "type...
[ 443, 0 ]
[ 462, 100 ]
python
en
['en', 'gl', 'en']
True
format_field
(type_context, field)
Format FieldDescriptorProto as a proto field. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Returns: Formatted proto field as a string.
Format FieldDescriptorProto as a proto field.
def format_field(type_context, field): """Format FieldDescriptorProto as a proto field. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Returns: Formatted proto field as a string. """ if protoxform_options.has_hide_option(fie...
[ "def", "format_field", "(", "type_context", ",", "field", ")", ":", "if", "protoxform_options", ".", "has_hide_option", "(", "field", ".", "options", ")", ":", "return", "''", "leading_comment", ",", "trailing_comment", "=", "format_type_context_comments", "(", "t...
[ 465, 0 ]
[ 481, 56 ]
python
en
['en', 'fy', 'en']
True
format_enum_value
(type_context, value)
Format a EnumValueDescriptorProto as a proto enum value. Args: type_context: contextual information for message/enum/field. value: EnumValueDescriptorProto. Returns: Formatted proto enum value as a string.
Format a EnumValueDescriptorProto as a proto enum value.
def format_enum_value(type_context, value): """Format a EnumValueDescriptorProto as a proto enum value. Args: type_context: contextual information for message/enum/field. value: EnumValueDescriptorProto. Returns: Formatted proto enum value as a string. """ if protoxform_opt...
[ "def", "format_enum_value", "(", "type_context", ",", "value", ")", ":", "if", "protoxform_options", ".", "has_hide_option", "(", "value", ".", "options", ")", ":", "return", "''", "leading_comment", ",", "trailing_comment", "=", "format_type_context_comments", "(",...
[ 484, 0 ]
[ 499, 91 ]
python
en
['en', 'es', 'it']
False