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
c3b131ac36721d1d8921bd0a
train
class
class Development(BaseConfig): SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URI")
class Development(BaseConfig):
SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URI")
"""QS Tech Test config objects""" import os class BaseConfig: SECRET_KEY = os.getenv("SECRET_KEY") or "ohsosecret" SQLALCHEMY_TRACK_MODIFICATIONS = False class Development(BaseConfig):
46
64
19
5
40
greener2/qs_techtest
qs_techtest/config.py
Python
Development
Development
11
12
11
11
a53926dfc7ecc5a26358bcf0af0055bea2a2438d
bigcode/the-stack
train
20559f53cfcbbef2634374b6
train
function
def initialise_from_environment(app_factory): """ If you're not using Paste, you can configure and instantiate instances of the application. """ config = utils.read_configuration('PASTETRON_CONFIG', 'pastetron') return app_factory(global_config=None, **config)
def initialise_from_environment(app_factory):
""" If you're not using Paste, you can configure and instantiate instances of the application. """ config = utils.read_configuration('PASTETRON_CONFIG', 'pastetron') return app_factory(global_config=None, **config)
request here. """ with pool.connect(): return handler() app.add_processor(request_processor) # Authentication. views.auth.method = utils.load_object(settings['auth_method']) views.auth.realm = settings['auth_realm'] return app.wsgifunc() def initialise_from_environmen...
64
64
59
7
57
kgaughan/pastetron
pastetron/bootstrap.py
Python
initialise_from_environment
initialise_from_environment
51
57
51
51
2279c8a327fc3193b9ec19bf940c13bdc4339016
bigcode/the-stack
train
e169e379f0973fb39b9f79fb
train
function
def initialise(app, global_config=None, **settings): """ Initialise a web.py application, returning a WSGI application. """ if global_config is None: global_config = { 'here': '.', } # Defaults. settings.setdefault('db_path', '%(here)s/pastetron.db' % global_config) ...
def initialise(app, global_config=None, **settings):
""" Initialise a web.py application, returning a WSGI application. """ if global_config is None: global_config = { 'here': '.', } # Defaults. settings.setdefault('db_path', '%(here)s/pastetron.db' % global_config) settings.setdefault('auth_method', 'pastetron.htt...
""" Application bootstrapping. """ import sqlite3 import dbkit import web from pastetron import utils, views def initialise(app, global_config=None, **settings):
38
74
248
11
26
kgaughan/pastetron
pastetron/bootstrap.py
Python
initialise
initialise
13
48
13
13
5e0e38f8b3e198d726731c826cccc0af3ab9e8b5
bigcode/the-stack
train
03ef4ddedbfb9523945eb8b7
train
function
@app.route('/jwt-verify') def jwt_verify(): token = request.args.get('token') try: return jwt.decode(token, "my-super-super-secret", algorithms=["HS256"]) except jwt.ExpiredSignatureError: return {'status': 'Unauthorized'}, 401
@app.route('/jwt-verify') def jwt_verify():
token = request.args.get('token') try: return jwt.decode(token, "my-super-super-secret", algorithms=["HS256"]) except jwt.ExpiredSignatureError: return {'status': 'Unauthorized'}, 401
-super-super-secret", algorithm='HS256', headers = {"iss": username, "iat": now, "exp": now + 300}) # generate JWT token # return the JWT token return {'status': 'Unauthorized'}, 401 @app.route('/jwt-verify') def jwt_verify():
64
64
59
11
52
PythonAttempt/Ticket-Zon
auth-service/main.py
Python
jwt_verify
jwt_verify
40
46
40
41
02aa76837eeb2e5b2355270d5d7b4ec6cf924e25
bigcode/the-stack
train
1ecf87f84126bb80271fabe3
train
function
@app.route('/jwt-token') #/jwt-token?username=james?password=whatever def jwt_issuer(): username = request.args.get('username') password = request.args.get('password') # match the username and password to users for user in users: if(user['username'] == username and user['password'] == password):...
@app.route('/jwt-token') #/jwt-token?username=james?password=whatever def jwt_issuer():
username = request.args.get('username') password = request.args.get('password') # match the username and password to users for user in users: if(user['username'] == username and user['password'] == password): #return (username + " " + password) now = int(time.time()) ...
}, { 'username': 'person1', 'password': 'password1' } ] @app.route('/') def hello_world(): return '<p>Hello, World!</p>' @app.route('/jwt-token') #/jwt-token?username=james?password=whatever def jwt_issuer():
63
64
160
24
39
PythonAttempt/Ticket-Zon
auth-service/main.py
Python
jwt_issuer
jwt_issuer
24
38
24
25
1f6f39d24704ffa4012abaee28de0bedd4b7bbe1
bigcode/the-stack
train
a4218ab015af1824befc41f1
train
function
@app.route('/') def hello_world(): return '<p>Hello, World!</p>'
@app.route('/') def hello_world():
return '<p>Hello, World!</p>'
request import jwt import time app = Flask(__name__) users = [ { 'username': 'james', 'password': 'whatever' }, { 'username': 'person1', 'password': 'password1' } ] @app.route('/') def hello_world():
64
64
17
7
57
PythonAttempt/Ticket-Zon
auth-service/main.py
Python
hello_world
hello_world
20
22
20
21
9dd844d80cf645814c6fa090905fb759b6a2cca3
bigcode/the-stack
train
f1820f1246fe8c9ba042be37
train
function
def _handle_list_values( cls, field_name, field_type, field_validator, field_value, new_instance, use_validator_field, value_to_field, field_ignored_list=None, ): if value_to_field: field_value = value_to_field(field_value) field_instance_type = _calculate_list_field_...
def _handle_list_values( cls, field_name, field_type, field_validator, field_value, new_instance, use_validator_field, value_to_field, field_ignored_list=None, ):
if value_to_field: field_value = value_to_field(field_value) field_instance_type = _calculate_list_field_instance_type(field_type) if isinstance(field_instance_type, str): # If str, check if it's a known registered Platform Play class # and convert field_instance_type from str to cla...
else: if field_value is None and not field_required: return field_value if field_type is not None and not isinstance(field_value, field_type): raise CreateSingleValueWrongTypeError( f"{field_value} is not of type {field_type}" ) return fi...
112
112
375
47
64
kdfwow64/yoyo
locations/utils/convertible.py
Python
_handle_list_values
_handle_list_values
253
306
253
263
04029ee86341557c83a067ffd67c8995f0bdb0ae
bigcode/the-stack
train
4025485233d3e86d33f39757
train
function
def from_dict( cls, d: dict, use_validator_field=True, ignored_fields: Union[list, tuple] = None ): new_instance = cls() # Generating {field: [field_nested_ignore_value_1, field_nested_ignore_value_2]} dictionary to ignore nested fields nested_ignore_dict = {} if ignored_fields is not None: ...
def from_dict( cls, d: dict, use_validator_field=True, ignored_fields: Union[list, tuple] = None ):
new_instance = cls() # Generating {field: [field_nested_ignore_value_1, field_nested_ignore_value_2]} dictionary to ignore nested fields nested_ignore_dict = {} if ignored_fields is not None: nested_ignore_fields = [field for field in ignored_fields if "." in field] for f in nested_ignor...
_callable(f, callable_name): if hasattr(f, "metadata"): if callable_name in f.metadata and hasattr( f.metadata[callable_name], "__call__" ): return f.metadata[callable_name] return None def _extract_metadata_boolean(f, boolean_name): if hasattr(f, "metadata"): ...
256
256
933
28
227
kdfwow64/yoyo
locations/utils/convertible.py
Python
from_dict
from_dict
66
184
66
68
d2e43efaac478ceba0026c641991be7b0f6a064c
bigcode/the-stack
train
d9df56994a1743df52b77685
train
class
class CreateSingleValueWrongTypeError(ValueError): """It wasn't possible to deserialize single element"""
class CreateSingleValueWrongTypeError(ValueError):
"""It wasn't possible to deserialize single element"""
"Field [{}.{}] is mandatory".format(cls.__name__, field_name) ) if hasattr(cls, "validate"): cls.validate(new_instance) if hasattr(cls, "post_init"): new_instance.post_init() return new_instance class CreateSingleValueWrongTypeError(ValueError):
64
64
20
10
53
kdfwow64/yoyo
locations/utils/convertible.py
Python
CreateSingleValueWrongTypeError
CreateSingleValueWrongTypeError
187
188
187
187
3726a09fbb810cd82510636fa341949aac3a3f63
bigcode/the-stack
train
b8240b21a1abddd9d581844f
train
function
def convertibleclass(_cls): """Keep track of a class""" registered_class[_cls.__name__] = _cls _cls = dataclass(_cls) setattr(_cls, __FIELDS, _cls.__name__) _cls.to_dict = to_dict _cls.from_dict = classmethod(from_dict) _cls.to_json = to_json _cls.from_json = from_json return _cls
def convertibleclass(_cls):
"""Keep track of a class""" registered_class[_cls.__name__] = _cls _cls = dataclass(_cls) setattr(_cls, __FIELDS, _cls.__name__) _cls.to_dict = to_dict _cls.from_dict = classmethod(from_dict) _cls.to_json = to_json _cls.from_json = from_json return _cls
_ascii, check_circular=check_circular, allow_nan=allow_nan, cls=cls, indent=indent, separators=separators, default=default, sort_keys=sort_keys, **kw, ) registered_class = {} def convertibleclass(_cls):
63
64
92
6
57
kdfwow64/yoyo
locations/utils/convertible.py
Python
convertibleclass
convertibleclass
459
468
459
459
d1803baaed618e17992e3dd3eac7284f14760cda
bigcode/the-stack
train
ce05183366a06a7fd2e30d90
train
function
def to_dict(self, include_none=True, ignored_fields: Union[list, tuple] = None): if not hasattr(self, "__dict__"): return self result = {} # Generating {field: [field_nested_ignore_value_1, field_nested_ignore_value_2]} dictionary to ignore nested fields nested_ignore_dict = {} if ignored_f...
def to_dict(self, include_none=True, ignored_fields: Union[list, tuple] = None):
if not hasattr(self, "__dict__"): return self result = {} # Generating {field: [field_nested_ignore_value_1, field_nested_ignore_value_2]} dictionary to ignore nested fields nested_ignore_dict = {} if ignored_fields is not None: nested_ignore_fields = [field for field in ignored_fie...
return field_instance_type def _is_from_generic_list(field_type): try: return field_type.__origin__ == list except Exception: return False def is_list_field(field_type, field_value): value_is_list = isinstance(field_value, list) field_type_is_list = isinstance(field_type, list) or ...
115
115
386
20
95
kdfwow64/yoyo
locations/utils/convertible.py
Python
to_dict
to_dict
331
375
331
331
7ee327dfe9a547b07c0d0bb577590db8dce845d2
bigcode/the-stack
train
0eec813d47679c81cb65192a
train
function
def _from_single_value( field_type, field_validator, field_value, use_validator_field, field_required, value_to_field=None, ignored_fields=None, ): if value_to_field: field_value = value_to_field(field_value) if isinstance(field_value, int) and field_validator is float: ...
def _from_single_value( field_type, field_validator, field_value, use_validator_field, field_required, value_to_field=None, ignored_fields=None, ):
if value_to_field: field_value = value_to_field(field_value) if isinstance(field_value, int) and field_validator is float: # WARN: The opposite is not tolerable and MUST NOT be implemented return float(field_value) elif ( isinstance(field_value, float) and isinstance...
] is mandatory".format(cls.__name__, field_name) ) if hasattr(cls, "validate"): cls.validate(new_instance) if hasattr(cls, "post_init"): new_instance.post_init() return new_instance class CreateSingleValueWrongTypeError(ValueError): """It wasn't possible to deserialize sin...
107
107
359
39
68
kdfwow64/yoyo
locations/utils/convertible.py
Python
_from_single_value
_from_single_value
191
250
191
199
908421f68d2a127863b37570d9ca0d977fafacd8
bigcode/the-stack
train
c38ea8ace0d1a26b42c9b2e7
train
function
def _is_from_generic_list(field_type): try: return field_type.__origin__ == list except Exception: return False
def _is_from_generic_list(field_type):
try: return field_type.__origin__ == list except Exception: return False
) ) def _calculate_list_field_instance_type(field_type): if _is_from_generic_list(field_type): field_instance_type = field_type.__args__[0] else: field_instance_type = field_type[0] return field_instance_type def _is_from_generic_list(field_type):
64
64
30
9
54
kdfwow64/yoyo
locations/utils/convertible.py
Python
_is_from_generic_list
_is_from_generic_list
317
322
317
317
cd31a1fb345ef55ce930c811d061e1452cccc3a2
bigcode/the-stack
train
705e06f294fb797e98a41781
train
function
@classmethod def from_json( cls, s, *, encoding=None, _cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw, ): return cls.from_dict( json.loads( s, encoding=encoding, c...
@classmethod def from_json( cls, s, *, encoding=None, _cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw, ):
return cls.from_dict( json.loads( s, encoding=encoding, cls=_cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, ...
_dict(val, include_none, ignored_fields) @classmethod def from_json( cls, s, *, encoding=None, _cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw, ):
64
64
120
55
9
kdfwow64/yoyo
locations/utils/convertible.py
Python
from_json
from_json
397
423
397
410
6ce39ab9de570c4b05cc16edf0242352d2e8d608
bigcode/the-stack
train
995a8a99c14d319048d4e25e
train
function
def _is_convertible(_cls): if hasattr(_cls, __FIELDS): return True return False
def _is_convertible(_cls):
if hasattr(_cls, __FIELDS): return True return False
import EnumMeta, Enum from typing import Union import aenum from locations.exceptions import DetailedException, ErrorCodes from locations.utils.json_utils import decamelize, camelize logger = logging.getLogger(__name__) __FIELDS = "_____CONVERTIBLE______" def _is_convertible(_cls):
64
64
25
8
56
kdfwow64/yoyo
locations/utils/convertible.py
Python
_is_convertible
_is_convertible
20
24
20
20
1f8e3f1243c988d53cd9f8855bda775a97e76628
bigcode/the-stack
train
8e4fcc650b2e9854f8ebd89c
train
function
def _extract_metadata_boolean(f, boolean_name): if hasattr(f, "metadata"): if boolean_name in f.metadata and isinstance(f.metadata[boolean_name], bool): return f.metadata[boolean_name] return False
def _extract_metadata_boolean(f, boolean_name):
if hasattr(f, "metadata"): if boolean_name in f.metadata and isinstance(f.metadata[boolean_name], bool): return f.metadata[boolean_name] return False
_extract_metadata_callable(f, callable_name): if hasattr(f, "metadata"): if callable_name in f.metadata and hasattr( f.metadata[callable_name], "__call__" ): return f.metadata[callable_name] return None def _extract_metadata_boolean(f, boolean_name):
64
64
47
10
53
kdfwow64/yoyo
locations/utils/convertible.py
Python
_extract_metadata_boolean
_extract_metadata_boolean
37
42
37
37
948429574bfcb5ada06d5556aca037cbe6ad83d3
bigcode/the-stack
train
3be4b47ff772bdae698bc960
train
function
def _calculate_list_field_instance_type(field_type): if _is_from_generic_list(field_type): field_instance_type = field_type.__args__[0] else: field_instance_type = field_type[0] return field_instance_type
def _calculate_list_field_instance_type(field_type):
if _is_from_generic_list(field_type): field_instance_type = field_type.__args__[0] else: field_instance_type = field_type[0] return field_instance_type
except Exception: raise ConvertibleClassValidationError( "List Field [{}.{}] with value [{}] is not type of [{}]".format( cls.__name__, field_name, field_value, field_instance_type.__name__ ) ) def _calculate_list_field_instance_type(...
64
64
51
10
54
kdfwow64/yoyo
locations/utils/convertible.py
Python
_calculate_list_field_instance_type
_calculate_list_field_instance_type
309
314
309
309
cf9a9833ecb044a1b2b5bc1d29a0106c122bfc4d
bigcode/the-stack
train
e56e0eeacbdd5b0b08465872
train
class
class ConvertibleClassValidationError(DetailedException): """ConvertibleClass validation error.""" def __init__(self, message=None): super().__init__( code=ErrorCodes.INVALID_REQUEST, debug_message=message or "Invalid Request", status_code=403, )
class ConvertibleClassValidationError(DetailedException):
"""ConvertibleClass validation error.""" def __init__(self, message=None): super().__init__( code=ErrorCodes.INVALID_REQUEST, debug_message=message or "Invalid Request", status_code=403, )
setattr(_cls, __FIELDS, _cls.__name__) _cls.to_dict = to_dict _cls.from_dict = classmethod(from_dict) _cls.to_json = to_json _cls.from_json = from_json return _cls class ConvertibleClassValidationError(DetailedException):
64
64
57
9
54
kdfwow64/yoyo
locations/utils/convertible.py
Python
ConvertibleClassValidationError
ConvertibleClassValidationError
471
479
471
471
aefdb9c5816e3751b5060dc9122c89a2fcef9dde
bigcode/the-stack
train
2624441115d1061d3c26e6c4
train
function
def to_json( obj, *, include_none=True, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw, ): return json.dumps( obj.to_dict(include_none), skipkeys=s...
def to_json( obj, *, include_none=True, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw, ):
return json.dumps( obj.to_dict(include_none), skipkeys=skipkeys, ensure_ascii=ensure_ascii, check_circular=check_circular, allow_nan=allow_nan, cls=cls, indent=indent, separators=separators, default=default, sort_keys=sort_keys, ...
) ) def to_json( obj, *, include_none=True, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw, ):
64
64
138
61
3
kdfwow64/yoyo
locations/utils/convertible.py
Python
to_json
to_json
426
453
426
440
eca967c32131ab7c2e1cec56bb31037bf1c2c329
bigcode/the-stack
train
ed6291c98a80fa6277f3a496
train
function
def _to_single_value( val, include_none: bool, ignored_fields: Union[list, tuple] = None ): if isinstance(val, Enum): first_enum = [item for item in val.__class__][0] if isinstance(first_enum, int): return int(val) return val.name elif isinstance(val, Decimal): ...
def _to_single_value( val, include_none: bool, ignored_fields: Union[list, tuple] = None ):
if isinstance(val, Enum): first_enum = [item for item in val.__class__][0] if isinstance(first_enum, int): return int(val) return val.name elif isinstance(val, Decimal): return float(val) elif isinstance(val, (dict, datetime)): return val else: ...
_value(element) if include_none: result[key] = element elif element is not None and val is not None: result[key] = element return result def _to_single_value( val, include_none: bool, ignored_fields: Union[list, tuple] = None ):
64
64
108
26
37
kdfwow64/yoyo
locations/utils/convertible.py
Python
_to_single_value
_to_single_value
378
394
378
380
6c226196d838d9ab13a9ddda8a5b52d7438d2819
bigcode/the-stack
train
339533708ed972f96fe96742
train
function
def meta( validator=None, required: bool = False, field_to_value=None, value_to_field=None ): result = {} if validator is not None: result[VALIDATOR] = validator if required is not None: result[REQUIRED] = required if value_to_field: result[VAL_TO_FIELD] = value_to_field ...
def meta( validator=None, required: bool = False, field_to_value=None, value_to_field=None ):
result = {} if validator is not None: result[VALIDATOR] = validator if required is not None: result[REQUIRED] = required if value_to_field: result[VAL_TO_FIELD] = value_to_field if field_to_value: result[FIELD_TO_VAL] = field_to_value return result
f.metadata[boolean_name] return False VALIDATOR = "validator" REQUIRED = "required" VAL_TO_FIELD = "val_to_field" FIELD_TO_VAL = "field_to_val" def meta( validator=None, required: bool = False, field_to_value=None, value_to_field=None ):
64
64
100
24
40
kdfwow64/yoyo
locations/utils/convertible.py
Python
meta
meta
51
63
51
53
7f2a9d872b4712911340bce28b0eb35eb8cae9a1
bigcode/the-stack
train
ebf40ec3196fef2c7014e4bb
train
function
def _extract_metadata_callable(f, callable_name): if hasattr(f, "metadata"): if callable_name in f.metadata and hasattr( f.metadata[callable_name], "__call__" ): return f.metadata[callable_name] return None
def _extract_metadata_callable(f, callable_name):
if hasattr(f, "metadata"): if callable_name in f.metadata and hasattr( f.metadata[callable_name], "__call__" ): return f.metadata[callable_name] return None
.utils.json_utils import decamelize, camelize logger = logging.getLogger(__name__) __FIELDS = "_____CONVERTIBLE______" def _is_convertible(_cls): if hasattr(_cls, __FIELDS): return True return False def _extract_metadata_callable(f, callable_name):
64
64
55
10
53
kdfwow64/yoyo
locations/utils/convertible.py
Python
_extract_metadata_callable
_extract_metadata_callable
27
34
27
27
b687c88a9513192f9b4957ed40024ddc0c34a7f3
bigcode/the-stack
train
15f7ab2d287d4f993c557e56
train
class
class Convertible: @classmethod def from_dict(cls, data: dict): _dict = {} for k, v in data.items(): key = decamelize(k) _dict[key] = v return cls(**_dict) def to_dict(self, remove_keys: [] = None) -> dict: _dict = camelize(self.__dict__) kwar...
class Convertible: @classmethod
def from_dict(cls, data: dict): _dict = {} for k, v in data.items(): key = decamelize(k) _dict[key] = v return cls(**_dict) def to_dict(self, remove_keys: [] = None) -> dict: _dict = camelize(self.__dict__) kwargs = _dict.pop("kwargs", None) ...
class ConvertibleClassValidationError(DetailedException): """ConvertibleClass validation error.""" def __init__(self, message=None): super().__init__( code=ErrorCodes.INVALID_REQUEST, debug_message=message or "Invalid Request", status_code=403, ) class Conver...
64
64
126
7
57
kdfwow64/yoyo
locations/utils/convertible.py
Python
Convertible
Convertible
482
501
482
483
9f03ebca45f98ed4db266d1a48f067125d52fa5c
bigcode/the-stack
train
deb6714f707d7652d26fa600
train
function
def is_list_field(field_type, field_value): value_is_list = isinstance(field_value, list) field_type_is_list = isinstance(field_type, list) or field_type == list return (value_is_list and field_type_is_list) or _is_from_generic_list(field_type)
def is_list_field(field_type, field_value):
value_is_list = isinstance(field_value, list) field_type_is_list = isinstance(field_type, list) or field_type == list return (value_is_list and field_type_is_list) or _is_from_generic_list(field_type)
.__args__[0] else: field_instance_type = field_type[0] return field_instance_type def _is_from_generic_list(field_type): try: return field_type.__origin__ == list except Exception: return False def is_list_field(field_type, field_value):
64
64
60
10
53
kdfwow64/yoyo
locations/utils/convertible.py
Python
is_list_field
is_list_field
325
328
325
325
9f1b8d14b25b6e717bbbd13042c6132c13616073
bigcode/the-stack
train
e0486d0bd80f95c30dfd72f7
train
function
def connected(s, request): selector.unregister(s.fileno()) # socket 可写 s.send(request.encode()) chunks = [] def callback(): return readable(s, chunks) f = Future() f.callbacks.append(callback) selector.register(s.fileno(), EVENT_READ, data=f)
def connected(s, request):
selector.unregister(s.fileno()) # socket 可写 s.send(request.encode()) chunks = [] def callback(): return readable(s, chunks) f = Future() f.callbacks.append(callback) selector.register(s.fileno(), EVENT_READ, data=f)
'GET {} HTTP/1.0\r\n\r\n'.format(path) def callback(): return connected(s, request) f = Future() f.callbacks.append(callback) selector.register(s.fileno(), EVENT_WRITE, data=f) # data 是 Future 对象 def connected(s, request):
64
64
63
6
57
jumploop/collection_python
socket_programming/3_nonblocking_future_loop.py
Python
connected
connected
45
55
45
45
05c4ae08a15cff476bfdfbfe1a14e255f15335fd
bigcode/the-stack
train
20f2c5818c08e7576b5a261b
train
function
def get(path): global num_tasks num_tasks += 1 s = socket.socket() s.setblocking(False) # 非阻塞模式 try: s.connect(('localhost', 5000)) except BlockingIOError: pass request = 'GET {} HTTP/1.0\r\n\r\n'.format(path) def callback(): return connected(s, request) f = Futu...
def get(path):
global num_tasks num_tasks += 1 s = socket.socket() s.setblocking(False) # 非阻塞模式 try: s.connect(('localhost', 5000)) except BlockingIOError: pass request = 'GET {} HTTP/1.0\r\n\r\n'.format(path) def callback(): return connected(s, request) f = Future() f.call...
from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ selector = DefaultSelector() num_tasks = 0 class Future: """代表pending 的 events""" def __init__(self): self.callbacks = [] def resolve(self): for callback in self.callbacks: callback() def get(path):
64
64
118
4
60
jumploop/collection_python
socket_programming/3_nonblocking_future_loop.py
Python
get
get
27
42
27
27
294587f2a100e18ee07bf13b982092c1564885fa
bigcode/the-stack
train
791afbd12524d4d049a20d7c
train
function
def readable(s, chunks): global num_tasks # s is readable selector.unregister(s.fileno()) chunk = s.recv(1000) if chunk: chunks.append(chunk) def callback(): return readable(s, chunks) f = Future() f.callbacks.append(callback) selector.register(s.fileno(), EV...
def readable(s, chunks):
global num_tasks # s is readable selector.unregister(s.fileno()) chunk = s.recv(1000) if chunk: chunks.append(chunk) def callback(): return readable(s, chunks) f = Future() f.callbacks.append(callback) selector.register(s.fileno(), EVENT_READ, data=f) els...
): selector.unregister(s.fileno()) # socket 可写 s.send(request.encode()) chunks = [] def callback(): return readable(s, chunks) f = Future() f.callbacks.append(callback) selector.register(s.fileno(), EVENT_READ, data=f) def readable(s, chunks):
64
64
102
6
58
jumploop/collection_python
socket_programming/3_nonblocking_future_loop.py
Python
readable
readable
58
73
58
58
7de78c3ff58683afdf0154c41e2cc44844294ea0
bigcode/the-stack
train
4e762c078829a8a2cacd112b
train
class
class Future: """代表pending 的 events""" def __init__(self): self.callbacks = [] def resolve(self): for callback in self.callbacks: callback()
class Future:
"""代表pending 的 events""" def __init__(self): self.callbacks = [] def resolve(self): for callback in self.callbacks: callback()
# -*- coding: utf-8 -*- """ Future generators Task """ import socket import time from selectors import DefaultSelector, EVENT_WRITE, EVENT_READ selector = DefaultSelector() num_tasks = 0 class Future:
50
64
37
3
46
jumploop/collection_python
socket_programming/3_nonblocking_future_loop.py
Python
Future
Future
17
24
17
17
6b71a05f58b300c6125efefdb60bfdd9ae5361db
bigcode/the-stack
train
5f5c3749c966d8fe0230492e
train
function
def test_main(capsys): """CLI Tests""" # capsys is a pytest fixture that allows asserts agains stdout/stderr # https://docs.pytest.org/en/stable/capture.html main(["7"]) captured = capsys.readouterr() assert "The 7-th Fibonacci number is 13" in captured.out
def test_main(capsys):
"""CLI Tests""" # capsys is a pytest fixture that allows asserts agains stdout/stderr # https://docs.pytest.org/en/stable/capture.html main(["7"]) captured = capsys.readouterr() assert "The 7-th Fibonacci number is 13" in captured.out
= "MIT" def test_fib(): """API Tests""" assert fib(1) == 1 assert fib(2) == 1 assert fib(7) == 13 with pytest.raises(AssertionError): fib(-10) def test_main(capsys):
64
64
75
7
57
luk036/bairstow
tests/test_skeleton.py
Python
test_main
test_main
19
25
19
19
36576c4ec1f211bf8e614c1d4df5b8241b794cc0
bigcode/the-stack
train
931adbb3fb3503d43599f1ec
train
function
def test_fib(): """API Tests""" assert fib(1) == 1 assert fib(2) == 1 assert fib(7) == 13 with pytest.raises(AssertionError): fib(-10)
def test_fib():
"""API Tests""" assert fib(1) == 1 assert fib(2) == 1 assert fib(7) == 13 with pytest.raises(AssertionError): fib(-10)
import pytest from bairstow.skeleton import fib, main __author__ = "Wai-Shing Luk" __copyright__ = "Wai-Shing Luk" __license__ = "MIT" def test_fib():
48
64
53
5
43
luk036/bairstow
tests/test_skeleton.py
Python
test_fib
test_fib
10
16
10
10
8b5d4c6826faa1889ee25aba34fb70ddf43acd91
bigcode/the-stack
train
17de02abdf36acd1dc51088a
train
class
class MemoryMultiTab(page_test.PageTest): def __init__(self): super(MemoryMultiTab, self).__init__() self._memory_metric = None # _first_tab is used to make memory measurements self._first_tab = None def DidStartBrowser(self, browser): self._memory_metric = memory.MemoryMetric(browser) def ...
class MemoryMultiTab(page_test.PageTest):
def __init__(self): super(MemoryMultiTab, self).__init__() self._memory_metric = None # _first_tab is used to make memory measurements self._first_tab = None def DidStartBrowser(self, browser): self._memory_metric = memory.MemoryMetric(browser) def CustomizeBrowserOptions(self, options): ...
. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Multi tab memory test. This test is a multi tab test, but we're interested in measurements for the entire test rather than each single page. """ from telemetry.page import page_test from metrics import memory ...
77
77
259
9
67
bopopescu/MQUIC
src/tools/perf/measurements/memory_multi_tab.py
Python
MemoryMultiTab
MemoryMultiTab
16
46
16
17
b03604b15b77b2fc082d3b05d4dc2cdd60405132
bigcode/the-stack
train
80a0cb0334699ab301e8f1c4
train
function
def main(): THIS_DIR = path.dirname(path.realpath(__file__)) PCD_DIR = path.join(THIS_DIR, '..', '..', 'fixtures', 'pcd') mesh_file = path.join(PCD_DIR, 'pc_01.pcd') pc, pc_image = load_pcd_file( mesh_file, stride=2) # Not Smooth Mesh tri_mesh_noisy, tri_mesh_noisy_o3d = create_mesh_fro...
def main():
THIS_DIR = path.dirname(path.realpath(__file__)) PCD_DIR = path.join(THIS_DIR, '..', '..', 'fixtures', 'pcd') mesh_file = path.join(PCD_DIR, 'pc_01.pcd') pc, pc_image = load_pcd_file( mesh_file, stride=2) # Not Smooth Mesh tri_mesh_noisy, tri_mesh_noisy_o3d = create_mesh_from_organized_...
"""Demonsrates Bilateral Normal Filtering using CPU and GPU Acceleration """ from os import path import numpy as np import logging import open3d as o3d import organizedpointfilters as opf from organizedpointfilters import Matrix3f, Matrix3fRef logging.basicConfig(level=logging.INFO) logger = logging.getLogger("PPB") l...
136
181
604
3
132
oori/OrganizedPointFilters
examples/python/example-bilateral.py
Python
main
main
20
55
20
20
f5a9369c78b86b97627aacf67527d9401d5591ad
bigcode/the-stack
train
aa01f9fc684b136406ae239e
train
function
def decode_base58(bc, length): n = 0 for char in bc: n = n * 58 + digits58.index(char) return n.to_bytes(length, 'big')
def decode_base58(bc, length):
n = 0 for char in bc: n = n * 58 + digits58.index(char) return n.to_bytes(length, 'big')
from hashlib import sha256 digits58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def decode_base58(bc, length):
31
64
44
9
22
silverlogic/dj-bitcoin
djbitcoin/utils.py
Python
decode_base58
decode_base58
6
10
6
6
efaf6c543b3b358e4eba1b14b20495ad612a9ef8
bigcode/the-stack
train
305dea0e9046a23cfdef7b2a
train
function
def is_bitcoin_address_valid(address): try: bcbytes = decode_base58(address, 25) except ValueError: return False return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
def is_bitcoin_address_valid(address):
try: bcbytes = decode_base58(address, 25) except ValueError: return False return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4]
123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' def decode_base58(bc, length): n = 0 for char in bc: n = n * 58 + digits58.index(char) return n.to_bytes(length, 'big') def is_bitcoin_address_valid(address):
64
64
58
8
56
silverlogic/dj-bitcoin
djbitcoin/utils.py
Python
is_bitcoin_address_valid
is_bitcoin_address_valid
13
18
13
13
2c225e179a42cc60754d675d1a4535686a6abf71
bigcode/the-stack
train
f74207125d6ac7626f023788
train
function
def get_font_paths_from_list(list_filename): with open(list_filename) as f: lines = f.readlines() fonts = [os.path.abspath(l.strip()) for l in lines] for font in fonts: if not os.path.exists(font): print("Font [%s] not exist." % font) exit(-1) ...
def get_font_paths_from_list(list_filename):
with open(list_filename) as f: lines = f.readlines() fonts = [os.path.abspath(l.strip()) for l in lines] for font in fonts: if not os.path.exists(font): print("Font [%s] not exist." % font) exit(-1) print("Total fonts num: %d" % len(lines...
() def get_font_paths(fonts_dir): """ Load font path recursively from a folder :param fonts_dir: folder contains ttf、otf or ttc format font :return: path of all fonts """ print('Load fonts from %s' % os.path.abspath(fonts_dir)) fonts = glob.glob(fonts_dir + '/**/*', recursive=True) font...
151
151
504
9
141
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
get_font_paths_from_list
get_font_paths_from_list
49
94
49
49
e21b966abcf21da74653b8b8731ff705a78862a9
bigcode/the-stack
train
909f538297b35424148bb792
train
function
def load_chars(filepath): if not os.path.exists(filepath): print("Chars file not exists.") exit(1) ret = '' with open(filepath, 'r', encoding='utf-8') as f: while True: line = f.readline() if not line: break ret += line.strip('\n')...
def load_chars(filepath):
if not os.path.exists(filepath): print("Chars file not exists.") exit(1) ret = '' with open(filepath, 'r', encoding='utf-8') as f: while True: line = f.readline() if not line: break ret += line.strip('\n') return ret
import os import pickle import glob from itertools import chain import hashlib from fontTools.ttLib import TTCollection, TTFont from fontTools.unicode import Unicode # from .utils import md5, load_chars def load_chars(filepath):
53
64
77
5
47
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
load_chars
load_chars
13
25
13
13
bd1dcd465af70371c089c4961ca1cabdf731ccca
bigcode/the-stack
train
aa5a6cef3ec5d92e06969dfa
train
function
def get_fonts_chars(fonts, chars_file): """ loads/saves font supported chars from cache file :param fonts: list of font path. e.g ['./data/fonts/msyh.ttc'] :param chars_file: arg from parse_args :return: dict key -> font_path value -> font supported chars """ out = {} ca...
def get_fonts_chars(fonts, chars_file):
""" loads/saves font supported chars from cache file :param fonts: list of font path. e.g ['./data/fonts/msyh.ttc'] :param chars_file: arg from parse_args :return: dict key -> font_path value -> font supported chars """ out = {} cache_dir = os.path.abspath(os.path.join(o...
0]],) for y in x.cmap.items()] for x in ttf["cmap"].tables) try: chars_int=set() for table in ttf['cmap'].tables: for k,v in table.cmap.items(): chars_int.add(k) unsupported_chars = [] supported_chars = [] for c in charset: if ord(c) n...
129
129
432
10
118
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
get_fonts_chars
get_fonts_chars
144
197
144
144
874bfd1e8d94d88bbe997068583d65bc3bea5634
bigcode/the-stack
train
768cf2a811238b9aa6b3178d
train
function
def get_unsupported_chars(fonts, chars_file): """ Get fonts unsupported chars by loads/saves font supported chars from cache file :param fonts: :param chars_file: :return: dict key -> font_path value -> font unsupported chars """ charset = load_chars(chars_file) charset =...
def get_unsupported_chars(fonts, chars_file):
""" Get fonts unsupported chars by loads/saves font supported chars from cache file :param fonts: :param chars_file: :return: dict key -> font_path value -> font unsupported chars """ charset = load_chars(chars_file) charset = ''.join(charset) fonts_chars = get_fonts_...
(%s) supported chars(%d) from cache' % (font_path, len(supported_chars))) except: print('这个字体不行' ,font_path) continue out[font_path] = supported_chars return out def get_unsupported_chars(fonts, chars_file):
64
64
144
11
52
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
get_unsupported_chars
get_unsupported_chars
200
216
200
200
1899422207e2f846daac954461019c7bf24e090f
bigcode/the-stack
train
6cf34382624a999d1d7eab75
train
function
def get_font_paths(fonts_dir): """ Load font path recursively from a folder :param fonts_dir: folder contains ttf、otf or ttc format font :return: path of all fonts """ print('Load fonts from %s' % os.path.abspath(fonts_dir)) fonts = glob.glob(fonts_dir + '/**/*', recursive=True) fonts = ...
def get_font_paths(fonts_dir):
""" Load font path recursively from a folder :param fonts_dir: folder contains ttf、otf or ttc format font :return: path of all fonts """ print('Load fonts from %s' % os.path.abspath(fonts_dir)) fonts = glob.glob(fonts_dir + '/**/*', recursive=True) fonts = list(filter(lambda x: os.path.i...
True: line = f.readline() if not line: break ret += line.strip('\n') return ret def md5(string): m = hashlib.md5() m.update(string.encode('utf-8')) return m.hexdigest() def get_font_paths(fonts_dir):
64
64
141
8
56
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
get_font_paths
get_font_paths
32
46
32
32
3814f27f8695191317d72a41d5511e01f871459a
bigcode/the-stack
train
2d51ace74b3a82000822574e
train
function
def md5(string): m = hashlib.md5() m.update(string.encode('utf-8')) return m.hexdigest()
def md5(string):
m = hashlib.md5() m.update(string.encode('utf-8')) return m.hexdigest()
not exists.") exit(1) ret = '' with open(filepath, 'r', encoding='utf-8') as f: while True: line = f.readline() if not line: break ret += line.strip('\n') return ret def md5(string):
64
64
28
5
58
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
md5
md5
27
30
27
27
7aa53e8be9fe1fb07dec1597cecdf8c53acbb2c9
bigcode/the-stack
train
291b2a3d2a666ddd610ed4f8
train
function
def check_font_chars(ttf, charset): """ Get font supported chars and unsupported chars :param ttf: TTFont ojbect :param charset: chars :return: unsupported_chars, supported_chars """ #chars = chain.from_iterable([y + (Unicode[y[0]],) for y in x.cmap.items()] for x in ttf["cmap"].tables) ...
def check_font_chars(ttf, charset):
""" Get font supported chars and unsupported chars :param ttf: TTFont ojbect :param charset: chars :return: unsupported_chars, supported_chars """ #chars = chain.from_iterable([y + (Unicode[y[0]],) for y in x.cmap.items()] for x in ttf["cmap"].tables) try: chars_int=set() ...
('ttf') or font_path.endswith('TTF') or font_path.endswith('otf'): ttf = TTFont(font_path, 0, allowVID=0, ignoreDecompileErrors=True, fontNumber=-1) return ttf def check_font_chars(ttf, charset):
64
64
185
9
54
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
check_font_chars
check_font_chars
116
141
116
116
14f7dc8fdb9ffdf1870685a5b38f9c4f67747245
bigcode/the-stack
train
f44b98160338ffec14de04fa
train
function
def load_font(font_path): """ Read ttc, ttf, otf font file, return a TTFont object """ # ttc is collection of ttf if font_path.endswith('ttc'): ttc = TTCollection(font_path) # assume all ttfs in ttc file have same supported chars return ttc.fonts[0] if font_path.endswit...
def load_font(font_path):
""" Read ttc, ttf, otf font file, return a TTFont object """ # ttc is collection of ttf if font_path.endswith('ttc'): ttc = TTCollection(font_path) # assume all ttfs in ttc file have same supported chars return ttc.fonts[0] if font_path.endswith('ttf') or font_path.ends...
.lower()\ and 'Lato-SemiboldItalic.ttf'.lower() not in font_path.lower(): font_dct['eng_strict'].append(font_path) font_dct['eng'].append(font_path) print(font_dct) return font_dct def load_font(font_path):
64
64
141
6
57
Sand0001/OCR_textrender_jap_chn_eng
libs/font_utils.py
Python
load_font
load_font
97
113
97
97
e1ef17af0622dd5afbb28426d16e2e7aca70e24c
bigcode/the-stack
train
6d752bcb9a0d9dfd2f4b5f9e
train
class
class MessageConv(Converter): @staticmethod def get_channels_and_id(ctx, argument): # Checking if it's a dual ID match = DUAL_ID_REGEX.match(argument) if match is not None: channel_id = int(match[1]) message_id = int(match[2]) channel = ctx.guild.get_...
class MessageConv(Converter): @staticmethod
def get_channels_and_id(ctx, argument): # Checking if it's a dual ID match = DUAL_ID_REGEX.match(argument) if match is not None: channel_id = int(match[1]) message_id = int(match[2]) channel = ctx.guild.get_channel(channel_id) if channel is No...
is distributed in the hopes that it will be useful, but # WITHOUT ANY WARRANTY. See the LICENSE file for more details. # import asyncio import logging import re import discord from discord.ext.commands import BadArgument, Converter from futaba.utils import first from .utils import DUAL_ID_REGEX, ID_REGEX logger =...
134
134
447
10
124
Hoffs/futaba
futaba/converters/message.py
Python
MessageConv
MessageConv
33
96
33
34
7193ce2c87bb787de563f83f8e2cafa6ca98dbf6
bigcode/the-stack
train
1f9eac06fac7ceedf8d06198
train
function
def lrotate(s, d): ''' Function to rotate string left by d length ''' return s[d:] + s[0:d]
def lrotate(s, d):
''' Function to rotate string left by d length ''' return s[d:] + s[0:d]
def is_printable(text, ignore_code): ''' Function to check if every character in text is printable ''' for ch in text: if ord(ch) == ignore_code: continue if ch not in string.printable: return False return True def lrotate(s, d):
64
64
29
7
56
usamanaveed900/Known-Plaintext-Attack
KPA.py
Python
lrotate
lrotate
22
24
22
22
2c3aaa52d460a2ed3a5a82d439820724f51d9d87
bigcode/the-stack
train
93de87578710ac9f1f62315d
train
function
def is_printable(text, ignore_code): ''' Function to check if every character in text is printable ''' for ch in text: if ord(ch) == ignore_code: continue if ch not in string.printable: return False return True
def is_printable(text, ignore_code):
''' Function to check if every character in text is printable ''' for ch in text: if ord(ch) == ignore_code: continue if ch not in string.printable: return False return True
#!/usr/bin/python from __future__ import print_function from __future__ import division import string, sys ignore_code = 0xff printable_key = True max_key_length = 100 def is_printable(text, ignore_code):
54
64
57
9
44
usamanaveed900/Known-Plaintext-Attack
KPA.py
Python
is_printable
is_printable
12
19
12
12
a488d88a8682b9f0feb924e587204ab7518e43bb
bigcode/the-stack
train
e603f46399a9b6d6239e6993
train
function
def _test_ops_on_store(store): s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello', '_non_existing_key_']) # test "not in" assert ( '_non_existing_key_' not in s ), "I really wasn't expecting that key to be in there!" s['_foo'] = 'bar' # sto...
def _test_ops_on_store(store):
s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello', '_non_existing_key_']) # test "not in" assert ( '_non_existing_key_' not in s ), "I really wasn't expecting that key to be in there!" s['_foo'] = 'bar' # store 'bar' in '_foo' assert '...
import pytest import os import shutil from tempfile import gettempdir from py2store.errors import OverWritesNotAllowedError, DeletionsNotAllowed from py2store.test.util import get_s3_test_access_info_from_env_vars # from collections.abc import MutableMapping # from py2store.base import AbstractObjStore # import typin...
139
175
584
8
131
i2mint/py2store
tests/test_simple.py
Python
_test_ops_on_store
_test_ops_on_store
22
83
22
22
9904dfa894eec4d599d77405e67b2f84bc2b4fa0
bigcode/the-stack
train
d0a94fdb800592397e276ab7
train
function
def _test_len(store): s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello']) n = len(s) # remember how many items there are s['_foo'] = 'bar' # store 'bar' in '_foo' assert len(s) == n + 1, 'You should have an extra item in the store' s['_hello'] =...
def _test_len(store):
s = store # just to be able to use shorthand "s" _delete_keys_from_store(s, ['_foo', '_hello']) n = len(s) # remember how many items there are s['_foo'] = 'bar' # store 'bar' in '_foo' assert len(s) == n + 1, 'You should have an extra item in the store' s['_hello'] = 'world' # store 'wor...
put it back except DeletionsNotAllowed: pass # wraped in try/except in case overwriting is not allowed try: s['_foo'] = 'a different value' assert s['_foo'] == 'a different value' except OverWritesNotAllowedError: pass _delete_keys_from_store(s, ['_foo', '_hello'])...
89
90
301
6
83
i2mint/py2store
tests/test_simple.py
Python
_test_len
_test_len
86
119
86
86
07d771c6cd72c214acaf7f6e9bf1533938e80f94
bigcode/the-stack
train
9ffd17141ab7d1ca1b9dc20d
train
function
def test_dropbox(): from py2store.util import ModuleNotFoundIgnore with ModuleNotFoundIgnore(): from py2store.access import FAK from py2store.stores.dropbox_store import DropboxTextStore import json import os try: filepath = os.path.expanduser( ...
def test_dropbox():
from py2store.util import ModuleNotFoundIgnore with ModuleNotFoundIgnore(): from py2store.access import FAK from py2store.stores.dropbox_store import DropboxTextStore import json import os try: filepath = os.path.expanduser( '~/.py2store_conf...
.mkdir(rootdir) from py2store.stores.local_store import RelativePathFormatStore as cls _test_path_format_local_file_ops(cls) from py2store.stores.local_store import RelativePathFormatStore2 as cls _test_path_format_local_file_ops(cls) def test_dropbox():
64
64
144
5
59
i2mint/py2store
tests/test_simple.py
Python
test_dropbox
test_dropbox
177
196
177
177
427a95ca50ef2079e9c84427f53f27146a424e1c
bigcode/the-stack
train
2b2fde7b58769926d705be05
train
function
def test_local_file_ops(): rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) from py2store.stores.local_store import RelativePathFormatStore as cls _test_path_format_local...
def test_local_file_ops():
rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) from py2store.stores.local_store import RelativePathFormatStore as cls _test_path_format_local_file_ops(cls) from py...
os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) store = cls(path_format=rootdir) _multi_test(store) def test_local_file_ops():
64
64
108
6
58
i2mint/py2store
tests/test_simple.py
Python
test_local_file_ops
test_local_file_ops
161
174
161
161
8489cd8d333b0c8ae933c822d083d4816fcc1c40
bigcode/the-stack
train
b52b876e33057ac3f70d646d
train
function
def test_dict_ops(): store = dict() _multi_test(store)
def test_dict_ops():
store = dict() _multi_test(store)
WritesNotAllowedError: pass _delete_keys_from_store(s, ['_foo', '_hello']) # # @fixture # def empty_dict_store(): # return {} def _multi_test(store): _test_ops_on_store(store) _test_len(store) def test_dict_ops():
64
64
16
5
59
i2mint/py2store
tests/test_simple.py
Python
test_dict_ops
test_dict_ops
131
133
131
131
8e9ad51283a06b6b511be0841fc0d1ff8142e8b7
bigcode/the-stack
train
636d5741b271ad5d2a0fe287
train
function
def _test_path_format_local_file_ops(cls): rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) store = cls(path_format=rootdir) _multi_test(store)
def _test_path_format_local_file_ops(cls):
rootdir = os.path.join(gettempdir(), 'py_store_tests') # empty and recreate rootdir if necessary if os.path.isdir(rootdir): shutil.rmtree(rootdir) os.mkdir(rootdir) store = cls(path_format=rootdir) _multi_test(store)
# shutil.rmtree(rootdir) # os.mkdir(rootdir) # # store = RelativePathFormatStore(path_format=rootdir) # # store._obj_of_data = partial(str, encoding='utf-8') # _multi_test(store) def _test_path_format_local_file_ops(cls):
64
64
72
10
54
i2mint/py2store
tests/test_simple.py
Python
_test_path_format_local_file_ops
_test_path_format_local_file_ops
150
158
150
150
d90bc962454de1f478ea023f9b11aead2f15aeed
bigcode/the-stack
train
fa57fc0aaf2d87844eed4733
train
function
def _delete_keys_from_store(store, keys_to_delete): for k in keys_to_delete: if k in store: # if key already in s, delete it del store[k]
def _delete_keys_from_store(store, keys_to_delete):
for k in keys_to_delete: if k in store: # if key already in s, delete it del store[k]
store.test.util import get_s3_test_access_info_from_env_vars # from collections.abc import MutableMapping # from py2store.base import AbstractObjStore # import typing # # Store = typing.Union(AbstractObjStore, MutableMapping) def _delete_keys_from_store(store, keys_to_delete):
64
64
42
12
52
i2mint/py2store
tests/test_simple.py
Python
_delete_keys_from_store
_delete_keys_from_store
16
19
16
16
bfc0ca9bc08b151f30bf666ca2a9b00075d8fb3c
bigcode/the-stack
train
f46a49fb46a0686c3c88a967
train
function
def _multi_test(store): _test_ops_on_store(store) _test_len(store)
def _multi_test(store):
_test_ops_on_store(store) _test_len(store)
'a different value' assert len(s) == n + 2 except OverWritesNotAllowedError: pass _delete_keys_from_store(s, ['_foo', '_hello']) # # @fixture # def empty_dict_store(): # return {} def _multi_test(store):
64
64
20
6
58
i2mint/py2store
tests/test_simple.py
Python
_multi_test
_multi_test
126
128
126
126
5c51dceb134a50f257002a7d22923bad44614c8d
bigcode/the-stack
train
a497dea3272f89b34428b380
train
function
@pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla_nprocs(xmp_executor, dirname): n = int(os.environ["NUM_TPU_WORKERS"]) xmp_execu...
@pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla_nprocs(xmp_executor, dirname):
n = int(os.environ["NUM_TPU_WORKERS"]) xmp_executor(_test_tpu_saves_to_cpu_nprocs, args=(dirname,), nprocs=n)
@pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" not in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla_nprocs(xmp_executor, dirname):
71
64
109
71
0
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_distrib_single_device_xla_nprocs
test_distrib_single_device_xla_nprocs
1,256
1,261
1,256
1,259
1d4fe946e767488153ecf536c121ccc6b2856bbc
bigcode/the-stack
train
76a3312629722048053ee786
train
function
def test_setup_filename_pattern(): # default filename pattern assert Checkpoint.setup_filename_pattern() == "{filename_prefix}_{name}_{global_step}_{score_name}={score}.{ext}" assert Checkpoint.setup_filename_pattern(False) == "{name}_{global_step}_{score_name}={score}.{ext}" assert Checkpoint.setup_fi...
def test_setup_filename_pattern(): # default filename pattern
assert Checkpoint.setup_filename_pattern() == "{filename_prefix}_{name}_{global_step}_{score_name}={score}.{ext}" assert Checkpoint.setup_filename_pattern(False) == "{name}_{global_step}_{score_name}={score}.{ext}" assert Checkpoint.setup_filename_pattern(False, False, False) == "{name}_{global_step}.{ext}...
_test(to_save, filename_pattern=pattern) == "203-chk--model-None-None.pt" with pytest.raises(KeyError, match=r"random_key"): pattern = "SAVE:{random_key}.{ext}" _test(to_save, filename_pattern=pattern) def test_setup_filename_pattern(): # default filename pattern
70
70
234
12
58
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_setup_filename_pattern
test_setup_filename_pattern
1,411
1,425
1,411
1,412
bc35c5502ca0c89dd797843167cbe93306fa0f1e
bigcode/the-stack
train
04c22cb753d73c29f2329d68
train
function
def test_model_checkpoint_args_validation(dirname): existing = os.path.join(dirname, "existing_dir") nonempty = os.path.join(dirname, "nonempty") os.makedirs(existing) os.makedirs(nonempty) with open(os.path.join(nonempty, f"{_PREFIX}_name_0.pt"), "w"): pass with pytest.raises(ValueEr...
def test_model_checkpoint_args_validation(dirname):
existing = os.path.join(dirname, "existing_dir") nonempty = os.path.join(dirname, "nonempty") os.makedirs(existing) os.makedirs(nonempty) with open(os.path.join(nonempty, f"{_PREFIX}_name_0.pt"), "w"): pass with pytest.raises(ValueError, match=r"with extension '.pt' are already presen...
f): assert f == "model_12.pt" to_save = {"model": DummyModel()} checkpointer = Checkpoint(to_save, save_handler=save_handler,) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=1, iteration=12) checkpointer(trainer) def test_model_checkpoint_args_validation(dirname):
77
77
258
8
69
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_model_checkpoint_args_validation
test_model_checkpoint_args_validation
492
517
492
492
6d46989fe7610b55fc2e0e3e745f3d3cf3abb50f
bigcode/the-stack
train
658754a3cb5f7d41eac121a4
train
function
def test_checkpoint_score_function_wrong_output(): model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, lambda x: x, score_function=lambda e: {"1": 1}, score_name="acc") trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) with pytest.rai...
def test_checkpoint_score_function_wrong_output():
model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, lambda x: x, score_function=lambda e: {"1": 1}, score_name="acc") trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) with pytest.raises(ValueError, match=r"Output of score_function sh...
) def __len__(self): return len(to_save) with pytest.raises(TypeError, match="If `include_self` is True, then `to_save` must be mutable"): Checkpoint(ImmutableMapping(), lambda x: x, include_self=True) def test_checkpoint_score_function_wrong_output():
64
64
102
8
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_score_function_wrong_output
test_checkpoint_score_function_wrong_output
80
88
80
80
d2698735289f35fe94b815a2821648c3ce8c2eac
bigcode/the-stack
train
37d245a4803b10cb1b59d7a2
train
function
def test_checkpoint_default(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(e...
def test_checkpoint_default():
def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) c...
Model() to_save = {"model": model} checkpointer = Checkpoint(to_save, lambda x: x, score_function=lambda e: {"1": 1}, score_name="acc") trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) with pytest.raises(ValueError, match=r"Output of score_function should be a number"...
95
95
319
5
90
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_default
test_checkpoint_default
91
124
91
91
5fafebf956f284636dee54c8e8c093df4a178df4
bigcode/the-stack
train
a7e04036b6b5ecd7bf2d1c2f
train
function
def test_greater_or_equal(): scores = iter([1, 2, 2, 2]) def score_function(_): return next(scores) class Saver: def __init__(self): self.counter = 0 def __call__(self, c, f, m): if self.counter == 0: assert f == "model_1.pt" els...
def test_greater_or_equal():
scores = iter([1, 2, 2, 2]) def score_function(_): return next(scores) class Saver: def __init__(self): self.counter = 0 def __call__(self, c, f, m): if self.counter == 0: assert f == "model_1.pt" else: assert f =...
2) expected += [f"{_PREFIX}_{name}_{i}.pt" for i in [1 * 2, 2 * 2]] assert sorted(os.listdir(dirname)) == sorted(expected) assert "PREFIX_model_4.pt" in handler.last_checkpoint def test_greater_or_equal():
64
64
184
7
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_greater_or_equal
test_greater_or_equal
1,550
1,580
1,550
1,550
8cd902b525bbe4bf67ab35ae0c4a25e26a081864
bigcode/the-stack
train
c3707e899b48dc5e70a7dbf3
train
function
def test_checkpoint_with_dp(): model = DummyModel() dp_model = nn.DataParallel(model) to_save = {"model": dp_model} save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=...
def test_checkpoint_with_dp():
model = DummyModel() dp_model = nn.DataParallel(model) to_save = {"model": dp_model} save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) checkpointe...
model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") def test_checkpoint_with_dp():
64
64
137
6
58
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_with_dp
test_checkpoint_with_dp
177
192
177
178
2a3a7cf4596cc6d198f299eee36b97e019fa8f70
bigcode/the-stack
train
709cb58ba669525bd0467a2a
train
function
def _test_checkpoint_with_ddp(device): torch.manual_seed(0) model = DummyModel().to(device) device_ids = ( None if "cpu" in device.type else [device,] ) ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=device_ids) to_save = {"model": ddp_model} save_handler = Magic...
def _test_checkpoint_with_ddp(device):
torch.manual_seed(0) model = DummyModel().to(device) device_ids = ( None if "cpu" in device.type else [device,] ) ddp_model = nn.parallel.DistributedDataParallel(model, device_ids=device_ids) to_save = {"model": ddp_model} save_handler = MagicMock(spec=BaseSaveHandler) checkpoi...
}{ext}") with open(previous_fname, "w") as f: f.write("test") with pytest.raises(ValueError, match=r"with extension '.pt' are already present"): DiskSaver(dirname, require_empty=True) _test(".pt") def _test_checkpoint_with_ddp(device):
64
64
181
9
55
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
_test_checkpoint_with_ddp
_test_checkpoint_with_ddp
1,148
1,167
1,148
1,148
7606a1655b467db2be93b2f07bb5d617c8401e31
bigcode/the-stack
train
5356f2c8a80a3b2fa2b9e9f9
train
function
def _setup_checkpoint(): save_handler = MagicMock(spec=BaseSaveHandler) model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state ...
def _setup_checkpoint():
save_handler = MagicMock(spec=BaseSaveHandler) model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteratio...
with_global_step should be True."): Checkpoint.setup_filename_pattern(False, False, False, False) with pytest.raises(ValueError, match=r"If with_score_name is True, with_score should be also True"): Checkpoint.setup_filename_pattern(True, False, True, True) def _setup_checkpoint():
64
64
135
5
59
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
_setup_checkpoint
_setup_checkpoint
1,428
1,445
1,428
1,428
19f85b3184c13f00be1e548bb3851ac90abad1ba
bigcode/the-stack
train
f27092b54532f1e0e85698e3
train
function
def test_removes_each_score_at_most_once(dirname): scores = [0, 1, 1, 2, 3] scores_iter = iter(scores) def score_function(_): return next(scores_iter) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function) engine = Engine(lambda e, b: None) e...
def test_removes_each_score_at_most_once(dirname):
scores = [0, 1, 1, 2, 3] scores_iter = iter(scores) def score_function(_): return next(scores_iter) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) mode...
1 h(engine, to_save) expected = [f"{_PREFIX}_model_val_loss={scores[e - 1]:.4}.pt" for e in [1, 3]] assert sorted(os.listdir(dirname)) == expected def test_removes_each_score_at_most_once(dirname):
64
64
128
12
51
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_removes_each_score_at_most_once
test_removes_each_score_at_most_once
725
740
725
725
6de4f2a1e2ad9da28cbce136bceee921a62e24f2
bigcode/the-stack
train
bf27e58b3c79af19cb7f69cd
train
function
@pytest.mark.skipif( parse_version(torch.__version__) < parse_version("1.4.0"), reason="Zipfile serialization was introduced in 1.4.0" ) def test_disk_saver_zipfile_serialization_keyword(dirname): model = DummyModel() to_save = {"model": model} saver = DiskSaver(dirname, create_dir=False, _use_new_zipf...
@pytest.mark.skipif( parse_version(torch.__version__) < parse_version("1.4.0"), reason="Zipfile serialization was introduced in 1.4.0" ) def test_disk_saver_zipfile_serialization_keyword(dirname):
model = DummyModel() to_save = {"model": model} saver = DiskSaver(dirname, create_dir=False, _use_new_zipfile_serialization=False) fname = "test.pt" saver(to_save, fname) fp = os.path.join(saver.dirname, fname) assert os.path.exists(fp) saver.remove(fname)
, _to_save=to_save_non_serializable, expected=False) @pytest.mark.skipif( parse_version(torch.__version__) < parse_version("1.4.0"), reason="Zipfile serialization was introduced in 1.4.0" ) def test_disk_saver_zipfile_serialization_keyword(dirname):
64
64
123
50
14
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_disk_saver_zipfile_serialization_keyword
test_disk_saver_zipfile_serialization_keyword
614
626
614
617
63b34c530c89356ca53ce96a041ea83636b7347d
bigcode/the-stack
train
e1f498a6f9a2a4249b8f1e7b
train
function
def test_checkpoint_with_global_step_transform(): def _test(filename_prefix, to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, filename_prefix=filename_prefix, global_ste...
def test_checkpoint_with_global_step_transform():
def _test(filename_prefix, to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, filename_prefix=filename_prefix, global_step_transform=lambda e, _: e.state.epoch, ) ...
_model} save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) checkpointer(trainer) assert save_handler.call_count == 1 metadata = {"basename": "model", "...
116
116
387
8
108
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_with_global_step_transform
test_checkpoint_with_global_step_transform
195
236
195
195
9306d90b962e37a794e0d70414d1c85c07a169a2
bigcode/the-stack
train
87fd83161d0f29262ebc59ef
train
function
def test_checkpoint_include_self_state_dict(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, include_self=True) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: No...
def test_checkpoint_include_self_state_dict():
def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, include_self=True) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iter...
.call_count == 1 save_handler.remove.assert_called_with(f"{name}_0.pt") assert checkpointer.last_checkpoint == f"{name}_1234.pt" model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parame...
130
130
435
8
122
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_include_self_state_dict
test_checkpoint_include_self_state_dict
127
174
127
127
b404498d39b78ca15251147e88640480f3e322d0
bigcode/the-stack
train
75cb500131df2f6a7e056aec
train
function
def test_save_model_optimizer_lr_scheduler_with_validation(dirname): _test_save_model_optimizer_lr_scheduler_with_validation("cpu", dirname)
def test_save_model_optimizer_lr_scheduler_with_validation(dirname):
_test_save_model_optimizer_lr_scheduler_with_validation("cpu", dirname)
was restored correctly, it should continue to respect n_saved # and delete old checkpoints, and have the correct last_checkpoint. assert os.listdir(dirname) == ["checkpoint_4.pt"] assert checkpointer2.last_checkpoint == "checkpoint_4.pt" def test_save_model_optimizer_lr_scheduler_with_validation(dirname):
64
64
26
11
53
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_save_model_optimizer_lr_scheduler_with_validation
test_save_model_optimizer_lr_scheduler_with_validation
1,025
1,026
1,025
1,025
790781837984977404f683a7d5949045677e4540
bigcode/the-stack
train
4fc45697795dcd77c8c4c928
train
function
def test_model_checkpoint_invalid_save_handler(dirname): h = ModelCheckpoint(dirname, _PREFIX) to_save = {"model": DummyModel()} # Redefine save_handler h.save_handler = lambda x, y: None h(Engine(lambda x, y: None), to_save) with pytest.raises( RuntimeError, match=rf"Unable to save che...
def test_model_checkpoint_invalid_save_handler(dirname):
h = ModelCheckpoint(dirname, _PREFIX) to_save = {"model": DummyModel()} # Redefine save_handler h.save_handler = lambda x, y: None h(Engine(lambda x, y: None), to_save) with pytest.raises( RuntimeError, match=rf"Unable to save checkpoint, save_handler should be DiskSaver, got {type(h.sa...
os.path.exists(fname) assert os.path.exists(previous_fname) loaded_objects = torch.load(fname) assert loaded_objects == model.state_dict() os.remove(fname) _test(".txt", require_empty=True) _test(".pt", require_empty=False) def test_model_checkpoint_invalid_save_handler(dirname...
64
64
103
9
55
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_model_checkpoint_invalid_save_handler
test_model_checkpoint_invalid_save_handler
565
575
565
565
57d7b29549166aab509b6d51574f2cb26c190ffc
bigcode/the-stack
train
e4d410079ae0deaf27c232ab
train
function
def test_checkpoint_with_int_score(): def _test(to_save, obj, name, score_name=None): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, score_name=score_name, score_function=lambda e: e.state.epoch ) if score_n...
def test_checkpoint_with_int_score():
def _test(to_save, obj, name, score_name=None): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_handler=save_handler, score_name=score_name, score_function=lambda e: e.state.epoch ) if score_name is None: score_name = ...
_with(f"{name}_loss=-0.7700.pt") assert checkpointer.last_checkpoint == f"{name}_loss=-0.7600.pt" model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model":...
126
126
422
7
119
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_with_int_score
test_checkpoint_with_int_score
315
357
315
315
888c061794d74da3aea7e724280618f9247f602b
bigcode/the-stack
train
5649ffe1752e244c833bacc1
train
function
def _test_save_model_optimizer_lr_scheduler_with_validation(device, dirname, on_zero_rank=False): torch.manual_seed(23) def _build_objects(acc_list): model = DummyModel().to(device) optim = torch.optim.SGD(model.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.ExponentialL...
def _test_save_model_optimizer_lr_scheduler_with_validation(device, dirname, on_zero_rank=False):
torch.manual_seed(23) def _build_objects(acc_list): model = DummyModel().to(device) optim = torch.optim.SGD(model.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=0.5) def update_fn(engine, batch): x = torch.rand((4, 1)).to(d...
# Specifically move device to CPU first model_state_dict = model.cpu().state_dict() for key in model_state_dict.keys(): assert key in loaded_model_state_dict model_value = model_state_dict[key] loaded_model_value = loaded_model_state_dict[key] assert model_value.cpu().numpy()...
256
256
1,065
19
237
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
_test_save_model_optimizer_lr_scheduler_with_validation
_test_save_model_optimizer_lr_scheduler_with_validation
897
1,022
897
897
bd934f0574f9fb4982bd845281d96588530e1657
bigcode/the-stack
train
0e2697f9929f2beb8b139e42
train
function
def test_get_default_score_fn(): with pytest.raises(ValueError, match=r"Argument score_sign should be 1 or -1"): Checkpoint.get_default_score_fn("acc", 2.0) engine = Engine(lambda e, b: None) engine.state.metrics["acc"] = 0.9 engine.state.metrics["loss"] = 0.123 score_fn = Checkpoint.get_...
def test_get_default_score_fn():
with pytest.raises(ValueError, match=r"Argument score_sign should be 1 or -1"): Checkpoint.get_default_score_fn("acc", 2.0) engine = Engine(lambda e, b: None) engine.state.metrics["acc"] = 0.9 engine.state.metrics["loss"] = 0.123 score_fn = Checkpoint.get_default_score_fn("acc") score ...
=handler, score_function=score_function, n_saved=2, greater_or_equal=True, ) trainer = Engine(lambda e, b: None) for _ in range(4): checkpointer(trainer) assert handler.counter == 4 def test_get_default_score_fn():
64
64
141
7
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_get_default_score_fn
test_get_default_score_fn
1,583
1,598
1,583
1,584
1ecbaaab78b820484c45c7b2ba6ec92d7f4493b8
bigcode/the-stack
train
66c89992836e576b93eb053f
train
function
@pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") def test_distrib_gloo_cpu_or_gpu(distributed_context_single_node_gloo, get_rank_zero_dirname): device = idist.device() dirname = get_rank_zero_dirname() _test_save_model_optimizer_lr_sch...
@pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") def test_distrib_gloo_cpu_or_gpu(distributed_context_single_node_gloo, get_rank_zero_dirname):
device = idist.device() dirname = get_rank_zero_dirname() _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "2"), on_zero_rank=True) _test_checkpoint_with_ddp(device) _...
": opt.state_dict()} Checkpoint.load_objects(to_load, checkpoint) @pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") def test_distrib_gloo_cpu_or_gpu(distributed_context_single_node_gloo, get_rank_zero_dirname):
64
64
131
49
15
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_distrib_gloo_cpu_or_gpu
test_distrib_gloo_cpu_or_gpu
1,189
1,198
1,189
1,192
2afbb59949c9b27e3141c0707262c7115d8194e4
bigcode/the-stack
train
e8583be424849a6fdcf86dd3
train
function
def _test_tpu_saves_to_cpu(device, dirname): torch.manual_seed(0) h = ModelCheckpoint(dirname, _PREFIX) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=1) model = DummyModel().to(device) to_save = {"model": model} h(engine, to_save) idist.barrier() fna...
def _test_tpu_saves_to_cpu(device, dirname):
torch.manual_seed(0) h = ModelCheckpoint(dirname, _PREFIX) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=1) model = DummyModel().to(device) to_save = {"model": model} h(engine, to_save) idist.barrier() fname = h.last_checkpoint assert isinstance(...
"1")) _test_save_model_optimizer_lr_scheduler_with_state_dict("cpu", os.path.join(dirname, "2"), on_zero_rank=True) _test_checkpoint_with_ddp(device=device) _test_checkpoint_load_objects_ddp(device=device) def _test_tpu_saves_to_cpu(device, dirname):
64
64
138
13
51
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
_test_tpu_saves_to_cpu
_test_tpu_saves_to_cpu
1,214
1,233
1,214
1,214
611bf70bf57b6ac9fe368496cf731a71bcbdc1cb
bigcode/the-stack
train
fd9326cbef1dcf58f212a30d
train
function
def test_checkpoint_load_state_dict(): true_checkpointer = _setup_checkpoint() save_handler = MagicMock(spec=BaseSaveHandler) model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) sd = {"saved": [(0, "model_0.pt"), (10, "mod...
def test_checkpoint_load_state_dict():
true_checkpointer = _setup_checkpoint() save_handler = MagicMock(spec=BaseSaveHandler) model = DummyModel() to_save = {"model": model} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) sd = {"saved": [(0, "model_0.pt"), (10, "model_10.pt"), (20, "model_20.pt")]} c...
list) and len(sd["saved"]) == len(checkpointer._saved) for saved_item, true_item in zip(sd["saved"], checkpointer._saved): assert saved_item[0] == true_item.priority assert saved_item[1] == true_item.filename def test_checkpoint_load_state_dict():
64
64
117
7
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_load_state_dict
test_checkpoint_load_state_dict
1,459
1,469
1,459
1,459
ba0680f6526079aadf817a6337f0ad08fb2da3d8
bigcode/the-stack
train
33452a1c125257fe60e4feb1
train
function
def test_checkpoint_load_objects(): with pytest.raises(TypeError, match=r"Argument checkpoint should be a dictionary"): Checkpoint.load_objects({}, []) with pytest.raises(TypeError, match=r"should have `load_state_dict` method"): Checkpoint.load_objects({"a": None}, {"a": None}) model = D...
def test_checkpoint_load_objects():
with pytest.raises(TypeError, match=r"Argument checkpoint should be a dictionary"): Checkpoint.load_objects({}, []) with pytest.raises(TypeError, match=r"should have `load_state_dict` method"): Checkpoint.load_objects({"a": None}, {"a": None}) model = DummyModel() to_load = {"model": m...
the correct last_checkpoint. assert os.listdir(dirname) == ["checkpoint_4.pt"] assert checkpointer2.last_checkpoint == "checkpoint_4.pt" def test_save_model_optimizer_lr_scheduler_with_validation(dirname): _test_save_model_optimizer_lr_scheduler_with_validation("cpu", dirname) def test_checkpoint_load_ob...
64
64
174
6
58
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_load_objects
test_checkpoint_load_objects
1,029
1,049
1,029
1,030
d82be8d3f3ce2144b7deaf226b1413b0da86dc3d
bigcode/the-stack
train
f72e8e2b921839e8072c8596
train
function
def test_checkpoint_filename_pattern(): def _test( to_save, filename_prefix="", score_function=None, score_name=None, global_step_transform=None, filename_pattern=None, ): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( ...
def test_checkpoint_filename_pattern():
def _test( to_save, filename_prefix="", score_function=None, score_name=None, global_step_transform=None, filename_pattern=None, ): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint( to_save, save_han...
assert "xla" in idist.device().type _test_tpu_saves_to_cpu(idist.device(), os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(idist.device(), os.path.join(dirname, "2")) def _test_tpu_saves_to_cpu_nprocs(index, dirname): device = idist.device() _test_tpu_saves_to_c...
256
256
1,360
6
250
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_filename_pattern
test_checkpoint_filename_pattern
1,264
1,408
1,264
1,264
4e0fd89dfcaa67f7cff921199a996a99f66d7f47
bigcode/the-stack
train
15b3c26e2b410ae8ce68471f
train
function
def test_checkpoint_last_checkpoint(): save_handler = MagicMock(spec=BaseSaveHandler) to_save = {"model": DummyModel()} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) trainer = Engine(lambda e, b: None) for i in range(10): trainer.state = State(epoch=1, iterat...
def test_checkpoint_last_checkpoint():
save_handler = MagicMock(spec=BaseSaveHandler) to_save = {"model": DummyModel()} checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=None) trainer = Engine(lambda e, b: None) for i in range(10): trainer.state = State(epoch=1, iteration=i) checkpointer(trainer) ...
_val_acc=0.7700.pt") assert checkpointer.last_checkpoint == f"{name}_12_val_acc=0.7800.pt" model = DummyModel() to_save = {"model": model} _test(to_save, model.state_dict(), "model") def test_checkpoint_last_checkpoint():
64
64
108
6
58
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_last_checkpoint
test_checkpoint_last_checkpoint
438
451
438
438
66a3f3a5531ad7a204cb4005adc205bf5dbb234e
bigcode/the-stack
train
b4c79bbc6821620f07920cfc
train
function
def _test_save_model_optimizer_lr_scheduler_with_state_dict(device, dirname, on_zero_rank=False): torch.manual_seed(23) model = DummyModel().to(device) optim = torch.optim.SGD(model.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=0.5) def update_fn(engine...
def _test_save_model_optimizer_lr_scheduler_with_state_dict(device, dirname, on_zero_rank=False):
torch.manual_seed(23) model = DummyModel().to(device) optim = torch.optim.SGD(model.parameters(), lr=0.1) lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim, gamma=0.5) def update_fn(engine, batch): x = torch.rand((4, 1)).to(device) optim.zero_grad() y = model(x) ...
_dict = model.state_dict() loaded_model_state_dict = load_model for key in model_state_dict.keys(): assert key in loaded_model_state_dict model_value = model_state_dict[key] loaded_model_value = loaded_model_state_dict[key] assert model_value.numpy() == loaded_model_value.numpy...
209
209
698
20
189
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
_test_save_model_optimizer_lr_scheduler_with_state_dict
_test_save_model_optimizer_lr_scheduler_with_state_dict
811
890
811
812
19305003e5cbdd5d86124ac319544eaec1fe2a70
bigcode/the-stack
train
ffd1507db42700852512b220
train
function
def test_checkpoint_reset_with_engine(dirname): name = "model" engine = Engine(lambda e, b: None) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) model = DummyModel() to_save = {"model": model} engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to_save) engin...
def test_checkpoint_reset_with_engine(dirname):
name = "model" engine = Engine(lambda e, b: None) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) model = DummyModel() to_save = {"model": model} engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to_save) engine.run([0, 1,], max_epochs=10) expected = so...
ainer) assert save_handler.call_count == 3 assert checkpointer.last_checkpoint == "model_124.pt" assert len(checkpointer._saved) == 1 assert sorted([item.filename for item in checkpointer._saved]) == sorted(["model_124.pt",]) def test_checkpoint_reset_with_engine(dirname):
68
68
228
8
60
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_reset_with_engine
test_checkpoint_reset_with_engine
1,527
1,547
1,527
1,527
c6bbf6b65285f373c87ac8b0226675977f33dadb
bigcode/the-stack
train
e0fd99c93ae0e59c8cc75920
train
function
def test_checkpoint_with_score_function_and_trainer_epoch(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) trainer = Engine(lambda e, b: None) evaluator = Engine(lambda e, b: None) trainer.state = State(epoch=11, iteration=1) checkpointer = C...
def test_checkpoint_with_score_function_and_trainer_epoch():
def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) trainer = Engine(lambda e, b: None) evaluator = Engine(lambda e, b: None) trainer.state = State(epoch=11, iteration=1) checkpointer = Checkpoint( to_save, save_handler=save...
.state_dict(), "model", "epoch") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(to_save, {"model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint") _test(to_save, {"model": model.state_dict...
105
105
351
11
94
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_with_score_function_and_trainer_epoch
test_checkpoint_with_score_function_and_trainer_epoch
360
395
360
360
30c47a057ca127a3f636e5b2c65eb04d44d088d3
bigcode/the-stack
train
6c8864409a3409e007943d1e
train
function
def test_valid_state_dict_save(dirname): model = DummyModel() h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) to_save = {"name": 42} with pytest.raises(TypeError, match=r"should have `state_dict` m...
def test_valid_state_dict_save(dirname):
model = DummyModel() h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) to_save = {"name": 42} with pytest.raises(TypeError, match=r"should have `state_dict` method"): h(engine, to_save) t...
_state_dict = load_model for key in model_state_dict.keys(): assert key in loaded_model_state_dict model_value = model_state_dict[key] loaded_model_value = loaded_model_state_dict[key] assert model_value.numpy() == loaded_model_value.numpy() def test_valid_state_dict_save(dirname):...
64
64
124
8
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_valid_state_dict_save
test_valid_state_dict_save
794
808
794
794
c66b0391f1edf5b0d9eb03441f1d9cfc65305dd7
bigcode/the-stack
train
d6096f9973975ee6b108c2ca
train
function
@pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") @pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU") def test_distrib_nccl_gpu(distributed_context_single_node_nccl, get_rank_zero_dirname): device = idist.device() di...
@pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") @pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU") def test_distrib_nccl_gpu(distributed_context_single_node_nccl, get_rank_zero_dirname):
device = idist.device() dirname = get_rank_zero_dirname() _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict("cpu", os.path.join(dirname, "2"), on_zero_rank=True) _test_checkpoint_with_ddp(device=device)...
@pytest.mark.distributed @pytest.mark.skipif(not idist.has_native_dist_support, reason="Skip if no native dist support") @pytest.mark.skipif(torch.cuda.device_count() < 1, reason="Skip if no GPU") def test_distrib_nccl_gpu(distributed_context_single_node_nccl, get_rank_zero_dirname):
67
64
152
67
0
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_distrib_nccl_gpu
test_distrib_nccl_gpu
1,201
1,211
1,201
1,205
019b13325dffcb0b0d95d2d3fff4f64a96971ae6
bigcode/the-stack
train
17a4786d6b8c7be8c6fbe5a3
train
function
def test_last_k(dirname): h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} h(engine, to_save) for i in range(1, 9): engine.state.iteratio...
def test_last_k(dirname):
h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} h(engine, to_save) for i in range(1, 9): engine.state.iteration = i h(engine, to_...
() to_save = {"model": model} saver = DiskSaver(dirname, create_dir=False, unknown_keyword="") fname = "test.pt" with pytest.raises(TypeError, match=r"got an unexpected keyword argument 'unknown_keyword'"): saver(to_save, fname) def test_last_k(dirname):
64
64
143
6
58
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_last_k
test_last_k
639
655
639
640
ad085838c07a25a6be97ce915525de6b96a6030b
bigcode/the-stack
train
c8e24b4ef0faa5e333ef1735
train
function
def test_checkpoint_reset(): model = DummyModel() to_save = {"model": model} save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=2) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.sta...
def test_checkpoint_reset():
model = DummyModel() to_save = {"model": model} save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=2) assert checkpointer.last_checkpoint is None trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration...
) checkpointer(trainer) assert save_handler.call_count == i + 1 metadata = {"basename": "model", "score_name": None, "priority": i} save_handler.assert_called_with(model.state_dict(), "model.pt", metadata) _test(None) _test(1) _test(3) def test_checkpoint_res...
77
77
259
5
72
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_reset
test_checkpoint_reset
1,494
1,524
1,494
1,494
852a9ca1045c4fd8439f4585e987a8fcb6efb783
bigcode/the-stack
train
5aab775ab2c1978142922b60
train
function
def test_checkpoint_wrong_input(): with pytest.raises(TypeError, match=r"Argument `to_save` should be a dictionary"): Checkpoint(12, lambda x: x, "prefix") with pytest.raises(TypeError, match=r"Argument `to_save` should be a dictionary"): Checkpoint([12], lambda x: x, "prefix") model = Du...
def test_checkpoint_wrong_input():
with pytest.raises(TypeError, match=r"Argument `to_save` should be a dictionary"): Checkpoint(12, lambda x: x, "prefix") with pytest.raises(TypeError, match=r"Argument `to_save` should be a dictionary"): Checkpoint([12], lambda x: x, "prefix") model = DummyModel() to_save = {"model": m...
(1, 1) def forward(self, x): return self.net(x) class DummyPretrainedModel(nn.Module): def __init__(self): super(DummyPretrainedModel, self).__init__() self.features = nn.Linear(4, 2, bias=False) self.fc = nn.Linear(2, 1) def forward(self, x): x = self.features(x)...
104
104
349
6
97
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_wrong_input
test_checkpoint_wrong_input
41
77
41
42
de40adb40b884bba7118d51c0689fd4e93b4e756
bigcode/the-stack
train
0be4a889918c9598e406434c
train
function
def test_checkpoint_with_score_name_and_function_and_trainer_epoch(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) trainer = Engine(lambda e, b: None) evaluator = Engine(lambda e, b: None) trainer.state = State(epoch=11, iteration=1) checkpo...
def test_checkpoint_with_score_name_and_function_and_trainer_epoch():
def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) trainer = Engine(lambda e, b: None) evaluator = Engine(lambda e, b: None) trainer.state = State(epoch=11, iteration=1) checkpointer = Checkpoint( to_save, save_handler=save...
save_handler.assert_called_with(obj, f"{name}_12_0.7800.pt", metadata) assert save_handler.remove.call_count == 1 save_handler.remove.assert_called_with(f"{name}_11_0.7700.pt") assert checkpointer.last_checkpoint == f"{name}_12_0.7800.pt" model = DummyModel() to_save = {"model": model}...
111
111
370
13
98
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_with_score_name_and_function_and_trainer_epoch
test_checkpoint_with_score_name_and_function_and_trainer_epoch
398
435
398
398
897db6e42bbbbb507e03b72aec6f8e8c46cc1052
bigcode/the-stack
train
698ea25ff7b8842bcb56525b
train
function
@pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla(dirname): assert "xla" in idist.device().type _test_tpu_saves_to_cpu(idist.device()...
@pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla(dirname):
assert "xla" in idist.device().type _test_tpu_saves_to_cpu(idist.device(), os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(idist.device(), os.path.join(dirname, "2"))
() @pytest.mark.tpu @pytest.mark.skipif("NUM_TPU_WORKERS" in os.environ, reason="Skip if NUM_TPU_WORKERS is in env vars") @pytest.mark.skipif(not idist.has_xla_support, reason="Not on TPU device") def test_distrib_single_device_xla(dirname):
64
64
120
63
1
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_distrib_single_device_xla
test_distrib_single_device_xla
1,236
1,242
1,236
1,239
514e14a7c2be1c53e52af3dd205e77c5c7d92479
bigcode/the-stack
train
6f0290afd1e583c68e97f1b7
train
function
def test_with_engine(dirname): def update_fn(_1, _2): pass name = "model" engine = Engine(update_fn) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) model = DummyModel() to_save = {"model": model} engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to...
def test_with_engine(dirname):
def update_fn(_1, _2): pass name = "model" engine = Engine(update_fn) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2) model = DummyModel() to_save = {"model": model} engine.add_event_handler(Events.EPOCH_COMPLETED, handler, to_save) engine.run([0, 1,], ...
for _ in range(len(scores)): h(engine, to_save) # If a score was removed multiple times, the code above would have raise a # FileNotFoundError. So this just tests the absence of such a failure # without futher assertions. def test_with_engine(dirname):
64
64
139
6
58
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_with_engine
test_with_engine
747
762
747
747
ff503fefaf8458c526b2f35919e6be5ef472d7f0
bigcode/the-stack
train
1276e25456edb7a69754d550
train
function
def test_checkpoint_load_objects_from_saved_file(dirname): def _get_single_obj_to_save(): model = DummyModel() to_save = {"model": model} return to_save def _get_multiple_objs_to_save(): model = DummyModel() optim = torch.optim.SGD(model.parameters(), lr=0.001) l...
def test_checkpoint_load_objects_from_saved_file(dirname):
def _get_single_obj_to_save(): model = DummyModel() to_save = {"model": model} return to_save def _get_multiple_objs_to_save(): model = DummyModel() optim = torch.optim.SGD(model.parameters(), lr=0.001) lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optim,...
` method"): Checkpoint.load_objects({"a": None}, {"a": None}) model = DummyModel() to_load = {"model": model, "another_model": model} with pytest.raises(ValueError, match=r"from `to_load` is not found in the checkpoint"): Checkpoint.load_objects(to_load, {}) model = DummyModel() t...
138
138
461
10
128
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_load_objects_from_saved_file
test_checkpoint_load_objects_from_saved_file
1,052
1,102
1,052
1,052
a1bd2292b553e6feb7c5dd30f28ca38cc59a84a0
bigcode/the-stack
train
1fb15b9097f6b30fb4c4ac57
train
function
def test_checkpoint_fixed_filename(): model = DummyModel() to_save = {"model": model} def _test(n_saved): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=n_saved, filename_pattern="{name}.{ext}") trainer = Engine(...
def test_checkpoint_fixed_filename():
model = DummyModel() to_save = {"model": model} def _test(n_saved): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, n_saved=n_saved, filename_pattern="{name}.{ext}") trainer = Engine(lambda e, b: None) for i in r...
_saved=None) sd = {"saved": [(0, "model_0.pt"), (10, "model_10.pt"), (20, "model_20.pt")]} checkpointer.load_state_dict(sd) assert checkpointer._saved == true_checkpointer._saved def test_checkpoint_fixed_filename():
64
64
168
6
57
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_fixed_filename
test_checkpoint_fixed_filename
1,472
1,491
1,472
1,472
020fa5fecc1c6c76fe7d3d49240488b87d921f50
bigcode/the-stack
train
f8d1cccdafff1c29e1327fa1
train
function
def test_load_checkpoint_with_different_num_classes(dirname): model = DummyPretrainedModel() to_save_single_object = {"model": model} trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) handler...
def test_load_checkpoint_with_different_num_classes(dirname):
model = DummyPretrainedModel() to_save_single_object = {"model": model} trainer = Engine(lambda e, b: None) trainer.state = State(epoch=0, iteration=0) handler = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=1) handler(trainer, to_save_single_object) fname = handler.last_che...
fname = handler.last_checkpoint assert isinstance(fname, str) assert os.path.join(dirname, _PREFIX) in fname assert os.path.exists(fname) loaded_objects = torch.load(fname) Checkpoint.load_objects(to_save, loaded_objects) def test_load_checkpoint_with_different_num_classes(dirname):
64
64
205
11
53
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_load_checkpoint_with_different_num_classes
test_load_checkpoint_with_different_num_classes
1,105
1,129
1,105
1,105
6bb16479a27d6c0660f0ec5332b791b773d02ba3
bigcode/the-stack
train
fedc6ed1d0c96189fa3c26c2
train
function
def test_best_k(dirname): scores = iter([1.2, -2.0, 3.1, -4.0]) def score_function(_): return next(scores) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) m...
def test_best_k(dirname):
scores = iter([1.2, -2.0, 3.1, -4.0]) def score_function(_): return next(scores) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to...
.listdir(dirname)) assert len(saved_files) == num_iters, f"{saved_files}" expected = sorted([f"{_PREFIX}_model_{i}.pt" for i in range(num_iters)]) assert saved_files == expected, f"{saved_files} vs {expected}" def test_best_k(dirname):
63
64
161
6
57
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_best_k
test_best_k
679
697
679
679
961eff875c950a2b0e856dfe2df1eac6169c5d61
bigcode/the-stack
train
b66ac121855265e4dd94b1f9
train
class
class DummyModel(nn.Module): def __init__(self): super(DummyModel, self).__init__() self.net = nn.Linear(1, 1) def forward(self, x): return self.net(x)
class DummyModel(nn.Module):
def __init__(self): super(DummyModel, self).__init__() self.net = nn.Linear(1, 1) def forward(self, x): return self.net(x)
import parse_version import ignite.distributed as idist from ignite.engine import Engine, Events, State from ignite.handlers import Checkpoint, DiskSaver, EarlyStopping, ModelCheckpoint, global_step_from_engine from ignite.handlers.checkpoint import BaseSaveHandler _PREFIX = "PREFIX" class DummyModel(nn.Module):
64
64
48
6
58
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
DummyModel
DummyModel
20
26
20
20
2bc0c2c491790a00dbff03adb278102141cb991b
bigcode/the-stack
train
215b51408da411bcac718105
train
function
def _test_tpu_saves_to_cpu_nprocs(index, dirname): device = idist.device() _test_tpu_saves_to_cpu(device, os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "2")) import time # hack to have all proc properly sync: time.sleep(1)
def _test_tpu_saves_to_cpu_nprocs(index, dirname):
device = idist.device() _test_tpu_saves_to_cpu(device, os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(device, os.path.join(dirname, "2")) import time # hack to have all proc properly sync: time.sleep(1)
().type _test_tpu_saves_to_cpu(idist.device(), os.path.join(dirname, "1")) _test_save_model_optimizer_lr_scheduler_with_state_dict(idist.device(), os.path.join(dirname, "2")) def _test_tpu_saves_to_cpu_nprocs(index, dirname):
63
64
83
16
47
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
_test_tpu_saves_to_cpu_nprocs
_test_tpu_saves_to_cpu_nprocs
1,245
1,253
1,245
1,245
d6765aac6a7e43006715dffc3f9fb0898587bd21
bigcode/the-stack
train
2fdd39f90d014e655b5715fa
train
class
class DummyPretrainedModel(nn.Module): def __init__(self): super(DummyPretrainedModel, self).__init__() self.features = nn.Linear(4, 2, bias=False) self.fc = nn.Linear(2, 1) def forward(self, x): x = self.features(x) x = self.fc(x) return x
class DummyPretrainedModel(nn.Module):
def __init__(self): super(DummyPretrainedModel, self).__init__() self.features = nn.Linear(4, 2, bias=False) self.fc = nn.Linear(2, 1) def forward(self, x): x = self.features(x) x = self.fc(x) return x
SaveHandler _PREFIX = "PREFIX" class DummyModel(nn.Module): def __init__(self): super(DummyModel, self).__init__() self.net = nn.Linear(1, 1) def forward(self, x): return self.net(x) class DummyPretrainedModel(nn.Module):
64
64
79
8
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
DummyPretrainedModel
DummyPretrainedModel
29
38
29
29
fd8f17e9e0fc55962b6353f1571b571fb983dcde
bigcode/the-stack
train
7a5f2b7123aee9bb49b5f0a5
train
function
def test_model_checkpoint_simple_recovery(dirname): h = ModelCheckpoint(dirname, _PREFIX, create_dir=False) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=1) model = DummyModel() to_save = {"model": model} h(engine, to_save) fname = h.last_checkpoint assert ...
def test_model_checkpoint_simple_recovery(dirname):
h = ModelCheckpoint(dirname, _PREFIX, create_dir=False) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=1) model = DummyModel() to_save = {"model": model} h(engine, to_save) fname = h.last_checkpoint assert isinstance(fname, str) assert os.path.join(dirna...
create_dir=False, global_step_transform=1234) h = ModelCheckpoint(dirname, _PREFIX, create_dir=False) assert h.last_checkpoint is None with pytest.raises(RuntimeError, match=r"No objects to checkpoint found."): h(None, []) def test_model_checkpoint_simple_recovery(dirname):
63
64
120
9
54
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_model_checkpoint_simple_recovery
test_model_checkpoint_simple_recovery
520
534
520
520
cd17d30f34013370d83fceeec265a86bb862c638
bigcode/the-stack
train
5f6ea2144ea8927764b42eca
train
function
def test_checkpoint_with_score_function(): def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, score_function=lambda e: e.state.score) trainer = Engine(lambda e, b: None) trainer.state = State(e...
def test_checkpoint_with_score_function():
def _test(to_save, obj, name): save_handler = MagicMock(spec=BaseSaveHandler) checkpointer = Checkpoint(to_save, save_handler=save_handler, score_function=lambda e: e.state.score) trainer = Engine(lambda e, b: None) trainer.state = State(epoch=1, iteration=1, score=0.77) c...
", "dummytask"]: model = DummyModel() to_save = {"model": model} _test(prefix, to_save, model.state_dict(), "model") model = DummyModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.1) to_save = {"model": model, "optimizer": optimizer} _test(prefix, to_s...
105
105
350
7
98
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_with_score_function
test_checkpoint_with_score_function
239
273
239
239
a8bf04809808f935e929e04c1b7d12e533905ec9
bigcode/the-stack
train
5dc7a0e077ffff7616fc7ec2
train
function
def test_disabled_n_saved(dirname): h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=None) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} num_iters = 100 for i in range(num_iters): engine...
def test_disabled_n_saved(dirname):
h = ModelCheckpoint(dirname, _PREFIX, create_dir=False, n_saved=None) engine = Engine(lambda e, b: None) engine.state = State(epoch=0, iteration=0) model = DummyModel() to_save = {"model": model} num_iters = 100 for i in range(num_iters): engine.state.iteration = i h(engine...
= i h(engine, to_save) expected = [f"{_PREFIX}_model_{i}.pt" for i in [7, 8]] assert sorted(os.listdir(dirname)) == expected, f"{sorted(os.listdir(dirname))} vs {expected}" def test_disabled_n_saved(dirname):
63
64
157
7
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_disabled_n_saved
test_disabled_n_saved
658
676
658
659
74241abc22da8bca3961740419889115c6385ebe
bigcode/the-stack
train
1eecb0dbf11feda093468ee2
train
function
def test_best_k_with_suffix(dirname): scores = [0.3456789, 0.1234, 0.4567, 0.134567] scores_iter = iter(scores) def score_function(engine): return next(scores_iter) h = ModelCheckpoint( dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function, score_name="val_loss" ...
def test_best_k_with_suffix(dirname):
scores = [0.3456789, 0.1234, 0.4567, 0.134567] scores_iter = iter(scores) def score_function(engine): return next(scores_iter) h = ModelCheckpoint( dirname, _PREFIX, create_dir=False, n_saved=2, score_function=score_function, score_name="val_loss" ) engine = Engine(lambda e, b...
for _ in range(4): h(engine, to_save) expected = [f"{_PREFIX}_model_{i:.4f}.pt" for i in [1.2, 3.1]] assert sorted(os.listdir(dirname)) == expected def test_best_k_with_suffix(dirname):
64
64
196
8
55
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_best_k_with_suffix
test_best_k_with_suffix
700
722
700
700
3fc2fcff65f9810357f1465f849095616409d7d3
bigcode/the-stack
train
b985dee77eddf7c7f2c805f9
train
function
def test_checkpoint_last_checkpoint_on_score(): save_handler = MagicMock(spec=BaseSaveHandler) to_save = {"model": DummyModel()} checkpointer = Checkpoint( to_save, save_handler=save_handler, n_saved=None, score_name="val_acc", score_function=lambda e: e.state.metric...
def test_checkpoint_last_checkpoint_on_score():
save_handler = MagicMock(spec=BaseSaveHandler) to_save = {"model": DummyModel()} checkpointer = Checkpoint( to_save, save_handler=save_handler, n_saved=None, score_name="val_acc", score_function=lambda e: e.state.metrics["val_acc"], ) trainer = Engine(lambda...
(lambda e, b: None) for i in range(10): trainer.state = State(epoch=1, iteration=i) checkpointer(trainer) assert save_handler.call_count == 10 assert checkpointer.last_checkpoint == "model_9.pt" def test_checkpoint_last_checkpoint_on_score():
64
64
169
8
56
OBITORASU/ignite
tests/ignite/handlers/test_checkpoint.py
Python
test_checkpoint_last_checkpoint_on_score
test_checkpoint_last_checkpoint_on_score
454
475
454
454
20102bc38480d827b8e1a04ba11b95839cc1fc87
bigcode/the-stack
train