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
ProgressBar.init_sanity_tqdm
(self)
Override this to customize the tqdm bar for the validation sanity run.
Override this to customize the tqdm bar for the validation sanity run.
def init_sanity_tqdm(self) -> tqdm: """ Override this to customize the tqdm bar for the validation sanity run. """ bar = tqdm( desc='Validation sanity check', position=(2 * self.process_position), disable=self.is_disabled, leave=False, dynamic_...
[ "def", "init_sanity_tqdm", "(", "self", ")", "->", "tqdm", ":", "bar", "=", "tqdm", "(", "desc", "=", "'Validation sanity check'", ",", "position", "=", "(", "2", "*", "self", ".", "process_position", ")", ",", "disable", "=", "self", ".", "is_disabled", ...
[ 315, 4 ]
[ 325, 18 ]
python
en
['en', 'en', 'en']
True
ProgressBar.init_train_tqdm
(self)
Override this to customize the tqdm bar for training.
Override this to customize the tqdm bar for training.
def init_train_tqdm(self) -> tqdm: """ Override this to customize the tqdm bar for training. """ bar = tqdm( desc='Training', initial=self.train_batch_idx, position=(2 * self.process_position), disable=self.is_disabled, leave=True, ...
[ "def", "init_train_tqdm", "(", "self", ")", "->", "tqdm", ":", "bar", "=", "tqdm", "(", "desc", "=", "'Training'", ",", "initial", "=", "self", ".", "train_batch_idx", ",", "position", "=", "(", "2", "*", "self", ".", "process_position", ")", ",", "dis...
[ 327, 4 ]
[ 339, 18 ]
python
en
['en', 'en', 'en']
True
ProgressBar.init_predict_tqdm
(self)
Override this to customize the tqdm bar for predicting.
Override this to customize the tqdm bar for predicting.
def init_predict_tqdm(self) -> tqdm: """ Override this to customize the tqdm bar for predicting. """ bar = tqdm( desc='Predicting', initial=self.train_batch_idx, position=(2 * self.process_position), disable=self.is_disabled, leave=True, ...
[ "def", "init_predict_tqdm", "(", "self", ")", "->", "tqdm", ":", "bar", "=", "tqdm", "(", "desc", "=", "'Predicting'", ",", "initial", "=", "self", ".", "train_batch_idx", ",", "position", "=", "(", "2", "*", "self", ".", "process_position", ")", ",", ...
[ 341, 4 ]
[ 353, 18 ]
python
en
['en', 'en', 'en']
True
ProgressBar.init_validation_tqdm
(self)
Override this to customize the tqdm bar for validation.
Override this to customize the tqdm bar for validation.
def init_validation_tqdm(self) -> tqdm: """ Override this to customize the tqdm bar for validation. """ bar = tqdm( desc='Validating', position=(2 * self.process_position + 1), disable=self.is_disabled, leave=False, dynamic_ncols=True, ...
[ "def", "init_validation_tqdm", "(", "self", ")", "->", "tqdm", ":", "bar", "=", "tqdm", "(", "desc", "=", "'Validating'", ",", "position", "=", "(", "2", "*", "self", ".", "process_position", "+", "1", ")", ",", "disable", "=", "self", ".", "is_disable...
[ 355, 4 ]
[ 365, 18 ]
python
en
['en', 'en', 'en']
True
ProgressBar.init_test_tqdm
(self)
Override this to customize the tqdm bar for testing.
Override this to customize the tqdm bar for testing.
def init_test_tqdm(self) -> tqdm: """ Override this to customize the tqdm bar for testing. """ bar = tqdm( desc="Testing", position=(2 * self.process_position), disable=self.is_disabled, leave=True, dynamic_ncols=True, file=sys.stdo...
[ "def", "init_test_tqdm", "(", "self", ")", "->", "tqdm", ":", "bar", "=", "tqdm", "(", "desc", "=", "\"Testing\"", ",", "position", "=", "(", "2", "*", "self", ".", "process_position", ")", ",", "disable", "=", "self", ".", "is_disabled", ",", "leave",...
[ 367, 4 ]
[ 377, 18 ]
python
en
['en', 'en', 'en']
True
ProgressBar._update_bar
(self, bar)
Updates the bar by the refresh rate without overshooting.
Updates the bar by the refresh rate without overshooting.
def _update_bar(self, bar): """ Updates the bar by the refresh rate without overshooting. """ if bar.total is not None: delta = min(self.refresh_rate, bar.total - bar.n) else: # infinite / unknown size delta = self.refresh_rate if delta > 0: ...
[ "def", "_update_bar", "(", "self", ",", "bar", ")", ":", "if", "bar", ".", "total", "is", "not", "None", ":", "delta", "=", "min", "(", "self", ".", "refresh_rate", ",", "bar", ".", "total", "-", "bar", ".", "n", ")", "else", ":", "# infinite / unk...
[ 480, 4 ]
[ 488, 29 ]
python
en
['en', 'en', 'en']
True
apply_to_collection
( data: Any, dtype: Union[type, tuple], function: Callable, *args, wrong_dtype: Optional[Union[type, tuple]] = None, **kwargs )
Recursively applies a function to all elements of a certain dtype. Args: data: the collection to apply the function to dtype: the given function will be applied to all elements of this dtype function: the function to apply *args: positional arguments (will be forwarded to calls...
Recursively applies a function to all elements of a certain dtype.
def apply_to_collection( data: Any, dtype: Union[type, tuple], function: Callable, *args, wrong_dtype: Optional[Union[type, tuple]] = None, **kwargs ) -> Any: """ Recursively applies a function to all elements of a certain dtype. Args: data: the collection to apply the funct...
[ "def", "apply_to_collection", "(", "data", ":", "Any", ",", "dtype", ":", "Union", "[", "type", ",", "tuple", "]", ",", "function", ":", "Callable", ",", "*", "args", ",", "wrong_dtype", ":", "Optional", "[", "Union", "[", "type", ",", "tuple", "]", ...
[ 53, 0 ]
[ 93, 15 ]
python
en
['en', 'error', 'th']
False
move_data_to_device
(batch: Any, device: torch.device)
Transfers a collection of data to the given device. Any object that defines a method ``to(device)`` will be moved and all other objects in the collection will be left untouched. Args: batch: A tensor or collection of tensors or anything that has a method `.to(...)`. See :func:`apply_to...
Transfers a collection of data to the given device. Any object that defines a method ``to(device)`` will be moved and all other objects in the collection will be left untouched.
def move_data_to_device(batch: Any, device: torch.device): """ Transfers a collection of data to the given device. Any object that defines a method ``to(device)`` will be moved and all other objects in the collection will be left untouched. Args: batch: A tensor or collection of tensors or anyt...
[ "def", "move_data_to_device", "(", "batch", ":", "Any", ",", "device", ":", "torch", ".", "device", ")", ":", "def", "batch_to", "(", "data", ")", ":", "# try to move torchtext data first", "if", "_TORCHTEXT_AVAILABLE", "and", "isinstance", "(", "data", ",", "...
[ 122, 0 ]
[ 157, 69 ]
python
en
['en', 'error', 'th']
False
all_zeros
(modules)
Check if the weight(and bias) is all zero.
Check if the weight(and bias) is all zero.
def all_zeros(modules): """Check if the weight(and bias) is all zero.""" weight_zero = torch.equal(modules.weight.data, torch.zeros_like(modules.weight.data)) if hasattr(modules, 'bias'): bias_zero = torch.equal(modules.bias.data, torch.z...
[ "def", "all_zeros", "(", "modules", ")", ":", "weight_zero", "=", "torch", ".", "equal", "(", "modules", ".", "weight", ".", "data", ",", "torch", ".", "zeros_like", "(", "modules", ".", "weight", ".", "data", ")", ")", "if", "hasattr", "(", "modules",...
[ 10, 0 ]
[ 20, 36 ]
python
en
['en', 'en', 'en']
True
check_norm_state
(modules, train_state)
Check if norm layer is in correct train state.
Check if norm layer is in correct train state.
def check_norm_state(modules, train_state): """Check if norm layer is in correct train state.""" for mod in modules: if isinstance(mod, _BatchNorm): if mod.training != train_state: return False return True
[ "def", "check_norm_state", "(", "modules", ",", "train_state", ")", ":", "for", "mod", "in", "modules", ":", "if", "isinstance", "(", "mod", ",", "_BatchNorm", ")", ":", "if", "mod", ".", "training", "!=", "train_state", ":", "return", "False", "return", ...
[ 23, 0 ]
[ 29, 15 ]
python
en
['en', 'en', 'en']
True
test_seresnet
()
Test resnet backbone.
Test resnet backbone.
def test_seresnet(): """Test resnet backbone.""" with pytest.raises(KeyError): # SEResNet depth should be in [50, 101, 152] SEResNet(20) with pytest.raises(AssertionError): # In SEResNet: 1 <= num_stages <= 4 SEResNet(50, num_stages=0) with pytest.raises(AssertionError)...
[ "def", "test_seresnet", "(", ")", ":", "with", "pytest", ".", "raises", "(", "KeyError", ")", ":", "# SEResNet depth should be in [50, 101, 152]", "SEResNet", "(", "20", ")", "with", "pytest", ".", "raises", "(", "AssertionError", ")", ":", "# In SEResNet: 1 <= nu...
[ 121, 0 ]
[ 241, 55 ]
python
en
['nl', 'no', 'en']
False
compute_Xphi_data
( X_data, X_row, X_col, theta_vi_shape, theta_vi_rate, beta_vi_shape, beta_vi_rate, delta_vi_shape, delta_vi_rate, )
Fast version of Xphi computation using numba & gsl_digamma Parameters ---------- X_data : ndarray of np.int32 (number_nonzero, ) array of nonzero values X_row : ndarray of np.int32 (number_nonzero, ) array of row ids for each nonzero value X_col : ndarray (np.int32) (number_...
Fast version of Xphi computation using numba & gsl_digamma
def compute_Xphi_data( X_data, X_row, X_col, theta_vi_shape, theta_vi_rate, beta_vi_shape, beta_vi_rate, delta_vi_shape, delta_vi_rate, ): """Fast version of Xphi computation using numba & gsl_digamma Parameters ---------- X_data : ndarray of np.int32 (number...
[ "def", "compute_Xphi_data", "(", "X_data", ",", "X_row", ",", "X_col", ",", "theta_vi_shape", ",", "theta_vi_rate", ",", "beta_vi_shape", ",", "beta_vi_rate", ",", "delta_vi_shape", ",", "delta_vi_rate", ",", ")", ":", "# convenience", "ncells", ",", "ngenes", "...
[ 81, 0 ]
[ 157, 15 ]
python
en
['en', 'en', 'en']
True
compute_loading_shape_update
(Xphi_data, X_keep, nkeep, nfactors, shape_prior)
Compute gamma shape updates for theta or beta using numba Parameters ---------- Xphi_data : ndarray (number_nonzero, nfactors) array of X * phi X_keep : ndarray (number_nonzer,) vector of indices along the axis of interest. If X is an (ncell,ngene) coo_matrix, this should be X.r...
Compute gamma shape updates for theta or beta using numba
def compute_loading_shape_update(Xphi_data, X_keep, nkeep, nfactors, shape_prior): """Compute gamma shape updates for theta or beta using numba Parameters ---------- Xphi_data : ndarray (number_nonzero, nfactors) array of X * phi X_keep : ndarray (number_nonzer,) vector of indices a...
[ "def", "compute_loading_shape_update", "(", "Xphi_data", ",", "X_keep", ",", "nkeep", ",", "nfactors", ",", "shape_prior", ")", ":", "nnz", "=", "Xphi_data", ".", "shape", "[", "0", "]", "dtype", "=", "Xphi_data", ".", "dtype", "result", "=", "shape_prior", ...
[ 161, 0 ]
[ 190, 17 ]
python
en
['en', 'en', 'en']
True
compute_cell_shape_update
(Xphi_data, X_keep, nkeep, nfactors, shape_prior)
Compute gamma shape updates for theta or beta using numba Parameters ---------- Xphi_data : ndarray (number_nonzero, nfactors) array of X * phi X_keep : ndarray (number_nonzer,) vector of indices along the axis of interest. If X is an (ncell,ngene) coo_matrix, this should be X.r...
Compute gamma shape updates for theta or beta using numba
def compute_cell_shape_update(Xphi_data, X_keep, nkeep, nfactors, shape_prior): """Compute gamma shape updates for theta or beta using numba Parameters ---------- Xphi_data : ndarray (number_nonzero, nfactors) array of X * phi X_keep : ndarray (number_nonzer,) vector of indices alon...
[ "def", "compute_cell_shape_update", "(", "Xphi_data", ",", "X_keep", ",", "nkeep", ",", "nfactors", ",", "shape_prior", ")", ":", "nnz", "=", "Xphi_data", ".", "shape", "[", "0", "]", "dtype", "=", "Xphi_data", ".", "dtype", "result", "=", "shape_prior", "...
[ 230, 0 ]
[ 259, 17 ]
python
en
['en', 'en', 'en']
True
compute_shared_shape_update
( result, Xphi_data, X_keep, nkeep, nfactors, shape_prior )
Compute gamma shape updates for theta or beta using numba Parameters ---------- Xphi_data : List of ndarray List of (number_nonzero, nfactors) array of X * phi X_keep : ndarray (number_nonzer,) vector of indices along the axis of interest. If X is an (ncell,ngene) coo_matrix, th...
Compute gamma shape updates for theta or beta using numba
def compute_shared_shape_update( result, Xphi_data, X_keep, nkeep, nfactors, shape_prior ): """Compute gamma shape updates for theta or beta using numba Parameters ---------- Xphi_data : List of ndarray List of (number_nonzero, nfactors) array of X * phi X_keep : ndarray (number...
[ "def", "compute_shared_shape_update", "(", "result", ",", "Xphi_data", ",", "X_keep", ",", "nkeep", ",", "nfactors", ",", "shape_prior", ")", ":", "nnz", "=", "Xphi_data", ".", "shape", "[", "0", "]", "dtype", "=", "Xphi_data", ".", "dtype", "for", "i", ...
[ 263, 0 ]
[ 290, 17 ]
python
en
['en', 'en', 'en']
True
loss_function_for_data
(loss_function, X)
Get a loss function for a fixed dataset Parameters ---------- loss_function : function The loss function to use. The data parameter for the function must be `X` X : coo_matrix coo_matrix of data to apply loss function to Returns ------- fixed_data_loss_function : f...
Get a loss function for a fixed dataset
def loss_function_for_data(loss_function, X): """Get a loss function for a fixed dataset Parameters ---------- loss_function : function The loss function to use. The data parameter for the function must be `X` X : coo_matrix coo_matrix of data to apply loss function to ...
[ "def", "loss_function_for_data", "(", "loss_function", ",", "X", ")", ":", "return", "functools", ".", "partial", "(", "loss_function", ",", "X", "=", "X", ")" ]
[ 366, 0 ]
[ 383, 48 ]
python
en
['es', 'en', 'en']
True
pois_llh_pointwise
(X, *, theta, beta, **kwargs)
Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict, optional extra arguments not used in this loss function Returns ------...
Poisson log-likelihood for each nonzero entry
def pois_llh_pointwise(X, *, theta, beta, **kwargs): """Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict, optional extra argu...
[ "def", "pois_llh_pointwise", "(", "X", ",", "*", ",", "theta", ",", "beta", ",", "*", "*", "kwargs", ")", ":", "try", ":", "llh", "=", "compute_pois_llh", "(", "X", ".", "data", ",", "X", ".", "row", ",", "X", ".", "col", ",", "theta", ".", "vi...
[ 389, 0 ]
[ 425, 14 ]
python
en
['en', 'el-Latn', 'en']
True
mean_negative_pois_llh
(X, *, theta, beta, **kwargs)
Mean Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict, optional extra arguments not used in this loss function Returns -...
Mean Poisson log-likelihood for each nonzero entry
def mean_negative_pois_llh(X, *, theta, beta, **kwargs): """Mean Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict, optional e...
[ "def", "mean_negative_pois_llh", "(", "X", ",", "*", ",", "theta", ",", "beta", ",", "*", "*", "kwargs", ")", ":", "return", "np", ".", "mean", "(", "-", "pois_llh_pointwise", "(", "X", "=", "X", ",", "theta", "=", "theta", ",", "beta", "=", "beta"...
[ 428, 0 ]
[ 451, 68 ]
python
en
['en', 'el-Latn', 'en']
True
pois_llh_pointwise2
(X, *, theta, beta, delta, datasetno, **kwargs)
Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict, optional extra arguments not used in this loss function Returns ------...
Poisson log-likelihood for each nonzero entry
def pois_llh_pointwise2(X, *, theta, beta, delta, datasetno, **kwargs): """Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict, optional...
[ "def", "pois_llh_pointwise2", "(", "X", ",", "*", ",", "theta", ",", "beta", ",", "delta", ",", "datasetno", ",", "*", "*", "kwargs", ")", ":", "try", ":", "llh", "=", "compute_pois_llh2", "(", "X", "[", "datasetno", "]", ".", "data", ",", "X", "["...
[ 454, 0 ]
[ 492, 14 ]
python
en
['en', 'el-Latn', 'en']
True
mean_negative_pois_llh2
(X, *, theta, beta, delta, datasetno, **kwargs)
Mean Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict, optional extra arguments not used in this loss function Returns -...
Mean Poisson log-likelihood for each nonzero entry
def mean_negative_pois_llh2(X, *, theta, beta, delta, datasetno, **kwargs): """Mean Poisson log-likelihood for each nonzero entry Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma beta : HPF_Gamma **kwargs : dict,...
[ "def", "mean_negative_pois_llh2", "(", "X", ",", "*", ",", "theta", ",", "beta", ",", "delta", ",", "datasetno", ",", "*", "*", "kwargs", ")", ":", "return", "np", ".", "mean", "(", "-", "pois_llh_pointwise2", "(", "X", "=", "X", ",", "theta", "=", ...
[ 495, 0 ]
[ 522, 5 ]
python
en
['en', 'el-Latn', 'en']
True
combine_across_cells
(x, y, y_ixs)
Combine theta & xi from two scHPF instance with the same beta & eta Intended to be used combining variational distributions for local variables (theta,xi) from training data with variational distributions for local variables from validation or other data that was projected onto the same global variatio...
Combine theta & xi from two scHPF instance with the same beta & eta
def combine_across_cells(x, y, y_ixs): """Combine theta & xi from two scHPF instance with the same beta & eta Intended to be used combining variational distributions for local variables (theta,xi) from training data with variational distributions for local variables from validation or other data that w...
[ "def", "combine_across_cells", "(", "x", ",", "y", ",", "y_ixs", ")", ":", "assert", "x", ".", "dp", "==", "y", ".", "dp", "assert", "x", ".", "eta", "==", "y", ".", "eta", "assert", "x", ".", "beta", "==", "y", ".", "beta", "xy", "=", "deepcop...
[ 1320, 0 ]
[ 1357, 13 ]
python
en
['en', 'en', 'en']
True
run_trials
( X, nfactors, ntrials=15, min_iter=30, max_iter=500, check_freq=10, epsilon=0.001, better_than_n_ago=5, dtype=np.float64, verbose=True, vcells=None, vX=None, loss_function=None, model_kwargs={}, )
Train with multiple random initializations, selecting model with best loss As scHPF uses non-convex optimization, it benefits from training with multiple random initializations to avoid local minima. Parameters ---------- X: coo_matrix Data to fit nfactors: int Number of f...
Train with multiple random initializations, selecting model with best loss
def run_trials( X, nfactors, ntrials=15, min_iter=30, max_iter=500, check_freq=10, epsilon=0.001, better_than_n_ago=5, dtype=np.float64, verbose=True, vcells=None, vX=None, loss_function=None, model_kwargs={}, ): """ Train with multiple random initializati...
[ "def", "run_trials", "(", "X", ",", "nfactors", ",", "ntrials", "=", "15", ",", "min_iter", "=", "30", ",", "max_iter", "=", "500", ",", "check_freq", "=", "10", ",", "epsilon", "=", "0.001", ",", "better_than_n_ago", "=", "5", ",", "dtype", "=", "np...
[ 1360, 0 ]
[ 1460, 21 ]
python
en
['en', 'error', 'th']
False
HPF_Gamma.random_gamma_factory
(dims, shape_prior, rate_prior, dtype=np.float64)
Factory method to randomly initialize variational distributions Parameters ---------- dims: list-like Numpy-style shape of the matrix of Gammas. shape_prior: float Prior for variational Gammas' shapes. Must be greater than 0. rate_prior: float ...
Factory method to randomly initialize variational distributions
def random_gamma_factory(dims, shape_prior, rate_prior, dtype=np.float64): """Factory method to randomly initialize variational distributions Parameters ---------- dims: list-like Numpy-style shape of the matrix of Gammas. shape_prior: float Prior for var...
[ "def", "random_gamma_factory", "(", "dims", ",", "shape_prior", ",", "rate_prior", ",", "dtype", "=", "np", ".", "float64", ")", ":", "vi_shape", "=", "np", ".", "random", ".", "uniform", "(", "0.5", "*", "shape_prior", ",", "1.5", "*", "shape_prior", ",...
[ 548, 4 ]
[ 570, 43 ]
python
en
['en', 'en', 'en']
True
HPF_Gamma.__init__
(self, vi_shape, vi_rate)
Initializes HPF_Gamma with variational shape and rates
Initializes HPF_Gamma with variational shape and rates
def __init__(self, vi_shape, vi_rate): """Initializes HPF_Gamma with variational shape and rates""" assert vi_shape.shape == vi_rate.shape assert vi_shape.dtype == vi_rate.dtype assert np.all(vi_shape > 0) assert np.all(vi_rate > 0) self.vi_shape = vi_shape self.v...
[ "def", "__init__", "(", "self", ",", "vi_shape", ",", "vi_rate", ")", ":", "assert", "vi_shape", ".", "shape", "==", "vi_rate", ".", "shape", "assert", "vi_shape", ".", "dtype", "==", "vi_rate", ".", "dtype", "assert", "np", ".", "all", "(", "vi_shape", ...
[ 572, 4 ]
[ 580, 35 ]
python
en
['en', 'en', 'en']
True
HPF_Gamma.e_x
(self)
Expected value of the random variable(s) given variational distribution(s)
Expected value of the random variable(s) given variational distribution(s)
def e_x(self): """Expected value of the random variable(s) given variational distribution(s) """ return self.vi_shape / self.vi_rate
[ "def", "e_x", "(", "self", ")", ":", "return", "self", ".", "vi_shape", "/", "self", ".", "vi_rate" ]
[ 596, 4 ]
[ 600, 43 ]
python
en
['en', 'en', 'en']
True
HPF_Gamma.e_logx
(self)
Expectation of the log of random variable given variational distribution(s)
Expectation of the log of random variable given variational distribution(s)
def e_logx(self): """Expectation of the log of random variable given variational distribution(s)""" return digamma(self.vi_shape) - np.log(self.vi_rate)
[ "def", "e_logx", "(", "self", ")", ":", "return", "digamma", "(", "self", ".", "vi_shape", ")", "-", "np", ".", "log", "(", "self", ".", "vi_rate", ")" ]
[ 603, 4 ]
[ 606, 60 ]
python
en
['en', 'en', 'en']
True
HPF_Gamma.entropy
(self)
Entropy of variational Gammas
Entropy of variational Gammas
def entropy(self): """Entropy of variational Gammas""" return ( self.vi_shape - np.log(self.vi_rate) + gammaln(self.vi_shape) + (1 - self.vi_shape) * digamma(self.vi_shape) )
[ "def", "entropy", "(", "self", ")", ":", "return", "(", "self", ".", "vi_shape", "-", "np", ".", "log", "(", "self", ".", "vi_rate", ")", "+", "gammaln", "(", "self", ".", "vi_shape", ")", "+", "(", "1", "-", "self", ".", "vi_shape", ")", "*", ...
[ 609, 4 ]
[ 616, 9 ]
python
en
['en', 'fil', 'en']
True
HPF_Gamma.sample
(self, nsamples=1)
Sample from variational distributions Parameters ---------- nsamples: int (optional, default 1) Number of samples to take. Returns ------- X_rep : np.ndarray An ndarray of samples from the variational distributions, where the last dim...
Sample from variational distributions
def sample(self, nsamples=1): """Sample from variational distributions Parameters ---------- nsamples: int (optional, default 1) Number of samples to take. Returns ------- X_rep : np.ndarray An ndarray of samples from the variational dist...
[ "def", "sample", "(", "self", ",", "nsamples", "=", "1", ")", ":", "samples", "=", "[", "]", "for", "i", "in", "range", "(", "nsamples", ")", ":", "samples", ".", "append", "(", "np", ".", "random", ".", "gamma", "(", "self", ".", "vi_shape", ","...
[ 618, 4 ]
[ 635, 34 ]
python
en
['en', 'en', 'en']
True
HPF_Gamma.combine
(self, other, other_ixs)
Combine with another HPF_Gamma Useful for combining variational distributions from training data with variational distributions from cells that were projected onto frozen beta and eta Parameters ---------- other : `HPF_Gamma` Other HPF_Gamma to merge with ...
Combine with another HPF_Gamma
def combine(self, other, other_ixs): """Combine with another HPF_Gamma Useful for combining variational distributions from training data with variational distributions from cells that were projected onto frozen beta and eta Parameters ---------- other : `HPF_Gam...
[ "def", "combine", "(", "self", ",", "other", ",", "other_ixs", ")", ":", "assert", "other", ".", "dims", "[", "0", "]", "==", "len", "(", "other_ixs", ")", "assert", "len", "(", "np", ".", "unique", "(", "other_ixs", ")", ")", "==", "len", "(", "...
[ 637, 4 ]
[ 672, 51 ]
python
en
['en', 'en', 'en']
True
scIHPF.__init__
( self, nfactors, a=0.3, ap=1, bp=None, c=0.3, cp=1, dp=None, min_iter=30, max_iter=500, check_freq=10, epsilon=0.001, better_than_n_ago=5, dtype=np.float64, xi=None, theta=None, eta=N...
Initialize HPF instance
Initialize HPF instance
def __init__( self, nfactors, a=0.3, ap=1, bp=None, c=0.3, cp=1, dp=None, min_iter=30, max_iter=500, check_freq=10, epsilon=0.001, better_than_n_ago=5, dtype=np.float64, xi=None, theta=None, ...
[ "def", "__init__", "(", "self", ",", "nfactors", ",", "a", "=", "0.3", ",", "ap", "=", "1", ",", "bp", "=", "None", ",", "c", "=", "0.3", ",", "cp", "=", "1", ",", "dp", "=", "None", ",", "min_iter", "=", "30", ",", "max_iter", "=", "500", ...
[ 721, 4 ]
[ 774, 42 ]
python
en
['en', 'en', 'en']
True
scIHPF.pois_llh_pointwise
(self, X, theta=None, beta=None)
Poisson log-likelihood (for each nonzero data) Attempt to use numba/cffi/gsl, use numpy otherwise Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. theta : HPF_Gamma, optional If given, use for theta in...
Poisson log-likelihood (for each nonzero data)
def pois_llh_pointwise(self, X, theta=None, beta=None): """Poisson log-likelihood (for each nonzero data) Attempt to use numba/cffi/gsl, use numpy otherwise Parameters ---------- X: coo_matrix Data to compute Poisson log likelihood of. Assumed to be nonzero. ...
[ "def", "pois_llh_pointwise", "(", "self", ",", "X", ",", "theta", "=", "None", ",", "beta", "=", "None", ")", ":", "theta", "=", "self", ".", "theta", "if", "theta", "is", "None", "else", "theta", "beta", "=", "self", ".", "beta", "if", "beta", "is...
[ 801, 4 ]
[ 821, 65 ]
python
en
['en', 'no', 'en']
True
scIHPF.mean_negative_pois_llh
(X, theta=None, beta=None, **kwargs)
Convenience method for mean negative llh of nonzero entries
Convenience method for mean negative llh of nonzero entries
def mean_negative_pois_llh(X, theta=None, beta=None, **kwargs): """Convenience method for mean negative llh of nonzero entries""" theta = self.theta if theta is None else theta beta = self.beta if beta is None else beta return ls.mean_negative_pois_llh(X=X, theta=theta, beta=beta)
[ "def", "mean_negative_pois_llh", "(", "X", ",", "theta", "=", "None", ",", "beta", "=", "None", ",", "*", "*", "kwargs", ")", ":", "theta", "=", "self", ".", "theta", "if", "theta", "is", "None", "else", "theta", "beta", "=", "self", ".", "beta", "...
[ 823, 4 ]
[ 827, 69 ]
python
en
['en', 'en', 'en']
True
scIHPF.fit
(self, X, **kwargs)
Fit an scHPF model Parameters ---------- X: coo_matrix Data to fit loss_function : function, optional (Default: None) loss function to use for fit. set to negative poisson likelihood of X if not given
Fit an scHPF model
def fit(self, X, **kwargs): """Fit an scHPF model Parameters ---------- X: coo_matrix Data to fit loss_function : function, optional (Default: None) loss function to use for fit. set to negative poisson likelihood of X if not given """...
[ "def", "fit", "(", "self", ",", "X", ",", "*", "*", "kwargs", ")", ":", "(", "bp", ",", "dp", ",", "xi", ",", "eta", ",", "zeta", ",", "theta", ",", "beta", ",", "delta", ",", "loss", ")", "=", "self", ".", "_fit", "(", "X", ",", "*", "*"...
[ 829, 4 ]
[ 850, 19 ]
python
en
['en', 'lb', 'en']
True
scIHPF._score
(self, capacity, loading)
Get the hierarchically normalized loadings which we call the cell or gene score in the scHPF paper Parameters ---------- capacity : HPF_Gamma xi or eta loading : HPF_Gamma theta or beta Returns ------- score : ndarray
Get the hierarchically normalized loadings which we call the cell or gene score in the scHPF paper
def _score(self, capacity, loading): """Get the hierarchically normalized loadings which we call the cell or gene score in the scHPF paper Parameters ---------- capacity : HPF_Gamma xi or eta loading : HPF_Gamma theta or beta Returns ...
[ "def", "_score", "(", "self", ",", "capacity", ",", "loading", ")", ":", "assert", "loading", ".", "dims", "[", "0", "]", "==", "capacity", ".", "dims", "[", "0", "]", "return", "loading", ".", "e_x", "*", "capacity", ".", "e_x", "[", ":", ",", "...
[ 852, 4 ]
[ 869, 50 ]
python
en
['en', 'en', 'en']
True
scIHPF._fit
( self, X, freeze_shared_genes=False, freeze_genes=False, reinit=True, loss_function=None, min_iter=None, max_iter=None, epsilon=None, check_freq=None, checkstep_function=None, dataset_ratio=0.1, verbose=None, )
Combined internal fit/transform function Parameters ---------- X: List of coo_matrix List of Data to fit freeze_genes: bool, (optional, default False) Should we update gene variational distributions eta and beta reinit: bool, (optional, default True) ...
Combined internal fit/transform function
def _fit( self, X, freeze_shared_genes=False, freeze_genes=False, reinit=True, loss_function=None, min_iter=None, max_iter=None, epsilon=None, check_freq=None, checkstep_function=None, dataset_ratio=0.1, verbose=None...
[ "def", "_fit", "(", "self", ",", "X", ",", "freeze_shared_genes", "=", "False", ",", "freeze_genes", "=", "False", ",", "reinit", "=", "True", ",", "loss_function", "=", "None", ",", "min_iter", "=", "None", ",", "max_iter", "=", "None", ",", "epsilon", ...
[ 871, 4 ]
[ 1142, 64 ]
python
en
['en', 'en', 'en']
True
scIHPF._setup
( self, X, freeze_shared_genes=False, freeze_genes=False, reinit=True, clip=True )
Setup variational distributions Parameters ---------- X : list of coo_matrix List of data to fit freeze_genes: bool, optional (Default: False) Should we update gene variational distributions eta and beta reinit: bool, optional (Default: True) ...
Setup variational distributions
def _setup( self, X, freeze_shared_genes=False, freeze_genes=False, reinit=True, clip=True ): """Setup variational distributions Parameters ---------- X : list of coo_matrix List of data to fit freeze_genes: bool, optional (Default: False) Sho...
[ "def", "_setup", "(", "self", ",", "X", ",", "freeze_shared_genes", "=", "False", ",", "freeze_genes", "=", "False", ",", "reinit", "=", "True", ",", "clip", "=", "True", ")", ":", "# locals for convenience", "nfactors", "=", "self", ".", "nfactors", "ngen...
[ 1144, 4 ]
[ 1265, 58 ]
python
en
['en', 'da', 'en']
True
scIHPF._get_empirical_hypers
(self, X, freeze_genes=False, clip=False)
Get empirical values for bp, dp Parameters ---------- X : list of coo_matrix List of data to fit Returns ------- bp : list of float dp : list of float
Get empirical values for bp, dp
def _get_empirical_hypers(self, X, freeze_genes=False, clip=False): """Get empirical values for bp, dp Parameters ---------- X : list of coo_matrix List of data to fit Returns ------- bp : list of float dp : list of float """ ...
[ "def", "_get_empirical_hypers", "(", "self", ",", "X", ",", "freeze_genes", "=", "False", ",", "clip", "=", "False", ")", ":", "bp", ",", "dp", "=", "self", ".", "bp", ",", "self", ".", "dp", "# empirically set bp and dp", "def", "mean_var_ratio", "(", "...
[ 1267, 4 ]
[ 1303, 21 ]
python
en
['en', 'pt', 'en']
True
scIHPF._initialize
(self, X, freeze_genes=False)
Shortcut to setup random distributions & set variables
Shortcut to setup random distributions & set variables
def _initialize(self, X, freeze_genes=False): """Shortcut to setup random distributions & set variables""" bp, dp, xi, eta, zeta, theta, beta, delta = self._setup( X, freeze_genes, reinit=True ) self.bp = bp self.dp = dp self.xi = xi self.eta = eta ...
[ "def", "_initialize", "(", "self", ",", "X", ",", "freeze_genes", "=", "False", ")", ":", "bp", ",", "dp", ",", "xi", ",", "eta", ",", "zeta", ",", "theta", ",", "beta", ",", "delta", "=", "self", ".", "_setup", "(", "X", ",", "freeze_genes", ","...
[ 1305, 4 ]
[ 1317, 26 ]
python
en
['en', 'hmn', 'en']
True
_make_complex
(real, imag)
Like real + 1j * imag, but behaves as expected when imag contains non-finite values
Like real + 1j * imag, but behaves as expected when imag contains non-finite values
def _make_complex(real, imag): """ Like real + 1j * imag, but behaves as expected when imag contains non-finite values """ ret = np.zeros(np.broadcast(real, imag).shape, np.complex_) ret.real = real ret.imag = imag return ret
[ "def", "_make_complex", "(", "real", ",", "imag", ")", ":", "ret", "=", "np", ".", "zeros", "(", "np", ".", "broadcast", "(", "real", ",", "imag", ")", ".", "shape", ",", "np", ".", "complex_", ")", "ret", ".", "real", "=", "real", "ret", ".", ...
[ 36, 0 ]
[ 44, 14 ]
python
en
['en', 'error', 'th']
False
TestInterp.sc
(self, request)
scale function used by the below tests
scale function used by the below tests
def sc(self, request): """ scale function used by the below tests """ return request.param
[ "def", "sc", "(", "self", ",", "request", ")", ":", "return", "request", ".", "param" ]
[ 2410, 4 ]
[ 2412, 28 ]
python
en
['en', 'en', 'en']
True
TestInterp.test_non_finite_any_nan
(self, sc)
test that nans are propagated
test that nans are propagated
def test_non_finite_any_nan(self, sc): """ test that nans are propagated """ assert_equal(np.interp(0.5, [np.nan, 1], sc([ 0, 10])), sc(np.nan)) assert_equal(np.interp(0.5, [ 0, np.nan], sc([ 0, 10])), sc(np.nan)) assert_equal(np.interp(0.5, [ 0, 1], sc(...
[ "def", "test_non_finite_any_nan", "(", "self", ",", "sc", ")", ":", "assert_equal", "(", "np", ".", "interp", "(", "0.5", ",", "[", "np", ".", "nan", ",", "1", "]", ",", "sc", "(", "[", "0", ",", "10", "]", ")", ")", ",", "sc", "(", "np", "."...
[ 2414, 4 ]
[ 2419, 88 ]
python
en
['en', 'en', 'en']
True
TestInterp.test_non_finite_inf
(self, sc)
Test that interp between opposite infs gives nan
Test that interp between opposite infs gives nan
def test_non_finite_inf(self, sc): """ Test that interp between opposite infs gives nan """ assert_equal(np.interp(0.5, [-np.inf, +np.inf], sc([ 0, 10])), sc(np.nan)) assert_equal(np.interp(0.5, [ 0, 1], sc([-np.inf, +np.inf])), sc(np.nan)) assert_equal(np.interp(0.5...
[ "def", "test_non_finite_inf", "(", "self", ",", "sc", ")", ":", "assert_equal", "(", "np", ".", "interp", "(", "0.5", ",", "[", "-", "np", ".", "inf", ",", "+", "np", ".", "inf", "]", ",", "sc", "(", "[", "0", ",", "10", "]", ")", ")", ",", ...
[ 2421, 4 ]
[ 2428, 88 ]
python
en
['en', 'lb', 'en']
True
TestInterp.test_non_finite_half_inf_xf
(self, sc)
Test that interp where both axes have a bound at inf gives nan
Test that interp where both axes have a bound at inf gives nan
def test_non_finite_half_inf_xf(self, sc): """ Test that interp where both axes have a bound at inf gives nan """ assert_equal(np.interp(0.5, [-np.inf, 1], sc([-np.inf, 10])), sc(np.nan)) assert_equal(np.interp(0.5, [-np.inf, 1], sc([+np.inf, 10])), sc(np.nan)) asse...
[ "def", "test_non_finite_half_inf_xf", "(", "self", ",", "sc", ")", ":", "assert_equal", "(", "np", ".", "interp", "(", "0.5", ",", "[", "-", "np", ".", "inf", ",", "1", "]", ",", "sc", "(", "[", "-", "np", ".", "inf", ",", "10", "]", ")", ")", ...
[ 2430, 4 ]
[ 2439, 92 ]
python
en
['en', 'en', 'en']
True
TestInterp.test_non_finite_half_inf_x
(self, sc)
Test interp where the x axis has a bound at inf
Test interp where the x axis has a bound at inf
def test_non_finite_half_inf_x(self, sc): """ Test interp where the x axis has a bound at inf """ assert_equal(np.interp(0.5, [-np.inf, -np.inf], sc([0, 10])), sc(10)) assert_equal(np.interp(0.5, [-np.inf, 1 ], sc([0, 10])), sc(10)) assert_equal(np.interp(0.5, [ 0, +np.inf], sc...
[ "def", "test_non_finite_half_inf_x", "(", "self", ",", "sc", ")", ":", "assert_equal", "(", "np", ".", "interp", "(", "0.5", ",", "[", "-", "np", ".", "inf", ",", "-", "np", ".", "inf", "]", ",", "sc", "(", "[", "0", ",", "10", "]", ")", ")", ...
[ 2441, 4 ]
[ 2446, 76 ]
python
en
['en', 'en', 'en']
True
TestInterp.test_non_finite_half_inf_f
(self, sc)
Test interp where the f axis has a bound at inf
Test interp where the f axis has a bound at inf
def test_non_finite_half_inf_f(self, sc): """ Test interp where the f axis has a bound at inf """ assert_equal(np.interp(0.5, [0, 1], sc([ 0, -np.inf])), sc(-np.inf)) assert_equal(np.interp(0.5, [0, 1], sc([ 0, +np.inf])), sc(+np.inf)) assert_equal(np.interp(0.5, [0, 1], sc([-n...
[ "def", "test_non_finite_half_inf_f", "(", "self", ",", "sc", ")", ":", "assert_equal", "(", "np", ".", "interp", "(", "0.5", ",", "[", "0", ",", "1", "]", ",", "sc", "(", "[", "0", ",", "-", "np", ".", "inf", "]", ")", ")", ",", "sc", "(", "-...
[ 2448, 4 ]
[ 2455, 81 ]
python
en
['en', 'en', 'en']
True
Jarvis.sub_call
(self, exe_file)
This method can directly use call method of subprocess module and according to the argument(exe_file) passed it returns the output. exe_file:- must pass the exe file name as str object type.
This method can directly use call method of subprocess module and according to the argument(exe_file) passed it returns the output. exe_file:- must pass the exe file name as str object type.
def sub_call(self, exe_file): """ This method can directly use call method of subprocess module and according to the argument(exe_file) passed it returns the output. exe_file:- must pass the exe file name as str object type. """ return subprocess.call([e...
[ "def", "sub_call", "(", "self", ",", "exe_file", ")", ":", "return", "subprocess", ".", "call", "(", "[", "exe_file", "]", ")" ]
[ 86, 4 ]
[ 94, 42 ]
python
en
['en', 'error', 'th']
False
Jarvis.get_dict
(self)
This method returns the dictionary of important task that can be performed by the JARVIS module. Later on this can also be used by the user itself to add or update their preferred apps.
This method returns the dictionary of important task that can be performed by the JARVIS module. Later on this can also be used by the user itself to add or update their preferred apps.
def get_dict(self): ''' This method returns the dictionary of important task that can be performed by the JARVIS module. Later on this can also be used by the user itself to add or update their preferred apps. ''' _dict = dict( time=datetime.now(), ...
[ "def", "get_dict", "(", "self", ")", ":", "_dict", "=", "dict", "(", "time", "=", "datetime", ".", "now", "(", ")", ",", "notepad", "=", "'Notepad.exe'", ",", "calculator", "=", "'calc.exe'", ",", "stickynot", "=", "'StickyNot.exe'", ",", "shell", "=", ...
[ 96, 4 ]
[ 113, 20 ]
python
en
['en', 'error', 'th']
False
AbstractFileLock.__init__
(self, filename)
Constructor, is given the filename of a potential lockfile. The usage of this filename is optional and no file is created by default. Raises ``NotImplementedError`` by default, must be implemented by subclasses.
Constructor, is given the filename of a potential lockfile.
def __init__(self, filename): """Constructor, is given the filename of a potential lockfile. The usage of this filename is optional and no file is created by default. Raises ``NotImplementedError`` by default, must be implemented by subclasses. """ raise NotImpl...
[ "def", "__init__", "(", "self", ",", "filename", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 290, 4 ]
[ 299, 35 ]
python
en
['en', 'en', 'en']
True
AbstractFileLock.acquire
(self, wait=True)
Acquire the "write" lock. This is a direct call to :meth:`.AbstractFileLock.acquire_write_lock`.
Acquire the "write" lock.
def acquire(self, wait=True): """Acquire the "write" lock. This is a direct call to :meth:`.AbstractFileLock.acquire_write_lock`. """ return self.acquire_write_lock(wait)
[ "def", "acquire", "(", "self", ",", "wait", "=", "True", ")", ":", "return", "self", ".", "acquire_write_lock", "(", "wait", ")" ]
[ 301, 4 ]
[ 307, 44 ]
python
en
['en', 'it', 'en']
True
AbstractFileLock.release
(self)
Release the "write" lock. This is a direct call to :meth:`.AbstractFileLock.release_write_lock`.
Release the "write" lock.
def release(self): """Release the "write" lock. This is a direct call to :meth:`.AbstractFileLock.release_write_lock`. """ self.release_write_lock()
[ "def", "release", "(", "self", ")", ":", "self", ".", "release_write_lock", "(", ")" ]
[ 309, 4 ]
[ 315, 33 ]
python
en
['en', 'it', 'en']
True
AbstractFileLock.read
(self)
Provide a context manager for the "read" lock. This method makes use of :meth:`.AbstractFileLock.acquire_read_lock` and :meth:`.AbstractFileLock.release_read_lock`
Provide a context manager for the "read" lock.
def read(self): """Provide a context manager for the "read" lock. This method makes use of :meth:`.AbstractFileLock.acquire_read_lock` and :meth:`.AbstractFileLock.release_read_lock` """ self.acquire_read_lock(True) try: yield finally: s...
[ "def", "read", "(", "self", ")", ":", "self", ".", "acquire_read_lock", "(", "True", ")", "try", ":", "yield", "finally", ":", "self", ".", "release_read_lock", "(", ")" ]
[ 318, 4 ]
[ 330, 36 ]
python
en
['en', 'en', 'en']
True
AbstractFileLock.write
(self)
Provide a context manager for the "write" lock. This method makes use of :meth:`.AbstractFileLock.acquire_write_lock` and :meth:`.AbstractFileLock.release_write_lock`
Provide a context manager for the "write" lock.
def write(self): """Provide a context manager for the "write" lock. This method makes use of :meth:`.AbstractFileLock.acquire_write_lock` and :meth:`.AbstractFileLock.release_write_lock` """ self.acquire_write_lock(True) try: yield finally: ...
[ "def", "write", "(", "self", ")", ":", "self", ".", "acquire_write_lock", "(", "True", ")", "try", ":", "yield", "finally", ":", "self", ".", "release_write_lock", "(", ")" ]
[ 333, 4 ]
[ 345, 37 ]
python
en
['en', 'en', 'en']
True
AbstractFileLock.is_open
(self)
optional method.
optional method.
def is_open(self): """optional method.""" raise NotImplementedError()
[ "def", "is_open", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 348, 4 ]
[ 350, 35 ]
python
en
['en', 'xh', 'en']
False
AbstractFileLock.acquire_read_lock
(self, wait)
Acquire a 'reader' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses.
Acquire a 'reader' lock.
def acquire_read_lock(self, wait): """Acquire a 'reader' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses. """ raise NotImplementedError()
[ "def", "acquire_read_lock", "(", "self", ",", "wait", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 352, 4 ]
[ 358, 35 ]
python
en
['en', 'it', 'en']
True
AbstractFileLock.acquire_write_lock
(self, wait)
Acquire a 'write' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses.
Acquire a 'write' lock.
def acquire_write_lock(self, wait): """Acquire a 'write' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses. """ raise NotImplementedError()
[ "def", "acquire_write_lock", "(", "self", ",", "wait", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 360, 4 ]
[ 366, 35 ]
python
en
['en', 'it', 'en']
True
AbstractFileLock.release_read_lock
(self)
Release a 'reader' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses.
Release a 'reader' lock.
def release_read_lock(self): """Release a 'reader' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses. """ raise NotImplementedError()
[ "def", "release_read_lock", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 368, 4 ]
[ 374, 35 ]
python
en
['en', 'de', 'en']
True
AbstractFileLock.release_write_lock
(self)
Release a 'writer' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses.
Release a 'writer' lock.
def release_write_lock(self): """Release a 'writer' lock. Raises ``NotImplementedError`` by default, must be implemented by subclasses. """ raise NotImplementedError()
[ "def", "release_write_lock", "(", "self", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 376, 4 ]
[ 382, 35 ]
python
en
['en', 'fy', 'en']
True
test_tensor_running_accum_reset
()
Test that reset would set all attributes to the initialization state
Test that reset would set all attributes to the initialization state
def test_tensor_running_accum_reset(): """ Test that reset would set all attributes to the initialization state """ window_length = 10 accum = TensorRunningAccum(window_length=window_length) assert accum.last() is None assert accum.mean() is None accum.append(torch.tensor(1.5)) assert acc...
[ "def", "test_tensor_running_accum_reset", "(", ")", ":", "window_length", "=", "10", "accum", "=", "TensorRunningAccum", "(", "window_length", "=", "window_length", ")", "assert", "accum", ".", "last", "(", ")", "is", "None", "assert", "accum", ".", "mean", "(...
[ 30, 0 ]
[ 48, 28 ]
python
en
['en', 'en', 'en']
True
test_cycle_iterator
()
Test the cycling function of `CycleIterator`
Test the cycling function of `CycleIterator`
def test_cycle_iterator(): """Test the cycling function of `CycleIterator`""" iterator = CycleIterator(range(100), 1000) assert len(iterator) == 1000 for idx, item in enumerate(iterator): assert item < 100 assert idx == len(iterator) - 1
[ "def", "test_cycle_iterator", "(", ")", ":", "iterator", "=", "CycleIterator", "(", "range", "(", "100", ")", ",", "1000", ")", "assert", "len", "(", "iterator", ")", "==", "1000", "for", "idx", ",", "item", "in", "enumerate", "(", "iterator", ")", ":"...
[ 51, 0 ]
[ 58, 35 ]
python
en
['en', 'en', 'en']
True
test_none_length_cycle_iterator
()
Test the infinite cycling function of `CycleIterator`
Test the infinite cycling function of `CycleIterator`
def test_none_length_cycle_iterator(): """Test the infinite cycling function of `CycleIterator`""" iterator = CycleIterator(range(100)) assert iterator.__len__() == float("inf") # test infinite loop for idx, item in enumerate(iterator): if idx == 1000: break assert item == 0
[ "def", "test_none_length_cycle_iterator", "(", ")", ":", "iterator", "=", "CycleIterator", "(", "range", "(", "100", ")", ")", "assert", "iterator", ".", "__len__", "(", ")", "==", "float", "(", "\"inf\"", ")", "# test infinite loop", "for", "idx", ",", "ite...
[ 61, 0 ]
[ 70, 20 ]
python
en
['en', 'en', 'en']
True
test_combined_dataset
(dataset_1, dataset_2)
Verify the length of the CombinedDataset
Verify the length of the CombinedDataset
def test_combined_dataset(dataset_1, dataset_2): """Verify the length of the CombinedDataset""" datasets = [dataset_1, dataset_2] combined_dataset = CombinedDataset(datasets) assert combined_dataset.max_len == 20 assert combined_dataset.min_len == len(combined_dataset) == 10
[ "def", "test_combined_dataset", "(", "dataset_1", ",", "dataset_2", ")", ":", "datasets", "=", "[", "dataset_1", ",", "dataset_2", "]", "combined_dataset", "=", "CombinedDataset", "(", "datasets", ")", "assert", "combined_dataset", ".", "max_len", "==", "20", "a...
[ 83, 0 ]
[ 89, 66 ]
python
en
['en', 'en', 'en']
True
test_combined_loader_iterator_dict_min_size
()
Test `CombinedLoaderIterator` given mapping loaders
Test `CombinedLoaderIterator` given mapping loaders
def test_combined_loader_iterator_dict_min_size(): """Test `CombinedLoaderIterator` given mapping loaders""" loaders = { "a": torch.utils.data.DataLoader(range(10), batch_size=4), "b": torch.utils.data.DataLoader(range(20), batch_size=5), } combined_iter = CombinedLoaderIterator(loaders...
[ "def", "test_combined_loader_iterator_dict_min_size", "(", ")", ":", "loaders", "=", "{", "\"a\"", ":", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "range", "(", "10", ")", ",", "batch_size", "=", "4", ")", ",", "\"b\"", ":", "torch", "."...
[ 97, 0 ]
[ 111, 63 ]
python
en
['da', 'en', 'en']
True
test_combined_loader_init_mode_error
()
Test the ValueError when constructing `CombinedLoader`
Test the ValueError when constructing `CombinedLoader`
def test_combined_loader_init_mode_error(): """Test the ValueError when constructing `CombinedLoader`""" with pytest.raises(MisconfigurationException, match="selected unsupported mode"): CombinedLoader([range(10)], "testtt")
[ "def", "test_combined_loader_init_mode_error", "(", ")", ":", "with", "pytest", ".", "raises", "(", "MisconfigurationException", ",", "match", "=", "\"selected unsupported mode\"", ")", ":", "CombinedLoader", "(", "[", "range", "(", "10", ")", "]", ",", "\"testtt\...
[ 114, 0 ]
[ 117, 45 ]
python
en
['en', 'nl', 'en']
True
test_combined_loader_loader_type_error
()
Test the ValueError when wrapping the loaders
Test the ValueError when wrapping the loaders
def test_combined_loader_loader_type_error(): """Test the ValueError when wrapping the loaders""" with pytest.raises(ValueError, match="Invalid Datatype"): CombinedLoader(None, "max_size_cycle")
[ "def", "test_combined_loader_loader_type_error", "(", ")", ":", "with", "pytest", ".", "raises", "(", "ValueError", ",", "match", "=", "\"Invalid Datatype\"", ")", ":", "CombinedLoader", "(", "None", ",", "\"max_size_cycle\"", ")" ]
[ 120, 0 ]
[ 123, 46 ]
python
en
['en', 'en', 'en']
True
test_combined_loader_calc_length_mode_error
()
Test the ValueError when calculating the number of batches
Test the ValueError when calculating the number of batches
def test_combined_loader_calc_length_mode_error(): """Test the ValueError when calculating the number of batches""" with pytest.raises(TypeError, match="Expected data to be int, Sequence or Mapping, but got NoneType"): CombinedLoader._calc_num_batches(None)
[ "def", "test_combined_loader_calc_length_mode_error", "(", ")", ":", "with", "pytest", ".", "raises", "(", "TypeError", ",", "match", "=", "\"Expected data to be int, Sequence or Mapping, but got NoneType\"", ")", ":", "CombinedLoader", ".", "_calc_num_batches", "(", "None"...
[ 126, 0 ]
[ 129, 46 ]
python
en
['en', 'en', 'en']
True
test_combined_loader_dict_min_size
()
Test `CombinedLoader` of mode 'min_size' given mapping loaders
Test `CombinedLoader` of mode 'min_size' given mapping loaders
def test_combined_loader_dict_min_size(): """Test `CombinedLoader` of mode 'min_size' given mapping loaders""" loaders = { "a": torch.utils.data.DataLoader(range(10), batch_size=4), "b": torch.utils.data.DataLoader(range(20), batch_size=5), } combined_loader = CombinedLoader(loaders, "m...
[ "def", "test_combined_loader_dict_min_size", "(", ")", ":", "loaders", "=", "{", "\"a\"", ":", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "range", "(", "10", ")", ",", "batch_size", "=", "4", ")", ",", "\"b\"", ":", "torch", ".", "util...
[ 132, 0 ]
[ 148, 42 ]
python
en
['en', 'en', 'en']
True
test_combined_loader_dict_max_size_cycle
()
Test `CombinedLoader` of mode 'max_size_cycle' given mapping loaders
Test `CombinedLoader` of mode 'max_size_cycle' given mapping loaders
def test_combined_loader_dict_max_size_cycle(): """Test `CombinedLoader` of mode 'max_size_cycle' given mapping loaders""" loaders = { "a": torch.utils.data.DataLoader(range(10), batch_size=4), "b": torch.utils.data.DataLoader(range(20), batch_size=5), } combined_loader = CombinedLoader...
[ "def", "test_combined_loader_dict_max_size_cycle", "(", ")", ":", "loaders", "=", "{", "\"a\"", ":", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "range", "(", "10", ")", ",", "batch_size", "=", "4", ")", ",", "\"b\"", ":", "torch", ".", ...
[ 151, 0 ]
[ 167, 42 ]
python
en
['en', 'en', 'en']
True
test_combined_loader_sequence_min_size
()
Test `CombinedLoader` of mode 'min_size' given sequence loaders
Test `CombinedLoader` of mode 'min_size' given sequence loaders
def test_combined_loader_sequence_min_size(): """Test `CombinedLoader` of mode 'min_size' given sequence loaders""" loaders = [ torch.utils.data.DataLoader(range(10), batch_size=4), torch.utils.data.DataLoader(range(20), batch_size=5), ] combined_loader = CombinedLoader(loaders, "min_si...
[ "def", "test_combined_loader_sequence_min_size", "(", ")", ":", "loaders", "=", "[", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "range", "(", "10", ")", ",", "batch_size", "=", "4", ")", ",", "torch", ".", "utils", ".", "data", ".", "D...
[ 170, 0 ]
[ 185, 42 ]
python
en
['en', 'en', 'en']
True
test_combined_loader_sequence_max_size_cycle
()
Test `CombinedLoader` of mode 'max_size_cycle' given sequence loaders
Test `CombinedLoader` of mode 'max_size_cycle' given sequence loaders
def test_combined_loader_sequence_max_size_cycle(): """Test `CombinedLoader` of mode 'max_size_cycle' given sequence loaders""" loaders = [ torch.utils.data.DataLoader(range(10), batch_size=4), torch.utils.data.DataLoader(range(20), batch_size=5), ] combined_loader = CombinedLoader(load...
[ "def", "test_combined_loader_sequence_max_size_cycle", "(", ")", ":", "loaders", "=", "[", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "range", "(", "10", ")", ",", "batch_size", "=", "4", ")", ",", "torch", ".", "utils", ".", "data", "."...
[ 188, 0 ]
[ 203, 42 ]
python
en
['en', 'en', 'en']
True
test_train_step_no_return
(tmpdir, single_cb)
Tests that only training_step can be used
Tests that only training_step can be used
def test_train_step_no_return(tmpdir, single_cb): """ Tests that only training_step can be used """ class CB(Callback): def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): d = outputs[0][0] assert 'minimize' in d def on_...
[ "def", "test_train_step_no_return", "(", "tmpdir", ",", "single_cb", ")", ":", "class", "CB", "(", "Callback", ")", ":", "def", "on_train_batch_end", "(", "self", ",", "trainer", ",", "pl_module", ",", "outputs", ",", "batch", ",", "batch_idx", ",", "dataloa...
[ 20, 0 ]
[ 72, 18 ]
python
en
['en', 'error', 'th']
False
test_cpu_slurm_save_load
(tmpdir)
Verify model save/load/checkpoint on CPU.
Verify model save/load/checkpoint on CPU.
def test_cpu_slurm_save_load(tmpdir): """Verify model save/load/checkpoint on CPU.""" model = BoringModel() # logger file to get meta logger = tutils.get_default_logger(tmpdir) version = logger.version # fit model trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, ...
[ "def", "test_cpu_slurm_save_load", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "# logger file to get meta", "logger", "=", "tutils", ".", "get_default_logger", "(", "tmpdir", ")", "version", "=", "logger", ".", "version", "# fit model", "traine...
[ 29, 0 ]
[ 94, 22 ]
python
en
['wa', 'en', 'en']
True
test_multi_cpu_model_ddp
(tmpdir)
Make sure DDP works.
Make sure DDP works.
def test_multi_cpu_model_ddp(tmpdir): """Make sure DDP works.""" tutils.set_random_master_port() trainer_options = dict( default_root_dir=tmpdir, progress_bar_refresh_rate=0, max_epochs=1, limit_train_batches=0.4, limit_val_batches=0.2, gpus=None, num...
[ "def", "test_multi_cpu_model_ddp", "(", "tmpdir", ")", ":", "tutils", ".", "set_random_master_port", "(", ")", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "progress_bar_refresh_rate", "=", "0", ",", "max_epochs", "=", "1", ",", "...
[ 129, 0 ]
[ 146, 72 ]
python
en
['en', 'da', 'en']
True
test_lbfgs_cpu_model
(tmpdir)
Test each of the trainer options. Testing LBFGS optimizer
Test each of the trainer options. Testing LBFGS optimizer
def test_lbfgs_cpu_model(tmpdir): """Test each of the trainer options. Testing LBFGS optimizer""" class ModelSpecifiedOptimizer(BoringModel): def __init__(self, optimizer_name, learning_rate): super().__init__() self.optimizer_name = optimizer_name self.learning_rat...
[ "def", "test_lbfgs_cpu_model", "(", "tmpdir", ")", ":", "class", "ModelSpecifiedOptimizer", "(", "BoringModel", ")", ":", "def", "__init__", "(", "self", ",", "optimizer_name", ",", "learning_rate", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "se...
[ 149, 0 ]
[ 170, 79 ]
python
en
['en', 'en', 'en']
True
test_default_logger_callbacks_cpu_model
(tmpdir)
Test each of the trainer options.
Test each of the trainer options.
def test_default_logger_callbacks_cpu_model(tmpdir): """Test each of the trainer options.""" trainer_options = dict( default_root_dir=tmpdir, max_epochs=1, gradient_clip_val=1.0, overfit_batches=0.20, progress_bar_refresh_rate=0, limit_train_batches=0.01, ...
[ "def", "test_default_logger_callbacks_cpu_model", "(", "tmpdir", ")", ":", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "max_epochs", "=", "1", ",", "gradient_clip_val", "=", "1.0", ",", "overfit_batches", "=", "0.20", ",", "progres...
[ 173, 0 ]
[ 190, 20 ]
python
en
['en', 'en', 'en']
True
test_running_test_after_fitting
(tmpdir)
Verify test() on fitted model.
Verify test() on fitted model.
def test_running_test_after_fitting(tmpdir): """Verify test() on fitted model.""" class ModelTrainValTest(BoringModel): def validation_step(self, *args, **kwargs): output = super().validation_step(*args, **kwargs) self.log('val_loss', output['x']) return output ...
[ "def", "test_running_test_after_fitting", "(", "tmpdir", ")", ":", "class", "ModelTrainValTest", "(", "BoringModel", ")", ":", "def", "validation_step", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "output", "=", "super", "(", ")", "."...
[ 193, 0 ]
[ 234, 65 ]
python
en
['en', 'en', 'en']
True
test_running_test_no_val
(tmpdir)
Verify `test()` works on a model with no `val_dataloader`. It performs train and test only
Verify `test()` works on a model with no `val_dataloader`. It performs train and test only
def test_running_test_no_val(tmpdir): """Verify `test()` works on a model with no `val_dataloader`. It performs train and test only""" class ModelTrainTest(BoringModel): def val_dataloader(self): pass def test_step(self, *args, **kwargs): output = super().test_step...
[ "def", "test_running_test_no_val", "(", "tmpdir", ")", ":", "class", "ModelTrainTest", "(", "BoringModel", ")", ":", "def", "val_dataloader", "(", "self", ")", ":", "pass", "def", "test_step", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ...
[ 237, 0 ]
[ 277, 56 ]
python
en
['en', 'en', 'en']
True
test_simple_cpu
(tmpdir)
Verify continue training session on CPU.
Verify continue training session on CPU.
def test_simple_cpu(tmpdir): """Verify continue training session on CPU.""" model = BoringModel() # fit model trainer = Trainer( default_root_dir=tmpdir, max_epochs=1, limit_val_batches=0.1, limit_train_batches=20, ) trainer.fit(model) # traning complete ...
[ "def", "test_simple_cpu", "(", "tmpdir", ")", ":", "model", "=", "BoringModel", "(", ")", "# fit model", "trainer", "=", "Trainer", "(", "default_root_dir", "=", "tmpdir", ",", "max_epochs", "=", "1", ",", "limit_val_batches", "=", "0.1", ",", "limit_train_bat...
[ 280, 0 ]
[ 294, 87 ]
python
en
['en', 'en', 'en']
True
test_cpu_model
(tmpdir)
Make sure model trains on CPU.
Make sure model trains on CPU.
def test_cpu_model(tmpdir): """Make sure model trains on CPU.""" trainer_options = dict( default_root_dir=tmpdir, progress_bar_refresh_rate=0, max_epochs=1, limit_train_batches=4, limit_val_batches=4 ) model = BoringModel() tpipes.run_model_test(trainer_options, model, on_gpu=False)
[ "def", "test_cpu_model", "(", "tmpdir", ")", ":", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "progress_bar_refresh_rate", "=", "0", ",", "max_epochs", "=", "1", ",", "limit_train_batches", "=", "4", ",", "limit_val_batches", "="...
[ 297, 0 ]
[ 304, 63 ]
python
en
['en', 'en', 'en']
True
test_all_features_cpu_model
(tmpdir)
Test each of the trainer options.
Test each of the trainer options.
def test_all_features_cpu_model(tmpdir): """Test each of the trainer options.""" trainer_options = dict( default_root_dir=tmpdir, gradient_clip_val=1.0, overfit_batches=0.20, track_grad_norm=2, progress_bar_refresh_rate=0, accumulate_grad_batches=2, max_ep...
[ "def", "test_all_features_cpu_model", "(", "tmpdir", ")", ":", "trainer_options", "=", "dict", "(", "default_root_dir", "=", "tmpdir", ",", "gradient_clip_val", "=", "1.0", ",", "overfit_batches", "=", "0.20", ",", "track_grad_norm", "=", "2", ",", "progress_bar_r...
[ 307, 0 ]
[ 323, 77 ]
python
en
['en', 'en', 'en']
True
test_tbptt_cpu_model
(tmpdir)
Test truncated back propagation through time works.
Test truncated back propagation through time works.
def test_tbptt_cpu_model(tmpdir): """Test truncated back propagation through time works.""" truncated_bptt_steps = 2 sequence_size = 30 batch_size = 30 x_seq = torch.rand(batch_size, sequence_size, 1) y_seq_list = torch.rand(batch_size, sequence_size, 1).tolist() class MockSeq2SeqDataset(t...
[ "def", "test_tbptt_cpu_model", "(", "tmpdir", ")", ":", "truncated_bptt_steps", "=", "2", "sequence_size", "=", "30", "batch_size", "=", "30", "x_seq", "=", "torch", ".", "rand", "(", "batch_size", ",", "sequence_size", ",", "1", ")", "y_seq_list", "=", "tor...
[ 326, 0 ]
[ 395, 90 ]
python
en
['en', 'en', 'en']
True
test_min_max_steps_epochs
(tmpdir, min_epochs, max_epochs, min_steps, max_steps)
Tests that max_steps can be used without max_epochs
Tests that max_steps can be used without max_epochs
def test_min_max_steps_epochs(tmpdir, min_epochs, max_epochs, min_steps, max_steps): """ Tests that max_steps can be used without max_epochs """ model = BoringModel() trainer = Trainer( default_root_dir=tmpdir, min_epochs=min_epochs, max_epochs=max_epochs, min_steps=...
[ "def", "test_min_max_steps_epochs", "(", "tmpdir", ",", "min_epochs", ",", "max_epochs", ",", "min_steps", ",", "max_steps", ")", ":", "model", "=", "BoringModel", "(", ")", "trainer", "=", "Trainer", "(", "default_root_dir", "=", "tmpdir", ",", "min_epochs", ...
[ 18, 0 ]
[ 38, 55 ]
python
en
['en', 'error', 'th']
False
Runner.args
(self)
Parsed args
Parsed args
def args(self) -> argparse.Namespace: """Parsed args""" return self.parser.parse_known_args(self._args)[0]
[ "def", "args", "(", "self", ")", "->", "argparse", ".", "Namespace", ":", "return", "self", ".", "parser", ".", "parse_known_args", "(", "self", ".", "_args", ")", "[", "0", "]" ]
[ 31, 4 ]
[ 33, 58 ]
python
en
['en', 'la', 'en']
False
Runner.extra_args
(self)
Unparsed args
Unparsed args
def extra_args(self) -> list: """Unparsed args""" return self.parser.parse_known_args(self._args)[1]
[ "def", "extra_args", "(", "self", ")", "->", "list", ":", "return", "self", ".", "parser", ".", "parse_known_args", "(", "self", ".", "_args", ")", "[", "1", "]" ]
[ 36, 4 ]
[ 38, 58 ]
python
en
['en', 'la', 'it']
False
Runner.log
(self)
Instantiated logger
Instantiated logger
def log(self) -> logging.Logger: """Instantiated logger""" logger = logging.getLogger(self.name) logger.setLevel(self.log_level) stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(logging.DEBUG) stdout_handler.addFilter(LogFilter()) stderr_...
[ "def", "log", "(", "self", ")", "->", "logging", ".", "Logger", ":", "logger", "=", "logging", ".", "getLogger", "(", "self", ".", "name", ")", "logger", ".", "setLevel", "(", "self", ".", "log_level", ")", "stdout_handler", "=", "logging", ".", "Strea...
[ 41, 4 ]
[ 52, 21 ]
python
en
['en', 'en', 'en']
False
Runner.log_level
(self)
Log level parsed from args
Log level parsed from args
def log_level(self) -> int: """Log level parsed from args""" return dict(LOG_LEVELS)[self.args.log_level]
[ "def", "log_level", "(", "self", ")", "->", "int", ":", "return", "dict", "(", "LOG_LEVELS", ")", "[", "self", ".", "args", ".", "log_level", "]" ]
[ 55, 4 ]
[ 57, 52 ]
python
en
['en', 'en', 'en']
True
Runner.name
(self)
Name of the runner
Name of the runner
def name(self) -> str: """Name of the runner""" return self.__class__.__name__
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "self", ".", "__class__", ".", "__name__" ]
[ 60, 4 ]
[ 62, 38 ]
python
en
['en', 'no', 'en']
True
Runner.parser
(self)
Argparse parser
Argparse parser
def parser(self) -> argparse.ArgumentParser: """Argparse parser""" parser = argparse.ArgumentParser(allow_abbrev=False) self.add_arguments(parser) return parser
[ "def", "parser", "(", "self", ")", "->", "argparse", ".", "ArgumentParser", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "allow_abbrev", "=", "False", ")", "self", ".", "add_arguments", "(", "parser", ")", "return", "parser" ]
[ 65, 4 ]
[ 69, 21 ]
python
de
['en', 'de', 'hi']
False
Runner.add_arguments
(self, parser: argparse.ArgumentParser)
Override this method to add custom arguments to the arg parser
Override this method to add custom arguments to the arg parser
def add_arguments(self, parser: argparse.ArgumentParser) -> None: """Override this method to add custom arguments to the arg parser""" pass
[ "def", "add_arguments", "(", "self", ",", "parser", ":", "argparse", ".", "ArgumentParser", ")", "->", "None", ":", "pass" ]
[ 75, 4 ]
[ 77, 12 ]
python
en
['en', 'en', 'en']
True
ForkingAdapter.subproc_run
( self, *args, capture_output: bool = True, **kwargs)
Fork a subprocess, using self.context.path as the cwd by default
Fork a subprocess, using self.context.path as the cwd by default
def subproc_run( self, *args, capture_output: bool = True, **kwargs) -> subprocess.CompletedProcess: """Fork a subprocess, using self.context.path as the cwd by default""" kwargs["cwd"] = kwargs.get("cwd", self.context.path) return subprocess.run(*args, capture_output=capture_output,...
[ "def", "subproc_run", "(", "self", ",", "*", "args", ",", "capture_output", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ")", "->", "subprocess", ".", "CompletedProcess", ":", "kwargs", "[", "\"cwd\"", "]", "=", "kwargs", ".", "get", "(", "\"cwd\...
[ 88, 4 ]
[ 92, 77 ]
python
en
['en', 'en', 'en']
True
BazelAdapter.query
(self, query: str)
Run a bazel query and return stdout as list of lines
Run a bazel query and return stdout as list of lines
def query(self, query: str) -> list: """Run a bazel query and return stdout as list of lines""" resp = self.context.subproc_run(["bazel", "query", f"'{query}'"]) if resp.returncode: raise BazelRunError(f"Bazel query failed: {resp}") return resp.stdout.decode("utf-8").split("\...
[ "def", "query", "(", "self", ",", "query", ":", "str", ")", "->", "list", ":", "resp", "=", "self", ".", "context", ".", "subproc_run", "(", "[", "\"bazel\"", ",", "\"query\"", ",", "f\"'{query}'\"", "]", ")", "if", "resp", ".", "returncode", ":", "r...
[ 100, 4 ]
[ 105, 54 ]
python
en
['en', 'en', 'en']
True
BazelAdapter.run
( self, target: str, *args, capture_output: bool = False, cwd: str = "", raises: bool = True)
Run a bazel target and return the subprocess response
Run a bazel target and return the subprocess response
def run( self, target: str, *args, capture_output: bool = False, cwd: str = "", raises: bool = True) -> subprocess.CompletedProcess: """Run a bazel target and return the subprocess response""" args = (("--",) + args) if args else ar...
[ "def", "run", "(", "self", ",", "target", ":", "str", ",", "*", "args", ",", "capture_output", ":", "bool", "=", "False", ",", "cwd", ":", "str", "=", "\"\"", ",", "raises", ":", "bool", "=", "True", ")", "->", "subprocess", ".", "CompletedProcess", ...
[ 107, 4 ]
[ 121, 19 ]
python
en
['en', 'su', 'en']
True
_fr0
(a)
fix rank-0 --> rank-1
fix rank-0 --> rank-1
def _fr0(a): """fix rank-0 --> rank-1""" if a.ndim == 0: a = a.copy() a.shape = (1,) return a
[ "def", "_fr0", "(", "a", ")", ":", "if", "a", ".", "ndim", "==", "0", ":", "a", "=", "a", ".", "copy", "(", ")", "a", ".", "shape", "=", "(", "1", ",", ")", "return", "a" ]
[ 18, 0 ]
[ 23, 12 ]
python
en
['en', 'hu', 'en']
True
_fr1
(a)
fix rank > 0 --> rank-0
fix rank > 0 --> rank-0
def _fr1(a): """fix rank > 0 --> rank-0""" if a.size == 1: a = a.copy() a.shape = () return a
[ "def", "_fr1", "(", "a", ")", ":", "if", "a", ".", "size", "==", "1", ":", "a", "=", "a", ".", "copy", "(", ")", "a", ".", "shape", "=", "(", ")", "return", "a" ]
[ 26, 0 ]
[ 31, 12 ]
python
en
['en', 'hu', 'en']
True
_get_machar
(ftype)
Get MachAr instance or MachAr-like instance Get parameters for floating point type, by first trying signatures of various known floating point types, then, if none match, attempting to identify parameters by analysis. Parameters ---------- ftype : class Numpy floating point type class...
Get MachAr instance or MachAr-like instance
def _get_machar(ftype): """ Get MachAr instance or MachAr-like instance Get parameters for floating point type, by first trying signatures of various known floating point types, then, if none match, attempting to identify parameters by analysis. Parameters ---------- ftype : class ...
[ "def", "_get_machar", "(", "ftype", ")", ":", "params", "=", "_MACHAR_PARAMS", ".", "get", "(", "ftype", ")", "if", "params", "is", "None", ":", "raise", "ValueError", "(", "repr", "(", "ftype", ")", ")", "# Detect known / suspected types", "key", "=", "ft...
[ 238, 0 ]
[ 278, 36 ]
python
en
['en', 'de', 'en']
True
_discovered_machar
(ftype)
Create MachAr instance with found information on float types
Create MachAr instance with found information on float types
def _discovered_machar(ftype): """ Create MachAr instance with found information on float types """ params = _MACHAR_PARAMS[ftype] return MachAr(lambda v: array([v], ftype), lambda v:_fr0(v.astype(params['itype']))[0], lambda v:array(_fr0(v)[0], ftype), ...
[ "def", "_discovered_machar", "(", "ftype", ")", ":", "params", "=", "_MACHAR_PARAMS", "[", "ftype", "]", "return", "MachAr", "(", "lambda", "v", ":", "array", "(", "[", "v", "]", ",", "ftype", ")", ",", "lambda", "v", ":", "_fr0", "(", "v", ".", "a...
[ 281, 0 ]
[ 289, 34 ]
python
en
['en', 'en', 'en']
True
Iface.add
(self, a, b)
Parameters: - a - b
Parameters: - a - b
def add(self, a, b): """ Parameters: - a - b """ pass
[ "def", "add", "(", "self", ",", "a", ",", "b", ")", ":", "pass" ]
[ 27, 4 ]
[ 33, 12 ]
python
en
['en', 'error', 'th']
False
Iface.execute
(self, input)
Parameters: - input
Parameters: - input
def execute(self, input): """ Parameters: - input """ pass
[ "def", "execute", "(", "self", ",", "input", ")", ":", "pass" ]
[ 35, 4 ]
[ 40, 12 ]
python
en
['en', 'error', 'th']
False
Client.add
(self, a, b)
Parameters: - a - b
Parameters: - a - b
def add(self, a, b): """ Parameters: - a - b """ self.send_add(a, b) return self.recv_add()
[ "def", "add", "(", "self", ",", "a", ",", "b", ")", ":", "self", ".", "send_add", "(", "a", ",", "b", ")", "return", "self", ".", "recv_add", "(", ")" ]
[ 84, 4 ]
[ 91, 30 ]
python
en
['en', 'error', 'th']
False
Client.execute
(self, input)
Parameters: - input
Parameters: - input
def execute(self, input): """ Parameters: - input """ self.send_execute(input) return self.recv_execute()
[ "def", "execute", "(", "self", ",", "input", ")", ":", "self", ".", "send_execute", "(", "input", ")", "return", "self", ".", "recv_execute", "(", ")" ]
[ 117, 4 ]
[ 123, 34 ]
python
en
['en', 'error', 'th']
False
build_optimizers
(model, cfgs)
Build multiple optimizers from configs. If `cfgs` contains several dicts for optimizers, then a dict for each constructed optimizers will be returned. If `cfgs` only contains one optimizer config, the constructed optimizer itself will be returned. For example, 1) Multiple optimizer configs: ...
Build multiple optimizers from configs.
def build_optimizers(model, cfgs): """Build multiple optimizers from configs. If `cfgs` contains several dicts for optimizers, then a dict for each constructed optimizers will be returned. If `cfgs` only contains one optimizer config, the constructed optimizer itself will be returned. For exam...
[ "def", "build_optimizers", "(", "model", ",", "cfgs", ")", ":", "optimizers", "=", "{", "}", "if", "hasattr", "(", "model", ",", "'module'", ")", ":", "model", "=", "model", ".", "module", "# determine whether 'cfgs' has several dicts for optimizers", "if", "all...
[ 3, 0 ]
[ 51, 39 ]
python
en
['en', 'en', 'en']
True