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
10f472a238f94874d8350455
train
class
class ResourceClassNotFound(HTTPNotFound): message = _("Resource class %(resource_class)s could not be found.")
class ResourceClassNotFound(HTTPNotFound):
message = _("Resource class %(resource_class)s could not be found.")
NotFound(HTTPNotFound): message = _("Zun service %(binary)s on host %(host)s could not be found.") class ResourceProviderNotFound(HTTPNotFound): message = _("Resource provider %(resource_provider)s could not be found.") class ResourceClassNotFound(HTTPNotFound):
63
64
25
10
53
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ResourceClassNotFound
ResourceClassNotFound
375
376
375
375
b4b856926016c39a776f4277b34b25f04762c939
bigcode/the-stack
train
8a1d31e4c71ff1f553d7bf18
train
class
class CapsuleAlreadyExists(ResourceExists): message = _("A capsule with %(field)s %(value)s already exists.")
class CapsuleAlreadyExists(ResourceExists):
message = _("A capsule with %(field)s %(value)s already exists.")
," " but not both") class PciDeviceNotFoundById(NotFound): message = _("PCI device %(id)s not found") class PciDeviceNotFound(NotFound): message = _("PCI Device %(node_id)s:%(address)s not found.") class CapsuleAlreadyExists(ResourceExists):
63
64
23
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
CapsuleAlreadyExists
CapsuleAlreadyExists
551
552
551
551
ed4ce4132cca44d284a24e3bcc6fccb85cbec35a
bigcode/the-stack
train
59cc21e2fd4b87f3003f45de
train
function
def wrap_exception(notifier=None, event_type=None): """This decorator wraps a method to catch any exceptions. It logs the exception as well as optionally sending it to the notification system. """ def inner(f): def wrapped(self, context, *args, **kwargs): # Don't store self or c...
def wrap_exception(notifier=None, event_type=None):
"""This decorator wraps a method to catch any exceptions. It logs the exception as well as optionally sending it to the notification system. """ def inner(f): def wrapped(self, context, *args, **kwargs): # Don't store self or context in the payload, it now seems to #...
. As it changed import group. So # add here before branch to prevent gate failure. # Bug: #1447873 CONF.import_opt('fatal_exception_format_errors', 'oslo_versionedobjects.exception', group='oslo_versionedobjects') def wrap_exception(notifier=None, event_type=None):
68
68
229
11
57
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
wrap_exception
wrap_exception
56
87
56
56
adf5bec3e0712a645d15a4415c4a61c8c0dc851d
bigcode/the-stack
train
0d3e5aeb0965ccfa3eff5b47
train
class
class ConnectionFailed(ZunException): message = _("Failed to connect to remote host")
class ConnectionFailed(ZunException):
message = _("Failed to connect to remote host")
NotFound(NotFound): message = _("Class %(class_name)s could not be found: %(exception)s") class ApiVersionsIntersect(ZunException): message = _("Version of %(name)s %(min_ver)s %(max_ver)s intersects " "with another versions.") class ConnectionFailed(ZunException):
63
64
18
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ConnectionFailed
ConnectionFailed
505
506
505
505
bbd15ad53307f2c3882b25c28be55f6d2ac31980
bigcode/the-stack
train
d5d543a5552f3b0711d143a0
train
class
class PciDeviceInvalidDeviceName(ZunException): message = _("Invalid PCI Whitelist: " "The PCI whitelist can specify devname or address," " but not both")
class PciDeviceInvalidDeviceName(ZunException):
message = _("Invalid PCI Whitelist: " "The PCI whitelist can specify devname or address," " but not both")
.") class PciConfigInvalidWhitelist(ZunException): message = _("Invalid PCI devices Whitelist config %(reason)s") class PciDeviceWrongAddressFormat(ZunException): message = _("The PCI address %(address)s has an incorrect format.") class PciDeviceInvalidDeviceName(ZunException):
63
64
39
11
52
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
PciDeviceInvalidDeviceName
PciDeviceInvalidDeviceName
537
540
537
537
40cd7253f35d5dd579c37318fe382bbce056b8b6
bigcode/the-stack
train
679ed7110daf6ad3b19ede30
train
class
class PciConfigInvalidWhitelist(ZunException): message = _("Invalid PCI devices Whitelist config %(reason)s")
class PciConfigInvalidWhitelist(ZunException):
message = _("Invalid PCI devices Whitelist config %(reason)s")
class InvalidWebsocketToken(ZunException): message = _("Websocket token is invalid") class ValidationError(ZunException): message = _("Validation error") class ResourcesUnavailable(ZunException): message = _("Insufficient compute resources: %(reason)s.") class PciConfigInvalidWhitelist(ZunException):
63
64
24
10
53
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
PciConfigInvalidWhitelist
PciConfigInvalidWhitelist
529
530
529
529
094f0cfe30faf5a74748233ba825dcd71c766aca
bigcode/the-stack
train
01a6d2d0ecfc56d0d83d0410
train
class
class InvalidIdentity(Invalid): message = _("Expected an uuid or int but received %(identity)s.")
class InvalidIdentity(Invalid):
message = _("Expected an uuid or int but received %(identity)s.")
covery_endpoint)s'.") class GetDiscoveryUrlFailed(ZunException): message = _("Failed to get discovery url from '%(discovery_endpoint)s'.") class InvalidUuidOrName(Invalid): message = _("Expected a name or uuid but received %(uuid)s.") class InvalidIdentity(Invalid):
63
64
21
6
57
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidIdentity
InvalidIdentity
295
296
295
295
a575b6a92103315623ba7858f7e08448b39300f4
bigcode/the-stack
train
0d8d43b394f50155f932598e
train
class
class SocketException(ZunException): message = _("Socket exceptions")
class SocketException(ZunException):
message = _("Socket exceptions")
: %(exception)s") class ApiVersionsIntersect(ZunException): message = _("Version of %(name)s %(min_ver)s %(max_ver)s intersects " "with another versions.") class ConnectionFailed(ZunException): message = _("Failed to connect to remote host") class SocketException(ZunException):
64
64
14
7
57
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
SocketException
SocketException
509
510
509
509
432dbf4fc26fe559ec4064947803c82ad9fe5408
bigcode/the-stack
train
53c9f60f1132e11664fb0b76
train
function
def wrap_keystone_exception(func): """Wrap keystone exceptions and throw Zun specific exceptions.""" @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except keystone_exceptions.AuthorizationFailure: raise AuthorizationFailure( ...
def wrap_keystone_exception(func):
"""Wrap keystone exceptions and throw Zun specific exceptions.""" @functools.wraps(func) def wrapped(*args, **kwargs): try: return func(*args, **kwargs) except keystone_exceptions.AuthorizationFailure: raise AuthorizationFailure( client=func.__name__, ...
.status = status_code return { 'status_code': status_code, 'title': six.text_type(excp), 'description': six.text_type(excp), } return wrap_controller_exception(func, _func_server_error, _fu...
64
64
131
7
57
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
wrap_keystone_exception
wrap_keystone_exception
155
169
155
155
6b304d8b9b6021ef54fde687fb7cb17476cbf078
bigcode/the-stack
train
9aeaefdcf862075a0d317ba3
train
class
class InvalidCapsuleTemplate(ZunException): message = _("Invalid capsule template: %(reason)s.")
class InvalidCapsuleTemplate(ZunException):
message = _("Invalid capsule template: %(reason)s.")
address)s not found.") class CapsuleAlreadyExists(ResourceExists): message = _("A capsule with %(field)s %(value)s already exists.") class CapsuleNotFound(HTTPNotFound): message = _("Capsule %(capsule)s could not be found.") class InvalidCapsuleTemplate(ZunException):
63
64
21
9
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidCapsuleTemplate
InvalidCapsuleTemplate
559
560
559
559
2efb2c77d7e4f7b7719ea2fa6cb33d498773ea3b
bigcode/the-stack
train
e81e4cd05a7d83de4c8afaff
train
class
class ValidationError(Invalid): message = "%(detail)s"
class ValidationError(Invalid):
message = "%(detail)s"
%(method)s on orphaned %(objtype)s object') class Invalid(ZunException): message = _("Unacceptable parameters.") code = 400 class InvalidValue(Invalid): message = _("Received value '%(value)s' is invalid for type %(type)s.") class ValidationError(Invalid):
63
64
14
6
57
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ValidationError
ValidationError
266
267
266
266
fadb6174f68f5c589ab5b2ab859c486e3da8b93e
bigcode/the-stack
train
83ebfe85114a439ad70806cb
train
class
class ZunServiceNotFound(HTTPNotFound): message = _("Zun service %(binary)s on host %(host)s could not be found.")
class ZunServiceNotFound(HTTPNotFound):
message = _("Zun service %(binary)s on host %(host)s could not be found.")
not be found.") class PortNotFound(HTTPNotFound): message = _("Neutron port %(port)s could not be found.") class ImageNotFound(HTTPNotFound): message = _("Image %(image)s could not be found.") class ZunServiceNotFound(HTTPNotFound):
63
64
31
11
52
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ZunServiceNotFound
ZunServiceNotFound
367
368
367
367
81a748cd4a4046694c8c90e3bd51cbf2b30d61c2
bigcode/the-stack
train
ff2150ef71e106bd7f35d956
train
class
class GetDiscoveryUrlFailed(ZunException): message = _("Failed to get discovery url from '%(discovery_endpoint)s'.")
class GetDiscoveryUrlFailed(ZunException):
message = _("Failed to get discovery url from '%(discovery_endpoint)s'.")
(Invalid): message = _("Expected a name but received %(uuid)s.") class InvalidDiscoveryURL(Invalid): message = _("Received invalid discovery URL '%(discovery_url)s' for " "discovery endpoint '%(discovery_endpoint)s'.") class GetDiscoveryUrlFailed(ZunException):
63
64
27
9
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
GetDiscoveryUrlFailed
GetDiscoveryUrlFailed
287
288
287
287
8e448d8ecae52c954c2bb718bbd7e69cdb44aedf
bigcode/the-stack
train
ff8b7b07bf720b7da490646b
train
function
def wrap_controller_exception(func, func_server_error, func_client_error): """This decorator wraps controllers methods to handle exceptions: - if an unhandled Exception or a ZunException with an error code >=500 is catched, raise a http 5xx ClientSideError and correlates it with a log message - if...
def wrap_controller_exception(func, func_server_error, func_client_error):
"""This decorator wraps controllers methods to handle exceptions: - if an unhandled Exception or a ZunException with an error code >=500 is catched, raise a http 5xx ClientSideError and correlates it with a log message - if a ZunException is catched and its error code is <500, raise a http 4xx...
ensure the name is # propagated. temp_type = f.__name__ notifier.error(context, temp_type, payload) return functools.wraps(f)(wrapped) return inner OBFUSCATED_MSG = _('Your request could not be handled ' ...
91
91
304
14
77
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
wrap_controller_exception
wrap_controller_exception
95
129
95
95
b4cb85cbea80e493d01ccf3cc6340c538174db14
bigcode/the-stack
train
28a9595fdb16731a164f99a7
train
class
class InvalidUuidOrName(Invalid): message = _("Expected a name or uuid but received %(uuid)s.")
class InvalidUuidOrName(Invalid):
message = _("Expected a name or uuid but received %(uuid)s.")
_("Received invalid discovery URL '%(discovery_url)s' for " "discovery endpoint '%(discovery_endpoint)s'.") class GetDiscoveryUrlFailed(ZunException): message = _("Failed to get discovery url from '%(discovery_endpoint)s'.") class InvalidUuidOrName(Invalid):
63
64
23
8
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidUuidOrName
InvalidUuidOrName
291
292
291
291
f79e773d09902126c2759e8db97bd24c4330f2ef
bigcode/the-stack
train
49a119fb9e346882ab0eed64
train
class
class CPUUnpinningUnknown(Invalid): message = _("CPU set to unpin %(requested)s must be a subset of " "known CPU set %(cpuset)s")
class CPUUnpinningUnknown(Invalid):
message = _("CPU set to unpin %(requested)s must be a subset of " "known CPU set %(cpuset)s")
reason)s") class NoInteractiveFlag(Invalid): message = _("%(msg)s") class CPUPinningUnknown(ZunException): message = _("CPU set to pin %(requested)s must be a subset of " "known CPU set %(cpuset)s") class CPUUnpinningUnknown(Invalid):
64
64
37
9
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
CPUUnpinningUnknown
CPUUnpinningUnknown
472
474
472
472
2f62868252a7f5f34bdf3e4d9f8d812866c393c0
bigcode/the-stack
train
d90a4bb576fece4437bee8cf
train
class
class ConfigInvalid(ZunException): message = _("Invalid configuration file. %(error_msg)s")
class ConfigInvalid(ZunException):
message = _("Invalid configuration file. %(error_msg)s")
(Invalid): message = _('Invalid param %(param)s') class PatchError(Invalid): message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s") class NotAuthorized(ZunException): message = _("Not authorized.") code = 403 class ConfigInvalid(ZunException):
64
64
20
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ConfigInvalid
ConfigInvalid
335
336
335
335
d7c22034b5771f1c9209dac70009003c371ab22d
bigcode/the-stack
train
c54ebd2c923ef0300911658c
train
class
class InvalidStateException(ZunException): message = _("Cannot %(action)s container %(id)s in %(actual_state)s state") code = 409
class InvalidStateException(ZunException):
message = _("Cannot %(action)s container %(id)s in %(actual_state)s state") code = 409
.") class PortBindingFailed(Invalid): message = _("Binding failed for port %(port)s, please check neutron " "logs for more information.") class UniqueConstraintViolated(ResourceExists): message = _("A resource with %(fields)s violates unique constraint.") class InvalidStateException(ZunExcep...
63
64
33
8
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidStateException
InvalidStateException
428
430
428
428
e23bd01187a9a86051e7127f086bf5f87edfb095
bigcode/the-stack
train
0c11ae26f42e9682d7ca513c
train
class
class DockerError(ZunException): message = _("Docker internal error: %(error_msg)s.")
class DockerError(ZunException):
message = _("Docker internal error: %(error_msg)s.")
) class UniqueConstraintViolated(ResourceExists): message = _("A resource with %(fields)s violates unique constraint.") class InvalidStateException(ZunException): message = _("Cannot %(action)s container %(id)s in %(actual_state)s state") code = 409 class DockerError(ZunException):
64
64
20
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
DockerError
DockerError
433
434
433
433
e54207662d8b827742db1ce1882fca844ca0db4c
bigcode/the-stack
train
78d8fe478c7c803c16755e11
train
class
class UnsupportedObjectError(ZunException): message = _('Unsupported object type %(objtype)s')
class UnsupportedObjectError(ZunException):
message = _('Unsupported object type %(objtype)s')
be found.") code = 404 class ResourceExists(ObjectNotUnique): message = _("The %(name)s resource already exists.") code = 409 class AuthorizationFailure(ZunException): message = _("%(client)s connection failed. %(message)s") class UnsupportedObjectError(ZunException):
64
64
20
8
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
UnsupportedObjectError
UnsupportedObjectError
245
246
245
245
d269a67270af84ec1913d102daabb0836335fc4d
bigcode/the-stack
train
09f73d42f6c5fdd4a8b35a17
train
class
class CPUPinningUnknown(ZunException): message = _("CPU set to pin %(requested)s must be a subset of " "known CPU set %(cpuset)s")
class CPUPinningUnknown(ZunException):
message = _("CPU set to pin %(requested)s must be a subset of " "known CPU set %(cpuset)s")
): message = _("The command: %(cmd)s failed on the system.") class NoValidHost(ZunException): message = _("No valid host was found. %(reason)s") class NoInteractiveFlag(Invalid): message = _("%(msg)s") class CPUPinningUnknown(ZunException):
64
64
36
9
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
CPUPinningUnknown
CPUPinningUnknown
467
469
467
467
39f5240fd88edde3a73b10b699d145d5faadcb44
bigcode/the-stack
train
f32fc46afffec48b8bbcdb26
train
class
class PortNotFound(HTTPNotFound): message = _("Neutron port %(port)s could not be found.")
class PortNotFound(HTTPNotFound):
message = _("Neutron port %(port)s could not be found.")
not up.") class ComputeNodeNotFound(HTTPNotFound): message = _("Compute node %(compute_node)s could not be found.") class NetworkNotFound(HTTPNotFound): message = _("Neutron network %(network)s could not be found.") class PortNotFound(HTTPNotFound):
63
64
24
9
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
PortNotFound
PortNotFound
359
360
359
359
c514623d8a593b1f4f67a02d86e458678e4b8ceb
bigcode/the-stack
train
ed73e76e8ed2ca1a8527a6e3
train
class
class NetworkNotFound(HTTPNotFound): message = _("Neutron network %(network)s could not be found.")
class NetworkNotFound(HTTPNotFound):
message = _("Neutron network %(network)s could not be found.")
found.") class ContainerHostNotUp(ZunException): message = _("Container %(container)s host %(host)s is not up.") class ComputeNodeNotFound(HTTPNotFound): message = _("Compute node %(compute_node)s could not be found.") class NetworkNotFound(HTTPNotFound):
63
64
24
9
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
NetworkNotFound
NetworkNotFound
355
356
355
355
60537bab39e339d31d2c28e19ff0e7e65bf25acc
bigcode/the-stack
train
76cad8160344f831c6ff6a66
train
class
class UniqueConstraintViolated(ResourceExists): message = _("A resource with %(fields)s violates unique constraint.")
class UniqueConstraintViolated(ResourceExists):
message = _("A resource with %(fields)s violates unique constraint.")
the container.") class PortInUse(Invalid): message = _("Port %(port)s is still in use.") class PortBindingFailed(Invalid): message = _("Binding failed for port %(port)s, please check neutron " "logs for more information.") class UniqueConstraintViolated(ResourceExists):
63
64
22
8
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
UniqueConstraintViolated
UniqueConstraintViolated
424
425
424
424
b1c12464be6184a7d0e65831c99eceebe22e823e
bigcode/the-stack
train
1ddecf7ca96a4d37b97e348d
train
class
class InvalidDiscoveryURL(Invalid): message = _("Received invalid discovery URL '%(discovery_url)s' for " "discovery endpoint '%(discovery_endpoint)s'.")
class InvalidDiscoveryURL(Invalid):
message = _("Received invalid discovery URL '%(discovery_url)s' for " "discovery endpoint '%(discovery_endpoint)s'.")
" class SchemaValidationError(ValidationError): message = "%(detail)s" class InvalidUUID(Invalid): message = _("Expected a uuid but received %(uuid)s.") class InvalidName(Invalid): message = _("Expected a name but received %(uuid)s.") class InvalidDiscoveryURL(Invalid):
63
64
37
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidDiscoveryURL
InvalidDiscoveryURL
282
284
282
282
96473754983c3bb5399cf7ff9beb8577fe37c516
bigcode/the-stack
train
0c936956284b7881562eb3a6
train
class
class ZunServiceAlreadyExists(ResourceExists): message = _("Service %(binary)s on host %(host)s already exists.")
class ZunServiceAlreadyExists(ResourceExists):
message = _("Service %(binary)s on host %(host)s already exists.")
.") class ComputeNodeAlreadyExists(ResourceExists): message = _("A compute node with %(field)s %(value)s already exists.") class ImageAlreadyExists(ResourceExists): message = _("An image with tag %(tag)s and repo %(repo)s already exists.") class ZunServiceAlreadyExists(ResourceExists):
63
64
25
9
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ZunServiceAlreadyExists
ZunServiceAlreadyExists
399
400
399
399
64c4f6f7a323bf5c96a686e9ee70e3e24885276c
bigcode/the-stack
train
2ea323834ca23f4dcf73c6a9
train
class
class PciDeviceNotFound(NotFound): message = _("PCI Device %(node_id)s:%(address)s not found.")
class PciDeviceNotFound(NotFound):
message = _("PCI Device %(node_id)s:%(address)s not found.")
(ZunException): message = _("Invalid PCI Whitelist: " "The PCI whitelist can specify devname or address," " but not both") class PciDeviceNotFoundById(NotFound): message = _("PCI device %(id)s not found") class PciDeviceNotFound(NotFound):
64
64
26
9
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
PciDeviceNotFound
PciDeviceNotFound
547
548
547
547
28a22b6dabf7814bc3518000b941d85716ea6a02
bigcode/the-stack
train
aee3017536625a9afdd1c07d
train
class
class InvalidUUID(Invalid): message = _("Expected a uuid but received %(uuid)s.")
class InvalidUUID(Invalid):
message = _("Expected a uuid but received %(uuid)s.")
400 class InvalidValue(Invalid): message = _("Received value '%(value)s' is invalid for type %(type)s.") class ValidationError(Invalid): message = "%(detail)s" class SchemaValidationError(ValidationError): message = "%(detail)s" class InvalidUUID(Invalid):
64
64
19
6
58
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidUUID
InvalidUUID
274
275
274
274
0d92bd3f78d0fe5b62df827e6dc7777249371d3a
bigcode/the-stack
train
f51106ddedd3cf0f71833704
train
class
class InvalidCsr(Invalid): message = _("Received invalid csr %(csr)s.")
class InvalidCsr(Invalid):
message = _("Received invalid csr %(csr)s.")
url from '%(discovery_endpoint)s'.") class InvalidUuidOrName(Invalid): message = _("Expected a name or uuid but received %(uuid)s.") class InvalidIdentity(Invalid): message = _("Expected an uuid or int but received %(identity)s.") class InvalidCsr(Invalid):
63
64
18
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidCsr
InvalidCsr
299
300
299
299
487d2e8df4f6ce8f3089b99ddd41069cddd4a1e4
bigcode/the-stack
train
813e29132932e6921b287c2f
train
class
class Conflict(ZunException): message = _('Conflict.') code = 409
class Conflict(ZunException):
message = _('Conflict.') code = 409
received %(uuid)s.") class InvalidIdentity(Invalid): message = _("Expected an uuid or int but received %(identity)s.") class InvalidCsr(Invalid): message = _("Received invalid csr %(csr)s.") class HTTPNotFound(ResourceNotFound): pass class Conflict(ZunException):
64
64
18
6
57
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
Conflict
Conflict
307
309
307
307
57f61563ff85a285411362aedf77a743ffeac36c
bigcode/the-stack
train
c6165423f5c50fb1b20a3535
train
class
class PortInUse(Invalid): message = _("Port %(port)s is still in use.")
class PortInUse(Invalid):
message = _("Port %(port)s is still in use.")
)s %(value)s already exists.") class ResourceClassAlreadyExists(ResourceExists): message = _("A resource class with %(field)s %(value)s already exists.") class PortNotUsable(Invalid): message = _("Port %(port)s not usable for the container.") class PortInUse(Invalid):
63
64
20
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
PortInUse
PortInUse
415
416
415
415
9fbf47847a496b1cfc420c1111d8f2a241ed144d
bigcode/the-stack
train
0ae3169e01770253aa94e624
train
class
class ResourceClassAlreadyExists(ResourceExists): message = _("A resource class with %(field)s %(value)s already exists.")
class ResourceClassAlreadyExists(ResourceExists):
message = _("A resource class with %(field)s %(value)s already exists.")
already exists.") class ZunServiceAlreadyExists(ResourceExists): message = _("Service %(binary)s on host %(host)s already exists.") class ResourceProviderAlreadyExists(ResourceExists): message = _("A resource provider with %(field)s %(value)s already exists.") class ResourceClassAlreadyExists(ResourceExist...
63
64
25
8
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ResourceClassAlreadyExists
ResourceClassAlreadyExists
407
408
407
407
9df73a59e93984f8b39932ea87e531fa68d2a857
bigcode/the-stack
train
57f05e6c7550daa71abeeba5
train
class
class HTTPNotFound(ResourceNotFound): pass
class HTTPNotFound(ResourceNotFound):
pass
message = _("Expected a name or uuid but received %(uuid)s.") class InvalidIdentity(Invalid): message = _("Expected an uuid or int but received %(identity)s.") class InvalidCsr(Invalid): message = _("Received invalid csr %(csr)s.") class HTTPNotFound(ResourceNotFound):
63
64
11
8
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
HTTPNotFound
HTTPNotFound
303
304
303
303
da53a28d1c021d3c360ed11a1f359abfd6649028
bigcode/the-stack
train
97493f4cfdecc16bee10e71b
train
class
class Invalid(ZunException): message = _("Unacceptable parameters.") code = 400
class Invalid(ZunException):
message = _("Unacceptable parameters.") code = 400
type)s') class IncompatibleObjectVersion(ZunException): message = _('Version %(objver)s of %(objname)s is not supported') class OrphanedObjectError(ZunException): message = _('Cannot call %(method)s on orphaned %(objtype)s object') class Invalid(ZunException):
64
64
20
6
58
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
Invalid
Invalid
257
259
257
257
8b1b8521328d756a41fd8fcbb5d6f6a5ce9cc7ac
bigcode/the-stack
train
2ce74931c79ba7c255688616
train
class
class InvalidName(Invalid): message = _("Expected a name but received %(uuid)s.")
class InvalidName(Invalid):
message = _("Expected a name but received %(uuid)s.")
invalid for type %(type)s.") class ValidationError(Invalid): message = "%(detail)s" class SchemaValidationError(ValidationError): message = "%(detail)s" class InvalidUUID(Invalid): message = _("Expected a uuid but received %(uuid)s.") class InvalidName(Invalid):
63
64
19
6
57
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InvalidName
InvalidName
278
279
278
278
49ce1358ec2aeff5e3796425c57d3762aa4e5891
bigcode/the-stack
train
011b5361ce12287e1ac78734
train
class
class CPUPinningInvalid(Invalid): message = _("CPU set to pin %(requested)s must be a subset of " "free CPU set %(free)s")
class CPUPinningInvalid(Invalid):
message = _("CPU set to pin %(requested)s must be a subset of " "free CPU set %(free)s")
%(requested)s must be a subset of " "known CPU set %(cpuset)s") class CPUUnpinningUnknown(Invalid): message = _("CPU set to unpin %(requested)s must be a subset of " "known CPU set %(cpuset)s") class CPUPinningInvalid(Invalid):
64
64
34
8
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
CPUPinningInvalid
CPUPinningInvalid
477
479
477
477
1d6a5953df968875ce612ef654622f8de35b23f5
bigcode/the-stack
train
0539baf091b43d4d7d384e1b
train
class
class CapsuleNotFound(HTTPNotFound): message = _("Capsule %(capsule)s could not be found.")
class CapsuleNotFound(HTTPNotFound):
message = _("Capsule %(capsule)s could not be found.")
)s not found") class PciDeviceNotFound(NotFound): message = _("PCI Device %(node_id)s:%(address)s not found.") class CapsuleAlreadyExists(ResourceExists): message = _("A capsule with %(field)s %(value)s already exists.") class CapsuleNotFound(HTTPNotFound):
63
64
24
9
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
CapsuleNotFound
CapsuleNotFound
555
556
555
555
3d9f699c9e7e2d0667bc30c99d6de5ba2a2f7246
bigcode/the-stack
train
e51110bfefd2261bba828e96
train
class
class ServerUnknownStatus(ZunException): message = _('%(result)s - Unknown status %(resource_status)s due to ' '"%(status_reason)s"')
class ServerUnknownStatus(ZunException):
message = _('%(result)s - Unknown status %(resource_status)s due to ' '"%(status_reason)s"')
error: %(error_msg)s.") class PollTimeOut(ZunException): message = _("Polling request timed out.") class ServerInError(ZunException): message = _('Went to status %(resource_status)s due to ' '"%(status_reason)s"') class ServerUnknownStatus(ZunException):
64
64
34
8
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ServerUnknownStatus
ServerUnknownStatus
446
448
446
446
9de2916d6c39f1b572b6c5d54df238ecc7c02e3c
bigcode/the-stack
train
28e929c38c774af1122ce53d
train
class
class OrphanedObjectError(ZunException): message = _('Cannot call %(method)s on orphaned %(objtype)s object')
class OrphanedObjectError(ZunException):
message = _('Cannot call %(method)s on orphaned %(objtype)s object')
connection failed. %(message)s") class UnsupportedObjectError(ZunException): message = _('Unsupported object type %(objtype)s') class IncompatibleObjectVersion(ZunException): message = _('Version %(objver)s of %(objname)s is not supported') class OrphanedObjectError(ZunException):
64
64
28
10
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
OrphanedObjectError
OrphanedObjectError
253
254
253
253
1eedccdf03f331d4c89e59a9507d495c8d3d11eb
bigcode/the-stack
train
f374a27b2a2da0b606f1b506
train
class
class InventoryNotFound(HTTPNotFound): message = _("Inventory %(inventory)s could not be found.")
class InventoryNotFound(HTTPNotFound):
message = _("Inventory %(inventory)s could not be found.")
found.") class ResourceProviderNotFound(HTTPNotFound): message = _("Resource provider %(resource_provider)s could not be found.") class ResourceClassNotFound(HTTPNotFound): message = _("Resource class %(resource_class)s could not be found.") class InventoryNotFound(HTTPNotFound):
63
64
22
9
54
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
InventoryNotFound
InventoryNotFound
379
380
379
379
043ef459affe3b02331f351704cc9e1ee11ac828
bigcode/the-stack
train
b26648200f0fdc7023e96967
train
class
class ResourceProviderAlreadyExists(ResourceExists): message = _("A resource provider with %(field)s %(value)s already exists.")
class ResourceProviderAlreadyExists(ResourceExists):
message = _("A resource provider with %(field)s %(value)s already exists.")
exists.") class ImageAlreadyExists(ResourceExists): message = _("An image with tag %(tag)s and repo %(repo)s already exists.") class ZunServiceAlreadyExists(ResourceExists): message = _("Service %(binary)s on host %(host)s already exists.") class ResourceProviderAlreadyExists(ResourceExists):
63
64
25
8
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ResourceProviderAlreadyExists
ResourceProviderAlreadyExists
403
404
403
403
a32a9f911e184eee08cde2023f195fe54053f8bf
bigcode/the-stack
train
b472bbed6c1de899df43d111
train
class
class PortNotUsable(Invalid): message = _("Port %(port)s not usable for the container.")
class PortNotUsable(Invalid):
message = _("Port %(port)s not usable for the container.")
already exists.") class ResourceProviderAlreadyExists(ResourceExists): message = _("A resource provider with %(field)s %(value)s already exists.") class ResourceClassAlreadyExists(ResourceExists): message = _("A resource class with %(field)s %(value)s already exists.") class PortNotUsable(Invalid):
63
64
22
8
55
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
PortNotUsable
PortNotUsable
411
412
411
411
dcaf603fb70284b0b63a623444ab8489251e190d
bigcode/the-stack
train
1b77a73a0f4fac39378933e9
train
class
class ContainerAlreadyExists(ResourceExists): message = _("A container with %(field)s %(value)s already exists.")
class ContainerAlreadyExists(ResourceExists):
message = _("A container with %(field)s %(value)s already exists.")
class %(resource_class)s could not be found.") class InventoryNotFound(HTTPNotFound): message = _("Inventory %(inventory)s could not be found.") class AllocationNotFound(HTTPNotFound): message = _("Allocation %(allocation)s could not be found.") class ContainerAlreadyExists(ResourceExists):
63
64
23
7
56
cooldharma06/zun_glance_tag
zun/common/exception.py
Python
ContainerAlreadyExists
ContainerAlreadyExists
387
388
387
387
b9f095b24911ff135500eb1cd4712d8cc0002b20
bigcode/the-stack
train
2c904d57a4fd78a003f957ba
train
class
class DevelopmentEngine(metaclass=Singleton): def __init__(self): self.spark = self.__get_spark() dbutils, ide_environment = self.__get_dbutils(self.spark) self.dbutils = dbutils self.ide_environment = ide_environment def __get_spark(self) -> SparkSession: MAX_MEMORY = ...
class DevelopmentEngine(metaclass=Singleton):
def __init__(self): self.spark = self.__get_spark() dbutils, ide_environment = self.__get_dbutils(self.spark) self.dbutils = dbutils self.ide_environment = ide_environment def __get_spark(self) -> SparkSession: MAX_MEMORY = "5g" spark = SparkSession.builder.\ ...
m in mounts] res = True if mount_name in names else False return res @trace def list_mounts(self) -> list: mounts = self.files('/mnt') return mounts @trace def files(self, path: str) -> list: files = self.dbutils.fs.ls(path) return files @classmeth...
101
101
337
9
92
microsoft/dstoolkit-ml-ops-for-databricks
src/modules/dbkdev/core.py
Python
DevelopmentEngine
DevelopmentEngine
325
363
325
326
e2d7eb6b61cac9a7bddc74bffadb169950daef05
bigcode/the-stack
train
616fd66bb31b64e4d8bbb4c1
train
class
class IdeEnvironment(str, Enum): LOCAL = "local" DATABRICKS = "databricks"
class IdeEnvironment(str, Enum):
LOCAL = "local" DATABRICKS = "databricks"
.sql import DataFrame, SparkSession from dbkcore.core import trace, Log import re from pathlib import Path from typing import Any, List from typeguard import typechecked from dbkcore.core import Singleton from enum import Enum import pkg_resources class IdeEnvironment(str, Enum):
64
64
24
7
56
microsoft/dstoolkit-ml-ops-for-databricks
src/modules/dbkdev/core.py
Python
IdeEnvironment
IdeEnvironment
15
17
15
15
bc135ddfe8c46abae4c7483169160dbef6efcc67
bigcode/the-stack
train
159dbff35ad6cafc5aad9022
train
class
@typechecked class DevelopmentClient(metaclass=Singleton): """ Client to use for local Databricks' local development """ # @trace def __init__( self, dbutils, spark: SparkSession, ide_environment: IdeEnvironment # deployment_environment: DeploymentEnvironment...
@typechecked class DevelopmentClient(metaclass=Singleton):
""" Client to use for local Databricks' local development """ # @trace def __init__( self, dbutils, spark: SparkSession, ide_environment: IdeEnvironment # deployment_environment: DeploymentEnvironment ): """ Instantiates this object ...
from pyspark.sql import DataFrame, SparkSession from dbkcore.core import trace, Log import re from pathlib import Path from typing import Any, List from typeguard import typechecked from dbkcore.core import Singleton from enum import Enum import pkg_resources class IdeEnvironment(str, Enum): LOCAL = "local" ...
97
256
1,824
13
84
microsoft/dstoolkit-ml-ops-for-databricks
src/modules/dbkdev/core.py
Python
DevelopmentClient
DevelopmentClient
20
322
20
21
e7e54ca76350843e0334dc93600dc805bf9d4260
bigcode/the-stack
train
4c06398532c22c5afba6ca84
train
function
def shape_fn_qntd(args, kwargs): r""" Overview: Return qntd shape for hpc Returns: shape: [T, B, N] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['data'].q.shape)) else: tmp = [args[0].reward.shape[0]] tmp.ext...
def shape_fn_qntd(args, kwargs):
r""" Overview: Return qntd shape for hpc Returns: shape: [T, B, N] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['data'].q.shape)) else: tmp = [args[0].reward.shape[0]] tmp.extend(list(args[0].q.shape)) re...
'q', 'next_n_q', 'action', 'next_n_action', 'reward', 'done', 'done_one_step', 'weight', 'new_n_q_one_step', 'next_n_action_one_step', 'is_expert' ] ) def shape_fn_qntd(args, kwargs):
64
64
105
10
54
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
shape_fn_qntd
shape_fn_qntd
328
341
328
328
cf11af8aa1c69db1f2f553a36702d22c4bcf3279
bigcode/the-stack
train
9dfa564c0b821258dcccf3a9
train
function
@hpc_wrapper( shape_fn=shape_fn_qntd_rescale, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma'] ) def q_nstep_td_error_with_rescale_ngu( data: namedtuple, gamma: Any, nstep: int = 1, value_gamma: Optional[torch.Tensor] = None, criterion: torch.nn.modules = nn.MSELoss(re...
@hpc_wrapper( shape_fn=shape_fn_qntd_rescale, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma'] ) def q_nstep_td_error_with_rescale_ngu( data: namedtuple, gamma: Any, nstep: int = 1, value_gamma: Optional[torch.Tensor] = None, criterion: torch.nn.modules = nn.MSELoss(re...
""" Overview: Multistep (1 step or n step) td_error with value rescaling Arguments: - data (:obj:`q_nstep_td_data`): the input data, q_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - nstep (:obj:`int`): nstep num, default set to 1 - criterion...
) target_q_s_a = nstep_return(nstep_return_data(reward, target_q_s_a, done), gamma, nstep, value_gamma) target_q_s_a = trans_fn(target_q_s_a) td_error_per_sample = criterion(q_s_a, target_q_s_a.detach()) return (td_error_per_sample * weight).mean(), td_error_per_sample @hpc_wrapper( shape_fn=shape_...
203
203
679
124
78
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
q_nstep_td_error_with_rescale_ngu
q_nstep_td_error_with_rescale_ngu
523
573
523
534
8e4bde9dd5dc5355eb32573f7d8d3d9c9cb8123c
bigcode/the-stack
train
14c29c7eae5197fe1bd2ece2
train
function
def q_nstep_sql_td_error( data: namedtuple, gamma: float, alpha: float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criterion: torch.nn.modules = nn.MSELoss(reduction='none'), ) -> torch.Tensor: """ Overview: ...
def q_nstep_sql_td_error( data: namedtuple, gamma: float, alpha: float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criterion: torch.nn.modules = nn.MSELoss(reduction='none'), ) -> torch.Tensor:
""" Overview: Multistep (1 step or n step) td_error for q-learning based algorithm Arguments: - data (:obj:`q_nstep_td_data`): the input data, q_nstep_sql_td_data to calculate loss - gamma (:obj:`float`): discount factor - Alpha (:obj:`float`): A parameter to weight entropy t...
queeze(-1) + (gamma ** nstep ) * target_q_s_a * (1 - done).unsqueeze(-1).unsqueeze(-1) else: target_q_s_a = reward.unsqueeze(-1).unsqueeze( -1 ) + value_gamma.unsqueeze(-1).unsqueeze(-1) * target_q_s_a * (1 - done).unsqueeze(-1...
252
252
841
74
177
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
q_nstep_sql_td_error
q_nstep_sql_td_error
849
909
849
857
e45f92a6a1b0baa6b374770a0eddd9e44bcf8cf4
bigcode/the-stack
train
65857b0bc3c1e0101c24b705
train
function
def dqfd_nstep_td_error( data: namedtuple, gamma: float, lambda_n_step_td: float, lambda_supervised_loss: float, margin_function: float, lambda_one_step_td: float = 1., nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] =...
def dqfd_nstep_td_error( data: namedtuple, gamma: float, lambda_n_step_td: float, lambda_supervised_loss: float, margin_function: float, lambda_one_step_td: float = 1., nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] =...
""" Overview: Multistep n step td_error + 1 step td_error + supervised margin loss or dqfd Arguments: - data (:obj:`dqfd_nstep_td_data`): the input data, dqfd_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - cum_reward (:obj:`bool`): whether to use cu...
1, action.shape if weight is None: weight = torch.ones_like(action) batch_range = torch.arange(action.shape[0]) q_s_a = q[batch_range, action] target_q_s_a = next_n_q[batch_range, next_n_action] target_q_s_a = inv_trans_fn(target_q_s_a) target_q_s_a = nstep_return_ngu(nstep_return_dat...
256
256
1,287
102
153
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
dqfd_nstep_td_error
dqfd_nstep_td_error
576
668
576
587
7136659693b0cc18c6fb2c647f6f66a06b5afb4f
bigcode/the-stack
train
b6df779c4654b4c1ff6d0016
train
function
@hpc_wrapper( shape_fn=shape_fn_qntd_rescale, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma'] ) def q_nstep_td_error_with_rescale( data: namedtuple, gamma: float, nstep: int = 1, value_gamma: Optional[torch.Tensor] = None, criterion: torch.nn.modules = nn.MSELoss(redu...
@hpc_wrapper( shape_fn=shape_fn_qntd_rescale, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma'] ) def q_nstep_td_error_with_rescale( data: namedtuple, gamma: float, nstep: int = 1, value_gamma: Optional[torch.Tensor] = None, criterion: torch.nn.modules = nn.MSELoss(redu...
""" Overview: Multistep (1 step or n step) td_error with value rescaling Arguments: - data (:obj:`q_nstep_td_data`): the input data, q_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - nstep (:obj:`int`): nstep num, default set to 1 - criterion...
Returns: shape: [T, B, N] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['data'].q.shape)) else: tmp = [args[0].reward.shape[0]] tmp.extend(list(args[0].q.shape)) return tmp @hpc_wrapper( shape_fn=shape_fn_qntd_rescal...
202
202
675
122
79
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
q_nstep_td_error_with_rescale
q_nstep_td_error_with_rescale
470
520
470
481
6fa4932f69f7afe9a5d963e923af6e61fa3d89aa
bigcode/the-stack
train
8ae88efa88688b4f0054de31
train
function
def multistep_forward_view( bootstrap_values: torch.Tensor, rewards: torch.Tensor, gammas: float, lambda_: float ) -> torch.Tensor: r""" Overview: Same as trfl.sequence_ops.multistep_forward_view Implementing (12.18) in Sutton & Barto ``` result[T-1] = rewards[T-1] + gam...
def multistep_forward_view( bootstrap_values: torch.Tensor, rewards: torch.Tensor, gammas: float, lambda_: float ) -> torch.Tensor:
r""" Overview: Same as trfl.sequence_ops.multistep_forward_view Implementing (12.18) in Sutton & Barto ``` result[T-1] = rewards[T-1] + gammas[T-1] * bootstrap_values[T] for t in 0...T-2 : result[t] = rewards[t] + gammas[t]*(lambdas[t]*result[t+1] + (1-lambdas[t]...
_traj, batchsize] Returns: - return (:obj:`torch.Tensor`): Computed lambda return value for each state from 0 to T-1, of size [T_traj, batchsize] """ if not isinstance(gammas, torch.Tensor): gammas = gammas * torch.ones_like(rewards) if not isinstance(lambda_, torch.Tensor): ...
160
161
539
33
127
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
multistep_forward_view
multistep_forward_view
1,088
1,126
1,088
1,090
857b77ecb58de4bcdb2d3e5334c5d14a27721e36
bigcode/the-stack
train
1816ccd34236efe5096aa365
train
function
def iqn_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, kappa: float = 1.0, value_gamma: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Overview: Multistep (1 step or n step) td_error with in IQN, \ referenced paper Implicit Quan...
def iqn_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, kappa: float = 1.0, value_gamma: Optional[torch.Tensor] = None, ) -> torch.Tensor:
""" Overview: Multistep (1 step or n step) td_error with in IQN, \ referenced paper Implicit Quantile Networks for Distributional Reinforcement Learning \ <https://arxiv.org/pdf/1806.06923.pdf> Arguments: - data (:obj:`iqn_nstep_td_data`): the input data, iqn_nstep_td...
# The hardcodes above are to prevent this situation from happening record_target_v = copy.deepcopy(target_v) # print(target_v) if cum_reward: if value_gamma is None: target_v = reward + (gamma ** nstep) * target_v * (1 - done) else: target_v = reward + value_gamma...
256
256
1,167
56
200
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
iqn_nstep_td_error
iqn_nstep_td_error
917
1,004
917
923
89b113a23cbbb8c4cdb9a97cab1a6f54d3398ba7
bigcode/the-stack
train
89fd1680be3b40cf7f66444e
train
function
def v_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor: r""" Overview: Multistep (n step) td_error for distributed value based algorithm Arguments: - data (:obj...
def v_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor:
r""" Overview: Multistep (n step) td_error for distributed value based algorithm Arguments: - data (:obj:`dist_nstep_td_data`): the input data, v_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - nstep (:obj:`int`): nstep num, default set to 1 Retu...
* next_v + reward else: target_v = gamma * next_v + reward td_error_per_sample = criterion(v, target_v.detach()) return (td_error_per_sample * weight).mean(), td_error_per_sample v_nstep_td_data = namedtuple('v_nstep_td_data', ['v', 'next_n_v', 'reward', 'done', 'weight', 'value_gamma']) def v_ns...
138
139
465
52
86
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
v_nstep_td_error
v_nstep_td_error
282
313
282
287
dc5e19cb4eb5a28bee5140f58c11a92daa16643e
bigcode/the-stack
train
cc70aa49ca14acc2b3a7d442
train
function
def nstep_return(data: namedtuple, gamma: float, nstep: int, value_gamma: Optional[torch.Tensor] = None): reward, next_value, done = data assert reward.shape[0] == nstep device = reward.device reward_factor = torch.ones(nstep).to(device) for i in range(1, nstep): reward_factor[i] = gamma * r...
def nstep_return(data: namedtuple, gamma: float, nstep: int, value_gamma: Optional[torch.Tensor] = None):
reward, next_value, done = data assert reward.shape[0] == nstep device = reward.device reward_factor = torch.ones(nstep).to(device) for i in range(1, nstep): reward_factor[i] = gamma * reward_factor[i - 1] reward_factor = view_similar(reward_factor, reward) reward = reward.mul(reward...
len(x.shape))] return x.view(*size) nstep_return_data = namedtuple('nstep_return_data', ['reward', 'next_value', 'done']) def nstep_return(data: namedtuple, gamma: float, nstep: int, value_gamma: Optional[torch.Tensor] = None):
63
64
172
29
34
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
nstep_return
nstep_return
72
85
72
72
c02c3f01b4a920529c4bfecc39fbc034180f3b26
bigcode/the-stack
train
f0c2c55f464c142a0c6b4175
train
function
@hpc_wrapper( shape_fn=shape_fn_td_lambda, namedtuple_data=True, include_args=[0, 1, 2], include_kwargs=['data', 'gamma', 'lambda_'] ) def td_lambda_error(data: namedtuple, gamma: float = 0.9, lambda_: float = 0.8) -> torch.Tensor: """ Overview: Computing TD(lambda) loss given constant g...
@hpc_wrapper( shape_fn=shape_fn_td_lambda, namedtuple_data=True, include_args=[0, 1, 2], include_kwargs=['data', 'gamma', 'lambda_'] ) def td_lambda_error(data: namedtuple, gamma: float = 0.9, lambda_: float = 0.8) -> torch.Tensor:
""" Overview: Computing TD(lambda) loss given constant gamma and lambda. There is no special handling for terminal state value, if some state has reached the terminal, just fill in zeros for values and rewards beyond terminal (*including the terminal state*, values[terminal] shou...
r""" Overview: Return td_lambda shape for hpc Returns: shape: [T, B] """ if len(args) <= 0: tmp = kwargs['data'].reward.shape[0] else: tmp = args[0].reward.shape return tmp @hpc_wrapper( shape_fn=shape_fn_td_lambda, namedtuple_data=True, include_ar...
143
143
479
77
65
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
td_lambda_error
td_lambda_error
1,024
1,057
1,024
1,030
95b44122b2d2aa2f651ba8faea97f109f24f433e
bigcode/the-stack
train
1d60478e53f9eb3edd96d4b6
train
function
@hpc_wrapper(shape_fn=shape_fn_qntd, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma']) def q_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criterion: torch.n...
@hpc_wrapper(shape_fn=shape_fn_qntd, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma']) def q_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criterion: torch.n...
""" Overview: Multistep (1 step or n step) td_error for q-learning based algorithm Arguments: - data (:obj:`q_nstep_td_data`): the input data, q_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - cum_reward (:obj:`bool`): whether to use cumulative nstep...
', 'new_n_q_one_step', 'next_n_action_one_step', 'is_expert' ] ) def shape_fn_qntd(args, kwargs): r""" Overview: Return qntd shape for hpc Returns: shape: [T, B, N] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['dat...
231
231
772
102
128
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
q_nstep_td_error
q_nstep_td_error
344
398
344
352
4bfdd712e102180431f52626c42bc17aca9adcc8
bigcode/the-stack
train
da96e4f4c0b878ff11cf3d95
train
function
def view_similar(x: torch.Tensor, target: torch.Tensor) -> torch.Tensor: size = list(x.shape) + [1 for _ in range(len(target.shape) - len(x.shape))] return x.view(*size)
def view_similar(x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
size = list(x.shape) + [1 for _ in range(len(target.shape) - len(x.shape))] return x.view(*size)
queeze(1) * v + reward.unsqueeze(1) td_error_per_sample = criterion(q_s_a, target_q_s_a.detach()) return (td_error_per_sample * weight).mean(), td_error_per_sample def view_similar(x: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
64
64
48
18
45
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
view_similar
view_similar
64
66
64
64
552d272bd5cf10a0c143b01d00a461c34fe67d63
bigcode/the-stack
train
f5a0ecb98b6b3da6a54368a9
train
function
def shape_fn_td_lambda(args, kwargs): r""" Overview: Return td_lambda shape for hpc Returns: shape: [T, B] """ if len(args) <= 0: tmp = kwargs['data'].reward.shape[0] else: tmp = args[0].reward.shape return tmp
def shape_fn_td_lambda(args, kwargs):
r""" Overview: Return td_lambda shape for hpc Returns: shape: [T, B] """ if len(args) <= 0: tmp = kwargs['data'].reward.shape[0] else: tmp = args[0].reward.shape return tmp
loss = quantile_huber_loss.sum(dim=2).mean(dim=1)[:, 0] return (loss * weight).mean(), loss td_lambda_data = namedtuple('td_lambda_data', ['value', 'reward', 'weight']) def shape_fn_td_lambda(args, kwargs):
63
64
75
9
54
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
shape_fn_td_lambda
shape_fn_td_lambda
1,010
1,021
1,010
1,010
15234a5cae673eadb4bdc94e61e86bd9ee66a09b
bigcode/the-stack
train
c96541d56bbe4a87082e713f
train
function
def v_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor: v, next_v, reward, done, weight = data if weight is None: weight = torch.ones_like(reward) if done is not None: target_v = gamma...
def v_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor:
v, next_v, reward, done, weight = data if weight is None: weight = torch.ones_like(reward) if done is not None: target_v = gamma * (1 - done) * next_v + reward else: target_v = gamma * next_v + reward td_error_per_sample = criterion(v, target_v.detach()) return (td_error_...
_td_data', ['v', 'next_v', 'reward', 'done', 'weight']) def v_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor:
63
64
141
44
19
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
v_1step_td_error
v_1step_td_error
263
276
263
267
567848c4daa6c6461b306449ea896c3c57f2497b
bigcode/the-stack
train
4fb8f34b1406bfe0b0c8d296
train
function
def dqfd_nstep_td_error_with_rescale( data: namedtuple, gamma: float, lambda_n_step_td: float, lambda_supervised_loss: float, lambda_one_step_td: float, margin_function: float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criterion: torch....
def dqfd_nstep_td_error_with_rescale( data: namedtuple, gamma: float, lambda_n_step_td: float, lambda_supervised_loss: float, lambda_one_step_td: float, margin_function: float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criterion: torch....
""" Overview: Multistep n step td_error + 1 step td_error + supervised margin loss or dqfd Arguments: - data (:obj:`dqfd_nstep_td_data`): the input data, dqfd_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - cum_reward (:obj:`bool`): whether to use cu...
device=device_cpu)) # along the first dimension. for the index of the action, fill the corresponding position in l with 0 JE = is_expert * (torch.max(q + l.to(device), dim=1)[0] - q_s_a) return ( ( ( lambda_n_step_td * td_error_per_sample + lambda_one_step_td * td_error...
256
256
1,437
122
134
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
dqfd_nstep_td_error_with_rescale
dqfd_nstep_td_error_with_rescale
671
774
671
684
1a3c42e37a4af3614b3010396f081209fdf576a5
bigcode/the-stack
train
50f033e18296a3212f8d3665
train
function
def shape_fn_qntd_rescale(args, kwargs): r""" Overview: Return qntd_rescale shape for hpc Returns: shape: [T, B, N] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['data'].q.shape)) else: tmp = [args[0].reward.shape[0]]...
def shape_fn_qntd_rescale(args, kwargs):
r""" Overview: Return qntd_rescale shape for hpc Returns: shape: [T, B, N] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['data'].q.shape)) else: tmp = [args[0].reward.shape[0]] tmp.extend(list(args[0].q.shape)...
(reward, target_q_s_a, done), gamma, nstep, value_gamma) td_error_per_sample = criterion(q_s_a, target_q_s_a.detach()) return (td_error_per_sample * weight).mean(), td_error_per_sample def shape_fn_qntd_rescale(args, kwargs):
64
64
109
12
51
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
shape_fn_qntd_rescale
shape_fn_qntd_rescale
454
467
454
454
508dde3d5678dc8d15d7e55676c3f0fdd1710a00
bigcode/the-stack
train
e432d9a84f0f0d8c49ad2cd4
train
function
def nstep_return_ngu(data: namedtuple, gamma: Any, nstep: int, value_gamma: Optional[torch.Tensor] = None): reward, next_value, done = data assert reward.shape[0] == nstep device = reward.device return_list = [] for j in range(done.shape[0]): # reward.shape[1]): # batch_size reward_factor ...
def nstep_return_ngu(data: namedtuple, gamma: Any, nstep: int, value_gamma: Optional[torch.Tensor] = None):
reward, next_value, done = data assert reward.shape[0] == nstep device = reward.device return_list = [] for j in range(done.shape[0]): # reward.shape[1]): # batch_size reward_factor = torch.ones(nstep).to(device) for i in range(1, nstep): reward_factor[i] = gamma[j] * r...
next_value * (1 - done) else: return_ = reward + value_gamma * next_value * (1 - done) return return_ def nstep_return_ngu(data: namedtuple, gamma: Any, nstep: int, value_gamma: Optional[torch.Tensor] = None):
63
64
204
31
32
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
nstep_return_ngu
nstep_return_ngu
88
103
88
88
2b3d65597da2ac0fec94dccc82d3f805cbc2838c
bigcode/the-stack
train
23dd1a9b35de4ed4618e77f9
train
function
@hpc_wrapper(shape_fn=shape_fn_qntd, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma']) def q_nstep_td_error_ngu( data: namedtuple, gamma: Any, # float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criter...
@hpc_wrapper(shape_fn=shape_fn_qntd, namedtuple_data=True, include_args=[0, 1], include_kwargs=['data', 'gamma']) def q_nstep_td_error_ngu( data: namedtuple, gamma: Any, # float, nstep: int = 1, cum_reward: bool = False, value_gamma: Optional[torch.Tensor] = None, criter...
""" Overview: Multistep (1 step or n step) td_error for q-learning based algorithm Arguments: - data (:obj:`q_nstep_td_data`): the input data, q_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - cum_reward (:obj:`bool`): whether to use cumulative nstep...
+ (gamma ** nstep) * target_q_s_a * (1 - done) else: target_q_s_a = reward + value_gamma * target_q_s_a * (1 - done) else: target_q_s_a = nstep_return(nstep_return_data(reward, target_q_s_a, done), gamma, nstep, value_gamma) td_error_per_sample = criterion(q_s_a, target_q_s_a.detach...
218
218
727
108
109
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
q_nstep_td_error_ngu
q_nstep_td_error_ngu
401
451
401
409
f15cb16811afcbd98720247c313562ed9348ee4b
bigcode/the-stack
train
439de67d94610744fa27e039
train
function
def q_v_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') ) -> torch.Tensor: # we will use this function in discrete sac algorithm to calculate td error between q and v value. q, v, act, reward, done, weight = data if len(act.shape) == 1: ...
def q_v_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') ) -> torch.Tensor: # we will use this function in discrete sac algorithm to calculate td error between q and v value.
q, v, act, reward, done, weight = data if len(act.shape) == 1: assert len(reward.shape) == 1, reward.shape batch_range = torch.arange(act.shape[0]) if weight is None: weight = torch.ones_like(reward) q_s_a = q[batch_range, act] target_q_s_a = gamma * (1 - done...
_s_a.detach()) * weight).mean() q_v_1step_td_data = namedtuple('q_v_1step_td_data', ['q', 'v', 'act', 'reward', 'done', 'weight']) def q_v_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') ) -> torch.Tensor: # we will use this function in discrete s...
106
107
357
60
46
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
q_v_1step_td_error
q_v_1step_td_error
36
61
36
39
1159bae6ad29e9d5a1bdfe078b7aec31412e9c8b
bigcode/the-stack
train
52d3d7a06a77d9d5cf30d660
train
function
def shape_fn_dntd(args, kwargs): r""" Overview: Return dntd shape for hpc Returns: shape: [T, B, N, n_atom] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['data'].dist.shape)) else: tmp = [args[0].reward.shape[0]] ...
def shape_fn_dntd(args, kwargs):
r""" Overview: Return dntd shape for hpc Returns: shape: [T, B, N, n_atom] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp.extend(list(kwargs['data'].dist.shape)) else: tmp = [args[0].reward.shape[0]] tmp.extend(list(args[0].dist....
sum(-1).mean() return loss dist_nstep_td_data = namedtuple( 'dist_1step_td_data', ['dist', 'next_n_dist', 'act', 'next_n_act', 'reward', 'done', 'weight'] ) def shape_fn_dntd(args, kwargs):
64
64
108
10
54
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
shape_fn_dntd
shape_fn_dntd
160
173
160
160
ce7e6f7f532102a8579778f60649149ab07af999
bigcode/the-stack
train
fe2ddc86d7943d72428c5ddb
train
function
def generalized_lambda_returns( bootstrap_values: torch.Tensor, rewards: torch.Tensor, gammas: float, lambda_: float ) -> torch.Tensor: r""" Overview: Functional equivalent to trfl.value_ops.generalized_lambda_returns https://github.com/deepmind/trfl/blob/2c07ac22512a16715cc759f0072be43a...
def generalized_lambda_returns( bootstrap_values: torch.Tensor, rewards: torch.Tensor, gammas: float, lambda_: float ) -> torch.Tensor:
r""" Overview: Functional equivalent to trfl.value_ops.generalized_lambda_returns https://github.com/deepmind/trfl/blob/2c07ac22512a16715cc759f0072be43a5d12ae45/trfl/value_ops.py#L74 Passing in a number instead of tensor to make the value constant for all samples in batch Arguments: ...
= data if weight is None: weight = torch.ones_like(reward) with torch.no_grad(): return_ = generalized_lambda_returns(value, reward, gamma, lambda_) # discard the value at T as it should be considered in the next slice loss = 0.5 * (F.mse_loss(return_, value[:-1], reduction='none') * we...
119
119
397
31
87
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
generalized_lambda_returns
generalized_lambda_returns
1,060
1,085
1,060
1,062
e634f637ee5a6d681f2b4ff77b63b4d9c0f833e0
bigcode/the-stack
train
d25acf3972f1e7dae04e4e4f
train
function
def qrdqn_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, value_gamma: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Overview: Multistep (1 step or n step) td_error with in QRDQN Arguments: - data (:obj:`iqn_nstep_td_data`): the input d...
def qrdqn_nstep_td_error( data: namedtuple, gamma: float, nstep: int = 1, value_gamma: Optional[torch.Tensor] = None, ) -> torch.Tensor:
""" Overview: Multistep (1 step or n step) td_error with in QRDQN Arguments: - data (:obj:`iqn_nstep_td_data`): the input data, iqn_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - nstep (:obj:`int`): nstep num, default set to 1 Returns: -...
device=device_cpu)) # along the first dimension. for the index of the action, fill the corresponding position in l with 0 JE = is_expert * (torch.max(q + l.to(device), dim=1)[0] - q_s_a) return ( ( ( lambda_n_step_td * td_error_per_sample + lambda_one_step_td * td_error...
248
248
827
46
202
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
qrdqn_nstep_td_error
qrdqn_nstep_td_error
782
846
782
787
c056ec2bdfadcd64afc96b9a5570694cf5a4090d
bigcode/the-stack
train
d09e0e9983238d98c7f73a54
train
function
@hpc_wrapper( shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0, 1, 2, 3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'] ) def dist_nstep_td_error( data: namedtuple, gamma: float, v_min: float, v_max: float, n_atom: int, nstep: int = 1, ...
@hpc_wrapper( shape_fn=shape_fn_dntd, namedtuple_data=True, include_args=[0, 1, 2, 3], include_kwargs=['data', 'gamma', 'v_min', 'v_max'] ) def dist_nstep_td_error( data: namedtuple, gamma: float, v_min: float, v_max: float, n_atom: int, nstep: int = 1, ...
r""" Overview: Multistep (1 step or n step) td_error for distributed q-learning based algorithm Arguments: - data (:obj:`dist_nstep_td_data`): the input data, dist_nstep_td_data to calculate loss - gamma (:obj:`float`): discount factor - nstep (:obj:`int`): nstep num, default...
_1step_td_data', ['dist', 'next_n_dist', 'act', 'next_n_act', 'reward', 'done', 'weight'] ) def shape_fn_dntd(args, kwargs): r""" Overview: Return dntd shape for hpc Returns: shape: [T, B, N, n_atom] """ if len(args) <= 0: tmp = [kwargs['data'].reward.shape[0]] tmp....
256
256
1,011
116
139
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
dist_nstep_td_error
dist_nstep_td_error
176
257
176
190
8d4a38e891a844b4af117dbdddb46e775865cf17
bigcode/the-stack
train
af4ddf79ae7545ef8a7d3e6b
train
function
def q_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor: q, next_q, act, next_act, reward, done, weight = data assert len(act.shape) == 1, act.shape assert len(reward.shape) == 1, reward.shape batc...
def q_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor:
q, next_q, act, next_act, reward, done, weight = data assert len(act.shape) == 1, act.shape assert len(reward.shape) == 1, reward.shape batch_range = torch.arange(act.shape[0]) if weight is None: weight = torch.ones_like(reward) q_s_a = q[batch_range, act] target_q_s_a = next_q[batch...
next_q', 'act', 'next_act', 'reward', 'done', 'weight']) def q_1step_td_error( data: namedtuple, gamma: float, criterion: torch.nn.modules = nn.MSELoss(reduction='none') # noqa ) -> torch.Tensor:
63
64
183
44
19
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
q_1step_td_error
q_1step_td_error
16
30
16
20
c5252462f5f943f272021a17955ccc5f2810797a
bigcode/the-stack
train
56a971bb3007f3f35076ad6e
train
function
def dist_1step_td_error( data: namedtuple, gamma: float, v_min: float, v_max: float, n_atom: int, ) -> torch.Tensor: dist, next_dist, act, next_act, reward, done, weight = data device = reward.device assert len(act.shape) == 1, act.shape assert len(reward.shape) =...
def dist_1step_td_error( data: namedtuple, gamma: float, v_min: float, v_max: float, n_atom: int, ) -> torch.Tensor:
dist, next_dist, act, next_act, reward, done, weight = data device = reward.device assert len(act.shape) == 1, act.shape assert len(reward.shape) == 1, reward.shape reward = reward.unsqueeze(-1) done = done.unsqueeze(-1) support = torch.linspace(v_min, v_max, n_atom).to(device) delta_z =...
] ** nstep) * next_value[j] * (1 - done[j]) return_list.append(return_.unsqueeze(0)) # return_list = to_tensor(return_list) return_ = torch.cat(return_list, dim=0) return return_ dist_1step_td_data = namedtuple( 'dist_1step_td_data', ['dist', 'next_dist', 'act', 'next_act', 'reward', 'done', ...
141
141
470
42
99
mingzhang96/DI-engine
ding/rl_utils/td.py
Python
dist_1step_td_error
dist_1step_td_error
111
152
111
117
e4000289f205c3e80084505fa513ac7b25fd9d53
bigcode/the-stack
train
781931299e772770c8cc8d0b
train
class
class ElementsEmitterNode(base.BaseNode): bl_idname = 'elements_emitter_node' bl_label = 'Emitter' required_nodes = { 'Source Object': [ 'elements_source_object_node', ], 'Material': [ 'elements_material_node', ] } typ: bpy.props.StringPropert...
class ElementsEmitterNode(base.BaseNode):
bl_idname = 'elements_emitter_node' bl_label = 'Emitter' required_nodes = { 'Source Object': [ 'elements_source_object_node', ], 'Material': [ 'elements_material_node', ] } typ: bpy.props.StringProperty(default='EMITTER') category = base.E...
import bpy from .. import base class ElementsEmitterNode(base.BaseNode):
16
69
230
8
7
LewisOrton/taichi_elements_houdini
blender/nodes/element/emitter.py
Python
ElementsEmitterNode
ElementsEmitterNode
6
40
6
6
81f47ab16d267a1bc679c003475f8cc6ae63bbec
bigcode/the-stack
train
e36696c70e2d44c60f124edd
train
function
def multi_gpu_test(model, data_loader, tmpdir=None): model.eval() results = [] dataset = data_loader.dataset rank, world_size = get_dist_info() if rank == 0: prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result ...
def multi_gpu_test(model, data_loader, tmpdir=None):
model.eval() results = [] dataset = data_loader.dataset rank, world_size = get_dist_info() if rank == 0: prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) ...
data) results.append(result) if show: model.module.show_result(data, result) batch_size = data['img'][0].size(0) for _ in range(batch_size): prog_bar.update() return results def multi_gpu_test(model, data_loader, tmpdir=None):
64
64
154
13
50
michael-camilleri/AQA
tao_detection_release/.history/tools/multi_process_inference/inference_20200802135024.py
Python
multi_gpu_test
multi_gpu_test
47
67
47
47
7a8d248896ffdc004edb798a7f2e8873410ad021
bigcode/the-stack
train
eb0de73ccc82608d7a6f4914
train
function
def single_gpu_test(model, data_loader, show=False, cfg=None): model.eval() results = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=not show, **data...
def single_gpu_test(model, data_loader, show=False, cfg=None):
model.eval() results = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) for i, data in enumerate(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=not show, **data) results.append(result) if show: ...
_model from mmdet.datasets import build_dataloader, build_dataset, FilesDataset from mmdet.models import build_detector from mmdet.core import build_assigner import pickle import common from inference_utils import * def single_gpu_test(model, data_loader, show=False, cfg=None):
63
64
123
15
48
michael-camilleri/AQA
tao_detection_release/.history/tools/multi_process_inference/inference_20200802135024.py
Python
single_gpu_test
single_gpu_test
29
45
29
29
3fa461bd71903145e471509f2bb00a022729903a
bigcode/the-stack
train
e488160596e731d8190e3868
train
function
def save_in_tao_format(mmdet_res, results_path): ''' Args: mmdet_res (list[array]): 一张图的结果 ''' boxes_decoded = [] scores_decoded = [] classes_decoded = [] for i, dets in enumerate(mmdet_res): for det in dets: boxes_decoded.append([det[0], det[1], det[2], det[3]]...
def save_in_tao_format(mmdet_res, results_path):
''' Args: mmdet_res (list[array]): 一张图的结果 ''' boxes_decoded = [] scores_decoded = [] classes_decoded = [] for i, dets in enumerate(mmdet_res): for det in dets: boxes_decoded.append([det[0], det[1], det[2], det[3]]) scores_decoded.append(det[4]) ...
# ([1231, 1024]) weight = pnorm(weight, tau) model_dict[k].copy_(weight) print('Reweight param {:<30} with tau={}'.format(k, tau)) return model def save_in_tao_format(mmdet_res, results_path):
64
64
180
14
49
michael-camilleri/AQA
tao_detection_release/.history/tools/multi_process_inference/inference_20200802135024.py
Python
save_in_tao_format
save_in_tao_format
162
185
162
162
b80b201d82e07e0712d257758e57d3f8b5ed94f1
bigcode/the-stack
train
ecdc735bb01f45ebde538ade
train
function
def parse_args(): parser = argparse.ArgumentParser(description='MMDet test detector') parser.add_argument('--config', type=str, default='/home/songbai.xb/workspace/research/detection/BalancedGroupSoftmax/configs/tao/gs_htc_dconv_c3-c5_mstrain_400_1400_x101_64x4d_fpn_20e_lvis.py', help='test config file path') ...
def parse_args():
parser = argparse.ArgumentParser(description='MMDet test detector') parser.add_argument('--config', type=str, default='/home/songbai.xb/workspace/research/detection/BalancedGroupSoftmax/configs/tao/gs_htc_dconv_c3-c5_mstrain_400_1400_x101_64x4d_fpn_20e_lvis.py', help='test config file path') parser.add_argu...
results of all parts from tmp dir part_list = [] for i in range(world_size): part_file = osp.join(tmpdir, 'part_{}.pkl'.format(i)) part_list.append(mmcv.load(part_file)) # sort the results ordered_results = [] for res in zip(*part_list): order...
119
119
399
4
114
michael-camilleri/AQA
tao_detection_release/.history/tools/multi_process_inference/inference_20200802135024.py
Python
parse_args
parse_args
112
132
112
112
9d0fb47d7edce223598e7ffe2c37e934e1291ab3
bigcode/the-stack
train
7b5d2e2c2cce0d02b2cb1f0d
train
function
def reweight_cls(model, tauuu): if tauuu == 0: return model model_dict = model.state_dict() def pnorm(weights, tau): normB = torch.norm(weights, 2, 1) ws = weights.clone() for i in range(0, weights.shape[0]): ws[i] = ws[i] / torch.pow(normB[i], tau) r...
def reweight_cls(model, tauuu):
if tauuu == 0: return model model_dict = model.state_dict() def pnorm(weights, tau): normB = torch.norm(weights, 2, 1) ws = weights.clone() for i in range(0, weights.shape[0]): ws[i] = ws[i] / torch.pow(normB[i], tau) return ws reweight_set = ['bb...
0) parser.add_argument('--tau', type=float, default=0.0) args = parser.parse_args() if 'LOCAL_RANK' not in os.environ: os.environ['LOCAL_RANK'] = str(args.local_rank) return args def reweight_cls(model, tauuu):
64
64
175
9
54
michael-camilleri/AQA
tao_detection_release/.history/tools/multi_process_inference/inference_20200802135024.py
Python
reweight_cls
reweight_cls
134
158
134
135
9cdefad02683c5b1a4c1218e5ff1c93e8799883d
bigcode/the-stack
train
a0083a8ab2be3dcabc7afe20
train
function
def main(): args = parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = args.gpuid img_dir = args.img_dir out_dir = args.out_dir batch_size = args.batch_size cfg = mmcv.Config.fromfile(args.config) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.be...
def main():
args = parse_args() os.environ['CUDA_VISIBLE_DEVICES'] = args.gpuid img_dir = args.img_dir out_dir = args.out_dir batch_size = args.batch_size cfg = mmcv.Config.fromfile(args.config) # set cudnn_benchmark if cfg.get('cudnn_benchmark', False): torch.backends.cudnn.benchmark = Tr...
return model def save_in_tao_format(mmdet_res, results_path): ''' Args: mmdet_res (list[array]): 一张图的结果 ''' boxes_decoded = [] scores_decoded = [] classes_decoded = [] for i, dets in enumerate(mmdet_res): for det in dets: boxes_decoded.append([det[0], det...
187
187
626
3
184
michael-camilleri/AQA
tao_detection_release/.history/tools/multi_process_inference/inference_20200802135024.py
Python
main
main
187
255
187
187
4a840e4189ef7c0e99d5f8228d85ffd54e2a0780
bigcode/the-stack
train
30c7c64344f8216c89a11872
train
function
def collect_results(result_part, size, tmpdir=None): rank, world_size = get_dist_info() # create a tmp dir if it is not specified if tmpdir is None: MAX_LEN = 512 # 32 is whitespace dir_tensor = torch.full((MAX_LEN, ), 32, ...
def collect_results(result_part, size, tmpdir=None):
rank, world_size = get_dist_info() # create a tmp dir if it is not specified if tmpdir is None: MAX_LEN = 512 # 32 is whitespace dir_tensor = torch.full((MAX_LEN, ), 32, dtype=torch.uint8, ...
(data_loader): with torch.no_grad(): result = model(return_loss=False, rescale=True, **data) results.append(result) if rank == 0: batch_size = data['img'][0].size(0) for _ in range(batch_size * world_size): prog_bar.update() # collect res...
103
103
346
12
90
michael-camilleri/AQA
tao_detection_release/.history/tools/multi_process_inference/inference_20200802135024.py
Python
collect_results
collect_results
70
109
70
70
22c8ef59dc3ccf18564fa3e4e0e5bc66f23e3a69
bigcode/the-stack
train
4738829ad6598dbc51dc6a74
train
class
class FeefilterConn(P2PInterface): feefilter_received = False def on_feefilter(self, message): self.feefilter_received = True def assert_feefilter_received(self, recv: bool): with p2p_lock: assert_equal(self.feefilter_received, recv)
class FeefilterConn(P2PInterface):
feefilter_received = False def on_feefilter(self, message): self.feefilter_received = True def assert_feefilter_received(self, recv: bool): with p2p_lock: assert_equal(self.feefilter_received, recv)
, MSG_WTX, msg_feefilter from test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import AFCOTestFramework from test_framework.util import assert_equal from test_framework.wallet import MiniWallet class FeefilterConn(P2PInterface):
64
64
68
10
53
afco2021/afco_sourcecode
test/functional/p2p_feefilter.py
Python
FeefilterConn
FeefilterConn
16
24
16
16
602b520935379e60cff6ed980991e71035b83041
bigcode/the-stack
train
35ef1fed50d539576dea47e0
train
class
class FeeFilterTest(AFCOTestFramework): def set_test_params(self): self.num_nodes = 2 # We lower the various required feerates for this test # to catch a corner-case where feefilter used to slightly undercut # mempool and wallet feerate calculation based on GetFee # rounding ...
class FeeFilterTest(AFCOTestFramework):
def set_test_params(self): self.num_nodes = 2 # We lower the various required feerates for this test # to catch a corner-case where feefilter used to slightly undercut # mempool and wallet feerate calculation based on GetFee # rounding down 3 places, leading to stranded trans...
test_framework.p2p import P2PInterface, p2p_lock from test_framework.test_framework import AFCOTestFramework from test_framework.util import assert_equal from test_framework.wallet import MiniWallet class FeefilterConn(P2PInterface): feefilter_received = False def on_feefilter(self, message): self.f...
255
256
974
9
246
afco2021/afco_sourcecode
test/functional/p2p_feefilter.py
Python
FeeFilterTest
FeeFilterTest
46
120
46
46
ecd36fb6dee1f3eef0c189d908aa9baf473fd389
bigcode/the-stack
train
4ff5be26a30d9b8f44a40331
train
class
class TestP2PConn(P2PInterface): def __init__(self): super().__init__() self.txinvs = [] def on_inv(self, message): for i in message.inv: if (i.type == MSG_TX) or (i.type == MSG_WTX): self.txinvs.append('{:064x}'.format(i.hash)) def wait_for_invs_to_matc...
class TestP2PConn(P2PInterface):
def __init__(self): super().__init__() self.txinvs = [] def on_inv(self, message): for i in message.inv: if (i.type == MSG_TX) or (i.type == MSG_WTX): self.txinvs.append('{:064x}'.format(i.hash)) def wait_for_invs_to_match(self, invs_expected): i...
= False def on_feefilter(self, message): self.feefilter_received = True def assert_feefilter_received(self, recv: bool): with p2p_lock: assert_equal(self.feefilter_received, recv) class TestP2PConn(P2PInterface):
64
64
135
11
53
afco2021/afco_sourcecode
test/functional/p2p_feefilter.py
Python
TestP2PConn
TestP2PConn
27
43
27
27
5e0220823f4a071bbf1a1453e620004c2efa5bfb
bigcode/the-stack
train
5ba0f0b68f2f9d9ee0c959fb
train
class
class PopChoice(CFModel): """model class for popular choice predictions.""" def __init__(self, n_items, train): self.item_to_deg = popchoice.degree_of_item(train) self.sorted_by_deg = popchoice.sorted_by_degrees(self.item_to_deg) self.n_items = n_items def get_queries(self, input_tensor): pass ...
class PopChoice(CFModel):
"""model class for popular choice predictions.""" def __init__(self, n_items, train): self.item_to_deg = popchoice.degree_of_item(train) self.sorted_by_deg = popchoice.sorted_by_degrees(self.item_to_deg) self.n_items = n_items def get_queries(self, input_tensor): pass def get_rhs(self, input_...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v2 as tf from hyperbolic.models.base import CFModel import hyperbolic.utils.popchoice as popchoice class PopChoice(CFModel):
64
64
206
7
56
egonrian/google-research
hyperbolic/models/popchoice.py
Python
PopChoice
PopChoice
29
57
29
29
8eb46e6005e168d11ad1ed5fd3dbc990a5d304cd
bigcode/the-stack
train
a66c8d8280aa29860d37743a
train
function
def create_examples(xseq_list, cseq_list, set_type): """Creates examples for the training and dev sets.""" examples = [] for i, (xseq, cseq) in enumerate(zip(xseq_list, cseq_list)): guid = "%s-%s" % (set_type, i) examples.append(InputExample(guid=guid, text=xseq, label=cseq)) return exa...
def create_examples(xseq_list, cseq_list, set_type):
"""Creates examples for the training and dev sets.""" examples = [] for i, (xseq, cseq) in enumerate(zip(xseq_list, cseq_list)): guid = "%s-%s" % (set_type, i) examples.append(InputExample(guid=guid, text=xseq, label=cseq)) return examples
(save_file_name, 'w') as fout: for key in sorted(key2val): fout.write('{} ||| {}\n'.format(key, key2val[key])) # self-defined helper functions for preprocessing # matcher=xbert def create_examples(xseq_list, cseq_list, set_type):
64
64
88
14
49
bimhud/X-BERT
xbert/preprocess.py
Python
create_examples
create_examples
97
104
97
97
6c5cdf697136bb4343b93f9f8d3246215f0a60b6
bigcode/the-stack
train
b011770085e99334ec65e1c0
train
function
def build_vocab_map(sentences, max_vocab_size=50000): ''' Trim vocab by number of occurence ''' word_counts = Counter(itertools.chain(*sentences)) #wid2word = [Constants.PAD_WORD, Constants.UNK_WORD] wid2word = [Constants.UNK_WORD, Constants.PAD_WORD] wid2word = wid2word + [x[0] for x in word_count...
def build_vocab_map(sentences, max_vocab_size=50000):
''' Trim vocab by number of occurence ''' word_counts = Counter(itertools.chain(*sentences)) #wid2word = [Constants.PAD_WORD, Constants.UNK_WORD] wid2word = [Constants.UNK_WORD, Constants.PAD_WORD] wid2word = wid2word + [x[0] for x in word_counts.most_common(max_vocab_size+1) if x[0] != Constants.P...
cseq = [csr_codes[y] for y in yseq] cseq_list.append(cseq) return xseq_list, cseq_list, yseq_list # self-defined helper functions for preprocessing # matcher=xttention def build_vocab_map(sentences, max_vocab_size=50000):
64
64
195
14
49
bimhud/X-BERT
xbert/preprocess.py
Python
build_vocab_map
build_vocab_map
61
73
61
61
143a9812e1968f11625a15874c547646017890dc
bigcode/the-stack
train
c882d23f6689a3e95cbb5978
train
function
def load_mlc2seq_data(data_path, csr_codes, matcher='xbert'): xseq_list, cseq_list, yseq_list = [], [], [] with open(data_path, 'r') as fin: for idx, line in enumerate(tqdm(fin)): label_str, text_str = line.strip().split('\t') assert(len(text_str) > 0) assert(len(labe...
def load_mlc2seq_data(data_path, csr_codes, matcher='xbert'):
xseq_list, cseq_list, yseq_list = [], [], [] with open(data_path, 'r') as fin: for idx, line in enumerate(tqdm(fin)): label_str, text_str = line.strip().split('\t') assert(len(text_str) > 0) assert(len(label_str) > 0) # xseq if matcher == 'xbe...
c, yp, yn)_i}, i=1,...,N # xseq is a list of string # cseq is a list of cluster_id # yseq is a list of positive labels def load_mlc2seq_data(data_path, csr_codes, matcher='xbert'):
64
64
215
18
45
bimhud/X-BERT
xbert/preprocess.py
Python
load_mlc2seq_data
load_mlc2seq_data
33
56
33
33
99fffb2dc2131ef5e0207d2d1a42e219d244db77
bigcode/the-stack
train
057d40f2ab144e7a9d3767a1
train
function
def write_dict_map(key2val, save_file_name): with open(save_file_name, 'w') as fout: for key in sorted(key2val): fout.write('{} ||| {}\n'.format(key, key2val[key]))
def write_dict_map(key2val, save_file_name):
with open(save_file_name, 'w') as fout: for key in sorted(key2val): fout.write('{} ||| {}\n'.format(key, key2val[key]))
1 # continue ret_x_list.append(x_wid_list) print('[Info] Trimmed documents = {},'.format(len(ret_x_list)), 'Ignored documents = {}'.format(ignored_doc_count)) return ret_x_list def write_dict_map(key2val, save_file_name):
64
64
51
12
51
bimhud/X-BERT
xbert/preprocess.py
Python
write_dict_map
write_dict_map
89
92
89
89
b8e93cca70d8b7152354190c530832ad2f4f2fd7
bigcode/the-stack
train
8fef02bc9b9b23e7a46f6e50
train
function
def main(args): # set hyper-parameters input_data_dir = args.input_data_dir input_code_path = args.input_code_path output_data_dir = args.output_data_dir # load existing code C = smat.load_npz(input_code_path) csr_codes = C.nonzero()[1] # a short glimpse at clustering result for fast d...
def main(args): # set hyper-parameters
input_data_dir = args.input_data_dir input_code_path = args.input_code_path output_data_dir = args.output_data_dir # load existing code C = smat.load_npz(input_code_path) csr_codes = C.nonzero()[1] # a short glimpse at clustering result for fast debugging logger.info('NUM_LABELS: {}'.f...
_ids: %s" % " ".join([str(x) for x in output_ids])) logger.info("output_mask: %s" % " ".join([str(x) for x in output_mask])) tmp = InputFeatures(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, output_ids=output_ids, ...
256
256
1,338
11
245
bimhud/X-BERT
xbert/preprocess.py
Python
main
main
193
294
193
194
4dfab28289c35700a561829e6909d29482c7dcfe
bigcode/the-stack
train
62a31744abfca60d51a26895
train
function
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since ...
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that...
_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, output_ids=output_ids, output_mask=output_mask) features.append(tmp) return features, xseq_lens, cseq_lens def _truncate_seq_pair(tokens_a, tokens_b, max_length):
64
64
146
14
49
bimhud/X-BERT
xbert/preprocess.py
Python
_truncate_seq_pair
_truncate_seq_pair
176
190
176
176
9995435b6f0f9e8b55affc060dc9d3a9604f03f3
bigcode/the-stack
train
1766af22db0005cdc1c08064
train
function
def convert_raw_to_id(raw_x_list, word2wid): ignored_doc_count = 0 ret_x_list = [] for i, x_word_list in enumerate(raw_x_list): # filter out document whose wid are all <UNK> x_wid_list = [word2wid[w] if w in word2wid else Constants.UNK for w in x_word_list] #if all([x_wid == Constant...
def convert_raw_to_id(raw_x_list, word2wid):
ignored_doc_count = 0 ret_x_list = [] for i, x_word_list in enumerate(raw_x_list): # filter out document whose wid are all <UNK> x_wid_list = [word2wid[w] if w in word2wid else Constants.UNK for w in x_word_list] #if all([x_wid == Constants.UNK for x_wid in x_wid_list]): # ...
_counts))) print('[Info] Trimmed x_vocabulary size = {},'.format(len(word2wid))) wid2word = {v: k for k, v in word2wid.items()} return word2wid, wid2word def convert_raw_to_id(raw_x_list, word2wid):
64
64
163
13
50
bimhud/X-BERT
xbert/preprocess.py
Python
convert_raw_to_id
convert_raw_to_id
75
87
75
75
dc4081b3b5c29bcb85c7af9da412d067080e25a3
bigcode/the-stack
train
7a4048fbb2e3073476d25da9
train
function
def convert_examples_to_features(examples, tokenizer, max_xseq_len=512, max_cseq_len=128): """Loads a data file into a list of `InputBatch`s.""" features = [] xseq_lens, cseq_lens = [], [] for (ex_index, example) in enumerate(examples): tokens = tokenizer.tokenize(example.text) xseq_lens...
def convert_examples_to_features(examples, tokenizer, max_xseq_len=512, max_cseq_len=128):
"""Loads a data file into a list of `InputBatch`s.""" features = [] xseq_lens, cseq_lens = [], [] for (ex_index, example) in enumerate(examples): tokens = tokenizer.tokenize(example.text) xseq_lens.append(len(tokens)) # Account for [CLS] and [SEP] with "- 2" if len(token...
]): # ignored_doc_count += 1 # continue ret_x_list.append(x_wid_list) print('[Info] Trimmed documents = {},'.format(len(ret_x_list)), 'Ignored documents = {}'.format(ignored_doc_count)) return ret_x_list def write_dict_map(key2val, save_file_name): with open(save_fil...
238
238
796
24
213
bimhud/X-BERT
xbert/preprocess.py
Python
convert_examples_to_features
convert_examples_to_features
106
174
106
106
35e5f1d107ab739d3fe3442563adb73f690d9f5a
bigcode/the-stack
train
96fc40303a8c6bf97d55e92f
train
class
class UserClient(APIClient): """ A Client object for the User resource. """ def __init__(self): self._base_url = "" async def list_users( self, query_params={} ): """ Lists users in your organization with pagination in mos t cases. A subset of users...
class UserClient(APIClient):
""" A Client object for the User resource. """ def __init__(self): self._base_url = "" async def list_users( self, query_params={} ): """ Lists users in your organization with pagination in mos t cases. A subset of users can be returned that match ...
limitations under the License. """ # AUTO-GENERATED! DO NOT EDIT FILE DIRECTLY # SEE CONTRIBUTOR DOCUMENTATION from urllib.parse import urlencode from okta.models.user\ import User from okta.models.app_link\ import AppLink from okta.models.o_auth_2_client\ import OAuth2Client from okta.models.o_auth_2_sco...
256
256
12,560
6
249
csanders-git/okta-sdk-python
okta/resource_clients/user_client.py
Python
UserClient
UserClient
55
2,201
55
55
4aae621e0e7bff3fa19b4e624edec8fb4e09aec5
bigcode/the-stack
train
688724d30b3b48244a1c120e
train
class
class List2Attr: # https://github.com/bittorrent/webui/blob/master/constants.js _TYPES = { 'TORRENT': { 'HASH': 0, 'STATUS': 1, 'NAME': 2, 'SIZE': 3, 'PROGRESS': 4, 'DOWNLOADED': 5, 'UPLOADED': 6, 'RATIO': 7...
class List2Attr: # https://github.com/bittorrent/webui/blob/master/constants.js
_TYPES = { 'TORRENT': { 'HASH': 0, 'STATUS': 1, 'NAME': 2, 'SIZE': 3, 'PROGRESS': 4, 'DOWNLOADED': 5, 'UPLOADED': 6, 'RATIO': 7, 'UPSPEED': 8, 'DOWNSPEED': 9, 'ETA': 10, ...
break return ' '.join(['{:.3f}'.format(n).rstrip('0').rstrip('.')[:7], unit]) def limit_dict_lenght(dict:Dict, lenght:int) -> None: while len(dict) > lenght: del dict[next(iter(dict))] class KB: units = {'K': 1 << 10, 'M': 1 << 20, 'G': 1 << 30} _cache:Dict[Tuple[str, int], int] ...
256
256
1,208
21
235
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
List2Attr
List2Attr
349
521
349
351
49ecec2c9aae8d42929325a74ef1ddb54b7ae1b3
bigcode/the-stack
train
cf7adbd16b7f2acebf90e9d7
train
class
class KB: units = {'K': 1 << 10, 'M': 1 << 20, 'G': 1 << 30} _cache:Dict[Tuple[str, int], int] = {} def __getattr__(self, name) -> int: try: unit = name[0].upper() assert unit in self.units num = int(name[1:]) assert 0 < num < 1024 except: ...
class KB:
units = {'K': 1 << 10, 'M': 1 << 20, 'G': 1 << 30} _cache:Dict[Tuple[str, int], int] = {} def __getattr__(self, name) -> int: try: unit = name[0].upper() assert unit in self.units num = int(name[1:]) assert 0 < num < 1024 except: r...
: break return ' '.join(['{:.3f}'.format(n).rstrip('0').rstrip('.')[:7], unit]) def limit_dict_lenght(dict:Dict, lenght:int) -> None: while len(dict) > lenght: del dict[next(iter(dict))] class KB:
63
64
171
3
61
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
KB
KB
326
344
326
326
ccd83859b8d2747fe93ebbbe7c293eeb82339b9d
bigcode/the-stack
train
7822b5a37e5076f78f5606c2
train
class
class UTorrentPairing: _pairing:Optional[str] _session:Optional[str] def __init__(self, utweb:UTorrentWebAPI, close_pairing:bool=False) -> None: self._utweb = utweb self._close_pairing = close_pairing self._url_root = utweb._url_root.replace('/gui/', '/btapp/') self._req = ...
class UTorrentPairing:
_pairing:Optional[str] _session:Optional[str] def __init__(self, utweb:UTorrentWebAPI, close_pairing:bool=False) -> None: self._utweb = utweb self._close_pairing = close_pairing self._url_root = utweb._url_root.replace('/gui/', '/btapp/') self._req = Request(self._url_root) ...
show_operations: print(CLL, end='') msgs = [ss and self.statistics or _('Choose your operation: ' '(Q)uit, (S)top, (R)estart, (P)ause/Proceed')] if err_cr: msgs.insert(0, _('DISCONNECTED')) ...
251
251
839
6
245
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
UTorrentPairing
UTorrentPairing
1,224
1,321
1,224
1,225
07abb38e61b24962cb23da9fc0274ece9c96d0ff
bigcode/the-stack
train
51ead6d26432594e07f43a84
train
function
def main(argv=None): import inspect import argparse from . import config try: tr = translation('argparse') argparse._ = tr.gettext argparse.ngettext = tr.ngettext except (NameError, FileNotFoundError): pass kwargs = { k: v.default for k, v in ins...
def main(argv=None):
import inspect import argparse from . import config try: tr = translation('argparse') argparse._ = tr.gettext argparse.ngettext = tr.ngettext except (NameError, FileNotFoundError): pass kwargs = { k: v.default for k, v in inspect.signature(UTorre...
() else: self.log(_('set_setting(%(name)r, %(value)s) fail: %(error)s') % {'name': s, 'value': v, 'error': error}) return self.log(_('Set uTorrent setting %(name)r to %(value)s') % {'name': s, 'value': v}) @property d...
256
256
1,978
5
250
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
main
main
1,324
1,545
1,324
1,324
936453d9ff2c23370bdc0d935de1e2e53bc3790d
bigcode/the-stack
train
dd75b0037063c4060a203e66
train
class
class UTorrentWebAPI: _high_level:Set[str] _torrents_private:Dict[str, bool] _torrents_piece_size:Dict[str, int] _statistics:Dict[str, Dict[str, Tuple[int, int]]] _statistics_choked:Dict[str, Tuple[int, Optional[float]]] _statistics_started:Dict[str, float] _statistics_overflow:MutableMappi...
class UTorrentWebAPI:
_high_level:Set[str] _torrents_private:Dict[str, bool] _torrents_piece_size:Dict[str, int] _statistics:Dict[str, Dict[str, Tuple[int, int]]] _statistics_choked:Dict[str, Tuple[int, Optional[float]]] _statistics_started:Dict[str, float] _statistics_overflow:MutableMapping[str, Dict[str, Tuple...
() try: return self._cache[name] except KeyError: value = self._list[self._type[name]] if isinstance(value, int) and 0 > value >= self._32bit_signed_mini: # [PEER] Overflow 32bit signed (2G - 4G) value &= self._32bit1 if name == 'IP': ...
255
256
6,703
6
249
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
UTorrentWebAPI
UTorrentWebAPI
524
1,221
524
525
d49c380673188f8e36cc874ad8a0606e255de715
bigcode/the-stack
train
3130d3afb4ed40d2debdcc56
train
function
def is_ip(ip:Any) -> bool: try: if ':' in ip: inet_pton(AF_INET6, ip.strip('[]')) # Python bug? elif '.' in ip: inet_pton(AF_INET, ip) else: return False except: return False return True
def is_ip(ip:Any) -> bool:
try: if ':' in ip: inet_pton(AF_INET6, ip.strip('[]')) # Python bug? elif '.' in ip: inet_pton(AF_INET, ip) else: return False except: return False return True
getch() return None except ImportError: import select def get_keyhit() -> Optional[bytes]: if select.select([sys.stdin], [], [], 0)[0]: return sys.stdin.buffer.read(1) return None def is_ip(ip:Any) -> bool:
64
64
70
10
53
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
is_ip
is_ip
299
309
299
299
b15bde046bdd7049679610f16a6d84879e3b53a3
bigcode/the-stack
train
7920ab65c7286dbc0d28b12c
train
function
def limit_dict_lenght(dict:Dict, lenght:int) -> None: while len(dict) > lenght: del dict[next(iter(dict))]
def limit_dict_lenght(dict:Dict, lenght:int) -> None:
while len(dict) > lenght: del dict[next(iter(dict))]
' and n >= 1024: n /= 1024.0 else: break return ' '.join(['{:.3f}'.format(n).rstrip('0').rstrip('.')[:7], unit]) def limit_dict_lenght(dict:Dict, lenght:int) -> None:
64
64
31
16
48
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
limit_dict_lenght
limit_dict_lenght
321
323
321
321
28d41e89a3143354c153fb0900a40bd6aab78609
bigcode/the-stack
train
0e5f47613c368a94082abcea
train
function
def make_size_human(n:Union[int, float]) -> str: for unit in ('B', 'KB', 'MB', 'GB'): if unit != 'GB' and n >= 1024: n /= 1024.0 else: break return ' '.join(['{:.3f}'.format(n).rstrip('0').rstrip('.')[:7], unit])
def make_size_human(n:Union[int, float]) -> str:
for unit in ('B', 'KB', 'MB', 'GB'): if unit != 'GB' and n >= 1024: n /= 1024.0 else: break return ' '.join(['{:.3f}'.format(n).rstrip('0').rstrip('.')[:7], unit])
_pton(AF_INET6, ip.strip('[]')) # Python bug? elif '.' in ip: inet_pton(AF_INET, ip) else: return False except: return False return True def make_size_human(n:Union[int, float]) -> str:
64
64
85
15
48
SeaHOH/ban-peers
src/ban_peers/__init__.py
Python
make_size_human
make_size_human
312
318
312
312
12c0d0835a23a4f2151272dad754769372123ede
bigcode/the-stack
train