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
85625177d31fa6a5a0621427
train
class
class PreNorm(nn.Module): def __init__(self, norm_class, dim, fn): super().__init__() self.norm = norm_class(dim) self.fn = fn def forward(self, x, **kwargs): x = self.norm(x) return self.fn(x, **kwargs)
class PreNorm(nn.Module):
def __init__(self, norm_class, dim, fn): super().__init__() self.norm = norm_class(dim) self.fn = fn def forward(self, x, **kwargs): x = self.norm(x) return self.fn(x, **kwargs)
init__() self.g = nn.Parameter(torch.ones(1)) self.eps = eps def forward(self, x): n = torch.norm(x, dim=-1, keepdim=True).clamp(min=self.eps) return x / n * self.g class PreNorm(nn.Module):
64
64
65
6
57
wilson1yan/reformer-pytorch
reformer_pytorch/reformer_pytorch.py
Python
PreNorm
PreNorm
140
147
140
140
08cba7aac96a85b5ae6d1d87a99e483ca8e81a5b
bigcode/the-stack
train
3eab948a3c85b83aacd2b751
train
function
def sort_key_val(t1, t2, dim=-1): values, indices = t1.sort(dim=dim) t2 = t2.expand_as(t1) return values, t2.gather(dim, indices)
def sort_key_val(t1, t2, dim=-1):
values, indices = t1.sort(dim=dim) t2 = t2.expand_as(t1) return values, t2.gather(dim, indices)
itionalEmbedding from product_key_memory import PKM from reformer_pytorch.reversible import ReversibleSequence #constants TOKEN_SELF_ATTN_VALUE = -5e4 # carefully set for half precision to work # helper fns def sort_key_val(t1, t2, dim=-1):
64
64
49
14
49
wilson1yan/reformer-pytorch
reformer_pytorch/reformer_pytorch.py
Python
sort_key_val
sort_key_val
22
25
22
22
257f1c46763655c76e906d852ba9be9b826deed1
bigcode/the-stack
train
86b25f2ac4d9e869ea989c7f
train
class
class AbsolutePositionalEmbedding(nn.Module): def __init__(self, dim, max_seq_len): super().__init__() self.emb = nn.Embedding(max_seq_len, dim) def forward(self, x): t = torch.arange(x.shape[1], device=x.device) return self.emb(t)
class AbsolutePositionalEmbedding(nn.Module):
def __init__(self, dim, max_seq_len): super().__init__() self.emb = nn.Embedding(max_seq_len, dim) def forward(self, x): t = torch.arange(x.shape[1], device=x.device) return self.emb(t)
(x) else: x, v = self.w1(x).chunk(2, dim=-1) x = self.act(x) * v x = self.dropout(x) x = self.w2(x) return x # positional embeddings class AbsolutePositionalEmbedding(nn.Module):
64
64
66
8
55
wilson1yan/reformer-pytorch
reformer_pytorch/reformer_pytorch.py
Python
AbsolutePositionalEmbedding
AbsolutePositionalEmbedding
617
624
617
617
17d296766e5bdbbf03937d0e2dc4a63be1941b44
bigcode/the-stack
train
b4c4ee9e6d3bce3e6a7ed0ad
train
function
def chunked_sum(tensor, chunks=1): *orig_size, last_dim = tensor.shape tensor = tensor.reshape(-1, last_dim) summed_tensors = [c.sum(dim=-1) for c in tensor.chunk(chunks, dim=0)] return torch.cat(summed_tensors, dim=0).reshape(orig_size)
def chunked_sum(tensor, chunks=1):
*orig_size, last_dim = tensor.shape tensor = tensor.reshape(-1, last_dim) summed_tensors = [c.sum(dim=-1) for c in tensor.chunk(chunks, dim=0)] return torch.cat(summed_tensors, dim=0).reshape(orig_size)
]))), chunked_args) outputs = [fn(*c_args, **c_kwargs) for c_args, c_kwargs in all_args] return tuple(map(lambda x: torch.cat(x, dim=dim), zip(*outputs))) return inner_fn def chunked_sum(tensor, chunks=1):
64
64
74
11
52
wilson1yan/reformer-pytorch
reformer_pytorch/reformer_pytorch.py
Python
chunked_sum
chunked_sum
40
44
40
40
2c43d42a4dc37241e833759cf3ff7b3817080003
bigcode/the-stack
train
8bb440eaab64fcd48feaba79
train
function
def cast_tuple(x): return x if isinstance(x, tuple) else (x,)
def cast_tuple(x):
return x if isinstance(x, tuple) else (x,)
summed_tensors = [c.sum(dim=-1) for c in tensor.chunk(chunks, dim=0)] return torch.cat(summed_tensors, dim=0).reshape(orig_size) def default(val, default_val): return default_val if val is None else val def cast_tuple(x):
64
64
18
5
58
wilson1yan/reformer-pytorch
reformer_pytorch/reformer_pytorch.py
Python
cast_tuple
cast_tuple
49
50
49
49
a181fbdf0fa90489873a72515705329ef0cedd80
bigcode/the-stack
train
8dd007e77d8a096ba0551816
train
class
class Reformer(nn.Module): def __init__(self, dim, depth, max_seq_len, heads = 8, dim_head = None, bucket_size = 64, n_hashes = 8, ff_chunks = 100, attn_chunks = None, causal = False, weight_tie = False, lsh_dropout = 0., ff_dropout = 0., ff_activation = None, f...
class Reformer(nn.Module):
def __init__(self, dim, depth, max_seq_len, heads = 8, dim_head = None, bucket_size = 64, n_hashes = 8, ff_chunks = 100, attn_chunks = None, causal = False, weight_tie = False, lsh_dropout = 0., ff_dropout = 0., ff_activation = None, ff_mult = 4, ff_glu = False,...
v x = self.dropout(x) x = self.w2(x) return x # positional embeddings class AbsolutePositionalEmbedding(nn.Module): def __init__(self, dim, max_seq_len): super().__init__() self.emb = nn.Embedding(max_seq_len, dim) def forward(self, x): t = torch.arange(x.sha...
244
244
816
6
237
wilson1yan/reformer-pytorch
reformer_pytorch/reformer_pytorch.py
Python
Reformer
Reformer
640
714
640
640
1146e3b1b24a47a163b15330633cd1225a6ddea5
bigcode/the-stack
train
23e90950ec90c85e538ebc5f
train
function
def cache_fn(f): cache = None @wraps(f) def cached_fn(*args, **kwargs): nonlocal cache if cache is not None: return cache cache = f(*args, **kwargs) return cache return cached_fn
def cache_fn(f):
cache = None @wraps(f) def cached_fn(*args, **kwargs): nonlocal cache if cache is not None: return cache cache = f(*args, **kwargs) return cache return cached_fn
(orig_size) def default(val, default_val): return default_val if val is None else val def cast_tuple(x): return x if isinstance(x, tuple) else (x,) def max_neg_value(tensor): return -torch.finfo(tensor.dtype).max def cache_fn(f):
64
64
61
5
58
wilson1yan/reformer-pytorch
reformer_pytorch/reformer_pytorch.py
Python
cache_fn
cache_fn
55
64
55
55
21b8f38bbe955f7d90568fc0d6ad3fa6a29fcc12
bigcode/the-stack
train
5fef1c3da3acb80a1485969d
train
function
def mkpath(*parts): return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', *parts))
def mkpath(*parts):
return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', *parts))
# encoding: utf-8 import os from datetime import datetime, timedelta from django.conf import settings from django.core.management.base import BaseCommand from django.utils.timezone import now from dateutil.tz import tzlocal from core.utils import slugify def mkpath(*parts):
62
64
27
6
55
Siikakala/kompassi
events/animecon2016/management/commands/setup_animecon2016.py
Python
mkpath
mkpath
17
18
17
17
1dfd0d9d3327c7b52736bc2532090c7453428dae
bigcode/the-stack
train
30a46d52066a7f4d16fcabd5
train
class
class Setup(object): def __init__(self): self._ordering = 0 def get_ordering_number(self): self._ordering += 10 return self._ordering def setup(self, test=False): self.test = test self.tz = tzlocal() self.setup_core() self.setup_labour() self...
class Setup(object):
def __init__(self): self._ordering = 0 def get_ordering_number(self): self._ordering += 10 return self._ordering def setup(self, test=False): self.test = test self.tz = tzlocal() self.setup_core() self.setup_labour() self.setup_tickets() ...
# encoding: utf-8 import os from datetime import datetime, timedelta from django.conf import settings from django.core.management.base import BaseCommand from django.utils.timezone import now from dateutil.tz import tzlocal from core.utils import slugify def mkpath(*parts): return os.path.abspath(os.path.jo...
87
256
5,062
4
83
Siikakala/kompassi
events/animecon2016/management/commands/setup_animecon2016.py
Python
Setup
Setup
21
501
21
21
25ecb8a447472b203d04eecb71dbccce08002c9f
bigcode/the-stack
train
a40aa38640d9d3ea0e4d8b5b
train
class
class Command(BaseCommand): args = '' help = 'Setup animecon2016 specific stuff' def handle(self, *args, **opts): Setup().setup(test=settings.DEBUG)
class Command(BaseCommand):
args = '' help = 'Setup animecon2016 specific stuff' def handle(self, *args, **opts): Setup().setup(test=settings.DEBUG)
_admin_group, = BadgesEventMeta.get_or_create_groups(self.event, ['admins']) meta, unused = BadgesEventMeta.objects.get_or_create( event=self.event, defaults=dict( admin_group=badge_admin_group, badge_layout='nick', ) ) class Command(Ba...
64
64
40
5
59
Siikakala/kompassi
events/animecon2016/management/commands/setup_animecon2016.py
Python
Command
Command
504
509
504
504
591c3e843003255cf344d7eaecd0167931a692fb
bigcode/the-stack
train
9a43bca354876c0b2547679d
train
function
def get_backend(find_library=None): global _lib try: if _lib is None: _lib = _load_library(find_library=find_library) _setup_prototypes(_lib) return _LibUSB(_lib) except usb.libloader.LibraryException: # exception already logged (if any) _logger.error(...
def get_backend(find_library=None):
global _lib try: if _lib is None: _lib = _load_library(find_library=find_library) _setup_prototypes(_lib) return _LibUSB(_lib) except usb.libloader.LibraryException: # exception already logged (if any) _logger.error('Error loading libusb 1.0 backend', ...
(c_ubyte)), length, byref(transferred), timeout) # do not assume LIBUSB_ERROR_TIMEOUT means no I/O. if not (transferred.value and retval == LIBUSB_ERROR_TIMEOUT): _check(retval) return transferred.value def get_backend(find_librar...
64
64
117
7
56
yawara/pyusb
usb/backend/libusb1.py
Python
get_backend
get_backend
938
951
938
938
27c290e583c375365882387dd6083ecdef652dc1
bigcode/the-stack
train
856d8362da3a52e9616ff62e
train
class
class _libusb_iso_packet_descriptor(Structure): _fields_ = [('length', c_uint), ('actual_length', c_uint), ('status', c_int)] # enum libusb_transfer_status
class _libusb_iso_packet_descriptor(Structure):
_fields_ = [('length', c_uint), ('actual_length', c_uint), ('status', c_int)] # enum libusb_transfer_status
bcdDevice', c_uint16), ('iManufacturer', c_uint8), ('iProduct', c_uint8), ('iSerialNumber', c_uint8), ('bNumConfigurations', c_uint8)] # Isochronous packet descriptor. class _libusb_iso_packet_descriptor(Structure):
64
64
43
10
54
yawara/pyusb
usb/backend/libusb1.py
Python
_libusb_iso_packet_descriptor
_libusb_iso_packet_descriptor
226
229
226
226
645ac9ed75ed38045e0a5c1700c5f3c4ace0e502
bigcode/the-stack
train
36486004b85e32e1634c5e63
train
class
class _IsoTransferHandler(_objfinalizer.AutoFinalizedObject): def __init__(self, dev_handle, ep, buff, timeout): address, length = buff.buffer_info() packet_length = _lib.libusb_get_max_iso_packet_size(dev_handle.devid, ep) packet_count = int(math.ceil(float(length) / packet_length)) ...
class _IsoTransferHandler(_objfinalizer.AutoFinalizedObject):
def __init__(self, dev_handle, ep, buff, timeout): address, length = buff.buffer_info() packet_length = _lib.libusb_get_max_iso_packet_size(dev_handle.devid, ep) packet_count = int(math.ceil(float(length) / packet_length)) self.transfer = _lib.libusb_alloc_transfer(packet_count) ...
byref(self.dev_list)) ) def __iter__(self): for i in range(self.num_devs): yield _Device(self.dev_list[i]) def _finalize_object(self): _lib.libusb_free_device_list(self.dev_list, 1) class _DeviceHandle(object): def __init__(self, dev): se...
124
124
415
14
110
yawara/pyusb
usb/backend/libusb1.py
Python
_IsoTransferHandler
_IsoTransferHandler
636
690
636
636
ef8aebaa297e01268d318d5606718cd475804699
bigcode/the-stack
train
d7741023acf60f9c3bc8a334
train
class
class _libusb_interface(Structure): _fields_ = [('altsetting', POINTER(_libusb_interface_descriptor)), ('num_altsetting', c_int)]
class _libusb_interface(Structure):
_fields_ = [('altsetting', POINTER(_libusb_interface_descriptor)), ('num_altsetting', c_int)]
InterfaceSubClass', c_uint8), ('bInterfaceProtocol', c_uint8), ('iInterface', c_uint8), ('endpoint', POINTER(_libusb_endpoint_descriptor)), ('extra', POINTER(c_ubyte)), ('extra_length', c_int)] class _libusb_interface(Structure):
64
64
33
8
56
yawara/pyusb
usb/backend/libusb1.py
Python
_libusb_interface
_libusb_interface
191
193
191
191
d4ad44d081c4144180de6e52ee358063c0689a30
bigcode/the-stack
train
a7820f44b3a6f209c0e53dc3
train
class
class _DevIterator(_objfinalizer.AutoFinalizedObject): def __init__(self, ctx): self.dev_list = POINTER(c_void_p)() self.num_devs = _check(_lib.libusb_get_device_list( ctx, byref(self.dev_list)) )...
class _DevIterator(_objfinalizer.AutoFinalizedObject):
def __init__(self, ctx): self.dev_list = POINTER(c_void_p)() self.num_devs = _check(_lib.libusb_get_device_list( ctx, byref(self.dev_list)) ) def __iter__(self): for i in range(self.nu...
self.desc = desc def _finalize_object(self): _lib.libusb_free_config_descriptor(self.desc) def __getattr__(self, name): return getattr(self.desc.contents, name) # iterator for libusb devices class _DevIterator(_objfinalizer.AutoFinalizedObject):
64
64
112
13
50
yawara/pyusb
usb/backend/libusb1.py
Python
_DevIterator
_DevIterator
617
628
617
617
b271e26a871275a13f12b5c30d13d78e340fa5a5
bigcode/the-stack
train
eb63fafd545a3d92aa928e27
train
class
class _libusb_transfer(Structure): pass
class _libusb_transfer(Structure):
pass
packet descriptor. class _libusb_iso_packet_descriptor(Structure): _fields_ = [('length', c_uint), ('actual_length', c_uint), ('status', c_int)] # enum libusb_transfer_status _libusb_device_handle = c_void_p class _libusb_transfer(Structure):
64
64
11
8
55
yawara/pyusb
usb/backend/libusb1.py
Python
_libusb_transfer
_libusb_transfer
233
234
233
233
62b053d6ffb3af817b56f52ca3dcf9e690f098a8
bigcode/the-stack
train
45024e288636c3bf4b9e7954
train
class
class _libusb_device_descriptor(Structure): _fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bcdUSB', c_uint16), ('bDeviceClass', c_uint8), ('bDeviceSubClass', c_uint8), ('bDeviceProtocol', c_uint8), ('b...
class _libusb_device_descriptor(Structure):
_fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bcdUSB', c_uint16), ('bDeviceClass', c_uint8), ('bDeviceSubClass', c_uint8), ('bDeviceProtocol', c_uint8), ('bMaxPacketSize0', c_uint8), (...
('iConfiguration', c_uint8), ('bmAttributes', c_uint8), ('bMaxPower', c_uint8), ('interface', POINTER(_libusb_interface)), ('extra', POINTER(c_ubyte)), ('extra_length', c_int)] class _libusb_device_descriptor(Structure):
64
64
151
9
55
yawara/pyusb
usb/backend/libusb1.py
Python
_libusb_device_descriptor
_libusb_device_descriptor
208
222
208
208
955bae50ed54ece5db25dce7cffe2f15a0d18df6
bigcode/the-stack
train
ee545c92c74de1b0a213ad4c
train
class
class _ConfigDescriptor(_objfinalizer.AutoFinalizedObject): def __init__(self, desc): self.desc = desc def _finalize_object(self): _lib.libusb_free_config_descriptor(self.desc) def __getattr__(self, name): return getattr(self.desc.contents, name)
class _ConfigDescriptor(_objfinalizer.AutoFinalizedObject):
def __init__(self, desc): self.desc = desc def _finalize_object(self): _lib.libusb_free_config_descriptor(self.desc) def __getattr__(self, name): return getattr(self.desc.contents, name)
(object): def __init__(self, desc, obj = None): self.obj = obj self.desc = desc def __getattr__(self, name): return getattr(self.desc, name) # wrap a configuration descriptor class _ConfigDescriptor(_objfinalizer.AutoFinalizedObject):
64
64
67
13
50
yawara/pyusb
usb/backend/libusb1.py
Python
_ConfigDescriptor
_ConfigDescriptor
607
613
607
607
dc4e2ace632a54eb5b680463242af1ec133375c8
bigcode/the-stack
train
e63fca936c33e5d9a98e799d
train
function
def _check(ret): if hasattr(ret, 'value'): ret = ret.value if ret < 0: if ret == LIBUSB_ERROR_NOT_SUPPORTED: raise NotImplementedError(_strerror(ret)) else: raise USBError(_strerror(ret), ret, _libusb_errno[ret]) return ret
def _check(ret):
if hasattr(ret, 'value'): ret = ret.value if ret < 0: if ret == LIBUSB_ERROR_NOT_SUPPORTED: raise NotImplementedError(_strerror(ret)) else: raise USBError(_strerror(ret), ret, _libusb_errno[ret]) return ret
lib.libusb_get_port_numbers.restype = c_int except AttributeError: pass #int libusb_handle_events(libusb_context *ctx); lib.libusb_handle_events.argtypes = [c_void_p] # check a libusb function call def _check(ret):
64
64
71
5
58
yawara/pyusb
usb/backend/libusb1.py
Python
_check
_check
578
588
578
578
ac77d779978df71a69ad8176deae4dd1bde92237
bigcode/the-stack
train
eef0808182342f091de42676
train
function
def _setup_prototypes(lib): # void libusb_set_debug (libusb_context *ctx, int level) lib.libusb_set_debug.argtypes = [c_void_p, c_int] # int libusb_init (libusb_context **context) lib.libusb_init.argtypes = [POINTER(c_void_p)] # void libusb_exit (struct libusb_context *ctx) lib.libusb_exit.arg...
def _setup_prototypes(lib): # void libusb_set_debug (libusb_context *ctx, int level)
lib.libusb_set_debug.argtypes = [c_void_p, c_int] # int libusb_init (libusb_context **context) lib.libusb_init.argtypes = [POINTER(c_void_p)] # void libusb_exit (struct libusb_context *ctx) lib.libusb_exit.argtypes = [c_void_p] # ssize_t libusb_get_device_list (libusb_context *ctx, # ...
_descriptor) ] def _get_iso_packet_list(transfer): list_type = _libusb_iso_packet_descriptor * transfer.num_iso_packets return list_type.from_address(addressof(transfer.iso_packet_desc)) _lib = None def _load_library(find_library=None): # Windows backend uses stdcall calling convention # # On Fre...
256
256
2,434
24
232
yawara/pyusb
usb/backend/libusb1.py
Python
_setup_prototypes
_setup_prototypes
277
575
277
278
25a77087e0f46da6c2ff37ae7d3a9fff47c23ba6
bigcode/the-stack
train
2f6ec1327a62f2b479bb1a4c
train
class
class _DeviceHandle(object): def __init__(self, dev): self.handle = _libusb_device_handle() self.devid = dev.devid _check(_lib.libusb_open(self.devid, byref(self.handle)))
class _DeviceHandle(object):
def __init__(self, dev): self.handle = _libusb_device_handle() self.devid = dev.devid _check(_lib.libusb_open(self.devid, byref(self.handle)))
byref(self.dev_list)) ) def __iter__(self): for i in range(self.num_devs): yield _Device(self.dev_list[i]) def _finalize_object(self): _lib.libusb_free_device_list(self.dev_list, 1) class _DeviceHandle(object):
64
64
52
6
58
yawara/pyusb
usb/backend/libusb1.py
Python
_DeviceHandle
_DeviceHandle
630
634
630
630
20965ba8e42e38e0189100a0f1c3d9e269e6655b
bigcode/the-stack
train
a62990e7b685fa11df12c483
train
class
class _libusb_config_descriptor(Structure): _fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('wTotalLength', c_uint16), ('bNumInterfaces', c_uint8), ('bConfigurationValue', c_uint8), ('iConfiguration', c_uint8), ...
class _libusb_config_descriptor(Structure):
_fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('wTotalLength', c_uint16), ('bNumInterfaces', c_uint8), ('bConfigurationValue', c_uint8), ('iConfiguration', c_uint8), ('bmAttributes', c_uint8), ...
usb_endpoint_descriptor)), ('extra', POINTER(c_ubyte)), ('extra_length', c_int)] class _libusb_interface(Structure): _fields_ = [('altsetting', POINTER(_libusb_interface_descriptor)), ('num_altsetting', c_int)] class _libusb_config_descriptor(Structure):
64
64
118
9
55
yawara/pyusb
usb/backend/libusb1.py
Python
_libusb_config_descriptor
_libusb_config_descriptor
195
206
195
195
d694a5de8ad70c7a91e26235c51f50f5098cdd1d
bigcode/the-stack
train
d63e2cb983ec792318adf5f6
train
class
class _libusb_endpoint_descriptor(Structure): _fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bEndpointAddress', c_uint8), ('bmAttributes', c_uint8), ('wMaxPacketSize', c_uint16), ('bInterval', c_uint8), ...
class _libusb_endpoint_descriptor(Structure):
_fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bEndpointAddress', c_uint8), ('bmAttributes', c_uint8), ('wMaxPacketSize', c_uint16), ('bInterval', c_uint8), ('bRefresh', c_uint8), ('bSy...
get('EOVERFLOW', None) } def _strerror(errcode): try: return _lib.libusb_strerror(errcode).decode('utf8') except AttributeError: return _str_error_map[errcode] # Data structures class _libusb_endpoint_descriptor(Structure):
64
64
109
9
54
yawara/pyusb
usb/backend/libusb1.py
Python
_libusb_endpoint_descriptor
_libusb_endpoint_descriptor
165
175
165
165
590edc5fabaff5292b4c187f2bd77b6b940c06b7
bigcode/the-stack
train
746b8bd74f523161202e05bf
train
function
def _strerror(errcode): try: return _lib.libusb_strerror(errcode).decode('utf8') except AttributeError: return _str_error_map[errcode]
def _strerror(errcode):
try: return _lib.libusb_strerror(errcode).decode('utf8') except AttributeError: return _str_error_map[errcode]
LIBUSB_TRANSFER_STALL:errno.__dict__.get('EIO', None), LIBUSB_TRANSFER_NO_DEVICE:errno.__dict__.get('ENODEV', None), LIBUSB_TRANSFER_OVERFLOW:errno.__dict__.get('EOVERFLOW', None) } def _strerror(errcode):
64
64
42
7
57
yawara/pyusb
usb/backend/libusb1.py
Python
_strerror
_strerror
157
161
157
157
b060b8116cc50ec4aa97986eb5f614ede40aa989
bigcode/the-stack
train
e28f4bc9a6b775051d0ff4d6
train
function
def _get_iso_packet_list(transfer): list_type = _libusb_iso_packet_descriptor * transfer.num_iso_packets return list_type.from_address(addressof(transfer.iso_packet_desc))
def _get_iso_packet_list(transfer):
list_type = _libusb_iso_packet_descriptor * transfer.num_iso_packets return list_type.from_address(addressof(transfer.iso_packet_desc))
', c_int), ('callback', _libusb_transfer_cb_fn_p), ('user_data', py_object), ('buffer', c_void_p), ('num_iso_packets', c_int), ('iso_packet_desc', _libusb_iso_packet_descripto...
64
64
40
9
55
yawara/pyusb
usb/backend/libusb1.py
Python
_get_iso_packet_list
_get_iso_packet_list
254
256
254
254
546f959ecdc0a5aacb3c9b35cb5118f5a129e2bb
bigcode/the-stack
train
2a35df12521dc6ec80306323
train
class
class _WrapDescriptor(object): def __init__(self, desc, obj = None): self.obj = obj self.desc = desc def __getattr__(self, name): return getattr(self.desc, name)
class _WrapDescriptor(object):
def __init__(self, desc, obj = None): self.obj = obj self.desc = desc def __getattr__(self, name): return getattr(self.desc, name)
devid): self.devid = _lib.libusb_ref_device(devid) def _finalize_object(self): _lib.libusb_unref_device(self.devid) # wrap a descriptor and keep a reference to another object # Thanks to Thomas Reitmayr. class _WrapDescriptor(object):
64
64
49
6
58
yawara/pyusb
usb/backend/libusb1.py
Python
_WrapDescriptor
_WrapDescriptor
599
604
599
599
a31351822e0b88aa9fd8921fd97caae54ace4b98
bigcode/the-stack
train
111ba6b51ba2069d92883ee8
train
class
class _Device(_objfinalizer.AutoFinalizedObject): def __init__(self, devid): self.devid = _lib.libusb_ref_device(devid) def _finalize_object(self): _lib.libusb_unref_device(self.devid)
class _Device(_objfinalizer.AutoFinalizedObject):
def __init__(self, devid): self.devid = _lib.libusb_ref_device(devid) def _finalize_object(self): _lib.libusb_unref_device(self.devid)
0: if ret == LIBUSB_ERROR_NOT_SUPPORTED: raise NotImplementedError(_strerror(ret)) else: raise USBError(_strerror(ret), ret, _libusb_errno[ret]) return ret # wrap a device class _Device(_objfinalizer.AutoFinalizedObject):
64
64
56
12
51
yawara/pyusb
usb/backend/libusb1.py
Python
_Device
_Device
591
595
591
591
6c64dd5f718d5fbc415a4a140f7ef48d9496ad48
bigcode/the-stack
train
32b3e67779e73bdc64e62286
train
function
def _load_library(find_library=None): # Windows backend uses stdcall calling convention # # On FreeBSD 8/9, libusb 1.0 and libusb 0.1 are in the same shared # object libusb.so, so if we found libusb library name, we must assure # it is 1.0 version. We just try to get some symbol from 1.0 version ...
def _load_library(find_library=None): # Windows backend uses stdcall calling convention # # On FreeBSD 8/9, libusb 1.0 and libusb 0.1 are in the same shared # object libusb.so, so if we found libusb library name, we must assure # it is 1.0 version. We just try to get some symbol from 1.0 version
if sys.platform == 'win32': win_cls = WinDLL else: win_cls = None return usb.libloader.load_locate_library( ('usb-1.0', 'libusb-1.0', 'usb'), 'cygusb-1.0.dll', 'Libusb 1', win_cls=win_cls, find_library=find_library, check_symbo...
def _load_library(find_library=None): # Windows backend uses stdcall calling convention # # On FreeBSD 8/9, libusb 1.0 and libusb 0.1 are in the same shared # object libusb.so, so if we found libusb library name, we must assure # it is 1.0 version. We just try to get some symbol from 1.0 version
93
64
185
93
0
yawara/pyusb
usb/backend/libusb1.py
Python
_load_library
_load_library
260
275
260
265
e525f5c6723839823d69a7ebc9c33ffc670aba6c
bigcode/the-stack
train
30d0daf9f318ef3990a84266
train
class
class _libusb_interface_descriptor(Structure): _fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bInterfaceNumber', c_uint8), ('bAlternateSetting', c_uint8), ('bNumEndpoints', c_uint8), ('bInterfaceClass', c_uint8), ...
class _libusb_interface_descriptor(Structure):
_fields_ = [('bLength', c_uint8), ('bDescriptorType', c_uint8), ('bInterfaceNumber', c_uint8), ('bAlternateSetting', c_uint8), ('bNumEndpoints', c_uint8), ('bInterfaceClass', c_uint8), ('bInterfaceSubClass', c_uint8), ...
MaxPacketSize', c_uint16), ('bInterval', c_uint8), ('bRefresh', c_uint8), ('bSynchAddress', c_uint8), ('extra', POINTER(c_ubyte)), ('extra_length', c_int)] class _libusb_interface_descriptor(Structure):
64
64
131
9
55
yawara/pyusb
usb/backend/libusb1.py
Python
_libusb_interface_descriptor
_libusb_interface_descriptor
177
189
177
177
ef73f8637fe5817b78f3256d12b153199df3a504
bigcode/the-stack
train
d12090839c370decf7a7e01c
train
class
class _LibUSB(usb.backend.IBackend): @methodtrace(_logger) def __init__(self, lib): usb.backend.IBackend.__init__(self) self.lib = lib self.ctx = c_void_p() _check(self.lib.libusb_init(byref(self.ctx))) @methodtrace(_logger) def _finalize_object(self): self.lib.l...
class _LibUSB(usb.backend.IBackend): @methodtrace(_logger)
def __init__(self, lib): usb.backend.IBackend.__init__(self) self.lib = lib self.ctx = c_void_p() _check(self.lib.libusb_init(byref(self.ctx))) @methodtrace(_logger) def _finalize_object(self): self.lib.libusb_exit(self.ctx) @methodtrace(_logger) def enumer...
= 0 _check(_lib.libusb_submit_transfer(self.transfer)) while not self.__callback_done: _check(_lib.libusb_handle_events(ctx)) status = int(self.transfer.contents.status) if status != LIBUSB_TRANSFER_COMPLETED: raise usb.USBError(_str_transfer_error[status], ...
256
256
1,850
17
238
yawara/pyusb
usb/backend/libusb1.py
Python
_LibUSB
_LibUSB
693
936
693
694
ad72356b572685803281a34a879610feb650e72d
bigcode/the-stack
train
4277401b7e730e6b5fe8485f
train
function
def loading_banner(screen, stuff) : global etc screen.fill((0,0,0)) font = pygame.font.Font("./font.ttf", 150) text = font.render("ETC", True, (255,255,255)) textpos = text.get_rect() textpos.centerx = screen.get_width() / 2 textpos.centery = screen.get_height() /2 screen.blit(...
def loading_banner(screen, stuff) :
global etc screen.fill((0,0,0)) font = pygame.font.Font("./font.ttf", 150) text = font.render("ETC", True, (255,255,255)) textpos = text.get_rect() textpos.centerx = screen.get_width() / 2 textpos.centery = screen.get_height() /2 screen.blit(text, textpos) font = pygame.fo...
0) if i == 14 : color = etc.RED x = offx + 14 * i pygame.draw.rect(screen, color, (x + 1, offy + 1, 9, 29)) # loading banner helper def loading_banner(screen, stuff) :
64
64
164
8
55
henning/ETC_Mother
osd.py
Python
loading_banner
loading_banner
37
54
37
37
04b63c4eb57dd58ed56ca9ab5a8e8b0190d84959
bigcode/the-stack
train
6fc50920917a7a3bfb2f0770
train
function
def draw_knob_slider(screen, etc, offx, offy, index) : if etc.knob_override[index]: color = etc.RED else : color = etc.WHITE pygame.draw.line(screen, color, [offx, offy], [offx + 16, offy], 1) pygame.draw.line(screen, color, [offx, offy], [offx, offy + 40], 1) pygame.draw.line(screen...
def draw_knob_slider(screen, etc, offx, offy, index) :
if etc.knob_override[index]: color = etc.RED else : color = etc.WHITE pygame.draw.line(screen, color, [offx, offy], [offx + 16, offy], 1) pygame.draw.line(screen, color, [offx, offy], [offx, offy + 40], 1) pygame.draw.line(screen, color, [offx + 16, offy], [offx + 16, offy + 40], 1) ...
import pygame import socket etc = None def init(etc_obj) : global etc etc = etc_obj def draw_knob_slider(screen, etc, offx, offy, index) :
45
64
204
18
26
henning/ETC_Mother
osd.py
Python
draw_knob_slider
draw_knob_slider
10
19
10
10
744c4fa314f43dc21ef55519e1a356ed9814f88e
bigcode/the-stack
train
2014fa0b3bf7b16ef4f05e57
train
function
def draw_vu(screen, etc, offx, offy): color = etc.WHITE for i in range(0,15) : x = offx + 14 * i pygame.draw.line(screen, color, [x, offy], [x + 10, offy], 1) pygame.draw.line(screen, color, [x, offy], [x, offy + 30], 1) pygame.draw.line(screen, color, [x + 10, offy], [x + 10, of...
def draw_vu(screen, etc, offx, offy):
color = etc.WHITE for i in range(0,15) : x = offx + 14 * i pygame.draw.line(screen, color, [x, offy], [x + 10, offy], 1) pygame.draw.line(screen, color, [x, offy], [x, offy + 30], 1) pygame.draw.line(screen, color, [x + 10, offy], [x + 10, offy + 30], 1) pygame.draw.line(...
40], [offx + 16, offy + 40], 1) pygame.draw.rect(screen, color, (offx, offy + 40 - int(40*etc.knob[index]), 16, int(40*etc.knob[index]))) def draw_vu(screen, etc, offx, offy):
72
73
245
14
58
henning/ETC_Mother
osd.py
Python
draw_vu
draw_vu
21
34
21
21
743c50468a0204756e9bcf90c338c8fd34e09a57
bigcode/the-stack
train
bad47c32c6244752e93723ee
train
function
def render_overlay(screen) : global etc font = pygame.font.Font("font.ttf", 32) # first time through, gather some info if etc.osd_first : etc.ip = socket.gethostbyname(socket.gethostname()) etc.osd_first = False # mode mode_str = " Mode: " + str(etc.mode) + " (" + str(etc....
def render_overlay(screen) :
global etc font = pygame.font.Font("font.ttf", 32) # first time through, gather some info if etc.osd_first : etc.ip = socket.gethostbyname(socket.gethostname()) etc.osd_first = False # mode mode_str = " Mode: " + str(etc.mode) + " (" + str(etc.mode_index + 1) +" of "+str(l...
0, etc.audio_peak / 2048): if i > 8 : color = (255,255,0) if i == 14 : color = etc.RED x = offx + 14 * i pygame.draw.rect(screen, color, (x + 1, offy + 1, 9, 29)) # loading banner helper def loading_banner(screen, stuff) : global etc screen.fill((0,0,0)) font = pyg...
256
256
1,735
6
249
henning/ETC_Mother
osd.py
Python
render_overlay
render_overlay
57
222
57
57
ccec767c83020ccf19ff8952e625d338a353034e
bigcode/the-stack
train
af93f9685cedd7418ef3f279
train
function
def init(etc_obj) : global etc etc = etc_obj
def init(etc_obj) :
global etc etc = etc_obj
import pygame import socket etc = None def init(etc_obj) :
17
64
17
7
9
henning/ETC_Mother
osd.py
Python
init
init
6
8
6
6
daf471e861793f630a081112898c66c419f8a322
bigcode/the-stack
train
7689272abc03ac1919718339
train
function
def test_usage(): """Usage""" for flag in ['-h', '--help']: rv, out = getstatusoutput(f'{prg} {flag}') assert rv == 0 assert re.match("usage", out, re.IGNORECASE)
def test_usage():
"""Usage""" for flag in ['-h', '--help']: rv, out = getstatusoutput(f'{prg} {flag}') assert rv == 0 assert re.match("usage", out, re.IGNORECASE)
0808\n60.919540' bad_file1 = 'test_data/bad_input_gc_1.txt' bad_file2 = 'test_data/bad_input_gc_2.txt' # -------------------------------------------------- def test_exists(): """Exists""" assert os.path.isfile(prg) # -------------------------------------------------- def test_usage():
64
64
56
4
60
nathaliagg/my_rosalind_answers
bioinformatics_stronghold/tests/test_gc.py
Python
test_usage
test_usage
25
31
25
25
e6692fec2b27bf4330a0aa860c15b5de89b350c5
bigcode/the-stack
train
d60046384e32e2cdcf1774d0
train
function
def test_exists(): """Exists""" assert os.path.isfile(prg)
def test_exists():
"""Exists""" assert os.path.isfile(prg)
_file = 'test_data/good_input_gc.txt' good_output = 'Rosalind_0808\n60.919540' bad_file1 = 'test_data/bad_input_gc_1.txt' bad_file2 = 'test_data/bad_input_gc_2.txt' # -------------------------------------------------- def test_exists():
64
64
16
4
60
nathaliagg/my_rosalind_answers
bioinformatics_stronghold/tests/test_gc.py
Python
test_exists
test_exists
18
21
18
18
8da830cbde9033b37e393fcf26f915ade3076bf9
bigcode/the-stack
train
903bc9264716edde92be0aa4
train
function
def test_bad_file1(): """Test with a file with more than 10 seqs""" rv, out = getstatusoutput(f'{prg} {bad_file1}') assert rv != 0 error_string = "Limit of 10 fasta sequences per file" assert re.findall(error_string, out, re.IGNORECASE)
def test_bad_file1():
"""Test with a file with more than 10 seqs""" rv, out = getstatusoutput(f'{prg} {bad_file1}') assert rv != 0 error_string = "Limit of 10 fasta sequences per file" assert re.findall(error_string, out, re.IGNORECASE)
"""Output when no args are provided""" rv, out = getstatusoutput(f'{prg}') assert rv != 0 error_string = 'following arguments are required: FILE' assert re.findall(error_string, out, re.IGNORECASE) # -------------------------------------------------- def test_bad_file1():
64
64
73
6
58
nathaliagg/my_rosalind_answers
bioinformatics_stronghold/tests/test_gc.py
Python
test_bad_file1
test_bad_file1
45
51
45
45
e2b527f2a7e9139eab4a08366185e5ee920fd1e1
bigcode/the-stack
train
c7f43dd25b25d6537eccbbdf
train
function
def test_good_args(): """Test with a good input file""" rv, out = getstatusoutput(f'{prg} {good_file}') assert rv == 0 assert out == good_output
def test_good_args():
"""Test with a good input file""" rv, out = getstatusoutput(f'{prg} {good_file}') assert rv == 0 assert out == good_output
, out = getstatusoutput(f'{prg} {bad_file2}') assert rv != 0 error_string = "BadSequenceLength: Sequence must be shorter than 1000 nt." assert re.findall(error_string, out, re.IGNORECASE) # -------------------------------------------------- def test_good_args():
64
64
45
5
59
nathaliagg/my_rosalind_answers
bioinformatics_stronghold/tests/test_gc.py
Python
test_good_args
test_good_args
65
70
65
65
c21b1c6269184e1e6b41d6842df580e6c7a3de72
bigcode/the-stack
train
166bd30c3a029dfa42ef700f
train
function
def test_bad_file2(): """Test with long sequence""" rv, out = getstatusoutput(f'{prg} {bad_file2}') assert rv != 0 error_string = "BadSequenceLength: Sequence must be shorter than 1000 nt." assert re.findall(error_string, out, re.IGNORECASE)
def test_bad_file2():
"""Test with long sequence""" rv, out = getstatusoutput(f'{prg} {bad_file2}') assert rv != 0 error_string = "BadSequenceLength: Sequence must be shorter than 1000 nt." assert re.findall(error_string, out, re.IGNORECASE)
s""" rv, out = getstatusoutput(f'{prg} {bad_file1}') assert rv != 0 error_string = "Limit of 10 fasta sequences per file" assert re.findall(error_string, out, re.IGNORECASE) # -------------------------------------------------- def test_bad_file2():
64
64
71
6
58
nathaliagg/my_rosalind_answers
bioinformatics_stronghold/tests/test_gc.py
Python
test_bad_file2
test_bad_file2
55
61
55
55
61da03cab77afbfb07bc1726db3ebf53da8ac1ef
bigcode/the-stack
train
7ea9afdbade07d7245518dfd
train
function
def test_no_args(): """Output when no args are provided""" rv, out = getstatusoutput(f'{prg}') assert rv != 0 error_string = 'following arguments are required: FILE' assert re.findall(error_string, out, re.IGNORECASE)
def test_no_args():
"""Output when no args are provided""" rv, out = getstatusoutput(f'{prg}') assert rv != 0 error_string = 'following arguments are required: FILE' assert re.findall(error_string, out, re.IGNORECASE)
def test_usage(): """Usage""" for flag in ['-h', '--help']: rv, out = getstatusoutput(f'{prg} {flag}') assert rv == 0 assert re.match("usage", out, re.IGNORECASE) # -------------------------------------------------- def test_no_args():
64
64
60
5
59
nathaliagg/my_rosalind_answers
bioinformatics_stronghold/tests/test_gc.py
Python
test_no_args
test_no_args
35
41
35
35
9398d9825b2c552fb042712ddf5d8e4eace93f9b
bigcode/the-stack
train
783d77a89422b22a9a280240
train
class
@HEADS.register_module class FCOSDeeperFeedbackHead(nn.Module): """ Fully Convolutional One-Stage Object Detection head from [1]_. The FCOS head does not use anchor boxes. Instead bounding boxes are predicted at each pixel and a centerness measure is used to supress low-quality predictions. Re...
@HEADS.register_module class FCOSDeeperFeedbackHead(nn.Module):
""" Fully Convolutional One-Stage Object Detection head from [1]_. The FCOS head does not use anchor boxes. Instead bounding boxes are predicted at each pixel and a centerness measure is used to supress low-quality predictions. References: .. [1] https://arxiv.org/abs/1904.01355 E...
import torch import torch.nn as nn from mmcv.cnn import normal_init from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms, bbox_overlaps from ..builder import build_loss from ..registry import HEADS from ..utils import ConvModule, Scale, bias_init_with_prob from mmdet.ops import DeformConv, Mas...
117
256
4,514
16
100
Lanselott/mmdetection
mmdet/models/anchor_heads/fcos_deeper_feedback_head.py
Python
FCOSDeeperFeedbackHead
FCOSDeeperFeedbackHead
15
500
15
16
1f46dcbbc563a53d7b368221c6271b8b1c17af1e
bigcode/the-stack
train
fe3d6282614ad2af5133a4e0
train
function
def plot_multiple_learning_curves(results: ExperimentResults, filename: Union[str, Path], metric_names: List[str]): # plot averaged learning curve for all tasks fig, axs = plt.subplots(1, len(metric_names), figsize=(7, 4)) for i, metric_name in enumerate(metric_names): ...
def plot_multiple_learning_curves(results: ExperimentResults, filename: Union[str, Path], metric_names: List[str]): # plot averaged learning curve for all tasks
fig, axs = plt.subplots(1, len(metric_names), figsize=(7, 4)) for i, metric_name in enumerate(metric_names): plot_learning_curves_ax(axs[i], results, metric_name=metric_name) fig.legend(*axs[0].get_legend_handles_labels(), loc='upper center', bbox_to_anchor=(0.5, 0.15), ncol=4) plt.tight_layou...
_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig) def plot_multiple_learning_curves(results: ExperimentResults, filename: Union[str, Path], metric_names: List[str]): # plot averaged learning curve for all tasks...
64
64
182
35
29
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_multiple_learning_curves
plot_multiple_learning_curves
264
277
264
266
af4cd6b224552ec44d1fa9f03106793fbb6a2d33
bigcode/the-stack
train
4582147b8441f9ab7944294b
train
function
def plot_batch_sizes_ax(ax: plt.Axes, results: ExperimentResults, metric_name: str, set_ticks_and_labels: bool = True, **plot_options): last_errors = results.get_last_errors(metric_name) ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) # htt...
def plot_batch_sizes_ax(ax: plt.Axes, results: ExperimentResults, metric_name: str, set_ticks_and_labels: bool = True, **plot_options):
last_errors = results.get_last_errors(metric_name) ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) # https://stackoverflow.com/questions/42086276/get-default-line-colour-cycle # default matplotlib colors: # colors = [u'#1f77b4', u'#ff7f0e', u'#2ca02c', u'#...
import matplotlib #matplotlib.use('Agg') matplotlib.use('pdf') matplotlib.rcParams.update({ "pgf.texsystem": "pdflatex", 'font.family': 'serif', 'font.size': 10, 'text.usetex': True, 'pgf.rcfonts': False, # 'legend.framealpha': 0.5, 'text.latex.preamble': r'\usepackage{times} \usepackage{ams...
250
256
924
35
214
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_batch_sizes_ax
plot_batch_sizes_ax
34
98
34
35
bd8878e8b12ad33366255e0a7e2555e11eae1995
bigcode/the-stack
train
2a39784a2a03b2530b9f50b3
train
function
def rgb_to_hex(rgb): return '#%02x%02x%02x' % rgb
def rgb_to_hex(rgb):
return '#%02x%02x%02x' % rgb
import custom_paths from .analysis import * from pathlib import Path import seaborn as sns fontsize = 10 axis_font = {'size': str(fontsize)} sns.axes_style("whitegrid") def escape(name: str): return name.replace('_', r'\_') def rgb_to_hex(rgb):
64
64
22
6
58
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
rgb_to_hex
rgb_to_hex
30
31
30
30
5a38ee48ee00503d17914e1275c11f3314bb3d29
bigcode/the-stack
train
5800a76a8ee1372a80332ea7
train
function
def plot_learning_curves_metrics_subplots(results: ExperimentResults, filename: Union[str, Path]): # plot mean final log metric against the al batch size fig, axs = plt.subplots(3, 2, figsize=(7, 9)) metric_names = ['mae', 'rmse', 'q95', 'q99', 'maxe'] for metric_idx, metric_name in enumerate(metric_nam...
def plot_learning_curves_metrics_subplots(results: ExperimentResults, filename: Union[str, Path]): # plot mean final log metric against the al batch size
fig, axs = plt.subplots(3, 2, figsize=(7, 9)) metric_names = ['mae', 'rmse', 'q95', 'q99', 'maxe'] for metric_idx, metric_name in enumerate(metric_names): i = metric_idx // 2 j = metric_idx % 2 ax = axs[i, j] plot_learning_curves_ax(ax, results, metric_name) axs[-1, -1]....
Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig) def plot_learning_curves_metrics_subplots(results: ExperimentResults, filename: Union[str, Path]): # plot mean final log metric against the al batch size
66
66
221
33
33
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_learning_curves_metrics_subplots
plot_learning_curves_metrics_subplots
335
351
335
336
9416b68fb79d4466c517d9295bcd79e3f666cb58
bigcode/the-stack
train
21377aab0fce158582896f2b
train
function
def escape(name: str): return name.replace('_', r'\_')
def escape(name: str):
return name.replace('_', r'\_')
}) import matplotlib.pyplot as plt from typing import * import numpy as np import custom_paths from .analysis import * from pathlib import Path import seaborn as sns fontsize = 10 axis_font = {'size': str(fontsize)} sns.axes_style("whitegrid") def escape(name: str):
64
64
16
6
58
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
escape
escape
26
27
26
26
09abb9048f24f24b45cf672d25f2bd41482af0f2
bigcode/the-stack
train
21e7d09342d3de3478396b88
train
function
def plot_skewness_ax(ax: plt.Axes, results: ExperimentResults, metric_name: str, alg_name: str, use_relative_improvement: bool = False): sns.color_palette("Paired") # plot mean final log metric against the al batch size all_alg_names = list(results.results_dict.keys()) all_task_nam...
def plot_skewness_ax(ax: plt.Axes, results: ExperimentResults, metric_name: str, alg_name: str, use_relative_improvement: bool = False):
sns.color_palette("Paired") # plot mean final log metric against the al batch size all_alg_names = list(results.results_dict.keys()) all_task_names = {task_name for alg_name in all_alg_names for task_name in results.results_dict[alg_name].keys()} ds_names = list({'_'.join(task_name.split('_')[:-1])...
.split('_')[1]), **axis_font) for i in range(len(alg_names)): for j in range(i+1, len(alg_names)): axs[j-1, i].plot([min_result, max_result], [min_result, max_result], 'k-') axs[j-1, i].plot([min_result, max_result], [0.0, 0.0], 'k--') axs[j - 1, i].plot([0.0, 0.0], [min...
256
256
1,008
37
219
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_skewness_ax
plot_skewness_ax
427
490
427
428
66ce7ee9ce56ef2213b33cb9d607676cd50cb20a
bigcode/the-stack
train
4692b172669857b989649f3a
train
function
def plot_learning_curves(results: ExperimentResults, filename: Union[str, Path], metric_name: str, labels: Optional[List[str]] = None, figsize: Optional[Tuple[int, int]] = None): # plot averaged learning curve for all tasks fig, axs = plt.subplots(figsize=figsize or (3.5, 3.5)) plo...
def plot_learning_curves(results: ExperimentResults, filename: Union[str, Path], metric_name: str, labels: Optional[List[str]] = None, figsize: Optional[Tuple[int, int]] = None): # plot averaged learning curve for all tasks
fig, axs = plt.subplots(figsize=figsize or (3.5, 3.5)) plot_learning_curves_ax(axs, results=results, metric_name=metric_name, labels=labels) axs.legend() plt.tight_layout() plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(...
_metric_name(metric_name)}', **axis_font) def plot_learning_curves(results: ExperimentResults, filename: Union[str, Path], metric_name: str, labels: Optional[List[str]] = None, figsize: Optional[Tuple[int, int]] = None): # plot averaged learning curve for all tasks
64
64
145
54
10
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_learning_curves
plot_learning_curves
249
261
249
251
6acfd36b2db471860180e6d69359c6aaded77b2a
bigcode/the-stack
train
029f5b42f3461c3bc0e8b46c
train
function
def plot_learning_curves_v2(results: ExperimentResults, filename: Union[str, Path], metric_name: str): # plot averaged learning curve for all tasks all_alg_names = list(results.results_dict.keys()) all_task_names = {task_name for alg_name in all_alg_names for task_name in results.results_dict[alg_name].keys...
def plot_learning_curves_v2(results: ExperimentResults, filename: Union[str, Path], metric_name: str): # plot averaged learning curve for all tasks
all_alg_names = list(results.results_dict.keys()) all_task_names = {task_name for alg_name in all_alg_names for task_name in results.results_dict[alg_name].keys()} ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in all_task_names}) algs_with_all_tasks = [alg_name for alg_name in all_a...
1], log_means_ll[0] - log_means_grad_rp[0], 'o', label=escape(name_task)) axs.legend() plt.tight_layout() plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig) def plot_learning_curves_v2(results: Experimen...
108
108
362
34
74
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_learning_curves_v2
plot_learning_curves_v2
543
569
543
544
baa904f82c827ec3181cbb213ae4fa1490db2572
bigcode/the-stack
train
4014d84a6f63d1922525e288
train
function
def plot_multiple_batch_sizes(results: ExperimentResults, filename: Union[str, Path], metric_names: List[str]): # plot averaged learning curve for all tasks fig, axs = plt.subplots(1, len(metric_names), figsize=(7, 4)) for i, metric_name in enumerate(metric_names): ...
def plot_multiple_batch_sizes(results: ExperimentResults, filename: Union[str, Path], metric_names: List[str]): # plot averaged learning curve for all tasks
fig, axs = plt.subplots(1, len(metric_names), figsize=(7, 4)) for i, metric_name in enumerate(metric_names): plot_batch_sizes_ax(axs[i], results, metric_name) fig.legend(*axs[0].get_legend_handles_labels(), loc='upper center', bbox_to_anchor=(0.5, 0.15), ncol=4) plt.tight_layout(rect=[0, 0.15,...
.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig) def plot_multiple_batch_sizes(results: ExperimentResults, filename: Union[str, Path], metric_names: List[str]): # plot averaged learning curve for all tasks...
64
64
177
34
30
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_multiple_batch_sizes
plot_multiple_batch_sizes
115
128
115
117
8a0afc9ec629e6287fe697c97f54e5b2adb799c8
bigcode/the-stack
train
cfd05e10005dced665f2411d
train
function
def plot_batch_sizes_individual(results: ExperimentResults, metric_name: str): # plot mean final log metric against the al batch size ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() for ds_name in ds_names: fig, ax = plt.subplots(figsiz...
def plot_batch_sizes_individual(results: ExperimentResults, metric_name: str): # plot mean final log metric against the al batch size
ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() for ds_name in ds_names: fig, ax = plt.subplots(figsize=(4, 4)) plot_batch_sizes_ax(ax, results.filter_task_prefix(ds_name), metric_name) ax.legend() plt.tight_layout(...
_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig) def plot_batch_sizes_individual(results: ExperimentResults, metric_name: str): # plot mean final log metric against the al batch size
64
64
160
29
35
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_batch_sizes_individual
plot_batch_sizes_individual
131
146
131
132
90470825c10582211d0d30b5999000c69f0e7b6f
bigcode/the-stack
train
15f7c6e6af26c21b85769dd0
train
function
def alt_plot_eff_dim(results: ExperimentResults, filename: Union[str, Path], pattern: str, metric_name: str): # plots, for every data set, error of grad_rp-512 to ll vs difference in effective dimensions (average), # for different selection methods (esp. maxdist, maxdet, lcmd, fw), all_alg_names = [pattern....
def alt_plot_eff_dim(results: ExperimentResults, filename: Union[str, Path], pattern: str, metric_name: str): # plots, for every data set, error of grad_rp-512 to ll vs difference in effective dimensions (average), # for different selection methods (esp. maxdist, maxdet, lcmd, fw),
all_alg_names = [pattern.replace('*', 'll'), pattern.replace('*', 'grad_rp-512'), 'NN_random'] all_task_names = {task_name for alg_name in all_alg_names for task_name in results.results_dict[alg_name].keys()} eff_dims = results.get_avg_al_stats('eff_dim') last_errors = results.get_last_errors(metric_na...
_names], axis=0) for alg_name in alg_names} for alg_name in alg_names: axs.plot(n_train, alg_results[alg_name] - alg_results['NN_random'], '--o', label=escape(alg_name)) axs.legend() plt.tight_layout() plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensu...
168
168
561
72
96
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
alt_plot_eff_dim
alt_plot_eff_dim
572
611
572
574
1d9abf0f3d9384aa6d0d6e9d06a0db871fc94d52
bigcode/the-stack
train
53cf1d1bf953c9542e815f63
train
function
def plot_learning_curves_individual(results: ExperimentResults, metric_name: str): # plot individual learning curve for all tasks ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() for ds_name in ds_names: fig, axs = plt.subplots(figsize=(...
def plot_learning_curves_individual(results: ExperimentResults, metric_name: str): # plot individual learning curve for all tasks
ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() for ds_name in ds_names: fig, axs = plt.subplots(figsize=(3.5, 3.5)) plot_learning_curves_ax(axs, results.filter_task_names([ds_name + '_256x16']), metric_name=metric_name) axs...
plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig) def plot_learning_curves_individual(results: ExperimentResults, metric_name: str): # plot individual learning curve for all tasks
64
64
178
27
37
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_learning_curves_individual
plot_learning_curves_individual
280
294
280
281
c7fd5482fbea6febb286c4ec2a2762b039403764
bigcode/the-stack
train
da86ac7b8bc8cd0902febade
train
function
def plot_batch_sizes(results: ExperimentResults, filename: Union[str, Path], metric_name: str): # plot mean final log metric against the al batch size fig, ax = plt.subplots(figsize=(4, 4)) plot_batch_sizes_ax(ax, results, metric_name) ax.legend() plt.tight_layout() plot_name = Path(custom_pat...
def plot_batch_sizes(results: ExperimentResults, filename: Union[str, Path], metric_name: str): # plot mean final log metric against the al batch size
fig, ax = plt.subplots(figsize=(4, 4)) plot_batch_sizes_ax(ax, results, metric_name) ax.legend() plt.tight_layout() plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig)
$', **axis_font) ax.set_ylabel(r'mean log ' + f'{get_latex_metric_name(metric_name)}', **axis_font) def plot_batch_sizes(results: ExperimentResults, filename: Union[str, Path], metric_name: str): # plot mean final log metric against the al batch size
64
64
106
34
30
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_batch_sizes
plot_batch_sizes
101
112
101
102
9ed527e3b125bc9d5d22ac9a9fe19fa3c2791c96
bigcode/the-stack
train
b779cca7e03c9cbe54e1b9ca
train
function
def plot_correlation_between_methods(results: ExperimentResults, filename: Union[str, Path], metric_name: str): sns.color_palette("Paired") # plot mean final log metric against the al batch size ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() ...
def plot_correlation_between_methods(results: ExperimentResults, filename: Union[str, Path], metric_name: str):
sns.color_palette("Paired") # plot mean final log metric against the al batch size ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() task_names = [ds_name + '_256x16' for ds_name in ds_names] alg_names = [alg_name for alg_name in results....
) plt.savefig(plot_name) plt.close(fig) def plot_learning_curves_metrics_subplots(results: ExperimentResults, filename: Union[str, Path]): # plot mean final log metric against the al batch size fig, axs = plt.subplots(3, 2, figsize=(7, 9)) metric_names = ['mae', 'rmse', 'q95', 'q99', 'maxe'] f...
256
256
1,094
23
233
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_correlation_between_methods
plot_correlation_between_methods
354
424
354
354
868c2d4dc2b304bfd3c633f18f063a873c5d7df5
bigcode/the-stack
train
bd748fbd865ec912a8137364
train
function
def plot_learning_curves_ax(ax: plt.Axes, results: ExperimentResults, metric_name: str, with_random_final: bool = True, set_ticks_and_labels: bool = True, labels: Optional[List[str]] = None, **plot_options): learning_curves = results.get_learning_curves(metric_name) # https://stacko...
def plot_learning_curves_ax(ax: plt.Axes, results: ExperimentResults, metric_name: str, with_random_final: bool = True, set_ticks_and_labels: bool = True, labels: Optional[List[str]] = None, **plot_options):
learning_curves = results.get_learning_curves(metric_name) # https://stackoverflow.com/questions/42086276/get-default-line-colour-cycle # default matplotlib colors: # colors = [u'#1f77b4', u'#ff7f0e', u'#2ca02c', u'#d62728', u'#9467bd', u'#8c564b', u'#e377c2', u'#7f7f7f', # u'#bcbd22', u'...
enumerate(metric_names): i = metric_idx // 2 j = metric_idx % 2 ax = axs[i, j] plot_batch_sizes_ax(ax, results, metric_name, set_ticks_and_labels=True) axs[-1, -1].axis('off') fig.legend(*axs[0, 0].get_legend_handles_labels(), loc='center', bbox_to_anchor=(0.78, 0.18), ncol=1) ...
194
194
647
53
141
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_learning_curves_ax
plot_learning_curves_ax
205
246
205
206
7e60758bc0f3b6e652444dfe8ef79a1021c934ea
bigcode/the-stack
train
91b2553969c7b1a26f01a8bb
train
function
def plot_eff_dim(results: ExperimentResults, filename: Union[str, Path], pattern: str, metric_name: str): # plots, for every data set, error of grad_rp-512 to ll vs difference in effective dimensions (average), # for different selection methods (esp. maxdist, maxdet, lcmd, fw), all_alg_names = [pattern.repl...
def plot_eff_dim(results: ExperimentResults, filename: Union[str, Path], pattern: str, metric_name: str): # plots, for every data set, error of grad_rp-512 to ll vs difference in effective dimensions (average), # for different selection methods (esp. maxdist, maxdet, lcmd, fw),
all_alg_names = [pattern.replace('*', 'll'), pattern.replace('*', 'grad_rp-512')] all_task_names = {task_name for alg_name in all_alg_names for task_name in results.results_dict[alg_name].keys()} eff_dims = results.get_avg_al_stats('eff_dim') last_errors = results.get_last_errors(metric_name) ds_na...
1.05, 1.02)) # plt.tight_layout() plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name, bbox_inches="tight") plt.close(fig) # ----- not needed plots ----- def plot_eff_dim(results: ExperimentResults, filename: Union[str, Pat...
135
135
453
71
63
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_eff_dim
plot_eff_dim
510
540
510
512
eb2771dc0715c39f8ace2463ecabc7b8c10ab9f2
bigcode/the-stack
train
b7bb02f0bbd341536c3241e8
train
function
def plot_learning_curves_individual_subplots(results: ExperimentResults, filename: str, metric_name: str): # plot individual learning curve for all tasks ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() fig, axs = plt.subplots(5, 3, figsize=(9, ...
def plot_learning_curves_individual_subplots(results: ExperimentResults, filename: str, metric_name: str): # plot individual learning curve for all tasks
ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() fig, axs = plt.subplots(5, 3, figsize=(9, 12)) if len(ds_names) != 15: print(f'plot_batch_sizes_individual_subplots needs 15 data sets, but got {len(ds_names)} data sets') return ...
= plt.subplots(figsize=(3.5, 3.5)) plot_learning_curves_ax(axs, results.filter_task_names([ds_name + '_256x16']), metric_name=metric_name) axs.legend(fontsize=fontsize) plt.tight_layout() plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / 'ds_learning_curves' / \ ...
142
142
476
33
109
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_learning_curves_individual_subplots
plot_learning_curves_individual_subplots
297
332
297
298
3c4de340399924bc75ce77f96dcde709f341f2f8
bigcode/the-stack
train
f9db374bc5a76a31f0ff8523
train
function
def plot_batch_sizes_metrics_subplots(results: ExperimentResults, filename: Union[str, Path]): # plot mean final log metric against the al batch size fig, axs = plt.subplots(3, 2, figsize=(7, 9)) metric_names = ['mae', 'rmse', 'q95', 'q99', 'maxe'] for metric_idx, metric_name in enumerate(metric_names)...
def plot_batch_sizes_metrics_subplots(results: ExperimentResults, filename: Union[str, Path]): # plot mean final log metric against the al batch size
fig, axs = plt.subplots(3, 2, figsize=(7, 9)) metric_names = ['mae', 'rmse', 'q95', 'q99', 'maxe'] for metric_idx, metric_name in enumerate(metric_names): i = metric_idx // 2 j = metric_idx % 2 ax = axs[i, j] plot_batch_sizes_ax(ax, results, metric_name, set_ticks_and_labels=...
_name = Path(custom_paths.get_plots_path()) / results.exp_name / filename utils.ensureDir(plot_name) plt.savefig(plot_name) plt.close(fig) def plot_batch_sizes_metrics_subplots(results: ExperimentResults, filename: Union[str, Path]): # plot mean final log metric against the al batch size
67
67
225
32
35
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_batch_sizes_metrics_subplots
plot_batch_sizes_metrics_subplots
185
202
185
187
d1d019e6198c248dbf43414975f82a7c1bdb857f
bigcode/the-stack
train
fcea6e9c59ab31cc3b6030d6
train
function
def plot_batch_sizes_individual_subplots(results: ExperimentResults, filename: Union[str, Path], metric_name: str): # plot mean final log metric against the al batch size ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() fig, axs = plt.subplots(5...
def plot_batch_sizes_individual_subplots(results: ExperimentResults, filename: Union[str, Path], metric_name: str): # plot mean final log metric against the al batch size
ds_names = list({'_'.join(task_name.split('_')[:-1]) for task_name in results.task_names}) ds_names.sort() fig, axs = plt.subplots(5, 3, figsize=(9, 12)) if len(ds_names) != 15: print(f'plot_batch_sizes_individual_subplots needs 15 data sets, but got {len(ds_names)} data sets') return ...
.sort() for ds_name in ds_names: fig, ax = plt.subplots(figsize=(4, 4)) plot_batch_sizes_ax(ax, results.filter_task_prefix(ds_name), metric_name) ax.legend() plt.tight_layout() plot_name = Path(custom_paths.get_plots_path()) / results.exp_name / 'ds_batch_sizes' / \ ...
141
141
472
38
103
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_batch_sizes_individual_subplots
plot_batch_sizes_individual_subplots
149
182
149
150
3e1a1d1ae9b70dacf564751faff792fff3bf2f0e
bigcode/the-stack
train
ab5af2547d8dd9934e7e28d3
train
function
def plot_error_variation(results: ExperimentResults, filename: Union[str, Path], metric_name: str, alg_name: str, use_relative_improvement: bool = False): fig, ax = plt.subplots(1, 1, figsize=(4.0, 4.0)) plot_skewness_ax(ax, results, metric_name=metric_name, alg_name=alg_name, ...
def plot_error_variation(results: ExperimentResults, filename: Union[str, Path], metric_name: str, alg_name: str, use_relative_improvement: bool = False):
fig, ax = plt.subplots(1, 1, figsize=(4.0, 4.0)) plot_skewness_ax(ax, results, metric_name=metric_name, alg_name=alg_name, use_relative_improvement=use_relative_improvement) plt.legend(loc='upper left', bbox_to_anchor=(1.05, 1.02)) # plt.tight_layout() plot_name = Path(custom_p...
='Linear Regression fit') print(f'plot_skewness_ax: R^2 = {r_value**2:g}') def plot_error_variation(results: ExperimentResults, filename: Union[str, Path], metric_name: str, alg_name: str, use_relative_improvement: bool = False):
63
64
163
37
26
dholzmueller/bmdal_reg
evaluation/plotting.py
Python
plot_error_variation
plot_error_variation
493
504
493
494
db118d44dc28882ab6a8353b07b59ce10c42856f
bigcode/the-stack
train
0f8ab02d6fdff384d6dca1a3
train
class
class DemoException(Exception): """An exception type for the demonstration."""
class DemoException(Exception):
"""An exception type for the demonstration."""
_coro.throw(ZeroDivisionError) Traceback (most recent call last): ... ZeroDivisionError >>> getgeneratorstate(exc_coro) 'GEN_CLOSED' # END DEMO_CORO_EXC_3 """ # BEGIN EX_CORO_EXC class DemoException(Exception):
64
64
14
5
58
cgDeepLearn/fluentpython
chapter16-coroutine/coro_exc_demo.py
Python
DemoException
DemoException
54
55
54
54
f34c3c9d3f8a22518fd3870073d7033ad3539edb
bigcode/the-stack
train
f694c2d76720a9655c24c79e
train
function
def demo_exc_handling(): print('-> coroutine started') while True: try: x = yield except DemoException: # <1> print('*** DemoException handled. Continuing...') else: # <2> print('-> coroutine received: {!r}'.format(x)) raise RuntimeError('This li...
def demo_exc_handling():
print('-> coroutine started') while True: try: x = yield except DemoException: # <1> print('*** DemoException handled. Continuing...') else: # <2> print('-> coroutine received: {!r}'.format(x)) raise RuntimeError('This line should never run.') #...
last): ... ZeroDivisionError >>> getgeneratorstate(exc_coro) 'GEN_CLOSED' # END DEMO_CORO_EXC_3 """ # BEGIN EX_CORO_EXC class DemoException(Exception): """An exception type for the demonstration.""" def demo_exc_handling():
64
64
82
6
58
cgDeepLearn/fluentpython
chapter16-coroutine/coro_exc_demo.py
Python
demo_exc_handling
demo_exc_handling
57
66
57
57
4cb6a234dc9715941b5b532e46fb2ab69582705b
bigcode/the-stack
train
c5047a94f94e5db1529f3273
train
class
class CppHeaderParser(object): def __init__(self): self.BLOCK_TYPE = 0 self.BLOCK_NAME = 1 self.PROCESS_FLAG = 2 self.PUBLIC_SECTION = 3 self.CLASS_DECL = 4 def batch_replace(self, s, pairs): for before, after in pairs: s = s.replace(before, after) ...
class CppHeaderParser(object):
def __init__(self): self.BLOCK_TYPE = 0 self.BLOCK_NAME = 1 self.PROCESS_FLAG = 2 self.PUBLIC_SECTION = 3 self.CLASS_DECL = 4 def batch_replace(self, s, pairs): for before, after in pairs: s = s.replace(before, after) return s def get_mac...
../../ml/include/opencv2/ml.hpp", "../../imgproc/include/opencv2/imgproc.hpp", "../../calib3d/include/opencv2/calib3d.hpp", "../../features2d/include/opencv2/features2d.hpp", "../../video/include/opencv2/video/tracking.hpp", "../../video/include/opencv2/video/background_segm.hpp", "../../objdetect/include/opencv2/objde...
256
256
7,473
7
249
gunnjo/opencv
modules/python/src2/hdr_parser.py
Python
CppHeaderParser
CppHeaderParser
32
869
32
33
15c7343baf31b010b4bd3bdfdbb6f6178b5095b9
bigcode/the-stack
train
f2f98e8fb1ae90bb0190c6c4
train
function
def test_reaper(): """ REAPER2 (DAEMON): Test the reaper2 daemon.""" if config_get_bool('common', 'multi_vo', raise_exception=False, default=False): vo = {'vo': config_get('client', 'vo', raise_exception=False, default='tst')} new_vo = {'vo': 'new'} if not vo_core.vo_exists(**new_vo): ...
def test_reaper():
""" REAPER2 (DAEMON): Test the reaper2 daemon.""" if config_get_bool('common', 'multi_vo', raise_exception=False, default=False): vo = {'vo': config_get('client', 'vo', raise_exception=False, default='tst')} new_vo = {'vo': 'new'} if not vo_core.vo_exists(**new_vo): vo_core.a...
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. # # Authors: # - Thomas Beermann <thomas.beermann@cern.ch>, 2020 # - Eli Chadwick <eli.chadwick@stfc.ac.uk>, 2020 # - Patrick Austin <patrick.a...
256
256
1,259
5
250
andresailer/rucio
lib/rucio/tests/test_reaper2.py
Python
test_reaper
test_reaper
35
119
35
35
6aa45d5e445da2bf673c721c6eb6c665c360dd81
bigcode/the-stack
train
c8f87dad6c96e72fcd199547
train
class
class FormatHDF5SaclaRayonix(FormatHDF5, FormatStill): """ Class to handle multi-event HDF5 files from Rayonix detector (MX300-HS) preprocessed by Cheetah SFX pipeline at SACLA. """ @staticmethod def understand(image_file): with h5py.File(image_file, "r") as h5_handle: if "m...
class FormatHDF5SaclaRayonix(FormatHDF5, FormatStill):
""" Class to handle multi-event HDF5 files from Rayonix detector (MX300-HS) preprocessed by Cheetah SFX pipeline at SACLA. """ @staticmethod def understand(image_file): with h5py.File(image_file, "r") as h5_handle: if "metadata/detector" not in h5_handle: ret...
import os import sys import h5py import numpy as np from cctbx import factor_ev_angstrom from scitbx.array_family import flex from dxtbx.format.FormatHDF5 import FormatHDF5 from dxtbx.format.FormatStill import FormatStill from dxtbx.format.nexus import h5str class FormatHDF5SaclaRayonix(FormatHDF5, FormatStill):
92
256
991
19
72
toastisme/dxtbx
src/dxtbx/format/FormatHDF5SaclaRayonix.py
Python
FormatHDF5SaclaRayonix
FormatHDF5SaclaRayonix
15
137
15
15
eb114c8bf469a10482d16946a80b6b4003e5b952
bigcode/the-stack
train
855d75a187bc6dff627dbc65
train
class
class VolumeDetachTestCase(VolumeOpsTestBase): @mock.patch.object(volumeops.vm_utils, 'lookup', return_value='vmref') @mock.patch.object(volumeops.volume_utils, 'find_vbd_by_number', return_value='vbdref') @mock.patch.object(volumeops.vm_utils, 'is_vm_shutdown', ...
class VolumeDetachTestCase(VolumeOpsTestBase): @mock.patch.object(volumeops.vm_utils, 'lookup', return_value='vmref') @mock.patch.object(volumeops.volume_utils, 'find_vbd_by_number', return_value='vbdref') @mock.patch.object(volumeops.vm_utils, 'is_vm_shutdown', ...
def test_detach_volume_call(self, mock_purge, mock_find_sr, mock_get_device_num, mock_destroy_vbd, mock_unplug_vbd, mock_is_vm, mock_find_vbd, mock_lookup): ops = volumeops.VolumeOps('session') ops.deta...
from nova.virt.xenapi import volumeops class VolumeOpsTestBase(stubs.XenAPITestBaseNoDB): def setUp(self): super(VolumeOpsTestBase, self).setUp() self._setup_mock_volumeops() def _setup_mock_volumeops(self): self.session = stubs.FakeSessionForVolumeTests('fake_uri') self.ops =...
256
256
1,749
167
89
taget/nova
nova/tests/unit/virt/xenapi/test_volumeops.py
Python
VolumeDetachTestCase
VolumeDetachTestCase
35
196
35
47
c9ab089fe8363bc37139f3e04328a58c07ec12dc
bigcode/the-stack
train
e4d9176701528d30b4889d12
train
class
class VolumeOpsTestBase(stubs.XenAPITestBaseNoDB): def setUp(self): super(VolumeOpsTestBase, self).setUp() self._setup_mock_volumeops() def _setup_mock_volumeops(self): self.session = stubs.FakeSessionForVolumeTests('fake_uri') self.ops = volumeops.VolumeOps(self.session)
class VolumeOpsTestBase(stubs.XenAPITestBaseNoDB):
def setUp(self): super(VolumeOpsTestBase, self).setUp() self._setup_mock_volumeops() def _setup_mock_volumeops(self): self.session = stubs.FakeSessionForVolumeTests('fake_uri') self.ops = volumeops.VolumeOps(self.session)
import test from nova.tests.unit.virt.xenapi import stubs from nova.virt.xenapi import vm_utils from nova.virt.xenapi import volume_utils from nova.virt.xenapi import volumeops class VolumeOpsTestBase(stubs.XenAPITestBaseNoDB):
64
64
78
15
48
taget/nova
nova/tests/unit/virt/xenapi/test_volumeops.py
Python
VolumeOpsTestBase
VolumeOpsTestBase
25
32
25
25
5ea2a2ad8b02648b371024e8bb71988628894042
bigcode/the-stack
train
4e1cdfe76056b3d5a50c7f76
train
class
class CleanupFromVDIsTestCase(VolumeOpsTestBase): def _check_find_purge_calls(self, find_sr_from_vdi, purge_sr, vdi_refs, sr_refs): find_sr_calls = [mock.call(self.ops._session, vdi_ref) for vdi_ref in vdi_refs] find_sr_from_vdi.assert_has_calls(find_sr_calls) pur...
class CleanupFromVDIsTestCase(VolumeOpsTestBase):
def _check_find_purge_calls(self, find_sr_from_vdi, purge_sr, vdi_refs, sr_refs): find_sr_calls = [mock.call(self.ops._session, vdi_ref) for vdi_ref in vdi_refs] find_sr_from_vdi.assert_has_calls(find_sr_calls) purge_sr_calls = [mock.call(self.ops._session, sr_ref...
): mock_get_all.return_value = ["vbd_ref"] mock_find_sr.return_value = "sr_ref" class FakeException(Exception): details = ['foo', "", "", ""] session = mock.Mock() session.XenAPI.Failure = FakeException self.ops._session = session with mock.patch.ob...
163
163
544
13
150
taget/nova
nova/tests/unit/virt/xenapi/test_volumeops.py
Python
CleanupFromVDIsTestCase
CleanupFromVDIsTestCase
501
547
501
501
8f06412ff7fa5f99a3aaaa01a45984c577fe7dc3
bigcode/the-stack
train
8c1f17c6cc872e70261c9a90
train
class
class AttachVolumeTestCase(VolumeOpsTestBase): @mock.patch.object(volumeops.VolumeOps, "_attach_volume") @mock.patch.object(vm_utils, "vm_ref_or_raise") def test_attach_volume_default_hotplug(self, mock_get_vm, mock_attach): mock_get_vm.return_value = "vm_ref" self.ops.attach_volume({}, "in...
class AttachVolumeTestCase(VolumeOpsTestBase): @mock.patch.object(volumeops.VolumeOps, "_attach_volume") @mock.patch.object(vm_utils, "vm_ref_or_raise")
def test_attach_volume_default_hotplug(self, mock_get_vm, mock_attach): mock_get_vm.return_value = "vm_ref" self.ops.attach_volume({}, "instance_name", "/dev/xvda") mock_attach.assert_called_once_with({}, "vm_ref", "instance_name", 0, True) ...
mock.patch.object(self.session.VM, "get_VBDs") as mock_get: with mock.patch.object(self.session.VBD, "get_other_config") as mock_conf: mock_get.return_value = ["1"] mock_conf.return_value = {} result = self.ops._get_all_vol...
256
256
2,315
39
217
taget/nova
nova/tests/unit/virt/xenapi/test_volumeops.py
Python
AttachVolumeTestCase
AttachVolumeTestCase
199
421
199
201
cef2a6387246667bedcab251f43dd7faca715302
bigcode/the-stack
train
e75cb37418c35da64ee3ebea
train
class
class FindBadVolumeTestCase(VolumeOpsTestBase): @mock.patch.object(volumeops.VolumeOps, "_get_all_volume_vbd_refs") def test_find_bad_volumes_no_vbds(self, mock_get_all): mock_get_all.return_value = [] result = self.ops.find_bad_volumes("vm_ref") mock_get_all.assert_called_once_with("v...
class FindBadVolumeTestCase(VolumeOpsTestBase): @mock.patch.object(volumeops.VolumeOps, "_get_all_volume_vbd_refs")
def test_find_bad_volumes_no_vbds(self, mock_get_all): mock_get_all.return_value = [] result = self.ops.find_bad_volumes("vm_ref") mock_get_all.assert_called_once_with("vm_ref") self.assertEqual([], result) @mock.patch.object(volume_utils, "find_sr_from_vbd") @mock.patch.o...
mock_vbd.assert_called_once_with(self.session, "vm", "vdi", 2, bootable=False, osvol=True) mock_shutdown.assert_called_once_with(self.session, "vm") @mock.patch.object(vm_utils, "is_vm_shutdown") @mock.patch.object(vm_utils, "create_vbd") def test_attach_vo...
216
216
720
30
186
taget/nova
nova/tests/unit/virt/xenapi/test_volumeops.py
Python
FindBadVolumeTestCase
FindBadVolumeTestCase
424
498
424
425
ac422306f1884e6945dc3645b70ec056b162259d
bigcode/the-stack
train
581c6fadd7dedc87d4caf452
train
class
class GetUserPhotos(TLObject): # type: ignore """Telegram API method. Details: - Layer: ``123`` - ID: ``0x91cd32a8`` Parameters: user_id: :obj:`InputUser <pyrogram.raw.base.InputUser>` offset: ``int`` ``32-bit`` max_id: ``int`` ``64-bit`` limit: ``int`` ``3...
class GetUserPhotos(TLObject): # type: ignore
"""Telegram API method. Details: - Layer: ``123`` - ID: ``0x91cd32a8`` Parameters: user_id: :obj:`InputUser <pyrogram.raw.base.InputUser>` offset: ``int`` ``32-bit`` max_id: ``int`` ``64-bit`` limit: ``int`` ``32-bit`` Returns: :obj:`photos.Phot...
from pyrogram.raw.core import TLObject from pyrogram import raw from typing import List, Union, Any # # # # # # # # # # # # # # # # # # # # # # # # # !!! WARNING !!! # # This is a generated file! # # All changes made in this file will be lost! # # # # # # # # # # # # # # #...
114
115
384
13
101
appheap/social-media-analyzer
backend/pyrogram/raw/functions/photos/get_user_photos.py
Python
GetUserPhotos
GetUserPhotos
33
89
33
33
a9ce9f84979620aa4b0885f6fddb04be05612324
bigcode/the-stack
train
d2519fbe801be26ead7a2ad9
train
class
class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True, autoincrement=True) email = Column(String, unique=True, nullable=True) hashed_password = Column(String) session_id = Column(String) create_date = Column(DateTime, default=datetime.utcnow()) last_login = Column(D...
class User(Base):
__tablename__ = "user" id = Column(Integer, primary_key=True, autoincrement=True) email = Column(String, unique=True, nullable=True) hashed_password = Column(String) session_id = Column(String) create_date = Column(DateTime, default=datetime.utcnow()) last_login = Column(DateTime, default=d...
from sqlalchemy import Table, Column, Integer, String from sqlalchemy.sql.sqltypes import DateTime from databases.database import Base from datetime import datetime class User(Base):
35
64
77
4
30
coolexplorer/py-auth
app/models/user.py
Python
User
User
6
14
6
6
faff18933bb8069f666988f981bfc5783cab3a24
bigcode/the-stack
train
bb06f28e00b2327aae2ad35e
train
function
def TetrapisisporaPhaffiiCbs4417( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: """Return new instance of the...
def TetrapisisporaPhaffiiCbs4417( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph:
"""Return new instance of the Tetrapisispora phaffii CBS 4417 graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = ...
cheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph...
186
186
620
86
99
AnacletoLAB/ensmallen
bindings/python/ensmallen/datasets/string/tetrapisisporaphaffiicbs4417.py
Python
TetrapisisporaPhaffiiCbs4417
TetrapisisporaPhaffiiCbs4417
30
104
30
39
e17e7285fd6088415a1774b6ecd6c9e09ea1be0c
bigcode/the-stack
train
8a3fdaf59030225c5e6705b3
train
function
def rhyme(): return "\n\n".join(_verse(n) for n in range(len(parts)))
def rhyme():
return "\n\n".join(_verse(n) for n in range(len(parts)))
is {}'.format(parts[n][1])] v.extend(['that {0} {1}'.format(parts[i][0], parts[i][1]) for i in range(n-1, -1, -1)]) v[-1] += '.' return '\n'.join(v) def rhyme():
64
64
21
3
61
mambocab/xpython
house/example.py
Python
rhyme
rhyme
23
24
23
23
79a393848de854e565b45ab3cb5dcb878a67747c
bigcode/the-stack
train
3b8ae7cbff6145136403c61f
train
function
def _verse(n): v = ['This is {}'.format(parts[n][1])] v.extend(['that {0} {1}'.format(parts[i][0], parts[i][1]) for i in range(n-1, -1, -1)]) v[-1] += '.' return '\n'.join(v)
def _verse(n):
v = ['This is {}'.format(parts[n][1])] v.extend(['that {0} {1}'.format(parts[i][0], parts[i][1]) for i in range(n-1, -1, -1)]) v[-1] += '.' return '\n'.join(v)
('woke', 'the priest all shaven and shorn'), ('kept', 'the rooster that crowed in the morn'), ('belonged to', 'the farmer sowing his corn'), ('', 'the horse and the hound and the horn')] def _verse(n):
63
64
71
5
58
mambocab/xpython
house/example.py
Python
_verse
_verse
15
20
15
15
ec6bc417ae2c906d4444334805a1fdfbd4bff53d
bigcode/the-stack
train
726f1da2ea99a89c09037d8a
train
class
class AbletonRawMarker(Marker): """ time for an Ableton raw marker is beat number (float) (not seconds time) """ @classmethod def fromxml(cls, locator): """ locator is the xml element that corresponds to the locator """ beat = float(locator.find('Time').get('Value')) ...
class AbletonRawMarker(Marker):
""" time for an Ableton raw marker is beat number (float) (not seconds time) """ @classmethod def fromxml(cls, locator): """ locator is the xml element that corresponds to the locator """ beat = float(locator.find('Time').get('Value')) # TODO: what if not foun...
# TODO: raise an error if doesn't match the ableton magic or something # validate project file version AbletonSetVersion = namedtuple('AbletonSetVersion', 'major minor minorA minorB minorC schema_change_count creator revision') # # Markers # class AbletonRawMarker(Marker):
64
64
135
8
56
offlinemark/dawtool
dawtool/daw/ableton.py
Python
AbletonRawMarker
AbletonRawMarker
45
65
45
45
600cdd6a41aef68e909d8ddb2d967f19c160b48f
bigcode/the-stack
train
45626f386474f7c87d8c0f9d
train
class
class AbletonProject(Project): EXT = '.als' TEMPO_QUANT = 16 # tempo automation quantized to 16th notes LOCATORS_TAG = 'Locators' TEMPO_TAG = 'Tempo' def __init__(self, filename, stream, *args, **kwargs): super().__init__(filename, stream, *args, **kwargs) # TODO: add underscores ...
class AbletonProject(Project):
EXT = '.als' TEMPO_QUANT = 16 # tempo automation quantized to 16th notes LOCATORS_TAG = 'Locators' TEMPO_TAG = 'Tempo' def __init__(self, filename, stream, *args, **kwargs): super().__init__(filename, stream, *args, **kwargs) # TODO: add underscores for priv self.beats_per...
1X') if curve1x is None: # Should either have all the curve controls, or none of them return cls(id, time, None, value, None, None, None) curve1y = float_event.get('CurveControl1Y') curve2x = float_event.get('CurveControl2X') curve2y = float_event.get('CurveContr...
256
256
1,710
6
250
offlinemark/dawtool
dawtool/daw/ableton.py
Python
AbletonProject
AbletonProject
141
349
141
141
8e4f1873e4d45b86521de783da68f8dca37e8b21
bigcode/the-stack
train
73024e382db0caee5e86c516
train
class
class TempoAutomationFloatEvent(AutomationFloatEvent): @property def bpm(self): return self.value @bpm.setter def bpm(self, val): self.value = val @property def beat(self): return self.time @beat.setter def beat(self, val): self.time = val
class TempoAutomationFloatEvent(AutomationFloatEvent): @property
def bpm(self): return self.value @bpm.setter def bpm(self, val): self.value = val @property def beat(self): return self.time @beat.setter def beat(self, val): self.time = val
(curve2y)) return cls(id, time, None, value, curve_control1, curve_control2, None) # It's really confusing to use .time and .value above, so here's an alias # with more semantic meaning. class TempoAutomationFloatEvent(AutomationFloatEvent): @property
64
64
75
14
50
offlinemark/dawtool
dawtool/daw/ableton.py
Python
TempoAutomationFloatEvent
TempoAutomationFloatEvent
119
134
119
120
a9e828aba75fcba148267719870d55b73cb0765b
bigcode/the-stack
train
513b2ff7ebb34e29eba129c3
train
class
@dataclass class AutomationFloatEvent: """ For tempo automation, time is beat num, not seconds time. real_time is seconds time. (only present here, not in the xml) """ id: str time: float real_time: float # computed value: float curve_control1: CurveControl curve_control2: Curve...
@dataclass class AutomationFloatEvent:
""" For tempo automation, time is beat num, not seconds time. real_time is seconds time. (only present here, not in the xml) """ id: str time: float real_time: float # computed value: float curve_control1: CurveControl curve_control2: CurveControl # this one is an to optimi...
locator is the xml element that corresponds to the locator """ beat = float(locator.find('Time').get('Value')) # TODO: what if not found? text = locator.find('Name').get('Value').strip() return cls(beat, text) @property def beat(self): return self.time ...
116
116
388
8
108
offlinemark/dawtool
dawtool/daw/ableton.py
Python
AutomationFloatEvent
AutomationFloatEvent
73
114
73
74
c17b8b97b5837b5775e83f5baacf8a645737ce9b
bigcode/the-stack
train
81d07b1203129fadbba32283
train
function
def initialize_datasets(train_directory: str, batch_size: int, crop_size: int = 96, upscale_factor: int = 4, dataset_multiplier: int = 1, workers: int = 16, distributed: bool = False) -> Tuple[DataLoader, DataLoader]: ""...
def initialize_datasets(train_directory: str, batch_size: int, crop_size: int = 96, upscale_factor: int = 4, dataset_multiplier: int = 1, workers: int = 16, distributed: bool = False) -> Tuple[DataLoader, DataLoader]:
""" Initialize testing and training datasets. Given a directory full of high quality sample images, randomly divide the directory up so 90% of the images are in the training dataset and the remaining 10% are in the testing dataset. The datasets are then converted to PyTorch DataLoaders which ar...
_factor=upscale_factor) if distributed: test_sampler = DistributedSampler(test_data) testloader = DataLoader( dataset=test_data, sampler=test_sampler, num_workers=workers, batch_size=1, persistent_workers=True ) else: te...
157
157
526
64
92
roclark/torchsr
torchsr/dataset.py
Python
initialize_datasets
initialize_datasets
345
401
345
349
ad75decbc8d1cbb97f0c188e2793a50b3de50299
bigcode/the-stack
train
e891b507452dfdb5ac3ad199
train
class
class TrainData(Dataset): """ Build the training dataset with transformations. Helper class which first creates a list of supported images given a directory as input and generates transformations based on those images. The high resolution image is taken directly from the source image and a random ...
class TrainData(Dataset):
""" Build the training dataset with transformations. Helper class which first creates a list of supported images given a directory as input and generates transformations based on those images. The high resolution image is taken directly from the source image and a random NxN cropping is taken f...
Resize, ToPILImage, ToTensor) from torchvision.transforms.functional import InterpolationMode from typing import Tuple SUPPORTED_IMAGES = ('.jpg', '.jpeg', '.png') def _image_dataset(directory: str) -> list: ...
185
185
619
6
178
roclark/torchsr
torchsr/dataset.py
Python
TrainData
TrainData
55
136
55
55
d63aeee0fef60cff862f042647034282fc6401a6
bigcode/the-stack
train
5c49cb480d1eafb128b716ee
train
class
class TestData(Dataset): """ Build the test dataset with transformations. Helper class which first creates a list of supported images given a directory as input and generates transformations based on those images. The high resolution image is taken directly from the source image and a random Nx...
class TestData(Dataset):
""" Build the test dataset with transformations. Helper class which first creates a list of supported images given a directory as input and generates transformations based on those images. The high resolution image is taken directly from the source image and a random NxN cropping is taken from ...
]: """ Sample a single image from the dataset. Given an index, open the resulting image from the dataset and perform the high and low resolution transformations on the image before returning the resulting low and high resolution images. Parameters ---------- ...
203
203
679
6
197
roclark/torchsr
torchsr/dataset.py
Python
TestData
TestData
139
224
139
139
91330babe7277c940072e875afdba0ae404bef45
bigcode/the-stack
train
2d3c3864ba76561d5b022267
train
function
def _train_dataset(train_subset: list, batch_size: int, crop_size: int = 96, upscale_factor: int = 4, dataset_multiplier: int = 1, workers: int = 16, distributed: bool = False) -> DataLoader: """ Build a training dataset based on the in...
def _train_dataset(train_subset: list, batch_size: int, crop_size: int = 96, upscale_factor: int = 4, dataset_multiplier: int = 1, workers: int = 16, distributed: bool = False) -> DataLoader:
""" Build a training dataset based on the input directory. Create a PyTorch DataLoader instance with multiple pipelined workers to reduce data reading and processing bottlenecks. Parameters ---------- train_subset : list A ``list`` of images to be used in the training dataset. ...
(high_res) bicubic = self.bicubic(low_res) return low_res, bicubic, high_res def __len__(self) -> int: """ Return the number of images in the dataset. Returns ------- int Returns an ``int`` of the number of images in the dataset. """ ...
137
137
459
59
78
roclark/torchsr
torchsr/dataset.py
Python
_train_dataset
_train_dataset
227
287
227
231
727e700c8692921f75b85feaa0693f2e807d0143
bigcode/the-stack
train
14f9bb87dc0b2bf541d319a6
train
function
def _image_dataset(directory: str) -> list: """ Build list of images in the dataset directory. Given a directory, find all supported image types in the directory and save the path and filename for each image to be used for the dataset. Parameters ---------- directory : str A ``stri...
def _image_dataset(directory: str) -> list:
""" Build list of images in the dataset directory. Given a directory, find all supported image types in the directory and save the path and filename for each image to be used for the dataset. Parameters ---------- directory : str A ``string`` of the directory containing images to s...
RandomCrop, RandomHorizontalFlip, RandomVerticalFlip, Resize, ToPILImage, ToTensor) from torchvision.transforms.functional import Interpola...
64
64
139
11
53
roclark/torchsr
torchsr/dataset.py
Python
_image_dataset
_image_dataset
32
52
32
32
a87e952ce068544844d19cb0868a8f167392a408
bigcode/the-stack
train
16ff3d50585f58915bf60f28
train
function
def _test_dataset(test_subset: list, upscale_factor: int = 4, crop_size: int = 96, workers: int = 16, distributed: bool = False) -> DataLoader: """ Build a testing dataset based on the input directory. Create a PyTorch DataLoader insta...
def _test_dataset(test_subset: list, upscale_factor: int = 4, crop_size: int = 96, workers: int = 16, distributed: bool = False) -> DataLoader:
""" Build a testing dataset based on the input directory. Create a PyTorch DataLoader instance to be used to test the latest model after each epoch. Parameters ---------- test_subset : list A ``list`` of images to be used in the testing dataset. upscale_factor : int An ...
dataset=train_data, sampler=train_sampler, num_workers=workers, batch_size=batch_size, persistent_workers=True ) else: trainloader = DataLoader( dataset=train_data, num_workers=workers, batch_size=batch_s...
113
113
379
46
66
roclark/torchsr
torchsr/dataset.py
Python
_test_dataset
_test_dataset
290
342
290
294
bf4f1228d8b353afc1bb34f15b4606423c25eb76
bigcode/the-stack
train
69fd2e46359e5296d1cc61b1
train
function
def on_enter_unproved(event_data): dispatch_events([CommitEvent(offer=event_data.model)])
def on_enter_unproved(event_data):
dispatch_events([CommitEvent(offer=event_data.model)])
] def __init__(self, commitment_signature, commitment_proof): super(CommitmentProofStateChange, self).__init__(commitment_proof.offer_id) self.commitment_signature = commitment_signature self.commitment_proof = commitment_proof def on_enter_unproved(event_data):
64
64
21
8
55
luehrsFred/raidex
raidex/raidex_node/order/events.py
Python
on_enter_unproved
on_enter_unproved
39
40
39
39
f9a00f245aa8b61203b06b9ba7719c06e4f87eef
bigcode/the-stack
train
f977cf29a4126f987d4060fb
train
class
class OfferStateChange: __slots__ = [ 'offer_id', ] def __init__(self, offer_id): self.offer_id = offer_id
class OfferStateChange:
__slots__ = [ 'offer_id', ] def __init__(self, offer_id): self.offer_id = offer_id
from raidex.raidex_node.architecture.event_architecture import dispatch_events from raidex.raidex_node.commitment_service.events import CommitEvent, CommitmentProvedEvent, ReceivedInboundEvent, CancellationRequestEvent class OfferStateChange:
49
64
36
5
43
luehrsFred/raidex
raidex/raidex_node/order/events.py
Python
OfferStateChange
OfferStateChange
5
12
5
6
9228197f646285fe62baf27cea1160c332dbedd6
bigcode/the-stack
train
01d2987047a5e420039e0460
train
function
def on_enter_cancellation(event_data): dispatch_events([CancellationRequestEvent(offer=event_data.model)])
def on_enter_cancellation(event_data):
dispatch_events([CancellationRequestEvent(offer=event_data.model)])
(event_data): dispatch_events([CommitmentProvedEvent(offer=event_data.model)]) def initiate_refund(event_data): dispatch_events([ReceivedInboundEvent(offer=event_data.model, raiden_event=event_data.kwargs['raiden_event'])]) def on_enter_cancellation(event_data):
64
64
22
8
56
luehrsFred/raidex
raidex/raidex_node/order/events.py
Python
on_enter_cancellation
on_enter_cancellation
52
53
52
52
83defa699b9fa8045e73f947b71f9cd6bdea2c9b
bigcode/the-stack
train
1de2549dc8480d2a6af1e986
train
function
def initiate_refund(event_data): dispatch_events([ReceivedInboundEvent(offer=event_data.model, raiden_event=event_data.kwargs['raiden_event'])])
def initiate_refund(event_data):
dispatch_events([ReceivedInboundEvent(offer=event_data.model, raiden_event=event_data.kwargs['raiden_event'])])
self.commitment_proof = commitment_proof def on_enter_unproved(event_data): dispatch_events([CommitEvent(offer=event_data.model)]) def on_enter_published(event_data): dispatch_events([CommitmentProvedEvent(offer=event_data.model)]) def initiate_refund(event_data):
63
64
36
7
56
luehrsFred/raidex
raidex/raidex_node/order/events.py
Python
initiate_refund
initiate_refund
47
49
47
47
363899c4669190a760aa59f76ca093b9100249ba
bigcode/the-stack
train
56aebad0cc3775f77ad5e2f0
train
class
class OfferTimeoutEvent(OfferStateChange): __slots__ = [ 'timeout_date' ] def __init__(self, offer_id, timeout_date): super(OfferTimeoutEvent, self).__init__(offer_id) self.timeout_date = timeout_date
class OfferTimeoutEvent(OfferStateChange):
__slots__ = [ 'timeout_date' ] def __init__(self, offer_id, timeout_date): super(OfferTimeoutEvent, self).__init__(offer_id) self.timeout_date = timeout_date
_service.events import CommitEvent, CommitmentProvedEvent, ReceivedInboundEvent, CancellationRequestEvent class OfferStateChange: __slots__ = [ 'offer_id', ] def __init__(self, offer_id): self.offer_id = offer_id class OfferTimeoutEvent(OfferStateChange):
64
64
57
9
54
luehrsFred/raidex
raidex/raidex_node/order/events.py
Python
OfferTimeoutEvent
OfferTimeoutEvent
15
23
15
16
a3d62b2ae6765262ad8ae722d48200b9d35fdfcf
bigcode/the-stack
train
4f77acc890b836e395a6dccc
train
class
class CommitmentProofStateChange(OfferStateChange): __slots__ = [ 'commitment_signature', 'commitment_proof' ] def __init__(self, commitment_signature, commitment_proof): super(CommitmentProofStateChange, self).__init__(commitment_proof.offer_id) self.commitment_signature =...
class CommitmentProofStateChange(OfferStateChange):
__slots__ = [ 'commitment_signature', 'commitment_proof' ] def __init__(self, commitment_signature, commitment_proof): super(CommitmentProofStateChange, self).__init__(commitment_proof.offer_id) self.commitment_signature = commitment_signature self.commitment_proof =...
Event(OfferStateChange): __slots__ = [ 'timeout_date' ] def __init__(self, offer_id, timeout_date): super(OfferTimeoutEvent, self).__init__(offer_id) self.timeout_date = timeout_date class CommitmentProofStateChange(OfferStateChange):
64
64
85
10
53
luehrsFred/raidex
raidex/raidex_node/order/events.py
Python
CommitmentProofStateChange
CommitmentProofStateChange
26
36
26
27
8853305a682b52a8b6ec8bdaf8eb43451046be82
bigcode/the-stack
train
28139752e5bd67d7136b6fce
train
function
def on_enter_published(event_data): dispatch_events([CommitmentProvedEvent(offer=event_data.model)])
def on_enter_published(event_data):
dispatch_events([CommitmentProvedEvent(offer=event_data.model)])
StateChange, self).__init__(commitment_proof.offer_id) self.commitment_signature = commitment_signature self.commitment_proof = commitment_proof def on_enter_unproved(event_data): dispatch_events([CommitEvent(offer=event_data.model)]) def on_enter_published(event_data):
63
64
24
8
55
luehrsFred/raidex
raidex/raidex_node/order/events.py
Python
on_enter_published
on_enter_published
43
44
43
43
ebbc0b6d3347f8590c8dbdc83269e11ebe9508cf
bigcode/the-stack
train
5443c60be6f24ad7d75278cb
train
class
class TestInit(TestCase): def setUp(self) -> None: self.maxDiff = None self.runner = CliRunner() self.init = init @patch('gameta.cli.click.Context.ensure_object') def test_init_with_default_values_folder_is_not_a_git_repo(self, mock_ensure_object): with self.runner.isolated_...
class TestInit(TestCase):
def setUp(self) -> None: self.maxDiff = None self.runner = CliRunner() self.init = init @patch('gameta.cli.click.Context.ensure_object') def test_init_with_default_values_folder_is_not_a_git_repo(self, mock_ensure_object): with self.runner.isolated_filesystem() as f: ...
import json import zipfile from os import listdir from os.path import join, dirname, basename from shutil import copyfile from unittest import TestCase from unittest.mock import patch from click.testing import CliRunner from gameta.context import GametaContext from gameta.init import init, sync class TestInit(TestCa...
72
256
1,511
6
65
genius-systems/gameta
tests/test_init.py
Python
TestInit
TestInit
16
193
16
16
71bcd24d3c230bfdcea91236109ada3e29fe3904
bigcode/the-stack
train
70f3e23c8b81a5710dcd0a3d
train
class
class TestSync(TestCase): def setUp(self) -> None: self.maxDiff = None self.runner = CliRunner() self.sync = sync @patch('gameta.cli.click.Context.ensure_object') def test_sync_empty_meta_file(self, mock_ensure_object): with self.runner.isolated_filesystem() as f: ...
class TestSync(TestCase):
def setUp(self) -> None: self.maxDiff = None self.runner = CliRunner() self.sync = sync @patch('gameta.cli.click.Context.ensure_object') def test_sync_empty_meta_file(self, mock_ensure_object): with self.runner.isolated_filesystem() as f: with zipfile.ZipFile(joi...
copyfile(join(dirname(__file__), 'data', '.gitignore'), join(f, '.gitignore')) context = GametaContext() context.project_dir = f context.load() mock_ensure_object.return_value = context result = self.runner.invoke(self.init) self.assert...
256
256
900
6
250
genius-systems/gameta
tests/test_init.py
Python
TestSync
TestSync
196
274
196
196
1050d9a9794076e073f5914a2ee225800823df3d
bigcode/the-stack
train
d5fd1ba3b71a809f1a2fad88
train
function
def set_short_rest_time(short_rest_time): short_rest_time = input("Enter short rest time :") return short_rest_time
def set_short_rest_time(short_rest_time):
short_rest_time = input("Enter short rest time :") return short_rest_time
import sqlite3 #creates database and cursor conn = sqlite3.connect('pomodoro.db') c = conn.cursor() def set_task_time(): pomodoro_time = input("Enter task time :") return pomodoro_time #set short rest intervals def set_short_rest_time(short_rest_time):
61
64
26
9
51
AustinRoy7/Pomodoro-timer
settings.py
Python
set_short_rest_time
set_short_rest_time
12
14
12
12
e97771cc519adf5b5d7454bb7ca8452eb32025c1
bigcode/the-stack
train
fa805706686f1ee7e4bb1f7b
train
function
def set_task_time(): pomodoro_time = input("Enter task time :") return pomodoro_time
def set_task_time():
pomodoro_time = input("Enter task time :") return pomodoro_time
import sqlite3 #creates database and cursor conn = sqlite3.connect('pomodoro.db') c = conn.cursor() def set_task_time():
30
64
22
5
25
AustinRoy7/Pomodoro-timer
settings.py
Python
set_task_time
set_task_time
7
9
7
7
e62c317e3119a2531b9fbbf6e92d33cd57bf5af6
bigcode/the-stack
train
bc3810604ce6f765cd8d9990
train
function
def set_long_rest_time(): long_rest_time = input("Enter long rest time :") return long_rest_time
def set_long_rest_time():
long_rest_time = input("Enter long rest time :") return long_rest_time
def set_task_time(): pomodoro_time = input("Enter task time :") return pomodoro_time #set short rest intervals def set_short_rest_time(short_rest_time): short_rest_time = input("Enter short rest time :") return short_rest_time #set long rest intervals def set_long_rest_time():
64
64
22
6
57
AustinRoy7/Pomodoro-timer
settings.py
Python
set_long_rest_time
set_long_rest_time
17
19
17
17
2009c6923d7b7f315e778b387a4852ff65ab8389
bigcode/the-stack
train
49d1582c6930e24cead0789b
train
function
def build_labels_7_tag(tag,data_name,time_inds): with open("./dataset/" + data_name + "/pkl/real_changes_per_label/matrix_labels_per_person.pkl", 'rb') as f: g = pickle.load(f) print(len(g)) 'for each person, take the 7th column' persons_7_vector = np.zeros((len(g), time_inds)) persons_7_lab...
def build_labels_7_tag(tag,data_name,time_inds):
with open("./dataset/" + data_name + "/pkl/real_changes_per_label/matrix_labels_per_person.pkl", 'rb') as f: g = pickle.load(f) print(len(g)) 'for each person, take the 7th column' persons_7_vector = np.zeros((len(g), time_inds)) persons_7_labeled = np.zeros(len(g)) label_all_0 = 0 l...
7_vector[idx][neg_tuple[0] - 1] == 0: persons_7_vector[idx][neg_tuple[0]:neg_tuple[1] + 1] = 0 else: persons_7_vector[idx][neg_tuple[0]:neg_tuple[1] + 1] = label_1 else: if persons_7_vector[idx][neg_tuple[1] + 1] > 0 and persons_7_vector[idx][neg_tuple[0] ...
180
180
603
12
167
rachelic44/Transitions
Communal_Transitions/real_changes/real_changes.py
Python
build_labels_7_tag
build_labels_7_tag
76
128
76
76
ba105089c34b3a61e886166d1fe5c1b8dc5bf878
bigcode/the-stack
train