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
b43b0a5fe0bb0cd1605b27cc
train
class
class VehicleDetection0203TestCase( create_object_detection_test_case( model_name='vehicle-detection-0203', **kwargs ) ): """ Test case for vehicle-detection-0203 model. """
class VehicleDetection0203TestCase( create_object_detection_test_case( model_name='vehicle-detection-0203', **kwargs ) ):
""" Test case for vehicle-detection-0203 model. """
_name='vehicle-detection-0202', **kwargs ) ): """ Test case for vehicle-detection-0202 model. """ class VehicleDetection0203TestCase( create_object_detection_test_case( model_name='vehicle-detection-0203', **kwargs ) ):
63
64
47
33
30
dqawami/openvino_training_extensions
models/object_detection/tests/train_tests_vehicle_detection.py
Python
VehicleDetection0203TestCase
VehicleDetection0203TestCase
54
60
54
59
cd4bc8e382532d0a71baac241a613be64024ea9e
bigcode/the-stack
train
29fb445abde84f715d2bec04
train
class
class VehicleDetection0202TestCase( create_object_detection_test_case( model_name='vehicle-detection-0202', **kwargs ) ): """ Test case for vehicle-detection-0202 model. """
class VehicleDetection0202TestCase( create_object_detection_test_case( model_name='vehicle-detection-0202', **kwargs ) ):
""" Test case for vehicle-detection-0202 model. """
_name='vehicle-detection-0201', **kwargs ) ): """ Test case for vehicle-detection-0201 model. """ class VehicleDetection0202TestCase( create_object_detection_test_case( model_name='vehicle-detection-0202', **kwargs ) ):
63
64
47
33
30
dqawami/openvino_training_extensions
models/object_detection/tests/train_tests_vehicle_detection.py
Python
VehicleDetection0202TestCase
VehicleDetection0202TestCase
45
51
45
50
05fc34dba69b25e134094aca93675c5844ebee6a
bigcode/the-stack
train
644332feb0d19985ba61aab2
train
class
class VehicleDetection0201TestCase( create_object_detection_test_case( model_name='vehicle-detection-0201', **kwargs ) ): """ Test case for vehicle-detection-0201 model. """
class VehicleDetection0201TestCase( create_object_detection_test_case( model_name='vehicle-detection-0201', **kwargs ) ):
""" Test case for vehicle-detection-0201 model. """
_name='vehicle-detection-0200', **kwargs ) ): """ Test case for vehicle-detection-0200 model. """ class VehicleDetection0201TestCase( create_object_detection_test_case( model_name='vehicle-detection-0201', **kwargs ) ):
63
64
47
33
30
dqawami/openvino_training_extensions
models/object_detection/tests/train_tests_vehicle_detection.py
Python
VehicleDetection0201TestCase
VehicleDetection0201TestCase
36
42
36
41
137f184610c2721e67b370b4c5dd833fbb8c34e8
bigcode/the-stack
train
d421ee818e208b7746e8d8d5
train
class
class VehicleDetection0200TestCase( create_object_detection_test_case( model_name='vehicle-detection-0200', **kwargs ) ): """ Test case for vehicle-detection-0200 model. """
class VehicleDetection0200TestCase( create_object_detection_test_case( model_name='vehicle-detection-0200', **kwargs ) ):
""" Test case for vehicle-detection-0200 model. """
+ '/../../../data/vehicle_detection/annotation_train.json', img_root=os.path.dirname(__file__) + '/../../../data/vehicle_detection/train' ) class VehicleDetection0200TestCase( create_object_detection_test_case( model_name='vehicle-detection-0200', **kwargs ) ):
64
64
47
33
31
dqawami/openvino_training_extensions
models/object_detection/tests/train_tests_vehicle_detection.py
Python
VehicleDetection0200TestCase
VehicleDetection0200TestCase
27
33
27
32
2c18981aa44c084ec2f8a0a762f8f4f547ed630e
bigcode/the-stack
train
d1a63dee57c4770d88b06b27
train
class
class UserException(Function): def __init__(self): pass def process(self, input, context): raise Exception('this will not work')
class UserException(Function):
def __init__(self): pass def process(self, input, context): raise Exception('this will not work')
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # from pulsar import Function # Example function that throws an excpetion class UserException(Function):
64
64
34
5
58
Zod705/pulsar
pulsar-functions/python-examples/user_exception.py
Python
UserException
UserException
23
28
23
23
9af3d3375df657fd20e40abfd0ec8929f8a1bb43
bigcode/the-stack
train
9892794948f9f5855e5c0836
train
function
def _repeater(dataloader): for loader in repeat(dataloader): for data in loader: yield data
def _repeater(dataloader):
for loader in repeat(dataloader): for data in loader: yield data
from itertools import repeat import torch def _repeater(dataloader):
15
64
25
7
7
AIasd/ADFuzz
carla_lbc/carla_project/src/dataset_wrapper.py
Python
_repeater
_repeater
6
9
6
6
c8f2fe718fdd7179e6636f42d4b82c8c8575e47e
bigcode/the-stack
train
e7b1f9a66bb5392c9e37b119
train
class
class Wrap(object): def __init__(self, data, sampler, batch_size, samples, num_workers): self.data = infinite_dataloader(data, sampler, batch_size, num_workers) self.samples = samples def __iter__(self): for i in range(self.samples): yield next(self.data) def __len__(se...
class Wrap(object):
def __init__(self, data, sampler, batch_size, samples, num_workers): self.data = infinite_dataloader(data, sampler, batch_size, num_workers) self.samples = samples def __iter__(self): for i in range(self.samples): yield next(self.data) def __len__(self): return ...
Loader( data, batch_size=batch_size, num_workers=num_workers, sampler=sampler, drop_last=True, pin_memory=True) def infinite_dataloader(data, sampler, batch_size, num_workers): return _repeater(_dataloader(data, sampler, batch_size, num_workers)) class Wrap(object):
64
64
79
4
60
AIasd/ADFuzz
carla_lbc/carla_project/src/dataset_wrapper.py
Python
Wrap
Wrap
22
32
22
22
294eccff053244503bb9ffe90b2c7c0ddb6da34a
bigcode/the-stack
train
87639af33ac2261f4efbf4ed
train
function
def infinite_dataloader(data, sampler, batch_size, num_workers): return _repeater(_dataloader(data, sampler, batch_size, num_workers))
def infinite_dataloader(data, sampler, batch_size, num_workers):
return _repeater(_dataloader(data, sampler, batch_size, num_workers))
data def _dataloader(data, sampler, batch_size, num_workers): return torch.utils.data.DataLoader( data, batch_size=batch_size, num_workers=num_workers, sampler=sampler, drop_last=True, pin_memory=True) def infinite_dataloader(data, sampler, batch_size, num_workers):
64
64
32
14
50
AIasd/ADFuzz
carla_lbc/carla_project/src/dataset_wrapper.py
Python
infinite_dataloader
infinite_dataloader
18
19
18
18
49585e02ebb8bf868e4f50b0c094e71ffd26f601
bigcode/the-stack
train
5c1716eda1294a52bad5eadd
train
function
def _dataloader(data, sampler, batch_size, num_workers): return torch.utils.data.DataLoader( data, batch_size=batch_size, num_workers=num_workers, sampler=sampler, drop_last=True, pin_memory=True)
def _dataloader(data, sampler, batch_size, num_workers):
return torch.utils.data.DataLoader( data, batch_size=batch_size, num_workers=num_workers, sampler=sampler, drop_last=True, pin_memory=True)
from itertools import repeat import torch def _repeater(dataloader): for loader in repeat(dataloader): for data in loader: yield data def _dataloader(data, sampler, batch_size, num_workers):
47
64
48
14
32
AIasd/ADFuzz
carla_lbc/carla_project/src/dataset_wrapper.py
Python
_dataloader
_dataloader
12
15
12
12
2fc14cb610d7e790608c465d30dc45b86171c8ad
bigcode/the-stack
train
dbf1df8ff0c9a0c8e367297f
train
class
class DeleteView(generic.DeleteView): model = Story context_object_name = 'story'
class DeleteView(generic.DeleteView):
model = Story context_object_name = 'story'
= 'story' class CreateView(generic.CreateView): model = Story template_name = 'story/create.html' class EditView(generic.UpdateView): model = Story template_name = 'story/edit.html' context_object_name = 'story' class DeleteView(generic.DeleteView):
64
64
21
8
56
mshrinetra/-little-django-app
src/story/views.py
Python
DeleteView
DeleteView
29
31
29
29
4217a4ba05d2859d05bcaf07028c68a0342a78d0
bigcode/the-stack
train
8dacbccf1dc4e61892088a52
train
class
class EditView(generic.UpdateView): model = Story template_name = 'story/edit.html' context_object_name = 'story'
class EditView(generic.UpdateView):
model = Story template_name = 'story/edit.html' context_object_name = 'story'
= 'stories' class DetailView(generic.DetailView): model = Story template_name = 'story/detail.html' context_object_name = 'story' class CreateView(generic.CreateView): model = Story template_name = 'story/create.html' class EditView(generic.UpdateView):
64
64
30
8
56
mshrinetra/-little-django-app
src/story/views.py
Python
EditView
EditView
23
26
23
23
a8c61662e562fd7bbe49f72fc1a945663aacc9a1
bigcode/the-stack
train
5029351959af6ade0d69ca54
train
class
class DetailView(generic.DetailView): model = Story template_name = 'story/detail.html' context_object_name = 'story'
class DetailView(generic.DetailView):
model = Story template_name = 'story/detail.html' context_object_name = 'story'
from django.shortcuts import render from django.views import generic from .models import Story class IndexView(generic.ListView): model = Story template_name = 'story/index.html' context_object_name = 'stories' class DetailView(generic.DetailView):
56
64
30
8
48
mshrinetra/-little-django-app
src/story/views.py
Python
DetailView
DetailView
12
15
12
12
d6ba8edc2ac8a8a4dc9b04b28864b3ab718d849e
bigcode/the-stack
train
c2f4060c24d265e14dae86ac
train
class
class IndexView(generic.ListView): model = Story template_name = 'story/index.html' context_object_name = 'stories'
class IndexView(generic.ListView):
model = Story template_name = 'story/index.html' context_object_name = 'stories'
from django.shortcuts import render from django.views import generic from .models import Story class IndexView(generic.ListView):
26
64
30
8
17
mshrinetra/-little-django-app
src/story/views.py
Python
IndexView
IndexView
6
9
6
6
8d1ce40f917de2505b714ef59a20df51882516e8
bigcode/the-stack
train
02553c1e904662ee2469a483
train
class
class CreateView(generic.CreateView): model = Story template_name = 'story/create.html'
class CreateView(generic.CreateView):
model = Story template_name = 'story/create.html'
eneric.ListView): model = Story template_name = 'story/index.html' context_object_name = 'stories' class DetailView(generic.DetailView): model = Story template_name = 'story/detail.html' context_object_name = 'story' class CreateView(generic.CreateView):
64
64
22
8
56
mshrinetra/-little-django-app
src/story/views.py
Python
CreateView
CreateView
18
20
18
18
afd99c214e9b2aceb177694edadea6367ca05aad
bigcode/the-stack
train
ef05ca7fee4e6fae55872fb4
train
class
class ScannerDiscoverEndpointRequest(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is a...
class ScannerDiscoverEndpointRequest(object):
"""NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The...
# coding: utf-8 """ ELEMENTS API The version of the OpenAPI document: 2 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from elements_sdk.configuration import Configuration class ScannerDiscoverEndpointRequest(object):
66
256
887
7
58
elements-storage/elements-sdk-python
elements_sdk/models/scanner_discover_endpoint_request.py
Python
ScannerDiscoverEndpointRequest
ScannerDiscoverEndpointRequest
19
147
19
19
8c94b03d8a3c038e8eb5beab7c08598208308e6e
bigcode/the-stack
train
d691f8f628bb1e09796f4f7c
train
function
def CoeffDecoder(z,ch_depth = 3, ch_dim = 512, coeff_length = 128): with tf.variable_scope('stage1'): with tf.variable_scope('decoder'): y = z for i in range(ch_depth): y = tf.layers.dense(y, ch_dim, tf.nn.relu, name='fc'+str(i)) x_hat = tf.layers.dense(y...
def CoeffDecoder(z,ch_depth = 3, ch_dim = 512, coeff_length = 128):
with tf.variable_scope('stage1'): with tf.variable_scope('decoder'): y = z for i in range(ch_depth): y = tf.layers.dense(y, ch_dim, tf.nn.relu, name='fc'+str(i)) x_hat = tf.layers.dense(y, coeff_length, name='x_hat') x_hat = tf.stop_gradient(x...
as tflib import config import tensorflow as tf import argparse from pathlib import Path file_path = Path(__file__).parent # define mapping network from z space to lambda space def CoeffDecoder(z,ch_depth = 3, ch_dim = 512, coeff_length = 128):
64
64
109
23
40
lychenyoko/DiscoFaceGAN
generate_images.py
Python
CoeffDecoder
CoeffDecoder
21
31
21
21
b46b53c0ca194b0769acfe31986731175efdb249
bigcode/the-stack
train
082c333b0424c06545b24e71
train
function
def get_model_and_average_w_id(model_name): G, D, Gs = misc.load_pkl(model_name) average_w_name = model_name.replace('.pkl','-average_w_id.txt') if not os.path.isfile(average_w_name): print('Calculating average w id...\n') latents = tf.placeholder(tf.float32, name='latents', shape=[1,128+32+...
def get_model_and_average_w_id(model_name):
G, D, Gs = misc.load_pkl(model_name) average_w_name = model_name.replace('.pkl','-average_w_id.txt') if not os.path.isfile(average_w_name): print('Calculating average w id...\n') latents = tf.placeholder(tf.float32, name='latents', shape=[1,128+32+16+3]) noise = tf.placeholder(tf.flo...
truncation trick fake_images_out = Gs.components.synthesis.get_output_for(dlatent_out_final, randomize_noise = False) fake_images_out = tf.clip_by_value((fake_images_out+1)*127.5,0,255) fake_images_out = tf.transpose(fake_images_out,perm = [0,2,3,1]) return fake_images_out # calculate average w spac...
106
106
355
10
96
lychenyoko/DiscoFaceGAN
generate_images.py
Python
get_model_and_average_w_id
get_model_and_average_w_id
97
123
97
97
4bf5788cccabb8e85715523e4ca17fe7a1caaf9d
bigcode/the-stack
train
83e5f3454b8a7a10d2943634
train
function
def parse_args(): desc = "Disentangled face image generation" parser = argparse.ArgumentParser(description=desc) parser.add_argument('--factor', type=int, default=0, help='factor variation mode. 0 = all, 1 = expression, 2 = lighting, 3 = pose.') parser.add_argument('--subject', type=int, default=20, he...
def parse_args():
desc = "Disentangled face image generation" parser = argparse.ArgumentParser(description=desc) parser.add_argument('--factor', type=int, default=0, help='factor variation mode. 0 = all, 1 = expression, 2 = lighting, 3 = pose.') parser.add_argument('--subject', type=int, default=20, help='how many subje...
= 0) average_w_id = np.mean(average_w_id,axis = 0) np.savetxt(average_w_name,average_w_id) else: average_w_id = np.loadtxt(average_w_name) return Gs,average_w_id def parse_args():
64
64
150
4
59
lychenyoko/DiscoFaceGAN
generate_images.py
Python
parse_args
parse_args
125
134
125
125
38ed9f38d8169b8b33c971693265b9ba4be0bb7c
bigcode/the-stack
train
e3d2d5e81aacc380ff815002
train
function
def load_Gs(url): with dnnlib.util.open_url(url, cache_dir=config.cache_dir) as f: _G, _D, Gs = pickle.load(f) return Gs
def load_Gs(url):
with dnnlib.util.open_url(url, cache_dir=config.cache_dir) as f: _G, _D, Gs = pickle.load(f) return Gs
variation', type=int, default=5, help='how many images to generate per subject.') parser.add_argument('--model',type=str,default=None,help='pkl file name of the generator. If None, use the default pre-trained model.') return parser.parse_args() def load_Gs(url):
64
64
44
6
58
lychenyoko/DiscoFaceGAN
generate_images.py
Python
load_Gs
load_Gs
137
140
137
137
560944bd46fa34047660db87dd41872ca4a5defd
bigcode/the-stack
train
a0014bf0e94e47ea41be0bfa
train
function
def z_to_lambda_mapping(latents): with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): with tf.variable_scope('id'): IDcoeff = CoeffDecoder(z = latents[:,:128],coeff_length = 160,ch_dim = 512, ch_depth = 3) with tf.variable_scope('exp'): EXPcoeff = CoeffDecod...
def z_to_lambda_mapping(latents):
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE): with tf.variable_scope('id'): IDcoeff = CoeffDecoder(z = latents[:,:128],coeff_length = 160,ch_dim = 512, ch_depth = 3) with tf.variable_scope('exp'): EXPcoeff = CoeffDecoder(z = latents[:,128:128+32],coeff...
saver_gamma.restore(tf.get_default_session(), str((file_path / './vae/weights/gamma/stage1_epoch_395.ckpt').resolve())) saver_rot.restore(tf.get_default_session(), str((file_path / './vae/weights/rot/stage1_epoch_395.ckpt').resolve())) def z_to_lambda_mapping(latents):
70
70
236
8
62
lychenyoko/DiscoFaceGAN
generate_images.py
Python
z_to_lambda_mapping
z_to_lambda_mapping
58
71
58
58
e2b60b750966e26078e8b5b1b849dc1b837f7419
bigcode/the-stack
train
7ab63a52cc4010edc663b02a
train
function
def main(): args = parse_args() if args is None: exit() # save path for generated images save_path = 'generate_images' if not os.path.exists(save_path): os.makedirs(save_path) resume_pkl = '' tflib.init_tf() with tf.device('/gpu:0'): # Use default pre-trained m...
def main():
args = parse_args() if args is None: exit() # save path for generated images save_path = 'generate_images' if not os.path.exists(save_path): os.makedirs(save_path) resume_pkl = '' tflib.init_tf() with tf.device('/gpu:0'): # Use default pre-trained model ...
def parse_args(): desc = "Disentangled face image generation" parser = argparse.ArgumentParser(description=desc) parser.add_argument('--factor', type=int, default=0, help='factor variation mode. 0 = all, 1 = expression, 2 = lighting, 3 = pose.') parser.add_argument('--subject', type=int, default=20, ...
198
198
662
3
194
lychenyoko/DiscoFaceGAN
generate_images.py
Python
main
main
142
199
142
143
30eb16f437129f5d7d4b0dd50ccadfb33eb9b9ce
bigcode/the-stack
train
5fab17eb0ed7fe30a0d1fbcc
train
function
def truncate_generation(Gs,inputcoeff,rate=0.7,dlatent_average_id=None): if dlatent_average_id is None: url_pretrained_model_ffhq_average_w_id = 'https://drive.google.com/uc?id=17L6-ENX3NbMsS3MSCshychZETLPtJnbS' with dnnlib.util.open_url(url_pretrained_model_ffhq_average_w_id, cache_dir=config.cach...
def truncate_generation(Gs,inputcoeff,rate=0.7,dlatent_average_id=None):
if dlatent_average_id is None: url_pretrained_model_ffhq_average_w_id = 'https://drive.google.com/uc?id=17L6-ENX3NbMsS3MSCshychZETLPtJnbS' with dnnlib.util.open_url(url_pretrained_model_ffhq_average_w_id, cache_dir=config.cache_dir) as f: dlatent_average_id = np.loadtxt(f) dlatent_av...
) with tf.variable_scope('rot'): Rotcoeff = CoeffDecoder(z = latents[:,128+32+16:128+32+16+3],coeff_length = 3,ch_dim = 32, ch_depth = 3) INPUTcoeff = tf.concat([IDcoeff,EXPcoeff,Rotcoeff,GAMMAcoeff], axis = 1) return INPUTcoeff # generate images using attribute-preserving truncat...
112
112
375
19
92
lychenyoko/DiscoFaceGAN
generate_images.py
Python
truncate_generation
truncate_generation
74
94
74
75
044953ee46f16b0fd683c8177666883845cd5666
bigcode/the-stack
train
f6ede34633566dc1acae8a36
train
function
def restore_weights_and_initialize(): var_list = tf.trainable_variables() g_list = tf.global_variables() # add batch normalization params into trainable variables bn_moving_vars = [g for g in g_list if 'moving_mean' in g.name] bn_moving_vars += [g for g in g_list if 'moving_variance' in g.name] ...
def restore_weights_and_initialize():
var_list = tf.trainable_variables() g_list = tf.global_variables() # add batch normalization params into trainable variables bn_moving_vars = [g for g in g_list if 'moving_mean' in g.name] bn_moving_vars += [g for g in g_list if 'moving_variance' in g.name] var_list +=bn_moving_vars var_i...
def CoeffDecoder(z,ch_depth = 3, ch_dim = 512, coeff_length = 128): with tf.variable_scope('stage1'): with tf.variable_scope('decoder'): y = z for i in range(ch_depth): y = tf.layers.dense(y, ch_dim, tf.nn.relu, name='fc'+str(i)) x_hat = tf.layers.dense(...
122
122
409
6
115
lychenyoko/DiscoFaceGAN
generate_images.py
Python
restore_weights_and_initialize
restore_weights_and_initialize
34
56
34
34
41b8d07564e4b9d45bbbec3f6f9ea78b16382789
bigcode/the-stack
train
8f788449cf57e633d507cd1d
train
class
class MockFH: def __init__(self, filename, read_data, *args, **kwargs): self.filename = filename self.read_data = read_data try: self.mode = args[0] except IndexError: self.mode = kwargs.get("mode", "r") self.binary_mode = "b" in self.mode self...
class MockFH:
def __init__(self, filename, read_data, *args, **kwargs): self.filename = filename self.read_data = read_data try: self.mode = args[0] except IndexError: self.mode = kwargs.get("mode", "r") self.binary_mode = "b" in self.mode self.read_mode = a...
does not have MagicMock.assert_called in Python < 3.6. """ # pylint: disable=unused-import,function-redefined,blacklisted-module,blacklisted-external-module import copy import errno import fnmatch import sys # By these days, we should blowup if mock is not available import mock # pylint: disable=blacklisted-ex...
256
256
1,344
4
252
tomdoherty/salt
tests/support/mock.py
Python
MockFH
MockFH
54
220
54
54
a43e77d24d644b881f406355fe568d912a23596b
bigcode/the-stack
train
ff5db8fad5719fda4742e0f0
train
class
class MockCall: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __repr__(self): ret = "MockCall(" for arg in self.args: ret += repr(arg) + ", " if not self.kwargs: if self.args: # Remove trailing ', '...
class MockCall:
def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __repr__(self): ret = "MockCall(" for arg in self.args: ret += repr(arg) + ", " if not self.kwargs: if self.args: # Remove trailing ', ' ...
SError("File not open for writing") for line in lines: self._write(line) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # pylint: disable=unused-argument pass class MockCall:
64
64
165
4
59
tomdoherty/salt
tests/support/mock.py
Python
MockCall
MockCall
223
246
223
223
dde0dabf647fdbdefcd9c0e1daf095a45076de4d
bigcode/the-stack
train
10af42a09a4cfb8acbce0c53
train
class
class MockTimedProc: """ Class used as a stand-in for salt.utils.timed_subprocess.TimedProc """ class _Process: """ Used to provide a dummy "process" attribute """ def __init__(self, returncode=0, pid=12345): self.returncode = returncode self.pid...
class MockTimedProc:
""" Class used as a stand-in for salt.utils.timed_subprocess.TimedProc """ class _Process: """ Used to provide a dummy "process" attribute """ def __init__(self, returncode=0, pid=12345): self.returncode = returncode self.pid = pid def __ini...
the results to files matching a given pattern. """ ret = [] for filename, handles in self.filehandles.items(): if path is None or fnmatch.fnmatch(filename, path): for fh_ in handles: ret.extend(fh_.writelines_calls) return ret class MockTi...
67
67
226
5
61
tomdoherty/salt
tests/support/mock.py
Python
MockTimedProc
MockTimedProc
440
472
440
440
f5a226bdff063cd7eabf9fee741b8988860bf7a9
bigcode/the-stack
train
353578ebbbd83fc8f3c0e6dd
train
class
class MockOpen: r''' This class can be used to mock the use of ``open()``. ``read_data`` is a string representing the contents of the file to be read. By default, this is an empty string. Optionally, ``read_data`` can be a dictionary mapping ``fnmatch.fnmatch()`` patterns to strings (or option...
class MockOpen:
r''' This class can be used to mock the use of ``open()``. ``read_data`` is a string representing the contents of the file to be read. By default, this is an empty string. Optionally, ``read_data`` can be a dictionary mapping ``fnmatch.fnmatch()`` patterns to strings (or optionally, exceptions...
(content_type.__name__) ) def _writelines(self, lines): if not self.write_mode: raise OSError("File not open for writing") for line in lines: self._write(line) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): ...
256
256
1,489
4
251
tomdoherty/salt
tests/support/mock.py
Python
MockOpen
MockOpen
249
437
249
249
9a7dc01e9cd47a7fde4dfb84a59192b936357baf
bigcode/the-stack
train
194a54615fb4b9ce8c2844fc
train
function
def parse_splice_component(component, line, line_buffer): if component == "<SpliceMaxComponent>": raise NotImplementedError("Script doesn't support SpliceMaxComponent.") line = consume_token(component, line) line = consume_token("<InputDim>", line) [input_dim, _, line] = line.strip().partition(...
def parse_splice_component(component, line, line_buffer):
if component == "<SpliceMaxComponent>": raise NotImplementedError("Script doesn't support SpliceMaxComponent.") line = consume_token(component, line) line = consume_token("<InputDim>", line) [input_dim, _, line] = line.strip().partition(" ") line = consume_token("<Context>", line) conte...
= tempfile.mkstemp(dir=tmpdir) with open(filename, "w") as f: f.write("[ ") np.savetxt(f, scales, newline="") f.write(" ]") return {"<Bias>": filename} def parse_splice_component(component, line, line_buffer):
64
64
175
12
52
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_splice_component
parse_splice_component
390
409
390
390
bfaf5726ce5231196a8678cf2a58af0aca25fe4d
bigcode/the-stack
train
adc18bd8f97a7a1f23b8720d
train
function
def parse_nnet2_header(line_buffer): """Returns number of components in Nnet2 header.""" line = next(line_buffer) assert line.startswith("<Nnet>") line = consume_token("<Nnet>", line) num_components = int(line.split()[1]) line = line.partition(str(num_components))[2] line = consume_token("<...
def parse_nnet2_header(line_buffer):
"""Returns number of components in Nnet2 header.""" line = next(line_buffer) assert line.startswith("<Nnet>") line = consume_token("<Nnet>", line) num_components = int(line.split()[1]) line = line.partition(str(num_components))[2] line = consume_token("<Components>", line) return line,...
"transition_model") with open(transition_model, "w") as fc: fc.write(line) while True: line = next(line_buffer) fc.write(line) if line.startswith("</TransitionModel>"): break return transition_model def parse_nnet2_header(line_buffer):
64
64
86
9
54
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_nnet2_header
parse_nnet2_header
306
316
306
306
8242405ab561a074fca057cf3104ceb285b6311a
bigcode/the-stack
train
80accc707f328f32492a990b
train
function
def GetArgs(): parser = argparse.ArgumentParser( description="Converts nnet2 into nnet3 models.", epilog="""e.g. steps/nnet3/convert_nnet2_to_nnet3.py exp/tri4_nnet2 exp/tri4_nnet3""", ) parser.add_argument( "--tmpdir", type=str, default="./", ...
def GetArgs():
parser = argparse.ArgumentParser( description="Converts nnet2 into nnet3 models.", epilog="""e.g. steps/nnet3/convert_nnet2_to_nnet3.py exp/tri4_nnet2 exp/tri4_nnet3""", ) parser.add_argument( "--tmpdir", type=str, default="./", help="Custom...
(NODE_NAMES.keys()) # End configuration section logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.StreamHandler() handler.setLevel(logging.INFO) formatter = logging.Formatter( "%(asctime)s [%(filename)s:%(lineno)s - " "%(funcName)s - %(levelname)s ] %(message)s" ) handler.set...
91
91
306
4
87
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
GetArgs
GetArgs
71
113
71
71
67576a6fdc1e9572bfd8b1926fc1f84db0a4d8cc
bigcode/the-stack
train
68d097357297b9414f2d15a8
train
function
def parse_bias(line): if "<BiasParams>" in line: line = consume_token("<BiasParams>", line) return np.array([parse_vector(line)])
def parse_bias(line):
if "<BiasParams>" in line: line = consume_token("<BiasParams>", line) return np.array([parse_vector(line)])
while True: line = next(line_buffer) if line.strip().endswith("["): continue elif line.strip().endswith("]"): weights.append(parse_vector(line)) break else: weights.append(parse_vector(line)) return np.array(weights) def parse_bia...
64
64
34
5
59
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_bias
parse_bias
462
466
462
462
c352fdf351cc9026a0a8ef485f1c1a287572cdce
bigcode/the-stack
train
cebf5328b2557d4834b108d7
train
function
def parse_fixed_bias_component(component, line, line_buffer): line = consume_token(component, line) line = consume_token("<Bias>", line) scales = np.array([parse_vector(line)]) _, filename = tempfile.mkstemp(dir=tmpdir) with open(filename, "w") as f: f.write("[ ") np.savetxt(f, sca...
def parse_fixed_bias_component(component, line, line_buffer):
line = consume_token(component, line) line = consume_token("<Bias>", line) scales = np.array([parse_vector(line)]) _, filename = tempfile.mkstemp(dir=tmpdir) with open(filename, "w") as f: f.write("[ ") np.savetxt(f, scales, newline="") f.write(" ]") return {"<Bias>": ...
(component, line, line_buffer): line = consume_token(component, line) line = consume_token("<Sizes>", line) sizes = line.strip().strip("[]").strip().replace(" ", ",") return {"<Sizes>": sizes} def parse_fixed_bias_component(component, line, line_buffer):
64
64
96
12
52
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_fixed_bias_component
parse_fixed_bias_component
375
387
375
375
8d3235754dfc4e53e875768fb35fb3b3bd826f84
bigcode/the-stack
train
40fea44b48a01ddeb7bc7119
train
function
def make_splice_string(nodename, context, const_component_dim=0): """Generates splice string from a list of context. E.g. make_splice_string("renorm4", [-4, 4]) returns "Append(Offset(renorm4, -4), Offset(renorm4, 4))" """ assert type(context) == list, "context argument must be a list" string =...
def make_splice_string(nodename, context, const_component_dim=0):
"""Generates splice string from a list of context. E.g. make_splice_string("renorm4", [-4, 4]) returns "Append(Offset(renorm4, -4), Offset(renorm4, 4))" """ assert type(context) == list, "context argument must be a list" string = ["Offset({0}, {1})".format(nodename, i) for i in context] if ...
)[0]: logger.error( "Unexpected token, expected '{0}', got '{1}'.".format( token, line.split(None, 1)[0] ) ) return line.partition(token)[2] def make_splice_string(nodename, context, const_component_dim=0):
64
64
156
17
47
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
make_splice_string
make_splice_string
508
519
508
508
39cc3aa0c2ad9118d929ab4363397311d07b5510
bigcode/the-stack
train
5e8a1e493a24f938a4405511
train
function
def parse_affine_component(component, line, line_buffer): assert "<LinearParams>" in line pairs = dict(re.findall("(<\w+>) ([\w.-]+)", line)) # read the linear params and bias and convert it to a matrix weights = parse_weights(line_buffer) bias = parse_bias(next(line_buffer)) matrix = np.conc...
def parse_affine_component(component, line, line_buffer):
assert "<LinearParams>" in line pairs = dict(re.findall("(<\w+>) ([\w.-]+)", line)) # read the linear params and bias and convert it to a matrix weights = parse_weights(line_buffer) bias = parse_bias(next(line_buffer)) matrix = np.concatenate([weights, bias.T], axis=1) # write matrix and...
_end_of_component(component, line, line_buffer): # Keeps reading until it hits the end tag for component end_component = "</" + component[1:] while end_component not in line: line = next(line_buffer) return def parse_affine_component(component, line, line_buffer):
64
64
156
12
51
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_affine_component
parse_affine_component
422
442
422
422
f19111d6e6e79d3a14b40e3e2c4b7d505a3577c9
bigcode/the-stack
train
e874f56d16eff65a696150c2
train
function
def parse_standard_component(component, line, line_buffer): # Ignores stats such as ValueSum and DerivSum line = consume_token(component, line) pairs = re.findall("(<\w+>) ([\w.-]+)", line) return dict(pairs)
def parse_standard_component(component, line, line_buffer): # Ignores stats such as ValueSum and DerivSum
line = consume_token(component, line) pairs = re.findall("(<\w+>) ([\w.-]+)", line) return dict(pairs)
else: raise LookupError("Unrecognised component, {0}.".format(component)) parse_end_of_component(component, line, line_buffer) return component, pairs def parse_standard_component(component, line, line_buffer): # Ignores stats such as ValueSum and DerivSum
64
64
60
26
37
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_standard_component
parse_standard_component
343
348
343
344
ef98871c9c39c58690473a4a895b40b210d0484e
bigcode/the-stack
train
74c25ddd0d1b1b4f49b7b463
train
function
def parse_priors(line, line_buffer): vector = parse_vector(line.partition("[")[2]) priors = os.path.join(tmpdir, "priors") with open(priors, "w") as f: f.write("[ ") np.savetxt(f, vector, newline=" ") f.write(" ]") return priors
def parse_priors(line, line_buffer):
vector = parse_vector(line.partition("[")[2]) priors = os.path.join(tmpdir, "priors") with open(priors, "w") as f: f.write("[ ") np.savetxt(f, vector, newline=" ") f.write(" ]") return priors
line = consume_token("<BiasParams>", line) return np.array([parse_vector(line)]) def parse_vector(line): vector = line.strip().strip("[]") return np.array([float(x) for x in vector.split()], dtype="float32") def parse_priors(line, line_buffer):
64
64
74
9
55
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_priors
parse_priors
474
483
474
474
b92277e983bc9500b570196482094769e77bb743
bigcode/the-stack
train
3273ad32036765d3fda83ad7
train
function
def parse_transition_model(line_buffer): """Writes transition model to text file. Returns filename. """ line = next(line_buffer) assert line.startswith("<TransitionModel>") transition_model = os.path.join(tmpdir, "transition_model") with open(transition_model, "w") as fc: fc.write...
def parse_transition_model(line_buffer):
"""Writes transition model to text file. Returns filename. """ line = next(line_buffer) assert line.startswith("<TransitionModel>") transition_model = os.path.join(tmpdir, "transition_model") with open(transition_model, "w") as fc: fc.write(line) while True: l...
= parse_priors(line, line_buffer) if model.components_read != model.num_components: logger.error( "Did not read all components succesfully: {0}/{1}".format( model.components_read, model.num_components ) ) return model def parse_transition_model(line_buf...
64
64
103
7
56
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_transition_model
parse_transition_model
284
303
284
284
a5d26bde047894cdc987fd22ccadf6738488c676
bigcode/the-stack
train
14f63087c89f6f1e1680b5e8
train
function
def parse_component(line, line_buffer): component = line.split()[0] pairs = {} if component in SPLICE_COMPONENTS: line, pairs = parse_splice_component(component, line, line_buffer) elif component in AFFINE_COMPONENTS: pairs = parse_affine_component(component, line, line_buffer) elif...
def parse_component(line, line_buffer):
component = line.split()[0] pairs = {} if component in SPLICE_COMPONENTS: line, pairs = parse_splice_component(component, line, line_buffer) elif component in AFFINE_COMPONENTS: pairs = parse_affine_component(component, line, line_buffer) elif component == "<FixedScaleComponent>": ...
line.startswith("<Nnet>") line = consume_token("<Nnet>", line) num_components = int(line.split()[1]) line = line.partition(str(num_components))[2] line = consume_token("<Components>", line) return line, num_components def parse_component(line, line_buffer):
64
64
200
8
55
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_component
parse_component
319
340
319
319
e2c13f6ef20971d8ff799568fd1f5a3ec9344bb6
bigcode/the-stack
train
cb320a14afcb195e93ed42c7
train
function
def parse_end_of_component(component, line, line_buffer): # Keeps reading until it hits the end tag for component end_component = "</" + component[1:] while end_component not in line: line = next(line_buffer) return
def parse_end_of_component(component, line, line_buffer): # Keeps reading until it hits the end tag for component
end_component = "</" + component[1:] while end_component not in line: line = next(line_buffer) return
().split()[0]) return line, { "<InputDim>": input_dim, "<Context>": context, "<ConstComponentDim>": const_component_dim, } def parse_end_of_component(component, line, line_buffer): # Keeps reading until it hits the end tag for component
64
64
54
25
39
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_end_of_component
parse_end_of_component
412
419
412
413
3d551bd7ca769884b1bc24f3763c2d9214e5c766
bigcode/the-stack
train
7617cf7247e896701132a6a3
train
function
def token_to_string(token): """Converts tokens to lowercase, hyphen-bounded strings. E.g. <InputDim> -> input-dim """ string = token[1:-1] string = re.sub(r"((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))", r"-\1", string).lower() return string
def token_to_string(token):
"""Converts tokens to lowercase, hyphen-bounded strings. E.g. <InputDim> -> input-dim """ string = token[1:-1] string = re.sub(r"((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))", r"-\1", string).lower() return string
("[")[2]) priors = os.path.join(tmpdir, "priors") with open(priors, "w") as f: f.write("[ ") np.savetxt(f, vector, newline=" ") f.write(" ]") return priors def token_to_string(token):
64
64
87
6
57
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
token_to_string
token_to_string
486
493
486
486
8fc46f9d573567d5c84a19426eb2dd42a8d31fc5
bigcode/the-stack
train
ffaa004a4db8aa975431d0bc
train
function
def parse_weights(line_buffer): weights = [] while True: line = next(line_buffer) if line.strip().endswith("["): continue elif line.strip().endswith("]"): weights.append(parse_vector(line)) break else: weights.append(parse_vector(...
def parse_weights(line_buffer):
weights = [] while True: line = next(line_buffer) if line.strip().endswith("["): continue elif line.strip().endswith("]"): weights.append(parse_vector(line)) break else: weights.append(parse_vector(line)) return np.array(weig...
_, filename = tempfile.mkstemp(dir=tmpdir) with open(filename, "w") as f: f.write("[ ") np.savetxt(f, matrix) f.write(" ]") pairs["<Matrix>"] = filename return pairs def parse_weights(line_buffer):
64
64
69
6
57
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_weights
parse_weights
445
459
445
445
4d0797c009f1447cc47e96c67f90f60e8c14b266
bigcode/the-stack
train
dda16483927e0a2bee55ade3
train
function
def parse_fixed_scale_component(component, line, line_buffer): line = consume_token(component, line) line = consume_token("<Scales>", line) scales = np.array([parse_vector(line)]) _, filename = tempfile.mkstemp(dir=tmpdir) with open(filename, "w") as f: f.write("[ ") np.savetxt(f, ...
def parse_fixed_scale_component(component, line, line_buffer):
line = consume_token(component, line) line = consume_token("<Scales>", line) scales = np.array([parse_vector(line)]) _, filename = tempfile.mkstemp(dir=tmpdir) with open(filename, "w") as f: f.write("[ ") np.savetxt(f, scales, newline="") f.write(" ]") return {"<Scales...
line_buffer): # Ignores stats such as ValueSum and DerivSum line = consume_token(component, line) pairs = re.findall("(<\w+>) ([\w.-]+)", line) return dict(pairs) def parse_fixed_scale_component(component, line, line_buffer):
64
64
98
12
52
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_fixed_scale_component
parse_fixed_scale_component
351
363
351
351
44b58ff464e2edbdadfa1d076a2bcb6ae5f75779
bigcode/the-stack
train
5f0af73a2861fac5d999558a
train
function
def parse_vector(line): vector = line.strip().strip("[]") return np.array([float(x) for x in vector.split()], dtype="float32")
def parse_vector(line):
vector = line.strip().strip("[]") return np.array([float(x) for x in vector.split()], dtype="float32")
.append(parse_vector(line)) break else: weights.append(parse_vector(line)) return np.array(weights) def parse_bias(line): if "<BiasParams>" in line: line = consume_token("<BiasParams>", line) return np.array([parse_vector(line)]) def parse_vector(line):
63
64
34
5
58
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_vector
parse_vector
469
471
469
469
c46b8d1ba400e97ce300d789f3d89cf65c9868bd
bigcode/the-stack
train
04413d7ab48f9bcb41457dd7
train
function
def consume_token(token, line): """Returns line without token""" if token != line.split(None, 1)[0]: logger.error( "Unexpected token, expected '{0}', got '{1}'.".format( token, line.split(None, 1)[0] ) ) return line.partition(token)[2]
def consume_token(token, line):
"""Returns line without token""" if token != line.split(None, 1)[0]: logger.error( "Unexpected token, expected '{0}', got '{1}'.".format( token, line.split(None, 1)[0] ) ) return line.partition(token)[2]
-dim """ string = token[1:-1] string = re.sub(r"((?<=[a-z])[A-Z]|(?<!\A)[A-Z](?=[a-z]))", r"-\1", string).lower() return string def consume_token(token, line):
64
64
71
7
56
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
consume_token
consume_token
496
505
496
496
9c37819f8aac0d49bc11d78bc4c2a35690e9e695
bigcode/the-stack
train
aae0dbc82cca591415ed6fc5
train
function
def parse_sum_group_component(component, line, line_buffer): line = consume_token(component, line) line = consume_token("<Sizes>", line) sizes = line.strip().strip("[]").strip().replace(" ", ",") return {"<Sizes>": sizes}
def parse_sum_group_component(component, line, line_buffer):
line = consume_token(component, line) line = consume_token("<Sizes>", line) sizes = line.strip().strip("[]").strip().replace(" ", ",") return {"<Sizes>": sizes}
tempfile.mkstemp(dir=tmpdir) with open(filename, "w") as f: f.write("[ ") np.savetxt(f, scales, newline="") f.write(" ]") return {"<Scales>": filename} def parse_sum_group_component(component, line, line_buffer):
64
64
57
12
52
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_sum_group_component
parse_sum_group_component
366
372
366
366
3f5aaa69ed19803f46b076021ff0150b5bd421eb
bigcode/the-stack
train
4ef3bb10f6e604016add732d
train
function
def parse_nnet2_to_nnet3(line_buffer): """Reads an Nnet2 model into an Nnet3 object. Parses by passing line_buffer objects depending upon the current place or component being read. Returns Nnet3 object. """ model = Nnet3Model() # <TransitionModel> ... model.transition_model = parse_tr...
def parse_nnet2_to_nnet3(line_buffer):
"""Reads an Nnet2 model into an Nnet3 object. Parses by passing line_buffer objects depending upon the current place or component being read. Returns Nnet3 object. """ model = Nnet3Model() # <TransitionModel> ... model.transition_model = parse_transition_model(line_buffer) # <Nne...
net3-am-adjust-priors " "--binary={0} {1} {2} {3}".format( binary, os.path.join(tmpdir, "nnet3_no_prior.mdl"), self.priors, model ) ) def parse_nnet2_to_nnet3(line_buffer):
64
64
216
12
52
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
parse_nnet2_to_nnet3
parse_nnet2_to_nnet3
248
281
248
248
9b943501e3e5ffb656cd637a6be2267ed19a6cab
bigcode/the-stack
train
757b965d7b3601a3cf9c4818
train
function
def Main(): args = GetArgs() logger.info( "Converting nnet2 model {0} to nnet3 model {1}".format( os.path.join(args.nnet2_dir, args.model), os.path.join(args.nnet3_dir, args.model), ) ) global tmpdir tmpdir = tempfile.mkdtemp(dir=args.tmpdir) # Convert nn...
def Main():
args = GetArgs() logger.info( "Converting nnet2 model {0} to nnet3 model {1}".format( os.path.join(args.nnet2_dir, args.model), os.path.join(args.nnet3_dir, args.model), ) ) global tmpdir tmpdir = tempfile.mkdtemp(dir=args.tmpdir) # Convert nnet2 model to...
type(context) == list, "context argument must be a list" string = ["Offset({0}, {1})".format(nodename, i) for i in context] if const_component_dim > 0: string.append("ReplaceIndex(ivector, t, 0)") string = "Append(" + ", ".join(string) + ")" return string tmpdir = "" def Main():
87
88
295
3
84
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
Main
Main
525
559
525
525
5a228dc7c5063e46121bea785f3d81b7eefbe085
bigcode/the-stack
train
d24092b2e07814554ba8dd83
train
class
class Nnet3Model(object): """Holds configuration for an Nnet3 model.""" def __init__(self): self.input_dim = -1 self.output_dim = -1 self.ivector_dim = 0 self.counts = defaultdict(int) self.num_components = 0 self.components_read = 0 self.config = "" ...
class Nnet3Model(object):
"""Holds configuration for an Nnet3 model.""" def __init__(self): self.input_dim = -1 self.output_dim = -1 self.ivector_dim = 0 self.counts = defaultdict(int) self.num_components = 0 self.components_read = 0 self.config = "" self.transition_model ...
tri4_nnet3""", ) parser.add_argument( "--tmpdir", type=str, default="./", help="Custom location for the temporary directory.", ) parser.add_argument( "--skip-cleanup", action="store_true", help="Will not remove the temporary directory.", ) ...
256
256
1,006
7
248
mlcommons/peoples-speech
scripts/recipes/librispeech/steps/nnet3/convert_nnet2_to_nnet3.py
Python
Nnet3Model
Nnet3Model
116
245
116
116
7d8ad97d47a4e5edf9acd2ffe593ada92146c794
bigcode/the-stack
train
3aa30b747efa8fc433606890
train
class
class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_k...
class Migration(migrations.Migration):
initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='...
# Generated by Django 3.1.2 on 2020-10-06 15:23 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
51
64
210
7
43
Hafsaaa/Django-Blog
mysite/blog/migrations/0001_initial.py
Python
Migration
Migration
8
33
8
9
163c5498b758ea4ae3cd64c149288cc2977293e7
bigcode/the-stack
train
0e3396f143a5c5e80c4be485
train
class
class ProjectSetup: # pylint: disable=R0903 """Class which sets up the project for unitt tests """ app_id = None @classmethod def setUpClass(cls): # pylint: disable=C0103 """Sets up project settings. """ if not cls.app_id: raise ValueError("You must set the ap...
class ProjectSetup: # pylint: disable=R0903
"""Class which sets up the project for unitt tests """ app_id = None @classmethod def setUpClass(cls): # pylint: disable=C0103 """Sets up project settings. """ if not cls.app_id: raise ValueError("You must set the app id before running the test.") PROJE...
"""Setup module for migration state test cases. """ import os from espressodb import init ROOT_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__))) class ProjectSetup: # pylint: disable=R0903
50
67
225
14
36
callat-qcd/espressodb
tests/migration_tests/tests/setup.py
Python
ProjectSetup
ProjectSetup
11
43
11
11
7f01b7ccc31ab0257bff7d8ae31c9548475b0c71
bigcode/the-stack
train
aecafdd311badaced1041da5
train
class
class PlatformXGBoostJobConverter(PlatformConverterMixin, XGBoostJobConverter): pass
class PlatformXGBoostJobConverter(PlatformConverterMixin, XGBoostJobConverter):
pass
od_policy=job.clean_pod_policy, scheduling_policy=job.scheduling_policy, sync_statuses=contexts.sync_statuses, notifications=plugins.notifications, labels=labels, annotations=self.annotations, ) class PlatformXGBoostJobConverter(PlatformConverterMixin,...
64
64
21
18
46
bobvdvelde/polyaxon
src/core/polyaxon/polypod/compiler/converters/kubeflow/xgboost_job.py
Python
PlatformXGBoostJobConverter
PlatformXGBoostJobConverter
87
88
87
87
c0fc6e72d9e372d2ad15d9448e2523f7a0554685
bigcode/the-stack
train
48a69c7e68956db98b97616d
train
class
class XGBoostJobConverter(XGBoostJobMixin, BaseConverter): def get_resource( self, compiled_operation: V1CompiledOperation, artifacts_store: V1ConnectionType, connection_by_names: Dict[str, V1ConnectionType], secrets: Optional[Iterable[V1K8sResourceType]], config_maps...
class XGBoostJobConverter(XGBoostJobMixin, BaseConverter):
def get_resource( self, compiled_operation: V1CompiledOperation, artifacts_store: V1ConnectionType, connection_by_names: Dict[str, V1ConnectionType], secrets: Optional[Iterable[V1K8sResourceType]], config_maps: Optional[Iterable[V1K8sResourceType]], default_sa...
V1Plugins, V1XGBoostJob from polyaxon.polypod.compiler.converters import BaseConverter from polyaxon.polypod.compiler.converters.base import PlatformConverterMixin from polyaxon.polypod.custom_resources import get_xgb_job_custom_resource from polyaxon.polypod.mixins import XGBoostJobMixin from polyaxon.polypod.specs.c...
133
133
446
15
117
bobvdvelde/polyaxon
src/core/polyaxon/polypod/compiler/converters/kubeflow/xgboost_job.py
Python
XGBoostJobConverter
XGBoostJobConverter
30
84
30
30
a43eea33e099fd039612ef582e446f6b6be745f3
bigcode/the-stack
train
da54bccf1fcf90efb6ba1b5e
train
class
class UserMeta(WordPressModel): """ Meta information about a user. """ id = models.IntegerField(db_column='umeta_id', primary_key=True) user = models.ForeignKey(User, related_name="meta", db_column='user_id', on_delete=models.CASCADE) key = models.CharField(max_length=255, db_column='meta_key')...
class UserMeta(WordPressModel):
""" Meta information about a user. """ id = models.IntegerField(db_column='umeta_id', primary_key=True) user = models.ForeignKey(User, related_name="meta", db_column='user_id', on_delete=models.CASCADE) key = models.CharField(max_length=255, db_column='meta_key') value = models.TextField(db...
= models.CharField(max_length=255, db_column='display_name') class Meta: db_table = '%s_users' % TABLE_PREFIX ordering = ["display_name"] managed = False def __unicode__(self): return self.display_name class UserMeta(WordPressModel):
64
64
136
8
55
2e2a/django-wordpress
wordpress/models.py
Python
UserMeta
UserMeta
151
166
151
151
8e31a3521636f21cd4d02b3effb45d00905243e9
bigcode/the-stack
train
34099df70d56de4b1a720133
train
class
class OptionManager(WordPressManager): def get_value(self, name): try: o = self.get(name=name) return o.value except ObjectDoesNotExist: pass
class OptionManager(WordPressManager):
def get_value(self, name): try: o = self.get(name=name) return o.value except ObjectDoesNotExist: pass
(WordPressModel, self).save(**kwargs) def delete(self, override=False): if READ_ONLY and not override: raise WordPressException("object is read-only") super(WordPressModel, self).delete() # # WordPress models # class OptionManager(WordPressManager):
64
64
42
8
56
2e2a/django-wordpress
wordpress/models.py
Python
OptionManager
OptionManager
98
104
98
98
2b913ceae035170c485f7be7b29fd5a2f626ba5b
bigcode/the-stack
train
c8cc13d7ab29eebe9ab7344e
train
class
class PostMeta(WordPressModel): """ Post meta data. """ id = models.IntegerField(db_column='meta_id', primary_key=True) post = models.ForeignKey(Post, related_name='meta', db_column='post_id', on_delete=models.CASCADE) key = models.CharField(max_length=255, db_column='meta_key') value = mod...
class PostMeta(WordPressModel):
""" Post meta data. """ id = models.IntegerField(db_column='meta_id', primary_key=True) post = models.ForeignKey(Post, related_name='meta', db_column='post_id', on_delete=models.CASCADE) key = models.CharField(max_length=255, db_column='meta_key') value = models.TextField(db_column='meta_va...
, 'timestamp': post.post_date, 'description': post.content, 'title': post.title, 'guid': post.guid, 'mimetype': post.mime_type, } def tags(self): return self._get_terms("post_tag") class Post...
64
64
132
8
56
2e2a/django-wordpress
wordpress/models.py
Python
PostMeta
PostMeta
403
418
403
403
2b2c8fe97f3e2fbc1b82f075b0b0862f0b09988b
bigcode/the-stack
train
17ac9a0f7335cabca621695d
train
class
class WordPressManager(models.Manager): """ Base manager for wordpress queries. """ pass
class WordPressManager(models.Manager):
""" Base manager for wordpress queries. """ pass
_READ_ONLY", True) TABLE_PREFIX = getattr(settings, "WP_TABLE_PREFIX", "wp") # # Exceptions # class WordPressException(Exception): """ Exception that is thrown when attempting to save a read-only object. """ pass # # Base managers # class WordPressManager(models.Manager):
64
64
21
7
57
2e2a/django-wordpress
wordpress/models.py
Python
WordPressManager
WordPressManager
52
56
52
52
d6f3e4256a96e55e4aca841819276432dd8ab9cd
bigcode/the-stack
train
526aa76479261220bee1c704
train
class
class User(WordPressModel): """ User object. Referenced by Posts, Comments, and Links """ id = models.AutoField(primary_key=True, db_column='ID') login = models.CharField(max_length=60, db_column='user_login') password = models.CharField(max_length=64, db_column='user_pass') username = mod...
class User(WordPressModel):
""" User object. Referenced by Posts, Comments, and Links """ id = models.AutoField(primary_key=True, db_column='ID') login = models.CharField(max_length=60, db_column='user_login') password = models.CharField(max_length=64, db_column='user_pass') username = models.CharField(max_length=255...
_column='option_value') autoload = models.CharField(max_length=20) class Meta: db_table = '%s_options' % TABLE_PREFIX ordering = ["name"] managed = False def __unicode__(self): return u"%s: %s" % (self.name, self.value) class User(WordPressModel):
75
75
250
7
68
2e2a/django-wordpress
wordpress/models.py
Python
User
User
125
148
125
125
7a02ce3b79c01983af5e27f6dfc55051d6cc70e3
bigcode/the-stack
train
dae7a61fa6dac9da89b584c8
train
class
class Comment(WordPressModel): """ Comments to Posts. """ id = models.IntegerField(db_column='comment_id', primary_key=True) post = models.ForeignKey(Post, related_name="comments", db_column="comment_post_id", on_delete=models.CASCADE) user_id = models.IntegerField(db_column='user_id', default=...
class Comment(WordPressModel):
""" Comments to Posts. """ id = models.IntegerField(db_column='comment_id', primary_key=True) post = models.ForeignKey(Post, related_name="comments", db_column="comment_post_id", on_delete=models.CASCADE) user_id = models.IntegerField(db_column='user_id', default=0) parent_id = models.Integ...
. """ id = models.IntegerField(db_column='meta_id', primary_key=True) post = models.ForeignKey(Post, related_name='meta', db_column='post_id', on_delete=models.CASCADE) key = models.CharField(max_length=255, db_column='meta_key') value = models.TextField(db_column='meta_value') class Meta: ...
125
125
419
7
118
2e2a/django-wordpress
wordpress/models.py
Python
Comment
Comment
421
470
421
421
2700786194cfb082d5af86ad63518f1b6cab52b6
bigcode/the-stack
train
931a2078699fddad2867354c
train
class
class WordPressException(Exception): """ Exception that is thrown when attempting to save a read-only object. """ pass
class WordPressException(Exception):
""" Exception that is thrown when attempting to save a read-only object. """ pass
', 'post'), ('revision', 'revision'), ) USER_STATUS_CHOICES = ( (0, "active"), ) READ_ONLY = getattr(settings, "WP_READ_ONLY", True) TABLE_PREFIX = getattr(settings, "WP_TABLE_PREFIX", "wp") # # Exceptions # class WordPressException(Exception):
64
64
27
6
58
2e2a/django-wordpress
wordpress/models.py
Python
WordPressException
WordPressException
41
45
41
41
29c576c867bcd630fa8d458cbd527b6524e110fe
bigcode/the-stack
train
ed612f7e7b72036d7613a53b
train
class
class Option(WordPressModel): objects = OptionManager() id = models.IntegerField(db_column='option_id', primary_key=True) name = models.CharField(max_length=64, db_column='option_name') value = models.TextField(db_column='option_value') autoload = models.CharField(max_length=20) class Meta: ...
class Option(WordPressModel):
objects = OptionManager() id = models.IntegerField(db_column='option_id', primary_key=True) name = models.CharField(max_length=64, db_column='option_name') value = models.TextField(db_column='option_value') autoload = models.CharField(max_length=20) class Meta: db_table = '%s_options' ...
WordPressModel, self).delete() # # WordPress models # class OptionManager(WordPressManager): def get_value(self, name): try: o = self.get(name=name) return o.value except ObjectDoesNotExist: pass class Option(WordPressModel):
64
64
121
7
56
2e2a/django-wordpress
wordpress/models.py
Python
Option
Option
107
122
107
108
bc7a9c4b1816e15f0df7ccaa13b180f34fde0632
bigcode/the-stack
train
ddbf2fc90f0eea1721ff53be
train
class
class Term(WordPressModel): id = models.IntegerField(db_column='term_id', primary_key=True) name = models.CharField(max_length=200) slug = models.CharField(max_length=200) group = models.IntegerField(default=0, db_column='term_group') class Meta: db_table = '%s_terms' % TABLE_PREFIX ...
class Term(WordPressModel):
id = models.IntegerField(db_column='term_id', primary_key=True) name = models.CharField(max_length=200) slug = models.CharField(max_length=200) group = models.IntegerField(default=0, db_column='term_group') class Meta: db_table = '%s_terms' % TABLE_PREFIX ordering = ['name'] ...
self.parent_id) """ def user(self): return self._get_object(User, self.user_id) """ def is_approved(self): return self.approved == '1' def is_spam(self): return self.approved == 'spam' class Term(WordPressModel):
64
64
120
7
57
2e2a/django-wordpress
wordpress/models.py
Python
Term
Term
473
489
473
474
5f312e30dc9e607624051275c4b54b3530add2e3
bigcode/the-stack
train
07b97a49e139d342633448b2
train
class
class PostManager(WordPressManager): """ Provides convenience methods for filtering posts by status. """ def _by_status(self, status, post_type='post'): return self.filter(status=status, post_type=post_type)\ .select_related().prefetch_related('meta') def drafts(self, post_type...
class PostManager(WordPressManager):
""" Provides convenience methods for filtering posts by status. """ def _by_status(self, status, post_type='post'): return self.filter(status=status, post_type=post_type)\ .select_related().prefetch_related('meta') def drafts(self, post_type='post'): return self._by_sta...
rel = models.CharField(max_length=255, db_column='link_rel') notes = models.TextField(db_column='link_notes') rss = models.CharField(max_length=255, db_column='link_rss') class Meta: db_table = '%s_links' % TABLE_PREFIX managed = False def __unicode__(self): return u"%s %s"...
113
113
378
8
105
2e2a/django-wordpress
wordpress/models.py
Python
PostManager
PostManager
199
247
199
199
979e1400915848f621bca2c6251d26de8de0d610
bigcode/the-stack
train
8c4d910e1ef0021655c29a7e
train
class
class Link(WordPressModel): """ An external link. """ id = models.IntegerField(db_column='link_id', primary_key=True) url = models.URLField(max_length=255, db_column='link_url') name = models.CharField(max_length=255, db_column='link_name') image = models.CharField(max_length=255, db_column...
class Link(WordPressModel):
""" An external link. """ id = models.IntegerField(db_column='link_id', primary_key=True) url = models.URLField(max_length=255, db_column='link_url') name = models.CharField(max_length=255, db_column='link_name') image = models.CharField(max_length=255, db_column='link_image') target = ...
', on_delete=models.CASCADE) key = models.CharField(max_length=255, db_column='meta_key') value = models.TextField(db_column='meta_value') class Meta: db_table = '%s_usermeta' % TABLE_PREFIX managed = False def __unicode__(self): return u"%s: %s" % (self.key, self.value) class ...
89
89
298
7
82
2e2a/django-wordpress
wordpress/models.py
Python
Link
Link
169
196
169
169
c3dcfa086ada12fda1f436881c2e5dbe038a63c8
bigcode/the-stack
train
965d2864020c424faef8a330
train
class
class Post(WordPressModel): """ The mother lode. The WordPress post. """ objects = PostManager() id = models.AutoField(primary_key=True, db_column='ID') # post data guid = models.CharField(max_length=255) post_type = models.CharField(max_length=20, choices=POST_TYPE_CHOICES) s...
class Post(WordPressModel):
""" The mother lode. The WordPress post. """ objects = PostManager() id = models.AutoField(primary_key=True, db_column='ID') # post data guid = models.CharField(max_length=255) post_type = models.CharField(max_length=20, choices=POST_TYPE_CHOICES) status = models.CharField(max...
return self.published().filter(pk__in=post_ids) except Taxonomy.DoesNotExist: return self.none() def from_path(self, path): (ymd, slug) = path.strip('/').rsplit('/', 1) start_date = datetime.datetime.strptime(ymd, "%Y/%m/%d") end_date = start_date + datetim...
256
256
931
7
248
2e2a/django-wordpress
wordpress/models.py
Python
Post
Post
267
400
267
267
4d6807ebb4873824438b900d4005458ddbbc0ab1
bigcode/the-stack
train
ea87ab2eafcf82b82d977627
train
class
class WordPressModel(models.Model): """ Base model for all WordPress objects. Overrides save and delete methods to enforce read-only setting. Overrides self.objects to enforce WP_DATABASE setting. """ objects = WordPressManager() class Meta: abstract = True managed = False...
class WordPressModel(models.Model):
""" Base model for all WordPress objects. Overrides save and delete methods to enforce read-only setting. Overrides self.objects to enforce WP_DATABASE setting. """ objects = WordPressManager() class Meta: abstract = True managed = False def _get_object(self, model, o...
Exception(Exception): """ Exception that is thrown when attempting to save a read-only object. """ pass # # Base managers # class WordPressManager(models.Manager): """ Base manager for wordpress queries. """ pass # # Base models # class WordPressModel(models.Model):
64
64
178
7
57
2e2a/django-wordpress
wordpress/models.py
Python
WordPressModel
WordPressModel
63
91
63
63
aba554014d10ac0f225a683cd83b82e9fe1a7b34
bigcode/the-stack
train
fd08cf27f2ca1096df8abe9e
train
class
class Taxonomy(WordPressModel): id = models.IntegerField(db_column='term_taxonomy_id', primary_key=True) term = models.ForeignKey(Term, related_name='taxonomies', blank=True, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=32, db_column='taxonomy') description = models.TextFiel...
class Taxonomy(WordPressModel):
id = models.IntegerField(db_column='term_taxonomy_id', primary_key=True) term = models.ForeignKey(Term, related_name='taxonomies', blank=True, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=32, db_column='taxonomy') description = models.TextField() parent_id = models.Intege...
db_table = '%s_terms' % TABLE_PREFIX ordering = ['name'] managed = False def __unicode__(self): return self.name def get_absolute_url(self): return reverse('wp_archive_term', (self.slug, )) class Taxonomy(WordPressModel):
63
64
193
8
55
2e2a/django-wordpress
wordpress/models.py
Python
Taxonomy
Taxonomy
492
514
492
493
f1e914368896b422e8d9eccc4a46f466a3fd7b7b
bigcode/the-stack
train
95f43f922fade8eaf473101d
train
class
class TermTaxonomyRelationship(WordPressModel): object = models.ForeignKey('Post', on_delete=models.CASCADE) term_taxonomy = models.ForeignKey( 'Taxonomy', related_name='relationships', db_column='term_taxonomy_id', on_delete=models.CASCADE, ) order = models.IntegerField...
class TermTaxonomyRelationship(WordPressModel):
object = models.ForeignKey('Post', on_delete=models.CASCADE) term_taxonomy = models.ForeignKey( 'Taxonomy', related_name='relationships', db_column='term_taxonomy_id', on_delete=models.CASCADE, ) order = models.IntegerField(db_column='term_order') class Meta: ...
= { 'post_date__range': (start_date, end_date), 'slug': slug, } try: return self.published().get(**params) except ObjectDoesNotExist: pass # fall through to return None class TermTaxonomyRelationship(WordPressModel):
64
64
102
10
53
2e2a/django-wordpress
wordpress/models.py
Python
TermTaxonomyRelationship
TermTaxonomyRelationship
250
264
250
251
df79643e6d029bd55b29d90b3043732d61726eca
bigcode/the-stack
train
0dc6ac6ed09c4dc86a910656
train
class
class FTP(): """Object to interact with the mainframe FTP capabilities""" DEFAULT_TEMPORARY_PATH = '/tmp' def __init__(self, hostname, username, password, port=21, passive=True): self.hostname = hostname self.username = username self.password = password self.port = port ...
class FTP():
"""Object to interact with the mainframe FTP capabilities""" DEFAULT_TEMPORARY_PATH = '/tmp' def __init__(self, hostname, username, password, port=21, passive=True): self.hostname = hostname self.username = username self.password = password self.port = port self.pass...
"""FTP library exploiting the peculiar z/OS features""" import ftplib import io import string import random class FTP():
27
123
410
3
23
davidegirardi/zos-pivoting
zosutils/ftp.py
Python
FTP
FTP
8
57
8
8
2d39381c8520b08a93e899b47952d86bbc2becda
bigcode/the-stack
train
083c8b3b05f696dacf911d6b
train
class
class VulnerabilityAPITests(CairisDaemonTestCase): @classmethod def setUpClass(cls): importModelFile(os.environ['CAIRIS_SRC'] + '/../examples/exemplars/NeuroGrid/NeuroGrid.xml',1,'test') def setUp(self): # region Class fields self.logger = logging.getLogger(__name__) self....
class VulnerabilityAPITests(CairisDaemonTestCase): @classmethod
def setUpClass(cls): importModelFile(os.environ['CAIRIS_SRC'] + '/../examples/exemplars/NeuroGrid/NeuroGrid.xml',1,'test') def setUp(self): # region Class fields self.logger = logging.getLogger(__name__) self.existing_vulnerability_name = 'Replay vulnerability' self.exi...
to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the...
256
256
1,855
17
239
nebloc/cairis
cairis/test/test_VulnerabilityAPI.py
Python
VulnerabilityAPITests
VulnerabilityAPITests
35
208
35
37
9f7c600820d96a4de1ce1322e5f678f6812c520b
bigcode/the-stack
train
d72110bf5190c7b4a7c5808e
train
function
def loggly_time_string(date): formatted_dt = date.strftime("%Y-%m-%dT%H:%M:%S") milliseconds = str(round(date.microsecond * (10.0 ** -5), 3)) return quote(formatted_dt + milliseconds + "Z")
def loggly_time_string(date):
formatted_dt = date.strftime("%Y-%m-%dT%H:%M:%S") milliseconds = str(round(date.microsecond * (10.0 ** -5), 3)) return quote(formatted_dt + milliseconds + "Z")
"name": name, "amount": bid, "address": address, "txid": tx.id, "nout": txo.position, "value": claim_dict, "height": -1, "claim_sequence": -1, } def loggly_time_string(date):
64
64
59
7
57
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
loggly_time_string
loggly_time_string
5,659
5,662
5,659
5,659
5f079ca38f35e716152c0bac06aa28a9ee8ac11c
bigcode/the-stack
train
ed3679efe7f279e7d636143e
train
class
class Daemon(metaclass=JSONRPCServerType): """ LBRYnet daemon, a jsonrpc interface to lbry functions """ callable_methods: dict deprecated_methods: dict pending_requests_metric = Gauge( "pending_requests", "Number of running api requests", namespace="daemon_api", labelnames=("me...
class Daemon(metaclass=JSONRPCServerType):
""" LBRYnet daemon, a jsonrpc interface to lbry functions """ callable_methods: dict deprecated_methods: dict pending_requests_metric = Gauge( "pending_requests", "Number of running api requests", namespace="daemon_api", labelnames=("method",) ) requests_count_metric = ...
+ "\n" def trap(err, *to_trap): err.trap(*to_trap) class JSONRPCServerType(type): def __new__(mcs, name, bases, newattrs): klass = type.__new__(mcs, name, bases, newattrs) klass.callable_methods = {} klass.deprecated_methods = {} for methodname in dir(klass): if...
256
256
52,909
12
244
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
Daemon
Daemon
293
5,656
293
293
61f3b611620b64d7b225e06581718f75fcb11ce8
bigcode/the-stack
train
0cf784152669fb21dea13618
train
function
async def paginate_rows(get_records: Callable, get_record_count: Optional[Callable], page: Optional[int], page_size: Optional[int], **constraints): page = max(1, page or 1) page_size = max(1, page_size or DEFAULT_PAGE_SIZE) constraints.update({ "offset": page_size * (page - 1...
async def paginate_rows(get_records: Callable, get_record_count: Optional[Callable], page: Optional[int], page_size: Optional[int], **constraints):
page = max(1, page or 1) page_size = max(1, page_size or DEFAULT_PAGE_SIZE) constraints.update({ "offset": page_size * (page - 1), "limit": page_size }) items = await get_records(**constraints) result = {"items": items, "page": page, "page_size": page_size} if get_record_coun...
.", "total_pages": "Total number of pages.", "total_items": "Total number of items.", "items": [items], } async def paginate_rows(get_records: Callable, get_record_count: Optional[Callable], page: Optional[int], page_size: Optional[int], **constraints):
64
64
171
32
32
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
paginate_rows
paginate_rows
139
153
139
140
d1aba4ccd717774bdaabddafc38e268dd1e0e6b0
bigcode/the-stack
train
8f8bf3b93ba36128f57d3230
train
function
def is_transactional_function(name): for action in ('create', 'update', 'abandon', 'send', 'fund'): if action in name: return True
def is_transactional_function(name):
for action in ('create', 'update', 'abandon', 'send', 'fund'): if action in name: return True
lbry.extras.daemon.exchange_rate_manager import ExchangeRateManager from lbry.extras.daemon.storage import SQLiteStorage from lbry.wallet import WalletManager, Ledger from lbry.file.file_manager import FileManager log = logging.getLogger(__name__) def is_transactional_function(name):
64
64
37
7
57
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
is_transactional_function
is_transactional_function
68
71
68
68
8dc4244e44bff04561ccaedfdc744e597207af22
bigcode/the-stack
train
518fdf36b2afff2aab08dcb6
train
class
class DHTHasContacts(RequiredCondition): name = DHT_HAS_CONTACTS component = DHT_COMPONENT message = "your node is not connected to the dht" @staticmethod def evaluate(component): return len(component.contacts) > 0
class DHTHasContacts(RequiredCondition):
name = DHT_HAS_CONTACTS component = DHT_COMPONENT message = "your node is not connected to the dht" @staticmethod def evaluate(component): return len(component.contacts) > 0
"total_pages": int((total_items + (page_size - 1)) / page_size), "total_items": total_items, "page": page, "page_size": page_size } DHT_HAS_CONTACTS = "dht_has_contacts" class DHTHasContacts(RequiredCondition):
64
64
58
9
55
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
DHTHasContacts
DHTHasContacts
175
182
175
175
00b203cc267befa849f9eaa15a5a95502f5fb1df
bigcode/the-stack
train
c0cb5c7c727b73bb20d1725a
train
function
def deprecated(new_command=None): def _deprecated_wrapper(f): f.new_command = new_command f._deprecated = True return f return _deprecated_wrapper
def deprecated(new_command=None):
def _deprecated_wrapper(f): f.new_command = new_command f._deprecated = True return f return _deprecated_wrapper
if not component_manager.all_components_running(*components): raise ComponentsNotStartedError( f"the following required components have not yet started: {json.dumps(components)}" ) return method(*args, **kwargs) return _inner retu...
64
64
38
6
57
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
deprecated
deprecated
98
104
98
98
48e84c6d8116ce2753c57b5cc78fef8217b28809
bigcode/the-stack
train
3b9b2b7c1ca9030d79bc7595
train
class
class UnknownAPIMethodError(Exception): pass
class UnknownAPIMethodError(Exception):
pass
cls( cls.CODE_APPLICATION_ERROR, str(exception), { 'name': exception.__class__.__name__, 'traceback': cls.filter_traceback(traceback), 'command': command, 'args': args, 'kwargs': kwargs, } ) class UnknownAPI...
64
64
11
8
56
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
UnknownAPIMethodError
UnknownAPIMethodError
256
257
256
256
e2477a3fe070abb588cb68cf368182cbaa859a1c
bigcode/the-stack
train
78e6bbad4ac5c384f06c910f
train
class
class JSONRPCServerType(type): def __new__(mcs, name, bases, newattrs): klass = type.__new__(mcs, name, bases, newattrs) klass.callable_methods = {} klass.deprecated_methods = {} for methodname in dir(klass): if methodname.startswith("jsonrpc_"): method =...
class JSONRPCServerType(type):
def __new__(mcs, name, bases, newattrs): klass = type.__new__(mcs, name, bases, newattrs) klass.callable_methods = {} klass.deprecated_methods = {} for methodname in dir(klass): if methodname.startswith("jsonrpc_"): method = getattr(klass, methodname) ...
rpc": "2.0", "result": obj} return json.dumps(data, cls=JSONResponseEncoder, sort_keys=True, indent=2, **kwargs) + "\n" def trap(err, *to_trap): err.trap(*to_trap) class JSONRPCServerType(type):
64
64
136
7
57
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
JSONRPCServerType
JSONRPCServerType
272
285
272
272
9233aab7d6c759e29d59736cea32079f27556670
bigcode/the-stack
train
891bab17cd69a749564ad9d5
train
class
class JSONRPCError: # http://www.jsonrpc.org/specification#error_object CODE_PARSE_ERROR = -32700 # Invalid JSON. Error while parsing the JSON text. CODE_INVALID_REQUEST = -32600 # The JSON sent is not a valid Request object. CODE_METHOD_NOT_FOUND = -32601 # The method does not exist / is not availab...
class JSONRPCError: # http://www.jsonrpc.org/specification#error_object
CODE_PARSE_ERROR = -32700 # Invalid JSON. Error while parsing the JSON text. CODE_INVALID_REQUEST = -32600 # The JSON sent is not a valid Request object. CODE_METHOD_NOT_FOUND = -32601 # The method does not exist / is not available. CODE_INVALID_PARAMS = -32602 # Invalid method parameter(s). COD...
) total_items = len(items) offset = page_size * (page - 1) subitems = [] if offset <= total_items: subitems = items[offset:offset+page_size] return { "items": subitems, "total_pages": int((total_items + (page_size - 1)) / page_size), "total_items": total_items, ...
186
186
620
18
167
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
JSONRPCError
JSONRPCError
185
253
185
186
7e0007db9cc41f2ee4cf2c24545484cf1007458c
bigcode/the-stack
train
d8f5b4a523f788b3ad579830
train
function
def jsonrpc_dumps_pretty(obj, **kwargs): if isinstance(obj, JSONRPCError): data = {"jsonrpc": "2.0", "error": obj.to_dict()} else: data = {"jsonrpc": "2.0", "result": obj} return json.dumps(data, cls=JSONResponseEncoder, sort_keys=True, indent=2, **kwargs) + "\n"
def jsonrpc_dumps_pretty(obj, **kwargs):
if isinstance(obj, JSONRPCError): data = {"jsonrpc": "2.0", "error": obj.to_dict()} else: data = {"jsonrpc": "2.0", "result": obj} return json.dumps(data, cls=JSONResponseEncoder, sort_keys=True, indent=2, **kwargs) + "\n"
': exception.__class__.__name__, 'traceback': cls.filter_traceback(traceback), 'command': command, 'args': args, 'kwargs': kwargs, } ) class UnknownAPIMethodError(Exception): pass def jsonrpc_dumps_pretty(obj, **kwargs):
64
64
87
12
51
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
jsonrpc_dumps_pretty
jsonrpc_dumps_pretty
260
265
260
260
17235fbf977ff96af6f6c54b195e3bae4406b7bc
bigcode/the-stack
train
81b4299d745db1acc215855f
train
function
def get_loggly_query_string(installation_id): base_loggly_search_url = "https://lbry.loggly.com/search#" now = utils.now() yesterday = now - utils.timedelta(days=1) params = { 'terms': f'json.installation_id:{installation_id[:SHORT_ID_LEN]}*', 'from': loggly_time_string(yesterday), ...
def get_loggly_query_string(installation_id):
base_loggly_search_url = "https://lbry.loggly.com/search#" now = utils.now() yesterday = now - utils.timedelta(days=1) params = { 'terms': f'json.installation_id:{installation_id[:SHORT_ID_LEN]}*', 'from': loggly_time_string(yesterday), 'to': loggly_time_string(now) } dat...
(date): formatted_dt = date.strftime("%Y-%m-%dT%H:%M:%S") milliseconds = str(round(date.microsecond * (10.0 ** -5), 3)) return quote(formatted_dt + milliseconds + "Z") def get_loggly_query_string(installation_id):
64
64
108
10
54
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
get_loggly_query_string
get_loggly_query_string
5,665
5,675
5,665
5,665
af8d49aa7012a2e5a1bcdd9ed484064b30280f56
bigcode/the-stack
train
ef9685c5ba836a65eabd4633
train
function
def requires(*components, **conditions): if conditions and ["conditions"] != list(conditions.keys()): raise SyntaxError("invalid conditions argument") condition_names = conditions.get("conditions", []) def _wrap(method): @wraps(method) def _inner(*args, **kwargs): compon...
def requires(*components, **conditions):
if conditions and ["conditions"] != list(conditions.keys()): raise SyntaxError("invalid conditions argument") condition_names = conditions.get("conditions", []) def _wrap(method): @wraps(method) def _inner(*args, **kwargs): component_manager = args[0].component_manager ...
from lbry.file.file_manager import FileManager log = logging.getLogger(__name__) def is_transactional_function(name): for action in ('create', 'update', 'abandon', 'send', 'fund'): if action in name: return True def requires(*components, **conditions):
64
64
170
8
55
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
requires
requires
74
95
74
74
3ee603312d707e9ef4da9979bfb0e37dfbd75495
bigcode/the-stack
train
8d17df69bbc14d39a4703211
train
function
def paginate_list(items: List, page: Optional[int], page_size: Optional[int]): page = max(1, page or 1) page_size = max(1, page_size or DEFAULT_PAGE_SIZE) total_items = len(items) offset = page_size * (page - 1) subitems = [] if offset <= total_items: subitems = items[offset:offset+page_...
def paginate_list(items: List, page: Optional[int], page_size: Optional[int]):
page = max(1, page or 1) page_size = max(1, page_size or DEFAULT_PAGE_SIZE) total_items = len(items) offset = page_size * (page - 1) subitems = [] if offset <= total_items: subitems = items[offset:offset+page_size] return { "items": subitems, "total_pages": int((total...
_items = await get_record_count(**constraints) result["total_pages"] = int((total_items + (page_size - 1)) / page_size) result["total_items"] = total_items return result def paginate_list(items: List, page: Optional[int], page_size: Optional[int]):
64
64
142
18
45
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
paginate_list
paginate_list
156
169
156
156
46ed9fae7adf1b269a98cd6743de7fb713f50b34
bigcode/the-stack
train
8616b8121348d63d5f812d81
train
function
def trap(err, *to_trap): err.trap(*to_trap)
def trap(err, *to_trap):
err.trap(*to_trap)
", "error": obj.to_dict()} else: data = {"jsonrpc": "2.0", "result": obj} return json.dumps(data, cls=JSONResponseEncoder, sort_keys=True, indent=2, **kwargs) + "\n" def trap(err, *to_trap):
64
64
18
9
55
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
trap
trap
268
269
268
268
a70f5f5cfa6c1199243620f3000aa6db99421442
bigcode/the-stack
train
647a3f3d8ea7dbc3dd488494
train
function
def encode_pagination_doc(items): return { "page": "Page number of the current items.", "page_size": "Number of items to show on a page.", "total_pages": "Total number of pages.", "total_items": "Total number of items.", "items": [items], }
def encode_pagination_doc(items):
return { "page": "Page number of the current items.", "page_size": "Number of items to show on a page.", "total_pages": "Total number of pages.", "total_items": "Total number of items.", "items": [items], }
DOWNLOAD_TIMEOUT_CODE, 'Stream timed out') ] SHORT_ID_LEN = 20 MAX_UPDATE_FEE_ESTIMATE = 0.3 DEFAULT_PAGE_SIZE = 20 VALID_FULL_CLAIM_ID = re.compile('[0-9a-fA-F]{40}') def encode_pagination_doc(items):
63
64
68
7
56
molllyn1/lbry-sdk
lbry/extras/daemon/daemon.py
Python
encode_pagination_doc
encode_pagination_doc
129
136
129
129
119107356b2668fb332650d8941c651fa10d3530
bigcode/the-stack
train
b61f05a5d1879340ab6bfb8b
train
class
class StaticSerializer: _refs: Dict[object, Any] = {} # obj -> ref (dict, preferably dataclass) _defs: List[Any] = [] # (ref & def)[] (dict, preferably dataclass) def __init__(self) -> None: self._refs = {} # obj -> ref (dict, preferably dataclass) self._defs = [] # (ref & def)[] (dict, pr...
class StaticSerializer:
_refs: Dict[object, Any] = {} # obj -> ref (dict, preferably dataclass) _defs: List[Any] = [] # (ref & def)[] (dict, preferably dataclass) def __init__(self) -> None: self._refs = {} # obj -> ref (dict, preferably dataclass) self._defs = [] # (ref & def)[] (dict, preferably dataclass) ...
This is an "out" parameter**. The values it contains will be modified in-place. Returns: None ''' for event in reversed(old_events): if event.combine(new_event): return # no combination was possible old_events.append(new_event) class StaticSerializer:
65
65
218
4
61
martinfleis/bokeh
bokeh/document/document.py
Python
StaticSerializer
StaticSerializer
1,067
1,089
1,067
1,068
9806e0218a31f6124815b6add5f8e3ed307e9426
bigcode/the-stack
train
61e442b0a4e245197c43241f
train
function
def _combine_document_events(new_event: DocumentChangedEvent, old_events: List[DocumentChangedEvent]) -> None: ''' Attempt to combine a new event with a list of previous events. The ``old_event`` will be scanned in reverse, and ``.combine(new_event)`` will be called on each. If a combination can be made, t...
def _combine_document_events(new_event: DocumentChangedEvent, old_events: List[DocumentChangedEvent]) -> None:
''' Attempt to combine a new event with a list of previous events. The ``old_event`` will be scanned in reverse, and ``.combine(new_event)`` will be called on each. If a combination can be made, the function will return immediately. Otherwise, ``new_event`` will be appended to ``old_events``. ...
kwargs): @wraps(f) def invoke() -> None: return f(*args, **kwargs) return self._with_self_as_curdoc(invoke) return wrapper def _combine_document_events(new_event: DocumentChangedEvent, old_events: List[DocumentChangedEvent]) -> None:
64
64
205
24
39
martinfleis/bokeh
bokeh/document/document.py
Python
_combine_document_events
_combine_document_events
1,038
1,065
1,038
1,038
ba43d54d2cee8c6848beb36e494b8340bf7cc9b1
bigcode/the-stack
train
b5ed7592d85c0d0c6f937239
train
class
class Document: ''' The basic unit of serialization for Bokeh. Document instances collect Bokeh models (e.g. plots, layouts, widgets, etc.) so that they may be reflected into the BokehJS client runtime. Because models may refer to other models (e.g., a plot *has* a list of renderers), it is not gen...
class Document:
''' The basic unit of serialization for Bokeh. Document instances collect Bokeh models (e.g. plots, layouts, widgets, etc.) so that they may be reflected into the BokehJS client runtime. Because models may refer to other models (e.g., a plot *has* a list of renderers), it is not generally useful or...
RootRemovedEvent, SessionCallbackAdded, SessionCallbackRemoved, TitleChangedEvent, ) from .json import DocJson, PatchJson, RootsJson from .locking import UnlockedDocumentProxy from .models import DocumentModelManager from .modules import DocumentModuleManager from .util import initialize_references_json, i...
256
256
6,327
3
253
martinfleis/bokeh
bokeh/document/document.py
Python
Document
Document
124
1,035
124
124
bb2cf3d86bb11452f52c848de5eced9591f14aac
bigcode/the-stack
train
2b351935544c86dd1365052c
train
class
class DbModelTestCase(base.BaseTestCase): """DB model tests.""" def test_repr(self): """testing the string representation of 'model' classes.""" network = models_v2.Network(name="net_net", status="OK", admin_state_up=True) actual_repr_output = repr(net...
class DbModelTestCase(base.BaseTestCase):
"""DB model tests.""" def test_repr(self): """testing the string representation of 'model' classes.""" network = models_v2.Network(name="net_net", status="OK", admin_state_up=True) actual_repr_output = repr(network) exp_start_with = "<neutron.d...
.code) def test_port_prevents_subnet_deletion(self): with self.port() as p: self._delete('subnets', p['port']['fixed_ips'][0]['subnet_id'], expected_code=webob.exc.HTTPConflict.code) class DbModelTestCase(base.BaseTestCase):
64
64
156
10
54
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
DbModelTestCase
DbModelTestCase
4,045
4,058
4,045
4,045
ec90e8127b72b5255b8ad44d5daaa47c32447167
bigcode/the-stack
train
7fbc5ee1fabad2beb0ab4b11
train
function
def _fake_get_pagination_helper(self, request): return api_common.PaginationEmulatedHelper(request, self._primary_key)
def _fake_get_pagination_helper(self, request):
return api_common.PaginationEmulatedHelper(request, self._primary_key)
'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' def optional_ctx(obj, fallback): if not obj: return fallback() @contextlib.contextmanager def context_wrapper(): yield obj return context_wrapper() def _fake_get_pagination_helper(self, request):
64
64
27
11
53
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
_fake_get_pagination_helper
_fake_get_pagination_helper
58
59
58
58
5a96e215147d0a5e6c5f1187a44a9a7e013e9459
bigcode/the-stack
train
5df1bb94919db33cfc0470e5
train
class
class TestNetworksV2(NeutronDbPluginV2TestCase): # NOTE(cerberus): successful network update and delete are # effectively tested above def test_create_network(self): name = 'net1' keys = [('subnets', []), ('name', name), ('admin_state_up', True), ('status', se...
class TestNetworksV2(NeutronDbPluginV2TestCase): # NOTE(cerberus): successful network update and delete are # effectively tested above
def test_create_network(self): name = 'net1' keys = [('subnets', []), ('name', name), ('admin_state_up', True), ('status', self.net_create_status), ('shared', False)] with self.network(name=name) as net: for k, v in keys: self.assertEqual(net['netw...
_port_not_found(self, plugin): ctx = context.get_admin_context() with self.subnet() as subnet: with contextlib.nested( self.port(subnet=subnet, device_id='owner1'), mock.patch.object(plugin, 'delete_port') ) as (p, del_port): del_po...
256
256
4,963
37
219
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
TestNetworksV2
TestNetworksV2
1,839
2,354
1,839
1,841
2a761978902d0e05e2e5bc7965649ece67a47841
bigcode/the-stack
train
98dda19ae8b2ea97b1ea8174
train
class
class TestPortsV2(NeutronDbPluginV2TestCase): def test_create_port_json(self): keys = [('admin_state_up', True), ('status', self.port_create_status)] with self.port(name='myname') as port: for k, v in keys: self.assertEqual(port['port'][k], v) self.assertIn('m...
class TestPortsV2(NeutronDbPluginV2TestCase):
def test_create_port_json(self): keys = [('admin_state_up', True), ('status', self.port_create_status)] with self.port(name='myname') as port: for k, v in keys: self.assertEqual(port['port'][k], v) self.assertIn('mac_address', port['port']) ips = p...
self.deserialize(self.fmt, res) req = self.new_delete_request('networks', net['network']['id']) res = req.get_response(self.api) self.assertEqual(res.status_int, webob.exc.HTTPNoContent.code) def test_update_returns_200(self): with self.network() as net: req = self.new_...
256
256
11,730
15
241
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
TestPortsV2
TestPortsV2
782
1,836
782
782
497c60d37ba549ef55092f6b2d0700a357eb5fc6
bigcode/the-stack
train
d71fd5dd3f56bdd27bb4da96
train
class
class TestSubnetsV2(NeutronDbPluginV2TestCase): def _test_create_subnet(self, network=None, expected=None, **kwargs): keys = kwargs.copy() keys.setdefault('cidr', '10.0.0.0/24') keys.setdefault('ip_version', 4) keys.setdefault('enable_dhcp', True) with self.subnet(network=ne...
class TestSubnetsV2(NeutronDbPluginV2TestCase):
def _test_create_subnet(self, network=None, expected=None, **kwargs): keys = kwargs.copy() keys.setdefault('cidr', '10.0.0.0/24') keys.setdefault('ip_version', 4) keys.setdefault('enable_dhcp', True) with self.subnet(network=network, **keys) as subnet: # verify th...
ClientError.code], [True, True, webob.exc.HTTPCreated.code], ["True", True, webob.exc.HTTPCreated.code], ["true", True, webob.exc.HTTPCreated.code], [1, True, webob.exc.HTTPCreated.code], ["False", False, webob.exc.HTTPCreated.code], ...
256
256
18,745
16
240
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
TestSubnetsV2
TestSubnetsV2
2,357
4,042
2,357
2,358
19edda7ef5a82f8425304d0e430b3a2446955ea7
bigcode/the-stack
train
0283e9ab2b9de9833c6d48b4
train
class
class TestV2HTTPResponse(NeutronDbPluginV2TestCase): def test_create_returns_201(self): res = self._create_network(self.fmt, 'net2', True) self.assertEqual(res.status_int, webob.exc.HTTPCreated.code) def test_list_returns_200(self): req = self.new_list_request('networks') res = ...
class TestV2HTTPResponse(NeutronDbPluginV2TestCase):
def test_create_returns_201(self): res = self._create_network(self.fmt, 'net2', True) self.assertEqual(res.status_int, webob.exc.HTTPCreated.code) def test_list_returns_200(self): req = self.new_list_request('networks') res = req.get_response(self.api) self.assertEqual(r...
req = testlib_api.create_request(link['href'], '', content_type) self.assertEqual(len(res[resources]), limit) self.assertEqual(expected_page_num, page_num) ex...
256
256
865
16
240
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
TestV2HTTPResponse
TestV2HTTPResponse
690
779
690
690
241b6cb7b4c3b23716c0a0a480fd50a7b0558ec3
bigcode/the-stack
train
90f8eb787f9ae8df15baccdc
train
function
def optional_ctx(obj, fallback): if not obj: return fallback() @contextlib.contextmanager def context_wrapper(): yield obj return context_wrapper()
def optional_ctx(obj, fallback):
if not obj: return fallback() @contextlib.contextmanager def context_wrapper(): yield obj return context_wrapper()
import manager from neutron.tests import base from neutron.tests.unit import test_extensions from neutron.tests.unit import testlib_api from neutron.tests.unit import testlib_plugin DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' def optional_ctx(obj, fallback):
64
64
37
7
57
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
optional_ctx
optional_ctx
48
55
48
48
a6e43465d519a5761aa517172fe481779beaf4dc
bigcode/the-stack
train
290d7beeb5e87119fd56dc52
train
function
def _get_create_db_method(resource): ml2_method = '_create_%s_db' % resource if hasattr(manager.NeutronManager.get_plugin(), ml2_method): return ml2_method else: return 'create_%s' % resource
def _get_create_db_method(resource):
ml2_method = '_create_%s_db' % resource if hasattr(manager.NeutronManager.get_plugin(), ml2_method): return ml2_method else: return 'create_%s' % resource
self._attr_info) # TODO(banix): Move the following method to ML2 db test module when ML2 # mechanism driver unit tests are corrected to use Ml2PluginV2TestCase # instead of directly using NeutronDbPluginV2TestCase def _get_create_db_method(resource):
64
64
55
8
55
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
_get_create_db_method
_get_create_db_method
69
74
69
69
4b9ee29f56a72c10930eec3164d04dd17c3903cf
bigcode/the-stack
train
983a67b56a3612990064d38b
train
class
class NeutronDbPluginV2AsMixinTestCase(testlib_api.SqlTestCase): """Tests for NeutronDbPluginV2 as Mixin. While NeutronDbPluginV2TestCase checks NeutronDbPlugin and all plugins as a complete plugin, this test case verifies abilities of NeutronDbPlugin which are provided to other plugins (e.g. DB operat...
class NeutronDbPluginV2AsMixinTestCase(testlib_api.SqlTestCase):
"""Tests for NeutronDbPluginV2 as Mixin. While NeutronDbPluginV2TestCase checks NeutronDbPlugin and all plugins as a complete plugin, this test case verifies abilities of NeutronDbPlugin which are provided to other plugins (e.g. DB operations). This test case may include tests only for NeutronDbPlu...
:ffff:f2ef'], ['b', '2001::ffff:ffff:ffff:f2f1', '2001::ffff:ffff:ffff:ff0f'], ['b', '2001::ffff:ffff:ffff:ff11', '2001::ffff:ffff:ffff:fffe']] self._validate_rebuild_availability_ranges(pools, allocations, ...
106
106
355
18
88
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
NeutronDbPluginV2AsMixinTestCase
NeutronDbPluginV2AsMixinTestCase
4,173
4,205
4,173
4,173
4743efc379e07cdda4e2ff59098ec033d0fbad5e
bigcode/the-stack
train
a18b0290875a2e681941905e
train
class
class TestBasicGet(NeutronDbPluginV2TestCase): def test_single_get_admin(self): plugin = neutron.db.db_base_plugin_v2.NeutronDbPluginV2() with self.network() as network: net_id = network['network']['id'] ctx = context.get_admin_context() n = plugin._get_network(c...
class TestBasicGet(NeutronDbPluginV2TestCase):
def test_single_get_admin(self): plugin = neutron.db.db_base_plugin_v2.NeutronDbPluginV2() with self.network() as network: net_id = network['network']['id'] ctx = context.get_admin_context() n = plugin._get_network(ctx, net_id) self.assertEqual(net_id,...
self.assertEqual(expected_page_num, page_num) expected_res = [item[resource]['id'] for item in items] expected_res.reverse() self.assertEqual(expected_res, [n['id'] for n in item_res]) class TestBasicGet(NeutronDbPluginV2TestCase):
64
64
161
14
50
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
TestBasicGet
TestBasicGet
671
687
671
672
3dcc43afb9eeb97bec64dab47da0d1cf77b23e40
bigcode/the-stack
train
07c57e06fc79bf7c0fb015b7
train
class
class NeutronDbPluginV2TestCase(testlib_api.WebTestCase, testlib_plugin.PluginSetupHelper): fmt = 'json' resource_prefix_map = {} def setUp(self, plugin=None, service_plugins=None, ext_mgr=None): super(NeutronDbPluginV2TestCase, self).setUp() c...
class NeutronDbPluginV2TestCase(testlib_api.WebTestCase, testlib_plugin.PluginSetupHelper):
fmt = 'json' resource_prefix_map = {} def setUp(self, plugin=None, service_plugins=None, ext_mgr=None): super(NeutronDbPluginV2TestCase, self).setUp() cfg.CONF.set_override('notify_nova_on_port_status_changes', False) # Make sure at each test according extensions for ...
testlib_api from neutron.tests.unit import testlib_plugin DB_PLUGIN_KLASS = 'neutron.db.db_base_plugin_v2.NeutronDbPluginV2' def optional_ctx(obj, fallback): if not obj: return fallback() @contextlib.contextmanager def context_wrapper(): yield obj return context_wrapper() def _fak...
256
256
5,518
24
231
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
NeutronDbPluginV2TestCase
NeutronDbPluginV2TestCase
77
668
77
78
f683ef44c260e0252c1c3fd637add5f65f75542b
bigcode/the-stack
train
8226a5a96c6b886574162a52
train
class
class TestNeutronDbPluginV2(base.BaseTestCase): """Unit Tests for NeutronDbPluginV2 IPAM Logic.""" def test_generate_ip(self): with mock.patch.object(db_base_plugin_v2.NeutronDbPluginV2, '_try_generate_ip') as generate: with mock.patch.object(db_base_plugin_v2...
class TestNeutronDbPluginV2(base.BaseTestCase):
"""Unit Tests for NeutronDbPluginV2 IPAM Logic.""" def test_generate_ip(self): with mock.patch.object(db_base_plugin_v2.NeutronDbPluginV2, '_try_generate_ip') as generate: with mock.patch.object(db_base_plugin_v2.NeutronDbPluginV2, ...
): with self.port() as p: self._delete('networks', p['port']['network_id'], expected_code=webob.exc.HTTPConflict.code) def test_port_prevents_subnet_deletion(self): with self.port() as p: self._delete('subnets', p['port']['fixed_ips'][0]['subnet_id']...
256
256
1,183
13
243
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
TestNeutronDbPluginV2
TestNeutronDbPluginV2
4,061
4,170
4,061
4,061
1abfaead6401008b1e6d747e03540facab8199af
bigcode/the-stack
train
d28b61659addbe356ce5dabb
train
function
def _fake_get_sorting_helper(self, request): return api_common.SortingEmulatedHelper(request, self._attr_info)
def _fake_get_sorting_helper(self, request):
return api_common.SortingEmulatedHelper(request, self._attr_info)
: return fallback() @contextlib.contextmanager def context_wrapper(): yield obj return context_wrapper() def _fake_get_pagination_helper(self, request): return api_common.PaginationEmulatedHelper(request, self._primary_key) def _fake_get_sorting_helper(self, request):
64
64
27
11
53
Metaswitch/calico-neutron
neutron/tests/unit/test_db_plugin.py
Python
_fake_get_sorting_helper
_fake_get_sorting_helper
62
63
62
62
e75ff4198941166126e449916a785bf7e4854c9f
bigcode/the-stack
train