uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
537402fb8973e82cb9ee8fd9
train
class
class L1Unstructured(BasePruningMethod): r"""Prune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of ...
class L1Unstructured(BasePruningMethod):
r"""Prune (currently unpruned) units in a tensor by zeroing out the ones with the lowest L1-norm. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it repre...
amount): r"""Adds the forward pre-hook that enables pruning on the fly and the reparametrization of a tensor in terms of the original tensor and the pruning mask. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within `...
168
168
562
10
158
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
L1Unstructured
L1Unstructured
479
536
479
479
6ac3bf5d8ab9f88651bed0148b0e022a4e04c339
bigcode/the-stack
train
7c95475786025f394936f113
train
function
def ln_structured(module, name, amount, n, dim): r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) channels along the specified ``dim`` with the lowest L``n``-norm. Modifies module in place (and also return the modifie...
def ln_structured(module, name, amount, n, dim):
r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) channels along the specified ``dim`` with the lowest L``n``-norm. Modifies module in place (and also return the modified module) by: 1) adding a named buffer ca...
: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.random_structured( nn.Linear(5, 3), 'weight', amount=3, dim=1 ) >>> columns_pruned = int(sum(torch.sum(m.weight, dim=0) == 0)) >>> print(columns_pruned) ...
119
119
398
14
104
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
ln_structured
ln_structured
927
960
927
927
46b7676a200f46e0e53b1d4f02e32d410ab0f89f
bigcode/the-stack
train
b85ffa52614649922c1a22ef
train
function
def _validate_pruning_amount(amount, tensor_size): r"""Validation helper to check that the amount of parameters to prune is meaningful wrt to the size of the data (`tensor_size`). Args: amount (int or float): quantity of parameters to prune. If float, should be between 0.0 and 1.0 and r...
def _validate_pruning_amount(amount, tensor_size):
r"""Validation helper to check that the amount of parameters to prune is meaningful wrt to the size of the data (`tensor_size`). Args: amount (int or float): quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to ...
> 1.0 or amount < 0.0) ): raise ValueError( "amount={} should either be a float in the " "range [0, 1] or a non-negative integer" "".format(amount) ) def _validate_pruning_amount(amount, tensor_size):
65
65
218
11
54
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
_validate_pruning_amount
_validate_pruning_amount
1,192
1,212
1,192
1,192
5ad6d5ac908076c276f31b7f027ca71fbb8edbd4
bigcode/the-stack
train
4d2f70cc29a7ee92973636ec
train
class
class PruningContainer(BasePruningMethod): """Container holding a sequence of pruning methods for iterative pruning. Keeps track of the order in which pruning methods are applied and handles combining successive pruning calls. Accepts as argument an instance of a BasePruningMethod or an iterable of ...
class PruningContainer(BasePruningMethod):
"""Container holding a sequence of pruning methods for iterative pruning. Keeps track of the order in which pruning methods are applied and handles combining successive pruning calls. Accepts as argument an instance of a BasePruningMethod or an iterable of them. """ def __init__(self, *arg...
def remove(self, module): r"""Removes the pruning reparameterization from a module. The pruned parameter named ``name`` remains permanently pruned, and the parameter named ``name+'_orig'`` is removed from the parameter list. Similarly, the buffer named ``name+'_mask'`` is removed from t...
256
256
1,319
9
247
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
PruningContainer
PruningContainer
244
392
244
244
4585e2a0480fe3162b2a7d50f3070d27b9dc2c3e
bigcode/the-stack
train
c28746fcd1eca8ca492d80e8
train
class
class RandomUnstructured(BasePruningMethod): r"""Prune (currently unpruned) units in a tensor at random. Args: name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between ...
class RandomUnstructured(BasePruningMethod):
r"""Prune (currently unpruned) units in a tensor at random. Args: name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fra...
prune any units but generates the pruning parametrization with a mask of ones. """ PRUNING_TYPE = "unstructured" def compute_mask(self, t, default_mask): mask = default_mask return mask @classmethod def apply(cls, module, name): r"""Adds the forward pre-hook that enab...
160
160
534
9
151
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
RandomUnstructured
RandomUnstructured
420
476
420
420
bf1af8871a2c1d137bbd92f12a2b87a7b3c4d5c3
bigcode/the-stack
train
b90bbafd0e52f537e733cfd5
train
class
class BasePruningMethod(ABC): r"""Abstract base class for creation of new pruning techniques. Provides a skeleton for customization requiring the overriding of methods such as :meth:`compute_mask` and :meth:`apply`. """ def __init__(self): pass def __call__(self, module, inputs): ...
class BasePruningMethod(ABC):
r"""Abstract base class for creation of new pruning techniques. Provides a skeleton for customization requiring the overriding of methods such as :meth:`compute_mask` and :meth:`apply`. """ def __init__(self): pass def __call__(self, module, inputs): r"""Multiplies the mask (st...
r""" Pruning methods """ from abc import abstractmethod import numbers import torch # For Python 2 and 3 support try: from abc import ABC from collections.abc import Iterable except ImportError: from abc import ABCMeta ABC = ABCMeta('ABC', (), {}) from collections import Iterable class BasePruningMe...
80
256
2,063
8
71
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
BasePruningMethod
BasePruningMethod
16
241
16
16
316381cea590fc618bb9bdf7ab1920826136057b
bigcode/the-stack
train
b856ea2f122a2d1d564e6c59
train
class
class CustomFromMask(BasePruningMethod): PRUNING_TYPE = "global" def __init__(self, mask): self.mask = mask def compute_mask(self, t, default_mask): assert default_mask.shape == self.mask.shape mask = default_mask * self.mask.to(dtype=default_mask.dtype) return mask @...
class CustomFromMask(BasePruningMethod):
PRUNING_TYPE = "global" def __init__(self, mask): self.mask = mask def compute_mask(self, t, default_mask): assert default_mask.shape == self.mask.shape mask = default_mask * self.mask.to(dtype=default_mask.dtype) return mask @classmethod def apply(cls, module, nam...
func:`torch.norm`. dim (int): index of the dim along which we define channels to prune. """ return super(LnStructured, cls).apply( module, name, amount=amount, n=n, dim=dim ) class CustomFromMask(BasePruningMethod):
64
64
183
9
55
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
CustomFromMask
CustomFromMask
765
790
765
766
102a5d55845b3be8c3f0599b82cc571295d2bdd7
bigcode/the-stack
train
71e01a549fa361e79c8d4f63
train
function
def random_unstructured(module, name, amount): r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) units selected at random. Modifies module in place (and also return the modified module) by: 1) adding a named buffer...
def random_unstructured(module, name, amount):
r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) units selected at random. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the ...
module`` on which pruning will act. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.identity(nn.Linear(2, 3), 'bias') >>> print(m.bias_mask) tensor([1., 1., 1.]) """ Identity.apply(module, name) ...
95
95
318
10
84
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
random_unstructured
random_unstructured
824
854
824
824
6ce49625b78757c42c4409562dbf301b82003a77
bigcode/the-stack
train
655f6d6b2f003d0a5f8d605d
train
function
def _compute_nparams_toprune(amount, tensor_size): r"""Since amount can be expressed either in absolute value or as a percentage of the number of units/channels in a tensor, this utility function converts the percentage to absolute value to standardize the handling of pruning. Args: amount ...
def _compute_nparams_toprune(amount, tensor_size):
r"""Since amount can be expressed either in absolute value or as a percentage of the number of units/channels in a tensor, this utility function converts the percentage to absolute value to standardize the handling of pruning. Args: amount (int or float): quantity of parameters to prune. ...
if len(shape) <= 1: raise ValueError( "Structured pruning can only be applied to " "multidimensional tensors. Found tensor of shape " "{} with {} dims".format(shape, len(shape)) ) def _compute_nparams_toprune(amount, tensor_size):
64
64
206
13
51
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
_compute_nparams_toprune
_compute_nparams_toprune
1,234
1,255
1,234
1,234
f17c586369837cc8c823c2be7df71b92477f1878
bigcode/the-stack
train
76caf488934b05603626ee9a
train
function
def _validate_pruning_dim(t, dim): r""" Args: t (torch.Tensor): tensor representing the parameter to prune dim (int): index of the dim along which we define channels to prune """ if dim >= t.dim(): raise IndexError( "Invalid index {} for tensor of size {}".format(dim,...
def _validate_pruning_dim(t, dim):
r""" Args: t (torch.Tensor): tensor representing the parameter to prune dim (int): index of the dim along which we define channels to prune """ if dim >= t.dim(): raise IndexError( "Invalid index {} for tensor of size {}".format(dim, t.shape) )
the tensor """ # incorrect type already checked in _validate_pruning_amount_init if isinstance(amount, numbers.Integral): return amount else: return int(round(amount * tensor_size)) # int needed for Python 2 def _validate_pruning_dim(t, dim):
64
64
78
10
53
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
_validate_pruning_dim
_validate_pruning_dim
1,258
1,267
1,258
1,258
8706edf41a3ba82f4741059fc123d91250cb2a7d
bigcode/the-stack
train
26b559585f3b4994d84b2507
train
class
class Identity(BasePruningMethod): r"""Utility pruning method that does not prune any units but generates the pruning parametrization with a mask of ones. """ PRUNING_TYPE = "unstructured" def compute_mask(self, t, default_mask): mask = default_mask return mask @classmethod ...
class Identity(BasePruningMethod):
r"""Utility pruning method that does not prune any units but generates the pruning parametrization with a mask of ones. """ PRUNING_TYPE = "unstructured" def compute_mask(self, t, default_mask): mask = default_mask return mask @classmethod def apply(cls, module, name): ...
default_mask=mask[slc]) new_mask[slc] = partial_mask.to(dtype=new_mask.dtype) return new_mask method = self._pruning_methods[-1] mask = _combine_masks(method, t, default_mask) return mask class Identity(BasePruningMethod):
64
64
167
7
56
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
Identity
Identity
395
417
395
395
360059e618828865ed111317ac01bb3d06c298da
bigcode/the-stack
train
d4f42c5de6b9cc87967f457e
train
function
def remove(module, name): r"""Removes the pruning reparameterization from a module and the pruning method from the forward hook. The pruned parameter named ``name`` remains permanently pruned, and the parameter named ``name+'_orig'`` is removed from the parameter list. Similarly, the buffer named ``...
def remove(module, name):
r"""Removes the pruning reparameterization from a module and the pruning method from the forward hook. The pruned parameter named ``name`` remains permanently pruned, and the parameter named ``name+'_orig'`` is removed from the parameter list. Similarly, the buffer named ``name+'_mask'`` is removed ...
m = prune.custom_from_mask( nn.Linear(5, 3), name='bias', mask=torch.Tensor([0, 1, 0]) ) >>> print(m.bias_mask) tensor([0., 1., 0.]) """ CustomFromMask.apply(module, name, mask) return module def remove(module, name):
76
76
254
6
69
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
remove
remove
1,100
1,128
1,100
1,100
7813e396fad62d9cea7b29eb559b27af85c4cde7
bigcode/the-stack
train
b31fc6eb97b022dcbb460115
train
function
def l1_unstructured(module, name, amount): r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified `amount` of (currently unpruned) units with the lowest L1-norm. Modifies module in place (and also return the modified module) by: 1) adding a named buf...
def l1_unstructured(module, name, amount):
r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified `amount` of (currently unpruned) units with the lowest L1-norm. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding t...
absolute number of parameters to prune. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.random_unstructured(nn.Linear(2, 3), 'weight', amount=1) >>> torch.sum(m.weight_mask == 0) tensor(1) """ RandomUnstructured....
100
100
335
11
88
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
l1_unstructured
l1_unstructured
857
887
857
857
117a182bd6c619a5072f44ed5358ffd7dbb5e368
bigcode/the-stack
train
a2302e19ae7097592767a719
train
class
class RandomStructured(BasePruningMethod): r"""Prune entire (currently unpruned) channels in a tensor at random. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int`...
class RandomStructured(BasePruningMethod):
r"""Prune entire (currently unpruned) channels in a tensor at random. Args: amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the absolute n...
# largest=True --> top k; largest=False --> bottom k # Prune the smallest k topk = torch.topk( torch.abs(t).view(-1), k=nparams_toprune, largest=False ) # topk will have .indices and .values mask.view(-1)[topk.indices] = 0 return mask...
256
256
1,047
8
248
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
RandomStructured
RandomStructured
539
641
539
539
e174fe22abf667a2b56d687e0090331a21461a13
bigcode/the-stack
train
8bbba40cb9aaa69a31c24b85
train
function
def global_unstructured(parameters, pruning_method, **kwargs): r""" Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``. Modifies modules in place by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary m...
def global_unstructured(parameters, pruning_method, **kwargs):
r""" Globally prunes tensors corresponding to all parameters in ``parameters`` by applying the specified ``pruning_method``. Modifies modules in place by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ``name`` by the pruning method. ...
name+'_orig'``. Args: module (nn.Module): module containing the tensor to prune name (str): parameter name within ``module`` on which pruning will act. amount (int or float): quantity of parameters to prune. If ``float``, should be between 0.0 and 1.0 and represe...
256
256
967
12
243
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
global_unstructured
global_unstructured
963
1,065
963
963
4e3821e344e7461c6f3c191fbfa25fe8019286ad
bigcode/the-stack
train
6441354c621f140a932010f2
train
class
class LnStructured(BasePruningMethod): r"""Prune entire (currently unpruned) channels in a tensor based on their Ln-norm. Args: amount (int or float): quantity of channels to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune...
class LnStructured(BasePruningMethod):
r"""Prune entire (currently unpruned) channels in a tensor based on their Ln-norm. Args: amount (int or float): quantity of channels to prune. If ``float``, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If ``int``, it represents the ...
potentially # unstructured) mask mask = make_mask(t, self.dim, tensor_size, nparams_toprune) mask *= default_mask.to(dtype=mask.dtype) return mask @classmethod def apply(cls, module, name, amount, dim=-1): r"""Adds the forward pre-hook that enables pruning on...
256
256
1,248
8
248
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
LnStructured
LnStructured
644
762
644
644
76ff1cc0e1929228847cec1a59b1178d5132423f
bigcode/the-stack
train
fe00a0f35cd2d67a92e763cc
train
function
def custom_from_mask(module, name, mask): r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by applying the pre-computed mask in ``mask``. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the...
def custom_from_mask(module, name, mask):
r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by applying the pre-computed mask in ``mask``. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``name+'_mask'`` corresponding to the binary mask applied to the parameter ...
_mask = final_mask[pointer : pointer + num_param].view_as(param) # Assign the correct pre-computed mask to each parameter and add it # to the forward_pre_hooks like any other pruning method custom_from_mask(module, name, param_mask) # Increment the pointer to continue slicing the final_...
84
84
281
10
73
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
custom_from_mask
custom_from_mask
1,068
1,097
1,068
1,068
d7985346b90bd9761a03e68c24cafdea1c1bae0f
bigcode/the-stack
train
55be0a89a7815175a7922c4c
train
function
def _validate_structured_pruning(t): r"""Validation helper to check that the tensor to be pruned is multi- dimensional, such that the concept of "channels" is well-defined. Args: t (torch.Tensor): tensor representing the parameter to prune Raises: ValueError: if the tensor `t` is not a...
def _validate_structured_pruning(t):
r"""Validation helper to check that the tensor to be pruned is multi- dimensional, such that the concept of "channels" is well-defined. Args: t (torch.Tensor): tensor representing the parameter to prune Raises: ValueError: if the tensor `t` is not at least 2D. """ shape = t.sha...
will just be fully pruned. if isinstance(amount, numbers.Integral) and amount > tensor_size: raise ValueError( "amount={} should be smaller than the number of " "parameters to prune={}".format(amount, tensor_size) ) def _validate_structured_pruning(t):
64
64
136
9
55
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
_validate_structured_pruning
_validate_structured_pruning
1,215
1,231
1,215
1,215
b71a685a7d6e849f453695a811d71d45b27cf32e
bigcode/the-stack
train
419a24c198793ec2731a146d
train
function
def _compute_norm(t, n, dim): r"""Compute the L_n-norm across all entries in tensor `t` along all dimension except for the one identified by dim. Example: if `t` is of shape, say, 3x2x4 and dim=2 (the last dim), then norm will have Size [4], and each entry will represent the `L_n`-norm computed usin...
def _compute_norm(t, n, dim):
r"""Compute the L_n-norm across all entries in tensor `t` along all dimension except for the one identified by dim. Example: if `t` is of shape, say, 3x2x4 and dim=2 (the last dim), then norm will have Size [4], and each entry will represent the `L_n`-norm computed using the 3x2=6 entries for each o...
(t, dim): r""" Args: t (torch.Tensor): tensor representing the parameter to prune dim (int): index of the dim along which we define channels to prune """ if dim >= t.dim(): raise IndexError( "Invalid index {} for tensor of size {}".format(dim, t.shape) ) def _...
82
82
275
10
72
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
_compute_norm
_compute_norm
1,270
1,295
1,270
1,270
42159dc6769a3efa5dfed5bf5a5c64bb91db880f
bigcode/the-stack
train
91ec85c8bdefae766de63152
train
function
def _validate_pruning_amount_init(amount): r"""Validation helper to check the range of amount at init. Args: amount (int or float): quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents t...
def _validate_pruning_amount_init(amount):
r"""Validation helper to check the range of amount at init. Args: amount (int or float): quantity of parameters to prune. If float, should be between 0.0 and 1.0 and represent the fraction of parameters to prune. If int, it represents the absolute number of parameter...
False >>> prune.random_unstructured(m, name='weight', amount=0.2) >>> print(prune.is_pruned(m)) True """ for _, submodule in module.named_modules(): for _, hook in submodule._forward_pre_hooks.items(): if isinstance(hook, BasePruningMethod): return Tr...
86
86
288
9
76
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
_validate_pruning_amount_init
_validate_pruning_amount_init
1,157
1,189
1,157
1,157
d3732408a5725853e54267e834e8aa0daa16d30d
bigcode/the-stack
train
733e1e2ad4c5c923ffaa0375
train
function
def random_structured(module, name, amount, dim): r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) channels along the specified ``dim`` selected at random. Modifies module in place (and also return the modified module...
def random_structured(module, name, amount, dim):
r"""Prunes tensor corresponding to parameter called ``name`` in ``module`` by removing the specified ``amount`` of (currently unpruned) channels along the specified ``dim`` selected at random. Modifies module in place (and also return the modified module) by: 1) adding a named buffer called ``na...
of parameters to prune. Returns: module (nn.Module): modified (i.e. pruned) version of the input module Examples: >>> m = prune.l1_unstructured(nn.Linear(2, 3), 'weight', amount=0.2) >>> m.state_dict().keys() odict_keys(['bias', 'weight_orig', 'weight_mask']) """ L1Uns...
110
110
369
12
97
wenhaopeter/read_pytorch_code
torch/nn/utils/prune.py
Python
random_structured
random_structured
890
924
890
890
b1a7e979f07cb92dd048bd20e2792e8e2ecb7a56
bigcode/the-stack
train
bb7ee8c43852d61855a3bc1c
train
class
class CalendarConfig(AppConfig): name = 'CALENDAR'
class CalendarConfig(AppConfig):
name = 'CALENDAR'
from django.apps import AppConfig class CalendarConfig(AppConfig):
13
64
13
6
6
andresbeltran98/Student_Organizational_System
CALENDAR/apps.py
Python
CalendarConfig
CalendarConfig
4
5
4
4
3f011c54faaab73d61017e394c0b17640453820e
bigcode/the-stack
train
1a9d0d99893b9f3a92e35302
train
function
def main(**kwargs): if kwargs["input"] is None: input_file = sys.stdin else: input_file = open(kwargs["input"]) if kwargs["output"] is None: output_file = sys.stdout else: output_file = open(kwargs["output"], "w") formatter = commandline.log_formatters[kwargs["format...
def main(**kwargs):
if kwargs["input"] is None: input_file = sys.stdin else: input_file = open(kwargs["input"]) if kwargs["output"] is None: output_file = sys.stdout else: output_file = open(kwargs["output"], "w") formatter = commandline.log_formatters[kwargs["format"]][0]() handle...
from, defaults to stdin") parser.add_argument("--output", action="store", default=None, help="Filename to write to, defaults to stdout") parser.add_argument("format", choices=commandline.log_formatters.keys(), help="Format to use") return parser def main(**kw...
64
64
110
5
58
lucashmorais/x-Bench
mozmill-env/python/Lib/site-packages/mozlog/structured/scripts/format.py
Python
main
main
17
33
17
17
b67ed96e665dcdd4b4db81a9889a9096a3693ef5
bigcode/the-stack
train
28531165db1215abb2f93b6c
train
function
def get_parser(add_help=True): parser = argparse.ArgumentParser("format", description="Format a structured log stream", add_help=add_help) parser.add_argument("--input", action="store", default=None, help="Filename to read from, defaults to stdin") ...
def get_parser(add_help=True):
parser = argparse.ArgumentParser("format", description="Format a structured log stream", add_help=add_help) parser.add_argument("--input", action="store", default=None, help="Filename to read from, defaults to stdin") parser.add_argument("--output...
import argparse import sys from .. import handlers, commandline, reader def get_parser(add_help=True):
23
64
110
7
15
lucashmorais/x-Bench
mozmill-env/python/Lib/site-packages/mozlog/structured/scripts/format.py
Python
get_parser
get_parser
6
15
6
6
4663f3c5d10e65b5b2da3b696e3397911bc66ca6
bigcode/the-stack
train
df1a1acd3afe3bc8a817cfe3
train
function
def test_basic_async(): t = Template( "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True ) async def func(): return await t.render_async() rv = run(func()) assert rv == "[1][2][3]"
def test_basic_async():
t = Template( "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True ) async def func(): return await t.render_async() rv = run(func()) assert rv == "[1][2][3]"
from jinja.asyncsupport import auto_aiter from jinja.exceptions import TemplateNotFound from jinja.exceptions import TemplatesNotFound from jinja.exceptions import UndefinedError def run(coro): loop = asyncio.get_event_loop() return loop.run_until_complete(coro) def test_basic_async():
64
64
71
5
59
aklajnert/jinja
tests/test_async.py
Python
test_basic_async
test_basic_async
19
28
19
19
5374f63d96218ec3d9a5bbe426ca15a66f433caf
bigcode/the-stack
train
7bc36c850b549388e194195a
train
class
@pytest.mark.core_tags @pytest.mark.for_loop class TestAsyncForLoop(object): def test_simple(self, test_env_async): tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}") assert tmpl.render(seq=list(range(10))) == "0123456789" def test_else(self, test_env_async): ...
@pytest.mark.core_tags @pytest.mark.for_loop class TestAsyncForLoop(object):
def test_simple(self, test_env_async): tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}") assert tmpl.render(seq=list(range(10))) == "0123456789" def test_else(self, test_env_async): tmpl = test_env_async.from_string( "{% for item in seq %}XXX{%...
% include 'item' %}{% endfor %}", item="{{ item }}", ) ) ) assert env.get_template("main").render() == "123" def test_unoptimized_scopes(self, test_env_async): t = test_env_async.from_string( """ {% macro outer(o) %} ...
255
256
3,003
17
238
aklajnert/jinja
tests/test_async.py
Python
TestAsyncForLoop
TestAsyncForLoop
282
581
282
284
ab0a6a98087ebc859ccc0d2e913edd98ccf3aa8f
bigcode/the-stack
train
5bff1fa31f8265f1879fae9e
train
function
def test_async_generate(): t = Template("{% for x in [1, 2, 3] %}{{ x }}{% endfor %}", enable_async=True) rv = list(t.generate()) assert rv == ["1", "2", "3"]
def test_async_generate():
t = Template("{% for x in [1, 2, 3] %}{{ x }}{% endfor %}", enable_async=True) rv = list(t.generate()) assert rv == ["1", "2", "3"]
"{% block foo %}<Test>{% endblock %}{{ self.foo() }}", enable_async=True, autoescape=True, ) async def func(): return await t.render_async() rv = run(func()) assert rv == "<Test><Test>" def test_async_generate():
63
64
57
5
58
aklajnert/jinja
tests/test_async.py
Python
test_async_generate
test_async_generate
91
94
91
91
3249ae062202daffb12b8904a3dbb1f32512d02f
bigcode/the-stack
train
970516e72584279beeab1311
train
function
def test_await_on_calls_normal_render(): t = Template("{{ async_func() + normal_func() }}", enable_async=True) async def async_func(): return 42 def normal_func(): return 23 rv = t.render(async_func=async_func, normal_func=normal_func) assert rv == "65"
def test_await_on_calls_normal_render():
t = Template("{{ async_func() + normal_func() }}", enable_async=True) async def async_func(): return 42 def normal_func(): return 23 rv = t.render(async_func=async_func, normal_func=normal_func) assert rv == "65"
def async_func(): return 42 def normal_func(): return 23 async def func(): return await t.render_async(async_func=async_func, normal_func=normal_func) rv = run(func()) assert rv == "65" def test_await_on_calls_normal_render():
64
64
73
9
55
aklajnert/jinja
tests/test_async.py
Python
test_await_on_calls_normal_render
test_await_on_calls_normal_render
47
58
47
47
9fcc80aa009c5af3e756bff522d85dc98574607f
bigcode/the-stack
train
8a9ccabaac8569e4ea6b0335
train
class
@pytest.mark.imports class TestAsyncImports(object): def test_context_imports(self, test_env_async): t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}') assert t.render(foo=42) == "[|23]" t = test_env_async.from_string( '{% import "module" as m without cont...
@pytest.mark.imports class TestAsyncImports(object):
def test_context_imports(self, test_env_async): t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}') assert t.render(foo=42) == "[|23]" t = test_env_async.from_string( '{% import "module" as m without context %}{{ m.test() }}' ) assert t.rend...
%}", enable_async=True ) stream = t.generate(rng=auto_aiter(range(1, 4))) assert next(stream) == "0" assert "".join(stream) == "/11/22/3" @pytest.fixture def test_env_async(): env = Environment( loader=DictLoader( dict( module="{% macro test() %}[{{ foo }}|{{ b...
154
154
516
11
142
aklajnert/jinja
tests/test_async.py
Python
TestAsyncImports
TestAsyncImports
133
180
133
134
adea56ba3cc9bfbeff31b418a3b0ab06d3882889
bigcode/the-stack
train
41c9b735dff2784d5a1a6ee5
train
function
def test_async_iteration_in_templates_extended(): t = Template( "{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}", enable_async=True ) stream = t.generate(rng=auto_aiter(range(1, 4))) assert next(stream) == "0" assert "".join(stream) == "/11/22/3"
def test_async_iteration_in_templates_extended():
t = Template( "{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}", enable_async=True ) stream = t.generate(rng=auto_aiter(range(1, 4))) assert next(stream) == "0" assert "".join(stream) == "/11/22/3"
for %}", enable_async=True) async def async_iterator(): for item in [1, 2, 3]: yield item rv = list(t.generate(rng=async_iterator())) assert rv == ["1", "2", "3"] def test_async_iteration_in_templates_extended():
63
64
83
8
55
aklajnert/jinja
tests/test_async.py
Python
test_async_iteration_in_templates_extended
test_async_iteration_in_templates_extended
108
114
108
108
bc2768c57cf1b15048829e85234a32ed98026d8d
bigcode/the-stack
train
b2b298ea2c92c497e03f5945
train
function
def test_async_blocks(): t = Template( "{% block foo %}<Test>{% endblock %}{{ self.foo() }}", enable_async=True, autoescape=True, ) async def func(): return await t.render_async() rv = run(func()) assert rv == "<Test><Test>"
def test_async_blocks():
t = Template( "{% block foo %}<Test>{% endblock %}{{ self.foo() }}", enable_async=True, autoescape=True, ) async def func(): return await t.render_async() rv = run(func()) assert rv == "<Test><Test>"
}{{ foo(42) }}", enable_async=True, ) async def async_func(): return 42 async def func(): return await t.render_async(async_func=async_func) rv = run(func()) assert rv == "[42][42]" def test_async_blocks():
63
64
69
5
58
aklajnert/jinja
tests/test_async.py
Python
test_async_blocks
test_async_blocks
77
88
77
77
86d7aad0f8d7cd73e2e5fd098c095a2e48072ebf
bigcode/the-stack
train
da7593f7e635892a144525d4
train
class
@pytest.mark.imports @pytest.mark.includes class TestAsyncIncludes(object): def test_context_include(self, test_env_async): t = test_env_async.from_string('{% include "header" %}') assert t.render(foo=42) == "[42|23]" t = test_env_async.from_string('{% include "header" with context %}') ...
@pytest.mark.imports @pytest.mark.includes class TestAsyncIncludes(object):
def test_context_include(self, test_env_async): t = test_env_async.from_string('{% include "header" %}') assert t.render(foo=42) == "[42|23]" t = test_env_async.from_string('{% include "header" with context %}') assert t.render(foo=42) == "[42|23]" t = test_env_async.from_str...
test_env_async.from_string('{% from "foo" import bar, baz with context %}') test_env_async.from_string('{% from "foo" import bar, baz, with context %}') test_env_async.from_string('{% from "foo" import bar, with context %}') test_env_async.from_string('{% from "foo" import bar, with, con...
249
249
831
15
234
aklajnert/jinja
tests/test_async.py
Python
TestAsyncIncludes
TestAsyncIncludes
183
279
183
185
c5b8376fa42d7d930acc82428c6f4ecf6ab59919
bigcode/the-stack
train
56c63829e4f8aeb1ae37afa7
train
function
def run(coro): loop = asyncio.get_event_loop() return loop.run_until_complete(coro)
def run(coro):
loop = asyncio.get_event_loop() return loop.run_until_complete(coro)
import pytest from jinja import DictLoader from jinja import Environment from jinja import Template from jinja.asyncsupport import auto_aiter from jinja.exceptions import TemplateNotFound from jinja.exceptions import TemplatesNotFound from jinja.exceptions import UndefinedError def run(coro):
64
64
22
5
58
aklajnert/jinja
tests/test_async.py
Python
run
run
14
16
14
14
62a1ed95635cb857c1eafa65ec259e42a39924a4
bigcode/the-stack
train
d4f330dfa29147c350ad5dc5
train
function
def test_await_and_macros(): t = Template( "{% macro foo(x) %}[{{ x }}][{{ async_func() }}]{% endmacro %}{{ foo(42) }}", enable_async=True, ) async def async_func(): return 42 async def func(): return await t.render_async(async_func=async_func) rv = run(func()) ...
def test_await_and_macros():
t = Template( "{% macro foo(x) %}[{{ x }}][{{ async_func() }}]{% endmacro %}{{ foo(42) }}", enable_async=True, ) async def async_func(): return 42 async def func(): return await t.render_async(async_func=async_func) rv = run(func()) assert rv == "[42][42]"
() + normal_func() }}", enable_async=True) async def async_func(): return 42 def normal_func(): return 23 rv = t.render(async_func=async_func, normal_func=normal_func) assert rv == "65" def test_await_and_macros():
64
64
94
8
56
aklajnert/jinja
tests/test_async.py
Python
test_await_and_macros
test_await_and_macros
61
74
61
61
c0d536439dfc6e42e85eb43130ec8905c54e8c4d
bigcode/the-stack
train
d4d5a32dadf0d2edc7db6215
train
function
def test_await_on_calls(): t = Template("{{ async_func() + normal_func() }}", enable_async=True) async def async_func(): return 42 def normal_func(): return 23 async def func(): return await t.render_async(async_func=async_func, normal_func=normal_func) rv = run(func()) ...
def test_await_on_calls():
t = Template("{{ async_func() + normal_func() }}", enable_async=True) async def async_func(): return 42 def normal_func(): return 23 async def func(): return await t.render_async(async_func=async_func, normal_func=normal_func) rv = run(func()) assert rv == "65"
in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True ) async def func(): return await t.render_async() rv = run(func()) assert rv == "[1][2][3]" def test_await_on_calls():
63
64
83
7
56
aklajnert/jinja
tests/test_async.py
Python
test_await_on_calls
test_await_on_calls
31
44
31
31
0a2d05a9d9daddf6401e5d2f3514d6ca100f159c
bigcode/the-stack
train
ee3a4e31f3c04680fac6eae4
train
function
@pytest.fixture def test_env_async(): env = Environment( loader=DictLoader( dict( module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}", header="[{{ foo }}|{{ 23 }}]", o_printer="({{ o }})", ) ), enable_async=Tr...
@pytest.fixture def test_env_async():
env = Environment( loader=DictLoader( dict( module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}", header="[{{ foo }}|{{ 23 }}]", o_printer="({{ o }})", ) ), enable_async=True, ) env.globals["bar"] = 23 ...
{{ x }}{% endfor %}", enable_async=True ) stream = t.generate(rng=auto_aiter(range(1, 4))) assert next(stream) == "0" assert "".join(stream) == "/11/22/3" @pytest.fixture def test_env_async():
64
64
93
8
56
aklajnert/jinja
tests/test_async.py
Python
test_env_async
test_env_async
117
130
117
118
9227393b98757ef0cf9758b38749701fed1992a1
bigcode/the-stack
train
19a0f37bc0c1be999ccf9b7a
train
function
def test_async_iteration_in_templates(): t = Template("{% for x in rng %}{{ x }}{% endfor %}", enable_async=True) async def async_iterator(): for item in [1, 2, 3]: yield item rv = list(t.generate(rng=async_iterator())) assert rv == ["1", "2", "3"]
def test_async_iteration_in_templates():
t = Template("{% for x in rng %}{{ x }}{% endfor %}", enable_async=True) async def async_iterator(): for item in [1, 2, 3]: yield item rv = list(t.generate(rng=async_iterator())) assert rv == ["1", "2", "3"]
test_async_generate(): t = Template("{% for x in [1, 2, 3] %}{{ x }}{% endfor %}", enable_async=True) rv = list(t.generate()) assert rv == ["1", "2", "3"] def test_async_iteration_in_templates():
63
64
79
7
56
aklajnert/jinja
tests/test_async.py
Python
test_async_iteration_in_templates
test_async_iteration_in_templates
97
105
97
97
a035894d3a8f632e5f5e64d1d4a4eea73572eb93
bigcode/the-stack
train
2b646911d42b391069c36745
train
class
class Solution: def findLonelyPixel(self, picture: List[List[str]]) -> int: R = len(picture) C = len(picture[0]) # To get the rows of the matrix: def get_rows(matrice): return [[c for c in r] for r in matrice] # To the cols of the matrix def get_columns(...
class Solution:
def findLonelyPixel(self, picture: List[List[str]]) -> int: R = len(picture) C = len(picture[0]) # To get the rows of the matrix: def get_rows(matrice): return [[c for c in r] for r in matrice] # To the cols of the matrix def get_columns(matrice): ...
from typing import * class Solution:
7
77
259
3
4
hariharanragothaman/leetcode-solutions
src/0531_lonely_pixel_1.py
Python
Solution
Solution
4
45
4
4
158929264a42d01802d79eebe158a38386339b59
bigcode/the-stack
train
adda47174fcf087f086b95d5
train
class
class PopularContentConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'popular_content'
class PopularContentConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField' name = 'popular_content'
from django.apps import AppConfig class PopularContentConfig(AppConfig):
14
64
27
7
6
Neil0406/BigData-Interview-Demo
big_data_interview_demo/popular_content/apps.py
Python
PopularContentConfig
PopularContentConfig
4
6
4
4
de0d267a9e7c36606b00101ce3bd485b3dff1f30
bigcode/the-stack
train
98cc27180f0eac465008e3fb
train
class
class Utils: def __init__(self): pass def remove_dirs(self): shutil.rmtree(VIDEOS_DIR) shutil.rmtree(CAPTIONS_DIR) def create_dirs(self): os.makedirs(DOWNLOADS_DIR, exist_ok=True) os.makedirs(VIDEOS_DIR, exist_ok=True) os.makedirs(CAPTIONS_DIR, exist_ok=True...
class Utils:
def __init__(self): pass def remove_dirs(self): shutil.rmtree(VIDEOS_DIR) shutil.rmtree(CAPTIONS_DIR) def create_dirs(self): os.makedirs(DOWNLOADS_DIR, exist_ok=True) os.makedirs(VIDEOS_DIR, exist_ok=True) os.makedirs(CAPTIONS_DIR, exist_ok=True) os....
import os import shutil from yt_concate.setting import DOWNLOADS_DIR from yt_concate.setting import VIDEOS_DIR from yt_concate.setting import CAPTIONS_DIR from yt_concate.setting import OUTPUTS_DIR class Utils:
50
101
337
3
46
menghsin-2021/yt-concate
yt_concate/utils.py
Python
Utils
Utils
10
50
10
10
4e498ebd317f28fa71be166b5e7b5e6a7bc84cdf
bigcode/the-stack
train
acc1962dd1a2bf2cb5e915f2
train
function
def get_account_balance_lock(*, account_number): """ Return balance lock for the given account_number """ account_balance_lock_cache_key = get_account_balance_lock_cache_key(account_number=account_number) account_balance_lock = cache.get(account_balance_lock_cache_key) if account_balance_lock ...
def get_account_balance_lock(*, account_number):
""" Return balance lock for the given account_number """ account_balance_lock_cache_key = get_account_balance_lock_cache_key(account_number=account_number) account_balance_lock = cache.get(account_balance_lock_cache_key) if account_balance_lock is None: account = Account.objects.filter...
_cache_key(account_number=account_number) account_balance = cache.get(account_balance_cache_key) if account_balance is None: account = Account.objects.filter(account_number=account_number).first() if account: return account.balance return account_balance def get_account_balanc...
64
64
94
10
53
VincentHch/Validator
v1/cache_tools/accounts.py
Python
get_account_balance_lock
get_account_balance_lock
24
38
24
24
762574092bafc349d5f324f94617a1d79ae576f0
bigcode/the-stack
train
d101d2678bc56d11743cf99e
train
function
def get_account_balance(*, account_number): """ Return balance for the given account_number """ account_balance_cache_key = get_account_balance_cache_key(account_number=account_number) account_balance = cache.get(account_balance_cache_key) if account_balance is None: account = Account....
def get_account_balance(*, account_number):
""" Return balance for the given account_number """ account_balance_cache_key = get_account_balance_cache_key(account_number=account_number) account_balance = cache.get(account_balance_cache_key) if account_balance is None: account = Account.objects.filter(account_number=account_number...
from django.core.cache import cache from v1.accounts.models.account import Account from .cache_keys import get_account_balance_cache_key, get_account_balance_lock_cache_key def get_account_balance(*, account_number):
43
64
85
9
33
VincentHch/Validator
v1/cache_tools/accounts.py
Python
get_account_balance
get_account_balance
7
21
7
7
99d894b44b04cfd08f7231ae9235e9c8e22d3326
bigcode/the-stack
train
17e096314dd6c648d8a14d45
train
function
def create(kernel): result = Static() result.template = "object/static/naboo/shared_waterfall_naboo_theed_base.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
def create(kernel):
result = Static() result.template = "object/static/naboo/shared_waterfall_naboo_theed_base.iff" result.attribute_template_id = -1 result.stfName("obj_n","unknown_object") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel):
46
64
69
4
42
obi-two/GameServer
data/scripts/templates/object/static/naboo/shared_waterfall_naboo_theed_base.py
Python
create
create
7
17
7
7
a7d4e54251f7d8f1e30e903585c310bd56cdee15
bigcode/the-stack
train
59979ca57ad420ce5d52b0b6
train
class
class CreateVolumeFromSpecTask(flow_utils.CinderTask): """Creates a volume from a provided specification. Reversion strategy: N/A """ default_provides = 'volume' def __init__(self, manager, db, driver, image_volume_cache=None): super(CreateVolumeFromSpecTask, self).__init__(addons=[ACTION...
class CreateVolumeFromSpecTask(flow_utils.CinderTask):
"""Creates a volume from a provided specification. Reversion strategy: N/A """ default_provides = 'volume' def __init__(self, manager, db, driver, image_volume_cache=None): super(CreateVolumeFromSpecTask, self).__init__(addons=[ACTION]) self.manager = manager self.db = db ...
_spec') # Restore the source volume status and set the volume to error status. common.restore_source_status(context, self.db, volume_spec) class NotifyVolumeActionTask(flow_utils.CinderTask): """Performs a notification about the given volume when called. Reversion strategy: N/A """ d...
256
256
4,459
12
244
UbuntuEvangelist/cinder
cinder/volume/flows/manager/create_volume.py
Python
CreateVolumeFromSpecTask
CreateVolumeFromSpecTask
350
853
350
350
19acd6b08fd417b0bc03a13119ce84ecbf9a4de5
bigcode/the-stack
train
5ff2b2d2ecb45151d66a1722
train
class
class ExtractVolumeSpecTask(flow_utils.CinderTask): """Extracts a spec of a volume to be created into a common structure. This task extracts and organizes the input requirements into a common and easier to analyze structure for later tasks to use. It will also attach the underlying database volume refe...
class ExtractVolumeSpecTask(flow_utils.CinderTask):
"""Extracts a spec of a volume to be created into a common structure. This task extracts and organizes the input requirements into a common and easier to analyze structure for later tasks to use. It will also attach the underlying database volume reference which can be used by other tasks to refere...
Extracts volume reference for given volume id.""" default_provides = 'volume_ref' def __init__(self, db, host, set_error=True): super(ExtractVolumeRefTask, self).__init__(addons=[ACTION]) self.db = db self.host = host self.set_error = set_error def execute(self, context, v...
256
256
903
11
245
UbuntuEvangelist/cinder
cinder/volume/flows/manager/create_volume.py
Python
ExtractVolumeSpecTask
ExtractVolumeSpecTask
221
320
221
221
fc93e57604c25588f5b0c114b8431296633802bd
bigcode/the-stack
train
2d63535b369fe2e7add1ceb7
train
class
class NotifyVolumeActionTask(flow_utils.CinderTask): """Performs a notification about the given volume when called. Reversion strategy: N/A """ def __init__(self, db, event_suffix): super(NotifyVolumeActionTask, self).__init__(addons=[ACTION, ...
class NotifyVolumeActionTask(flow_utils.CinderTask):
"""Performs a notification about the given volume when called. Reversion strategy: N/A """ def __init__(self, db, event_suffix): super(NotifyVolumeActionTask, self).__init__(addons=[ACTION, event_suffix]) self.db = db ...
**kwargs): if isinstance(result, ft.Failure): return volume_spec = result.get('volume_spec') # Restore the source volume status and set the volume to error status. common.restore_source_status(context, self.db, volume_spec) class NotifyVolumeActionTask(flow_utils.CinderTask)...
64
64
214
11
53
UbuntuEvangelist/cinder
cinder/volume/flows/manager/create_volume.py
Python
NotifyVolumeActionTask
NotifyVolumeActionTask
323
347
323
323
d6c35586cf182aba830a2b9a48766fae2ccf83b1
bigcode/the-stack
train
fdc6a876bdf22cabe4e71bfb
train
class
class OnFailureRescheduleTask(flow_utils.CinderTask): """Triggers a rescheduling request to be sent when reverting occurs. If rescheduling doesn't occur this task errors out the volume. Reversion strategy: Triggers the rescheduling mechanism whereby a cast gets sent to the scheduler rpc api to allow f...
class OnFailureRescheduleTask(flow_utils.CinderTask):
"""Triggers a rescheduling request to be sent when reverting occurs. If rescheduling doesn't occur this task errors out the volume. Reversion strategy: Triggers the rescheduling mechanism whereby a cast gets sent to the scheduler rpc api to allow for an attempt X of Y for scheduling this volume el...
# License for the specific language governing permissions and limitations # under the License. import math import traceback from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging from oslo_utils import timeutils from oslo_utils import units import taskflow.engi...
256
256
1,222
12
244
UbuntuEvangelist/cinder
cinder/volume/flows/manager/create_volume.py
Python
OnFailureRescheduleTask
OnFailureRescheduleTask
53
189
53
53
8a13f7815ee54c2395d2ff4b38993c919ccfb780
bigcode/the-stack
train
91afcfaabe886dba7f7b269d
train
function
def get_flow(context, manager, db, driver, scheduler_rpcapi, host, volume_id, allow_reschedule, reschedule_context, request_spec, filter_properties, image_volume_cache=None): """Constructs and returns the manager entrypoint flow. This flow will do the following: 1. Determines if...
def get_flow(context, manager, db, driver, scheduler_rpcapi, host, volume_id, allow_reschedule, reschedule_context, request_spec, filter_properties, image_volume_cache=None):
"""Constructs and returns the manager entrypoint flow. This flow will do the following: 1. Determines if rescheduling is enabled (ahead of time). 2. Inject keys & values for dependent tasks. 3. Selects 1 of 2 activated only on *failure* tasks (one to update the db status & notify or one to ...
use the parent to notify. super(CreateVolumeOnFinishTask, self).execute(context, volume_ref) except exception.CinderException: LOG.exception(_LE("Failed updating volume %(volume_id)s with " "%(update)s"), {'volume_id': volume_id, ...
159
159
532
41
118
UbuntuEvangelist/cinder
cinder/volume/flows/manager/create_volume.py
Python
get_flow
get_flow
901
957
901
904
b088d4a5c8d9d6d2394e2a46709ab72ae827b93d
bigcode/the-stack
train
f3eb37d904c8f14c0efdfcc0
train
class
class ExtractVolumeRefTask(flow_utils.CinderTask): """Extracts volume reference for given volume id.""" default_provides = 'volume_ref' def __init__(self, db, host, set_error=True): super(ExtractVolumeRefTask, self).__init__(addons=[ACTION]) self.db = db self.host = host se...
class ExtractVolumeRefTask(flow_utils.CinderTask):
"""Extracts volume reference for given volume id.""" default_provides = 'volume_ref' def __init__(self, db, host, set_error=True): super(ExtractVolumeRefTask, self).__init__(addons=[ACTION]) self.db = db self.host = host self.set_error = set_error def execute(self, con...
_reschedule(context, volume_id) self._reschedule(context, cause, volume_id=volume_id, **kwargs) self._post_reschedule(volume_id) return True except exception.CinderException: LOG.exception(_LE("Volume %s: rescheduling failed"), volume_id) ...
77
77
258
11
65
UbuntuEvangelist/cinder
cinder/volume/flows/manager/create_volume.py
Python
ExtractVolumeRefTask
ExtractVolumeRefTask
192
218
192
192
2d4808aef8b9f4df9b5dc783b297f5cb834872e2
bigcode/the-stack
train
d3d04fb0efeca030b56ea299
train
class
class CreateVolumeOnFinishTask(NotifyVolumeActionTask): """On successful volume creation this will perform final volume actions. When a volume is created successfully it is expected that MQ notifications and database updates will occur to 'signal' to others that the volume is now ready for usage. This ...
class CreateVolumeOnFinishTask(NotifyVolumeActionTask):
"""On successful volume creation this will perform final volume actions. When a volume is created successfully it is expected that MQ notifications and database updates will occur to 'signal' to others that the volume is now ready for usage. This task does those notifications and updates in a relia...
= self.db.volume_update(context, volume_ref['id'], model_update) except exception.CinderException: # If somehow the update failed we want to ensure that the # failure is logged (but not try rescheduling since the volume at #...
121
121
406
12
108
UbuntuEvangelist/cinder
cinder/volume/flows/manager/create_volume.py
Python
CreateVolumeOnFinishTask
CreateVolumeOnFinishTask
856
898
856
856
d80e62cce4735f480dbaed1278b7aae1b47ba59a
bigcode/the-stack
train
96b173c1859941a02f668764
train
function
def consumer(message): couler.run_container( image="docker/whalesay:latest", command=["cowsay"], args=[message] )
def consumer(message):
couler.run_container( image="docker/whalesay:latest", command=["cowsay"], args=[message] )
="/tmp/hello_world.txt" ) return couler.run_container( image="docker/whalesay:latest", args=["echo -n hello world > %s" % output_place.path], command=["bash", "-c"], output=output_place, ) def consumer(message):
64
64
33
4
60
pagliaccl/couler
couler/tests/step_output_test.py
Python
consumer
consumer
19
22
19
19
22db9fabaddfaa710f1e4a435fce9bec786be666
bigcode/the-stack
train
6d6cdef41398b786cebee747
train
class
class StepOutputTest(ArgoYamlTest): def test_producer_consumer(self): messge = producer() consumer(messge) self.check_argo_yaml("output_golden_1.yaml") def test_multiple_outputs(self): def producer_two(): output_one = couler.create_parameter_artifact( ...
class StepOutputTest(ArgoYamlTest):
def test_producer_consumer(self): messge = producer() consumer(messge) self.check_argo_yaml("output_golden_1.yaml") def test_multiple_outputs(self): def producer_two(): output_one = couler.create_parameter_artifact( path="/tmp/place_one.txt" ...
", args=["echo -n hello world > %s" % output_place.path], command=["bash", "-c"], output=output_place, ) def consumer(message): couler.run_container( image="docker/whalesay:latest", command=["cowsay"], args=[message] ) class StepOutputTest(ArgoYamlTest):
77
77
259
10
67
pagliaccl/couler
couler/tests/step_output_test.py
Python
StepOutputTest
StepOutputTest
25
58
25
25
2047e90bf4bcdb160270348dfc10a7ba739b5529
bigcode/the-stack
train
1c4e7df5360a684ccd928132
train
function
def producer(): output_place = couler.create_parameter_artifact( path="/tmp/hello_world.txt" ) return couler.run_container( image="docker/whalesay:latest", args=["echo -n hello world > %s" % output_place.path], command=["bash", "-c"], output=output_place, )
def producer():
output_place = couler.create_parameter_artifact( path="/tmp/hello_world.txt" ) return couler.run_container( image="docker/whalesay:latest", args=["echo -n hello world > %s" % output_place.path], command=["bash", "-c"], output=output_place, )
import couler.argo as couler from couler.tests.argo_yaml_test import ArgoYamlTest couler.config_workflow(name="pytest") def producer():
35
64
76
3
32
pagliaccl/couler
couler/tests/step_output_test.py
Python
producer
producer
7
16
7
7
d2fa035318c7ec57336117b856a4bfbd85619895
bigcode/the-stack
train
ba5a790ee7c0f7f6343a95ec
train
class
class Meter(Producer): def __init__(self, min_power_value: int, max_power_value: int, power_value_generator, broker: Broker): """ :param min_power_value: :param max_power_value: :param power_value_generator: """ # Broker info initialization ...
class Meter(Producer):
def __init__(self, min_power_value: int, max_power_value: int, power_value_generator, broker: Broker): """ :param min_power_value: :param max_power_value: :param power_value_generator: """ # Broker info initialization self.__broker = broker ...
""" Meter class is responsible for the connection to broker, dummy power value generation and it's publication. """ __author__ = 'Md Shifuddin Al Masud' __email__ = 'shifuddin.masud@gmail.com' __license__ = 'MIT License' from meter.Producer import Producer import time import logging from meter.Broker import Broker cl...
80
130
435
5
74
Shifuddin/PV-Simulator-Challenge
meter/Meter.py
Python
Meter
Meter
15
67
15
16
bb71b575ee873ae65103561474077698bfed55c4
bigcode/the-stack
train
6d278c065a303ba0808a1aa7
train
class
class Graph: def __init__(self) ->None: self.vertices: Dict[Any , List[Any]] = {} def add_edge(self , from_vertex: Any , to_vertex: Any) -> bool: if from_vertex == None or to_vertex == None: raise ValueError('None is invalid arguments') if not to_vertex in self.vertices: ...
class Graph:
def __init__(self) ->None: self.vertices: Dict[Any , List[Any]] = {} def add_edge(self , from_vertex: Any , to_vertex: Any) -> bool: if from_vertex == None or to_vertex == None: raise ValueError('None is invalid arguments') if not to_vertex in self.vertices: sel...
from typing import Dict , List , Set , Any class Graph:
14
112
374
3
10
Ho011/learning_python
data_structures/graphs/bfs.py
Python
Graph
Graph
2
58
2
2
1796186c7caa03ba2304dcd26503840d6e6b40e8
bigcode/the-stack
train
70e4eed3b1a01e36f57822b9
train
function
def main(): g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() # 0 : 1 -> 2 # 1 : 2 # 2 : 0 -> 3 # 3 : 3 print(g.bfs(1))
def main():
g = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() # 0 : 1 -> 2 # 1 : 2 # 2 : 0 -> 3 # 3 : 3 print(g.bfs(1))
(0) traversal_list.append(vertex) # loop through all adjacent vertex and enqueue it if not yet visited for adjacent_vertex in self.vertices[vertex]: if adjacent_vertex not in visited: visited.add(adjacent_vertex) queue.append(ad...
64
64
127
3
60
Ho011/learning_python
data_structures/graphs/bfs.py
Python
main
main
61
77
61
61
840a94cae99845283214a4522b14a42763dd1492
bigcode/the-stack
train
3f62a48817d030a8ad60f2f0
train
function
def test_Lam_Wind_22_wind_22(): """Test machine plot with Slot 22 and winding rad=2, tan=2 """ print("\nTest plot Slot 22") plt.close("all") test_obj = MachineDFIM() test_obj.rotor = LamSlotWind( Rint=0, Rext=0.5, is_internal=True, is_stator=False, L1=0.8, Nrvd=4, Wrvd=0.05, ) te...
def test_Lam_Wind_22_wind_22():
"""Test machine plot with Slot 22 and winding rad=2, tan=2 """ print("\nTest plot Slot 22") plt.close("all") test_obj = MachineDFIM() test_obj.rotor = LamSlotWind( Rint=0, Rext=0.5, is_internal=True, is_stator=False, L1=0.8, Nrvd=4, Wrvd=0.05, ) test_obj.rotor.slot = SlotW22(Zs=6...
, pi, zeros from ....Classes.Frame import Frame from ....Classes.LamSlotWind import LamSlotWind from ....Classes.LamSquirrelCage import LamSquirrelCage from ....Classes.MachineDFIM import MachineDFIM from ....Classes.Shaft import Shaft from ....Classes.VentilationCirc import VentilationCirc from ....Classes.Ventilatio...
218
218
728
13
205
magnetron/pyleecan
Tests/Plot/LamWind/test_Slot_22_plot.py
Python
test_Lam_Wind_22_wind_22
test_Lam_Wind_22_wind_22
29
84
29
29
7bef0c1ff3017e8ad52c0ca141fcfe8c84978c96
bigcode/the-stack
train
836209e1f81cfd783aa07497
train
function
def load_logging_settings(logging_file_name=LOGGING_FILE_NAME): logging.debug('Loading logging settings from %s', os.path.realpath(logging_file_name)) logging.config.fileConfig(logging_file_name)
def load_logging_settings(logging_file_name=LOGGING_FILE_NAME):
logging.debug('Loading logging settings from %s', os.path.realpath(logging_file_name)) logging.config.fileConfig(logging_file_name)
import logging import logging.config import os.path from gateway.config import ( LOGGING_FILE_NAME, ) def load_logging_settings(logging_file_name=LOGGING_FILE_NAME):
36
64
41
13
23
ghkim3221/auto-tracking-cctv-gateway
gateway/util/utils.py
Python
load_logging_settings
load_logging_settings
10
12
10
10
861e4d4974607c005b3e413cffcd265b511cd87c
bigcode/the-stack
train
0bf96f0ac851918cc82b226e
train
class
class HandlePushNotificationTest(PushNotificationTest): DEFAULT_SUBDOMAIN = "" def bounce_request(self, *args: Any, **kwargs: Any) -> HttpResponse: """This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests. """ ...
class HandlePushNotificationTest(PushNotificationTest):
DEFAULT_SUBDOMAIN = "" def bounce_request(self, *args: Any, **kwargs: Any) -> HttpResponse: """This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests. """ # args[0] is method, args[1] is URL. loc...
token=hex_to_b64(token), user=self.user_profile, ios_app_id=settings.ZULIP_IOS_APP_ID) self.remote_tokens = [u'cccc'] for token in self.remote_tokens: RemotePushDeviceToken.objects.create( kind=RemotePushDeviceToken.APNS, ...
256
256
3,404
10
246
macto/zulip
zerver/tests/test_push_notifications.py
Python
HandlePushNotificationTest
HandlePushNotificationTest
580
950
580
580
b532e8a8e00b26450ebf8051d68fd0dce333bb9b
bigcode/the-stack
train
fbc9880c2cdc2362cd9fe7ff
train
class
class TestSendNotificationsToBouncer(ZulipTestCase): @mock.patch('zerver.lib.remote_server.send_to_push_bouncer') def test_send_notifications_to_bouncer(self, mock_send: mock.MagicMock) -> None: send_notifications_to_bouncer(1, {'apns': True}, {'gcm': True}, {}) post_data = { 'user_i...
class TestSendNotificationsToBouncer(ZulipTestCase): @mock.patch('zerver.lib.remote_server.send_to_push_bouncer')
def test_send_notifications_to_bouncer(self, mock_send: mock.MagicMock) -> None: send_notifications_to_bouncer(1, {'apns': True}, {'gcm': True}, {}) post_data = { 'user_id': 1, 'apns_payload': {'apns': True}, 'gcm_payload': {'gcm': True}, 'gcm_options'...
topic": "Test Topic", "stream": "Denmark" }) self.assertDictEqual(gcm_options, { "priority": "high", }) class TestSendNotificationsToBouncer(ZulipTestCase): @mock.patch('zerver.lib.remote_server.send_to_push_bouncer')
64
64
152
29
35
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestSendNotificationsToBouncer
TestSendNotificationsToBouncer
1,399
1,413
1,399
1,400
a2b2fb85f3c15dd899bb37d2794b04f0fccc5895
bigcode/the-stack
train
c201b089c52cf8631c69d1d9
train
class
class PushBouncerSignupTest(ZulipTestCase): def test_push_signup_invalid_host(self) -> None: zulip_org_id = str(uuid.uuid4()) zulip_org_key = get_random_string(64) request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="invalid-ho...
class PushBouncerSignupTest(ZulipTestCase):
def test_push_signup_invalid_host(self) -> None: zulip_org_id = str(uuid.uuid4()) zulip_org_key = get_random_string(64) request = dict( zulip_org_id=zulip_org_id, zulip_org_key=zulip_org_key, hostname="invalid-host", contact_email="server-admin...
realm_emoji', 'rendered_content': '<p>Testing <img alt=":green_tick:" class="emoji" src="/user_avatars/%s/emoji/green_tick.png" title="green tick"> realm emoji.</p>' % ( realm.id,), 'expected_output': 'Testing :green_tick: realm emoji.', }, { ...
256
256
878
12
244
macto/zulip
zerver/tests/test_push_notifications.py
Python
PushBouncerSignupTest
PushBouncerSignupTest
1,847
1,938
1,847
1,847
2ad58156b1767b166ffca0605652c9c68921060b
bigcode/the-stack
train
975373978a91c16ccb894129
train
class
class GCMParseOptionsTest(TestCase): def test_invalid_option(self) -> None: with self.assertRaises(JsonableError): parse_gcm_options({"invalid": True}, {}) def test_invalid_priority_value(self) -> None: with self.assertRaises(JsonableError): parse_gcm_options({"priority"...
class GCMParseOptionsTest(TestCase):
def test_invalid_option(self) -> None: with self.assertRaises(JsonableError): parse_gcm_options({"invalid": True}, {}) def test_invalid_priority_value(self) -> None: with self.assertRaises(JsonableError): parse_gcm_options({"priority": "invalid"}, {}) def test_defau...
for endpoint, token in endpoints: result = self.client_delete(endpoint, {'token': token}) self.assert_json_success(result) tokens = list(PushDeviceToken.objects.filter(user=user, token=token)) self.assertEqual(len(tokens), 0) class GCMParseOptionsTest(TestCase):
64
64
194
9
55
macto/zulip
zerver/tests/test_push_notifications.py
Python
GCMParseOptionsTest
GCMParseOptionsTest
1,526
1,547
1,526
1,526
35b48aa9507363fd5639a5d52bddffc9fbd5fda4
bigcode/the-stack
train
3b60ab476b0ce618835f9b30
train
class
class PushBouncerNotificationTest(BouncerTestCase): DEFAULT_SUBDOMAIN = "" def test_unregister_remote_push_user_params(self) -> None: token = "111222" token_kind = PushDeviceToken.GCM endpoint = '/api/v1/remotes/push/unregister' result = self.api_post(self.server_uuid, endpoint...
class PushBouncerNotificationTest(BouncerTestCase):
DEFAULT_SUBDOMAIN = "" def test_unregister_remote_push_user_params(self) -> None: token = "111222" token_kind = PushDeviceToken.GCM endpoint = '/api/v1/remotes/push/unregister' result = self.api_post(self.server_uuid, endpoint, {'token_kind': token_kind}) self.assert_js...
).delete() super().tearDown() def bounce_request(self, *args: Any, **kwargs: Any) -> HttpResponse: """This method is used to carry out the push notification bouncer requests using the Django test browser, rather than python-requests. """ # args[0] is method, args[1] is URL. ...
256
256
1,837
11
245
macto/zulip
zerver/tests/test_push_notifications.py
Python
PushBouncerNotificationTest
PushBouncerNotificationTest
119
308
119
119
5c4c8b507a1d616646c39abd57a18dd687277aba
bigcode/the-stack
train
1d8a685f98ce81c95a1829b9
train
class
class TestClearOnRead(ZulipTestCase): def test_mark_stream_as_read(self) -> None: n_msgs = 3 max_unbatched = 2 hamlet = self.example_user("hamlet") hamlet.enable_stream_push_notifications = True hamlet.save() stream = self.subscribe(hamlet, "Denmark") messag...
class TestClearOnRead(ZulipTestCase):
def test_mark_stream_as_read(self) -> None: n_msgs = 3 max_unbatched = 2 hamlet = self.example_user("hamlet") hamlet.enable_stream_push_notifications = True hamlet.save() stream = self.subscribe(hamlet, "Denmark") message_ids = [self.send_stream_message(self...
1') res['errors'] = {'Failed': [token]} mock_gcm.json_request.return_value = res data = self.get_gcm_data() send_android_push_notification_to_user(self.user_profile, data, {}) c1 = call("GCM: Delivery to %s failed: Failed" % (token,)) mock_warn.assert_has_calls([c1], any...
94
94
316
11
83
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestClearOnRead
TestClearOnRead
1,688
1,719
1,688
1,688
c5601750ed4f1ef9ee24705a7caf58abfcfd06a1
bigcode/the-stack
train
886137c5495e705c337f6226
train
class
class AnalyticsBouncerTest(BouncerTestCase): TIME_ZERO = datetime.datetime(1988, 3, 14).replace(tzinfo=timezone_utc) @override_settings(PUSH_NOTIFICATION_BOUNCER_URL='https://push.zulip.org.example.com') @mock.patch('zerver.lib.push_notifications.requests.request') def test_analytics_api(self, mock_req...
class AnalyticsBouncerTest(BouncerTestCase):
TIME_ZERO = datetime.datetime(1988, 3, 14).replace(tzinfo=timezone_utc) @override_settings(PUSH_NOTIFICATION_BOUNCER_URL='https://push.zulip.org.example.com') @mock.patch('zerver.lib.push_notifications.requests.request') def test_analytics_api(self, mock_request: Any) -> None: """This is a vari...
for endpoint, token, kind in endpoints: # Test that we can push twice result = self.client_post(endpoint, {'token': token}, subdomain="zulip") self.assert_json_success(result) result = self.client_post(endpoint, {'token': tok...
256
256
2,423
10
246
macto/zulip
zerver/tests/test_push_notifications.py
Python
AnalyticsBouncerTest
AnalyticsBouncerTest
310
509
310
310
1d449692f5b38b928e3e054f90637473b5836e2f
bigcode/the-stack
train
bcad2e2a53b8de04bcc94dcb
train
class
class TestPushNotificationsContent(ZulipTestCase): def test_fixtures(self) -> None: fixtures = ujson.loads(self.fixture_data("markdown_test_cases.json")) tests = fixtures["regular_tests"] for test in tests: if "text_content" in test: with self.subTest(markdown_tes...
class TestPushNotificationsContent(ZulipTestCase):
def test_fixtures(self) -> None: fixtures = ujson.loads(self.fixture_data("markdown_test_cases.json")) tests = fixtures["regular_tests"] for test in tests: if "text_content" in test: with self.subTest(markdown_test_case=test["name"]): output = ...
.user.enable_stream_push_notifications = True self.assertFalse(receives_stream_notifications(self.user)) self.user.enable_stream_push_notifications = False self.assertFalse(receives_stream_notifications(self.user)) def test_receivers_stream_notifications_when_user_is_not_a_bot(self) -> Non...
119
119
397
11
108
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestPushNotificationsContent
TestPushNotificationsContent
1,807
1,845
1,807
1,807
b20de45bd9bef923aa62aa3518ca8941b86d1eef
bigcode/the-stack
train
79cf7392bb6a2e51b999d8ca
train
class
class TestAPNs(PushNotificationTest): def devices(self) -> List[DeviceToken]: return list(PushDeviceToken.objects.filter( user=self.user_profile, kind=PushDeviceToken.APNS)) def send(self, devices: Optional[List[PushDeviceToken]]=None, payload_data: Dict[str, Any]={}) -> None: ...
class TestAPNs(PushNotificationTest):
def devices(self) -> List[DeviceToken]: return list(PushDeviceToken.objects.filter( user=self.user_profile, kind=PushDeviceToken.APNS)) def send(self, devices: Optional[List[PushDeviceToken]]=None, payload_data: Dict[str, Any]={}) -> None: if devices is None: ...
_profile, kind=PushDeviceToken.GCM)) apple_devices = list( PushDeviceToken.objects.filter(user=self.user_profile, kind=PushDeviceToken.APNS)) with mock.patch('zerver.lib.push_notifications.get_message_pay...
256
256
1,196
9
247
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestAPNs
TestAPNs
952
1,071
952
952
42903574c01cf0447f7284aacfb9a9a0d476a1c6
bigcode/the-stack
train
3d43898e80079178746e1995
train
class
class BouncerTestCase(ZulipTestCase): def setUp(self) -> None: self.server_uuid = "1234-abcd" server = RemoteZulipServer(uuid=self.server_uuid, api_key="magic_secret_api_key", hostname="demo.example.com", ...
class BouncerTestCase(ZulipTestCase):
def setUp(self) -> None: self.server_uuid = "1234-abcd" server = RemoteZulipServer(uuid=self.server_uuid, api_key="magic_secret_api_key", hostname="demo.example.com", last_updated=now()) ...
_analytics_data, PushNotificationBouncerException from zerver.lib.request import JsonableError from zerver.lib.test_classes import ( TestCase, ZulipTestCase, ) from zilencer.models import RemoteZulipServer, RemotePushDeviceToken, \ RemoteRealmCount, RemoteInstallationCount, RemoteRealmAuditLog from django.util...
101
102
342
11
90
macto/zulip
zerver/tests/test_push_notifications.py
Python
BouncerTestCase
BouncerTestCase
76
117
76
76
1210f6cd197b0ef352811251adf51f699b3404b7
bigcode/the-stack
train
ddc337f28ffba0d0c78d7f35
train
class
class TestNumPushDevicesForUser(PushNotificationTest): def test_when_kind_is_none(self) -> None: self.setup_apns_tokens() self.assertEqual(num_push_devices_for_user(self.user_profile), 2) def test_when_kind_is_not_none(self) -> None: self.setup_apns_tokens() count = num_push_dev...
class TestNumPushDevicesForUser(PushNotificationTest):
def test_when_kind_is_none(self) -> None: self.setup_apns_tokens() self.assertEqual(num_push_devices_for_user(self.user_profile), 2) def test_when_kind_is_not_none(self) -> None: self.setup_apns_tokens() count = num_push_devices_for_user(self.user_profile, ...
with self.assertRaises(PushNotificationBouncerException) as exc: send_to_push_bouncer('register', 'register', {'msg': True}) self.assertEqual(str(exc.exception), 'Push notification bouncer returned unexpected status code 300') class TestNumPushDevicesForUser(PushNotificatio...
64
64
97
12
52
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestNumPushDevicesForUser
TestNumPushDevicesForUser
1,462
1,471
1,462
1,462
832695f140719777a76fd9ff6ba1fffbb9644ab9
bigcode/the-stack
train
2116a9ba29d473265d6da54f
train
class
class TestGetGCMPayload(PushNotificationTest): def test_get_message_payload_gcm(self) -> None: stream = Stream.objects.filter(name='Verona').get() message = self.get_message(Recipient.STREAM, stream.id) message.content = 'a' * 210 message.rendered_content = 'a' * 210 message....
class TestGetGCMPayload(PushNotificationTest):
def test_get_message_payload_gcm(self) -> None: stream = Stream.objects.filter(name='Verona').get() message = self.get_message(Recipient.STREAM, stream.id) message.content = 'a' * 210 message.rendered_content = 'a' * 210 message.save() message.trigger = 'mentioned' ...
, [self.example_email('othello'), self.example_email('cordelia')]) message = Message.objects.get(id=message_id) message.trigger = 'private_message' payload = get_message_payload_apns(user_profile, message) expected = { 'alert': { 'title': 'Cordelia...
256
256
1,164
11
245
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestGetGCMPayload
TestGetGCMPayload
1,279
1,396
1,279
1,279
bb1a0d336eaeb0c053b75013e737ac77e1621e7f
bigcode/the-stack
train
aa0d742ba085e0dcd6e128fd
train
class
class TestPushApi(ZulipTestCase): def test_push_api(self) -> None: user = self.example_user('cordelia') email = user.email self.login(email) endpoints = [ ('/json/users/me/apns_device_token', 'apple-tokenaz'), ('/json/users/me/android_gcm_reg_id', 'android-to...
class TestPushApi(ZulipTestCase):
def test_push_api(self) -> None: user = self.example_user('cordelia') email = user.email self.login(email) endpoints = [ ('/json/users/me/apns_device_token', 'apple-tokenaz'), ('/json/users/me/android_gcm_reg_id', 'android-token'), ] # Test e...
register', {'msg': True}) self.assertEqual(str(exc.exception), 'Push notification bouncer returned unexpected status code 300') class TestNumPushDevicesForUser(PushNotificationTest): def test_when_kind_is_none(self) -> None: self.setup_apns_tokens() self.assertEqual...
135
135
452
10
125
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestPushApi
TestPushApi
1,473
1,524
1,473
1,473
24da7a6da1cf4278651d126927b42aaab4481c9e
bigcode/the-stack
train
14749255f32dee298e0f9599
train
class
class Result: def __init__(self, status: int=200, content: str=ujson.dumps({'msg': 'error'})) -> None: self.status_code = status self.content = content
class Result:
def __init__(self, status: int=200, content: str=ujson.dumps({'msg': 'error'})) -> None: self.status_code = status self.content = content
apns': True}, 'gcm_payload': {'gcm': True}, 'gcm_options': {}, } mock_send.assert_called_with('POST', 'push/notify', ujson.dumps(post_data), extra_headers={'Content-type...
63
64
45
3
60
macto/zulip
zerver/tests/test_push_notifications.py
Python
Result
Result
1,415
1,418
1,415
1,415
0eff6e0a96b8dbd56060fec3c02821ee36ed4b6c
bigcode/the-stack
train
65adee0c36b8f90052ff25f9
train
class
class TestGetAPNsPayload(PushNotificationTest): def test_get_message_payload_apns_personal_message(self) -> None: user_profile = self.example_user("othello") message_id = self.send_personal_message( self.sender.email, user_profile.email, 'Content of personal messa...
class TestGetAPNsPayload(PushNotificationTest):
def test_get_message_payload_apns_personal_message(self) -> None: user_profile = self.example_user("othello") message_id = self.send_personal_message( self.sender.email, user_profile.email, 'Content of personal message', ) message = Message.objects...
.get_notification_result.side_effect = itertools.chain( [hyper.http20.exceptions.StreamResetError()], [hyper.http20.exceptions.StreamResetError()], [hyper.http20.exceptions.StreamResetError()], [hyper.http20.exceptions.StreamResetError()], ...
256
256
1,645
11
245
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestGetAPNsPayload
TestGetAPNsPayload
1,073
1,277
1,073
1,073
4891c4764d370e07a3ae2849c8112de62d03d276
bigcode/the-stack
train
cbf22b6e688d2bfa987d175a
train
class
class TestReceivesNotificationsFunctions(ZulipTestCase): def setUp(self) -> None: self.user = self.example_user('cordelia') def test_receivers_online_notifications_when_user_is_a_bot(self) -> None: self.user.is_bot = True self.user.enable_online_push_notifications = True self.a...
class TestReceivesNotificationsFunctions(ZulipTestCase):
def setUp(self) -> None: self.user = self.example_user('cordelia') def test_receivers_online_notifications_when_user_is_a_bot(self) -> None: self.user.is_bot = True self.user.enable_online_push_notifications = True self.assertFalse(receives_online_notifications(self.user)) ...
i in range(n_msgs)] UserMessage.objects.filter( user_profile_id=hamlet.id, message_id__in=message_ids, ).update( flags=F('flags').bitor( UserMessage.flags.active_mobile_push_notification)) with mock.patch("zerver.lib.actions.queue_json_publis...
221
221
739
12
209
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestReceivesNotificationsFunctions
TestReceivesNotificationsFunctions
1,721
1,805
1,721
1,721
bb2495f0093e4c84f6f5c0fdaa91c169fdfcae58
bigcode/the-stack
train
36a9efd779d3a8ad8be022ec
train
class
@mock.patch('zerver.lib.push_notifications.gcm_client') class GCMSendTest(PushNotificationTest): def setUp(self) -> None: super().setUp() self.setup_gcm_tokens() def get_gcm_data(self, **kwargs: Any) -> Dict[str, Any]: data = { 'key 1': 'Data 1', 'key 2': 'Data 2...
@mock.patch('zerver.lib.push_notifications.gcm_client') class GCMSendTest(PushNotificationTest):
def setUp(self) -> None: super().setUp() self.setup_gcm_tokens() def get_gcm_data(self, **kwargs: Any) -> Dict[str, Any]: data = { 'key 1': 'Data 1', 'key 2': 'Data 2', } data.update(kwargs) return data @mock.patch('zerver.lib.push_no...
{'token': token}) self.assert_json_success(result) tokens = list(PushDeviceToken.objects.filter(user=user, token=token)) self.assertEqual(len(tokens), 0) class GCMParseOptionsTest(TestCase): def test_invalid_option(self) -> None: with self.assertRaises(JsonableError): ...
256
256
1,446
23
233
macto/zulip
zerver/tests/test_push_notifications.py
Python
GCMSendTest
GCMSendTest
1,549
1,686
1,549
1,550
109337b8b3098e60dd93d9f535ed00a025ced60d
bigcode/the-stack
train
64c6d2138345bc90a7c8a28d
train
class
class PushNotificationTest(BouncerTestCase): def setUp(self) -> None: super().setUp() self.user_profile = self.example_user('hamlet') self.sending_client = get_client('test') self.sender = self.example_user('hamlet') def get_message(self, type: int, type_id: int=100) -> Message:...
class PushNotificationTest(BouncerTestCase):
def setUp(self) -> None: super().setUp() self.user_profile = self.example_user('hamlet') self.sending_client = get_client('test') self.sender = self.example_user('hamlet') def get_message(self, type: int, type_id: int=100) -> Message: recipient, _ = Recipient.objects.get...
realm=user.realm, modified_user=user, backfilled=True, event_type=RealmAuditLog.USER_REACTIVATED, event_time=self.TIME_ZERO, extra_data='data') send_analytics_to_remote_server() remote_log_entry = RemoteRealmAuditLog.objects.order_by('id').last() self.assertEqual(remote_log_entry.se...
156
156
522
9
147
macto/zulip
zerver/tests/test_push_notifications.py
Python
PushNotificationTest
PushNotificationTest
511
578
511
511
31bf23ffddc26745a5a6d45b7bb4bcc5ddbf9634
bigcode/the-stack
train
ec199787669b64ce8eedb315
train
class
class TestSendToPushBouncer(ZulipTestCase): @mock.patch('requests.request', return_value=Result(status=500)) @mock.patch('logging.warning') def test_500_error(self, mock_request: mock.MagicMock, mock_warning: mock.MagicMock) -> None: result, failed = send_to_push_bouncer('register', 'register', {'da...
class TestSendToPushBouncer(ZulipTestCase): @mock.patch('requests.request', return_value=Result(status=500)) @mock.patch('logging.warning')
def test_500_error(self, mock_request: mock.MagicMock, mock_warning: mock.MagicMock) -> None: result, failed = send_to_push_bouncer('register', 'register', {'data': True}) self.assertEqual(result, {}) self.assertEqual(failed, True) mock_warning.assert_called_once() @mock.patch('...
1, 'apns_payload': {'apns': True}, 'gcm_payload': {'gcm': True}, 'gcm_options': {}, } mock_send.assert_called_with('POST', 'push/notify', ujson.dumps(post_data), ...
153
153
511
37
115
macto/zulip
zerver/tests/test_push_notifications.py
Python
TestSendToPushBouncer
TestSendToPushBouncer
1,420
1,460
1,420
1,422
5fdd33df1ef1459cc5ddd0dd3237811b6bb6cc9d
bigcode/the-stack
train
cd834c9ab32dd518bd92c08b
train
class
class Baz(Generic[T]): def qux(self, v: T) -> None: ...
class Baz(Generic[T]):
def qux(self, v: T) -> None: ...
specialized function # used as an argument to a ParamSpec. from typing import Callable, Generic, Literal, ParamSpec, TypeVar T = TypeVar("T") P = ParamSpec("P") def foo(f: Callable[P, T]) -> Callable[P, T]: ... class Baz(Generic[T]):
64
64
20
5
59
sasano8/pyright
packages/pyright-internal/src/tests/samples/paramSpec7.py
Python
Baz
Baz
14
16
14
14
a1e424b76e58ed313bfce4ca4ad677818699447a
bigcode/the-stack
train
8ee6f1ba8ff5044abcbf0afa
train
function
def foo(f: Callable[P, T]) -> Callable[P, T]: ...
def foo(f: Callable[P, T]) -> Callable[P, T]:
...
This sample tests the handling of a specialized function # used as an argument to a ParamSpec. from typing import Callable, Generic, Literal, ParamSpec, TypeVar T = TypeVar("T") P = ParamSpec("P") def foo(f: Callable[P, T]) -> Callable[P, T]:
64
64
17
15
49
sasano8/pyright
packages/pyright-internal/src/tests/samples/paramSpec7.py
Python
foo
foo
10
11
10
10
2e751843c0b976645031802994a0b56b3fcfa6eb
bigcode/the-stack
train
bd1e8f6850ad85969971bf14
train
function
def main(_): """Runs main eval loop.""" # Parse config dict from yaml config files / command line flags. logdir = FLAGS.logdir config = util.ParseConfigsToLuaTable(FLAGS.config_paths, FLAGS.model_params) # Choose an estimator based on training strategy. estimator = get_estimator(config, logdir) # Wait f...
def main(_):
"""Runs main eval loop.""" # Parse config dict from yaml config files / command line flags. logdir = FLAGS.logdir config = util.ParseConfigsToLuaTable(FLAGS.config_paths, FLAGS.model_params) # Choose an estimator based on training strategy. estimator = get_estimator(config, logdir) # Wait for the first ...
parameters.') tf.app.flags.DEFINE_string('master', 'local', 'BNS name of the TensorFlow master to use') tf.app.flags.DEFINE_string( 'logdir', '/tmp/tcn', 'Directory where to write event logs.') FLAGS = tf.app.flags.FLAGS def main(_):
64
64
124
4
59
873040/Abhishek
research/tcn/eval.py
Python
main
main
44
60
44
44
4a9793b6ba933b3f708b969ece161ba8e50b0c82
bigcode/the-stack
train
f53fcedb81dc025173f61a94
train
function
def get_colored_area(perspective_transformed_image, margin, nwindows, minpixels): # make copy of the image image = np.copy(perspective_transformed_image) y_dir = image.shape[0] x_dir = image.shape[1] # Grab non zero pixels nonzero = image.nonzero() nonzero_y = np.array(nonzero[0]) ...
def get_colored_area(perspective_transformed_image, margin, nwindows, minpixels): # make copy of the image
image = np.copy(perspective_transformed_image) y_dir = image.shape[0] x_dir = image.shape[1] # Grab non zero pixels nonzero = image.nonzero() nonzero_y = np.array(nonzero[0]) nonzero_x = np.array(nonzero[1]) # Take a histogram for the bottom half of the image histogram = np.sum(ima...
# import import numpy as np import cv2 import glob import matplotlib.pyplot as plt import matplotlib.image as mpimg def get_colored_area(perspective_transformed_image, margin, nwindows, minpixels): # make copy of the image
57
256
1,202
29
27
DeanN96/CarND-Advanced-Lane-Lines
measure_curvature.py
Python
get_colored_area
get_colored_area
9
128
9
11
2d1f7c5ed4f651be09d05e83de945e394de07b54
bigcode/the-stack
train
85099676ee49672d37bbe84b
train
function
def hints(env: PysmtEnv) -> FrozenSet[Hint]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) symbs = frozenset([pc, x, y]) m_100 = mgr.Int(-100) m_1 = mgr.Int(-1) i_0 = mgr.Int...
def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) symbs = frozenset([pc, x, y]) m_100 = mgr.Int(-100) m_1 = mgr.Int(-1) i_0 = mgr.Int(0) i_1 = mgr.Int(1) i_2 = mgr.Int(2)...
= -1 cfg.append(mgr.Implies(pcend, x_pcend)) trans = [] same_x = mgr.Equals(x_x, x) same_y = mgr.Equals(x_y, y) same = mgr.And(same_x, same_y) # pc = 0 -> same trans.append(mgr.Implies(pcs[0], same)) # pc = 1 -> x' = x + y & same_y trans.append(mgr.Implies(pcs[1], ...
256
256
2,315
15
240
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_software_termination/18-2Nested_false-termination_28.py
Python
hints
hints
84
267
84
84
4fa39a6addbe2ac0d1888dd326392bf16b648156
bigcode/the-stack
train
ea23096241c2fbb555d42f09
train
function
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, FNode]: assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) x_pc = sym...
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, FNode]:
assert isinstance(env, PysmtEnv) mgr = env.formula_manager pc = mgr.Symbol("pc", types.INT) x = mgr.Symbol("x", types.INT) y = mgr.Symbol("y", types.INT) x_pc = symb_to_next(mgr, pc) x_x = symb_to_next(mgr, x) x_y = symb_to_next(mgr, y) symbols = frozenset([pc, x, y]) m_1 = mgr...
from typing import Tuple, FrozenSet from pysmt.environment import Environment as PysmtEnv from pysmt.fnode import FNode import pysmt.typing as types from utils import symb_to_next from hint import Hint, Location def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode, ...
80
207
690
28
51
EnricoMagnago/F3
benchmarks/f3_wrong_hints_permutations/scaling_software_termination/18-2Nested_false-termination_28.py
Python
transition_system
transition_system
11
81
11
12
ee7d9122ed3dd418f18e1c09634da5f16f30d0d1
bigcode/the-stack
train
41c089455118c396a5a10b41
train
function
def _beam_search_step(time, func, state, batch_size, beam_size, alpha, pad_id, eos_id): # Compute log probabilities seqs, log_probs = state.inputs[:2] flat_seqs = utils.merge_first_two_dims(seqs) flat_state = nest.map_structure(lambda x: utils.merge_first_two_dims(x), ...
def _beam_search_step(time, func, state, batch_size, beam_size, alpha, pad_id, eos_id): # Compute log probabilities
seqs, log_probs = state.inputs[:2] flat_seqs = utils.merge_first_two_dims(seqs) flat_state = nest.map_structure(lambda x: utils.merge_first_two_dims(x), state.state) step_log_probs, next_state = func(flat_seqs, flat_state) step_log_probs = utils.split_first_two_di...
"state", "finish"))): pass def _get_inference_fn(model_fns, features): def inference_fn(inputs, state): local_features = { "source": features["source"], "source_length": features["source_length"], # [bos_id, ...] => [..., 0] "target": tf.pad(inputs[:, 1...
256
256
888
32
223
fandongmeng/StackedDTMT
DTMT/dtmt/utils/inference.py
Python
_beam_search_step
_beam_search_step
52
125
52
54
b6bc5453849f5d9867aa9103ad6ae6038bd90912
bigcode/the-stack
train
7f10516dc88f0d1d0ae4281c
train
function
def _get_inference_fn(model_fns, features): def inference_fn(inputs, state): local_features = { "source": features["source"], "source_length": features["source_length"], # [bos_id, ...] => [..., 0] "target": tf.pad(inputs[:, 1:], [[0, 0], [0, 1]]), ...
def _get_inference_fn(model_fns, features):
def inference_fn(inputs, state): local_features = { "source": features["source"], "source_length": features["source_length"], # [bos_id, ...] => [..., 0] "target": tf.pad(inputs[:, 1:], [[0, 0], [0, 1]]), "target_length": tf.fill([tf.shape(inputs)[...
import tensorflow as tf import dtmt.utils.common as utils from collections import namedtuple from tensorflow.python.util import nest class BeamSearchState(namedtuple("BeamSearchState", ("inputs", "state", "finish"))): pass def _get_inference_fn(model_fns, features):
64
64
214
12
51
fandongmeng/StackedDTMT
DTMT/dtmt/utils/inference.py
Python
_get_inference_fn
_get_inference_fn
20
49
20
20
575c3dc160150c61cc8c46a15d26165f75bc0c34
bigcode/the-stack
train
ec549b23bde16af13bd2a4cb
train
function
def beam_search(func, state, batch_size, beam_size, max_length, alpha, pad_id, bos_id, eos_id): init_seqs = tf.fill([batch_size, beam_size, 1], bos_id) init_log_probs = tf.constant([[0.] + [tf.float32.min] * (beam_size - 1)]) init_log_probs = tf.tile(init_log_probs, [batch_size, 1]) init...
def beam_search(func, state, batch_size, beam_size, max_length, alpha, pad_id, bos_id, eos_id):
init_seqs = tf.fill([batch_size, beam_size, 1], bos_id) init_log_probs = tf.constant([[0.] + [tf.float32.min] * (beam_size - 1)]) init_log_probs = tf.tile(init_log_probs, [batch_size, 1]) init_scores = tf.zeros_like(init_log_probs) fin_seqs = tf.zeros([batch_size, beam_size, 1], tf.int32) fin_sc...
], axis=1) # [batch, beam_size] fin_scores, fin_indices = tf.nn.top_k(fin_scores, beam_size) fin_flags = utils.gather_2d(fin_flags, fin_indices) pad_seqs = tf.fill([batch_size, beam_size, 1], tf.constant(pad_id, tf.int32)) prev_fin_seqs = tf.concat([prev_fin_seqs, pad_seqs], a...
216
216
722
28
187
fandongmeng/StackedDTMT
DTMT/dtmt/utils/inference.py
Python
beam_search
beam_search
128
200
128
129
d4145b85550fd20abcba846887850bdb592fe053
bigcode/the-stack
train
c0e7158f212c58e9ff850818
train
function
def create_inference_graph(models, features, params): if not isinstance(models, (list, tuple)): raise ValueError("'models' must be a list or tuple") features = copy.copy(features) model_fns = [model.get_inference_func() for model in models] decode_length = params.decode_length beam_size = ...
def create_inference_graph(models, features, params):
if not isinstance(models, (list, tuple)): raise ValueError("'models' must be a list or tuple") features = copy.copy(features) model_fns = [model.get_inference_func() for model in models] decode_length = params.decode_length beam_size = params.beam_size top_beams = params.top_beams ...
], parallel_iterations=1, back_prop=False) final_state = outputs[1] alive_seqs = final_state.inputs[0] alive_scores = final_state.inputs[2] final_flags = final_state.finish[0] final_seqs = final_state.finish[1] final_scores = final_state.f...
167
167
558
11
155
fandongmeng/StackedDTMT
DTMT/dtmt/utils/inference.py
Python
create_inference_graph
create_inference_graph
203
264
203
203
3f9d8c0dd8a5d80207689af34f07ce0b81a79369
bigcode/the-stack
train
48d6766eac0d1612e66c8b02
train
class
class BeamSearchState(namedtuple("BeamSearchState", ("inputs", "state", "finish"))): pass
class BeamSearchState(namedtuple("BeamSearchState", ("inputs", "state", "finish"))):
pass
future__ import division from __future__ import print_function import copy import tensorflow as tf import dtmt.utils.common as utils from collections import namedtuple from tensorflow.python.util import nest class BeamSearchState(namedtuple("BeamSearchState", ("inputs", "state", "fini...
64
64
25
22
41
fandongmeng/StackedDTMT
DTMT/dtmt/utils/inference.py
Python
BeamSearchState
BeamSearchState
15
17
15
16
c6384cf6f558d0b9b73077376a7db8b06220e1d4
bigcode/the-stack
train
3b7997909e8561ea8ec7bfa8
train
class
class SingleValue(ValueContainer): def __init__(self, value): self.value = value def __iter__(self): yield self.value
class SingleValue(ValueContainer):
def __init__(self, value): self.value = value def __iter__(self): yield self.value
from Section08_Composite.Practice.ValueContainer import ValueContainer class SingleValue(ValueContainer):
19
64
33
6
12
enriqueescobar-askida/Kinito.Python
Section08_Composite/Practice/SingleValue.py
Python
SingleValue
SingleValue
4
9
4
4
8655b172bc36f88ebb9887aa4a838e3c9f5476ae
bigcode/the-stack
train
0c9cac0dbfe81aebd159982f
train
class
class TestRepositoryInstallIntegrationTestCase(integration_util.IntegrationTestCase, UsesShed): """Test data manager installation and table reload through the API""" @classmethod def handle_galaxy_config_kwds(cls, config): cls.configure_shed(config) def setUp(self): super().setUp() ...
class TestRepositoryInstallIntegrationTestCase(integration_util.IntegrationTestCase, UsesShed):
"""Test data manager installation and table reload through the API""" @classmethod def handle_galaxy_config_kwds(cls, config): cls.configure_shed(config) def setUp(self): super().setUp() self.dataset_populator = DatasetPopulator(self.galaxy_interactor) def tearDown(self): ...
import os from collections import namedtuple from galaxy_test.base.populators import DatasetPopulator from galaxy_test.driver import integration_util from tool_shed.util import hg_util from .uses_shed import UsesShed REPO_TYPE = namedtuple('Repository', 'name owner changeset') REPO = REPO_TYPE( 'collection_column...
147
256
1,136
19
128
biomarble/galaxy
test/integration/test_repository_operations.py
Python
TestRepositoryInstallIntegrationTestCase
TestRepositoryInstallIntegrationTestCase
19
127
19
20
6e00369a3c9e4cc336602b4c238422880cb473f9
bigcode/the-stack
train
1f1135cde04c0dd46d3fad09
train
class
class RProdlim(RPackage): """Product-Limit Estimation for Censored Event History Analysis Product-Limit Estimation for Censored Event History Analysis. Fast and user friendly implementation of nonparametric estimators for censored event history (survival) analysis. Kaplan-Meier and Aalen-Johansen metho...
class RProdlim(RPackage):
"""Product-Limit Estimation for Censored Event History Analysis Product-Limit Estimation for Censored Event History Analysis. Fast and user friendly implementation of nonparametric estimators for censored event history (survival) analysis. Kaplan-Meier and Aalen-Johansen method.""" homepage = "htt...
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RProdlim(RPackage):
61
123
413
7
54
kkauder/spack
var/spack/repos/builtin/packages/r-prodlim/package.py
Python
RProdlim
RProdlim
9
29
9
9
5852a4409b11793aaa64eaea0638ba4d7b1873a7
bigcode/the-stack
train
13a9c52a9aa242b4497492b4
train
class
class FFMPEG_AudioReader: """ A class to read the audio in either video files or audio files using ffmpeg. ffmpeg will read any audio and transform them into raw data. Parameters ------------ filename Name of any video or audio file, like ``video.mp4`` or ``sound.wav`` etc. ...
class FFMPEG_AudioReader:
""" A class to read the audio in either video files or audio files using ffmpeg. ffmpeg will read any audio and transform them into raw data. Parameters ------------ filename Name of any video or audio file, like ``video.mp4`` or ``sound.wav`` etc. buffersize The siz...
import subprocess as sp import warnings import numpy as np from moviepy.video.io.ffmpeg_reader import ffmpeg_parse_infos from moviepy.config import get_setting from moviepy.compat import PY3, DEVNULL import os class FFMPEG_AudioReader:
57
256
1,897
8
48
ilorevilo/moviepy
moviepy/audio/io/readers.py
Python
FFMPEG_AudioReader
FFMPEG_AudioReader
11
254
11
11
4bb0ca993c8a5b6dcb569282e961ea4d38fc790d
bigcode/the-stack
train
cf79e64c7d45729a2db1d56d
train
function
@app.route('/video_feed') def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame')
@app.route('/video_feed') def video_feed():
"""Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame')
') def gen(camera): """Video streaming generator function.""" while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed():
64
64
48
10
54
amshukla17/flask-screen-streaming
app.py
Python
video_feed
video_feed
26
30
26
27
252e0bdcac012c19bfcf574982c4a7cb5ed1c2bf
bigcode/the-stack
train
1dc25e131658b6143fcffb4d
train
function
@app.route('/') def index(): """Video streaming home page.""" return render_template('index.html')
@app.route('/') def index():
"""Video streaming home page.""" return render_template('index.html')
#!/usr/bin/env python from importlib import import_module import os from flask import Flask, render_template, Response from screen_camera import Camera app = Flask(__name__) @app.route('/') def index():
44
64
21
6
38
amshukla17/flask-screen-streaming
app.py
Python
index
index
12
15
12
13
6e54c87eb2da6470d58e91e8f8ee1c2fa9f8b61a
bigcode/the-stack
train
b8a881ecc4d7b023110cbe07
train
function
def gen(camera): """Video streaming generator function.""" while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
def gen(camera):
"""Video streaming generator function.""" while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
#!/usr/bin/env python from importlib import import_module import os from flask import Flask, render_template, Response from screen_camera import Camera app = Flask(__name__) @app.route('/') def index(): """Video streaming home page.""" return render_template('index.html') def gen(camera):
63
64
53
4
59
amshukla17/flask-screen-streaming
app.py
Python
gen
gen
18
23
18
18
67532fd2287dc59207e4d79b3e7d1a6a811c17f3
bigcode/the-stack
train
a3ea06865454b6b3e22a29d1
train
function
def main(): # SciELO Network csv scielodates()
def main(): # SciELO Network csv
scielodates()
odates(**rec) mdata.save() num_posts = models.Scielodates.objects().count() msg = u'Registred %d posts in SciELO Dates collection' % num_posts logger.info(msg) print(msg) def main(): # SciELO Network csv
64
64
17
11
53
ednilson/jcatalog
jcatalog/transform/scielo_dates_loader.py
Python
main
main
112
114
112
113
795a802e65f29f92831ae26711c1a9f32173ba34
bigcode/the-stack
train
b120259af0a772935eb6e17b
train
function
def scielodates(): scielo_sheet = pyexcel.get_sheet( file_name='data/scielo/documents_dates_network.csv', name_columns_by_row=0) # Key correction cols = [ 'extraction_date', 'study_unit', 'collection', 'issn_scielo', 'issns', 'title_at_scielo'...
def scielodates():
scielo_sheet = pyexcel.get_sheet( file_name='data/scielo/documents_dates_network.csv', name_columns_by_row=0) # Key correction cols = [ 'extraction_date', 'study_unit', 'collection', 'issn_scielo', 'issns', 'title_at_scielo', 'title_th...
# coding: utf-8 ''' This script reads data from various sources to process and store in MongoDB. ''' import pyexcel import logging import models import datetime logging.basicConfig(filename='logs/scielodatesnfo.txt', level=logging.INFO) logger = logging.getLogger(__name__) def scielodates():
69
237
790
6
63
ednilson/jcatalog
jcatalog/transform/scielo_dates_loader.py
Python
scielodates
scielodates
15
109
15
15
06cd84bd74cfde7b02026d143567d03993ff897b
bigcode/the-stack
train
46ee236d94691d843f41b3cd
train
function
def update_password(user_id: int, new_password: str): with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("""UPDATE users SET password_hash = ? WHERE id = ?""", [ hash_password(new_password), user_id ])
def update_password(user_id: int, new_password: str):
with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("""UPDATE users SET password_hash = ? WHERE id = ?""", [ hash_password(new_password), user_id ])
(password: Optional[str]) -> str: if password is None: # For SAI. return "" salted_password = password + cfg["password salt"] return hashlib.sha256(bytes(salted_password, "utf-8")).hexdigest() def update_password(user_id: int, new_password: str):
64
64
61
13
51
hinsley/infinite-go
user_db.py
Python
update_password
update_password
86
94
86
86
d5eac1199df9564fa5d0b475a1527634bb134dc3
bigcode/the-stack
train
79a675c2586ae877752a36e2
train
function
def validate_password(password: str) -> bool: """ Returns True if valid, False if invalid. """ return re.fullmatch(r"[A-Za-z0-9@#$%^&+=]{8,30}", password) is not None
def validate_password(password: str) -> bool:
""" Returns True if valid, False if invalid. """ return re.fullmatch(r"[A-Za-z0-9@#$%^&+=]{8,30}", password) is not None
(new_password), user_id ]) def validate_email(email: str) -> bool: """ Returns True if valid, False if invalid. """ return re.fullmatch(r"[^@]+@[^@]+\.[^@]+", email) def validate_password(password: str) -> bool:
64
64
53
10
54
hinsley/infinite-go
user_db.py
Python
validate_password
validate_password
102
106
102
102
457b2ee76431da3888397c5bc65f5a884011bc0b
bigcode/the-stack
train
5797c7eda4facf5144aef062
train
function
def validate_email(email: str) -> bool: """ Returns True if valid, False if invalid. """ return re.fullmatch(r"[^@]+@[^@]+\.[^@]+", email)
def validate_email(email: str) -> bool:
""" Returns True if valid, False if invalid. """ return re.fullmatch(r"[^@]+@[^@]+\.[^@]+", email)
, new_password: str): with sqlite3.connect(db_file) as db: cur = db.cursor() cur.execute("""UPDATE users SET password_hash = ? WHERE id = ?""", [ hash_password(new_password), user_id ]) def validate_email(email: str) -> bool:
64
64
45
10
54
hinsley/infinite-go
user_db.py
Python
validate_email
validate_email
96
100
96
96
a76977661072f6f9a029589c31f3c125c83625c1
bigcode/the-stack
train