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
ArrayZTestCase.testSetGet
(self)
Test ArrayZ __setitem__, __getitem__ methods
Test ArrayZ __setitem__, __getitem__ methods
def testSetGet(self): "Test ArrayZ __setitem__, __getitem__ methods" n = self.length for i in range(n): self.array3[i] = i*i for i in range(n): self.failUnless(self.array3[i] == i*i)
[ "def", "testSetGet", "(", "self", ")", ":", "n", "=", "self", ".", "length", "for", "i", "in", "range", "(", "n", ")", ":", "self", ".", "array3", "[", "i", "]", "=", "i", "*", "i", "for", "i", "in", "range", "(", "n", ")", ":", "self", "."...
[ 327, 4 ]
[ 333, 50 ]
python
en
['en', 'is', 'hi']
False
ArrayZTestCase.testSetBad1
(self)
Test ArrayZ __setitem__ method, negative index
Test ArrayZ __setitem__ method, negative index
def testSetBad1(self): "Test ArrayZ __setitem__ method, negative index" self.assertRaises(IndexError, self.array3.__setitem__, -1, 0)
[ "def", "testSetBad1", "(", "self", ")", ":", "self", ".", "assertRaises", "(", "IndexError", ",", "self", ".", "array3", ".", "__setitem__", ",", "-", "1", ",", "0", ")" ]
[ 335, 4 ]
[ 337, 69 ]
python
hi
['sl', 'hu', 'hi']
False
ArrayZTestCase.testSetBad2
(self)
Test ArrayZ __setitem__ method, out-of-range index
Test ArrayZ __setitem__ method, out-of-range index
def testSetBad2(self): "Test ArrayZ __setitem__ method, out-of-range index" self.assertRaises(IndexError, self.array3.__setitem__, self.length+1, 0)
[ "def", "testSetBad2", "(", "self", ")", ":", "self", ".", "assertRaises", "(", "IndexError", ",", "self", ".", "array3", ".", "__setitem__", ",", "self", ".", "length", "+", "1", ",", "0", ")" ]
[ 339, 4 ]
[ 341, 80 ]
python
en
['en', 'da', 'en']
True
ArrayZTestCase.testGetBad1
(self)
Test ArrayZ __getitem__ method, negative index
Test ArrayZ __getitem__ method, negative index
def testGetBad1(self): "Test ArrayZ __getitem__ method, negative index" self.assertRaises(IndexError, self.array3.__getitem__, -1)
[ "def", "testGetBad1", "(", "self", ")", ":", "self", ".", "assertRaises", "(", "IndexError", ",", "self", ".", "array3", ".", "__getitem__", ",", "-", "1", ")" ]
[ 343, 4 ]
[ 345, 66 ]
python
hi
['sl', 'tr', 'hi']
False
ArrayZTestCase.testGetBad2
(self)
Test ArrayZ __getitem__ method, out-of-range index
Test ArrayZ __getitem__ method, out-of-range index
def testGetBad2(self): "Test ArrayZ __getitem__ method, out-of-range index" self.assertRaises(IndexError, self.array3.__getitem__, self.length+1)
[ "def", "testGetBad2", "(", "self", ")", ":", "self", ".", "assertRaises", "(", "IndexError", ",", "self", ".", "array3", ".", "__getitem__", ",", "self", ".", "length", "+", "1", ")" ]
[ 347, 4 ]
[ 349, 77 ]
python
en
['en', 'da', 'en']
True
ArrayZTestCase.testAsString
(self)
Test ArrayZ asString method
Test ArrayZ asString method
def testAsString(self): "Test ArrayZ asString method" for i in range(self.array3.length()): self.array3[i] = complex(i+1,-i-1) self.failUnless(self.array3.asString() == "[ (1,-1), (2,-2), (3,-3), (4,-4), (5,-5) ]")
[ "def", "testAsString", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "array3", ".", "length", "(", ")", ")", ":", "self", ".", "array3", "[", "i", "]", "=", "complex", "(", "i", "+", "1", ",", "-", "i", "-", "1", ")", ...
[ 351, 4 ]
[ 354, 95 ]
python
en
['en', 'is', 'en']
True
ArrayZTestCase.testStr
(self)
Test ArrayZ __str__ method
Test ArrayZ __str__ method
def testStr(self): "Test ArrayZ __str__ method" for i in range(self.array3.length()): self.array3[i] = complex(i-2,(i-2)*2) self.failUnless(str(self.array3) == "[ (-2,-4), (-1,-2), (0,0), (1,2), (2,4) ]")
[ "def", "testStr", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "array3", ".", "length", "(", ")", ")", ":", "self", ".", "array3", "[", "i", "]", "=", "complex", "(", "i", "-", "2", ",", "(", "i", "-", "2", ")", "*", ...
[ 356, 4 ]
[ 359, 88 ]
python
en
['en', 'pl', 'tr']
False
ArrayZTestCase.testView
(self)
Test ArrayZ view method
Test ArrayZ view method
def testView(self): "Test ArrayZ view method" for i in range(self.array3.length()): self.array3[i] = complex(i+1,i+2) a = self.array3.view() self.failUnless(isinstance(a, np.ndarray)) self.failUnless(len(a) == self.length) self.failUnless((a == [1+2j, 2+3j, 3+4j, 4+5j, 5+...
[ "def", "testView", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "array3", ".", "length", "(", ")", ")", ":", "self", ".", "array3", "[", "i", "]", "=", "complex", "(", "i", "+", "1", ",", "i", "+", "2", ")", "a", "=",...
[ 361, 4 ]
[ 367, 68 ]
python
en
['en', 'pl', 'en']
True
BasePose.forward_train
(self, img, img_metas, **kwargs)
Defines the computation performed at training.
Defines the computation performed at training.
def forward_train(self, img, img_metas, **kwargs): """Defines the computation performed at training."""
[ "def", "forward_train", "(", "self", ",", "img", ",", "img_metas", ",", "*", "*", "kwargs", ")", ":" ]
[ 26, 4 ]
[ 27, 60 ]
python
en
['en', 'en', 'en']
True
BasePose.forward_test
(self, img, img_metas, **kwargs)
Defines the computation performed at testing.
Defines the computation performed at testing.
def forward_test(self, img, img_metas, **kwargs): """Defines the computation performed at testing."""
[ "def", "forward_test", "(", "self", ",", "img", ",", "img_metas", ",", "*", "*", "kwargs", ")", ":" ]
[ 30, 4 ]
[ 31, 59 ]
python
en
['en', 'en', 'en']
True
BasePose.forward
(self, img, img_metas, return_loss=True, **kwargs)
Forward function.
Forward function.
def forward(self, img, img_metas, return_loss=True, **kwargs): """Forward function."""
[ "def", "forward", "(", "self", ",", "img", ",", "img_metas", ",", "return_loss", "=", "True", ",", "*", "*", "kwargs", ")", ":" ]
[ 34, 4 ]
[ 35, 31 ]
python
en
['en', 'cy', 'en']
False
BasePose._parse_losses
(losses)
Parse the raw outputs (losses) of the network. Args: losses (dict): Raw output of the network, which usually contain losses and other necessary information. Returns: tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor which may be a we...
Parse the raw outputs (losses) of the network.
def _parse_losses(losses): """Parse the raw outputs (losses) of the network. Args: losses (dict): Raw output of the network, which usually contain losses and other necessary information. Returns: tuple[Tensor, dict]: (loss, log_vars), loss is the loss te...
[ "def", "_parse_losses", "(", "losses", ")", ":", "log_vars", "=", "OrderedDict", "(", ")", "for", "loss_name", ",", "loss_value", "in", "losses", ".", "items", "(", ")", ":", "if", "isinstance", "(", "loss_value", ",", "torch", ".", "Tensor", ")", ":", ...
[ 38, 4 ]
[ 76, 29 ]
python
en
['en', 'en', 'en']
True
BasePose.train_step
(self, data_batch, optimizer, **kwargs)
The iteration step during training. This method defines an iteration step during training, except for the back propagation and optimizer updating, which are done in an optimizer hook. Note that in some complicated cases or models, the whole process including back propagation and optimiz...
The iteration step during training.
def train_step(self, data_batch, optimizer, **kwargs): """The iteration step during training. This method defines an iteration step during training, except for the back propagation and optimizer updating, which are done in an optimizer hook. Note that in some complicated cases or models...
[ "def", "train_step", "(", "self", ",", "data_batch", ",", "optimizer", ",", "*", "*", "kwargs", ")", ":", "losses", "=", "self", ".", "forward", "(", "*", "*", "data_batch", ")", "loss", ",", "log_vars", "=", "self", ".", "_parse_losses", "(", "losses"...
[ 78, 4 ]
[ 113, 22 ]
python
en
['en', 'en', 'en']
True
BasePose.val_step
(self, data_batch, optimizer, **kwargs)
The iteration step during validation. This method shares the same signature as :func:`train_step`, but used during val epochs. Note that the evaluation after training epochs is not implemented with this method, but an evaluation hook.
The iteration step during validation.
def val_step(self, data_batch, optimizer, **kwargs): """The iteration step during validation. This method shares the same signature as :func:`train_step`, but used during val epochs. Note that the evaluation after training epochs is not implemented with this method, but an evaluation ho...
[ "def", "val_step", "(", "self", ",", "data_batch", ",", "optimizer", ",", "*", "*", "kwargs", ")", ":", "results", "=", "self", ".", "forward", "(", "return_loss", "=", "False", ",", "*", "*", "data_batch", ")", "outputs", "=", "dict", "(", "results", ...
[ 115, 4 ]
[ 126, 22 ]
python
en
['en', 'en', 'en']
True
BasePose.show_result
(self, **kwargs)
Visualize the results.
Visualize the results.
def show_result(self, **kwargs): """Visualize the results.""" raise NotImplementedError
[ "def", "show_result", "(", "self", ",", "*", "*", "kwargs", ")", ":", "raise", "NotImplementedError" ]
[ 129, 4 ]
[ 131, 33 ]
python
en
['en', 'en', 'en']
True
is_bst
(node, lower_lim=None, upper_lim=None)
Function to find is a binary tree is a binary search tree.
Function to find is a binary tree is a binary search tree.
def is_bst(node, lower_lim=None, upper_lim=None): """Function to find is a binary tree is a binary search tree.""" if lower_lim is not None and node.info < lower_lim: return False if upper_lim is not None and node.info > upper_lim: return False is_left_bst = True is_right_bst = True ...
[ "def", "is_bst", "(", "node", ",", "lower_lim", "=", "None", ",", "upper_lim", "=", "None", ")", ":", "if", "lower_lim", "is", "not", "None", "and", "node", ".", "info", "<", "lower_lim", ":", "return", "False", "if", "upper_lim", "is", "not", "None", ...
[ 146, 0 ]
[ 158, 39 ]
python
en
['en', 'en', 'en']
True
Node.__init__
(self, info)
Initialising a node
Initialising a node
def __init__(self, info): """Initialising a node""" self.info = info self.left = None self.right = None
[ "def", "__init__", "(", "self", ",", "info", ")", ":", "self", ".", "info", "=", "info", "self", ".", "left", "=", "None", "self", ".", "right", "=", "None" ]
[ 4, 4 ]
[ 8, 25 ]
python
en
['en', 'lb', 'it']
False
BinarySearchTree.__init__
(self)
Initialising a BST
Initialising a BST
def __init__(self): """Initialising a BST""" self.root = None
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "root", "=", "None" ]
[ 20, 4 ]
[ 22, 24 ]
python
en
['en', 'en', 'en']
True
BinarySearchTree.insert
(self, val)
Creating a BST with root value as val
Creating a BST with root value as val
def insert(self, val): """Creating a BST with root value as val""" # Check if tree has root with None value if self.root is None: self.root = Node(val) # Here the tree already has one root else: current = self.root while True: i...
[ "def", "insert", "(", "self", ",", "val", ")", ":", "# Check if tree has root with None value", "if", "self", ".", "root", "is", "None", ":", "self", ".", "root", "=", "Node", "(", "val", ")", "# Here the tree already has one root", "else", ":", "current", "="...
[ 24, 4 ]
[ 46, 25 ]
python
en
['en', 'en', 'en']
True
run
(canvas)
This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None
This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on.
def run(canvas): ''' This function runs the rules of game through all points, and changes their status accordingly.(in the same canvas) @Args: -- canvas : canvas of population to run the rules on. @returns: -- None ''' canvas = np.array(canvas) next_gen_canvas = np.array(create...
[ "def", "run", "(", "canvas", ")", ":", "canvas", "=", "np", ".", "array", "(", "canvas", ")", "next_gen_canvas", "=", "np", ".", "array", "(", "create_canvas", "(", "canvas", ".", "shape", "[", "0", "]", ")", ")", "for", "r", ",", "row", "in", "e...
[ 56, 0 ]
[ 75, 26 ]
python
en
['en', 'en', 'en']
True
urlopen_stub
(url, data=None)
Stub to replace urlopen for testing.
Stub to replace urlopen for testing.
def urlopen_stub(url, data=None): '''Stub to replace urlopen for testing.''' if url == valid_httpurl(): tmpfile = NamedTemporaryFile(prefix='urltmp_') return tmpfile else: raise URLError('Name or service not known')
[ "def", "urlopen_stub", "(", "url", ",", "data", "=", "None", ")", ":", "if", "url", "==", "valid_httpurl", "(", ")", ":", "tmpfile", "=", "NamedTemporaryFile", "(", "prefix", "=", "'urltmp_'", ")", "return", "tmpfile", "else", ":", "raise", "URLError", "...
[ 23, 0 ]
[ 29, 51 ]
python
en
['en', 'en', 'en']
True
LoggerConnector.cache_training_step_metrics
(self, opt_closure_result)
This function is responsible to update logger_connector internals metrics holder based for depreceated logging
This function is responsible to update logger_connector internals metrics holder based for depreceated logging
def cache_training_step_metrics(self, opt_closure_result): """ This function is responsible to update logger_connector internals metrics holder based for depreceated logging """ using_results_obj = isinstance(opt_closure_result.training_step_output, Result) # temporary d...
[ "def", "cache_training_step_metrics", "(", "self", ",", "opt_closure_result", ")", ":", "using_results_obj", "=", "isinstance", "(", "opt_closure_result", ".", "training_step_output", ",", "Result", ")", "# temporary dict to collect metrics", "logged_metrics_tmp", "=", "{",...
[ 160, 4 ]
[ 205, 79 ]
python
en
['en', 'error', 'th']
False
LoggerConnector.log_metrics
(self, metrics, grad_norm_dic, step=None)
Logs the metric dict passed in. If `step` parameter is None and `step` key is presented is metrics, uses metrics["step"] as a step Args: metrics (dict): Metric values grad_norm_dic (dict): Gradient norms step (int): Step for which metrics should be logged. De...
Logs the metric dict passed in. If `step` parameter is None and `step` key is presented is metrics, uses metrics["step"] as a step
def log_metrics(self, metrics, grad_norm_dic, step=None): """Logs the metric dict passed in. If `step` parameter is None and `step` key is presented is metrics, uses metrics["step"] as a step Args: metrics (dict): Metric values grad_norm_dic (dict): Gradient norm...
[ "def", "log_metrics", "(", "self", ",", "metrics", ",", "grad_norm_dic", ",", "step", "=", "None", ")", ":", "# add gpu memory", "if", "self", ".", "trainer", ".", "_device_type", "==", "DeviceType", ".", "GPU", "and", "self", ".", "log_gpu_memory", ":", "...
[ 207, 4 ]
[ 247, 82 ]
python
en
['en', 'en', 'en']
True
LoggerConnector.__prepare_epoch_end_inputs
(self, epoch_output)
Pulls out only the "extra" information for epoch end Return: a single list, each element per optimizer then batch then time
Pulls out only the "extra" information for epoch end
def __prepare_epoch_end_inputs(self, epoch_output): """ Pulls out only the "extra" information for epoch end Return: a single list, each element per optimizer then batch then time """ gathered_epoch_outputs = [] for opt_outputs in epoch_output: # ...
[ "def", "__prepare_epoch_end_inputs", "(", "self", ",", "epoch_output", ")", ":", "gathered_epoch_outputs", "=", "[", "]", "for", "opt_outputs", "in", "epoch_output", ":", "# gather across time first", "time_gathered_outputs", "=", "[", "]", "for", "tbptt_outs", "in", ...
[ 573, 4 ]
[ 598, 37 ]
python
en
['en', 'error', 'th']
False
LoggerConnector.__gather_result_across_time_and_optimizers
(self, epoch_output)
Gather results into a single padded tensor per metric where each tensor is gathered across time and across time steps. Returns: a list where each element is a Result with the tensors gathered
Gather results into a single padded tensor per metric where each tensor is gathered across time and across time steps.
def __gather_result_across_time_and_optimizers(self, epoch_output): """ Gather results into a single padded tensor per metric where each tensor is gathered across time and across time steps. Returns: a list where each element is a Result with the tensors gathered """...
[ "def", "__gather_result_across_time_and_optimizers", "(", "self", ",", "epoch_output", ")", ":", "gathered_epoch_outputs", "=", "[", "]", "for", "opt_outputs", "in", "epoch_output", ":", "# gather across time first", "time_gathered_outputs", "=", "[", "]", "for", "tbptt...
[ 600, 4 ]
[ 621, 37 ]
python
en
['en', 'error', 'th']
False
_check_same_shape
(pred: torch.Tensor, target: torch.Tensor)
Check that predictions and target have the same shape, else raise error
Check that predictions and target have the same shape, else raise error
def _check_same_shape(pred: torch.Tensor, target: torch.Tensor): """ Check that predictions and target have the same shape, else raise error """ if pred.shape != target.shape: raise RuntimeError("Predictions and targets are expected to have the same shape")
[ "def", "_check_same_shape", "(", "pred", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ")", ":", "if", "pred", ".", "shape", "!=", "target", ".", "shape", ":", "raise", "RuntimeError", "(", "\"Predictions and targets are expected to ...
[ 39, 0 ]
[ 42, 89 ]
python
en
['en', 'en', 'en']
True
_input_format_classification_one_hot
( num_classes: int, preds: torch.Tensor, target: torch.Tensor, threshold: float = 0.5, multilabel: bool = False )
Convert preds and target tensors into one hot spare label tensors Args: num_classes: number of classes preds: either tensor with labels, tensor with probabilities/logits or multilabel tensor target: tensor with ground true labels threshold: float used for thresholding mu...
Convert preds and target tensors into one hot spare label tensors
def _input_format_classification_one_hot( num_classes: int, preds: torch.Tensor, target: torch.Tensor, threshold: float = 0.5, multilabel: bool = False ) -> Tuple[torch.Tensor, torch.Tensor]: """Convert preds and target tensors into one hot spare label tensors Args: num_classes: num...
[ "def", "_input_format_classification_one_hot", "(", "num_classes", ":", "int", ",", "preds", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "threshold", ":", "float", "=", "0.5", ",", "multilabel", ":", "bool", "=", "False", ...
[ 45, 0 ]
[ 87, 74 ]
python
en
['en', 'en', 'en']
True
to_onehot
( label_tensor: torch.Tensor, num_classes: Optional[int] = None, )
Converts a dense label tensor to one-hot format Args: label_tensor: dense label tensor, with shape [N, d1, d2, ...] num_classes: number of classes C Returns: A sparse label tensor with shape [N, C, d1, d2, ...] Example: >>> from pytorch_lightning.metrics.utils import...
Converts a dense label tensor to one-hot format
def to_onehot( label_tensor: torch.Tensor, num_classes: Optional[int] = None, ) -> torch.Tensor: """ Converts a dense label tensor to one-hot format Args: label_tensor: dense label tensor, with shape [N, d1, d2, ...] num_classes: number of classes C Returns: A sparse la...
[ "def", "to_onehot", "(", "label_tensor", ":", "torch", ".", "Tensor", ",", "num_classes", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "torch", ".", "Tensor", ":", "if", "num_classes", "is", "None", ":", "num_classes", "=", "int", "("...
[ 90, 0 ]
[ 124, 48 ]
python
en
['en', 'error', 'th']
False
select_topk
(prob_tensor: torch.Tensor, topk: int = 1, dim: int = 1)
Convert a probability tensor to binary by selecting top-k highest entries. Args: prob_tensor: dense tensor of shape ``[..., C, ...]``, where ``C`` is in the position defined by the ``dim`` argument topk: number of highest entries to turn into 1s dim: dimension on which to c...
Convert a probability tensor to binary by selecting top-k highest entries.
def select_topk(prob_tensor: torch.Tensor, topk: int = 1, dim: int = 1) -> torch.Tensor: """ Convert a probability tensor to binary by selecting top-k highest entries. Args: prob_tensor: dense tensor of shape ``[..., C, ...]``, where ``C`` is in the position defined by the ``dim`` argum...
[ "def", "select_topk", "(", "prob_tensor", ":", "torch", ".", "Tensor", ",", "topk", ":", "int", "=", "1", ",", "dim", ":", "int", "=", "1", ")", "->", "torch", ".", "Tensor", ":", "zeros", "=", "torch", ".", "zeros_like", "(", "prob_tensor", ")", "...
[ 127, 0 ]
[ 150, 28 ]
python
en
['en', 'error', 'th']
False
to_categorical
(tensor: torch.Tensor, argmax_dim: int = 1)
Converts a tensor of probabilities to a dense label tensor Args: tensor: probabilities to get the categorical label [N, d1, d2, ...] argmax_dim: dimension to apply Return: A tensor with categorical labels [N, d2, ...] Example: >>> from pytorch_lightning.metrics.utils...
Converts a tensor of probabilities to a dense label tensor
def to_categorical(tensor: torch.Tensor, argmax_dim: int = 1) -> torch.Tensor: """ Converts a tensor of probabilities to a dense label tensor Args: tensor: probabilities to get the categorical label [N, d1, d2, ...] argmax_dim: dimension to apply Return: A tensor with categoric...
[ "def", "to_categorical", "(", "tensor", ":", "torch", ".", "Tensor", ",", "argmax_dim", ":", "int", "=", "1", ")", "->", "torch", ".", "Tensor", ":", "return", "torch", ".", "argmax", "(", "tensor", ",", "dim", "=", "argmax_dim", ")" ]
[ 153, 0 ]
[ 171, 47 ]
python
en
['en', 'error', 'th']
False
get_num_classes
( pred: torch.Tensor, target: torch.Tensor, num_classes: Optional[int] = None, )
Calculates the number of classes for a given prediction and target tensor. Args: pred: predicted values target: true labels num_classes: number of classes if known Return: An integer that represents the number of classes.
Calculates the number of classes for a given prediction and target tensor.
def get_num_classes( pred: torch.Tensor, target: torch.Tensor, num_classes: Optional[int] = None, ) -> int: """ Calculates the number of classes for a given prediction and target tensor. Args: pred: predicted values target: true labels num_classes: number of classes if k...
[ "def", "get_num_classes", "(", "pred", ":", "torch", ".", "Tensor", ",", "target", ":", "torch", ".", "Tensor", ",", "num_classes", ":", "Optional", "[", "int", "]", "=", "None", ",", ")", "->", "int", ":", "num_target_classes", "=", "int", "(", "targe...
[ 174, 0 ]
[ 203, 22 ]
python
en
['en', 'error', 'th']
False
reduce
(to_reduce: torch.Tensor, reduction: str)
Reduces a given tensor by a given reduction method Args: to_reduce : the tensor, which shall be reduced reduction : a string specifying the reduction method ('elementwise_mean', 'none', 'sum') Return: reduced Tensor Raise: ValueError if an invalid reduction parameter ...
Reduces a given tensor by a given reduction method
def reduce(to_reduce: torch.Tensor, reduction: str) -> torch.Tensor: """ Reduces a given tensor by a given reduction method Args: to_reduce : the tensor, which shall be reduced reduction : a string specifying the reduction method ('elementwise_mean', 'none', 'sum') Return: redu...
[ "def", "reduce", "(", "to_reduce", ":", "torch", ".", "Tensor", ",", "reduction", ":", "str", ")", "->", "torch", ".", "Tensor", ":", "if", "reduction", "==", "\"elementwise_mean\"", ":", "return", "torch", ".", "mean", "(", "to_reduce", ")", "if", "redu...
[ 206, 0 ]
[ 226, 52 ]
python
en
['en', 'error', 'th']
False
class_reduce
( num: torch.Tensor, denom: torch.Tensor, weights: torch.Tensor, class_reduction: str = "none" )
Function used to reduce classification metrics of the form `num / denom * weights`. For example for calculating standard accuracy the num would be number of true positives per class, denom would be the support per class, and weights would be a tensor of 1s Args: num: numerator tensor ...
Function used to reduce classification metrics of the form `num / denom * weights`. For example for calculating standard accuracy the num would be number of true positives per class, denom would be the support per class, and weights would be a tensor of 1s
def class_reduce( num: torch.Tensor, denom: torch.Tensor, weights: torch.Tensor, class_reduction: str = "none" ) -> torch.Tensor: """ Function used to reduce classification metrics of the form `num / denom * weights`. For example for calculating standard accuracy the num would be number of true posi...
[ "def", "class_reduce", "(", "num", ":", "torch", ".", "Tensor", ",", "denom", ":", "torch", ".", "Tensor", ",", "weights", ":", "torch", ".", "Tensor", ",", "class_reduction", ":", "str", "=", "\"none\"", ")", "->", "torch", ".", "Tensor", ":", "valid_...
[ 229, 0 ]
[ 272, 5 ]
python
en
['en', 'error', 'th']
False
_stable_1d_sort
(x: torch, N: int = 2049)
Stable sort of 1d tensors. Pytorch defaults to a stable sorting algorithm if number of elements are larger than 2048. This function pads the tensors, makes the sort and returns the sorted array (with the padding removed) See this discussion: https://discuss.pytorch.org/t/is-torch-sort-stable/20714
Stable sort of 1d tensors. Pytorch defaults to a stable sorting algorithm if number of elements are larger than 2048. This function pads the tensors, makes the sort and returns the sorted array (with the padding removed) See this discussion: https://discuss.pytorch.org/t/is-torch-sort-stable/20714
def _stable_1d_sort(x: torch, N: int = 2049): """ Stable sort of 1d tensors. Pytorch defaults to a stable sorting algorithm if number of elements are larger than 2048. This function pads the tensors, makes the sort and returns the sorted array (with the padding removed) See this discussion: https://...
[ "def", "_stable_1d_sort", "(", "x", ":", "torch", ",", "N", ":", "int", "=", "2049", ")", ":", "if", "x", ".", "ndim", ">", "1", ":", "raise", "ValueError", "(", "'Stable sort only works on 1d tensors'", ")", "n", "=", "x", ".", "numel", "(", ")", "i...
[ 275, 0 ]
[ 289, 48 ]
python
en
['en', 'error', 'th']
False
TPUAccelerator.all_gather
(self, tensor: Union[torch.Tensor], group: Optional[Any] = None, sync_grads: bool = False)
Function to gather a tensor from several distributed processes Args: tensor: tensor of shape (batch, ...) group: the process group to gather results from. Defaults to all processes (world) sync_grads: flag that allows users to synchronize gradients for all_gather op ...
Function to gather a tensor from several distributed processes Args: tensor: tensor of shape (batch, ...) group: the process group to gather results from. Defaults to all processes (world) sync_grads: flag that allows users to synchronize gradients for all_gather op ...
def all_gather(self, tensor: Union[torch.Tensor], group: Optional[Any] = None, sync_grads: bool = False): """ Function to gather a tensor from several distributed processes Args: tensor: tensor of shape (batch, ...) group: the process group to gather results from. Default...
[ "def", "all_gather", "(", "self", ",", "tensor", ":", "Union", "[", "torch", ".", "Tensor", "]", ",", "group", ":", "Optional", "[", "Any", "]", "=", "None", ",", "sync_grads", ":", "bool", "=", "False", ")", ":", "return", "xm", ".", "all_gather", ...
[ 32, 4 ]
[ 42, 72 ]
python
en
['en', 'error', 'th']
False
TestEpochEndVariations.test_epoch_end
(self, outputs)
Called at the end of test epoch to aggregate outputs :param outputs: list of individual outputs of each validation step :return:
Called at the end of test epoch to aggregate outputs :param outputs: list of individual outputs of each validation step :return:
def test_epoch_end(self, outputs): """ Called at the end of test epoch to aggregate outputs :param outputs: list of individual outputs of each validation step :return: """ # if returned a scalar from test_step, outputs is a list of tensor scalars # we return just ...
[ "def", "test_epoch_end", "(", "self", ",", "outputs", ")", ":", "# if returned a scalar from test_step, outputs is a list of tensor scalars", "# we return just the average in this case (if we want)", "# return torch.stack(outputs).mean()", "test_loss_mean", "=", "0", "test_acc_mean", "...
[ 22, 4 ]
[ 53, 21 ]
python
en
['en', 'error', 'th']
False
TestEpochEndVariations.test_epoch_end__multiple_dataloaders
(self, outputs)
Called at the end of test epoch to aggregate outputs :param outputs: list of individual outputs of each validation step :return:
Called at the end of test epoch to aggregate outputs :param outputs: list of individual outputs of each validation step :return:
def test_epoch_end__multiple_dataloaders(self, outputs): """ Called at the end of test epoch to aggregate outputs :param outputs: list of individual outputs of each validation step :return: """ # if returned a scalar from test_step, outputs is a list of tensor scalars ...
[ "def", "test_epoch_end__multiple_dataloaders", "(", "self", ",", "outputs", ")", ":", "# if returned a scalar from test_step, outputs is a list of tensor scalars", "# we return just the average in this case (if we want)", "# return torch.stack(outputs).mean()", "test_loss_mean", "=", "0", ...
[ 55, 4 ]
[ 89, 21 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_lightning_module
(tmpdir)
Test to ensure that a model wrapped in `LightningDeepSpeedModule` moves types and device correctly.
Test to ensure that a model wrapped in `LightningDeepSpeedModule` moves types and device correctly.
def test_deepspeed_lightning_module(tmpdir): """ Test to ensure that a model wrapped in `LightningDeepSpeedModule` moves types and device correctly. """ model = BoringModel() module = LightningDeepSpeedModule(model, precision=16) module.half() assert module.dtype == torch.half asse...
[ "def", "test_deepspeed_lightning_module", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "module", "=", "LightningDeepSpeedModule", "(", "model", ",", "precision", "=", "16", ")", "module", ".", "half", "(", ")", "assert", "module", ".", "dt...
[ 16, 0 ]
[ 30, 38 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_lightning_module_precision
(tmpdir)
Test to ensure that a model wrapped in `LightningDeepSpeedModule` moves tensors to half when precision 16.
Test to ensure that a model wrapped in `LightningDeepSpeedModule` moves tensors to half when precision 16.
def test_deepspeed_lightning_module_precision(tmpdir): """ Test to ensure that a model wrapped in `LightningDeepSpeedModule` moves tensors to half when precision 16. """ model = BoringModel() module = LightningDeepSpeedModule(model, precision=16) module.cuda().half() assert module.dtyp...
[ "def", "test_deepspeed_lightning_module_precision", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "module", "=", "LightningDeepSpeedModule", "(", "model", ",", "precision", "=", "16", ")", "module", ".", "cuda", "(", ")", ".", "half", "(", ...
[ 34, 0 ]
[ 53, 38 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_plugin_string
(tmpdir, input)
Test to ensure that the plugin can be passed via string or instance, and parallel devices is correctly set.
Test to ensure that the plugin can be passed via string or instance, and parallel devices is correctly set.
def test_deepspeed_plugin_string(tmpdir, input): """ Test to ensure that the plugin can be passed via string or instance, and parallel devices is correctly set. """ trainer = Trainer( fast_dev_run=True, default_root_dir=tmpdir, plugins=input if isinstance(input, str) else in...
[ "def", "test_deepspeed_plugin_string", "(", "tmpdir", ",", "input", ")", ":", "trainer", "=", "Trainer", "(", "fast_dev_run", "=", "True", ",", "default_root_dir", "=", "tmpdir", ",", "plugins", "=", "input", "if", "isinstance", "(", "input", ",", "str", ")"...
[ 84, 0 ]
[ 96, 93 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_plugin_env
(tmpdir, monkeypatch, deepspeed_config)
Test to ensure that the plugin can be passed via a string with an environment variable.
Test to ensure that the plugin can be passed via a string with an environment variable.
def test_deepspeed_plugin_env(tmpdir, monkeypatch, deepspeed_config): """ Test to ensure that the plugin can be passed via a string with an environment variable. """ config_path = os.path.join(tmpdir, 'temp.json') with open(config_path, 'w') as f: f.write(json.dumps(deepspeed_config)) ...
[ "def", "test_deepspeed_plugin_env", "(", "tmpdir", ",", "monkeypatch", ",", "deepspeed_config", ")", ":", "config_path", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'temp.json'", ")", "with", "open", "(", "config_path", ",", "'w'", ")", "as", ...
[ 100, 0 ]
[ 118, 44 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_precision_choice
(amp_backend, tmpdir)
Test to ensure precision plugin is also correctly chosen. DeepSpeed handles precision via Custom DeepSpeedPrecisionPlugin
Test to ensure precision plugin is also correctly chosen. DeepSpeed handles precision via Custom DeepSpeedPrecisionPlugin
def test_deepspeed_precision_choice(amp_backend, tmpdir): """ Test to ensure precision plugin is also correctly chosen. DeepSpeed handles precision via Custom DeepSpeedPrecisionPlugin """ trainer = Trainer( fast_dev_run=True, default_root_dir=tmpdir, plugins='deepspeed', amp_backend...
[ "def", "test_deepspeed_precision_choice", "(", "amp_backend", ",", "tmpdir", ")", ":", "trainer", "=", "Trainer", "(", "fast_dev_run", "=", "True", ",", "default_root_dir", "=", "tmpdir", ",", "plugins", "=", "'deepspeed'", ",", "amp_backend", "=", "amp_backend", ...
[ 129, 0 ]
[ 141, 63 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_with_invalid_config_path
(tmpdir)
Test to ensure if we pass an invalid config path we throw an exception.
Test to ensure if we pass an invalid config path we throw an exception.
def test_deepspeed_with_invalid_config_path(tmpdir): """ Test to ensure if we pass an invalid config path we throw an exception. """ with pytest.raises( MisconfigurationException, match="You passed in a path to a DeepSpeed config but the path does not exist" ): DeepSpeedPlugin(c...
[ "def", "test_deepspeed_with_invalid_config_path", "(", "tmpdir", ")", ":", "with", "pytest", ".", "raises", "(", "MisconfigurationException", ",", "match", "=", "\"You passed in a path to a DeepSpeed config but the path does not exist\"", ")", ":", "DeepSpeedPlugin", "(", "co...
[ 145, 0 ]
[ 153, 51 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_with_env_path
(tmpdir, monkeypatch, deepspeed_config)
Test to ensure if we pass an env variable, we load the config from the path.
Test to ensure if we pass an env variable, we load the config from the path.
def test_deepspeed_with_env_path(tmpdir, monkeypatch, deepspeed_config): """ Test to ensure if we pass an env variable, we load the config from the path. """ config_path = os.path.join(tmpdir, 'temp.json') with open(config_path, 'w') as f: f.write(json.dumps(deepspeed_config)) monkey...
[ "def", "test_deepspeed_with_env_path", "(", "tmpdir", ",", "monkeypatch", ",", "deepspeed_config", ")", ":", "config_path", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'temp.json'", ")", "with", "open", "(", "config_path", ",", "'w'", ")", "as"...
[ 157, 0 ]
[ 166, 44 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_defaults
(tmpdir)
Ensure that defaults are correctly set as a config for DeepSpeed if no arguments are passed.
Ensure that defaults are correctly set as a config for DeepSpeed if no arguments are passed.
def test_deepspeed_defaults(tmpdir): """ Ensure that defaults are correctly set as a config for DeepSpeed if no arguments are passed. """ plugin = DeepSpeedPlugin() assert plugin.config is not None assert isinstance(plugin.config["zero_optimization"], dict)
[ "def", "test_deepspeed_defaults", "(", "tmpdir", ")", ":", "plugin", "=", "DeepSpeedPlugin", "(", ")", "assert", "plugin", ".", "config", "is", "not", "None", "assert", "isinstance", "(", "plugin", ".", "config", "[", "\"zero_optimization\"", "]", ",", "dict",...
[ 170, 0 ]
[ 176, 63 ]
python
en
['en', 'error', 'th']
False
test_invalid_deepspeed_defaults_no_precision
(tmpdir)
Test to ensure that using defaults, if precision is not set to 16, we throw an exception.
Test to ensure that using defaults, if precision is not set to 16, we throw an exception.
def test_invalid_deepspeed_defaults_no_precision(tmpdir): """ Test to ensure that using defaults, if precision is not set to 16, we throw an exception. """ model = BoringModel() trainer = Trainer( fast_dev_run=True, default_root_dir=tmpdir, plugins='deepspeed', ) ...
[ "def", "test_invalid_deepspeed_defaults_no_precision", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "fast_dev_run", "=", "True", ",", "default_root_dir", "=", "tmpdir", ",", "plugins", "=", "'deepspeed'", ",", "...
[ 180, 0 ]
[ 193, 26 ]
python
en
['en', 'error', 'th']
False
test_warn_deepspeed_override_backward
(tmpdir)
Test to ensure that if the backward hook in the LightningModule is overridden, we throw a warning.
Test to ensure that if the backward hook in the LightningModule is overridden, we throw a warning.
def test_warn_deepspeed_override_backward(tmpdir): """ Test to ensure that if the backward hook in the LightningModule is overridden, we throw a warning. """ class TestModel(BoringModel): def backward(self, loss: Tensor, optimizer: Optimizer, optimizer_idx: int, *args, **kwargs) -> None: ...
[ "def", "test_warn_deepspeed_override_backward", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "backward", "(", "self", ",", "loss", ":", "Tensor", ",", "optimizer", ":", "Optimizer", ",", "optimizer_idx", ":", "int", ",", ...
[ 198, 0 ]
[ 211, 26 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_run_configure_optimizers
(tmpdir)
Test end to end that deepspeed works with defaults (without ZeRO as that requires compilation), whilst using configure_optimizers for optimizers and schedulers.
Test end to end that deepspeed works with defaults (without ZeRO as that requires compilation), whilst using configure_optimizers for optimizers and schedulers.
def test_deepspeed_run_configure_optimizers(tmpdir): """ Test end to end that deepspeed works with defaults (without ZeRO as that requires compilation), whilst using configure_optimizers for optimizers and schedulers. """ class TestModel(BoringModel): def on_train_start(self) -> No...
[ "def", "test_deepspeed_run_configure_optimizers", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "on_train_start", "(", "self", ")", "->", "None", ":", "from", "deepspeed", ".", "runtime", ".", "zero", ".", "stage2", "impor...
[ 216, 0 ]
[ 244, 55 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_config
(tmpdir, deepspeed_zero_config)
Test to ensure deepspeed works correctly when passed a DeepSpeed config object including optimizers/schedulers and saves the model weights to load correctly.
Test to ensure deepspeed works correctly when passed a DeepSpeed config object including optimizers/schedulers and saves the model weights to load correctly.
def test_deepspeed_config(tmpdir, deepspeed_zero_config): """ Test to ensure deepspeed works correctly when passed a DeepSpeed config object including optimizers/schedulers and saves the model weights to load correctly. """ class TestModel(BoringModel): def on_train_start(self) -> ...
[ "def", "test_deepspeed_config", "(", "tmpdir", ",", "deepspeed_zero_config", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "on_train_start", "(", "self", ")", "->", "None", ":", "from", "deepspeed", ".", "runtime", ".", "lr_schedules", "...
[ 249, 0 ]
[ 279, 55 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_custom_precision_params
(tmpdir)
Ensure if we modify the FP16 parameters via the DeepSpeedPlugin, the deepspeed config contains these changes.
Ensure if we modify the FP16 parameters via the DeepSpeedPlugin, the deepspeed config contains these changes.
def test_deepspeed_custom_precision_params(tmpdir): """ Ensure if we modify the FP16 parameters via the DeepSpeedPlugin, the deepspeed config contains these changes. """ class TestModel(BoringModel): def on_train_start(self) -> None: assert self.trainer.training_type_plugin.con...
[ "def", "test_deepspeed_custom_precision_params", "(", "tmpdir", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "on_train_start", "(", "self", ")", "->", "None", ":", "assert", "self", ".", "trainer", ".", "training_type_plugin", ".", "confi...
[ 284, 0 ]
[ 310, 26 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_assert_config_zero_offload_disabled
(tmpdir, deepspeed_zero_config)
Ensure if we use a config and turn off cpu_offload, that this is set to False within the config.
Ensure if we use a config and turn off cpu_offload, that this is set to False within the config.
def test_deepspeed_assert_config_zero_offload_disabled(tmpdir, deepspeed_zero_config): """ Ensure if we use a config and turn off cpu_offload, that this is set to False within the config. """ deepspeed_zero_config['zero_optimization']['cpu_offload'] = False class TestModel(BoringModel): ...
[ "def", "test_deepspeed_assert_config_zero_offload_disabled", "(", "tmpdir", ",", "deepspeed_zero_config", ")", ":", "deepspeed_zero_config", "[", "'zero_optimization'", "]", "[", "'cpu_offload'", "]", "=", "False", "class", "TestModel", "(", "BoringModel", ")", ":", "de...
[ 315, 0 ]
[ 331, 26 ]
python
en
['en', 'error', 'th']
False
test_deepspeed_multigpu
(tmpdir, deepspeed_config)
Test to ensure that DeepSpeed with multiple GPUs works, without ZeRO Optimization as this requires compilation.
Test to ensure that DeepSpeed with multiple GPUs works, without ZeRO Optimization as this requires compilation.
def test_deepspeed_multigpu(tmpdir, deepspeed_config): """ Test to ensure that DeepSpeed with multiple GPUs works, without ZeRO Optimization as this requires compilation. """ model = BoringModel() trainer = Trainer( plugins=[DeepSpeedPlugin()], default_root_dir=tmpdir, gp...
[ "def", "test_deepspeed_multigpu", "(", "tmpdir", ",", "deepspeed_config", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "plugins", "=", "[", "DeepSpeedPlugin", "(", ")", "]", ",", "default_root_dir", "=", "tmpdir", ",", "gp...
[ 340, 0 ]
[ 355, 55 ]
python
en
['en', 'error', 'th']
False
test_lightning_wrapper_module_methods
(wrapper_class)
Test that the LightningWrapper redirects .forward() to the LightningModule methods.
Test that the LightningWrapper redirects .forward() to the LightningModule methods.
def test_lightning_wrapper_module_methods(wrapper_class): """ Test that the LightningWrapper redirects .forward() to the LightningModule methods. """ pl_module = MagicMock() wrapped_module = wrapper_class(pl_module) batch = torch.rand(5) batch_idx = 3 pl_module.running_stage = RunningStage.TRA...
[ "def", "test_lightning_wrapper_module_methods", "(", "wrapper_class", ")", ":", "pl_module", "=", "MagicMock", "(", ")", "wrapped_module", "=", "wrapper_class", "(", "pl_module", ")", "batch", "=", "torch", ".", "rand", "(", "5", ")", "batch_idx", "=", "3", "p...
[ 21, 0 ]
[ 43, 47 ]
python
en
['en', 'no', 'en']
True
test_lightning_wrapper_module_warn_none_output
(wrapper_class)
Test that the LightningWrapper module warns about forgotten return statement.
Test that the LightningWrapper module warns about forgotten return statement.
def test_lightning_wrapper_module_warn_none_output(wrapper_class): """ Test that the LightningWrapper module warns about forgotten return statement. """ warning_cache.clear() pl_module = MagicMock() wrapped_module = wrapper_class(pl_module) pl_module.training_step.return_value = None pl_module....
[ "def", "test_lightning_wrapper_module_warn_none_output", "(", "wrapper_class", ")", ":", "warning_cache", ".", "clear", "(", ")", "pl_module", "=", "MagicMock", "(", ")", "wrapped_module", "=", "wrapper_class", "(", "pl_module", ")", "pl_module", ".", "training_step",...
[ 50, 0 ]
[ 75, 25 ]
python
en
['en', 'en', 'en']
True
test_unsqueeze_scalar_tensor
(inp, expected)
Test that the utility function unsqueezes only scalar tensors.
Test that the utility function unsqueezes only scalar tensors.
def test_unsqueeze_scalar_tensor(inp, expected): """ Test that the utility function unsqueezes only scalar tensors. """ assert torch.all(unsqueeze_scalar_tensor(inp).eq(expected))
[ "def", "test_unsqueeze_scalar_tensor", "(", "inp", ",", "expected", ")", ":", "assert", "torch", ".", "all", "(", "unsqueeze_scalar_tensor", "(", "inp", ")", ".", "eq", "(", "expected", ")", ")" ]
[ 85, 0 ]
[ 87, 63 ]
python
en
['en', 'en', 'en']
True
test_lightning_parallel_module_unsqueeze_scalar
()
Test that LightningParallelModule takes care of un-squeezeing 0-dim tensors.
Test that LightningParallelModule takes care of un-squeezeing 0-dim tensors.
def test_lightning_parallel_module_unsqueeze_scalar(): """ Test that LightningParallelModule takes care of un-squeezeing 0-dim tensors. """ class TestModel(BoringModel): def training_step(self, batch, batch_idx): output = super().training_step(batch, batch_idx) loss = output["l...
[ "def", "test_lightning_parallel_module_unsqueeze_scalar", "(", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "output", "=", "super", "(", ")", ".", "training_step", ...
[ 91, 0 ]
[ 120, 21 ]
python
en
['en', 'en', 'en']
True
test_lightning_parallel_module_python_scalar_conversion
(device)
Test that LightningParallelModule can convert Python scalars to tensors.
Test that LightningParallelModule can convert Python scalars to tensors.
def test_lightning_parallel_module_python_scalar_conversion(device): """ Test that LightningParallelModule can convert Python scalars to tensors. """ class TestModel(BoringModel): def training_step(self, batch, batch_idx): output = super().training_step(batch, batch_idx) # PyTo...
[ "def", "test_lightning_parallel_module_python_scalar_conversion", "(", "device", ")", ":", "class", "TestModel", "(", "BoringModel", ")", ":", "def", "training_step", "(", "self", ",", "batch", ",", "batch_idx", ")", ":", "output", "=", "super", "(", ")", ".", ...
[ 136, 0 ]
[ 156, 73 ]
python
en
['en', 'en', 'en']
True
proto_file_canonical_from_label
(label)
Compute path from API root to a proto file from a Bazel proto label. Args: label: Bazel source proto label string. Returns: A string with the path, e.g. for @envoy_api//envoy/type/matcher:metadata.proto this would be envoy/type/matcher/matcher.proto.
Compute path from API root to a proto file from a Bazel proto label.
def proto_file_canonical_from_label(label): """Compute path from API root to a proto file from a Bazel proto label. Args: label: Bazel source proto label string. Returns: A string with the path, e.g. for @envoy_api//envoy/type/matcher:metadata.proto this would be envoy/type/matcher...
[ "def", "proto_file_canonical_from_label", "(", "label", ")", ":", "assert", "(", "label", ".", "startswith", "(", "'@envoy_api_canonical//'", ")", ")", "return", "label", "[", "len", "(", "'@envoy_api_canonical//'", ")", ":", "]", ".", "replace", "(", "':'", "...
[ 3, 0 ]
[ 14, 66 ]
python
en
['en', 'en', 'en']
True
bazel_bin_path_for_output_artifact
(label, suffix, root='')
Find the location in bazel-bin/ for an api_proto_plugin output file. Args: label: Bazel source proto label string. suffix: output suffix for the artifact from label, e.g. ".types.pb_text". root: location of bazel-bin/, if not specified, PWD. Returns: Path in bazel-bin/external/...
Find the location in bazel-bin/ for an api_proto_plugin output file.
def bazel_bin_path_for_output_artifact(label, suffix, root=''): """Find the location in bazel-bin/ for an api_proto_plugin output file. Args: label: Bazel source proto label string. suffix: output suffix for the artifact from label, e.g. ".types.pb_text". root: location of bazel-bin/, i...
[ "def", "bazel_bin_path_for_output_artifact", "(", "label", ",", "suffix", ",", "root", "=", "''", ")", ":", "proto_file_path", "=", "proto_file_canonical_from_label", "(", "label", ")", "return", "os", ".", "path", ".", "join", "(", "root", ",", "'bazel-bin/exte...
[ 17, 0 ]
[ 31, 33 ]
python
en
['en', 'en', 'en']
True
export_rule_data
(variables, actions)
export_rule_data is used to export all information about the variables, actions, and operators to the client. This will return a dictionary with three keys: - variables: a list of all available variables along with their label, type and options - actions: a list of all actions along with their label and...
export_rule_data is used to export all information about the variables, actions, and operators to the client. This will return a dictionary with three keys: - variables: a list of all available variables along with their label, type and options - actions: a list of all actions along with their label and...
def export_rule_data(variables, actions): """export_rule_data is used to export all information about the variables, actions, and operators to the client. This will return a dictionary with three keys: - variables: a list of all available variables along with their label, type and options - actions:...
[ "def", "export_rule_data", "(", "variables", ",", "actions", ")", ":", "from", ".", "import", "operators", "actions_data", "=", "actions", ".", "get_all_actions", "(", ")", "variables_data", "=", "variables", ".", "get_all_variables", "(", ")", "variable_type_oper...
[ 10, 0 ]
[ 27, 117 ]
python
en
['en', 'en', 'en']
True
float_to_decimal
(f)
Convert a floating point number to a Decimal with no loss of information. Intended for Python 2.6 where casting float to Decimal does not work.
Convert a floating point number to a Decimal with no loss of information. Intended for Python 2.6 where casting float to Decimal does not work.
def float_to_decimal(f): """ Convert a floating point number to a Decimal with no loss of information. Intended for Python 2.6 where casting float to Decimal does not work. """ n, d = f.as_integer_ratio() numerator, denominator = Decimal(n), Decimal(d) ctx = Context(prec=60) result =...
[ "def", "float_to_decimal", "(", "f", ")", ":", "n", ",", "d", "=", "f", ".", "as_integer_ratio", "(", ")", "numerator", ",", "denominator", "=", "Decimal", "(", "n", ")", ",", "Decimal", "(", "d", ")", "ctx", "=", "Context", "(", "prec", "=", "60",...
[ 30, 0 ]
[ 44, 17 ]
python
en
['en', 'error', 'th']
False
XPSSpectrum.background_bounds
(self, value)
Only even-length numeral sequence-types are valid.
Only even-length numeral sequence-types are valid.
def background_bounds(self, value): """Only even-length numeral sequence-types are valid.""" if len(value) % 2 != 0: raise ValueError("Background bounds must be pairwise.") self._background_bounds = np.sort(np.array(value)) - self._energy_calibration self._background_bounds =...
[ "def", "background_bounds", "(", "self", ",", "value", ")", ":", "if", "len", "(", "value", ")", "%", "2", "!=", "0", ":", "raise", "ValueError", "(", "\"Background bounds must be pairwise.\"", ")", "self", ".", "_background_bounds", "=", "np", ".", "sort", ...
[ 153, 4 ]
[ 161, 87 ]
python
en
['en', 'en', 'en']
True
ModeledSpectrum.peaks
(self)
Returns peaks.
Returns peaks.
def peaks(self): """Returns peaks.""" return self._peaks.copy()
[ "def", "peaks", "(", "self", ")", ":", "return", "self", ".", "_peaks", ".", "copy", "(", ")" ]
[ 172, 4 ]
[ 174, 33 ]
python
en
['lv', 'et', 'en']
False
ModeledSpectrum.fit_intensity
(self)
Returns fit result on whole energy range.
Returns fit result on whole energy range.
def fit_intensity(self): """Returns fit result on whole energy range.""" with processing.IgnoreUnderflow(): fit = self.model.eval(params=self.params, x=self.energy) try: if fit.shape == self.energy.shape: return fit except AttributeError: ...
[ "def", "fit_intensity", "(", "self", ")", ":", "with", "processing", ".", "IgnoreUnderflow", "(", ")", ":", "fit", "=", "self", ".", "model", ".", "eval", "(", "params", "=", "self", ".", "params", ",", "x", "=", "self", ".", "energy", ")", "try", ...
[ 177, 4 ]
[ 186, 41 ]
python
en
['en', 'en', 'en']
True
ModeledSpectrum.fit_intensity_at_E
(self, energy)
Returns model intensity at given energy.
Returns model intensity at given energy.
def fit_intensity_at_E(self, energy): """Returns model intensity at given energy.""" energy = np.array([energy]) with processing.IgnoreUnderflow(): fit = self.model.eval(params=self.params, x=energy) return fit
[ "def", "fit_intensity_at_E", "(", "self", ",", "energy", ")", ":", "energy", "=", "np", ".", "array", "(", "[", "energy", "]", ")", "with", "processing", ".", "IgnoreUnderflow", "(", ")", ":", "fit", "=", "self", ".", "model", ".", "eval", "(", "para...
[ 188, 4 ]
[ 193, 18 ]
python
en
['en', 'en', 'en']
True
ModeledSpectrum.residual
(self)
Returns the fit residual.
Returns the fit residual.
def residual(self): """Returns the fit residual.""" return self.intensity - self.background - self.fit_intensity
[ "def", "residual", "(", "self", ")", ":", "return", "self", ".", "intensity", "-", "self", ".", "background", "-", "self", ".", "fit_intensity" ]
[ 196, 4 ]
[ 198, 68 ]
python
en
['en', 'en', 'en']
True
ModeledSpectrum.model
(self)
Returns the sum of all peak models.
Returns the sum of all peak models.
def model(self): """Returns the sum of all peak models.""" model = ConstantModel(prefix="BASE_") model.set_param_hint("c", vary=False, value=0) self.params += model.make_params() for peak in self._peaks: model += peak.model return model
[ "def", "model", "(", "self", ")", ":", "model", "=", "ConstantModel", "(", "prefix", "=", "\"BASE_\"", ")", "model", ".", "set_param_hint", "(", "\"c\"", ",", "vary", "=", "False", ",", "value", "=", "0", ")", "self", ".", "params", "+=", "model", "....
[ 201, 4 ]
[ 209, 20 ]
python
en
['en', 'la', 'en']
True
ModeledSpectrum.do_fit
(self)
Returns the fitted cps values.
Returns the fitted cps values.
def do_fit(self): """Returns the fitted cps values.""" with processing.IgnoreUnderflow(): result = self.model.fit( self.intensity - self.background, self.params, x=self.energy ) self.params.update(result.params)
[ "def", "do_fit", "(", "self", ")", ":", "with", "processing", ".", "IgnoreUnderflow", "(", ")", ":", "result", "=", "self", ".", "model", ".", "fit", "(", "self", ".", "intensity", "-", "self", ".", "background", ",", "self", ".", "params", ",", "x",...
[ 211, 4 ]
[ 219, 41 ]
python
en
['en', 'en', 'en']
True
ModeledSpectrum.add_peak
(self, name, **kwargs)
Add a peak with given parameters. Valid parameters: area, fwhm, position and model specific parameters: PseudoVoigt: fraction, gausswidth
Add a peak with given parameters. Valid parameters: area, fwhm, position and model specific parameters: PseudoVoigt: fraction, gausswidth
def add_peak(self, name, **kwargs): """ Add a peak with given parameters. Valid parameters: area, fwhm, position and model specific parameters: PseudoVoigt: fraction, gausswidth """ if name in [peak.name for peak in self._peaks]: raise ValueError("Peak alr...
[ "def", "add_peak", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "if", "name", "in", "[", "peak", ".", "name", "for", "peak", "in", "self", ".", "_peaks", "]", ":", "raise", "ValueError", "(", "\"Peak already exists\"", ")", "if", "\"f...
[ 221, 4 ]
[ 247, 19 ]
python
en
['en', 'error', 'th']
False
ModeledSpectrum.remove_peak
(self, peak)
Remove a peak specified by its name.
Remove a peak specified by its name.
def remove_peak(self, peak): """Remove a peak specified by its name.""" peak.clear_params() self._peaks.remove(peak)
[ "def", "remove_peak", "(", "self", ",", "peak", ")", ":", "peak", ".", "clear_params", "(", ")", "self", ".", "_peaks", ".", "remove", "(", "peak", ")" ]
[ 249, 4 ]
[ 252, 32 ]
python
en
['en', 'en', 'en']
True
Peak.get_param
(self, param_alias, use_alias=True)
Shortcut for getting the Parameter object by the param alias.
Shortcut for getting the Parameter object by the param alias.
def get_param(self, param_alias, use_alias=True): """Shortcut for getting the Parameter object by the param alias.""" if use_alias: aliases = {**self._default_aliases, **self.param_aliases} param_name = aliases.get(param_alias, param_alias) if param_name is None: ...
[ "def", "get_param", "(", "self", ",", "param_alias", ",", "use_alias", "=", "True", ")", ":", "if", "use_alias", ":", "aliases", "=", "{", "*", "*", "self", ".", "_default_aliases", ",", "*", "*", "self", ".", "param_aliases", "}", "param_name", "=", "...
[ 380, 4 ]
[ 387, 55 ]
python
en
['en', 'en', 'en']
True
Peak.clear_params
(self)
Clear this peaks' parameters from the model.
Clear this peaks' parameters from the model.
def clear_params(self): """Clear this peaks' parameters from the model.""" pars_to_del = [ par for par in self.params if re.match(fr"{self.name}_[a-z]+", par) ] for par in pars_to_del: self.params.pop(par)
[ "def", "clear_params", "(", "self", ")", ":", "pars_to_del", "=", "[", "par", "for", "par", "in", "self", ".", "params", "if", "re", ".", "match", "(", "fr\"{self.name}_[a-z]+\"", ",", "par", ")", "]", "for", "par", "in", "pars_to_del", ":", "self", "....
[ 389, 4 ]
[ 396, 32 ]
python
en
['en', 'en', 'en']
True
Peak.set_constraints
(self, param_alias, **new)
Sets a constraint for param. Valid keys: value, vary, min, max, expr
Sets a constraint for param. Valid keys: value, vary, min, max, expr
def set_constraints(self, param_alias, **new): """Sets a constraint for param. Valid keys: value, vary, min, max, expr""" try: param = self.get_param(param_alias) except ValueError: return old = self.get_constraints(param_alias) # enforce min=0 fo...
[ "def", "set_constraints", "(", "self", ",", "param_alias", ",", "*", "*", "new", ")", ":", "try", ":", "param", "=", "self", ".", "get_param", "(", "param_alias", ")", "except", "ValueError", ":", "return", "old", "=", "self", ".", "get_constraints", "("...
[ 398, 4 ]
[ 425, 56 ]
python
en
['en', 'sv', 'en']
True
Peak.get_constraints
(self, param_alias)
Returns a string containing min/max or expr.
Returns a string containing min/max or expr.
def get_constraints(self, param_alias): """Returns a string containing min/max or expr.""" try: param = self.get_param(param_alias) except ValueError: return self._default_constraints constraints = { "value": param.value, "min": param.min, ...
[ "def", "get_constraints", "(", "self", ",", "param_alias", ")", ":", "try", ":", "param", "=", "self", ".", "get_param", "(", "param_alias", ")", "except", "ValueError", ":", "return", "self", ".", "_default_constraints", "constraints", "=", "{", "\"value\"", ...
[ 427, 4 ]
[ 440, 26 ]
python
en
['en', 'en', 'en']
True
Peak.expr2relation
(self, expr)
Translates technical expr string into a human-readable relation.
Translates technical expr string into a human-readable relation.
def expr2relation(self, expr): """Translates technical expr string into a human-readable relation.""" if expr is None: return "" def param_repl(matchobj): """Replaces 'peakname_param' by 'peakname'""" param_key = matchobj.group(0) name = param_key....
[ "def", "expr2relation", "(", "self", ",", "expr", ")", ":", "if", "expr", "is", "None", ":", "return", "\"\"", "def", "param_repl", "(", "matchobj", ")", ":", "\"\"\"Replaces 'peakname_param' by 'peakname'\"\"\"", "param_key", "=", "matchobj", ".", "group", "(",...
[ 442, 4 ]
[ 455, 23 ]
python
en
['en', 'en', 'en']
True
Peak.relation2expr
(self, relation, param_alias)
Translates a human-readable arithmetic relation to an expr string.
Translates a human-readable arithmetic relation to an expr string.
def relation2expr(self, relation, param_alias): """Translates a human-readable arithmetic relation to an expr string.""" def name_repl(matchobj): """Replaces 'peakname' by 'peakname_param' (searches case-insensitive).""" name = matchobj.group(0) name = name.upper() ...
[ "def", "relation2expr", "(", "self", ",", "relation", ",", "param_alias", ")", ":", "def", "name_repl", "(", "matchobj", ")", ":", "\"\"\"Replaces 'peakname' by 'peakname_param' (searches case-insensitive).\"\"\"", "name", "=", "matchobj", ".", "group", "(", "0", ")",...
[ 457, 4 ]
[ 473, 19 ]
python
en
['en', 'en', 'en']
True
Peak.get_measured_area
(self)
Returns measured area under the peak.
Returns measured area under the peak.
def get_measured_area(self): """Returns measured area under the peak.""" return self._model.get_area(self.params)
[ "def", "get_measured_area", "(", "self", ")", ":", "return", "self", ".", "_model", ".", "get_area", "(", "self", ".", "params", ")" ]
[ 475, 4 ]
[ 477, 48 ]
python
en
['en', 'la', 'en']
True
Peak.get_measured_fwhm
(self)
Returns measured fwhm of the peak.
Returns measured fwhm of the peak.
def get_measured_fwhm(self): """Returns measured fwhm of the peak.""" return self._model.get_fwhm(self.params)
[ "def", "get_measured_fwhm", "(", "self", ")", ":", "return", "self", ".", "_model", ".", "get_fwhm", "(", "self", ".", "params", ")" ]
[ 479, 4 ]
[ 481, 48 ]
python
en
['en', 'no', 'en']
True
dimension_sub_dag
(parent_dag_name, child_dag_name, start_date, schedule_interval, redshift_conn_id, table_query_dict, append)
This function acts as a factory for creating dags for loading dimension tables Parameters: ----------- parent_dag_name (str): parent dag name child_dag_name (str): child dag name start_date (datetime): dag start time schedule_interval: dag schedule interval redshift_conn_id (str): RedS...
This function acts as a factory for creating dags for loading dimension tables Parameters: ----------- parent_dag_name (str): parent dag name child_dag_name (str): child dag name start_date (datetime): dag start time schedule_interval: dag schedule interval redshift_conn_id (str): RedS...
def dimension_sub_dag(parent_dag_name, child_dag_name, start_date, schedule_interval, redshift_conn_id, table_query_dict, append): """This function acts as a factory for creating dags for loading dimension tables Parameters: ----------- parent_dag_name (str): parent dag name child_dag_name (str...
[ "def", "dimension_sub_dag", "(", "parent_dag_name", ",", "child_dag_name", ",", "start_date", ",", "schedule_interval", ",", "redshift_conn_id", ",", "table_query_dict", ",", "append", ")", ":", "dag", "=", "DAG", "(", "'%s.%s'", "%", "(", "parent_dag_name", ",", ...
[ 5, 0 ]
[ 39, 14 ]
python
en
['en', 'en', 'en']
True
OperatorsClassTests.test_get_all_operators
(self)
Returns a dictionary listing all the operators on the class that can be called on that type, with some data about them.
Returns a dictionary listing all the operators on the class that can be called on that type, with some data about them.
def test_get_all_operators(self): """Returns a dictionary listing all the operators on the class that can be called on that type, with some data about them. """ class SomeType(BaseType): @type_operator(input_type='text') def some_operator(self): r...
[ "def", "test_get_all_operators", "(", "self", ")", ":", "class", "SomeType", "(", "BaseType", ")", ":", "@", "type_operator", "(", "input_type", "=", "'text'", ")", "def", "some_operator", "(", "self", ")", ":", "return", "True", "def", "not_an_operator", "(...
[ 13, 4 ]
[ 31, 61 ]
python
en
['en', 'en', 'en']
True
OperatorsClassTests.test_operator_decorator_casts_argument
(self)
Any operator that has the @type_operator decorator should call _assert_valid_value_and_cast on the parameter.
Any operator that has the
def test_operator_decorator_casts_argument(self): """Any operator that has the @type_operator decorator should call _assert_valid_value_and_cast on the parameter. """ class SomeType(BaseType): def __init__(self, value): self.value = value _assert...
[ "def", "test_operator_decorator_casts_argument", "(", "self", ")", ":", "class", "SomeType", "(", "BaseType", ")", ":", "def", "__init__", "(", "self", ",", "value", ")", ":", "self", ".", "value", "=", "value", "_assert_valid_value_and_cast", "=", "MagicMock", ...
[ 33, 4 ]
[ 66, 78 ]
python
en
['en', 'en', 'en']
True
Clustering.perform_kmeans
(X: pd.DataFrame, **kwargs)
Wrap in Clustering class which performs Kmeans algorithm. :param X: Dataset with samples :type X: pd.DataFrame :return: Inertias from data samples to clusters :rtype: dict
Wrap in Clustering class which performs Kmeans algorithm.
def perform_kmeans(X: pd.DataFrame, **kwargs): """Wrap in Clustering class which performs Kmeans algorithm. :param X: Dataset with samples :type X: pd.DataFrame :return: Inertias from data samples to clusters :rtype: dict """ k_list = np.arange(1, len(X.columns) ...
[ "def", "perform_kmeans", "(", "X", ":", "pd", ".", "DataFrame", ",", "*", "*", "kwargs", ")", ":", "k_list", "=", "np", ".", "arange", "(", "1", ",", "len", "(", "X", ".", "columns", ")", "+", "1", ")", "inertia_dic", "=", "{", "}", "for", "k",...
[ 15, 4 ]
[ 28, 26 ]
python
en
['en', 'en', 'en']
True
Clustering.perform_DBSCAN
(X: pd.DataFrame, **kwargs)
Wrap in Clustering class which performs. :param X: Dataset with samples :type X: pd.DataFrame :return: Distances for all data to its k-nearest-neighbor :rtype: list
Wrap in Clustering class which performs.
def perform_DBSCAN(X: pd.DataFrame, **kwargs): """Wrap in Clustering class which performs. :param X: Dataset with samples :type X: pd.DataFrame :return: Distances for all data to its k-nearest-neighbor :rtype: list """ neighbors = NearestNeighbors(n_neighbors=2 *...
[ "def", "perform_DBSCAN", "(", "X", ":", "pd", ".", "DataFrame", ",", "*", "*", "kwargs", ")", ":", "neighbors", "=", "NearestNeighbors", "(", "n_neighbors", "=", "2", "*", "len", "(", "X", ".", "columns", ")", ")", "neighbors_fit", "=", "neighbors", "....
[ 31, 4 ]
[ 44, 24 ]
python
en
['en', 'en', 'en']
True
find_functions
(filename, tag='API')
Scan the file, looking for tagged functions. Assuming ``tag=='API'``, a tagged function looks like:: /*API*/ static returntype* function_name(argtype1 arg1, argtype2 arg2) { } where the return type must be on a separate line, the function name must start the l...
Scan the file, looking for tagged functions.
def find_functions(filename, tag='API'): """ Scan the file, looking for tagged functions. Assuming ``tag=='API'``, a tagged function looks like:: /*API*/ static returntype* function_name(argtype1 arg1, argtype2 arg2) { } where the return type must be on a separ...
[ "def", "find_functions", "(", "filename", ",", "tag", "=", "'API'", ")", ":", "fo", "=", "open", "(", "filename", ",", "'r'", ")", "functions", "=", "[", "]", "return_type", "=", "None", "function_name", "=", "None", "function_args", "=", "[", "]", "do...
[ 195, 0 ]
[ 277, 20 ]
python
en
['en', 'error', 'th']
False
write_file
(filename, data)
Write data to filename Only write changed data to avoid updating timestamps unnecessarily
Write data to filename Only write changed data to avoid updating timestamps unnecessarily
def write_file(filename, data): """ Write data to filename Only write changed data to avoid updating timestamps unnecessarily """ if os.path.exists(filename): with open(filename) as f: if data == f.read(): return with open(filename, 'w') as fid: fid.w...
[ "def", "write_file", "(", "filename", ",", "data", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "with", "open", "(", "filename", ")", "as", "f", ":", "if", "data", "==", "f", ".", "read", "(", ")", ":", "return", ...
[ 289, 0 ]
[ 300, 23 ]
python
en
['en', 'error', 'th']
False
order_dict
(d)
Order dict by its values.
Order dict by its values.
def order_dict(d): """Order dict by its values.""" o = list(d.items()) def _key(x): return x[1] + (x[0],) return sorted(o, key=_key)
[ "def", "order_dict", "(", "d", ")", ":", "o", "=", "list", "(", "d", ".", "items", "(", ")", ")", "def", "_key", "(", "x", ")", ":", "return", "x", "[", "1", "]", "+", "(", "x", "[", "0", "]", ",", ")", "return", "sorted", "(", "o", ",", ...
[ 409, 0 ]
[ 414, 30 ]
python
en
['en', 'en', 'en']
True
check_api_dict
(d)
Check that an api dict is valid (does not use the same index twice).
Check that an api dict is valid (does not use the same index twice).
def check_api_dict(d): """Check that an api dict is valid (does not use the same index twice).""" # remove the extra value fields that aren't the index index_d = {k: v[0] for k, v in d.items()} # We have if a same index is used twice: we 'revert' the dict so that index # become keys. If the length ...
[ "def", "check_api_dict", "(", "d", ")", ":", "# remove the extra value fields that aren't the index", "index_d", "=", "{", "k", ":", "v", "[", "0", "]", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", "}", "# We have if a same index is used twice: we 'r...
[ 424, 0 ]
[ 455, 29 ]
python
en
['en', 'en', 'en']
True
get_api_functions
(tagname, api_dict)
Parse source files to get functions tagged by the given tag.
Parse source files to get functions tagged by the given tag.
def get_api_functions(tagname, api_dict): """Parse source files to get functions tagged by the given tag.""" functions = [] for f in API_FILES: functions.extend(find_functions(f, tagname)) dfunctions = [(api_dict[func.name][0], func) for func in functions] dfunctions.sort() return [a[1] ...
[ "def", "get_api_functions", "(", "tagname", ",", "api_dict", ")", ":", "functions", "=", "[", "]", "for", "f", "in", "API_FILES", ":", "functions", ".", "extend", "(", "find_functions", "(", "f", ",", "tagname", ")", ")", "dfunctions", "=", "[", "(", "...
[ 457, 0 ]
[ 464, 37 ]
python
en
['en', 'en', 'en']
True
fullapi_hash
(api_dicts)
Given a list of api dicts defining the numpy C API, compute a checksum of the list of items in the API (as a string).
Given a list of api dicts defining the numpy C API, compute a checksum of the list of items in the API (as a string).
def fullapi_hash(api_dicts): """Given a list of api dicts defining the numpy C API, compute a checksum of the list of items in the API (as a string).""" a = [] for d in api_dicts: for name, data in order_dict(d): a.extend(name) a.extend(','.join(map(str, data))) retu...
[ "def", "fullapi_hash", "(", "api_dicts", ")", ":", "a", "=", "[", "]", "for", "d", "in", "api_dicts", ":", "for", "name", ",", "data", "in", "order_dict", "(", "d", ")", ":", "a", ".", "extend", "(", "name", ")", "a", ".", "extend", "(", "','", ...
[ 466, 0 ]
[ 475, 62 ]
python
en
['en', 'en', 'en']
True
BaseDiscriminator._check
(self)
Check input to avoid ValueError.
Check input to avoid ValueError.
def _check(self): """Check input to avoid ValueError.""" if not isinstance(self.fc_layers, tuple): raise TypeError(f'fc_layers require tuple, ' f'get {type(self.fc_layers)}') if not isinstance(self.use_dropout, tuple): raise TypeError(f'use_dr...
[ "def", "_check", "(", "self", ")", ":", "if", "not", "isinstance", "(", "self", ".", "fc_layers", ",", "tuple", ")", ":", "raise", "TypeError", "(", "f'fc_layers require tuple, '", "f'get {type(self.fc_layers)}'", ")", "if", "not", "isinstance", "(", "self", "...
[ 37, 4 ]
[ 67, 33 ]
python
en
['en', 'fi', 'en']
True
BaseDiscriminator.create_layers
(self)
Create layers.
Create layers.
def create_layers(self): """Create layers.""" l_fc_layer = len(self.fc_layers) l_use_drop = len(self.use_dropout) l_use_activation = len(self.use_activation) self.fc_blocks = nn.Sequential() for i in range(l_fc_layer - 1): self.fc_blocks.add_module( ...
[ "def", "create_layers", "(", "self", ")", ":", "l_fc_layer", "=", "len", "(", "self", ".", "fc_layers", ")", "l_use_drop", "=", "len", "(", "self", ".", "use_dropout", ")", "l_use_activation", "=", "len", "(", "self", ".", "use_activation", ")", "self", ...
[ 69, 4 ]
[ 91, 59 ]
python
en
['es', 'tg', 'en']
False
BaseDiscriminator.forward
(self, inputs)
Forward function.
Forward function.
def forward(self, inputs): """Forward function.""" msg = 'the base class [BaseDiscriminator] is not callable!' raise NotImplementedError(msg)
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "msg", "=", "'the base class [BaseDiscriminator] is not callable!'", "raise", "NotImplementedError", "(", "msg", ")" ]
[ 94, 4 ]
[ 97, 38 ]
python
en
['en', 'cy', 'en']
False
BaseDiscriminator.init_weights
(self)
Initialize model weights.
Initialize model weights.
def init_weights(self): """Initialize model weights.""" for m in self.fc_blocks.named_modules(): if isinstance(m, nn.Linear): xavier_init(m, gain=0.01)
[ "def", "init_weights", "(", "self", ")", ":", "for", "m", "in", "self", ".", "fc_blocks", ".", "named_modules", "(", ")", ":", "if", "isinstance", "(", "m", ",", "nn", ".", "Linear", ")", ":", "xavier_init", "(", "m", ",", "gain", "=", "0.01", ")" ...
[ 99, 4 ]
[ 103, 41 ]
python
en
['es', 'en', 'en']
True
ShapeDiscriminator.forward
(self, inputs)
Forward function.
Forward function.
def forward(self, inputs): """Forward function.""" return self.fc_blocks(inputs)
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "return", "self", ".", "fc_blocks", "(", "inputs", ")" ]
[ 128, 4 ]
[ 130, 37 ]
python
en
['en', 'cy', 'en']
False
PoseDiscriminator.forward
(self, inputs)
Forward function. The input is (batch_size x joint_count x 9)
Forward function.
def forward(self, inputs): """Forward function. The input is (batch_size x joint_count x 9) """ # shape: batch_size x 9 x 1 x joint_count inputs = inputs.transpose(1, 2).unsqueeze(2).contiguous() # shape: batch_size x c x 1 x joint_count internal_outputs = self.c...
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "# shape: batch_size x 9 x 1 x joint_count", "inputs", "=", "inputs", ".", "transpose", "(", "1", ",", "2", ")", ".", "unsqueeze", "(", "2", ")", ".", "contiguous", "(", ")", "# shape: batch_size x c x 1 ...
[ 169, 4 ]
[ 182, 54 ]
python
en
['en', 'cy', 'en']
False
PoseDiscriminator.init_weights
(self)
Initialize model weights.
Initialize model weights.
def init_weights(self): """Initialize model weights.""" for m in self.conv_blocks: if isinstance(m, nn.Conv2d): normal_init(m, std=0.001, bias=0) for m in self.fc_layer.named_modules(): if isinstance(m, nn.Linear): xavier_init(m, gain=0.01)
[ "def", "init_weights", "(", "self", ")", ":", "for", "m", "in", "self", ".", "conv_blocks", ":", "if", "isinstance", "(", "m", ",", "nn", ".", "Conv2d", ")", ":", "normal_init", "(", "m", ",", "std", "=", "0.001", ",", "bias", "=", "0", ")", "for...
[ 184, 4 ]
[ 191, 41 ]
python
en
['es', 'en', 'en']
True
FullPoseDiscriminator.forward
(self, inputs)
Forward function.
Forward function.
def forward(self, inputs): """Forward function.""" return self.fc_blocks(inputs)
[ "def", "forward", "(", "self", ",", "inputs", ")", ":", "return", "self", ".", "fc_blocks", "(", "inputs", ")" ]
[ 216, 4 ]
[ 218, 37 ]
python
en
['en', 'cy', 'en']
False
SMPLDiscriminator._create_sub_modules
(self)
Create sub discriminators.
Create sub discriminators.
def _create_sub_modules(self): """Create sub discriminators.""" # create theta discriminator for each joint self.pose_discriminator = PoseDiscriminator(self.per_joint_channel, self.joint_count) # create full pose discriminator for tot...
[ "def", "_create_sub_modules", "(", "self", ")", ":", "# create theta discriminator for each joint", "self", ".", "pose_discriminator", "=", "PoseDiscriminator", "(", "self", ".", "per_joint_channel", ",", "self", ".", "joint_count", ")", "# create full pose discriminator fo...
[ 255, 4 ]
[ 278, 69 ]
python
en
['en', 'la', 'en']
True
SMPLDiscriminator.forward
(self, thetas)
Forward function.
Forward function.
def forward(self, thetas): """Forward function.""" _, poses, shapes = thetas batch_size = poses.shape[0] shape_disc_value = self.shape_discriminator(shapes) # The first rotation matrix is global rotation # and is NOT used in discriminator. if poses.dim() == 2: ...
[ "def", "forward", "(", "self", ",", "thetas", ")", ":", "_", ",", "poses", ",", "shapes", "=", "thetas", "batch_size", "=", "poses", ".", "shape", "[", "0", "]", "shape_disc_value", "=", "self", ".", "shape_discriminator", "(", "shapes", ")", "# The firs...
[ 280, 4 ]
[ 301, 73 ]
python
en
['en', 'cy', 'en']
False
SMPLDiscriminator.init_weights
(self)
Initialize model weights.
Initialize model weights.
def init_weights(self): """Initialize model weights.""" self.full_pose_discriminator.init_weights() self.pose_discriminator.init_weights() self.shape_discriminator.init_weights()
[ "def", "init_weights", "(", "self", ")", ":", "self", ".", "full_pose_discriminator", ".", "init_weights", "(", ")", "self", ".", "pose_discriminator", ".", "init_weights", "(", ")", "self", ".", "shape_discriminator", ".", "init_weights", "(", ")" ]
[ 303, 4 ]
[ 307, 47 ]
python
en
['es', 'en', 'en']
True