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
86d18e64f1220e111f6eaadf
train
function
def test(net): import numpy as np total_params = 0 for x in filter(lambda p: p.requires_grad, net.parameters()): total_params += np.prod(x.data.numpy().shape) print("Total number of params", total_params) print("Total layers", len(list(filter(lambda p: p.requires_grad and len(p.data.size())...
def test(net):
import numpy as np total_params = 0 for x in filter(lambda p: p.requires_grad, net.parameters()): total_params += np.prod(x.data.numpy().shape) print("Total number of params", total_params) print("Total layers", len(list(filter(lambda p: p.requires_grad and len(p.data.size())>1, net.paramet...
ResNet(BasicBlock, [9, 9, 9]) def resnet110(): return ResNet(BasicBlock, [18, 18, 18]) def resnet1202(): return ResNet(BasicBlock, [200, 200, 200]) def test(net):
64
64
83
4
60
hecate64/CSQ
modelscifar/resnet20hist.py
Python
test
test
183
190
183
183
3d178a97ef867480023bebc85e43ac038b5e120b
bigcode/the-stack
train
d1fbd4cf4fdb667a108a7874
train
function
def _weights_init(m): classname = m.__class__.__name__ #print(classname) if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight)
def _weights_init(m):
classname = m.__class__.__name__ #print(classname) if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d): init.kaiming_normal_(m.weight)
kernel_size=3, stride=1, padding=1, bias=False,nbits=2): return Q.Conv2dLSQ_sym(input, output, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias, nbits=nbits) def _weights_init(m):
64
64
48
6
58
hecate64/CSQ
modelscifar/resnet20hist.py
Python
_weights_init
_weights_init
46
50
46
46
c5edb220c8ac71352d4d054df866ab500b25c657
bigcode/the-stack
train
0562798179b4580f7985d71b
train
class
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 16 self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(16) self.layer1 = BasicBlock(self.in_pla...
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 16 self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(16) self.layer1 = BasicBlock(self.in_planes, 16, stride=1) ...
, planes//4), "constant", 0)) elif option == 'B': self.shortcut = nn.Sequential( nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion * planes) ) def forward(self,...
194
194
647
6
187
hecate64/CSQ
modelscifar/resnet20hist.py
Python
ResNet
ResNet
97
156
97
97
d1823bf02210d22be7f737ea9c32844cf5c5da2b
bigcode/the-stack
train
bbf1b2e4bbcb4ead00cc5cd9
train
function
def resnet1202(): return ResNet(BasicBlock, [200, 200, 200])
def resnet1202():
return ResNet(BasicBlock, [200, 200, 200])
Net(BasicBlock, [7, 7, 7]) def resnet56(): return ResNet(BasicBlock, [9, 9, 9]) def resnet110(): return ResNet(BasicBlock, [18, 18, 18]) def resnet1202():
64
64
23
6
58
hecate64/CSQ
modelscifar/resnet20hist.py
Python
resnet1202
resnet1202
179
180
179
179
110abf0771ec382c591b406ac9fc865e451f3138
bigcode/the-stack
train
083d237ef7d50caf9f04985c
train
function
def query_polygon(**kw): return Query(**kw).geopolygon
def query_polygon(**kw):
return Query(**kw).geopolygon
""" Interactive dc viewer """ from types import SimpleNamespace from pandas import Period from datacube.api.query import Query from odc.index import dataset_count from ._map import show_datasets def query_polygon(**kw):
49
64
16
6
42
tahvane1/odc-tools
libs/ui/odc/ui/_dc_explore.py
Python
query_polygon
query_polygon
10
11
10
10
f81997c12cf63f9d33215a54a021fdf476faf8bb
bigcode/the-stack
train
091428dd6a2ff747275e0e51
train
function
def dt_step(d: str, step: int = 1) -> str: return str(Period(d) + step)
def dt_step(d: str, step: int = 1) -> str:
return str(Period(d) + step)
from pandas import Period from datacube.api.query import Query from odc.index import dataset_count from ._map import show_datasets def query_polygon(**kw): return Query(**kw).geopolygon def dt_step(d: str, step: int = 1) -> str:
64
64
27
17
46
tahvane1/odc-tools
libs/ui/odc/ui/_dc_explore.py
Python
dt_step
dt_step
14
15
14
14
6277f235119d8e8c231e2c83f96326920a8c6ffe
bigcode/the-stack
train
b415738e70e39a16f95d5656
train
class
class DcViewer: def __init__( self, dc, time, products=None, zoom=None, center=None, height=None, width=None, style=None, ): """ :param dc: Datacube object :param time: Initial time as a string :p...
class DcViewer:
def __init__( self, dc, time, products=None, zoom=None, center=None, height=None, width=None, style=None, ): """ :param dc: Datacube object :param time: Initial time as a string :param products: ...
""" Interactive dc viewer """ from types import SimpleNamespace from pandas import Period from datacube.api.query import Query from odc.index import dataset_count from ._map import show_datasets def query_polygon(**kw): return Query(**kw).geopolygon def dt_step(d: str, step: int = 1) -> str: return str(Peri...
90
256
1,603
4
86
tahvane1/odc-tools
libs/ui/odc/ui/_dc_explore.py
Python
DcViewer
DcViewer
18
256
18
18
71172d23054c9884aac53eacf5c40fc47d1eabd6
bigcode/the-stack
train
f88b28933d945f6637b72208
train
function
def warmup(warmup_epochs, k=1.0): def fun(epoch): if epoch < warmup_epochs: return epoch / warmup_epochs # 0 curr_epoch = max(epoch - warmup_epochs, 1) # >= 1 return 1.0 / math.sqrt(max(curr_epoch / k, 1.0)) return fun
def warmup(warmup_epochs, k=1.0):
def fun(epoch): if epoch < warmup_epochs: return epoch / warmup_epochs # 0 curr_epoch = max(epoch - warmup_epochs, 1) # >= 1 return 1.0 / math.sqrt(max(curr_epoch / k, 1.0)) return fun
Loader( MappedDataset(self.dataset["test"], self.preproc.preprocess_tx), batch_size=self.val_batch_size, shuffle=True, num_workers=self.num_workers, collate_fn=self.preproc.pad_collate, ) def warmup(warmup_epochs, k=1.0):
64
64
83
14
50
Manny810/seesaw
seesaw/models/clip_module.py
Python
warmup
warmup
100
108
100
100
506c451ef411dd787b5b6e46f745fcc66df783ab
bigcode/the-stack
train
90578b0a0164da204a7c3566
train
function
def split_into_sentences(desc): lst = desc.split(".") stripped = [l.strip(". ") for l in lst] whole = [s for s in stripped if s != ""] return whole
def split_into_sentences(desc):
lst = desc.split(".") stripped = [l.strip(". ") for l in lst] whole = [s for s in stripped if s != ""] return whole
= ds self.tx = tx def map(self, tx): return MappedDataset(self, tx=tx) def __getitem__(self, idx): return self.tx(self.ds[idx]) def __len__(self): return len(self.ds) def split_into_sentences(desc):
64
64
45
7
57
Manny810/seesaw
seesaw/models/clip_module.py
Python
split_into_sentences
split_into_sentences
37
41
37
37
93c6f0ae8fbbc44873a99e4fb72ae83bbb39ebb4
bigcode/the-stack
train
bd7f69b24616e4e49bb38b96
train
function
def load_experiment(tune_exp_dir): # can be run on ray 1.9.2 # eg. if exp name is try5 /home/gridsan/omoll/ray_results/try5 register_trainable( "clip_fine_tune", make_trainable( num_epochs=10, gpus_per_trial=0.5, dataset=None, init_config=None, ...
def load_experiment(tune_exp_dir): # can be run on ray 1.9.2 # eg. if exp name is try5 /home/gridsan/omoll/ray_results/try5
register_trainable( "clip_fine_tune", make_trainable( num_epochs=10, gpus_per_trial=0.5, dataset=None, init_config=None, init_state_dict=None, processor=None, ), ) exp = tune.ExperimentAnalysis(tune_exp_dir) ...
) import ray import argparse from ray.tune import register_trainable def load_experiment(tune_exp_dir): # can be run on ray 1.9.2 # eg. if exp name is try5 /home/gridsan/omoll/ray_results/try5
64
64
121
48
15
Manny810/seesaw
seesaw/models/clip_module.py
Python
load_experiment
load_experiment
332
346
332
333
bb04927cacfbc4a9db1e1878fd5d8fdc07b7cdd1
bigcode/the-stack
train
796a188dd0bf32a9082af211
train
class
class CLIPFineTunedModel(pl.LightningModule): def __init__(self, path_or_model, **kwargs): super().__init__() # todo: its easier to let pl save everything so it can also restore with .load_from_checkpoint # then, instead of passing a model or path, we should pass a config to construct a blan...
class CLIPFineTunedModel(pl.LightningModule):
def __init__(self, path_or_model, **kwargs): super().__init__() # todo: its easier to let pl save everything so it can also restore with .load_from_checkpoint # then, instead of passing a model or path, we should pass a config to construct a blank clip model, # then use load weights ...
_group(opt_config, prelim_groups, name, param) groups = [] for _, gps in prelim_groups.items(): for gp in gps: if len(gp["params"]) > 0: groups.append(gp) optimizer = transformers.AdamW(params=groups) lr_scheduler = transformers.get_constant_schedule_with_warmup( ...
115
115
385
12
103
Manny810/seesaw
seesaw/models/clip_module.py
Python
CLIPFineTunedModel
CLIPFineTunedModel
161
209
161
161
356e2cdaa9e51e0e9639d751d526fb042c8756c4
bigcode/the-stack
train
13612fb746af39094197a68a
train
function
def configure_optimizer(m, h): prelim_groups = {} opt_config = h["opt_config"] for (name, param) in m.named_parameters(): add_to_group(opt_config, prelim_groups, name, param) groups = [] for _, gps in prelim_groups.items(): for gp in gps: if len(gp["params"]) > 0: ...
def configure_optimizer(m, h):
prelim_groups = {} opt_config = h["opt_config"] for (name, param) in m.named_parameters(): add_to_group(opt_config, prelim_groups, name, param) groups = [] for _, gps in prelim_groups.items(): for gp in gps: if len(gp["params"]) > 0: groups.append(gp) ...
{"name": name + "_biases", "params": [], **bias_opts}, ) gp = groups[longest] if name.endswith("bias"): gp[1]["params"].append(param) else: gp[0]["params"].append(param) def configure_optimizer(m, h):
64
64
139
7
57
Manny810/seesaw
seesaw/models/clip_module.py
Python
configure_optimizer
configure_optimizer
141
158
141
141
0eb8a04d845a83bf37041fa46f77e2aa53d4cbbc
bigcode/the-stack
train
4121bdce36b4a539edcf8d06
train
function
def load_best_model(exp: tune.ExperimentAnalysis, metric="val_loss", mode="min"): """Loads best checkpoint overall""" tr = exp.get_best_trial(metric=metric, mode=mode, scope="all") chkpoint = exp.get_best_checkpoint(tr, metric=metric, mode=mode) model = CLIPFineTunedModel.load_from_checkpoint(chkpoint +...
def load_best_model(exp: tune.ExperimentAnalysis, metric="val_loss", mode="min"):
"""Loads best checkpoint overall""" tr = exp.get_best_trial(metric=metric, mode=mode, scope="all") chkpoint = exp.get_best_checkpoint(tr, metric=metric, mode=mode) model = CLIPFineTunedModel.load_from_checkpoint(chkpoint + "/checkpoint") return model
=0.5, dataset=None, init_config=None, init_state_dict=None, processor=None, ), ) exp = tune.ExperimentAnalysis(tune_exp_dir) return exp def load_best_model(exp: tune.ExperimentAnalysis, metric="val_loss", mode="min"):
64
64
87
20
43
Manny810/seesaw
seesaw/models/clip_module.py
Python
load_best_model
load_best_model
349
354
349
349
7947710d2dd72c010b9c7093e044276b91f977f7
bigcode/the-stack
train
652fa3719f8b45069274228d
train
class
class MappedDataset(torch.utils.data.Dataset): def __init__(self, ds, tx): self.ds = ds self.tx = tx def map(self, tx): return MappedDataset(self, tx=tx) def __getitem__(self, idx): return self.tx(self.ds[idx]) def __len__(self): return len(self.ds)
class MappedDataset(torch.utils.data.Dataset):
def __init__(self, ds, tx): self.ds = ds self.tx = tx def map(self, tx): return MappedDataset(self, tx=tx) def __getitem__(self, idx): return self.tx(self.ds[idx]) def __len__(self): return len(self.ds)
, CLIPConfig, CLIPVisionConfig, CLIPTextConfig, ) import os from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint import PIL import numpy as np import random import io from ray import tune class MappedDataset(torch.utils.data.Dataset):
64
64
80
9
54
Manny810/seesaw
seesaw/models/clip_module.py
Python
MappedDataset
MappedDataset
22
34
22
22
134439c749b24366f4792aee986c0bfbe5c423bf
bigcode/the-stack
train
cd277598c383d07594c5392b
train
function
def make_trainable( *, num_epochs, gpus_per_trial, dataset, init_config, init_state_dict, processor ): return tune.with_parameters( clip_fine_tune, num_epochs=num_epochs, num_gpus=gpus_per_trial, dataset=dataset, init_config=init_config, init_state_dict=init_state...
def make_trainable( *, num_epochs, gpus_per_trial, dataset, init_config, init_state_dict, processor ):
return tune.with_parameters( clip_fine_tune, num_epochs=num_epochs, num_gpus=gpus_per_trial, dataset=dataset, init_config=init_config, init_state_dict=init_state_dict, processor=processor, )
trainer.validate(model, data_mod) trainer.fit(model, data_mod) return trainer from ray.tune import CLIReporter from ray.tune.schedulers import ASHAScheduler def make_trainable( *, num_epochs, gpus_per_trial, dataset, init_config, init_state_dict, processor ):
64
64
83
27
36
Manny810/seesaw
seesaw/models/clip_module.py
Python
make_trainable
make_trainable
312
323
312
314
f7d94b09b1093b91b78d1c1bdb5d921b5696793b
bigcode/the-stack
train
a55a4d12655d849a200dd3d3
train
class
class MultiModalDataModule(pl.LightningDataModule): def __init__( self, dataset, processor, *, test_size, batch_size, val_batch_size, num_workers ): super().__init__() self.processor = processor self.dataset = dataset.shuffle().train_test_split(test_size=test_size) self.p...
class MultiModalDataModule(pl.LightningDataModule):
def __init__( self, dataset, processor, *, test_size, batch_size, val_batch_size, num_workers ): super().__init__() self.processor = processor self.dataset = dataset.shuffle().train_test_split(test_size=test_size) self.preproc = CLIPTx(processor) self.batch_size =...
in input_list], } ans = self.processor.tokenizer.pad( token_dict, padding="longest", return_tensors="pt" ) ans["pixel_values"] = torch.cat([d["pixel_values"] for d in input_list]) return ans class MultiModalDataModule(pl.LightningDataModule):
68
68
227
11
56
Manny810/seesaw
seesaw/models/clip_module.py
Python
MultiModalDataModule
MultiModalDataModule
69
97
69
69
a21956d7874b7b116634c1a72bb47eb74a92d098
bigcode/the-stack
train
dc42948e770b3b5e3db9b391
train
function
def clip_fine_tune( config, num_epochs, num_gpus, dataset: pa.Table, init_config: CLIPConfig, init_state_dict: dict, processor: CLIPProcessor, ): if "SLURM_NTASKS" in os.environ: del os.environ["SLURM_NTASKS"] if "SLURM_JOB_NAME" in os.environ: del os.environ["SLURM_...
def clip_fine_tune( config, num_epochs, num_gpus, dataset: pa.Table, init_config: CLIPConfig, init_state_dict: dict, processor: CLIPProcessor, ):
if "SLURM_NTASKS" in os.environ: del os.environ["SLURM_NTASKS"] if "SLURM_JOB_NAME" in os.environ: del os.environ["SLURM_JOB_NAME"] bird_dataset = dataset data_mod = MultiModalDataModule( dataset=bird_dataset, processor=processor, test_size=config["test_size"], ...
() else: return v from pytorch_lightning.loggers import TensorBoardLogger from ray.tune.integration.pytorch_lightning import ( TuneReportCallback, TuneReportCheckpointCallback, ) # def make_model(config) def clip_fine_tune( config, num_epochs, num_gpus, dataset: pa.Table, init...
97
97
325
48
49
Manny810/seesaw
seesaw/models/clip_module.py
Python
clip_fine_tune
clip_fine_tune
261
305
261
269
1cd860e9d7ed75674ec22d0a26b7456f2441e128
bigcode/the-stack
train
bc172f8b59451a81dbbbb2a6
train
function
def random_rate( prob_none, prob_zero_decay=0.2, lr_scale=tune.loguniform(1e-7, 1e-2), decay_scale=tune.loguniform(1e-5, 1e-1), ): def random_fun(spec): if tune.uniform(0, 1).sample() < prob_none: return None else: if tune.uniform(0, 1).sample() < prob_zero_de...
def random_rate( prob_none, prob_zero_decay=0.2, lr_scale=tune.loguniform(1e-7, 1e-2), decay_scale=tune.loguniform(1e-5, 1e-1), ):
def random_fun(spec): if tune.uniform(0, 1).sample() < prob_none: return None else: if tune.uniform(0, 1).sample() < prob_zero_decay: decay = 0.0 else: decay = decay_scale.sample() return {"lr": lr_scale.sample(), "weig...
means don't train this param at all) def random_rate( prob_none, prob_zero_decay=0.2, lr_scale=tune.loguniform(1e-7, 1e-2), decay_scale=tune.loguniform(1e-5, 1e-1), ):
64
64
143
56
8
Manny810/seesaw
seesaw/models/clip_module.py
Python
random_rate
random_rate
358
375
358
363
f4275a03ab549c606f148ab16ae6b9f169168030
bigcode/the-stack
train
57014e93f56e3b6f5a081a1c
train
function
def make_config(num_cpus): config = { "batch_size": tune.choice([32, 64]), "logit_scale_init": tune.quniform( -1.0, 5.0, q=0.1 ), # value from checkpoint is 4.6 "opt_config": { # for each parameter, will find the longest matching prefix and apply that rule. ...
def make_config(num_cpus):
config = { "batch_size": tune.choice([32, 64]), "logit_scale_init": tune.quniform( -1.0, 5.0, q=0.1 ), # value from checkpoint is 4.6 "opt_config": { # for each parameter, will find the longest matching prefix and apply that rule. "logit_scale": random_rate(...
if tune.uniform(0, 1).sample() < prob_none: return None else: if tune.uniform(0, 1).sample() < prob_zero_decay: decay = 0.0 else: decay = decay_scale.sample() return {"lr": lr_scale.sample(), "weight_decay": decay} return tun...
87
87
291
7
80
Manny810/seesaw
seesaw/models/clip_module.py
Python
make_config
make_config
378
402
378
378
d44f7686a711af8f4384ce58fd730df8efdb6d25
bigcode/the-stack
train
6fde5c5f03f0cd14be937e16
train
function
def add_to_group(opt_config, groups, name, param): """places param within the most specific group possible based on the config""" longest = "" for gp in opt_config.keys(): if name.startswith(gp) and len(gp) > len(longest): longest = gp if longest == "": print("warning: no r...
def add_to_group(opt_config, groups, name, param):
"""places param within the most specific group possible based on the config""" longest = "" for gp in opt_config.keys(): if name.startswith(gp) and len(gp) > len(longest): longest = gp if longest == "": print("warning: no rule for parameter", name) assert False ...
warmup_epochs # 0 curr_epoch = max(epoch - warmup_epochs, 1) # >= 1 return 1.0 / math.sqrt(max(curr_epoch / k, 1.0)) return fun def add_to_group(opt_config, groups, name, param):
65
65
218
13
51
Manny810/seesaw
seesaw/models/clip_module.py
Python
add_to_group
add_to_group
111
138
111
111
1e76b756a7b005b608ab16c9450a6507a00b99ac
bigcode/the-stack
train
d17f59052e9e0d2c2e7e0b20
train
class
class CLIPTx: def __init__(self, processor): self.processor = processor def preprocess_tx(self, dataset_tup): im = PIL.Image.open(io.BytesIO(dataset_tup["image_bytes"])) sentences = split_into_sentences(dataset_tup["text"]) sentence = random.choice(sentences) inputs = se...
class CLIPTx:
def __init__(self, processor): self.processor = processor def preprocess_tx(self, dataset_tup): im = PIL.Image.open(io.BytesIO(dataset_tup["image_bytes"])) sentences = split_into_sentences(dataset_tup["text"]) sentence = random.choice(sentences) inputs = self.processor(t...
]) def __len__(self): return len(self.ds) def split_into_sentences(desc): lst = desc.split(".") stripped = [l.strip(". ") for l in lst] whole = [s for s in stripped if s != ""] return whole class CLIPTx:
64
64
214
5
58
Manny810/seesaw
seesaw/models/clip_module.py
Python
CLIPTx
CLIPTx
44
66
44
44
632c05f0f3f20da545116d58425718497d81a879
bigcode/the-stack
train
cd36e18b5daf9f5b7667dc45
train
function
def generate_sample(v): if isinstance(v, dict): return {k: generate_sample(w) for (k, w) in v.items()} elif isinstance(v, list): return [generate_sample(w) for w in v] elif getattr(v, "sample", None) != None: return v.sample() else: return v
def generate_sample(v):
if isinstance(v, dict): return {k: generate_sample(w) for (k, w) in v.items()} elif isinstance(v, list): return [generate_sample(w) for w in v] elif getattr(v, "sample", None) != None: return v.sample() else: return v
"init_scale": 17.08693539204199, "num_warmup_steps": 8, "num_workers": 8, "test_size": 1000, "val_batch_size": 500, } import ray.tune as tune def generate_sample(v):
64
64
75
5
58
Manny810/seesaw
seesaw/models/clip_module.py
Python
generate_sample
generate_sample
241
249
241
241
6c166dc72cdd97f2302e68c3d892e2a1dee08d56
bigcode/the-stack
train
55ace397f80d2588c7656e9b
train
class
class PharmacyFilter(django_filters.FilterSet): street = django_filters.Filter(lookup_expr='icontains', label='Адрес:') class Meta: model = core.models.Pharmacy fields = ('street',)
class PharmacyFilter(django_filters.FilterSet):
street = django_filters.Filter(lookup_expr='icontains', label='Адрес:') class Meta: model = core.models.Pharmacy fields = ('street',)
class ProductFilter(django_filters.FilterSet): name = django_filters.Filter(lookup_expr='icontains', label='Название:') price = django_filters.RangeFilter() class Meta: model = core.models.Product fields = ('name', 'price',) class PharmacyFilter(django_filters.FilterSet):
64
64
47
9
55
Wanderer2436/django_pharmacy
core/filters.py
Python
PharmacyFilter
PharmacyFilter
14
19
14
14
6db7499f3a6b27d0aa5d70ca79c753de45ce02b4
bigcode/the-stack
train
fdbc96f039a058ade98bd53f
train
class
class ProductFilter(django_filters.FilterSet): name = django_filters.Filter(lookup_expr='icontains', label='Название:') price = django_filters.RangeFilter() class Meta: model = core.models.Product fields = ('name', 'price',)
class ProductFilter(django_filters.FilterSet):
name = django_filters.Filter(lookup_expr='icontains', label='Название:') price = django_filters.RangeFilter() class Meta: model = core.models.Product fields = ('name', 'price',)
import django_filters import core.models class ProductFilter(django_filters.FilterSet):
17
64
55
9
7
Wanderer2436/django_pharmacy
core/filters.py
Python
ProductFilter
ProductFilter
5
11
5
5
359fa4f381fdffc892c7bf97812a47b56bea016d
bigcode/the-stack
train
8983b7d3bc5a7561ffa8f21c
train
function
def plot_line(x, y, legend=None): """Creates an aggregator that draw a line plot.""" # TODO(beam2d): Write a document. def get_normalized_axis_config(k): if isinstance(k, str): return {'key': k} return k x = get_normalized_axis_config(x) y = get_normalized_axis_config(y...
def plot_line(x, y, legend=None):
"""Creates an aggregator that draw a line plot.""" # TODO(beam2d): Write a document. def get_normalized_axis_config(k): if isinstance(k, str): return {'key': k} return k x = get_normalized_axis_config(x) y = get_normalized_axis_config(y) def callback(figure, data, ...
py:class:`matplotlib.figure.Figure`, :py:class:`PlotData`). """ @functools.wraps(callback_body) @maflib.util.aggregator def callback(values, abspath, parameter): figure = matplotlib.pyplot.figure() plot_data = PlotData(values) callback_body(figure, plot_data, parameter) ...
101
101
338
10
90
nozyh/maf
maflib/plot.py
Python
plot_line
plot_line
255
300
255
255
04e9f1ae844e2d931711f6824e6ccca13eb21c54
bigcode/the-stack
train
177c9ab799a0a2c982494c08
train
class
class PlotData: """Result of experimentation collected through a meta node to plot. Result of experiments is represented by a meta node consisted by a set of physical nodes each of which contains a dictionary or an array of dictionaries. This class is used to collect all dictionaries through the me...
class PlotData:
"""Result of experimentation collected through a meta node to plot. Result of experiments is represented by a meta node consisted by a set of physical nodes each of which contains a dictionary or an array of dictionaries. This class is used to collect all dictionaries through the meta node and to e...
the above copyright notice, # this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. ...
256
256
1,601
4
251
nozyh/maf
maflib/plot.py
Python
PlotData
PlotData
36
228
36
36
e39c18f4b8be7e04ef59bd0526a02bdc588f6bd0
bigcode/the-stack
train
ae7c568d82e12d400d320f1c
train
function
def plot_by(callback_body): """Creates an aggregator to plot data using matplotlib and PlotData. :param callback_body: Callable object or function that plots data. It takes three parameters: :py:class:`matplotlib.figure.Figure` object, :py:class:`maflib.plot.PlotData` object and a parameter of ...
def plot_by(callback_body):
"""Creates an aggregator to plot data using matplotlib and PlotData. :param callback_body: Callable object or function that plots data. It takes three parameters: :py:class:`matplotlib.figure.Figure` object, :py:class:`maflib.plot.PlotData` object and a parameter of class :py:class:`maf...
data: if sort: data[k].sort() data[k] = ( [v[0] for v in data[k]], [v[1] for v in data[k]], [v[2] for v in data[k]]) return data def plot_by(callback_body):
64
64
213
6
57
nozyh/maf
maflib/plot.py
Python
plot_by
plot_by
231
252
231
231
6a591374b1b5fe373b4cdd57442a66cdbcf9a8b6
bigcode/the-stack
train
9ff4685eb8ca99eabfb716bf
train
class
class NextcloudStore(SQLBaseStore): def __init__(self, database: DatabasePool, db_conn, hs: "Homeserver"): super().__init__(database, db_conn, hs) async def get_share_id(self, room_id: str): """Get Nextcloud share id of a room. Args: room_id: id of the room """ ...
class NextcloudStore(SQLBaseStore):
def __init__(self, database: DatabasePool, db_conn, hs: "Homeserver"): super().__init__(database, db_conn, hs) async def get_share_id(self, room_id: str): """Get Nextcloud share id of a room. Args: room_id: id of the room """ return await self.db_pool.simple...
from synapse.storage._base import SQLBaseStore from synapse.storage.database import DatabasePool class NextcloudStore(SQLBaseStore):
28
129
430
8
19
watcha-fr/synapse
synapse/storage/databases/main/watcha_nextcloud.py
Python
NextcloudStore
NextcloudStore
5
64
5
5
143ee1384e27d32349c20c0d586956954ece54a6
bigcode/the-stack
train
b405cc0481104cb6d8c4ee1f
train
class
class Join(HybridShape): """ Result of join operation """ def __init__(self, parent, cat_constructor, objs): super(Join, self).__init__(parent, cat_constructor) self.objs = objs
class Join(HybridShape):
""" Result of join operation """ def __init__(self, parent, cat_constructor, objs): super(Join, self).__init__(parent, cat_constructor) self.objs = objs
from ..hybridShape import HybridShape class Join(HybridShape):
16
64
50
6
9
robertpardillo/Funnel
src/server_3D/API/Rice/abstractObjects/hybridShapes/join.py
Python
Join
Join
5
11
5
5
1e10efda393e0933e58a2385deac8c8b54cab0e1
bigcode/the-stack
train
76e8f42fe02ee1ca234d02d5
train
class
class DataGenerator: ''' A generator to generate batches of samples and corresponding labels indefinitely. Can shuffle the dataset consistently after each complete pass. A general-purpose CSV parser is provided to parse annotation data, Can perform image transformations for data conversion and da...
class DataGenerator:
''' A generator to generate batches of samples and corresponding labels indefinitely. Can shuffle the dataset consistently after each complete pass. A general-purpose CSV parser is provided to parse annotation data, Can perform image transformations for data conversion and data augmentation, ...
OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Modifications author : Paul Pontisso ''' from __future__ import division import numpy as np import warnings import sklearn.utils from copy import deepcopy from PIL import Image i...
256
256
6,125
4
251
ekorudiawan/DRBox
data_generator/object_detection_2d_data_generator.py
Python
DataGenerator
DataGenerator
58
631
58
58
fc66fefc5e22abc6ef8d52f83e8eced0d68cfbfc
bigcode/the-stack
train
08195db25edc6e368f641974
train
class
class DatasetError(Exception): ''' An exception class to be raised if a anything is wrong with the dataset, in particular if you try to generate batches when no dataset was loaded. ''' pass
class DatasetError(Exception):
''' An exception class to be raised if a anything is wrong with the dataset, in particular if you try to generate batches when no dataset was loaded. ''' pass
) from data_generator.object_detection_2d_image_boxes_validation_utils import BoxFilter class DegenerateBatchError(Exception): ''' An exception class to be raised if a generated batch ends up being degenerate, e.g. if a generated batch is empty. ''' pass class DatasetError(Exception):
64
64
43
5
58
ekorudiawan/DRBox
data_generator/object_detection_2d_data_generator.py
Python
DatasetError
DatasetError
50
55
50
50
a7a1e610d99c0ce3b9f20f73dc80f6724f41848a
bigcode/the-stack
train
6a6adf3f14e2f7cf0a3a598b
train
class
class DegenerateBatchError(Exception): ''' An exception class to be raised if a generated batch ends up being degenerate, e.g. if a generated batch is empty. ''' pass
class DegenerateBatchError(Exception):
''' An exception class to be raised if a generated batch ends up being degenerate, e.g. if a generated batch is empty. ''' pass
import BoxFilter try: import pickle except ImportError: warnings.warn("'pickle' module is missing. You won't be able to save parsed file lists and annotations as pickled files.") from data_generator.object_detection_2d_image_boxes_validation_utils import BoxFilter class DegenerateBatchError(Exception):
64
64
42
7
56
ekorudiawan/DRBox
data_generator/object_detection_2d_data_generator.py
Python
DegenerateBatchError
DegenerateBatchError
43
48
43
43
0b46af997bc5c12ffa5e923d72a68e6bff511115
bigcode/the-stack
train
c944aaa67eb1e83fac9b9704
train
class
class Migration(migrations.Migration): dependencies = [ ('app_users', '0001_initial'), ('curriculum', '0004_auto_20200926_1217'), ] operations = [ migrations.AlterField( model_name='lesson', name='image', field=models.ImageField(blank=True, uploa...
class Migration(migrations.Migration):
dependencies = [ ('app_users', '0001_initial'), ('curriculum', '0004_auto_20200926_1217'), ] operations = [ migrations.AlterField( model_name='lesson', name='image', field=models.ImageField(blank=True, upload_to='images/', verbose_name='Images'), ...
# Generated by Django 3.1.1 on 2020-09-27 13:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
45
64
201
7
37
Akbarshokh/Schook_LMSS
curriculum/migrations/0005_auto_20200927_1914.py
Python
Migration
Migration
7
30
7
8
0c01445d15cf78b0806bd4398aa833d300ead59a
bigcode/the-stack
train
2cb45a42ce76128bcd2a6b25
train
class
class TestLogClass(unittest.TestCase): """Test case for Logging""" @classmethod def setUpClass(cls): """Setup the test class.""" cls.log = get_logger(__name__) def test_auto_gen_1(self): """ Test initalisation of log file.""" module_0.setup() self.assertEqual(mo...
class TestLogClass(unittest.TestCase):
"""Test case for Logging""" @classmethod def setUpClass(cls): """Setup the test class.""" cls.log = get_logger(__name__) def test_auto_gen_1(self): """ Test initalisation of log file.""" module_0.setup() self.assertEqual(module_0.TRACE_LEVEL, 5) def test_ca...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # File Name: test_log.py import logging import unittest import neorg.log as module_0 from neorg import constants from neorg.log import get_logger class TestLogClass(unittest.TestCase):
70
256
893
8
61
dchuri/neorg-discord-bot
tests/neorg/test_log.py
Python
TestLogClass
TestLogClass
14
106
14
14
1bd7b7535774256411a6d3082245da458bd82f7c
bigcode/the-stack
train
cde2693a0d42fd263f90bbfc
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ('playlists', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='playlist', name='playlist_usuario', ...
class Migration(migrations.Migration):
initial = True dependencies = [ ('playlists', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.AddField( model_name='playlist', name='playlist_usuario', field=models.ForeignKey(on_delete=...
# Generated by Django 3.0.8 on 2020-07-17 06:34 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
51
64
90
7
43
Antonio-Neves/My-Tube-Library-Django
playlists/migrations/0002_playlist_playlist_usuario.py
Python
Migration
Migration
8
23
8
9
d79801b2b52fdf48120aa446fab19a2aad205627
bigcode/the-stack
train
335e85b73e15a0d038753737
train
class
class Node: def __init__(self, value, next_item=None): self.value = value self.next_item = next_item
class Node:
def __init__(self, value, next_item=None): self.value = value self.next_item = next_item
class Node:
3
64
30
3
0
DimaZzZz101/Yandex_Practicum_Algorithms
Sprint_2/Practice/D/answer_file.py
Python
Node
Node
1
4
1
1
3d7d01e7ae2b619ec8676b360cd40275c78b2253
bigcode/the-stack
train
324f7e5b2fe8efb7e627fdec
train
function
def solution(node, elem) -> int: current_node = node index = 0 while current_node is not None: if current_node.value == elem: return index if current_node.next_item is None: return -1 current_node = current_node.next_item index += 1
def solution(node, elem) -> int:
current_node = node index = 0 while current_node is not None: if current_node.value == elem: return index if current_node.next_item is None: return -1 current_node = current_node.next_item index += 1
class Node: def __init__(self, value, next_item=None): self.value = value self.next_item = next_item def solution(node, elem) -> int:
39
64
70
9
29
DimaZzZz101/Yandex_Practicum_Algorithms
Sprint_2/Practice/D/answer_file.py
Python
solution
solution
7
19
7
7
a4945ab94a631a601150d31604310c603ac358ce
bigcode/the-stack
train
a86b339d00e6f3cb9bbafb45
train
class
class Bot(): def __init__(self, name, welcome_message=''): self.name = name self.len_name = len(name) self.welcome_message = welcome_message self.simple_listeners = {} self.complex_listeners = {} def add_simple_listener(self, term, action): self.simple_listeners[...
class Bot():
def __init__(self, name, welcome_message=''): self.name = name self.len_name = len(name) self.welcome_message = welcome_message self.simple_listeners = {} self.complex_listeners = {} def add_simple_listener(self, term, action): self.simple_listeners[term] = actio...
import socket class Bot():
6
196
656
3
2
jmtrachy/irc-bot
bot.py
Python
Bot
Bot
4
75
4
4
3d0f114579fd7fab653b25c0613aacf6e3d970dc
bigcode/the-stack
train
a40286ceb9bb3d3cf21b9b6d
train
class
@pulumi.input_type class NamespaceArgs: def __init__(__self__, *, resource_group_name: pulumi.Input[str], is_auto_inflate_enabled: Optional[pulumi.Input[bool]] = None, kafka_enabled: Optional[pulumi.Input[bool]] = None, location: Optional[pulumi.In...
@pulumi.input_type class NamespaceArgs:
def __init__(__self__, *, resource_group_name: pulumi.Input[str], is_auto_inflate_enabled: Optional[pulumi.Input[bool]] = None, kafka_enabled: Optional[pulumi.Input[bool]] = None, location: Optional[pulumi.Input[str]] = None, maxim...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
113
256
1,284
10
103
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/eventhub/namespace.py
Python
NamespaceArgs
NamespaceArgs
16
148
16
17
05dd9bcc0c601861dd53707f289c0f0da23fe8f5
bigcode/the-stack
train
40fd07b3c9c96cb1aa22f7c8
train
class
class Namespace(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, is_auto_inflate_enabled: Optional[pulumi.Input[bool]] = None, kafka_enabled: Optional[pulumi.Input[bool]...
class Namespace(pulumi.CustomResource): @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, is_auto_inflate_enabled: Optional[pulumi.Input[bool]] = None, kafka_enabled: Optional[pulumi.Input[bool]] = None, location: Optional[pulumi.I...
ter(name="namespaceName") def namespace_name(self) -> Optional[pulumi.Input[str]]: """ The Namespace name """ return pulumi.get(self, "namespace_name") @namespace_name.setter def namespace_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "namespace_na...
256
256
2,454
13
243
polivbr/pulumi-azure-native
sdk/python/pulumi_azure_native/eventhub/namespace.py
Python
Namespace
Namespace
151
383
151
152
eb30afb7d701588895e2588fe89e57d437474e46
bigcode/the-stack
train
d32c8f5d3908032c602bc182
train
class
class PrintVisitor(base_visitor.Visitor): """Visitor for converting ASTs back to pytd source code.""" visits_all_node_types = True unchecked_node_names = base_visitor.ALL_NODE_NAMES INDENT = " " * 4 _RESERVED = frozenset(parser_constants.RESERVED + parser_constants.RESERVED_PYTHON) ...
class PrintVisitor(base_visitor.Visitor):
"""Visitor for converting ASTs back to pytd source code.""" visits_all_node_types = True unchecked_node_names = base_visitor.ALL_NODE_NAMES INDENT = " " * 4 _RESERVED = frozenset(parser_constants.RESERVED + parser_constants.RESERVED_PYTHON) def __init__(self, multiline_args=False):...
"""Printer to output pytd trees in pyi format.""" import collections import copy import logging import re from pytype import utils from pytype.pytd import base_visitor from pytype.pytd import pep484 from pytype.pytd import pytd from pytype.pytd.parse import parser_constants class PrintVisitor(base_visitor.Visitor):
77
256
5,588
9
67
hboshnak/pytype
pytype/pytd/printer.py
Python
PrintVisitor
PrintVisitor
15
658
15
15
4ccca900fe0ed2efe8915238255190159793aa21
bigcode/the-stack
train
dbc1726e0f3883f198473090
train
class
class GinoStrategy(EngineStrategy): name = 'gino' engine_cls = GinoEngine async def create(self, name_or_url, loop=None, **kwargs): engine_cls = self.engine_cls u = url.make_url(name_or_url) if loop is None: loop = asyncio.get_event_loop() if u.drivername in {'po...
class GinoStrategy(EngineStrategy):
name = 'gino' engine_cls = GinoEngine async def create(self, name_or_url, loop=None, **kwargs): engine_cls = self.engine_cls u = url.make_url(name_or_url) if loop is None: loop = asyncio.get_event_loop() if u.drivername in {'postgresql', 'postgres'}: ...
import asyncio from sqlalchemy.engine import url from sqlalchemy import util from sqlalchemy.engine.strategies import EngineStrategy from .engine import GinoEngine class GinoStrategy(EngineStrategy):
40
130
435
8
31
jim-obrien-orig/gino
gino/strategies.py
Python
GinoStrategy
GinoStrategy
10
64
10
10
849531a942d5cef79251f726acc3c1e1776ec2b1
bigcode/the-stack
train
be0ae4dbcadce2a19f718192
train
function
def gru_train(X_train, X_val, y_train, y_val, params): tokenizer_obj = Tokenizer() tokenizer_obj.fit_on_texts(X_train) # save tokenizer experiment = Experiment() save_tokenizer = experiment.get_outputs_path() + '/GRU_tokenizer.pickle' with open(save_tokenizer, 'wb') as handle: ...
def gru_train(X_train, X_val, y_train, y_val, params):
tokenizer_obj = Tokenizer() tokenizer_obj.fit_on_texts(X_train) # save tokenizer experiment = Experiment() save_tokenizer = experiment.get_outputs_path() + '/GRU_tokenizer.pickle' with open(save_tokenizer, 'wb') as handle: pickle.dump(tokenizer_obj, handle, protocol=pickle.HIGHEST_P...
import numpy as np import math import pickle from tensorflow.python.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Sequential from tensorflow.keras.layers import (Dropout, Embedding, Dense, GRU, Bidirectional) from tensorfl...
95
144
480
18
76
dashtagger/sentiment_analysis_covid
src/experiment/model_GRU.py
Python
gru_train
gru_train
12
72
12
13
cd3b92ef453d5978cfc63d1627fa2bf9cb492d53
bigcode/the-stack
train
312c2f66d3417baf85613e16
train
class
class Lead(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) message = models.CharField(max_length=500, blank=True) created_at = models.DateTimeField(auto_now_add=True)
class Lead(models.Model):
name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) message = models.CharField(max_length=500, blank=True) created_at = models.DateTimeField(auto_now_add=True)
from django.db import models class Lead(models.Model):
11
64
57
5
5
raulburigo/leadmanager
leads/models.py
Python
Lead
Lead
4
8
4
4
2b43172c73885eb8092c07bed1f13521d2bdaf47
bigcode/the-stack
train
0894cf3df33b4aefe2c93956
train
function
def create(key): """Creates and attaches a disk for the given Instance. Args: key: ndb.Key for a models.Instance entity. """ instance = key.get() if not instance: logging.warning('Instance does not exist: %s', key) return if instance.disk: return igm_key = instances.get_instance_group_m...
def create(key):
"""Creates and attaches a disk for the given Instance. Args: key: ndb.Key for a models.Instance entity. """ instance = key.get() if not instance: logging.warning('Instance does not exist: %s', key) return if instance.disk: return igm_key = instances.get_instance_group_manager_key(key) ...
from components import gce from components import net import instances import models import utilities @ndb.transactional def set_attached(key, disk): """Sets the disk as attached to the given Instance. Args: key: ndb.Key for a models.Instance entity. disk: Name of the disk. """ instance = key.get() ...
139
139
466
4
135
Swift1313/luci-py
appengine/gce-backend/disks.py
Python
create
create
40
101
40
40
acf65ca4c0d864760bbf32a153169131d878757f
bigcode/the-stack
train
40c3b178dc02d61aae82cf9d
train
function
def schedule_creation(): """Enqueues tasks to create disks.""" for itr in models.InstanceTemplateRevision.query(): if itr.snapshot_url: _schedule_creation(itr.active) _schedule_creation(itr.drained)
def schedule_creation():
"""Enqueues tasks to create disks.""" for itr in models.InstanceTemplateRevision.query(): if itr.snapshot_url: _schedule_creation(itr.active) _schedule_creation(itr.drained)
Manager entities. """ for igm_key in keys: igm = igm_key.get() if igm: for key in igm.instances: instance = key.get() if instance and not instance.disk: utilities.enqueue_task('create-disk', key) def schedule_creation():
64
64
46
4
60
Swift1313/luci-py
appengine/gce-backend/disks.py
Python
schedule_creation
schedule_creation
119
124
119
119
bdcf80685f99e36288d8129ab4bbbee2209215f9
bigcode/the-stack
train
47f3ad1e7525b52d05f58835
train
function
def _schedule_creation(keys): """Enqueues tasks to create disks. Args: keys: ndb.Key for models.InstanceGroupManager entities. """ for igm_key in keys: igm = igm_key.get() if igm: for key in igm.instances: instance = key.get() if instance and not instance.disk: utili...
def _schedule_creation(keys):
"""Enqueues tasks to create disks. Args: keys: ndb.Key for models.InstanceGroupManager entities. """ for igm_key in keys: igm = igm_key.get() if igm: for key in igm.instances: instance = key.get() if instance and not instance.disk: utilities.enqueue_task('create-disk...
disk is attached. result = api.get_instance(igm_key.id(), name, fields=['disks/deviceName']) for d in result.get('disks', []): if d.get('deviceName') == disk: set_attached(key, disk) return def _schedule_creation(keys):
64
64
88
6
57
Swift1313/luci-py
appengine/gce-backend/disks.py
Python
_schedule_creation
_schedule_creation
104
116
104
104
f89435dae7b046fca12f45f5e3337539fbc301e4
bigcode/the-stack
train
fa0bd2006316db702d87dd44
train
function
@ndb.transactional def set_attached(key, disk): """Sets the disk as attached to the given Instance. Args: key: ndb.Key for a models.Instance entity. disk: Name of the disk. """ instance = key.get() if not instance: logging.warning('Instance does not exist: %s', key) return if instance.disk...
@ndb.transactional def set_attached(key, disk):
"""Sets the disk as attached to the given Instance. Args: key: ndb.Key for a models.Instance entity. disk: Name of the disk. """ instance = key.get() if not instance: logging.warning('Instance does not exist: %s', key) return if instance.disk == disk: return logging.info('Updating d...
# that can be found in the LICENSE file. """Utilities for operating on persistent disks.""" import logging from google.appengine.ext import ndb from components import gce from components import net import instances import models import utilities @ndb.transactional def set_attached(key, disk):
64
64
116
14
49
Swift1313/luci-py
appengine/gce-backend/disks.py
Python
set_attached
set_attached
19
37
19
20
f9f97336f2cd927aabc772e9a4300a318d0744f6
bigcode/the-stack
train
c1720473ba3e4de57d7c94d4
train
function
def create_task(current_gitlab_version, most_recent_gitlab_version, last_reminder): api = todoist.TodoistAPI(TODOIST_TOKEN) text = MESSAGE_TEMPLATE.format( most_recent_gitlab_version=most_recent_gitlab_version, current_gitlab_version=current_gitlab_version, hostname=platform.node(), ...
def create_task(current_gitlab_version, most_recent_gitlab_version, last_reminder):
api = todoist.TodoistAPI(TODOIST_TOKEN) text = MESSAGE_TEMPLATE.format( most_recent_gitlab_version=most_recent_gitlab_version, current_gitlab_version=current_gitlab_version, hostname=platform.node(), ) if last_reminder["last_id"]: last_item = api.items.get_by_id(last_remi...
.run(["sudo", "/usr/local/bin/gitlab-version"], stdout = subprocess.PIPE) print(result) result_stdout = result.stdout.decode("utf8").strip() version = result_stdout.split(":")[1] return version def create_task(current_gitlab_version, most_recent_gitlab_version, last_reminder):
66
66
221
18
47
sn0cr/docker-upgrade-check
check_for_upgrade.py
Python
create_task
create_task
66
88
66
66
8a646181a83b6b12636557c0432c3699597ffd87
bigcode/the-stack
train
2c6e37ebdd431f427ec8ed4d
train
function
def get_last_reminder(): if REMINDER_LOCATION.exists(): with REMINDER_LOCATION.open(mode="r") as reminder_file: reminder = json.load(reminder_file) reminder["last_checked"] = datetime.fromisoformat(reminder["last_checked"]) return reminder else: return {"last_chec...
def get_last_reminder():
if REMINDER_LOCATION.exists(): with REMINDER_LOCATION.open(mode="r") as reminder_file: reminder = json.load(reminder_file) reminder["last_checked"] = datetime.fromisoformat(reminder["last_checked"]) return reminder else: return {"last_checked": None, "last_version...
= """Upgrade Gitlab on {hostname} from {current_gitlab_version} to {most_recent_gitlab_version}""" TODOIST_DUE = "today" TODOIST_PROJECT_ID = os.getenv("TODOIST_PROJECT_ID") TODOIST_TOKEN = os.getenv("TODOIST_API_TOKEN") def get_last_reminder():
64
64
80
6
58
sn0cr/docker-upgrade-check
check_for_upgrade.py
Python
get_last_reminder
get_last_reminder
42
49
42
42
d1b71589cd369e6cec3b141ad9753ddd20ce8fec
bigcode/the-stack
train
8f26de8da51342c3a073c64e
train
function
def save_last_reminder(reminder): reminder['last_checked'] = reminder['last_checked'].isoformat() with REMINDER_LOCATION.open(mode="w") as reminder_file: json.dump(reminder, reminder_file)
def save_last_reminder(reminder):
reminder['last_checked'] = reminder['last_checked'].isoformat() with REMINDER_LOCATION.open(mode="w") as reminder_file: json.dump(reminder, reminder_file)
reminder_file: reminder = json.load(reminder_file) reminder["last_checked"] = datetime.fromisoformat(reminder["last_checked"]) return reminder else: return {"last_checked": None, "last_version": None, "last_id": None} def save_last_reminder(reminder):
64
64
46
8
56
sn0cr/docker-upgrade-check
check_for_upgrade.py
Python
save_last_reminder
save_last_reminder
52
55
52
52
7a8fcaebf06d76cea584601393d3d591a94b3373
bigcode/the-stack
train
1ff0254a059cf3a3a401b1b4
train
function
def get_gitlab_version(): result = subprocess.run(["sudo", "/usr/local/bin/gitlab-version"], stdout = subprocess.PIPE) print(result) result_stdout = result.stdout.decode("utf8").strip() version = result_stdout.split(":")[1] return version
def get_gitlab_version():
result = subprocess.run(["sudo", "/usr/local/bin/gitlab-version"], stdout = subprocess.PIPE) print(result) result_stdout = result.stdout.decode("utf8").strip() version = result_stdout.split(":")[1] return version
"last_version": None, "last_id": None} def save_last_reminder(reminder): reminder['last_checked'] = reminder['last_checked'].isoformat() with REMINDER_LOCATION.open(mode="w") as reminder_file: json.dump(reminder, reminder_file) def get_gitlab_version():
64
64
58
6
58
sn0cr/docker-upgrade-check
check_for_upgrade.py
Python
get_gitlab_version
get_gitlab_version
58
63
58
58
c657c78bfffbfb95e2e1942b7103f3add1e0ddfb
bigcode/the-stack
train
f085c20608a82ca70dd06d96
train
function
@logresult @encode_result_or_exception @logargs def run_rf_lint(host, port, project_location_path, excluded_paths, filepath, additional_arguments): global INTERPRETER_PATH import subprocess import os try: import rflint import rflint_integration except Exception as e: rai...
@logresult @encode_result_or_exception @logargs def run_rf_lint(host, port, project_location_path, excluded_paths, filepath, additional_arguments):
global INTERPRETER_PATH import subprocess import os try: import rflint import rflint_integration except Exception as e: raise RuntimeError('There is no rflint module installed for ' + INTERPRETER_PATH + ' interpreter') command = [INTERPRETER_PATH] command.ap...
rflint module installed for ' + INTERPRETER_PATH + ' interpreter') return rflint_integration.get_rules(rulesfiles) @logresult @encode_result_or_exception @logargs def run_rf_lint(host, port, project_location_path, excluded_paths, filepath, additional_arguments):
65
65
218
35
30
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
run_rf_lint
run_rf_lint
300
326
300
303
0f99d7284c0732c1b2b90f72296af3873bf0a42a
bigcode/the-stack
train
7e9e338e0c3d04f63d50060a
train
function
@logresult @encode_result_or_exception @logargs def get_modules_search_paths(): import red_modules return red_modules.get_modules_search_paths()
@logresult @encode_result_or_exception @logargs def get_modules_search_paths():
import red_modules return red_modules.get_modules_search_paths()
logresult @encode_result_or_exception @logargs def check_server_availability(interpreter_path): global INTERPRETER_PATH if interpreter_path != '': INTERPRETER_PATH = interpreter_path @logresult @encode_result_or_exception @logargs def get_modules_search_paths():
64
64
34
20
43
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_modules_search_paths
get_modules_search_paths
156
161
156
159
cf91b30d72929028229ecfa8a137808b2b62624e
bigcode/the-stack
train
d350aa3f14c33f2c6c61f4e0
train
function
@logresult @encode_result_or_exception @logargs def start_keyword_auto_discovering(port, data_source_path, support_gevent, python_paths, class_paths): import subprocess import os global INTERPRETER_PATH command = [INTERPRETER_PATH] command.append(os.path.join(os.path.dirname(os.path.realpath(_...
@logresult @encode_result_or_exception @logargs def start_keyword_auto_discovering(port, data_source_path, support_gevent, python_paths, class_paths):
import subprocess import os global INTERPRETER_PATH command = [INTERPRETER_PATH] command.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'red_keyword_autodiscover.py')) command.append(str(port)) command.append(__encode_unicode_if_needed(data_source_path)) command.a...
_if_needed(python_paths + class_paths))) RED_DRYRUN_PROCESSES.append(subprocess.Popen(command, stdin=subprocess.PIPE)) @logresult @encode_result_or_exception @logargs def start_keyword_auto_discovering(port, data_source_path, support_gevent, python_paths, class_paths):
64
64
149
37
27
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
start_keyword_auto_discovering
start_keyword_auto_discovering
260
276
260
263
d400e3d1bcbdc7cf1910b89513056621a735ff57
bigcode/the-stack
train
f9206e2bb74d8b5323f025dc
train
function
def __encode_unicode_if_needed(s): if sys.version_info < (3, 0, 0) and isinstance(s, unicode): return s.encode('utf-8') elif sys.version_info < (3, 0, 0) and isinstance(s, list): return [__encode_unicode_if_needed(elem) for elem in s] else: return s
def __encode_unicode_if_needed(s):
if sys.version_info < (3, 0, 0) and isinstance(s, unicode): return s.encode('utf-8') elif sys.version_info < (3, 0, 0) and isinstance(s, list): return [__encode_unicode_if_needed(elem) for elem in s] else: return s
red_libraries return red_libraries.create_html_doc(doc, format) def __get_robot_version(): try: import robot except ImportError: return None from robot import version return 'Robot Framework ' + version.get_full_version() def __encode_unicode_if_needed(s):
64
64
81
8
56
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__encode_unicode_if_needed
__encode_unicode_if_needed
422
428
422
422
0bcbfc5c315d8c5d7816774098fd0dadc3814215
bigcode/the-stack
train
8ed76151290e480004eddfc8
train
function
def __get_script_path(): is_py2 = sys.version_info < (3, 0, 0) is_tty = sys.stdout.isatty() decoded = __file__.decode(sys.getfilesystemencoding()) if is_py2 else __file__ encoded = decoded.encode(sys.stdout.encoding if is_tty else 'utf-8') return encoded if is_py2 else str(encoded, 'utf-8')
def __get_script_path():
is_py2 = sys.version_info < (3, 0, 0) is_tty = sys.stdout.isatty() decoded = __file__.decode(sys.getfilesystemencoding()) if is_py2 else __file__ encoded = decoded.encode(sys.stdout.encoding if is_tty else 'utf-8') return encoded if is_py2 else str(encoded, 'utf-8')
script shouldn't write anything to the input, so this function will # be blocked until parent process will be closed/killed; this will cause readline() # to read EOF and hence proceed to server.shutdown() which will terminate whole script sys.stdin.readline() server.shutdown() def __get_script_path():
64
64
90
6
58
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__get_script_path
__get_script_path
459
465
459
459
ca6bc32579be5f151dd0f9641ec42fa0a95cb368
bigcode/the-stack
train
765f3a0b49e6e80a52ba1621
train
function
def __shutdown_server_when_parent_process_becomes_unavailable(server): # this causes the function to block on readline() call; parent process which # started this script shouldn't write anything to the input, so this function will # be blocked until parent process will be closed/killed; this will cause read...
def __shutdown_server_when_parent_process_becomes_unavailable(server): # this causes the function to block on readline() call; parent process which # started this script shouldn't write anything to the input, so this function will # be blocked until parent process will be closed/killed; this will cause read...
sys.stdin.readline() server.shutdown()
def __shutdown_server_when_parent_process_becomes_unavailable(server): # this causes the function to block on readline() call; parent process which # started this script shouldn't write anything to the input, so this function will # be blocked until parent process will be closed/killed; this will cause read...
83
64
92
83
0
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__shutdown_server_when_parent_process_becomes_unavailable
__shutdown_server_when_parent_process_becomes_unavailable
450
456
450
454
d64d2549f39f5ffcfd8f8db953e3854f502eeaed
bigcode/the-stack
train
c6397c609d528926e96bd92e
train
function
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def create_libdoc_in_separate_process(libname, format, python_paths, class_paths, timeout_duration=30): import os import subprocess import threading import time try: import Queue as queue except: i...
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def create_libdoc_in_separate_process(libname, format, python_paths, class_paths, timeout_duration=30):
import os import subprocess import threading import time try: import Queue as queue except: import queue global INTERPRETER_PATH command = [INTERPRETER_PATH] command.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'red_libraries.py')) co...
_or_exception @cleanup_modules @cleanup_sys_path @logargs def create_libdoc(libname, format, python_paths, class_paths): import red_libraries __extend_paths(python_paths, class_paths) return red_libraries.create_libdoc(libname, format) @logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_pat...
108
108
363
47
61
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
create_libdoc_in_separate_process
create_libdoc_in_separate_process
355
402
355
360
9eabeafebbabeaf5a9e8e076da476bd3daaab5e8
bigcode/the-stack
train
275917d6eeab0edf05f65af6
train
function
@logresult @encode_result_or_exception @cleanup_sys_path @logargs def get_module_path(module_name, python_paths, class_paths): import red_modules __extend_paths(python_paths, class_paths) return red_modules.get_module_path(module_name)
@logresult @encode_result_or_exception @cleanup_sys_path @logargs def get_module_path(module_name, python_paths, class_paths):
import red_modules __extend_paths(python_paths, class_paths) return red_modules.get_module_path(module_name)
result @encode_result_or_exception @logargs def get_modules_search_paths(): import red_modules return red_modules.get_modules_search_paths() @logresult @encode_result_or_exception @cleanup_sys_path @logargs def get_module_path(module_name, python_paths, class_paths):
64
64
58
32
32
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_module_path
get_module_path
164
171
164
168
ff4b4bd66ecce4d18f53d9aac547b839c0640290
bigcode/the-stack
train
7f205189cd133405d93a167a
train
function
@logresult @encode_result_or_exception @logargs def start_library_auto_discovering(port, data_source_path, project_location_path, support_gevent, recursiveInVirtualenv, excluded_paths, python_paths, class_paths): import subprocess import os global INTERPRETER_PATH ...
@logresult @encode_result_or_exception @logargs def start_library_auto_discovering(port, data_source_path, project_location_path, support_gevent, recursiveInVirtualenv, excluded_paths, python_paths, class_paths):
import subprocess import os global INTERPRETER_PATH command = [INTERPRETER_PATH] command.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'red_library_autodiscover.py')) command.append(str(port)) command.append(__encode_unicode_if_needed(data_source_path)) comma...
args def get_robot_version(): return __get_robot_version() @logresult @encode_result_or_exception @logargs def start_library_auto_discovering(port, data_source_path, project_location_path, support_gevent, recursiveInVirtualenv, excluded_paths, python_paths, class_paths):
64
64
210
50
14
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
start_library_auto_discovering
start_library_auto_discovering
235
257
235
239
7f9a289784900e7fdc4dfa86e370cd044b95f20d
bigcode/the-stack
train
a57424b0891e142a9417fe90
train
function
def cleanup_sys_path(to_call): def inner(*args, **kwargs): old_sys_path = list(sys.path) try: return to_call(*args, **kwargs) except: raise finally: sys.path = old_sys_path return inner
def cleanup_sys_path(to_call):
def inner(*args, **kwargs): old_sys_path = list(sys.path) try: return to_call(*args, **kwargs) except: raise finally: sys.path = old_sys_path return inner
erved(module_name, modules_to_preserve): for to_preserve in modules_to_preserve: if module_name == to_preserve or module_name.startswith(to_preserve + '.'): return True return False # decorator which cleans system path changed during decorated call def cleanup_sys_path(to_call):
64
64
59
7
56
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
cleanup_sys_path
cleanup_sys_path
132
144
132
133
1e720a513015d276e1ab9844416a4eea95ffd072
bigcode/the-stack
train
33537c360119bfd39f7ffe62
train
function
@logresult @encode_result_or_exception @logargs def get_standard_libraries_names(): import red_libraries return red_libraries.get_standard_library_names()
@logresult @encode_result_or_exception @logargs def get_standard_libraries_names():
import red_libraries return red_libraries.get_standard_library_names()
[]) return red_variables.get_variables(path, args) @logresult @encode_result_or_exception @logargs def get_global_variables(): import red_variables return red_variables.get_global_variables() @logresult @encode_result_or_exception @logargs def get_standard_libraries_names():
64
64
37
21
43
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_standard_libraries_names
get_standard_libraries_names
204
209
204
207
33635f3c8cea5003e397c1fd14843983091370fb
bigcode/the-stack
train
15932f2c74bf0c648c91a67a
train
function
def logargs(func): def inner(*args, **kwargs): try: if args == None or len(args) == 0: STD_LOGGER.info('calling \'%s\' function, no arguments', func.__name__) else: STD_LOGGER.info('calling \'%s\' function, supplied arguments:', func.__name__) ...
def logargs(func):
def inner(*args, **kwargs): try: if args == None or len(args) == 0: STD_LOGGER.info('calling \'%s\' function, no arguments', func.__name__) else: STD_LOGGER.info('calling \'%s\' function, supplied arguments:', func.__name__) for arg in ...
('^.+Error: ', line): if exception_found: exception_id = i break else: exception_found = True exception_id = exception_id if exception_id > -1 else 0 return '\n'.join(lines[exception_id:]) def logargs(func):
63
64
103
5
59
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
logargs
logargs
67
80
67
68
fac0d798fd335099587189737f6eaa90c497412c
bigcode/the-stack
train
a9f7761a394f84618cee4cde
train
function
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def get_variables(path, args, python_paths): import red_variables __extend_paths(python_paths, []) return red_variables.get_variables(path, args)
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def get_variables(path, args, python_paths):
import red_variables __extend_paths(python_paths, []) return red_variables.get_variables(path, args)
_paths): import red_module_classes __extend_paths(python_paths, class_paths) return red_module_classes.get_classes_from_module(module_location) @logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def get_variables(path, args, python_paths):
64
64
57
33
31
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_variables
get_variables
185
193
185
190
1606996e89550df754b863384107bee76960d93d
bigcode/the-stack
train
d28902298ca60001809fd0f0
train
function
def __get_robot_version(): try: import robot except ImportError: return None from robot import version return 'Robot Framework ' + version.get_full_version()
def __get_robot_version():
try: import robot except ImportError: return None from robot import version return 'Robot Framework ' + version.get_full_version()
: process.kill() raise queue.Empty('Libdoc not generated due to timeout') @logresult @encode_result_or_exception @logargs def create_html_doc(doc, format): import red_libraries return red_libraries.create_html_doc(doc, format) def __get_robot_version():
64
64
40
6
58
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__get_robot_version
__get_robot_version
413
419
413
413
84f9781bdb5bf202f000c567ca6173a043734cba
bigcode/the-stack
train
20b3a7ed89a3900429c14976
train
function
@logresult @encode_result_or_exception @logargs def check_server_availability(interpreter_path): global INTERPRETER_PATH if interpreter_path != '': INTERPRETER_PATH = interpreter_path
@logresult @encode_result_or_exception @logargs def check_server_availability(interpreter_path):
global INTERPRETER_PATH if interpreter_path != '': INTERPRETER_PATH = interpreter_path
_sys_path = list(sys.path) try: return to_call(*args, **kwargs) except: raise finally: sys.path = old_sys_path return inner @logresult @encode_result_or_exception @logargs def check_server_availability(interpreter_path):
64
64
45
23
40
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
check_server_availability
check_server_availability
147
153
147
150
ca630a94b5efbd8a671f10f22feaa4f83f395f5c
bigcode/the-stack
train
ef7e6048e8b43dff0cad0a26
train
function
@logresult @encode_result_or_exception @logargs def get_robot_version(): return __get_robot_version()
@logresult @encode_result_or_exception @logargs def get_robot_version():
return __get_robot_version()
_library_path(libname) @logresult @encode_result_or_exception @logargs def get_site_packages_libraries_names(): import red_libraries return red_libraries.get_site_packages_libraries_names() @logresult @encode_result_or_exception @logargs def get_robot_version():
64
64
26
19
45
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_robot_version
get_robot_version
228
232
228
231
0811019b36e5aad8831c097248bbf0270a9d1baa
bigcode/the-stack
train
c77ae9b8b6475668e16650a7
train
function
@logresult @encode_result_or_exception @cleanup_modules @logargs def get_rf_lint_rules(rulesfiles): try: import rflint import rflint_integration except Exception as e: raise RuntimeError('There is no rflint module installed for ' + INTERPRETER_PATH + ' interpreter') return rflin...
@logresult @encode_result_or_exception @cleanup_modules @logargs def get_rf_lint_rules(rulesfiles):
try: import rflint import rflint_integration except Exception as e: raise RuntimeError('There is no rflint module installed for ' + INTERPRETER_PATH + ' interpreter') return rflint_integration.get_rules(rulesfiles)
args def stop_auto_discovering(): for process in RED_DRYRUN_PROCESSES: process.kill() del RED_DRYRUN_PROCESSES[:] @logresult @encode_result_or_exception @cleanup_modules @logargs def get_rf_lint_rules(rulesfiles):
64
64
89
28
35
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_rf_lint_rules
get_rf_lint_rules
287
298
287
291
88143eda0e529979d4af32c6e0c7da44e891161b
bigcode/the-stack
train
67e7836c5c1e014315947fcc
train
function
def __extend_paths(python_paths, class_paths): from robot import pythonpathsetter __extend_classpath(class_paths) for path in python_paths + class_paths: pythonpathsetter.add_path(path)
def __extend_paths(python_paths, class_paths):
from robot import pythonpathsetter __extend_classpath(class_paths) for path in python_paths + class_paths: pythonpathsetter.add_path(path)
): return s.encode('utf-8') elif sys.version_info < (3, 0, 0) and isinstance(s, list): return [__encode_unicode_if_needed(elem) for elem in s] else: return s def __extend_paths(python_paths, class_paths):
64
64
45
11
52
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__extend_paths
__extend_paths
431
437
431
431
4bafe531dc735cf930027de5e8a1eccb5b266498
bigcode/the-stack
train
043ff0f4f425d79af86a088f
train
function
@logresult @encode_result_or_exception @logargs def create_html_doc(doc, format): import red_libraries return red_libraries.create_html_doc(doc, format)
@logresult @encode_result_or_exception @logargs def create_html_doc(doc, format):
import red_libraries return red_libraries.create_html_doc(doc, format)
Libdoc >')) else: raise Exception(err.decode('UTF-8', 'replace')) except queue.Empty: process.kill() raise queue.Empty('Libdoc not generated due to timeout') @logresult @encode_result_or_exception @logargs def create_html_doc(doc, format):
64
64
40
22
42
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
create_html_doc
create_html_doc
405
410
405
408
aa511ef629f2a7902ab34b47a1c568cc0c25a71d
bigcode/the-stack
train
6d8bcb3a24316fe8dbd7b9a7
train
function
def logresult(func): def inner(*args, **kwargs): ret = func(*args, **kwargs) try: if ret['exception']: STD_LOGGER.info('call ended with exception, see stderr for details') else: STD_LOGGER.info('call ended with result:') STD_AR...
def logresult(func):
def inner(*args, **kwargs): ret = func(*args, **kwargs) try: if ret['exception']: STD_LOGGER.info('call ended with exception, see stderr for details') else: STD_LOGGER.info('call ended with result:') STD_ARGS_LOGGER.info(ret['re...
arguments', func.__name__) else: STD_LOGGER.info('calling \'%s\' function, supplied arguments:', func.__name__) for arg in args: STD_ARGS_LOGGER.info(arg) finally: return func(*args, **kwargs) return inner def logresult(func):
64
64
84
5
58
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
logresult
logresult
83
96
83
84
db2ba2db575b47049119f9267d3ca9851c8fbd74
bigcode/the-stack
train
58beadbbcfc832d7cb4029ec
train
function
def __cut_unimportant_red_exception(lines): exception_id = -1 exception_found = False for i, line in list(enumerate(lines)): if line.startswith('Exception: ') or re.search('^.+Error: ', line): if exception_found: exception_id = i break else: ...
def __cut_unimportant_red_exception(lines):
exception_id = -1 exception_found = False for i, line in list(enumerate(lines)): if line.startswith('Exception: ') or re.search('^.+Error: ', line): if exception_found: exception_id = i break else: exception_found = True exc...
return result except Exception as e: formatted_lines = traceback.format_exc().splitlines() msg = __cut_unimportant_red_exception(formatted_lines) result['exception'] = msg ERR_LOGGER.exception('') return result return inner def __cut_unimportant_...
64
64
103
9
54
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__cut_unimportant_red_exception
__cut_unimportant_red_exception
54
65
54
54
7dce30b57bd2900a8910d6342f1e65ef4de9f123
bigcode/the-stack
train
cd8b04177044b20e4943adc5
train
function
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def get_classes_from_module(module_location, python_paths, class_paths): import red_module_classes __extend_paths(python_paths, class_paths) return red_module_classes.get_classes_from_module(module_location)
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def get_classes_from_module(module_location, python_paths, class_paths):
import red_module_classes __extend_paths(python_paths, class_paths) return red_module_classes.get_classes_from_module(module_location)
): import red_modules __extend_paths(python_paths, class_paths) return red_modules.get_module_path(module_name) @logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def get_classes_from_module(module_location, python_paths, class_paths):
64
64
66
37
27
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_classes_from_module
get_classes_from_module
174
182
174
179
9ff99d7e29e3d6a308ee9188a09d3fa6f091d1ab
bigcode/the-stack
train
e11f5c3cccf5abab08d5eefe
train
function
def cleanup_modules(to_call): def inner(*args, **kwargs): old_modules = sys.modules.copy() try: return to_call(*args, **kwargs) except: raise finally: current_modules = sys.modules builtin_modules = set(sys.builtin_module_names) ...
def cleanup_modules(to_call):
def inner(*args, **kwargs): old_modules = sys.modules.copy() try: return to_call(*args, **kwargs) except: raise finally: current_modules = sys.modules builtin_modules = set(sys.builtin_module_names) to_preserve_with_submodul...
ended with exception, see stderr for details') else: STD_LOGGER.info('call ended with result:') STD_ARGS_LOGGER.info(ret['result']) finally: return ret return inner # decorator which cleans up all modules that were loaded during decorated call def ...
64
64
177
6
57
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
cleanup_modules
cleanup_modules
100
121
100
101
c6a13331a0049d329ba4a18eb807d24b78eb590c
bigcode/the-stack
train
468d83c8b6f8cf40b2e96fe6
train
function
def encode_result_or_exception(func): import traceback def inner(*args, **kwargs): result = {'result': None, 'exception': None} try: result['result'] = func(*args, **kwargs) return result except Exception as e: formatted_lines = traceback.format_exc()...
def encode_result_or_exception(func):
import traceback def inner(*args, **kwargs): result = {'result': None, 'exception': None} try: result['result'] = func(*args, **kwargs) return result except Exception as e: formatted_lines = traceback.format_exc().splitlines() msg = __cut_...
> %(message)s')) STD_ARGS_LOGGER = logging.getLogger(__name__ + '_args') STD_ARGS_LOGGER.setLevel(logging.INFO) STD_ARGS_LOGGER.addHandler(args_handler) RED_DRYRUN_PROCESSES = [] INTERPRETER_PATH = sys.executable def encode_result_or_exception(func):
64
64
105
7
56
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
encode_result_or_exception
encode_result_or_exception
37
52
37
37
6dc5c34aa44680c5fa5da1b9f96a6c2b7e5c1289
bigcode/the-stack
train
e11504b71f175b142720d8c1
train
function
@logresult @encode_result_or_exception @logargs def convert_robot_data_file(original_filepath): from robot.tidy import Tidy from base64 import b64encode converted_content = Tidy(format='robot').file(original_filepath) if sys.version_info < (3, 0, 0): return b64encode(converted_content.encode('...
@logresult @encode_result_or_exception @logargs def convert_robot_data_file(original_filepath):
from robot.tidy import Tidy from base64 import b64encode converted_content = Tidy(format='robot').file(original_filepath) if sys.version_info < (3, 0, 0): return b64encode(converted_content.encode('utf-8')) else: return str(b64encode(bytes(converted_content, 'utf-8')), 'utf-8')
_needed(excluded_paths))) command.extend(__encode_unicode_if_needed(additional_arguments)) command.append('-r') command.append(__encode_unicode_if_needed(filepath)) subprocess.Popen(command, stdin=subprocess.PIPE) @logresult @encode_result_or_exception @logargs def convert_robot_data_file(original_file...
64
64
107
22
42
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
convert_robot_data_file
convert_robot_data_file
329
341
329
332
91171185dcba798c4f627034fc06f2dffa3d6378
bigcode/the-stack
train
534ff12993f5dcbe6997d9c1
train
function
@logresult @encode_result_or_exception @logargs def stop_auto_discovering(): for process in RED_DRYRUN_PROCESSES: process.kill() del RED_DRYRUN_PROCESSES[:]
@logresult @encode_result_or_exception @logargs def stop_auto_discovering():
for process in RED_DRYRUN_PROCESSES: process.kill() del RED_DRYRUN_PROCESSES[:]
.append(str(support_gevent)) command.append(';'.join(__encode_unicode_if_needed(python_paths + class_paths))) RED_DRYRUN_PROCESSES.append(subprocess.Popen(command, stdin=subprocess.PIPE)) @logresult @encode_result_or_exception @logargs def stop_auto_discovering():
64
64
48
21
43
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
stop_auto_discovering
stop_auto_discovering
279
285
279
282
13331f55a4080a44c82db11253f83691a2a37200
bigcode/the-stack
train
454712e6bf61bab0c394c869
train
function
@logresult @encode_result_or_exception @logargs def get_standard_library_path(libname): import red_libraries return red_libraries.get_standard_library_path(libname)
@logresult @encode_result_or_exception @logargs def get_standard_library_path(libname):
import red_libraries return red_libraries.get_standard_library_path(libname)
_variables.get_global_variables() @logresult @encode_result_or_exception @logargs def get_standard_libraries_names(): import red_libraries return red_libraries.get_standard_library_names() @logresult @encode_result_or_exception @logargs def get_standard_library_path(libname):
64
64
40
22
42
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_standard_library_path
get_standard_library_path
212
217
212
215
e5291bc56d7522f6f9e98bb81eabae3bb7112353
bigcode/the-stack
train
7cef4560fa7e529f4362e2db
train
function
def __extend_classpath(class_paths): import platform if 'Jython' in platform.python_implementation(): for class_path in class_paths: from classpath_updater import ClassPathUpdater cp_updater = ClassPathUpdater() cp_updater.add_file(class_path)
def __extend_classpath(class_paths):
import platform if 'Jython' in platform.python_implementation(): for class_path in class_paths: from classpath_updater import ClassPathUpdater cp_updater = ClassPathUpdater() cp_updater.add_file(class_path)
elem in s] else: return s def __extend_paths(python_paths, class_paths): from robot import pythonpathsetter __extend_classpath(class_paths) for path in python_paths + class_paths: pythonpathsetter.add_path(path) def __extend_classpath(class_paths):
64
64
61
8
56
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__extend_classpath
__extend_classpath
440
447
440
440
d87df5eaae2a0f2b8acb5c3acd843036193f19b8
bigcode/the-stack
train
6fb7fb9695e43a47134f279d
train
function
@logresult @encode_result_or_exception @logargs def get_global_variables(): import red_variables return red_variables.get_global_variables()
@logresult @encode_result_or_exception @logargs def get_global_variables():
import red_variables return red_variables.get_global_variables()
_modules @cleanup_sys_path @logargs def get_variables(path, args, python_paths): import red_variables __extend_paths(python_paths, []) return red_variables.get_variables(path, args) @logresult @encode_result_or_exception @logargs def get_global_variables():
64
64
32
19
45
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_global_variables
get_global_variables
196
201
196
199
aea944ca48feca414c9c522ad66fc7e91c4a8213
bigcode/the-stack
train
8fc477da2140e245b2e09d49
train
function
def __has_to_be_preserved(module_name, modules_to_preserve): for to_preserve in modules_to_preserve: if module_name == to_preserve or module_name.startswith(to_preserve + '.'): return True return False
def __has_to_be_preserved(module_name, modules_to_preserve):
for to_preserve in modules_to_preserve: if module_name == to_preserve or module_name.startswith(to_preserve + '.'): return True return False
, to_preserve_with_submodules) and not (m in old_modules and old_modules[m] is current_modules[m])] for m in to_remove: del sys.modules[m] del m return inner def __has_to_be_preserved(module_name, modules_to_preserve):
64
64
52
15
48
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
__has_to_be_preserved
__has_to_be_preserved
124
128
124
124
89eb596366c4d7db4b382f1b699e1d8d58e478b7
bigcode/the-stack
train
d277d83d54e0f83c578ccdb5
train
function
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def create_libdoc(libname, format, python_paths, class_paths): import red_libraries __extend_paths(python_paths, class_paths) return red_libraries.create_libdoc(libname, format)
@logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def create_libdoc(libname, format, python_paths, class_paths):
import red_libraries __extend_paths(python_paths, class_paths) return red_libraries.create_libdoc(libname, format)
8')) else: return str(b64encode(bytes(converted_content, 'utf-8')), 'utf-8') @logresult @encode_result_or_exception @cleanup_modules @cleanup_sys_path @logargs def create_libdoc(libname, format, python_paths, class_paths):
64
64
68
38
26
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
create_libdoc
create_libdoc
344
352
344
349
532abe6d2d0954a0179e0a983104695846bdc978
bigcode/the-stack
train
eb4ad11c8b7a34184908a8fc
train
function
@logresult @encode_result_or_exception @logargs def get_site_packages_libraries_names(): import red_libraries return red_libraries.get_site_packages_libraries_names()
@logresult @encode_result_or_exception @logargs def get_site_packages_libraries_names():
import red_libraries return red_libraries.get_site_packages_libraries_names()
_names() @logresult @encode_result_or_exception @logargs def get_standard_library_path(libname): import red_libraries return red_libraries.get_standard_library_path(libname) @logresult @encode_result_or_exception @logargs def get_site_packages_libraries_names():
64
64
40
22
42
puraner/RED
src/RobotFrameworkCore/org.robotframework.ide.core-functions/src/main/python/scripts/robot_session_server.py
Python
get_site_packages_libraries_names
get_site_packages_libraries_names
220
225
220
223
2fab199de13324026cdd41035b59b25d322e9142
bigcode/the-stack
train
8aff65f303af85c25f66e852
train
function
def log(*args, **kwargs): if DEBUG_PARTICIPANT_AUTHENTICATION: print(*args, **kwargs)
def log(*args, **kwargs):
if DEBUG_PARTICIPANT_AUTHENTICATION: print(*args, **kwargs)
import functools from django.http.request import HttpRequest from database.user_models import Participant from libs.internal_types import ParticipantRequest from middleware.abort_middleware import abort DEBUG_PARTICIPANT_AUTHENTICATION = False def log(*args, **kwargs):
53
64
27
8
44
jhalljhall/beiwe-backend
authentication/participant_authentication.py
Python
log
log
13
15
13
13
e908b1ff77af989297167ffbeb55650f960bf54d
bigcode/the-stack
train
939c7d733032fa21743f85be
train
function
def authenticate_participant_registration(some_function) -> callable: """ Decorator for functions (pages) that require a user to provide identification. Returns 403 (forbidden) or 401 (depending on beiwe-api-version) if the identifying info (username, password, device ID) are invalid. In any funct...
def authenticate_participant_registration(some_function) -> callable:
""" Decorator for functions (pages) that require a user to provide identification. Returns 403 (forbidden) or 401 (depending on beiwe-api-version) if the identifying info (username, password, device ID) are invalid. In any function wrapped with this decorator provide a parameter named "patient_id" ...
if validate_post(request, require_password=True, validate_device_id=True): return some_function(*args, **kwargs) is_ios = kwargs.get("OS_API", None) == Participant.IOS_API return abort(401 if is_ios else 403) return authenticate_and_call def authenticate_participant_registrat...
73
73
246
12
60
jhalljhall/beiwe-backend
authentication/participant_authentication.py
Python
authenticate_participant_registration
authenticate_participant_registration
96
116
96
96
ac82f4779a176c8fbfbb255131497cde239392a1
bigcode/the-stack
train
1909697be0b09c0aa3b1ca84
train
function
def correct_for_basic_auth(request: ParticipantRequest): """ Basic auth is used in IOS. If basic authentication exists and is in the correct format, move the patient_id, device_id, and password into request.values for processing by the existing user authentication functions. Flask auto...
def correct_for_basic_auth(request: ParticipantRequest):
""" Basic auth is used in IOS. If basic authentication exists and is in the correct format, move the patient_id, device_id, and password into request.values for processing by the existing user authentication functions. Flask automatically parses a Basic authentication header into reques...
Participant.IOS_API return abort(401 if is_ios else 403) return authenticate_and_call # TODO: basic auth is not a good thing, it is only used because it was easy and we enforce # https on all connections. Fundamentally we need a rewrite of the participant auth structure to # disconnect it from ...
93
93
312
10
83
jhalljhall/beiwe-backend
authentication/participant_authentication.py
Python
correct_for_basic_auth
correct_for_basic_auth
122
156
122
122
6f44a6edf32e4033df2d5b3aa570125774fe0ff5
bigcode/the-stack
train
ce6d9831bb59612a36211ddc
train
function
def minimal_validation(some_function) -> callable: @functools.wraps(some_function) def authenticate_and_call(*args, **kwargs): request: ParticipantRequest = args[0] assert isinstance(request, HttpRequest), \ f"first parameter of {some_function.__name__} must be an HttpRequest, w...
def minimal_validation(some_function) -> callable: @functools.wraps(some_function)
def authenticate_and_call(*args, **kwargs): request: ParticipantRequest = args[0] assert isinstance(request, HttpRequest), \ f"first parameter of {some_function.__name__} must be an HttpRequest, was {type(request)}." correct_for_basic_auth(request) if valid...
log("incorrect device_id") return False # attach session participant to request object, defining the ParticipantRequest class. request.session_participant = session_participant return True #############################################################################################...
63
64
154
21
42
jhalljhall/beiwe-backend
authentication/participant_authentication.py
Python
minimal_validation
minimal_validation
57
71
57
58
36757c80faf63bf4f746a7d91101c208e5acc278
bigcode/the-stack
train
d71b39ecd7e2ae48e62b1858
train
function
def validate_post(request: HttpRequest, require_password: bool, validate_device_id: bool) -> bool: """Check if user exists, check if the provided passwords match, and if the device id matches.""" # even if the password won't be checked we want the key to be present. rp = request.POST if "patient_id"...
def validate_post(request: HttpRequest, require_password: bool, validate_device_id: bool) -> bool:
"""Check if user exists, check if the provided passwords match, and if the device id matches.""" # even if the password won't be checked we want the key to be present. rp = request.POST if "patient_id" not in rp or "password" not in rp or "device_id" not in rp: log("missing parameters entire...
import functools from django.http.request import HttpRequest from database.user_models import Participant from libs.internal_types import ParticipantRequest from middleware.abort_middleware import abort DEBUG_PARTICIPANT_AUTHENTICATION = False def log(*args, **kwargs): if DEBUG_PARTICIPANT_AUTHEN...
94
108
362
22
72
jhalljhall/beiwe-backend
authentication/participant_authentication.py
Python
validate_post
validate_post
18
52
18
18
467b63e6ef1c08ac4e88b8530f882025fd84ad54
bigcode/the-stack
train
a1ba3e4c3ed8f8bbf2e1bc1b
train
function
def authenticate_participant(some_function) -> callable: """Decorator for functions (pages) that require a user to provide identification. Returns 403 (forbidden) or 401 (depending on beiwei-api-version) if the identifying info (usernames, passwords device IDs are invalid. In any funcion wrapped w...
def authenticate_participant(some_function) -> callable:
"""Decorator for functions (pages) that require a user to provide identification. Returns 403 (forbidden) or 401 (depending on beiwei-api-version) if the identifying info (usernames, passwords device IDs are invalid. In any funcion wrapped with this decorator provide a parameter named "patient_id" ...
(request, require_password=False, validate_device_id=False): return some_function(*args, **kwargs) # ios requires different http codes is_ios = kwargs.get("OS_API", None) == Participant.IOS_API return abort(401 if is_ios else 403) return authenticate_and_call def a...
77
77
257
11
65
jhalljhall/beiwe-backend
authentication/participant_authentication.py
Python
authenticate_participant
authenticate_participant
74
93
74
74
fc4803785b15f171a808394186346db5ca4a3f23
bigcode/the-stack
train
456009dec048030e85d187be
train
function
def get_pretrain_weights(flag, class_name, save_dir, backbone_name=None): if flag is None: return None elif osp.isdir(flag): return flag elif osp.isfile(flag): return flag # TODO: check flag new_save_dir = save_dir if backbone_name is not None: weights_key = "{}_...
def get_pretrain_weights(flag, class_name, save_dir, backbone_name=None):
if flag is None: return None elif osp.isdir(flag): return flag elif osp.isfile(flag): return flag # TODO: check flag new_save_dir = save_dir if backbone_name is not None: weights_key = "{}_{}_{}".format(class_name, backbone_name, flag) else: weights_k...
.pdparams', 'MaskRCNN_ResNet101_vd_fpn_COCO': 'https://paddledet.bj.bcebos.com/models/mask_rcnn_r101_vd_fpn_1x_coco.pdparams' } def get_pretrain_weights(flag, class_name, save_dir, backbone_name=None):
72
72
241
17
55
liyhc/PaddleX
dygraph/paddlex/utils/checkpoint.py
Python
get_pretrain_weights
get_pretrain_weights
346
374
346
346
1683c1d7525a62c42fcf24641d8dacccc86371f5
bigcode/the-stack
train
eef2cf69e842be852d116e48
train
function
def load_pretrain_weights(model, pretrain_weights=None, model_name=None): if pretrain_weights is not None: logging.info( 'Loading pretrained model from {}'.format(pretrain_weights), use_color=True) if os.path.exists(pretrain_weights): param_state_dict = paddle.lo...
def load_pretrain_weights(model, pretrain_weights=None, model_name=None):
if pretrain_weights is not None: logging.info( 'Loading pretrained model from {}'.format(pretrain_weights), use_color=True) if os.path.exists(pretrain_weights): param_state_dict = paddle.load(pretrain_weights) model_state_dict = model.state_dict() ...
url = imagenet_weights[weights_key] elif flag == 'PascalVOC': url = pascalvoc_weights[weights_key] elif flag == 'COCO': url = coco_weights[weights_key] else: raise ValueError('Given pretrained weights {} is undefined.'.format( flag)) fname = download_and_decompress(u...
123
123
412
16
106
liyhc/PaddleX
dygraph/paddlex/utils/checkpoint.py
Python
load_pretrain_weights
load_pretrain_weights
377
417
377
377
dc0b1ac95782c82cb33992e96944c61f4edfd4fc
bigcode/the-stack
train
6e4ab1d0102cbd15cb379087
train
function
def load_checkpoint(model, optimizer, model_name, checkpoint): logging.info("Loading checkpoint from {}".format(checkpoint)) load_pretrain_weights( model, pretrain_weights=osp.join(checkpoint, 'model.pdparams'), model_name=model_name) load_optimizer( optimizer, state_dict_pat...
def load_checkpoint(model, optimizer, model_name, checkpoint):
logging.info("Loading checkpoint from {}".format(checkpoint)) load_pretrain_weights( model, pretrain_weights=osp.join(checkpoint, 'model.pdparams'), model_name=model_name) load_optimizer( optimizer, state_dict_path=osp.join(checkpoint, "model.pdopt"))
.info("Loading optimizer from {}".format(state_dict_path)) optim_state_dict = paddle.load(state_dict_path) if 'last_epoch' in optim_state_dict: optim_state_dict.pop('last_epoch') optimizer.set_state_dict(optim_state_dict) def load_checkpoint(model, optimizer, model_name, checkpoint):
64
64
77
12
52
liyhc/PaddleX
dygraph/paddlex/utils/checkpoint.py
Python
load_checkpoint
load_checkpoint
428
435
428
428
316dc3013e5fc8bffdf3e0362b506d67b9b008c5
bigcode/the-stack
train
cb669bef653a102d81cb170c
train
function
def load_optimizer(optimizer, state_dict_path): logging.info("Loading optimizer from {}".format(state_dict_path)) optim_state_dict = paddle.load(state_dict_path) if 'last_epoch' in optim_state_dict: optim_state_dict.pop('last_epoch') optimizer.set_state_dict(optim_state_dict)
def load_optimizer(optimizer, state_dict_path):
logging.info("Loading optimizer from {}".format(state_dict_path)) optim_state_dict = paddle.load(state_dict_path) if 'last_epoch' in optim_state_dict: optim_state_dict.pop('last_epoch') optimizer.set_state_dict(optim_state_dict)
_name)) else: raise ValueError('The pretrained model directory is not Found: {}'. format(pretrain_weights)) else: logging.info( 'No pretrained model to load, {} will be trained from scratch.'. format(model_name)) def load_optimizer(opt...
64
64
64
10
54
liyhc/PaddleX
dygraph/paddlex/utils/checkpoint.py
Python
load_optimizer
load_optimizer
420
425
420
420
9b68da72642887d3f8493663ac0e5987397d62b1
bigcode/the-stack
train
606d32da85967d9b28ca245f
train
class
class PerlFileSharedirInstall(PerlPackage): """Install shared files""" homepage = "http://search.cpan.org/~ether/File-ShareDir-Install-0.11/lib/File/ShareDir/Install.pm" url = "http://search.cpan.org/CPAN/authors/id/E/ET/ETHER/File-ShareDir-Install-0.11.tar.gz" version('0.11', '61107e6ce6eee42bf2...
class PerlFileSharedirInstall(PerlPackage):
"""Install shared files""" homepage = "http://search.cpan.org/~ether/File-ShareDir-Install-0.11/lib/File/ShareDir/Install.pm" url = "http://search.cpan.org/CPAN/authors/id/E/ET/ETHER/File-ShareDir-Install-0.11.tar.gz" version('0.11', '61107e6ce6eee42bf29525b1a4d029e0') depends_on('perl-modul...
Copyright 2013-2019 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 PerlFileSharedirInstall(PerlPackage):
64
64
123
11
53
nkianggiss/spack
var/spack/repos/builtin/packages/perl-file-sharedir-install/package.py
Python
PerlFileSharedirInstall
PerlFileSharedirInstall
9
17
9
9
2ff92ab9f4851e2732fef43af99eda330908a353
bigcode/the-stack
train
1a887620ce2130b46620c6db
train
class
class openram_back_end_test(openram_test): def runTest(self): OPENRAM_HOME = os.path.abspath(os.environ.get("OPENRAM_HOME")) globals.init_openram("{0}/tests/config_{1}".format(OPENRAM_HOME,OPTS.tech_name)) debug.info(1, "Testing top-level back-end openram.py with 2-bit, 16 word SRAM.") ...
class openram_back_end_test(openram_test):
def runTest(self): OPENRAM_HOME = os.path.abspath(os.environ.get("OPENRAM_HOME")) globals.init_openram("{0}/tests/config_{1}".format(OPENRAM_HOME,OPTS.tech_name)) debug.info(1, "Testing top-level back-end openram.py with 2-bit, 16 word SRAM.") out_file = "testsram" out_path ...
#!/usr/bin/env python3 # See LICENSE for licensing information. # # Copyright (c) 2016-2019 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # import unittest from test...
125
218
728
10
114
mguthaus/OpenRAM
compiler/tests/30_openram_back_end_test.py
Python
openram_back_end_test
openram_back_end_test
19
94
19
20
e5735fe7d176a813c9bfcb8c85b2f0953f196754
bigcode/the-stack
train
86e74382b7f75d938c73b411
train
class
class TestReqRep(BaseZMQTestCase): def test_basic(self): s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP) msg1 = b'message 1' msg2 = self.ping_pong(s1, s2, msg1) self.assertEqual(msg1, msg2) def test_multiple(self): s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP) ...
class TestReqRep(BaseZMQTestCase):
def test_basic(self): s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP) msg1 = b'message 1' msg2 = self.ping_pong(s1, s2, msg1) self.assertEqual(msg1, msg2) def test_multiple(self): s1, s2 = self.create_bound_pair(zmq.REQ, zmq.REP) for i in range(10): ...
# Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. from unittest import TestCase import zmq from zmq.tests import BaseZMQTestCase, have_gevent, GreenTest class TestReqRep(BaseZMQTestCase):
59
150
500
10
48
ITCRStevenLPZ/Proyecto2-Analisis-de-Algoritmos
.venv/lib/python3.7/site-packages/zmq/tests/test_reqrep.py
Python
TestReqRep
TestReqRep
11
58
11
12
59c10ae09b643fc937582c3b8a62939d08318bb1
bigcode/the-stack
train
ae6630f0dae35aac1deb4e77
train
class
class DistributedSoftmax(DistributedOperatorImplContainer): def __init__(self, name): super(DistributedSoftmax, self).__init__() self._name = name
class DistributedSoftmax(DistributedOperatorImplContainer):
def __init__(self, name): super(DistributedSoftmax, self).__init__() self._name = name
_shard from ..utils import is_dim_replicate from ..utils import is_valid_list_index from ..utils import compute_compatible_dim_mapping from ..utils import compute_compatible_dims_mapping from ..utils import compute_compatible_and_update_dim_mapping class DistributedSoftmax(DistributedOperatorImplContainer):
64
64
37
10
53
Avin0323/Paddle
python/paddle/distributed/auto_parallel/operators/dist_softmax.py
Python
DistributedSoftmax
DistributedSoftmax
27
30
27
27
0f5a0a652389409b2779c2927d9ebd4b996258e5
bigcode/the-stack
train
cc2d8c5807eeda2953e8da11
train
class
class DistributedSoftmaxImpl(DistributedOperatorImpl): def __init__(self, name): super(DistributedSoftmaxImpl, self).__init__() self._name = name self._forward_implemented = False self._backward_implemented = True def is_input_compatible(self, dist_op): op_desc = dist_op...
class DistributedSoftmaxImpl(DistributedOperatorImpl):
def __init__(self, name): super(DistributedSoftmaxImpl, self).__init__() self._name = name self._forward_implemented = False self._backward_implemented = True def is_input_compatible(self, dist_op): op_desc = dist_op.serial_op.desc op_dist_attr = dist_op.dist_att...
governing permissions and # limitations under the License from .common import DistributedOperatorImplContainer from .common import DistributedOperatorImpl from .common import register_distributed_operator_impl_container from .common import register_distributed_operator_impl from ..utils import is_dim_shard from ..uti...
173
174
583
10
163
Avin0323/Paddle
python/paddle/distributed/auto_parallel/operators/dist_softmax.py
Python
DistributedSoftmaxImpl
DistributedSoftmaxImpl
37
112
37
37
cb8f464b52071ce39f276ee5f6d9abf1a75832a1
bigcode/the-stack
train
ae6506c8bb37c2c45e3697ec
train
class
class TitleSlugDescriptionModel(Document): """ TitleSlugDescriptionModel An abstract base class model that provides title and description fields and a self-managed "slug" field that populates from the title. """ title = StringField(max_length=255) slug = AutoSlugField(populate_from='title'...
class TitleSlugDescriptionModel(Document):
""" TitleSlugDescriptionModel An abstract base class model that provides title and description fields and a self-managed "slug" field that populates from the title. """ title = StringField(max_length=255) slug = AutoSlugField(populate_from='title') description = StringField(blank=True,...
Model(Document): """ TimeStampedModel An abstract base class model that provides self-managed "created" and "modified" fields. """ created = CreationDateTimeField() modified = ModificationDateTimeField() class Meta: abstract = True class TitleSlugDescriptionModel(Document):...
64
64
87
7
56
sainjusajan/django-oscar
oscar/lib/python2.7/site-packages/django_extensions/mongodb/models.py
Python
TitleSlugDescriptionModel
TitleSlugDescriptionModel
29
39
29
29
bc43b80887bd659f2bbb2eda191f2b33a479c04d
bigcode/the-stack
train