id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
17,800
swisscom/cleanerversion
versions/admin.py
VersionedAdmin.get_object
def get_object(self, request, object_id, from_field=None): """ our implementation of get_object allows for cloning when updating an object, not cloning when the button 'save but not clone' is pushed and at no other time will clone be called """ # from_field breaks in 1.7.8 obj = super(VersionedAdmin, self).get_object(request, object_id) # Only clone if update view as get_object() is also called for change, # delete, and history views if request.method == 'POST' and \ obj and \ obj.is_latest and \ 'will_not_clone' not in request.path and \ 'delete' not in request.path and \ 'restore' not in request.path: obj = obj.clone() return obj
python
def get_object(self, request, object_id, from_field=None): """ our implementation of get_object allows for cloning when updating an object, not cloning when the button 'save but not clone' is pushed and at no other time will clone be called """ # from_field breaks in 1.7.8 obj = super(VersionedAdmin, self).get_object(request, object_id) # Only clone if update view as get_object() is also called for change, # delete, and history views if request.method == 'POST' and \ obj and \ obj.is_latest and \ 'will_not_clone' not in request.path and \ 'delete' not in request.path and \ 'restore' not in request.path: obj = obj.clone() return obj
[ "def", "get_object", "(", "self", ",", "request", ",", "object_id", ",", "from_field", "=", "None", ")", ":", "# from_field breaks in 1.7.8", "obj", "=", "super", "(", "VersionedAdmin", ",", "self", ")", ".", "get_object", "(", "request", ",", "object_id", ")", "# Only clone if update view as get_object() is also called for change,", "# delete, and history views", "if", "request", ".", "method", "==", "'POST'", "and", "obj", "and", "obj", ".", "is_latest", "and", "'will_not_clone'", "not", "in", "request", ".", "path", "and", "'delete'", "not", "in", "request", ".", "path", "and", "'restore'", "not", "in", "request", ".", "path", ":", "obj", "=", "obj", ".", "clone", "(", ")", "return", "obj" ]
our implementation of get_object allows for cloning when updating an object, not cloning when the button 'save but not clone' is pushed and at no other time will clone be called
[ "our", "implementation", "of", "get_object", "allows", "for", "cloning", "when", "updating", "an", "object", "not", "cloning", "when", "the", "button", "save", "but", "not", "clone", "is", "pushed", "and", "at", "no", "other", "time", "will", "clone", "be", "called" ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L240-L259
17,801
swisscom/cleanerversion
versions/admin.py
VersionedAdmin.get_urls
def get_urls(self): """ Appends the custom will_not_clone url to the admin site """ not_clone_url = [url(r'^(.+)/will_not_clone/$', admin.site.admin_view(self.will_not_clone))] restore_url = [ url(r'^(.+)/restore/$', admin.site.admin_view(self.restore))] return not_clone_url + restore_url + super(VersionedAdmin, self).get_urls()
python
def get_urls(self): """ Appends the custom will_not_clone url to the admin site """ not_clone_url = [url(r'^(.+)/will_not_clone/$', admin.site.admin_view(self.will_not_clone))] restore_url = [ url(r'^(.+)/restore/$', admin.site.admin_view(self.restore))] return not_clone_url + restore_url + super(VersionedAdmin, self).get_urls()
[ "def", "get_urls", "(", "self", ")", ":", "not_clone_url", "=", "[", "url", "(", "r'^(.+)/will_not_clone/$'", ",", "admin", ".", "site", ".", "admin_view", "(", "self", ".", "will_not_clone", ")", ")", "]", "restore_url", "=", "[", "url", "(", "r'^(.+)/restore/$'", ",", "admin", ".", "site", ".", "admin_view", "(", "self", ".", "restore", ")", ")", "]", "return", "not_clone_url", "+", "restore_url", "+", "super", "(", "VersionedAdmin", ",", "self", ")", ".", "get_urls", "(", ")" ]
Appends the custom will_not_clone url to the admin site
[ "Appends", "the", "custom", "will_not_clone", "url", "to", "the", "admin", "site" ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/admin.py#L297-L306
17,802
swisscom/cleanerversion
versions/util/postgresql.py
create_current_version_unique_identity_indexes
def create_current_version_unique_identity_indexes(app_name, database=None): """ Add partial unique indexes for the the identity column of versionable models. This enforces that no two *current* versions can have the same identity. This will only try to create indexes if they do not exist in the database, so it should be safe to run in a post_migrate signal handler. Running it several times should leave the database in the same state as running it once. :param str app_name: application name whose Versionable models will be acted on. :param str database: database alias to use. If None, use default connection. :return: number of partial unique indexes created :rtype: int """ indexes_created = 0 connection = database_connection(database) with connection.cursor() as cursor: for model in versionable_models(app_name): if getattr(model._meta, 'managed', True): table_name = model._meta.db_table index_name = '%s_%s_identity_v_uniq' % (app_name, table_name) if not index_exists(cursor, index_name): cursor.execute( "CREATE UNIQUE INDEX %s ON %s(%s) " "WHERE version_end_date IS NULL" % (index_name, table_name, 'identity')) indexes_created += 1 return indexes_created
python
def create_current_version_unique_identity_indexes(app_name, database=None): """ Add partial unique indexes for the the identity column of versionable models. This enforces that no two *current* versions can have the same identity. This will only try to create indexes if they do not exist in the database, so it should be safe to run in a post_migrate signal handler. Running it several times should leave the database in the same state as running it once. :param str app_name: application name whose Versionable models will be acted on. :param str database: database alias to use. If None, use default connection. :return: number of partial unique indexes created :rtype: int """ indexes_created = 0 connection = database_connection(database) with connection.cursor() as cursor: for model in versionable_models(app_name): if getattr(model._meta, 'managed', True): table_name = model._meta.db_table index_name = '%s_%s_identity_v_uniq' % (app_name, table_name) if not index_exists(cursor, index_name): cursor.execute( "CREATE UNIQUE INDEX %s ON %s(%s) " "WHERE version_end_date IS NULL" % (index_name, table_name, 'identity')) indexes_created += 1 return indexes_created
[ "def", "create_current_version_unique_identity_indexes", "(", "app_name", ",", "database", "=", "None", ")", ":", "indexes_created", "=", "0", "connection", "=", "database_connection", "(", "database", ")", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "for", "model", "in", "versionable_models", "(", "app_name", ")", ":", "if", "getattr", "(", "model", ".", "_meta", ",", "'managed'", ",", "True", ")", ":", "table_name", "=", "model", ".", "_meta", ".", "db_table", "index_name", "=", "'%s_%s_identity_v_uniq'", "%", "(", "app_name", ",", "table_name", ")", "if", "not", "index_exists", "(", "cursor", ",", "index_name", ")", ":", "cursor", ".", "execute", "(", "\"CREATE UNIQUE INDEX %s ON %s(%s) \"", "\"WHERE version_end_date IS NULL\"", "%", "(", "index_name", ",", "table_name", ",", "'identity'", ")", ")", "indexes_created", "+=", "1", "return", "indexes_created" ]
Add partial unique indexes for the the identity column of versionable models. This enforces that no two *current* versions can have the same identity. This will only try to create indexes if they do not exist in the database, so it should be safe to run in a post_migrate signal handler. Running it several times should leave the database in the same state as running it once. :param str app_name: application name whose Versionable models will be acted on. :param str database: database alias to use. If None, use default connection. :return: number of partial unique indexes created :rtype: int
[ "Add", "partial", "unique", "indexes", "for", "the", "the", "identity", "column", "of", "versionable", "models", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/util/postgresql.py#L148-L182
17,803
swisscom/cleanerversion
versions/models.py
VersionManager.get_queryset
def get_queryset(self): """ Returns a VersionedQuerySet capable of handling version time restrictions. :return: VersionedQuerySet """ qs = VersionedQuerySet(self.model, using=self._db) if hasattr(self, 'instance') and hasattr(self.instance, '_querytime'): qs.querytime = self.instance._querytime return qs
python
def get_queryset(self): """ Returns a VersionedQuerySet capable of handling version time restrictions. :return: VersionedQuerySet """ qs = VersionedQuerySet(self.model, using=self._db) if hasattr(self, 'instance') and hasattr(self.instance, '_querytime'): qs.querytime = self.instance._querytime return qs
[ "def", "get_queryset", "(", "self", ")", ":", "qs", "=", "VersionedQuerySet", "(", "self", ".", "model", ",", "using", "=", "self", ".", "_db", ")", "if", "hasattr", "(", "self", ",", "'instance'", ")", "and", "hasattr", "(", "self", ".", "instance", ",", "'_querytime'", ")", ":", "qs", ".", "querytime", "=", "self", ".", "instance", ".", "_querytime", "return", "qs" ]
Returns a VersionedQuerySet capable of handling version time restrictions. :return: VersionedQuerySet
[ "Returns", "a", "VersionedQuerySet", "capable", "of", "handling", "version", "time", "restrictions", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L62-L72
17,804
swisscom/cleanerversion
versions/models.py
VersionManager.next_version
def next_version(self, object, relations_as_of='end'): """ Return the next version of the given object. In case there is no next object existing, meaning the given object is the current version, the function returns this version. Note that if object's version_end_date is None, this does not check the database to see if there is a newer version (perhaps created by some other code), it simply returns the passed object. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose next version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :return: Versionable """ if object.version_end_date is None: next = object else: next = self.filter( Q(identity=object.identity), Q(version_start_date__gte=object.version_end_date) ).order_by('version_start_date').first() if not next: raise ObjectDoesNotExist( "next_version couldn't find a next version of object " + str(object.identity)) return self.adjust_version_as_of(next, relations_as_of)
python
def next_version(self, object, relations_as_of='end'): """ Return the next version of the given object. In case there is no next object existing, meaning the given object is the current version, the function returns this version. Note that if object's version_end_date is None, this does not check the database to see if there is a newer version (perhaps created by some other code), it simply returns the passed object. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose next version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :return: Versionable """ if object.version_end_date is None: next = object else: next = self.filter( Q(identity=object.identity), Q(version_start_date__gte=object.version_end_date) ).order_by('version_start_date').first() if not next: raise ObjectDoesNotExist( "next_version couldn't find a next version of object " + str(object.identity)) return self.adjust_version_as_of(next, relations_as_of)
[ "def", "next_version", "(", "self", ",", "object", ",", "relations_as_of", "=", "'end'", ")", ":", "if", "object", ".", "version_end_date", "is", "None", ":", "next", "=", "object", "else", ":", "next", "=", "self", ".", "filter", "(", "Q", "(", "identity", "=", "object", ".", "identity", ")", ",", "Q", "(", "version_start_date__gte", "=", "object", ".", "version_end_date", ")", ")", ".", "order_by", "(", "'version_start_date'", ")", ".", "first", "(", ")", "if", "not", "next", ":", "raise", "ObjectDoesNotExist", "(", "\"next_version couldn't find a next version of object \"", "+", "str", "(", "object", ".", "identity", ")", ")", "return", "self", ".", "adjust_version_as_of", "(", "next", ",", "relations_as_of", ")" ]
Return the next version of the given object. In case there is no next object existing, meaning the given object is the current version, the function returns this version. Note that if object's version_end_date is None, this does not check the database to see if there is a newer version (perhaps created by some other code), it simply returns the passed object. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose next version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :return: Versionable
[ "Return", "the", "next", "version", "of", "the", "given", "object", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L83-L117
17,805
swisscom/cleanerversion
versions/models.py
VersionManager.previous_version
def previous_version(self, object, relations_as_of='end'): """ Return the previous version of the given object. In case there is no previous object existing, meaning the given object is the first version of the object, then the function returns this version. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose previous version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :return: Versionable """ if object.version_birth_date == object.version_start_date: previous = object else: previous = self.filter( Q(identity=object.identity), Q(version_end_date__lte=object.version_start_date) ).order_by('-version_end_date').first() if not previous: raise ObjectDoesNotExist( "previous_version couldn't find a previous version of " "object " + str(object.identity)) return self.adjust_version_as_of(previous, relations_as_of)
python
def previous_version(self, object, relations_as_of='end'): """ Return the previous version of the given object. In case there is no previous object existing, meaning the given object is the first version of the object, then the function returns this version. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose previous version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :return: Versionable """ if object.version_birth_date == object.version_start_date: previous = object else: previous = self.filter( Q(identity=object.identity), Q(version_end_date__lte=object.version_start_date) ).order_by('-version_end_date').first() if not previous: raise ObjectDoesNotExist( "previous_version couldn't find a previous version of " "object " + str(object.identity)) return self.adjust_version_as_of(previous, relations_as_of)
[ "def", "previous_version", "(", "self", ",", "object", ",", "relations_as_of", "=", "'end'", ")", ":", "if", "object", ".", "version_birth_date", "==", "object", ".", "version_start_date", ":", "previous", "=", "object", "else", ":", "previous", "=", "self", ".", "filter", "(", "Q", "(", "identity", "=", "object", ".", "identity", ")", ",", "Q", "(", "version_end_date__lte", "=", "object", ".", "version_start_date", ")", ")", ".", "order_by", "(", "'-version_end_date'", ")", ".", "first", "(", ")", "if", "not", "previous", ":", "raise", "ObjectDoesNotExist", "(", "\"previous_version couldn't find a previous version of \"", "\"object \"", "+", "str", "(", "object", ".", "identity", ")", ")", "return", "self", ".", "adjust_version_as_of", "(", "previous", ",", "relations_as_of", ")" ]
Return the previous version of the given object. In case there is no previous object existing, meaning the given object is the first version of the object, then the function returns this version. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose previous version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :return: Versionable
[ "Return", "the", "previous", "version", "of", "the", "given", "object", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L119-L151
17,806
swisscom/cleanerversion
versions/models.py
VersionManager.current_version
def current_version(self, object, relations_as_of=None, check_db=False): """ Return the current version of the given object. The current version is the one having its version_end_date set to NULL. If there is not such a version then it means the object has been 'deleted' and so there is no current version available. In this case the function returns None. Note that if check_db is False and object's version_end_date is None, this does not check the database to see if there is a newer version (perhaps created by some other code), it simply returns the passed object. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose current version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :param bool check_db: Whether or not to look in the database for a more recent version :return: Versionable """ if object.version_end_date is None and not check_db: current = object else: current = self.current.filter(identity=object.identity).first() return self.adjust_version_as_of(current, relations_as_of)
python
def current_version(self, object, relations_as_of=None, check_db=False): """ Return the current version of the given object. The current version is the one having its version_end_date set to NULL. If there is not such a version then it means the object has been 'deleted' and so there is no current version available. In this case the function returns None. Note that if check_db is False and object's version_end_date is None, this does not check the database to see if there is a newer version (perhaps created by some other code), it simply returns the passed object. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose current version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :param bool check_db: Whether or not to look in the database for a more recent version :return: Versionable """ if object.version_end_date is None and not check_db: current = object else: current = self.current.filter(identity=object.identity).first() return self.adjust_version_as_of(current, relations_as_of)
[ "def", "current_version", "(", "self", ",", "object", ",", "relations_as_of", "=", "None", ",", "check_db", "=", "False", ")", ":", "if", "object", ".", "version_end_date", "is", "None", "and", "not", "check_db", ":", "current", "=", "object", "else", ":", "current", "=", "self", ".", "current", ".", "filter", "(", "identity", "=", "object", ".", "identity", ")", ".", "first", "(", ")", "return", "self", ".", "adjust_version_as_of", "(", "current", ",", "relations_as_of", ")" ]
Return the current version of the given object. The current version is the one having its version_end_date set to NULL. If there is not such a version then it means the object has been 'deleted' and so there is no current version available. In this case the function returns None. Note that if check_db is False and object's version_end_date is None, this does not check the database to see if there is a newer version (perhaps created by some other code), it simply returns the passed object. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. See ``VersionManager.version_as_of`` for details on valid ``relations_as_of`` values. :param Versionable object: object whose current version will be returned. :param mixed relations_as_of: determines point in time used to access relations. 'start'|'end'|datetime|None :param bool check_db: Whether or not to look in the database for a more recent version :return: Versionable
[ "Return", "the", "current", "version", "of", "the", "given", "object", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L153-L185
17,807
swisscom/cleanerversion
versions/models.py
VersionManager.adjust_version_as_of
def adjust_version_as_of(version, relations_as_of): """ Adjusts the passed version's as_of time to an appropriate value, and returns it. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. Valid ``relations_as_of`` values and how this affects the returned version's as_of attribute: - 'start': version start date - 'end': version end date - 1 microsecond (no effect if version is current version) - datetime object: given datetime (raises ValueError if given datetime not valid for version) - None: unset (related object queries will not be restricted to a point in time) :param Versionable object: object whose as_of will be adjusted as requested. :param mixed relations_as_of: valid values are the strings 'start' or 'end', or a datetime object. :return: Versionable """ if not version: return version if relations_as_of == 'end': if version.is_current: # Ensure that version._querytime is active, in case it wasn't # before. version.as_of = None else: version.as_of = version.version_end_date - datetime.timedelta( microseconds=1) elif relations_as_of == 'start': version.as_of = version.version_start_date elif isinstance(relations_as_of, datetime.datetime): as_of = relations_as_of.astimezone(utc) if not as_of >= version.version_start_date: raise ValueError( "Provided as_of '{}' is earlier than version's start " "time '{}'".format( as_of.isoformat(), version.version_start_date.isoformat() ) ) if version.version_end_date is not None \ and as_of >= version.version_end_date: raise ValueError( "Provided as_of '{}' is later than version's start " "time '{}'".format( as_of.isoformat(), version.version_end_date.isoformat() ) ) version.as_of = as_of elif relations_as_of is None: version._querytime = QueryTime(time=None, active=False) else: raise TypeError( "as_of parameter must be 'start', 'end', None, or datetime " "object") return version
python
def adjust_version_as_of(version, relations_as_of): """ Adjusts the passed version's as_of time to an appropriate value, and returns it. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. Valid ``relations_as_of`` values and how this affects the returned version's as_of attribute: - 'start': version start date - 'end': version end date - 1 microsecond (no effect if version is current version) - datetime object: given datetime (raises ValueError if given datetime not valid for version) - None: unset (related object queries will not be restricted to a point in time) :param Versionable object: object whose as_of will be adjusted as requested. :param mixed relations_as_of: valid values are the strings 'start' or 'end', or a datetime object. :return: Versionable """ if not version: return version if relations_as_of == 'end': if version.is_current: # Ensure that version._querytime is active, in case it wasn't # before. version.as_of = None else: version.as_of = version.version_end_date - datetime.timedelta( microseconds=1) elif relations_as_of == 'start': version.as_of = version.version_start_date elif isinstance(relations_as_of, datetime.datetime): as_of = relations_as_of.astimezone(utc) if not as_of >= version.version_start_date: raise ValueError( "Provided as_of '{}' is earlier than version's start " "time '{}'".format( as_of.isoformat(), version.version_start_date.isoformat() ) ) if version.version_end_date is not None \ and as_of >= version.version_end_date: raise ValueError( "Provided as_of '{}' is later than version's start " "time '{}'".format( as_of.isoformat(), version.version_end_date.isoformat() ) ) version.as_of = as_of elif relations_as_of is None: version._querytime = QueryTime(time=None, active=False) else: raise TypeError( "as_of parameter must be 'start', 'end', None, or datetime " "object") return version
[ "def", "adjust_version_as_of", "(", "version", ",", "relations_as_of", ")", ":", "if", "not", "version", ":", "return", "version", "if", "relations_as_of", "==", "'end'", ":", "if", "version", ".", "is_current", ":", "# Ensure that version._querytime is active, in case it wasn't", "# before.", "version", ".", "as_of", "=", "None", "else", ":", "version", ".", "as_of", "=", "version", ".", "version_end_date", "-", "datetime", ".", "timedelta", "(", "microseconds", "=", "1", ")", "elif", "relations_as_of", "==", "'start'", ":", "version", ".", "as_of", "=", "version", ".", "version_start_date", "elif", "isinstance", "(", "relations_as_of", ",", "datetime", ".", "datetime", ")", ":", "as_of", "=", "relations_as_of", ".", "astimezone", "(", "utc", ")", "if", "not", "as_of", ">=", "version", ".", "version_start_date", ":", "raise", "ValueError", "(", "\"Provided as_of '{}' is earlier than version's start \"", "\"time '{}'\"", ".", "format", "(", "as_of", ".", "isoformat", "(", ")", ",", "version", ".", "version_start_date", ".", "isoformat", "(", ")", ")", ")", "if", "version", ".", "version_end_date", "is", "not", "None", "and", "as_of", ">=", "version", ".", "version_end_date", ":", "raise", "ValueError", "(", "\"Provided as_of '{}' is later than version's start \"", "\"time '{}'\"", ".", "format", "(", "as_of", ".", "isoformat", "(", ")", ",", "version", ".", "version_end_date", ".", "isoformat", "(", ")", ")", ")", "version", ".", "as_of", "=", "as_of", "elif", "relations_as_of", "is", "None", ":", "version", ".", "_querytime", "=", "QueryTime", "(", "time", "=", "None", ",", "active", "=", "False", ")", "else", ":", "raise", "TypeError", "(", "\"as_of parameter must be 'start', 'end', None, or datetime \"", "\"object\"", ")", "return", "version" ]
Adjusts the passed version's as_of time to an appropriate value, and returns it. ``relations_as_of`` is used to fix the point in time for the version; this affects which related objects are returned when querying for object relations. Valid ``relations_as_of`` values and how this affects the returned version's as_of attribute: - 'start': version start date - 'end': version end date - 1 microsecond (no effect if version is current version) - datetime object: given datetime (raises ValueError if given datetime not valid for version) - None: unset (related object queries will not be restricted to a point in time) :param Versionable object: object whose as_of will be adjusted as requested. :param mixed relations_as_of: valid values are the strings 'start' or 'end', or a datetime object. :return: Versionable
[ "Adjusts", "the", "passed", "version", "s", "as_of", "time", "to", "an", "appropriate", "value", "and", "returns", "it", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L188-L252
17,808
swisscom/cleanerversion
versions/models.py
VersionedQuerySet._fetch_all
def _fetch_all(self): """ Completely overrides the QuerySet._fetch_all method by adding the timestamp to all objects :return: See django.db.models.query.QuerySet._fetch_all for return values """ if self._result_cache is None: self._result_cache = list(self.iterator()) # TODO: Do we have to test for ValuesListIterable, ValuesIterable, # and FlatValuesListIterable here? if self._iterable_class == ModelIterable: for x in self._result_cache: self._set_item_querytime(x) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects()
python
def _fetch_all(self): """ Completely overrides the QuerySet._fetch_all method by adding the timestamp to all objects :return: See django.db.models.query.QuerySet._fetch_all for return values """ if self._result_cache is None: self._result_cache = list(self.iterator()) # TODO: Do we have to test for ValuesListIterable, ValuesIterable, # and FlatValuesListIterable here? if self._iterable_class == ModelIterable: for x in self._result_cache: self._set_item_querytime(x) if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects()
[ "def", "_fetch_all", "(", "self", ")", ":", "if", "self", ".", "_result_cache", "is", "None", ":", "self", ".", "_result_cache", "=", "list", "(", "self", ".", "iterator", "(", ")", ")", "# TODO: Do we have to test for ValuesListIterable, ValuesIterable,", "# and FlatValuesListIterable here?", "if", "self", ".", "_iterable_class", "==", "ModelIterable", ":", "for", "x", "in", "self", ".", "_result_cache", ":", "self", ".", "_set_item_querytime", "(", "x", ")", "if", "self", ".", "_prefetch_related_lookups", "and", "not", "self", ".", "_prefetch_done", ":", "self", ".", "_prefetch_related_objects", "(", ")" ]
Completely overrides the QuerySet._fetch_all method by adding the timestamp to all objects :return: See django.db.models.query.QuerySet._fetch_all for return values
[ "Completely", "overrides", "the", "QuerySet", ".", "_fetch_all", "method", "by", "adding", "the", "timestamp", "to", "all", "objects" ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L500-L516
17,809
swisscom/cleanerversion
versions/models.py
VersionedQuerySet._clone
def _clone(self, *args, **kwargs): """ Overrides the QuerySet._clone method by adding the cloning of the VersionedQuerySet's query_time parameter :param kwargs: Same as the original QuerySet._clone params :return: Just as QuerySet._clone, this method returns a clone of the original object """ clone = super(VersionedQuerySet, self)._clone(**kwargs) clone.querytime = self.querytime return clone
python
def _clone(self, *args, **kwargs): """ Overrides the QuerySet._clone method by adding the cloning of the VersionedQuerySet's query_time parameter :param kwargs: Same as the original QuerySet._clone params :return: Just as QuerySet._clone, this method returns a clone of the original object """ clone = super(VersionedQuerySet, self)._clone(**kwargs) clone.querytime = self.querytime return clone
[ "def", "_clone", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "clone", "=", "super", "(", "VersionedQuerySet", ",", "self", ")", ".", "_clone", "(", "*", "*", "kwargs", ")", "clone", ".", "querytime", "=", "self", ".", "querytime", "return", "clone" ]
Overrides the QuerySet._clone method by adding the cloning of the VersionedQuerySet's query_time parameter :param kwargs: Same as the original QuerySet._clone params :return: Just as QuerySet._clone, this method returns a clone of the original object
[ "Overrides", "the", "QuerySet", ".", "_clone", "method", "by", "adding", "the", "cloning", "of", "the", "VersionedQuerySet", "s", "query_time", "parameter" ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L518-L529
17,810
swisscom/cleanerversion
versions/models.py
VersionedQuerySet._set_item_querytime
def _set_item_querytime(self, item, type_check=True): """ Sets the time for which the query was made on the resulting item :param item: an item of type Versionable :param type_check: Check the item to be a Versionable :return: Returns the item itself with the time set """ if isinstance(item, Versionable): item._querytime = self.querytime elif isinstance(item, VersionedQuerySet): item.querytime = self.querytime else: if type_check: raise TypeError( "This item is not a Versionable, it's a " + str( type(item))) return item
python
def _set_item_querytime(self, item, type_check=True): """ Sets the time for which the query was made on the resulting item :param item: an item of type Versionable :param type_check: Check the item to be a Versionable :return: Returns the item itself with the time set """ if isinstance(item, Versionable): item._querytime = self.querytime elif isinstance(item, VersionedQuerySet): item.querytime = self.querytime else: if type_check: raise TypeError( "This item is not a Versionable, it's a " + str( type(item))) return item
[ "def", "_set_item_querytime", "(", "self", ",", "item", ",", "type_check", "=", "True", ")", ":", "if", "isinstance", "(", "item", ",", "Versionable", ")", ":", "item", ".", "_querytime", "=", "self", ".", "querytime", "elif", "isinstance", "(", "item", ",", "VersionedQuerySet", ")", ":", "item", ".", "querytime", "=", "self", ".", "querytime", "else", ":", "if", "type_check", ":", "raise", "TypeError", "(", "\"This item is not a Versionable, it's a \"", "+", "str", "(", "type", "(", "item", ")", ")", ")", "return", "item" ]
Sets the time for which the query was made on the resulting item :param item: an item of type Versionable :param type_check: Check the item to be a Versionable :return: Returns the item itself with the time set
[ "Sets", "the", "time", "for", "which", "the", "query", "was", "made", "on", "the", "resulting", "item" ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L531-L548
17,811
swisscom/cleanerversion
versions/models.py
VersionedQuerySet.as_of
def as_of(self, qtime=None): """ Sets the time for which we want to retrieve an object. :param qtime: The UTC date and time; if None then use the current state (where version_end_date = NULL) :return: A VersionedQuerySet """ clone = self._clone() clone.querytime = QueryTime(time=qtime, active=True) return clone
python
def as_of(self, qtime=None): """ Sets the time for which we want to retrieve an object. :param qtime: The UTC date and time; if None then use the current state (where version_end_date = NULL) :return: A VersionedQuerySet """ clone = self._clone() clone.querytime = QueryTime(time=qtime, active=True) return clone
[ "def", "as_of", "(", "self", ",", "qtime", "=", "None", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "clone", ".", "querytime", "=", "QueryTime", "(", "time", "=", "qtime", ",", "active", "=", "True", ")", "return", "clone" ]
Sets the time for which we want to retrieve an object. :param qtime: The UTC date and time; if None then use the current state (where version_end_date = NULL) :return: A VersionedQuerySet
[ "Sets", "the", "time", "for", "which", "we", "want", "to", "retrieve", "an", "object", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L550-L560
17,812
swisscom/cleanerversion
versions/models.py
VersionedQuerySet.delete
def delete(self): """ Deletes the records in the QuerySet. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with delete." # Ensure that only current objects are selected. del_query = self.filter(version_end_date__isnull=True) # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_for_update = False del_query.query.select_related = False del_query.query.clear_ordering(force_empty=True) collector_class = get_versioned_delete_collector_class() collector = collector_class(using=del_query.db) collector.collect(del_query) collector.delete(get_utc_now()) # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None
python
def delete(self): """ Deletes the records in the QuerySet. """ assert self.query.can_filter(), \ "Cannot use 'limit' or 'offset' with delete." # Ensure that only current objects are selected. del_query = self.filter(version_end_date__isnull=True) # The delete is actually 2 queries - one to find related objects, # and one to delete. Make sure that the discovery of related # objects is performed on the same database as the deletion. del_query._for_write = True # Disable non-supported fields. del_query.query.select_for_update = False del_query.query.select_related = False del_query.query.clear_ordering(force_empty=True) collector_class = get_versioned_delete_collector_class() collector = collector_class(using=del_query.db) collector.collect(del_query) collector.delete(get_utc_now()) # Clear the result cache, in case this QuerySet gets reused. self._result_cache = None
[ "def", "delete", "(", "self", ")", ":", "assert", "self", ".", "query", ".", "can_filter", "(", ")", ",", "\"Cannot use 'limit' or 'offset' with delete.\"", "# Ensure that only current objects are selected.", "del_query", "=", "self", ".", "filter", "(", "version_end_date__isnull", "=", "True", ")", "# The delete is actually 2 queries - one to find related objects,", "# and one to delete. Make sure that the discovery of related", "# objects is performed on the same database as the deletion.", "del_query", ".", "_for_write", "=", "True", "# Disable non-supported fields.", "del_query", ".", "query", ".", "select_for_update", "=", "False", "del_query", ".", "query", ".", "select_related", "=", "False", "del_query", ".", "query", ".", "clear_ordering", "(", "force_empty", "=", "True", ")", "collector_class", "=", "get_versioned_delete_collector_class", "(", ")", "collector", "=", "collector_class", "(", "using", "=", "del_query", ".", "db", ")", "collector", ".", "collect", "(", "del_query", ")", "collector", ".", "delete", "(", "get_utc_now", "(", ")", ")", "# Clear the result cache, in case this QuerySet gets reused.", "self", ".", "_result_cache", "=", "None" ]
Deletes the records in the QuerySet.
[ "Deletes", "the", "records", "in", "the", "QuerySet", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L562-L588
17,813
swisscom/cleanerversion
versions/models.py
Versionable.uuid
def uuid(uuid_value=None): """ Returns a uuid value that is valid to use for id and identity fields. :return: unicode uuid object if using UUIDFields, uuid unicode string otherwise. """ if uuid_value: if not validate_uuid(uuid_value): raise ValueError( "uuid_value must be a valid UUID version 4 object") else: uuid_value = uuid.uuid4() if versions_settings.VERSIONS_USE_UUIDFIELD: return uuid_value else: return six.u(str(uuid_value))
python
def uuid(uuid_value=None): """ Returns a uuid value that is valid to use for id and identity fields. :return: unicode uuid object if using UUIDFields, uuid unicode string otherwise. """ if uuid_value: if not validate_uuid(uuid_value): raise ValueError( "uuid_value must be a valid UUID version 4 object") else: uuid_value = uuid.uuid4() if versions_settings.VERSIONS_USE_UUIDFIELD: return uuid_value else: return six.u(str(uuid_value))
[ "def", "uuid", "(", "uuid_value", "=", "None", ")", ":", "if", "uuid_value", ":", "if", "not", "validate_uuid", "(", "uuid_value", ")", ":", "raise", "ValueError", "(", "\"uuid_value must be a valid UUID version 4 object\"", ")", "else", ":", "uuid_value", "=", "uuid", ".", "uuid4", "(", ")", "if", "versions_settings", ".", "VERSIONS_USE_UUIDFIELD", ":", "return", "uuid_value", "else", ":", "return", "six", ".", "u", "(", "str", "(", "uuid_value", ")", ")" ]
Returns a uuid value that is valid to use for id and identity fields. :return: unicode uuid object if using UUIDFields, uuid unicode string otherwise.
[ "Returns", "a", "uuid", "value", "that", "is", "valid", "to", "use", "for", "id", "and", "identity", "fields", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L737-L754
17,814
swisscom/cleanerversion
versions/models.py
Versionable.restore
def restore(self, **kwargs): """ Restores this version as a new version, and returns this new version. If a current version already exists, it will be terminated before restoring this version. Relations (foreign key, reverse foreign key, many-to-many) are not restored with the old version. If provided in kwargs, (Versioned)ForeignKey fields will be set to the provided values. If passing an id for a (Versioned)ForeignKey, use the field.attname. For example: restore(team_id=myteam.pk) If passing an object, simply use the field name, e.g.: restore(team=myteam) If a (Versioned)ForeignKey is not nullable and no value is provided for it in kwargs, a ForeignKeyRequiresValueError will be raised. :param kwargs: arguments used to initialize the class instance :return: Versionable """ if not self.pk: raise ValueError( 'Instance must be saved and terminated before it can be ' 'restored.') if self.is_current: raise ValueError( 'This is the current version, no need to restore it.') if self.get_deferred_fields(): # It would be necessary to fetch the record from the database # again for this to succeed. # Alternatively, perhaps it would be possible to create a copy # of the object after fetching the missing fields. # Doing so may be unexpected by the calling code, so raise an # exception: the calling code should be adapted if necessary. raise ValueError( 'Can not restore a model instance that has deferred fields') cls = self.__class__ now = get_utc_now() restored = copy.copy(self) restored.version_end_date = None restored.version_start_date = now fields = [f for f in cls._meta.local_fields if f.name not in Versionable.VERSIONABLE_FIELDS] for field in fields: if field.attname in kwargs: # Fake an object in order to avoid a DB roundtrip # This was made necessary, since assigning to the field's # attname did not work anymore with Django 2.0 obj = field.remote_field.model(id=kwargs[field.attname]) setattr(restored, field.name, obj) elif field.name in kwargs: setattr(restored, field.name, kwargs[field.name]) elif isinstance(field, ForeignKey): # Set all non-provided ForeignKeys to None. If required, # raise an error. try: setattr(restored, field.name, None) # Check for non null foreign key removed since Django 1.10 # https://docs.djangoproject.com/en/1.10/releases/1.10/ # #removed-null-assignment-check-for-non-null-foreign- # key-fields if not field.null: raise ValueError except ValueError: raise ForeignKeyRequiresValueError self.id = self.uuid() with transaction.atomic(): # If this is not the latest version, terminate the latest version latest = cls.objects.current_version(self, check_db=True) if latest and latest != self: latest.delete() restored.version_start_date = latest.version_end_date self.save() restored.save() # Update ManyToMany relations to point to the old version's id # instead of the restored version's id. for field_name in self.get_all_m2m_field_names(): manager = getattr(restored, field_name) # returns a VersionedRelatedManager instance manager.through.objects.filter( **{manager.source_field.attname: restored.id}).update( **{manager.source_field_name: self}) return restored
python
def restore(self, **kwargs): """ Restores this version as a new version, and returns this new version. If a current version already exists, it will be terminated before restoring this version. Relations (foreign key, reverse foreign key, many-to-many) are not restored with the old version. If provided in kwargs, (Versioned)ForeignKey fields will be set to the provided values. If passing an id for a (Versioned)ForeignKey, use the field.attname. For example: restore(team_id=myteam.pk) If passing an object, simply use the field name, e.g.: restore(team=myteam) If a (Versioned)ForeignKey is not nullable and no value is provided for it in kwargs, a ForeignKeyRequiresValueError will be raised. :param kwargs: arguments used to initialize the class instance :return: Versionable """ if not self.pk: raise ValueError( 'Instance must be saved and terminated before it can be ' 'restored.') if self.is_current: raise ValueError( 'This is the current version, no need to restore it.') if self.get_deferred_fields(): # It would be necessary to fetch the record from the database # again for this to succeed. # Alternatively, perhaps it would be possible to create a copy # of the object after fetching the missing fields. # Doing so may be unexpected by the calling code, so raise an # exception: the calling code should be adapted if necessary. raise ValueError( 'Can not restore a model instance that has deferred fields') cls = self.__class__ now = get_utc_now() restored = copy.copy(self) restored.version_end_date = None restored.version_start_date = now fields = [f for f in cls._meta.local_fields if f.name not in Versionable.VERSIONABLE_FIELDS] for field in fields: if field.attname in kwargs: # Fake an object in order to avoid a DB roundtrip # This was made necessary, since assigning to the field's # attname did not work anymore with Django 2.0 obj = field.remote_field.model(id=kwargs[field.attname]) setattr(restored, field.name, obj) elif field.name in kwargs: setattr(restored, field.name, kwargs[field.name]) elif isinstance(field, ForeignKey): # Set all non-provided ForeignKeys to None. If required, # raise an error. try: setattr(restored, field.name, None) # Check for non null foreign key removed since Django 1.10 # https://docs.djangoproject.com/en/1.10/releases/1.10/ # #removed-null-assignment-check-for-non-null-foreign- # key-fields if not field.null: raise ValueError except ValueError: raise ForeignKeyRequiresValueError self.id = self.uuid() with transaction.atomic(): # If this is not the latest version, terminate the latest version latest = cls.objects.current_version(self, check_db=True) if latest and latest != self: latest.delete() restored.version_start_date = latest.version_end_date self.save() restored.save() # Update ManyToMany relations to point to the old version's id # instead of the restored version's id. for field_name in self.get_all_m2m_field_names(): manager = getattr(restored, field_name) # returns a VersionedRelatedManager instance manager.through.objects.filter( **{manager.source_field.attname: restored.id}).update( **{manager.source_field_name: self}) return restored
[ "def", "restore", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "pk", ":", "raise", "ValueError", "(", "'Instance must be saved and terminated before it can be '", "'restored.'", ")", "if", "self", ".", "is_current", ":", "raise", "ValueError", "(", "'This is the current version, no need to restore it.'", ")", "if", "self", ".", "get_deferred_fields", "(", ")", ":", "# It would be necessary to fetch the record from the database", "# again for this to succeed.", "# Alternatively, perhaps it would be possible to create a copy", "# of the object after fetching the missing fields.", "# Doing so may be unexpected by the calling code, so raise an", "# exception: the calling code should be adapted if necessary.", "raise", "ValueError", "(", "'Can not restore a model instance that has deferred fields'", ")", "cls", "=", "self", ".", "__class__", "now", "=", "get_utc_now", "(", ")", "restored", "=", "copy", ".", "copy", "(", "self", ")", "restored", ".", "version_end_date", "=", "None", "restored", ".", "version_start_date", "=", "now", "fields", "=", "[", "f", "for", "f", "in", "cls", ".", "_meta", ".", "local_fields", "if", "f", ".", "name", "not", "in", "Versionable", ".", "VERSIONABLE_FIELDS", "]", "for", "field", "in", "fields", ":", "if", "field", ".", "attname", "in", "kwargs", ":", "# Fake an object in order to avoid a DB roundtrip", "# This was made necessary, since assigning to the field's", "# attname did not work anymore with Django 2.0", "obj", "=", "field", ".", "remote_field", ".", "model", "(", "id", "=", "kwargs", "[", "field", ".", "attname", "]", ")", "setattr", "(", "restored", ",", "field", ".", "name", ",", "obj", ")", "elif", "field", ".", "name", "in", "kwargs", ":", "setattr", "(", "restored", ",", "field", ".", "name", ",", "kwargs", "[", "field", ".", "name", "]", ")", "elif", "isinstance", "(", "field", ",", "ForeignKey", ")", ":", "# Set all non-provided ForeignKeys to None. If required,", "# raise an error.", "try", ":", "setattr", "(", "restored", ",", "field", ".", "name", ",", "None", ")", "# Check for non null foreign key removed since Django 1.10", "# https://docs.djangoproject.com/en/1.10/releases/1.10/", "# #removed-null-assignment-check-for-non-null-foreign-", "# key-fields", "if", "not", "field", ".", "null", ":", "raise", "ValueError", "except", "ValueError", ":", "raise", "ForeignKeyRequiresValueError", "self", ".", "id", "=", "self", ".", "uuid", "(", ")", "with", "transaction", ".", "atomic", "(", ")", ":", "# If this is not the latest version, terminate the latest version", "latest", "=", "cls", ".", "objects", ".", "current_version", "(", "self", ",", "check_db", "=", "True", ")", "if", "latest", "and", "latest", "!=", "self", ":", "latest", ".", "delete", "(", ")", "restored", ".", "version_start_date", "=", "latest", ".", "version_end_date", "self", ".", "save", "(", ")", "restored", ".", "save", "(", ")", "# Update ManyToMany relations to point to the old version's id", "# instead of the restored version's id.", "for", "field_name", "in", "self", ".", "get_all_m2m_field_names", "(", ")", ":", "manager", "=", "getattr", "(", "restored", ",", "field_name", ")", "# returns a VersionedRelatedManager instance", "manager", ".", "through", ".", "objects", ".", "filter", "(", "*", "*", "{", "manager", ".", "source_field", ".", "attname", ":", "restored", ".", "id", "}", ")", ".", "update", "(", "*", "*", "{", "manager", ".", "source_field_name", ":", "self", "}", ")", "return", "restored" ]
Restores this version as a new version, and returns this new version. If a current version already exists, it will be terminated before restoring this version. Relations (foreign key, reverse foreign key, many-to-many) are not restored with the old version. If provided in kwargs, (Versioned)ForeignKey fields will be set to the provided values. If passing an id for a (Versioned)ForeignKey, use the field.attname. For example: restore(team_id=myteam.pk) If passing an object, simply use the field name, e.g.: restore(team=myteam) If a (Versioned)ForeignKey is not nullable and no value is provided for it in kwargs, a ForeignKeyRequiresValueError will be raised. :param kwargs: arguments used to initialize the class instance :return: Versionable
[ "Restores", "this", "version", "as", "a", "new", "version", "and", "returns", "this", "new", "version", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L908-L1002
17,815
swisscom/cleanerversion
versions/models.py
Versionable.detach
def detach(self): """ Detaches the instance from its history. Similar to creating a new object with the same field values. The id and identity fields are set to a new value. The returned object has not been saved, call save() afterwards when you are ready to persist the object. ManyToMany and reverse ForeignKey relations are lost for the detached object. :return: Versionable """ self.id = self.identity = self.uuid() self.version_start_date = self.version_birth_date = get_utc_now() self.version_end_date = None return self
python
def detach(self): """ Detaches the instance from its history. Similar to creating a new object with the same field values. The id and identity fields are set to a new value. The returned object has not been saved, call save() afterwards when you are ready to persist the object. ManyToMany and reverse ForeignKey relations are lost for the detached object. :return: Versionable """ self.id = self.identity = self.uuid() self.version_start_date = self.version_birth_date = get_utc_now() self.version_end_date = None return self
[ "def", "detach", "(", "self", ")", ":", "self", ".", "id", "=", "self", ".", "identity", "=", "self", ".", "uuid", "(", ")", "self", ".", "version_start_date", "=", "self", ".", "version_birth_date", "=", "get_utc_now", "(", ")", "self", ".", "version_end_date", "=", "None", "return", "self" ]
Detaches the instance from its history. Similar to creating a new object with the same field values. The id and identity fields are set to a new value. The returned object has not been saved, call save() afterwards when you are ready to persist the object. ManyToMany and reverse ForeignKey relations are lost for the detached object. :return: Versionable
[ "Detaches", "the", "instance", "from", "its", "history", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L1013-L1030
17,816
swisscom/cleanerversion
versions/models.py
Versionable.matches_querytime
def matches_querytime(instance, querytime): """ Checks whether the given instance satisfies the given QueryTime object. :param instance: an instance of Versionable :param querytime: QueryTime value to check against """ if not querytime.active: return True if not querytime.time: return instance.version_end_date is None return (instance.version_start_date <= querytime.time and (instance.version_end_date is None or instance.version_end_date > querytime.time))
python
def matches_querytime(instance, querytime): """ Checks whether the given instance satisfies the given QueryTime object. :param instance: an instance of Versionable :param querytime: QueryTime value to check against """ if not querytime.active: return True if not querytime.time: return instance.version_end_date is None return (instance.version_start_date <= querytime.time and (instance.version_end_date is None or instance.version_end_date > querytime.time))
[ "def", "matches_querytime", "(", "instance", ",", "querytime", ")", ":", "if", "not", "querytime", ".", "active", ":", "return", "True", "if", "not", "querytime", ".", "time", ":", "return", "instance", ".", "version_end_date", "is", "None", "return", "(", "instance", ".", "version_start_date", "<=", "querytime", ".", "time", "and", "(", "instance", ".", "version_end_date", "is", "None", "or", "instance", ".", "version_end_date", ">", "querytime", ".", "time", ")", ")" ]
Checks whether the given instance satisfies the given QueryTime object. :param instance: an instance of Versionable :param querytime: QueryTime value to check against
[ "Checks", "whether", "the", "given", "instance", "satisfies", "the", "given", "QueryTime", "object", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/models.py#L1033-L1048
17,817
swisscom/cleanerversion
versions/fields.py
VersionedForeignKey.contribute_to_related_class
def contribute_to_related_class(self, cls, related): """ Override ForeignKey's methods, and replace the descriptor, if set by the parent's methods """ # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. super(VersionedForeignKey, self).contribute_to_related_class(cls, related) accessor_name = related.get_accessor_name() if hasattr(cls, accessor_name): setattr(cls, accessor_name, VersionedReverseManyToOneDescriptor(related))
python
def contribute_to_related_class(self, cls, related): """ Override ForeignKey's methods, and replace the descriptor, if set by the parent's methods """ # Internal FK's - i.e., those with a related name ending with '+' - # and swapped models don't get a related descriptor. super(VersionedForeignKey, self).contribute_to_related_class(cls, related) accessor_name = related.get_accessor_name() if hasattr(cls, accessor_name): setattr(cls, accessor_name, VersionedReverseManyToOneDescriptor(related))
[ "def", "contribute_to_related_class", "(", "self", ",", "cls", ",", "related", ")", ":", "# Internal FK's - i.e., those with a related name ending with '+' -", "# and swapped models don't get a related descriptor.", "super", "(", "VersionedForeignKey", ",", "self", ")", ".", "contribute_to_related_class", "(", "cls", ",", "related", ")", "accessor_name", "=", "related", ".", "get_accessor_name", "(", ")", "if", "hasattr", "(", "cls", ",", "accessor_name", ")", ":", "setattr", "(", "cls", ",", "accessor_name", ",", "VersionedReverseManyToOneDescriptor", "(", "related", ")", ")" ]
Override ForeignKey's methods, and replace the descriptor, if set by the parent's methods
[ "Override", "ForeignKey", "s", "methods", "and", "replace", "the", "descriptor", "if", "set", "by", "the", "parent", "s", "methods" ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/fields.py#L32-L44
17,818
swisscom/cleanerversion
versions/fields.py
VersionedForeignKey.get_joining_columns
def get_joining_columns(self, reverse_join=False): """ Get and return joining columns defined by this foreign key relationship :return: A tuple containing the column names of the tables to be joined (<local_col_name>, <remote_col_name>) :rtype: tuple """ source = self.reverse_related_fields if reverse_join \ else self.related_fields joining_columns = tuple() for lhs_field, rhs_field in source: lhs_col_name = lhs_field.column rhs_col_name = rhs_field.column # Test whether # - self is the current ForeignKey relationship # - self was not auto_created (e.g. is not part of a M2M # relationship) if self is lhs_field and not self.auto_created: if rhs_col_name == Versionable.VERSION_IDENTIFIER_FIELD: rhs_col_name = Versionable.OBJECT_IDENTIFIER_FIELD elif self is rhs_field and not self.auto_created: if lhs_col_name == Versionable.VERSION_IDENTIFIER_FIELD: lhs_col_name = Versionable.OBJECT_IDENTIFIER_FIELD joining_columns = joining_columns + ((lhs_col_name, rhs_col_name),) return joining_columns
python
def get_joining_columns(self, reverse_join=False): """ Get and return joining columns defined by this foreign key relationship :return: A tuple containing the column names of the tables to be joined (<local_col_name>, <remote_col_name>) :rtype: tuple """ source = self.reverse_related_fields if reverse_join \ else self.related_fields joining_columns = tuple() for lhs_field, rhs_field in source: lhs_col_name = lhs_field.column rhs_col_name = rhs_field.column # Test whether # - self is the current ForeignKey relationship # - self was not auto_created (e.g. is not part of a M2M # relationship) if self is lhs_field and not self.auto_created: if rhs_col_name == Versionable.VERSION_IDENTIFIER_FIELD: rhs_col_name = Versionable.OBJECT_IDENTIFIER_FIELD elif self is rhs_field and not self.auto_created: if lhs_col_name == Versionable.VERSION_IDENTIFIER_FIELD: lhs_col_name = Versionable.OBJECT_IDENTIFIER_FIELD joining_columns = joining_columns + ((lhs_col_name, rhs_col_name),) return joining_columns
[ "def", "get_joining_columns", "(", "self", ",", "reverse_join", "=", "False", ")", ":", "source", "=", "self", ".", "reverse_related_fields", "if", "reverse_join", "else", "self", ".", "related_fields", "joining_columns", "=", "tuple", "(", ")", "for", "lhs_field", ",", "rhs_field", "in", "source", ":", "lhs_col_name", "=", "lhs_field", ".", "column", "rhs_col_name", "=", "rhs_field", ".", "column", "# Test whether", "# - self is the current ForeignKey relationship", "# - self was not auto_created (e.g. is not part of a M2M", "# relationship)", "if", "self", "is", "lhs_field", "and", "not", "self", ".", "auto_created", ":", "if", "rhs_col_name", "==", "Versionable", ".", "VERSION_IDENTIFIER_FIELD", ":", "rhs_col_name", "=", "Versionable", ".", "OBJECT_IDENTIFIER_FIELD", "elif", "self", "is", "rhs_field", "and", "not", "self", ".", "auto_created", ":", "if", "lhs_col_name", "==", "Versionable", ".", "VERSION_IDENTIFIER_FIELD", ":", "lhs_col_name", "=", "Versionable", ".", "OBJECT_IDENTIFIER_FIELD", "joining_columns", "=", "joining_columns", "+", "(", "(", "lhs_col_name", ",", "rhs_col_name", ")", ",", ")", "return", "joining_columns" ]
Get and return joining columns defined by this foreign key relationship :return: A tuple containing the column names of the tables to be joined (<local_col_name>, <remote_col_name>) :rtype: tuple
[ "Get", "and", "return", "joining", "columns", "defined", "by", "this", "foreign", "key", "relationship" ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/fields.py#L65-L90
17,819
swisscom/cleanerversion
versions/settings.py
get_versioned_delete_collector_class
def get_versioned_delete_collector_class(): """ Gets the class to use for deletion collection. :return: class """ key = 'VERSIONED_DELETE_COLLECTOR' try: cls = _cache[key] except KeyError: collector_class_string = getattr(settings, key) cls = import_from_string(collector_class_string, key) _cache[key] = cls return cls
python
def get_versioned_delete_collector_class(): """ Gets the class to use for deletion collection. :return: class """ key = 'VERSIONED_DELETE_COLLECTOR' try: cls = _cache[key] except KeyError: collector_class_string = getattr(settings, key) cls = import_from_string(collector_class_string, key) _cache[key] = cls return cls
[ "def", "get_versioned_delete_collector_class", "(", ")", ":", "key", "=", "'VERSIONED_DELETE_COLLECTOR'", "try", ":", "cls", "=", "_cache", "[", "key", "]", "except", "KeyError", ":", "collector_class_string", "=", "getattr", "(", "settings", ",", "key", ")", "cls", "=", "import_from_string", "(", "collector_class_string", ",", "key", ")", "_cache", "[", "key", "]", "=", "cls", "return", "cls" ]
Gets the class to use for deletion collection. :return: class
[ "Gets", "the", "class", "to", "use", "for", "deletion", "collection", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/settings.py#L57-L70
17,820
swisscom/cleanerversion
versions/deletion.py
VersionedCollector.related_objects
def related_objects(self, related, objs): """ Gets a QuerySet of current objects related to ``objs`` via the relation ``related``. """ from versions.models import Versionable related_model = related.related_model if issubclass(related_model, Versionable): qs = related_model.objects.current else: qs = related_model._base_manager.all() return qs.using(self.using).filter( **{"%s__in" % related.field.name: objs} )
python
def related_objects(self, related, objs): """ Gets a QuerySet of current objects related to ``objs`` via the relation ``related``. """ from versions.models import Versionable related_model = related.related_model if issubclass(related_model, Versionable): qs = related_model.objects.current else: qs = related_model._base_manager.all() return qs.using(self.using).filter( **{"%s__in" % related.field.name: objs} )
[ "def", "related_objects", "(", "self", ",", "related", ",", "objs", ")", ":", "from", "versions", ".", "models", "import", "Versionable", "related_model", "=", "related", ".", "related_model", "if", "issubclass", "(", "related_model", ",", "Versionable", ")", ":", "qs", "=", "related_model", ".", "objects", ".", "current", "else", ":", "qs", "=", "related_model", ".", "_base_manager", ".", "all", "(", ")", "return", "qs", ".", "using", "(", "self", ".", "using", ")", ".", "filter", "(", "*", "*", "{", "\"%s__in\"", "%", "related", ".", "field", ".", "name", ":", "objs", "}", ")" ]
Gets a QuerySet of current objects related to ``objs`` via the relation ``related``.
[ "Gets", "a", "QuerySet", "of", "current", "objects", "related", "to", "objs", "via", "the", "relation", "related", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/deletion.py#L149-L163
17,821
swisscom/cleanerversion
versions/deletion.py
VersionedCollector.versionable_delete
def versionable_delete(self, instance, timestamp): """ Soft-deletes the instance, setting it's version_end_date to timestamp. Override this method to implement custom behaviour. :param Versionable instance: :param datetime timestamp: """ instance._delete_at(timestamp, using=self.using)
python
def versionable_delete(self, instance, timestamp): """ Soft-deletes the instance, setting it's version_end_date to timestamp. Override this method to implement custom behaviour. :param Versionable instance: :param datetime timestamp: """ instance._delete_at(timestamp, using=self.using)
[ "def", "versionable_delete", "(", "self", ",", "instance", ",", "timestamp", ")", ":", "instance", ".", "_delete_at", "(", "timestamp", ",", "using", "=", "self", ".", "using", ")" ]
Soft-deletes the instance, setting it's version_end_date to timestamp. Override this method to implement custom behaviour. :param Versionable instance: :param datetime timestamp:
[ "Soft", "-", "deletes", "the", "instance", "setting", "it", "s", "version_end_date", "to", "timestamp", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/deletion.py#L185-L194
17,822
swisscom/cleanerversion
versions/descriptors.py
VersionedManyToManyDescriptor.pks_from_objects
def pks_from_objects(self, objects): """ Extract all the primary key strings from the given objects. Objects may be Versionables, or bare primary keys. :rtype : set """ return {o.pk if isinstance(o, Model) else o for o in objects}
python
def pks_from_objects(self, objects): """ Extract all the primary key strings from the given objects. Objects may be Versionables, or bare primary keys. :rtype : set """ return {o.pk if isinstance(o, Model) else o for o in objects}
[ "def", "pks_from_objects", "(", "self", ",", "objects", ")", ":", "return", "{", "o", ".", "pk", "if", "isinstance", "(", "o", ",", "Model", ")", "else", "o", "for", "o", "in", "objects", "}" ]
Extract all the primary key strings from the given objects. Objects may be Versionables, or bare primary keys. :rtype : set
[ "Extract", "all", "the", "primary", "key", "strings", "from", "the", "given", "objects", ".", "Objects", "may", "be", "Versionables", "or", "bare", "primary", "keys", "." ]
becadbab5d7b474a0e9a596b99e97682402d2f2c
https://github.com/swisscom/cleanerversion/blob/becadbab5d7b474a0e9a596b99e97682402d2f2c/versions/descriptors.py#L395-L402
17,823
matsui528/nanopq
nanopq/pq.py
PQ.fit
def fit(self, vecs, iter=20, seed=123): """Given training vectors, run k-means for each sub-space and create codewords for each sub-space. This function should be run once first of all. Args: vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32. iter (int): The number of iteration for k-means seed (int): The seed for random process Returns: object: self """ assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert self.Ks < N, "the number of training vector should be more than Ks" assert D % self.M == 0, "input dimension must be dividable by M" self.Ds = int(D / self.M) np.random.seed(seed) if self.verbose: print("iter: {}, seed: {}".format(iter, seed)) # [m][ks][ds]: m-th subspace, ks-the codeword, ds-th dim self.codewords = np.zeros((self.M, self.Ks, self.Ds), dtype=np.float32) for m in range(self.M): if self.verbose: print("Training the subspace: {} / {}".format(m, self.M)) vecs_sub = vecs[:, m * self.Ds : (m+1) * self.Ds] self.codewords[m], _ = kmeans2(vecs_sub, self.Ks, iter=iter, minit='points') return self
python
def fit(self, vecs, iter=20, seed=123): """Given training vectors, run k-means for each sub-space and create codewords for each sub-space. This function should be run once first of all. Args: vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32. iter (int): The number of iteration for k-means seed (int): The seed for random process Returns: object: self """ assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert self.Ks < N, "the number of training vector should be more than Ks" assert D % self.M == 0, "input dimension must be dividable by M" self.Ds = int(D / self.M) np.random.seed(seed) if self.verbose: print("iter: {}, seed: {}".format(iter, seed)) # [m][ks][ds]: m-th subspace, ks-the codeword, ds-th dim self.codewords = np.zeros((self.M, self.Ks, self.Ds), dtype=np.float32) for m in range(self.M): if self.verbose: print("Training the subspace: {} / {}".format(m, self.M)) vecs_sub = vecs[:, m * self.Ds : (m+1) * self.Ds] self.codewords[m], _ = kmeans2(vecs_sub, self.Ks, iter=iter, minit='points') return self
[ "def", "fit", "(", "self", ",", "vecs", ",", "iter", "=", "20", ",", "seed", "=", "123", ")", ":", "assert", "vecs", ".", "dtype", "==", "np", ".", "float32", "assert", "vecs", ".", "ndim", "==", "2", "N", ",", "D", "=", "vecs", ".", "shape", "assert", "self", ".", "Ks", "<", "N", ",", "\"the number of training vector should be more than Ks\"", "assert", "D", "%", "self", ".", "M", "==", "0", ",", "\"input dimension must be dividable by M\"", "self", ".", "Ds", "=", "int", "(", "D", "/", "self", ".", "M", ")", "np", ".", "random", ".", "seed", "(", "seed", ")", "if", "self", ".", "verbose", ":", "print", "(", "\"iter: {}, seed: {}\"", ".", "format", "(", "iter", ",", "seed", ")", ")", "# [m][ks][ds]: m-th subspace, ks-the codeword, ds-th dim", "self", ".", "codewords", "=", "np", ".", "zeros", "(", "(", "self", ".", "M", ",", "self", ".", "Ks", ",", "self", ".", "Ds", ")", ",", "dtype", "=", "np", ".", "float32", ")", "for", "m", "in", "range", "(", "self", ".", "M", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "\"Training the subspace: {} / {}\"", ".", "format", "(", "m", ",", "self", ".", "M", ")", ")", "vecs_sub", "=", "vecs", "[", ":", ",", "m", "*", "self", ".", "Ds", ":", "(", "m", "+", "1", ")", "*", "self", ".", "Ds", "]", "self", ".", "codewords", "[", "m", "]", ",", "_", "=", "kmeans2", "(", "vecs_sub", ",", "self", ".", "Ks", ",", "iter", "=", "iter", ",", "minit", "=", "'points'", ")", "return", "self" ]
Given training vectors, run k-means for each sub-space and create codewords for each sub-space. This function should be run once first of all. Args: vecs (np.ndarray): Training vectors with shape=(N, D) and dtype=np.float32. iter (int): The number of iteration for k-means seed (int): The seed for random process Returns: object: self
[ "Given", "training", "vectors", "run", "k", "-", "means", "for", "each", "sub", "-", "space", "and", "create", "codewords", "for", "each", "sub", "-", "space", "." ]
1ce68cad2e3cab62b409e6dd63f676ed7b443ee9
https://github.com/matsui528/nanopq/blob/1ce68cad2e3cab62b409e6dd63f676ed7b443ee9/nanopq/pq.py#L53-L87
17,824
matsui528/nanopq
nanopq/pq.py
PQ.encode
def encode(self, vecs): """Encode input vectors into PQ-codes. Args: vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32. Returns: np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype """ assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert D == self.Ds * self.M, "input dimension must be Ds * M" # codes[n][m] : code of n-th vec, m-th subspace codes = np.empty((N, self.M), dtype=self.code_dtype) for m in range(self.M): if self.verbose: print("Encoding the subspace: {} / {}".format(m, self.M)) vecs_sub = vecs[:, m * self.Ds : (m+1) * self.Ds] codes[:, m], _ = vq(vecs_sub, self.codewords[m]) return codes
python
def encode(self, vecs): """Encode input vectors into PQ-codes. Args: vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32. Returns: np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype """ assert vecs.dtype == np.float32 assert vecs.ndim == 2 N, D = vecs.shape assert D == self.Ds * self.M, "input dimension must be Ds * M" # codes[n][m] : code of n-th vec, m-th subspace codes = np.empty((N, self.M), dtype=self.code_dtype) for m in range(self.M): if self.verbose: print("Encoding the subspace: {} / {}".format(m, self.M)) vecs_sub = vecs[:, m * self.Ds : (m+1) * self.Ds] codes[:, m], _ = vq(vecs_sub, self.codewords[m]) return codes
[ "def", "encode", "(", "self", ",", "vecs", ")", ":", "assert", "vecs", ".", "dtype", "==", "np", ".", "float32", "assert", "vecs", ".", "ndim", "==", "2", "N", ",", "D", "=", "vecs", ".", "shape", "assert", "D", "==", "self", ".", "Ds", "*", "self", ".", "M", ",", "\"input dimension must be Ds * M\"", "# codes[n][m] : code of n-th vec, m-th subspace", "codes", "=", "np", ".", "empty", "(", "(", "N", ",", "self", ".", "M", ")", ",", "dtype", "=", "self", ".", "code_dtype", ")", "for", "m", "in", "range", "(", "self", ".", "M", ")", ":", "if", "self", ".", "verbose", ":", "print", "(", "\"Encoding the subspace: {} / {}\"", ".", "format", "(", "m", ",", "self", ".", "M", ")", ")", "vecs_sub", "=", "vecs", "[", ":", ",", "m", "*", "self", ".", "Ds", ":", "(", "m", "+", "1", ")", "*", "self", ".", "Ds", "]", "codes", "[", ":", ",", "m", "]", ",", "_", "=", "vq", "(", "vecs_sub", ",", "self", ".", "codewords", "[", "m", "]", ")", "return", "codes" ]
Encode input vectors into PQ-codes. Args: vecs (np.ndarray): Input vectors with shape=(N, D) and dtype=np.float32. Returns: np.ndarray: PQ codes with shape=(N, M) and dtype=self.code_dtype
[ "Encode", "input", "vectors", "into", "PQ", "-", "codes", "." ]
1ce68cad2e3cab62b409e6dd63f676ed7b443ee9
https://github.com/matsui528/nanopq/blob/1ce68cad2e3cab62b409e6dd63f676ed7b443ee9/nanopq/pq.py#L89-L112
17,825
matsui528/nanopq
nanopq/pq.py
PQ.decode
def decode(self, codes): """Given PQ-codes, reconstruct original D-dimensional vectors approximately by fetching the codewords. Args: codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype. Each row is a PQ-code Returns: np.ndarray: Reconstructed vectors with shape=(N, D) and dtype=np.float32 """ assert codes.ndim == 2 N, M = codes.shape assert M == self.M assert codes.dtype == self.code_dtype vecs = np.empty((N, self.Ds * self.M), dtype=np.float32) for m in range(self.M): vecs[:, m * self.Ds : (m+1) * self.Ds] = self.codewords[m][codes[:, m], :] return vecs
python
def decode(self, codes): """Given PQ-codes, reconstruct original D-dimensional vectors approximately by fetching the codewords. Args: codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype. Each row is a PQ-code Returns: np.ndarray: Reconstructed vectors with shape=(N, D) and dtype=np.float32 """ assert codes.ndim == 2 N, M = codes.shape assert M == self.M assert codes.dtype == self.code_dtype vecs = np.empty((N, self.Ds * self.M), dtype=np.float32) for m in range(self.M): vecs[:, m * self.Ds : (m+1) * self.Ds] = self.codewords[m][codes[:, m], :] return vecs
[ "def", "decode", "(", "self", ",", "codes", ")", ":", "assert", "codes", ".", "ndim", "==", "2", "N", ",", "M", "=", "codes", ".", "shape", "assert", "M", "==", "self", ".", "M", "assert", "codes", ".", "dtype", "==", "self", ".", "code_dtype", "vecs", "=", "np", ".", "empty", "(", "(", "N", ",", "self", ".", "Ds", "*", "self", ".", "M", ")", ",", "dtype", "=", "np", ".", "float32", ")", "for", "m", "in", "range", "(", "self", ".", "M", ")", ":", "vecs", "[", ":", ",", "m", "*", "self", ".", "Ds", ":", "(", "m", "+", "1", ")", "*", "self", ".", "Ds", "]", "=", "self", ".", "codewords", "[", "m", "]", "[", "codes", "[", ":", ",", "m", "]", ",", ":", "]", "return", "vecs" ]
Given PQ-codes, reconstruct original D-dimensional vectors approximately by fetching the codewords. Args: codes (np.ndarray): PQ-cdoes with shape=(N, M) and dtype=self.code_dtype. Each row is a PQ-code Returns: np.ndarray: Reconstructed vectors with shape=(N, D) and dtype=np.float32
[ "Given", "PQ", "-", "codes", "reconstruct", "original", "D", "-", "dimensional", "vectors", "approximately", "by", "fetching", "the", "codewords", "." ]
1ce68cad2e3cab62b409e6dd63f676ed7b443ee9
https://github.com/matsui528/nanopq/blob/1ce68cad2e3cab62b409e6dd63f676ed7b443ee9/nanopq/pq.py#L114-L135
17,826
stephenmcd/hot-redis
hot_redis/client.py
transaction
def transaction(): """ Swaps out the current client with a pipeline instance, so that each Redis method call inside the context will be pipelined. Once the context is exited, we execute the pipeline. """ client = default_client() _thread.client = client.pipeline() try: yield _thread.client.execute() finally: _thread.client = client
python
def transaction(): """ Swaps out the current client with a pipeline instance, so that each Redis method call inside the context will be pipelined. Once the context is exited, we execute the pipeline. """ client = default_client() _thread.client = client.pipeline() try: yield _thread.client.execute() finally: _thread.client = client
[ "def", "transaction", "(", ")", ":", "client", "=", "default_client", "(", ")", "_thread", ".", "client", "=", "client", ".", "pipeline", "(", ")", "try", ":", "yield", "_thread", ".", "client", ".", "execute", "(", ")", "finally", ":", "_thread", ".", "client", "=", "client" ]
Swaps out the current client with a pipeline instance, so that each Redis method call inside the context will be pipelined. Once the context is exited, we execute the pipeline.
[ "Swaps", "out", "the", "current", "client", "with", "a", "pipeline", "instance", "so", "that", "each", "Redis", "method", "call", "inside", "the", "context", "will", "be", "pipelined", ".", "Once", "the", "context", "is", "exited", "we", "execute", "the", "pipeline", "." ]
6b0cf260c775fd98c44b6703030d33004dabf67d
https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/client.py#L78-L90
17,827
stephenmcd/hot-redis
hot_redis/client.py
HotClient._get_lua_path
def _get_lua_path(self, name): """ Joins the given name with the relative path of the module. """ parts = (os.path.dirname(os.path.abspath(__file__)), "lua", name) return os.path.join(*parts)
python
def _get_lua_path(self, name): """ Joins the given name with the relative path of the module. """ parts = (os.path.dirname(os.path.abspath(__file__)), "lua", name) return os.path.join(*parts)
[ "def", "_get_lua_path", "(", "self", ",", "name", ")", ":", "parts", "=", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "__file__", ")", ")", ",", "\"lua\"", ",", "name", ")", "return", "os", ".", "path", ".", "join", "(", "*", "parts", ")" ]
Joins the given name with the relative path of the module.
[ "Joins", "the", "given", "name", "with", "the", "relative", "path", "of", "the", "module", "." ]
6b0cf260c775fd98c44b6703030d33004dabf67d
https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/client.py#L27-L32
17,828
stephenmcd/hot-redis
hot_redis/client.py
HotClient._create_lua_method
def _create_lua_method(self, name, code): """ Registers the code snippet as a Lua script, and binds the script to the client as a method that can be called with the same signature as regular client methods, eg with a single key arg. """ script = self.register_script(code) setattr(script, "name", name) # Helps debugging redis lib. method = lambda key, *a, **k: script(keys=[key], args=a, **k) setattr(self, name, method)
python
def _create_lua_method(self, name, code): """ Registers the code snippet as a Lua script, and binds the script to the client as a method that can be called with the same signature as regular client methods, eg with a single key arg. """ script = self.register_script(code) setattr(script, "name", name) # Helps debugging redis lib. method = lambda key, *a, **k: script(keys=[key], args=a, **k) setattr(self, name, method)
[ "def", "_create_lua_method", "(", "self", ",", "name", ",", "code", ")", ":", "script", "=", "self", ".", "register_script", "(", "code", ")", "setattr", "(", "script", ",", "\"name\"", ",", "name", ")", "# Helps debugging redis lib.", "method", "=", "lambda", "key", ",", "*", "a", ",", "*", "*", "k", ":", "script", "(", "keys", "=", "[", "key", "]", ",", "args", "=", "a", ",", "*", "*", "k", ")", "setattr", "(", "self", ",", "name", ",", "method", ")" ]
Registers the code snippet as a Lua script, and binds the script to the client as a method that can be called with the same signature as regular client methods, eg with a single key arg.
[ "Registers", "the", "code", "snippet", "as", "a", "Lua", "script", "and", "binds", "the", "script", "to", "the", "client", "as", "a", "method", "that", "can", "be", "called", "with", "the", "same", "signature", "as", "regular", "client", "methods", "eg", "with", "a", "single", "key", "arg", "." ]
6b0cf260c775fd98c44b6703030d33004dabf67d
https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/client.py#L47-L57
17,829
stephenmcd/hot-redis
hot_redis/types.py
value_left
def value_left(self, other): """ Returns the value of the other type instance to use in an operator method, namely when the method's instance is on the left side of the expression. """ return other.value if isinstance(other, self.__class__) else other
python
def value_left(self, other): """ Returns the value of the other type instance to use in an operator method, namely when the method's instance is on the left side of the expression. """ return other.value if isinstance(other, self.__class__) else other
[ "def", "value_left", "(", "self", ",", "other", ")", ":", "return", "other", ".", "value", "if", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", "else", "other" ]
Returns the value of the other type instance to use in an operator method, namely when the method's instance is on the left side of the expression.
[ "Returns", "the", "value", "of", "the", "other", "type", "instance", "to", "use", "in", "an", "operator", "method", "namely", "when", "the", "method", "s", "instance", "is", "on", "the", "left", "side", "of", "the", "expression", "." ]
6b0cf260c775fd98c44b6703030d33004dabf67d
https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L28-L34
17,830
stephenmcd/hot-redis
hot_redis/types.py
value_right
def value_right(self, other): """ Returns the value of the type instance calling an to use in an operator method, namely when the method's instance is on the right side of the expression. """ return self if isinstance(other, self.__class__) else self.value
python
def value_right(self, other): """ Returns the value of the type instance calling an to use in an operator method, namely when the method's instance is on the right side of the expression. """ return self if isinstance(other, self.__class__) else self.value
[ "def", "value_right", "(", "self", ",", "other", ")", ":", "return", "self", "if", "isinstance", "(", "other", ",", "self", ".", "__class__", ")", "else", "self", ".", "value" ]
Returns the value of the type instance calling an to use in an operator method, namely when the method's instance is on the right side of the expression.
[ "Returns", "the", "value", "of", "the", "type", "instance", "calling", "an", "to", "use", "in", "an", "operator", "method", "namely", "when", "the", "method", "s", "instance", "is", "on", "the", "right", "side", "of", "the", "expression", "." ]
6b0cf260c775fd98c44b6703030d33004dabf67d
https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L37-L43
17,831
stephenmcd/hot-redis
hot_redis/types.py
op_left
def op_left(op): """ Returns a type instance method for the given operator, applied when the instance appears on the left side of the expression. """ def method(self, other): return op(self.value, value_left(self, other)) return method
python
def op_left(op): """ Returns a type instance method for the given operator, applied when the instance appears on the left side of the expression. """ def method(self, other): return op(self.value, value_left(self, other)) return method
[ "def", "op_left", "(", "op", ")", ":", "def", "method", "(", "self", ",", "other", ")", ":", "return", "op", "(", "self", ".", "value", ",", "value_left", "(", "self", ",", "other", ")", ")", "return", "method" ]
Returns a type instance method for the given operator, applied when the instance appears on the left side of the expression.
[ "Returns", "a", "type", "instance", "method", "for", "the", "given", "operator", "applied", "when", "the", "instance", "appears", "on", "the", "left", "side", "of", "the", "expression", "." ]
6b0cf260c775fd98c44b6703030d33004dabf67d
https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L46-L53
17,832
stephenmcd/hot-redis
hot_redis/types.py
op_right
def op_right(op): """ Returns a type instance method for the given operator, applied when the instance appears on the right side of the expression. """ def method(self, other): return op(value_left(self, other), value_right(self, other)) return method
python
def op_right(op): """ Returns a type instance method for the given operator, applied when the instance appears on the right side of the expression. """ def method(self, other): return op(value_left(self, other), value_right(self, other)) return method
[ "def", "op_right", "(", "op", ")", ":", "def", "method", "(", "self", ",", "other", ")", ":", "return", "op", "(", "value_left", "(", "self", ",", "other", ")", ",", "value_right", "(", "self", ",", "other", ")", ")", "return", "method" ]
Returns a type instance method for the given operator, applied when the instance appears on the right side of the expression.
[ "Returns", "a", "type", "instance", "method", "for", "the", "given", "operator", "applied", "when", "the", "instance", "appears", "on", "the", "right", "side", "of", "the", "expression", "." ]
6b0cf260c775fd98c44b6703030d33004dabf67d
https://github.com/stephenmcd/hot-redis/blob/6b0cf260c775fd98c44b6703030d33004dabf67d/hot_redis/types.py#L56-L63
17,833
jfhbrook/pyee
pyee/_base.py
BaseEventEmitter.on
def on(self, event, f=None): """Registers the function ``f`` to the event name ``event``. If ``f`` isn't provided, this method returns a function that takes ``f`` as a callback; in other words, you can use this method as a decorator, like so:: @ee.on('data') def data_handler(data): print(data) In both the decorated and undecorated forms, the event handler is returned. The upshot of this is that you can call decorated handlers directly, as well as use them in remove_listener calls. """ def _on(f): self._add_event_handler(event, f, f) return f if f is None: return _on else: return _on(f)
python
def on(self, event, f=None): """Registers the function ``f`` to the event name ``event``. If ``f`` isn't provided, this method returns a function that takes ``f`` as a callback; in other words, you can use this method as a decorator, like so:: @ee.on('data') def data_handler(data): print(data) In both the decorated and undecorated forms, the event handler is returned. The upshot of this is that you can call decorated handlers directly, as well as use them in remove_listener calls. """ def _on(f): self._add_event_handler(event, f, f) return f if f is None: return _on else: return _on(f)
[ "def", "on", "(", "self", ",", "event", ",", "f", "=", "None", ")", ":", "def", "_on", "(", "f", ")", ":", "self", ".", "_add_event_handler", "(", "event", ",", "f", ",", "f", ")", "return", "f", "if", "f", "is", "None", ":", "return", "_on", "else", ":", "return", "_on", "(", "f", ")" ]
Registers the function ``f`` to the event name ``event``. If ``f`` isn't provided, this method returns a function that takes ``f`` as a callback; in other words, you can use this method as a decorator, like so:: @ee.on('data') def data_handler(data): print(data) In both the decorated and undecorated forms, the event handler is returned. The upshot of this is that you can call decorated handlers directly, as well as use them in remove_listener calls.
[ "Registers", "the", "function", "f", "to", "the", "event", "name", "event", "." ]
f5896239f421381e8b787c61c6185e33defb0292
https://github.com/jfhbrook/pyee/blob/f5896239f421381e8b787c61c6185e33defb0292/pyee/_base.py#L42-L65
17,834
jfhbrook/pyee
pyee/_base.py
BaseEventEmitter.once
def once(self, event, f=None): """The same as ``ee.on``, except that the listener is automatically removed after being called. """ def _wrapper(f): def g(*args, **kwargs): self.remove_listener(event, f) # f may return a coroutine, so we need to return that # result here so that emit can schedule it return f(*args, **kwargs) self._add_event_handler(event, f, g) return f if f is None: return _wrapper else: return _wrapper(f)
python
def once(self, event, f=None): """The same as ``ee.on``, except that the listener is automatically removed after being called. """ def _wrapper(f): def g(*args, **kwargs): self.remove_listener(event, f) # f may return a coroutine, so we need to return that # result here so that emit can schedule it return f(*args, **kwargs) self._add_event_handler(event, f, g) return f if f is None: return _wrapper else: return _wrapper(f)
[ "def", "once", "(", "self", ",", "event", ",", "f", "=", "None", ")", ":", "def", "_wrapper", "(", "f", ")", ":", "def", "g", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "remove_listener", "(", "event", ",", "f", ")", "# f may return a coroutine, so we need to return that", "# result here so that emit can schedule it", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "_add_event_handler", "(", "event", ",", "f", ",", "g", ")", "return", "f", "if", "f", "is", "None", ":", "return", "_wrapper", "else", ":", "return", "_wrapper", "(", "f", ")" ]
The same as ``ee.on``, except that the listener is automatically removed after being called.
[ "The", "same", "as", "ee", ".", "on", "except", "that", "the", "listener", "is", "automatically", "removed", "after", "being", "called", "." ]
f5896239f421381e8b787c61c6185e33defb0292
https://github.com/jfhbrook/pyee/blob/f5896239f421381e8b787c61c6185e33defb0292/pyee/_base.py#L110-L127
17,835
jfhbrook/pyee
pyee/_base.py
BaseEventEmitter.remove_all_listeners
def remove_all_listeners(self, event=None): """Remove all listeners attached to ``event``. If ``event`` is ``None``, remove all listeners on all events. """ if event is not None: self._events[event] = OrderedDict() else: self._events = defaultdict(OrderedDict)
python
def remove_all_listeners(self, event=None): """Remove all listeners attached to ``event``. If ``event`` is ``None``, remove all listeners on all events. """ if event is not None: self._events[event] = OrderedDict() else: self._events = defaultdict(OrderedDict)
[ "def", "remove_all_listeners", "(", "self", ",", "event", "=", "None", ")", ":", "if", "event", "is", "not", "None", ":", "self", ".", "_events", "[", "event", "]", "=", "OrderedDict", "(", ")", "else", ":", "self", ".", "_events", "=", "defaultdict", "(", "OrderedDict", ")" ]
Remove all listeners attached to ``event``. If ``event`` is ``None``, remove all listeners on all events.
[ "Remove", "all", "listeners", "attached", "to", "event", ".", "If", "event", "is", "None", "remove", "all", "listeners", "on", "all", "events", "." ]
f5896239f421381e8b787c61c6185e33defb0292
https://github.com/jfhbrook/pyee/blob/f5896239f421381e8b787c61c6185e33defb0292/pyee/_base.py#L133-L140
17,836
scott-griffiths/bitstring
bitstring.py
offsetcopy
def offsetcopy(s, newoffset): """Return a copy of a ByteStore with the newoffset. Not part of public interface. """ assert 0 <= newoffset < 8 if not s.bitlength: return copy.copy(s) else: if newoffset == s.offset % 8: return ByteStore(s.getbyteslice(s.byteoffset, s.byteoffset + s.bytelength), s.bitlength, newoffset) newdata = [] d = s._rawarray assert newoffset != s.offset % 8 if newoffset < s.offset % 8: # We need to shift everything left shiftleft = s.offset % 8 - newoffset # First deal with everything except for the final byte for x in range(s.byteoffset, s.byteoffset + s.bytelength - 1): newdata.append(((d[x] << shiftleft) & 0xff) +\ (d[x + 1] >> (8 - shiftleft))) bits_in_last_byte = (s.offset + s.bitlength) % 8 if not bits_in_last_byte: bits_in_last_byte = 8 if bits_in_last_byte > shiftleft: newdata.append((d[s.byteoffset + s.bytelength - 1] << shiftleft) & 0xff) else: # newoffset > s._offset % 8 shiftright = newoffset - s.offset % 8 newdata.append(s.getbyte(0) >> shiftright) for x in range(s.byteoffset + 1, s.byteoffset + s.bytelength): newdata.append(((d[x - 1] << (8 - shiftright)) & 0xff) +\ (d[x] >> shiftright)) bits_in_last_byte = (s.offset + s.bitlength) % 8 if not bits_in_last_byte: bits_in_last_byte = 8 if bits_in_last_byte + shiftright > 8: newdata.append((d[s.byteoffset + s.bytelength - 1] << (8 - shiftright)) & 0xff) new_s = ByteStore(bytearray(newdata), s.bitlength, newoffset) assert new_s.offset == newoffset return new_s
python
def offsetcopy(s, newoffset): """Return a copy of a ByteStore with the newoffset. Not part of public interface. """ assert 0 <= newoffset < 8 if not s.bitlength: return copy.copy(s) else: if newoffset == s.offset % 8: return ByteStore(s.getbyteslice(s.byteoffset, s.byteoffset + s.bytelength), s.bitlength, newoffset) newdata = [] d = s._rawarray assert newoffset != s.offset % 8 if newoffset < s.offset % 8: # We need to shift everything left shiftleft = s.offset % 8 - newoffset # First deal with everything except for the final byte for x in range(s.byteoffset, s.byteoffset + s.bytelength - 1): newdata.append(((d[x] << shiftleft) & 0xff) +\ (d[x + 1] >> (8 - shiftleft))) bits_in_last_byte = (s.offset + s.bitlength) % 8 if not bits_in_last_byte: bits_in_last_byte = 8 if bits_in_last_byte > shiftleft: newdata.append((d[s.byteoffset + s.bytelength - 1] << shiftleft) & 0xff) else: # newoffset > s._offset % 8 shiftright = newoffset - s.offset % 8 newdata.append(s.getbyte(0) >> shiftright) for x in range(s.byteoffset + 1, s.byteoffset + s.bytelength): newdata.append(((d[x - 1] << (8 - shiftright)) & 0xff) +\ (d[x] >> shiftright)) bits_in_last_byte = (s.offset + s.bitlength) % 8 if not bits_in_last_byte: bits_in_last_byte = 8 if bits_in_last_byte + shiftright > 8: newdata.append((d[s.byteoffset + s.bytelength - 1] << (8 - shiftright)) & 0xff) new_s = ByteStore(bytearray(newdata), s.bitlength, newoffset) assert new_s.offset == newoffset return new_s
[ "def", "offsetcopy", "(", "s", ",", "newoffset", ")", ":", "assert", "0", "<=", "newoffset", "<", "8", "if", "not", "s", ".", "bitlength", ":", "return", "copy", ".", "copy", "(", "s", ")", "else", ":", "if", "newoffset", "==", "s", ".", "offset", "%", "8", ":", "return", "ByteStore", "(", "s", ".", "getbyteslice", "(", "s", ".", "byteoffset", ",", "s", ".", "byteoffset", "+", "s", ".", "bytelength", ")", ",", "s", ".", "bitlength", ",", "newoffset", ")", "newdata", "=", "[", "]", "d", "=", "s", ".", "_rawarray", "assert", "newoffset", "!=", "s", ".", "offset", "%", "8", "if", "newoffset", "<", "s", ".", "offset", "%", "8", ":", "# We need to shift everything left", "shiftleft", "=", "s", ".", "offset", "%", "8", "-", "newoffset", "# First deal with everything except for the final byte", "for", "x", "in", "range", "(", "s", ".", "byteoffset", ",", "s", ".", "byteoffset", "+", "s", ".", "bytelength", "-", "1", ")", ":", "newdata", ".", "append", "(", "(", "(", "d", "[", "x", "]", "<<", "shiftleft", ")", "&", "0xff", ")", "+", "(", "d", "[", "x", "+", "1", "]", ">>", "(", "8", "-", "shiftleft", ")", ")", ")", "bits_in_last_byte", "=", "(", "s", ".", "offset", "+", "s", ".", "bitlength", ")", "%", "8", "if", "not", "bits_in_last_byte", ":", "bits_in_last_byte", "=", "8", "if", "bits_in_last_byte", ">", "shiftleft", ":", "newdata", ".", "append", "(", "(", "d", "[", "s", ".", "byteoffset", "+", "s", ".", "bytelength", "-", "1", "]", "<<", "shiftleft", ")", "&", "0xff", ")", "else", ":", "# newoffset > s._offset % 8", "shiftright", "=", "newoffset", "-", "s", ".", "offset", "%", "8", "newdata", ".", "append", "(", "s", ".", "getbyte", "(", "0", ")", ">>", "shiftright", ")", "for", "x", "in", "range", "(", "s", ".", "byteoffset", "+", "1", ",", "s", ".", "byteoffset", "+", "s", ".", "bytelength", ")", ":", "newdata", ".", "append", "(", "(", "(", "d", "[", "x", "-", "1", "]", "<<", "(", "8", "-", "shiftright", ")", ")", "&", "0xff", ")", "+", "(", "d", "[", "x", "]", ">>", "shiftright", ")", ")", "bits_in_last_byte", "=", "(", "s", ".", "offset", "+", "s", ".", "bitlength", ")", "%", "8", "if", "not", "bits_in_last_byte", ":", "bits_in_last_byte", "=", "8", "if", "bits_in_last_byte", "+", "shiftright", ">", "8", ":", "newdata", ".", "append", "(", "(", "d", "[", "s", ".", "byteoffset", "+", "s", ".", "bytelength", "-", "1", "]", "<<", "(", "8", "-", "shiftright", ")", ")", "&", "0xff", ")", "new_s", "=", "ByteStore", "(", "bytearray", "(", "newdata", ")", ",", "s", ".", "bitlength", ",", "newoffset", ")", "assert", "new_s", ".", "offset", "==", "newoffset", "return", "new_s" ]
Return a copy of a ByteStore with the newoffset. Not part of public interface.
[ "Return", "a", "copy", "of", "a", "ByteStore", "with", "the", "newoffset", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L248-L287
17,837
scott-griffiths/bitstring
bitstring.py
structparser
def structparser(token): """Parse struct-like format string token into sub-token list.""" m = STRUCT_PACK_RE.match(token) if not m: return [token] else: endian = m.group('endian') if endian is None: return [token] # Split the format string into a list of 'q', '4h' etc. formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt')) # Now deal with mulitiplicative factors, 4h -> hhhh etc. fmt = ''.join([f[-1] * int(f[:-1]) if len(f) != 1 else f for f in formatlist]) if endian == '@': # Native endianness if byteorder == 'little': endian = '<' else: assert byteorder == 'big' endian = '>' if endian == '<': tokens = [REPLACEMENTS_LE[c] for c in fmt] else: assert endian == '>' tokens = [REPLACEMENTS_BE[c] for c in fmt] return tokens
python
def structparser(token): """Parse struct-like format string token into sub-token list.""" m = STRUCT_PACK_RE.match(token) if not m: return [token] else: endian = m.group('endian') if endian is None: return [token] # Split the format string into a list of 'q', '4h' etc. formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt')) # Now deal with mulitiplicative factors, 4h -> hhhh etc. fmt = ''.join([f[-1] * int(f[:-1]) if len(f) != 1 else f for f in formatlist]) if endian == '@': # Native endianness if byteorder == 'little': endian = '<' else: assert byteorder == 'big' endian = '>' if endian == '<': tokens = [REPLACEMENTS_LE[c] for c in fmt] else: assert endian == '>' tokens = [REPLACEMENTS_BE[c] for c in fmt] return tokens
[ "def", "structparser", "(", "token", ")", ":", "m", "=", "STRUCT_PACK_RE", ".", "match", "(", "token", ")", "if", "not", "m", ":", "return", "[", "token", "]", "else", ":", "endian", "=", "m", ".", "group", "(", "'endian'", ")", "if", "endian", "is", "None", ":", "return", "[", "token", "]", "# Split the format string into a list of 'q', '4h' etc.", "formatlist", "=", "re", ".", "findall", "(", "STRUCT_SPLIT_RE", ",", "m", ".", "group", "(", "'fmt'", ")", ")", "# Now deal with mulitiplicative factors, 4h -> hhhh etc.", "fmt", "=", "''", ".", "join", "(", "[", "f", "[", "-", "1", "]", "*", "int", "(", "f", "[", ":", "-", "1", "]", ")", "if", "len", "(", "f", ")", "!=", "1", "else", "f", "for", "f", "in", "formatlist", "]", ")", "if", "endian", "==", "'@'", ":", "# Native endianness", "if", "byteorder", "==", "'little'", ":", "endian", "=", "'<'", "else", ":", "assert", "byteorder", "==", "'big'", "endian", "=", "'>'", "if", "endian", "==", "'<'", ":", "tokens", "=", "[", "REPLACEMENTS_LE", "[", "c", "]", "for", "c", "in", "fmt", "]", "else", ":", "assert", "endian", "==", "'>'", "tokens", "=", "[", "REPLACEMENTS_BE", "[", "c", "]", "for", "c", "in", "fmt", "]", "return", "tokens" ]
Parse struct-like format string token into sub-token list.
[ "Parse", "struct", "-", "like", "format", "string", "token", "into", "sub", "-", "token", "list", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L506-L532
17,838
scott-griffiths/bitstring
bitstring.py
tokenparser
def tokenparser(fmt, keys=None, token_cache={}): """Divide the format string into tokens and parse them. Return stretchy token and list of [initialiser, length, value] initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc. length is None if not known, as is value. If the token is in the keyword dictionary (keys) then it counts as a special case and isn't messed with. tokens must be of the form: [factor*][initialiser][:][length][=value] """ try: return token_cache[(fmt, keys)] except KeyError: token_key = (fmt, keys) # Very inefficient expanding of brackets. fmt = expand_brackets(fmt) # Split tokens by ',' and remove whitespace # The meta_tokens can either be ordinary single tokens or multiple # struct-format token strings. meta_tokens = (''.join(f.split()) for f in fmt.split(',')) return_values = [] stretchy_token = False for meta_token in meta_tokens: # See if it has a multiplicative factor m = MULTIPLICATIVE_RE.match(meta_token) if not m: factor = 1 else: factor = int(m.group('factor')) meta_token = m.group('token') # See if it's a struct-like format tokens = structparser(meta_token) ret_vals = [] for token in tokens: if keys and token in keys: # Don't bother parsing it, it's a keyword argument ret_vals.append([token, None, None]) continue value = length = None if token == '': continue # Match literal tokens of the form 0x... 0o... and 0b... m = LITERAL_RE.match(token) if m: name = m.group('name') value = m.group('value') ret_vals.append([name, length, value]) continue # Match everything else: m1 = TOKEN_RE.match(token) if not m1: # and if you don't specify a 'name' then the default is 'uint': m2 = DEFAULT_UINT.match(token) if not m2: raise ValueError("Don't understand token '{0}'.".format(token)) if m1: name = m1.group('name') length = m1.group('len') if m1.group('value'): value = m1.group('value') else: assert m2 name = 'uint' length = m2.group('len') if m2.group('value'): value = m2.group('value') if name == 'bool': if length is not None: raise ValueError("You can't specify a length with bool tokens - they are always one bit.") length = 1 if length is None and name not in ('se', 'ue', 'sie', 'uie'): stretchy_token = True if length is not None: # Try converting length to int, otherwise check it's a key. try: length = int(length) if length < 0: raise Error # For the 'bytes' token convert length to bits. if name == 'bytes': length *= 8 except Error: raise ValueError("Can't read a token with a negative length.") except ValueError: if not keys or length not in keys: raise ValueError("Don't understand length '{0}' of token.".format(length)) ret_vals.append([name, length, value]) # This multiplies by the multiplicative factor, but this means that # we can't allow keyword values as multipliers (e.g. n*uint:8). # The only way to do this would be to return the factor in some fashion # (we can't use the key's value here as it would mean that we couldn't # sensibly continue to cache the function's results. (TODO). return_values.extend(ret_vals * factor) return_values = [tuple(x) for x in return_values] if len(token_cache) < CACHE_SIZE: token_cache[token_key] = stretchy_token, return_values return stretchy_token, return_values
python
def tokenparser(fmt, keys=None, token_cache={}): """Divide the format string into tokens and parse them. Return stretchy token and list of [initialiser, length, value] initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc. length is None if not known, as is value. If the token is in the keyword dictionary (keys) then it counts as a special case and isn't messed with. tokens must be of the form: [factor*][initialiser][:][length][=value] """ try: return token_cache[(fmt, keys)] except KeyError: token_key = (fmt, keys) # Very inefficient expanding of brackets. fmt = expand_brackets(fmt) # Split tokens by ',' and remove whitespace # The meta_tokens can either be ordinary single tokens or multiple # struct-format token strings. meta_tokens = (''.join(f.split()) for f in fmt.split(',')) return_values = [] stretchy_token = False for meta_token in meta_tokens: # See if it has a multiplicative factor m = MULTIPLICATIVE_RE.match(meta_token) if not m: factor = 1 else: factor = int(m.group('factor')) meta_token = m.group('token') # See if it's a struct-like format tokens = structparser(meta_token) ret_vals = [] for token in tokens: if keys and token in keys: # Don't bother parsing it, it's a keyword argument ret_vals.append([token, None, None]) continue value = length = None if token == '': continue # Match literal tokens of the form 0x... 0o... and 0b... m = LITERAL_RE.match(token) if m: name = m.group('name') value = m.group('value') ret_vals.append([name, length, value]) continue # Match everything else: m1 = TOKEN_RE.match(token) if not m1: # and if you don't specify a 'name' then the default is 'uint': m2 = DEFAULT_UINT.match(token) if not m2: raise ValueError("Don't understand token '{0}'.".format(token)) if m1: name = m1.group('name') length = m1.group('len') if m1.group('value'): value = m1.group('value') else: assert m2 name = 'uint' length = m2.group('len') if m2.group('value'): value = m2.group('value') if name == 'bool': if length is not None: raise ValueError("You can't specify a length with bool tokens - they are always one bit.") length = 1 if length is None and name not in ('se', 'ue', 'sie', 'uie'): stretchy_token = True if length is not None: # Try converting length to int, otherwise check it's a key. try: length = int(length) if length < 0: raise Error # For the 'bytes' token convert length to bits. if name == 'bytes': length *= 8 except Error: raise ValueError("Can't read a token with a negative length.") except ValueError: if not keys or length not in keys: raise ValueError("Don't understand length '{0}' of token.".format(length)) ret_vals.append([name, length, value]) # This multiplies by the multiplicative factor, but this means that # we can't allow keyword values as multipliers (e.g. n*uint:8). # The only way to do this would be to return the factor in some fashion # (we can't use the key's value here as it would mean that we couldn't # sensibly continue to cache the function's results. (TODO). return_values.extend(ret_vals * factor) return_values = [tuple(x) for x in return_values] if len(token_cache) < CACHE_SIZE: token_cache[token_key] = stretchy_token, return_values return stretchy_token, return_values
[ "def", "tokenparser", "(", "fmt", ",", "keys", "=", "None", ",", "token_cache", "=", "{", "}", ")", ":", "try", ":", "return", "token_cache", "[", "(", "fmt", ",", "keys", ")", "]", "except", "KeyError", ":", "token_key", "=", "(", "fmt", ",", "keys", ")", "# Very inefficient expanding of brackets.", "fmt", "=", "expand_brackets", "(", "fmt", ")", "# Split tokens by ',' and remove whitespace", "# The meta_tokens can either be ordinary single tokens or multiple", "# struct-format token strings.", "meta_tokens", "=", "(", "''", ".", "join", "(", "f", ".", "split", "(", ")", ")", "for", "f", "in", "fmt", ".", "split", "(", "','", ")", ")", "return_values", "=", "[", "]", "stretchy_token", "=", "False", "for", "meta_token", "in", "meta_tokens", ":", "# See if it has a multiplicative factor", "m", "=", "MULTIPLICATIVE_RE", ".", "match", "(", "meta_token", ")", "if", "not", "m", ":", "factor", "=", "1", "else", ":", "factor", "=", "int", "(", "m", ".", "group", "(", "'factor'", ")", ")", "meta_token", "=", "m", ".", "group", "(", "'token'", ")", "# See if it's a struct-like format", "tokens", "=", "structparser", "(", "meta_token", ")", "ret_vals", "=", "[", "]", "for", "token", "in", "tokens", ":", "if", "keys", "and", "token", "in", "keys", ":", "# Don't bother parsing it, it's a keyword argument", "ret_vals", ".", "append", "(", "[", "token", ",", "None", ",", "None", "]", ")", "continue", "value", "=", "length", "=", "None", "if", "token", "==", "''", ":", "continue", "# Match literal tokens of the form 0x... 0o... and 0b...", "m", "=", "LITERAL_RE", ".", "match", "(", "token", ")", "if", "m", ":", "name", "=", "m", ".", "group", "(", "'name'", ")", "value", "=", "m", ".", "group", "(", "'value'", ")", "ret_vals", ".", "append", "(", "[", "name", ",", "length", ",", "value", "]", ")", "continue", "# Match everything else:", "m1", "=", "TOKEN_RE", ".", "match", "(", "token", ")", "if", "not", "m1", ":", "# and if you don't specify a 'name' then the default is 'uint':", "m2", "=", "DEFAULT_UINT", ".", "match", "(", "token", ")", "if", "not", "m2", ":", "raise", "ValueError", "(", "\"Don't understand token '{0}'.\"", ".", "format", "(", "token", ")", ")", "if", "m1", ":", "name", "=", "m1", ".", "group", "(", "'name'", ")", "length", "=", "m1", ".", "group", "(", "'len'", ")", "if", "m1", ".", "group", "(", "'value'", ")", ":", "value", "=", "m1", ".", "group", "(", "'value'", ")", "else", ":", "assert", "m2", "name", "=", "'uint'", "length", "=", "m2", ".", "group", "(", "'len'", ")", "if", "m2", ".", "group", "(", "'value'", ")", ":", "value", "=", "m2", ".", "group", "(", "'value'", ")", "if", "name", "==", "'bool'", ":", "if", "length", "is", "not", "None", ":", "raise", "ValueError", "(", "\"You can't specify a length with bool tokens - they are always one bit.\"", ")", "length", "=", "1", "if", "length", "is", "None", "and", "name", "not", "in", "(", "'se'", ",", "'ue'", ",", "'sie'", ",", "'uie'", ")", ":", "stretchy_token", "=", "True", "if", "length", "is", "not", "None", ":", "# Try converting length to int, otherwise check it's a key.", "try", ":", "length", "=", "int", "(", "length", ")", "if", "length", "<", "0", ":", "raise", "Error", "# For the 'bytes' token convert length to bits.", "if", "name", "==", "'bytes'", ":", "length", "*=", "8", "except", "Error", ":", "raise", "ValueError", "(", "\"Can't read a token with a negative length.\"", ")", "except", "ValueError", ":", "if", "not", "keys", "or", "length", "not", "in", "keys", ":", "raise", "ValueError", "(", "\"Don't understand length '{0}' of token.\"", ".", "format", "(", "length", ")", ")", "ret_vals", ".", "append", "(", "[", "name", ",", "length", ",", "value", "]", ")", "# This multiplies by the multiplicative factor, but this means that", "# we can't allow keyword values as multipliers (e.g. n*uint:8).", "# The only way to do this would be to return the factor in some fashion", "# (we can't use the key's value here as it would mean that we couldn't", "# sensibly continue to cache the function's results. (TODO).", "return_values", ".", "extend", "(", "ret_vals", "*", "factor", ")", "return_values", "=", "[", "tuple", "(", "x", ")", "for", "x", "in", "return_values", "]", "if", "len", "(", "token_cache", ")", "<", "CACHE_SIZE", ":", "token_cache", "[", "token_key", "]", "=", "stretchy_token", ",", "return_values", "return", "stretchy_token", ",", "return_values" ]
Divide the format string into tokens and parse them. Return stretchy token and list of [initialiser, length, value] initialiser is one of: hex, oct, bin, uint, int, se, ue, 0x, 0o, 0b etc. length is None if not known, as is value. If the token is in the keyword dictionary (keys) then it counts as a special case and isn't messed with. tokens must be of the form: [factor*][initialiser][:][length][=value]
[ "Divide", "the", "format", "string", "into", "tokens", "and", "parse", "them", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L534-L633
17,839
scott-griffiths/bitstring
bitstring.py
expand_brackets
def expand_brackets(s): """Remove whitespace and expand all brackets.""" s = ''.join(s.split()) while True: start = s.find('(') if start == -1: break count = 1 # Number of hanging open brackets p = start + 1 while p < len(s): if s[p] == '(': count += 1 if s[p] == ')': count -= 1 if not count: break p += 1 if count: raise ValueError("Unbalanced parenthesis in '{0}'.".format(s)) if start == 0 or s[start - 1] != '*': s = s[0:start] + s[start + 1:p] + s[p + 1:] else: m = BRACKET_RE.search(s) if m: factor = int(m.group('factor')) matchstart = m.start('factor') s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] + ',') + s[start + 1:p] + s[p + 1:] else: raise ValueError("Failed to parse '{0}'.".format(s)) return s
python
def expand_brackets(s): """Remove whitespace and expand all brackets.""" s = ''.join(s.split()) while True: start = s.find('(') if start == -1: break count = 1 # Number of hanging open brackets p = start + 1 while p < len(s): if s[p] == '(': count += 1 if s[p] == ')': count -= 1 if not count: break p += 1 if count: raise ValueError("Unbalanced parenthesis in '{0}'.".format(s)) if start == 0 or s[start - 1] != '*': s = s[0:start] + s[start + 1:p] + s[p + 1:] else: m = BRACKET_RE.search(s) if m: factor = int(m.group('factor')) matchstart = m.start('factor') s = s[0:matchstart] + (factor - 1) * (s[start + 1:p] + ',') + s[start + 1:p] + s[p + 1:] else: raise ValueError("Failed to parse '{0}'.".format(s)) return s
[ "def", "expand_brackets", "(", "s", ")", ":", "s", "=", "''", ".", "join", "(", "s", ".", "split", "(", ")", ")", "while", "True", ":", "start", "=", "s", ".", "find", "(", "'('", ")", "if", "start", "==", "-", "1", ":", "break", "count", "=", "1", "# Number of hanging open brackets", "p", "=", "start", "+", "1", "while", "p", "<", "len", "(", "s", ")", ":", "if", "s", "[", "p", "]", "==", "'('", ":", "count", "+=", "1", "if", "s", "[", "p", "]", "==", "')'", ":", "count", "-=", "1", "if", "not", "count", ":", "break", "p", "+=", "1", "if", "count", ":", "raise", "ValueError", "(", "\"Unbalanced parenthesis in '{0}'.\"", ".", "format", "(", "s", ")", ")", "if", "start", "==", "0", "or", "s", "[", "start", "-", "1", "]", "!=", "'*'", ":", "s", "=", "s", "[", "0", ":", "start", "]", "+", "s", "[", "start", "+", "1", ":", "p", "]", "+", "s", "[", "p", "+", "1", ":", "]", "else", ":", "m", "=", "BRACKET_RE", ".", "search", "(", "s", ")", "if", "m", ":", "factor", "=", "int", "(", "m", ".", "group", "(", "'factor'", ")", ")", "matchstart", "=", "m", ".", "start", "(", "'factor'", ")", "s", "=", "s", "[", "0", ":", "matchstart", "]", "+", "(", "factor", "-", "1", ")", "*", "(", "s", "[", "start", "+", "1", ":", "p", "]", "+", "','", ")", "+", "s", "[", "start", "+", "1", ":", "p", "]", "+", "s", "[", "p", "+", "1", ":", "]", "else", ":", "raise", "ValueError", "(", "\"Failed to parse '{0}'.\"", ".", "format", "(", "s", ")", ")", "return", "s" ]
Remove whitespace and expand all brackets.
[ "Remove", "whitespace", "and", "expand", "all", "brackets", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L638-L667
17,840
scott-griffiths/bitstring
bitstring.py
pack
def pack(fmt, *values, **kwargs): """Pack the values according to the format string and return a new BitStream. fmt -- A single string or a list of strings with comma separated tokens describing how to create the BitStream. values -- Zero or more values to pack according to the format. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string will be replaced with their given value. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' / 'uie': next bits as unsigned exp-Golomb code 'se' / 'sie': next bits as signed exp-Golomb code 'bits:5' : 5 bits as a bitstring object 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 zero bits as padding >>> s = pack('uint:12, bits', 100, '0xffe') >>> t = pack(['bits', 'bin:3'], s, '111') >>> u = pack('uint:8=a, uint:8=b, uint:55=a', a=6, b=44) """ tokens = [] if isinstance(fmt, basestring): fmt = [fmt] try: for f_item in fmt: _, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys()))) tokens.extend(tkns) except ValueError as e: raise CreationError(*e.args) value_iter = iter(values) s = BitStream() try: for name, length, value in tokens: # If the value is in the kwd dictionary then it takes precedence. if value in kwargs: value = kwargs[value] # If the length is in the kwd dictionary then use that too. if length in kwargs: length = kwargs[length] # Also if we just have a dictionary name then we want to use it if name in kwargs and length is None and value is None: s.append(kwargs[name]) continue if length is not None: length = int(length) if value is None and name != 'pad': # Take the next value from the ones provided value = next(value_iter) s._append(BitStream._init_with_token(name, length, value)) except StopIteration: raise CreationError("Not enough parameters present to pack according to the " "format. {0} values are needed.", len(tokens)) try: next(value_iter) except StopIteration: # Good, we've used up all the *values. return s raise CreationError("Too many parameters present to pack according to the format.")
python
def pack(fmt, *values, **kwargs): """Pack the values according to the format string and return a new BitStream. fmt -- A single string or a list of strings with comma separated tokens describing how to create the BitStream. values -- Zero or more values to pack according to the format. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string will be replaced with their given value. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' / 'uie': next bits as unsigned exp-Golomb code 'se' / 'sie': next bits as signed exp-Golomb code 'bits:5' : 5 bits as a bitstring object 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 zero bits as padding >>> s = pack('uint:12, bits', 100, '0xffe') >>> t = pack(['bits', 'bin:3'], s, '111') >>> u = pack('uint:8=a, uint:8=b, uint:55=a', a=6, b=44) """ tokens = [] if isinstance(fmt, basestring): fmt = [fmt] try: for f_item in fmt: _, tkns = tokenparser(f_item, tuple(sorted(kwargs.keys()))) tokens.extend(tkns) except ValueError as e: raise CreationError(*e.args) value_iter = iter(values) s = BitStream() try: for name, length, value in tokens: # If the value is in the kwd dictionary then it takes precedence. if value in kwargs: value = kwargs[value] # If the length is in the kwd dictionary then use that too. if length in kwargs: length = kwargs[length] # Also if we just have a dictionary name then we want to use it if name in kwargs and length is None and value is None: s.append(kwargs[name]) continue if length is not None: length = int(length) if value is None and name != 'pad': # Take the next value from the ones provided value = next(value_iter) s._append(BitStream._init_with_token(name, length, value)) except StopIteration: raise CreationError("Not enough parameters present to pack according to the " "format. {0} values are needed.", len(tokens)) try: next(value_iter) except StopIteration: # Good, we've used up all the *values. return s raise CreationError("Too many parameters present to pack according to the format.")
[ "def", "pack", "(", "fmt", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "tokens", "=", "[", "]", "if", "isinstance", "(", "fmt", ",", "basestring", ")", ":", "fmt", "=", "[", "fmt", "]", "try", ":", "for", "f_item", "in", "fmt", ":", "_", ",", "tkns", "=", "tokenparser", "(", "f_item", ",", "tuple", "(", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", ")", ")", "tokens", ".", "extend", "(", "tkns", ")", "except", "ValueError", "as", "e", ":", "raise", "CreationError", "(", "*", "e", ".", "args", ")", "value_iter", "=", "iter", "(", "values", ")", "s", "=", "BitStream", "(", ")", "try", ":", "for", "name", ",", "length", ",", "value", "in", "tokens", ":", "# If the value is in the kwd dictionary then it takes precedence.", "if", "value", "in", "kwargs", ":", "value", "=", "kwargs", "[", "value", "]", "# If the length is in the kwd dictionary then use that too.", "if", "length", "in", "kwargs", ":", "length", "=", "kwargs", "[", "length", "]", "# Also if we just have a dictionary name then we want to use it", "if", "name", "in", "kwargs", "and", "length", "is", "None", "and", "value", "is", "None", ":", "s", ".", "append", "(", "kwargs", "[", "name", "]", ")", "continue", "if", "length", "is", "not", "None", ":", "length", "=", "int", "(", "length", ")", "if", "value", "is", "None", "and", "name", "!=", "'pad'", ":", "# Take the next value from the ones provided", "value", "=", "next", "(", "value_iter", ")", "s", ".", "_append", "(", "BitStream", ".", "_init_with_token", "(", "name", ",", "length", ",", "value", ")", ")", "except", "StopIteration", ":", "raise", "CreationError", "(", "\"Not enough parameters present to pack according to the \"", "\"format. {0} values are needed.\"", ",", "len", "(", "tokens", ")", ")", "try", ":", "next", "(", "value_iter", ")", "except", "StopIteration", ":", "# Good, we've used up all the *values.", "return", "s", "raise", "CreationError", "(", "\"Too many parameters present to pack according to the format.\"", ")" ]
Pack the values according to the format string and return a new BitStream. fmt -- A single string or a list of strings with comma separated tokens describing how to create the BitStream. values -- Zero or more values to pack according to the format. kwargs -- A dictionary or keyword-value pairs - the keywords used in the format string will be replaced with their given value. Token examples: 'int:12' : 12 bits as a signed integer 'uint:8' : 8 bits as an unsigned integer 'float:64' : 8 bytes as a big-endian float 'intbe:16' : 2 bytes as a big-endian signed integer 'uintbe:16' : 2 bytes as a big-endian unsigned integer 'intle:32' : 4 bytes as a little-endian signed integer 'uintle:32' : 4 bytes as a little-endian unsigned integer 'floatle:64': 8 bytes as a little-endian float 'intne:24' : 3 bytes as a native-endian signed integer 'uintne:24' : 3 bytes as a native-endian unsigned integer 'floatne:32': 4 bytes as a native-endian float 'hex:80' : 80 bits as a hex string 'oct:9' : 9 bits as an octal string 'bin:1' : single bit binary string 'ue' / 'uie': next bits as unsigned exp-Golomb code 'se' / 'sie': next bits as signed exp-Golomb code 'bits:5' : 5 bits as a bitstring object 'bytes:10' : 10 bytes as a bytes object 'bool' : 1 bit as a bool 'pad:3' : 3 zero bits as padding >>> s = pack('uint:12, bits', 100, '0xffe') >>> t = pack(['bits', 'bin:3'], s, '111') >>> u = pack('uint:8=a, uint:8=b, uint:55=a', a=6, b=44)
[ "Pack", "the", "values", "according", "to", "the", "format", "string", "and", "return", "a", "new", "BitStream", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L4161-L4233
17,841
scott-griffiths/bitstring
bitstring.py
ConstByteStore.getbyteslice
def getbyteslice(self, start, end): """Direct access to byte data.""" c = self._rawarray[start:end] return c
python
def getbyteslice(self, start, end): """Direct access to byte data.""" c = self._rawarray[start:end] return c
[ "def", "getbyteslice", "(", "self", ",", "start", ",", "end", ")", ":", "c", "=", "self", ".", "_rawarray", "[", "start", ":", "end", "]", "return", "c" ]
Direct access to byte data.
[ "Direct", "access", "to", "byte", "data", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L157-L160
17,842
scott-griffiths/bitstring
bitstring.py
ConstByteStore._appendstore
def _appendstore(self, store): """Join another store on to the end of this one.""" if not store.bitlength: return # Set new array offset to the number of bits in the final byte of current array. store = offsetcopy(store, (self.offset + self.bitlength) % 8) if store.offset: # first do the byte with the join. joinval = (self._rawarray.pop() & (255 ^ (255 >> store.offset)) | (store.getbyte(0) & (255 >> store.offset))) self._rawarray.append(joinval) self._rawarray.extend(store._rawarray[1:]) else: self._rawarray.extend(store._rawarray) self.bitlength += store.bitlength
python
def _appendstore(self, store): """Join another store on to the end of this one.""" if not store.bitlength: return # Set new array offset to the number of bits in the final byte of current array. store = offsetcopy(store, (self.offset + self.bitlength) % 8) if store.offset: # first do the byte with the join. joinval = (self._rawarray.pop() & (255 ^ (255 >> store.offset)) | (store.getbyte(0) & (255 >> store.offset))) self._rawarray.append(joinval) self._rawarray.extend(store._rawarray[1:]) else: self._rawarray.extend(store._rawarray) self.bitlength += store.bitlength
[ "def", "_appendstore", "(", "self", ",", "store", ")", ":", "if", "not", "store", ".", "bitlength", ":", "return", "# Set new array offset to the number of bits in the final byte of current array.", "store", "=", "offsetcopy", "(", "store", ",", "(", "self", ".", "offset", "+", "self", ".", "bitlength", ")", "%", "8", ")", "if", "store", ".", "offset", ":", "# first do the byte with the join.", "joinval", "=", "(", "self", ".", "_rawarray", ".", "pop", "(", ")", "&", "(", "255", "^", "(", "255", ">>", "store", ".", "offset", ")", ")", "|", "(", "store", ".", "getbyte", "(", "0", ")", "&", "(", "255", ">>", "store", ".", "offset", ")", ")", ")", "self", ".", "_rawarray", ".", "append", "(", "joinval", ")", "self", ".", "_rawarray", ".", "extend", "(", "store", ".", "_rawarray", "[", "1", ":", "]", ")", "else", ":", "self", ".", "_rawarray", ".", "extend", "(", "store", ".", "_rawarray", ")", "self", ".", "bitlength", "+=", "store", ".", "bitlength" ]
Join another store on to the end of this one.
[ "Join", "another", "store", "on", "to", "the", "end", "of", "this", "one", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L173-L187
17,843
scott-griffiths/bitstring
bitstring.py
ConstByteStore._prependstore
def _prependstore(self, store): """Join another store on to the start of this one.""" if not store.bitlength: return # Set the offset of copy of store so that it's final byte # ends in a position that matches the offset of self, # then join self on to the end of it. store = offsetcopy(store, (self.offset - store.bitlength) % 8) assert (store.offset + store.bitlength) % 8 == self.offset % 8 bit_offset = self.offset % 8 if bit_offset: # first do the byte with the join. store.setbyte(-1, (store.getbyte(-1) & (255 ^ (255 >> bit_offset)) | \ (self._rawarray[self.byteoffset] & (255 >> bit_offset)))) store._rawarray.extend(self._rawarray[self.byteoffset + 1: self.byteoffset + self.bytelength]) else: store._rawarray.extend(self._rawarray[self.byteoffset: self.byteoffset + self.bytelength]) self._rawarray = store._rawarray self.offset = store.offset self.bitlength += store.bitlength
python
def _prependstore(self, store): """Join another store on to the start of this one.""" if not store.bitlength: return # Set the offset of copy of store so that it's final byte # ends in a position that matches the offset of self, # then join self on to the end of it. store = offsetcopy(store, (self.offset - store.bitlength) % 8) assert (store.offset + store.bitlength) % 8 == self.offset % 8 bit_offset = self.offset % 8 if bit_offset: # first do the byte with the join. store.setbyte(-1, (store.getbyte(-1) & (255 ^ (255 >> bit_offset)) | \ (self._rawarray[self.byteoffset] & (255 >> bit_offset)))) store._rawarray.extend(self._rawarray[self.byteoffset + 1: self.byteoffset + self.bytelength]) else: store._rawarray.extend(self._rawarray[self.byteoffset: self.byteoffset + self.bytelength]) self._rawarray = store._rawarray self.offset = store.offset self.bitlength += store.bitlength
[ "def", "_prependstore", "(", "self", ",", "store", ")", ":", "if", "not", "store", ".", "bitlength", ":", "return", "# Set the offset of copy of store so that it's final byte", "# ends in a position that matches the offset of self,", "# then join self on to the end of it.", "store", "=", "offsetcopy", "(", "store", ",", "(", "self", ".", "offset", "-", "store", ".", "bitlength", ")", "%", "8", ")", "assert", "(", "store", ".", "offset", "+", "store", ".", "bitlength", ")", "%", "8", "==", "self", ".", "offset", "%", "8", "bit_offset", "=", "self", ".", "offset", "%", "8", "if", "bit_offset", ":", "# first do the byte with the join.", "store", ".", "setbyte", "(", "-", "1", ",", "(", "store", ".", "getbyte", "(", "-", "1", ")", "&", "(", "255", "^", "(", "255", ">>", "bit_offset", ")", ")", "|", "(", "self", ".", "_rawarray", "[", "self", ".", "byteoffset", "]", "&", "(", "255", ">>", "bit_offset", ")", ")", ")", ")", "store", ".", "_rawarray", ".", "extend", "(", "self", ".", "_rawarray", "[", "self", ".", "byteoffset", "+", "1", ":", "self", ".", "byteoffset", "+", "self", ".", "bytelength", "]", ")", "else", ":", "store", ".", "_rawarray", ".", "extend", "(", "self", ".", "_rawarray", "[", "self", ".", "byteoffset", ":", "self", ".", "byteoffset", "+", "self", ".", "bytelength", "]", ")", "self", ".", "_rawarray", "=", "store", ".", "_rawarray", "self", ".", "offset", "=", "store", ".", "offset", "self", ".", "bitlength", "+=", "store", ".", "bitlength" ]
Join another store on to the start of this one.
[ "Join", "another", "store", "on", "to", "the", "start", "of", "this", "one", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L189-L208
17,844
scott-griffiths/bitstring
bitstring.py
Bits._assertsanity
def _assertsanity(self): """Check internal self consistency as a debugging aid.""" assert self.len >= 0 assert 0 <= self._offset, "offset={0}".format(self._offset) assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset return True
python
def _assertsanity(self): """Check internal self consistency as a debugging aid.""" assert self.len >= 0 assert 0 <= self._offset, "offset={0}".format(self._offset) assert (self.len + self._offset + 7) // 8 == self._datastore.bytelength + self._datastore.byteoffset return True
[ "def", "_assertsanity", "(", "self", ")", ":", "assert", "self", ".", "len", ">=", "0", "assert", "0", "<=", "self", ".", "_offset", ",", "\"offset={0}\"", ".", "format", "(", "self", ".", "_offset", ")", "assert", "(", "self", ".", "len", "+", "self", ".", "_offset", "+", "7", ")", "//", "8", "==", "self", ".", "_datastore", ".", "bytelength", "+", "self", ".", "_datastore", ".", "byteoffset", "return", "True" ]
Check internal self consistency as a debugging aid.
[ "Check", "internal", "self", "consistency", "as", "a", "debugging", "aid", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1195-L1200
17,845
scott-griffiths/bitstring
bitstring.py
Bits._setauto
def _setauto(self, s, length, offset): """Set bitstring from a bitstring, file, bool, integer, array, iterable or string.""" # As s can be so many different things it's important to do the checks # in the correct order, as some types are also other allowed types. # So basestring must be checked before Iterable # and bytes/bytearray before Iterable but after basestring! if isinstance(s, Bits): if length is None: length = s.len - offset self._setbytes_unsafe(s._datastore.rawbytes, length, s._offset + offset) return if isinstance(s, file): if offset is None: offset = 0 if length is None: length = os.path.getsize(s.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(s, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset) return if length is not None: raise CreationError("The length keyword isn't applicable to this initialiser.") if offset: raise CreationError("The offset keyword isn't applicable to this initialiser.") if isinstance(s, basestring): bs = self._converttobitstring(s) assert bs._offset == 0 self._setbytes_unsafe(bs._datastore.rawbytes, bs.length, 0) return if isinstance(s, (bytes, bytearray)): self._setbytes_unsafe(bytearray(s), len(s) * 8, 0) return if isinstance(s, array.array): b = s.tostring() self._setbytes_unsafe(bytearray(b), len(b) * 8, 0) return if isinstance(s, numbers.Integral): # Initialise with s zero bits. if s < 0: msg = "Can't create bitstring of negative length {0}." raise CreationError(msg, s) data = bytearray((s + 7) // 8) self._datastore = ByteStore(data, s, 0) return if isinstance(s, collections.Iterable): # Evaluate each item as True or False and set bits to 1 or 0. self._setbin_unsafe(''.join(str(int(bool(x))) for x in s)) return raise TypeError("Cannot initialise bitstring from {0}.".format(type(s)))
python
def _setauto(self, s, length, offset): """Set bitstring from a bitstring, file, bool, integer, array, iterable or string.""" # As s can be so many different things it's important to do the checks # in the correct order, as some types are also other allowed types. # So basestring must be checked before Iterable # and bytes/bytearray before Iterable but after basestring! if isinstance(s, Bits): if length is None: length = s.len - offset self._setbytes_unsafe(s._datastore.rawbytes, length, s._offset + offset) return if isinstance(s, file): if offset is None: offset = 0 if length is None: length = os.path.getsize(s.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(s, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset) return if length is not None: raise CreationError("The length keyword isn't applicable to this initialiser.") if offset: raise CreationError("The offset keyword isn't applicable to this initialiser.") if isinstance(s, basestring): bs = self._converttobitstring(s) assert bs._offset == 0 self._setbytes_unsafe(bs._datastore.rawbytes, bs.length, 0) return if isinstance(s, (bytes, bytearray)): self._setbytes_unsafe(bytearray(s), len(s) * 8, 0) return if isinstance(s, array.array): b = s.tostring() self._setbytes_unsafe(bytearray(b), len(b) * 8, 0) return if isinstance(s, numbers.Integral): # Initialise with s zero bits. if s < 0: msg = "Can't create bitstring of negative length {0}." raise CreationError(msg, s) data = bytearray((s + 7) // 8) self._datastore = ByteStore(data, s, 0) return if isinstance(s, collections.Iterable): # Evaluate each item as True or False and set bits to 1 or 0. self._setbin_unsafe(''.join(str(int(bool(x))) for x in s)) return raise TypeError("Cannot initialise bitstring from {0}.".format(type(s)))
[ "def", "_setauto", "(", "self", ",", "s", ",", "length", ",", "offset", ")", ":", "# As s can be so many different things it's important to do the checks", "# in the correct order, as some types are also other allowed types.", "# So basestring must be checked before Iterable", "# and bytes/bytearray before Iterable but after basestring!", "if", "isinstance", "(", "s", ",", "Bits", ")", ":", "if", "length", "is", "None", ":", "length", "=", "s", ".", "len", "-", "offset", "self", ".", "_setbytes_unsafe", "(", "s", ".", "_datastore", ".", "rawbytes", ",", "length", ",", "s", ".", "_offset", "+", "offset", ")", "return", "if", "isinstance", "(", "s", ",", "file", ")", ":", "if", "offset", "is", "None", ":", "offset", "=", "0", "if", "length", "is", "None", ":", "length", "=", "os", ".", "path", ".", "getsize", "(", "s", ".", "name", ")", "*", "8", "-", "offset", "byteoffset", ",", "offset", "=", "divmod", "(", "offset", ",", "8", ")", "bytelength", "=", "(", "length", "+", "byteoffset", "*", "8", "+", "offset", "+", "7", ")", "//", "8", "-", "byteoffset", "m", "=", "MmapByteArray", "(", "s", ",", "bytelength", ",", "byteoffset", ")", "if", "length", "+", "byteoffset", "*", "8", "+", "offset", ">", "m", ".", "filelength", "*", "8", ":", "raise", "CreationError", "(", "\"File is not long enough for specified \"", "\"length and offset.\"", ")", "self", ".", "_datastore", "=", "ConstByteStore", "(", "m", ",", "length", ",", "offset", ")", "return", "if", "length", "is", "not", "None", ":", "raise", "CreationError", "(", "\"The length keyword isn't applicable to this initialiser.\"", ")", "if", "offset", ":", "raise", "CreationError", "(", "\"The offset keyword isn't applicable to this initialiser.\"", ")", "if", "isinstance", "(", "s", ",", "basestring", ")", ":", "bs", "=", "self", ".", "_converttobitstring", "(", "s", ")", "assert", "bs", ".", "_offset", "==", "0", "self", ".", "_setbytes_unsafe", "(", "bs", ".", "_datastore", ".", "rawbytes", ",", "bs", ".", "length", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "s", ")", ",", "len", "(", "s", ")", "*", "8", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "array", ".", "array", ")", ":", "b", "=", "s", ".", "tostring", "(", ")", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "b", ")", ",", "len", "(", "b", ")", "*", "8", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "numbers", ".", "Integral", ")", ":", "# Initialise with s zero bits.", "if", "s", "<", "0", ":", "msg", "=", "\"Can't create bitstring of negative length {0}.\"", "raise", "CreationError", "(", "msg", ",", "s", ")", "data", "=", "bytearray", "(", "(", "s", "+", "7", ")", "//", "8", ")", "self", ".", "_datastore", "=", "ByteStore", "(", "data", ",", "s", ",", "0", ")", "return", "if", "isinstance", "(", "s", ",", "collections", ".", "Iterable", ")", ":", "# Evaluate each item as True or False and set bits to 1 or 0.", "self", ".", "_setbin_unsafe", "(", "''", ".", "join", "(", "str", "(", "int", "(", "bool", "(", "x", ")", ")", ")", "for", "x", "in", "s", ")", ")", "return", "raise", "TypeError", "(", "\"Cannot initialise bitstring from {0}.\"", ".", "format", "(", "type", "(", "s", ")", ")", ")" ]
Set bitstring from a bitstring, file, bool, integer, array, iterable or string.
[ "Set", "bitstring", "from", "a", "bitstring", "file", "bool", "integer", "array", "iterable", "or", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1245-L1297
17,846
scott-griffiths/bitstring
bitstring.py
Bits._setfile
def _setfile(self, filename, length, offset): """Use file as source of bits.""" source = open(filename, 'rb') if offset is None: offset = 0 if length is None: length = os.path.getsize(source.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(source, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset)
python
def _setfile(self, filename, length, offset): """Use file as source of bits.""" source = open(filename, 'rb') if offset is None: offset = 0 if length is None: length = os.path.getsize(source.name) * 8 - offset byteoffset, offset = divmod(offset, 8) bytelength = (length + byteoffset * 8 + offset + 7) // 8 - byteoffset m = MmapByteArray(source, bytelength, byteoffset) if length + byteoffset * 8 + offset > m.filelength * 8: raise CreationError("File is not long enough for specified " "length and offset.") self._datastore = ConstByteStore(m, length, offset)
[ "def", "_setfile", "(", "self", ",", "filename", ",", "length", ",", "offset", ")", ":", "source", "=", "open", "(", "filename", ",", "'rb'", ")", "if", "offset", "is", "None", ":", "offset", "=", "0", "if", "length", "is", "None", ":", "length", "=", "os", ".", "path", ".", "getsize", "(", "source", ".", "name", ")", "*", "8", "-", "offset", "byteoffset", ",", "offset", "=", "divmod", "(", "offset", ",", "8", ")", "bytelength", "=", "(", "length", "+", "byteoffset", "*", "8", "+", "offset", "+", "7", ")", "//", "8", "-", "byteoffset", "m", "=", "MmapByteArray", "(", "source", ",", "bytelength", ",", "byteoffset", ")", "if", "length", "+", "byteoffset", "*", "8", "+", "offset", ">", "m", ".", "filelength", "*", "8", ":", "raise", "CreationError", "(", "\"File is not long enough for specified \"", "\"length and offset.\"", ")", "self", ".", "_datastore", "=", "ConstByteStore", "(", "m", ",", "length", ",", "offset", ")" ]
Use file as source of bits.
[ "Use", "file", "as", "source", "of", "bits", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1299-L1312
17,847
scott-griffiths/bitstring
bitstring.py
Bits._setbytes_safe
def _setbytes_safe(self, data, length=None, offset=0): """Set the data from a string.""" data = bytearray(data) if length is None: # Use to the end of the data length = len(data)*8 - offset self._datastore = ByteStore(data, length, offset) else: if length + offset > len(data) * 8: msg = "Not enough data present. Need {0} bits, have {1}." raise CreationError(msg, length + offset, len(data) * 8) if length == 0: self._datastore = ByteStore(bytearray(0)) else: self._datastore = ByteStore(data, length, offset)
python
def _setbytes_safe(self, data, length=None, offset=0): """Set the data from a string.""" data = bytearray(data) if length is None: # Use to the end of the data length = len(data)*8 - offset self._datastore = ByteStore(data, length, offset) else: if length + offset > len(data) * 8: msg = "Not enough data present. Need {0} bits, have {1}." raise CreationError(msg, length + offset, len(data) * 8) if length == 0: self._datastore = ByteStore(bytearray(0)) else: self._datastore = ByteStore(data, length, offset)
[ "def", "_setbytes_safe", "(", "self", ",", "data", ",", "length", "=", "None", ",", "offset", "=", "0", ")", ":", "data", "=", "bytearray", "(", "data", ")", "if", "length", "is", "None", ":", "# Use to the end of the data", "length", "=", "len", "(", "data", ")", "*", "8", "-", "offset", "self", ".", "_datastore", "=", "ByteStore", "(", "data", ",", "length", ",", "offset", ")", "else", ":", "if", "length", "+", "offset", ">", "len", "(", "data", ")", "*", "8", ":", "msg", "=", "\"Not enough data present. Need {0} bits, have {1}.\"", "raise", "CreationError", "(", "msg", ",", "length", "+", "offset", ",", "len", "(", "data", ")", "*", "8", ")", "if", "length", "==", "0", ":", "self", ".", "_datastore", "=", "ByteStore", "(", "bytearray", "(", "0", ")", ")", "else", ":", "self", ".", "_datastore", "=", "ByteStore", "(", "data", ",", "length", ",", "offset", ")" ]
Set the data from a string.
[ "Set", "the", "data", "from", "a", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1314-L1328
17,848
scott-griffiths/bitstring
bitstring.py
Bits._setbytes_unsafe
def _setbytes_unsafe(self, data, length, offset): """Unchecked version of _setbytes_safe.""" self._datastore = ByteStore(data[:], length, offset) assert self._assertsanity()
python
def _setbytes_unsafe(self, data, length, offset): """Unchecked version of _setbytes_safe.""" self._datastore = ByteStore(data[:], length, offset) assert self._assertsanity()
[ "def", "_setbytes_unsafe", "(", "self", ",", "data", ",", "length", ",", "offset", ")", ":", "self", ".", "_datastore", "=", "ByteStore", "(", "data", "[", ":", "]", ",", "length", ",", "offset", ")", "assert", "self", ".", "_assertsanity", "(", ")" ]
Unchecked version of _setbytes_safe.
[ "Unchecked", "version", "of", "_setbytes_safe", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1330-L1333
17,849
scott-griffiths/bitstring
bitstring.py
Bits._readbytes
def _readbytes(self, length, start): """Read bytes and return them. Note that length is in bits.""" assert length % 8 == 0 assert start + length <= self.len if not (start + self._offset) % 8: return bytes(self._datastore.getbyteslice((start + self._offset) // 8, (start + self._offset + length) // 8)) return self._slice(start, start + length).tobytes()
python
def _readbytes(self, length, start): """Read bytes and return them. Note that length is in bits.""" assert length % 8 == 0 assert start + length <= self.len if not (start + self._offset) % 8: return bytes(self._datastore.getbyteslice((start + self._offset) // 8, (start + self._offset + length) // 8)) return self._slice(start, start + length).tobytes()
[ "def", "_readbytes", "(", "self", ",", "length", ",", "start", ")", ":", "assert", "length", "%", "8", "==", "0", "assert", "start", "+", "length", "<=", "self", ".", "len", "if", "not", "(", "start", "+", "self", ".", "_offset", ")", "%", "8", ":", "return", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "(", "start", "+", "self", ".", "_offset", ")", "//", "8", ",", "(", "start", "+", "self", ".", "_offset", "+", "length", ")", "//", "8", ")", ")", "return", "self", ".", "_slice", "(", "start", ",", "start", "+", "length", ")", ".", "tobytes", "(", ")" ]
Read bytes and return them. Note that length is in bits.
[ "Read", "bytes", "and", "return", "them", ".", "Note", "that", "length", "is", "in", "bits", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1335-L1342
17,850
scott-griffiths/bitstring
bitstring.py
Bits._setuint
def _setuint(self, uint, length=None): """Reset the bitstring to have given unsigned int interpretation.""" try: if length is None: # Use the whole length. Deliberately not using .len here. length = self._datastore.bitlength except AttributeError: # bitstring doesn't have a _datastore as it hasn't been created! pass # TODO: All this checking code should be hoisted out of here! if length is None or length == 0: raise CreationError("A non-zero length must be specified with a " "uint initialiser.") if uint >= (1 << length): msg = "{0} is too large an unsigned integer for a bitstring of length {1}. "\ "The allowed range is [0, {2}]." raise CreationError(msg, uint, length, (1 << length) - 1) if uint < 0: raise CreationError("uint cannot be initialsed by a negative number.") s = hex(uint)[2:] s = s.rstrip('L') if len(s) & 1: s = '0' + s try: data = bytes.fromhex(s) except AttributeError: # the Python 2.x way data = binascii.unhexlify(s) # Now add bytes as needed to get the right length. extrabytes = ((length + 7) // 8) - len(data) if extrabytes > 0: data = b'\x00' * extrabytes + data offset = 8 - (length % 8) if offset == 8: offset = 0 self._setbytes_unsafe(bytearray(data), length, offset)
python
def _setuint(self, uint, length=None): """Reset the bitstring to have given unsigned int interpretation.""" try: if length is None: # Use the whole length. Deliberately not using .len here. length = self._datastore.bitlength except AttributeError: # bitstring doesn't have a _datastore as it hasn't been created! pass # TODO: All this checking code should be hoisted out of here! if length is None or length == 0: raise CreationError("A non-zero length must be specified with a " "uint initialiser.") if uint >= (1 << length): msg = "{0} is too large an unsigned integer for a bitstring of length {1}. "\ "The allowed range is [0, {2}]." raise CreationError(msg, uint, length, (1 << length) - 1) if uint < 0: raise CreationError("uint cannot be initialsed by a negative number.") s = hex(uint)[2:] s = s.rstrip('L') if len(s) & 1: s = '0' + s try: data = bytes.fromhex(s) except AttributeError: # the Python 2.x way data = binascii.unhexlify(s) # Now add bytes as needed to get the right length. extrabytes = ((length + 7) // 8) - len(data) if extrabytes > 0: data = b'\x00' * extrabytes + data offset = 8 - (length % 8) if offset == 8: offset = 0 self._setbytes_unsafe(bytearray(data), length, offset)
[ "def", "_setuint", "(", "self", ",", "uint", ",", "length", "=", "None", ")", ":", "try", ":", "if", "length", "is", "None", ":", "# Use the whole length. Deliberately not using .len here.", "length", "=", "self", ".", "_datastore", ".", "bitlength", "except", "AttributeError", ":", "# bitstring doesn't have a _datastore as it hasn't been created!", "pass", "# TODO: All this checking code should be hoisted out of here!", "if", "length", "is", "None", "or", "length", "==", "0", ":", "raise", "CreationError", "(", "\"A non-zero length must be specified with a \"", "\"uint initialiser.\"", ")", "if", "uint", ">=", "(", "1", "<<", "length", ")", ":", "msg", "=", "\"{0} is too large an unsigned integer for a bitstring of length {1}. \"", "\"The allowed range is [0, {2}].\"", "raise", "CreationError", "(", "msg", ",", "uint", ",", "length", ",", "(", "1", "<<", "length", ")", "-", "1", ")", "if", "uint", "<", "0", ":", "raise", "CreationError", "(", "\"uint cannot be initialsed by a negative number.\"", ")", "s", "=", "hex", "(", "uint", ")", "[", "2", ":", "]", "s", "=", "s", ".", "rstrip", "(", "'L'", ")", "if", "len", "(", "s", ")", "&", "1", ":", "s", "=", "'0'", "+", "s", "try", ":", "data", "=", "bytes", ".", "fromhex", "(", "s", ")", "except", "AttributeError", ":", "# the Python 2.x way", "data", "=", "binascii", ".", "unhexlify", "(", "s", ")", "# Now add bytes as needed to get the right length.", "extrabytes", "=", "(", "(", "length", "+", "7", ")", "//", "8", ")", "-", "len", "(", "data", ")", "if", "extrabytes", ">", "0", ":", "data", "=", "b'\\x00'", "*", "extrabytes", "+", "data", "offset", "=", "8", "-", "(", "length", "%", "8", ")", "if", "offset", "==", "8", ":", "offset", "=", "0", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "data", ")", ",", "length", ",", "offset", ")" ]
Reset the bitstring to have given unsigned int interpretation.
[ "Reset", "the", "bitstring", "to", "have", "given", "unsigned", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1351-L1386
17,851
scott-griffiths/bitstring
bitstring.py
Bits._readuint
def _readuint(self, length, start): """Read bits and interpret as an unsigned int.""" if not length: raise InterpretError("Cannot interpret a zero length bitstring " "as an integer.") offset = self._offset startbyte = (start + offset) // 8 endbyte = (start + offset + length - 1) // 8 b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1))) assert b i = int(b, 16) final_bits = 8 - ((start + offset + length) % 8) if final_bits != 8: i >>= final_bits i &= (1 << length) - 1 return i
python
def _readuint(self, length, start): """Read bits and interpret as an unsigned int.""" if not length: raise InterpretError("Cannot interpret a zero length bitstring " "as an integer.") offset = self._offset startbyte = (start + offset) // 8 endbyte = (start + offset + length - 1) // 8 b = binascii.hexlify(bytes(self._datastore.getbyteslice(startbyte, endbyte + 1))) assert b i = int(b, 16) final_bits = 8 - ((start + offset + length) % 8) if final_bits != 8: i >>= final_bits i &= (1 << length) - 1 return i
[ "def", "_readuint", "(", "self", ",", "length", ",", "start", ")", ":", "if", "not", "length", ":", "raise", "InterpretError", "(", "\"Cannot interpret a zero length bitstring \"", "\"as an integer.\"", ")", "offset", "=", "self", ".", "_offset", "startbyte", "=", "(", "start", "+", "offset", ")", "//", "8", "endbyte", "=", "(", "start", "+", "offset", "+", "length", "-", "1", ")", "//", "8", "b", "=", "binascii", ".", "hexlify", "(", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "endbyte", "+", "1", ")", ")", ")", "assert", "b", "i", "=", "int", "(", "b", ",", "16", ")", "final_bits", "=", "8", "-", "(", "(", "start", "+", "offset", "+", "length", ")", "%", "8", ")", "if", "final_bits", "!=", "8", ":", "i", ">>=", "final_bits", "i", "&=", "(", "1", "<<", "length", ")", "-", "1", "return", "i" ]
Read bits and interpret as an unsigned int.
[ "Read", "bits", "and", "interpret", "as", "an", "unsigned", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1388-L1404
17,852
scott-griffiths/bitstring
bitstring.py
Bits._setint
def _setint(self, int_, length=None): """Reset the bitstring to have given signed int interpretation.""" # If no length given, and we've previously been given a length, use it. if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with an int initialiser.") if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)): raise CreationError("{0} is too large a signed integer for a bitstring of length {1}. " "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)), (1 << (length - 1)) - 1) if int_ >= 0: self._setuint(int_, length) return # TODO: We should decide whether to just use the _setuint, or to do the bit flipping, # based upon which will be quicker. If the -ive number is less than half the maximum # possible then it's probably quicker to do the bit flipping... # Do the 2's complement thing. Add one, set to minus number, then flip bits. int_ += 1 self._setuint(-int_, length) self._invert_all()
python
def _setint(self, int_, length=None): """Reset the bitstring to have given signed int interpretation.""" # If no length given, and we've previously been given a length, use it. if length is None and hasattr(self, 'len') and self.len != 0: length = self.len if length is None or length == 0: raise CreationError("A non-zero length must be specified with an int initialiser.") if int_ >= (1 << (length - 1)) or int_ < -(1 << (length - 1)): raise CreationError("{0} is too large a signed integer for a bitstring of length {1}. " "The allowed range is [{2}, {3}].", int_, length, -(1 << (length - 1)), (1 << (length - 1)) - 1) if int_ >= 0: self._setuint(int_, length) return # TODO: We should decide whether to just use the _setuint, or to do the bit flipping, # based upon which will be quicker. If the -ive number is less than half the maximum # possible then it's probably quicker to do the bit flipping... # Do the 2's complement thing. Add one, set to minus number, then flip bits. int_ += 1 self._setuint(-int_, length) self._invert_all()
[ "def", "_setint", "(", "self", ",", "int_", ",", "length", "=", "None", ")", ":", "# If no length given, and we've previously been given a length, use it.", "if", "length", "is", "None", "and", "hasattr", "(", "self", ",", "'len'", ")", "and", "self", ".", "len", "!=", "0", ":", "length", "=", "self", ".", "len", "if", "length", "is", "None", "or", "length", "==", "0", ":", "raise", "CreationError", "(", "\"A non-zero length must be specified with an int initialiser.\"", ")", "if", "int_", ">=", "(", "1", "<<", "(", "length", "-", "1", ")", ")", "or", "int_", "<", "-", "(", "1", "<<", "(", "length", "-", "1", ")", ")", ":", "raise", "CreationError", "(", "\"{0} is too large a signed integer for a bitstring of length {1}. \"", "\"The allowed range is [{2}, {3}].\"", ",", "int_", ",", "length", ",", "-", "(", "1", "<<", "(", "length", "-", "1", ")", ")", ",", "(", "1", "<<", "(", "length", "-", "1", ")", ")", "-", "1", ")", "if", "int_", ">=", "0", ":", "self", ".", "_setuint", "(", "int_", ",", "length", ")", "return", "# TODO: We should decide whether to just use the _setuint, or to do the bit flipping,", "# based upon which will be quicker. If the -ive number is less than half the maximum", "# possible then it's probably quicker to do the bit flipping...", "# Do the 2's complement thing. Add one, set to minus number, then flip bits.", "int_", "+=", "1", "self", ".", "_setuint", "(", "-", "int_", ",", "length", ")", "self", ".", "_invert_all", "(", ")" ]
Reset the bitstring to have given signed int interpretation.
[ "Reset", "the", "bitstring", "to", "have", "given", "signed", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1410-L1431
17,853
scott-griffiths/bitstring
bitstring.py
Bits._readint
def _readint(self, length, start): """Read bits and interpret as a signed int""" ui = self._readuint(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
python
def _readint(self, length, start): """Read bits and interpret as a signed int""" ui = self._readuint(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
[ "def", "_readint", "(", "self", ",", "length", ",", "start", ")", ":", "ui", "=", "self", ".", "_readuint", "(", "length", ",", "start", ")", "if", "not", "ui", ">>", "(", "length", "-", "1", ")", ":", "# Top bit not set, number is positive", "return", "ui", "# Top bit is set, so number is negative", "tmp", "=", "(", "~", "(", "ui", "-", "1", ")", ")", "&", "(", "(", "1", "<<", "length", ")", "-", "1", ")", "return", "-", "tmp" ]
Read bits and interpret as a signed int
[ "Read", "bits", "and", "interpret", "as", "a", "signed", "int" ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1433-L1441
17,854
scott-griffiths/bitstring
bitstring.py
Bits._setuintbe
def _setuintbe(self, uintbe, length=None): """Set the bitstring to a big-endian unsigned int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setuint(uintbe, length)
python
def _setuintbe(self, uintbe, length=None): """Set the bitstring to a big-endian unsigned int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setuint(uintbe, length)
[ "def", "_setuintbe", "(", "self", ",", "uintbe", ",", "length", "=", "None", ")", ":", "if", "length", "is", "not", "None", "and", "length", "%", "8", "!=", "0", ":", "raise", "CreationError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "self", ".", "_setuint", "(", "uintbe", ",", "length", ")" ]
Set the bitstring to a big-endian unsigned int interpretation.
[ "Set", "the", "bitstring", "to", "a", "big", "-", "endian", "unsigned", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1447-L1452
17,855
scott-griffiths/bitstring
bitstring.py
Bits._readuintbe
def _readuintbe(self, length, start): """Read bits and interpret as a big-endian unsigned int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readuint(length, start)
python
def _readuintbe(self, length, start): """Read bits and interpret as a big-endian unsigned int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readuint(length, start)
[ "def", "_readuintbe", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "8", ":", "raise", "InterpretError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "return", "self", ".", "_readuint", "(", "length", ",", "start", ")" ]
Read bits and interpret as a big-endian unsigned int.
[ "Read", "bits", "and", "interpret", "as", "a", "big", "-", "endian", "unsigned", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1454-L1459
17,856
scott-griffiths/bitstring
bitstring.py
Bits._setintbe
def _setintbe(self, intbe, length=None): """Set bitstring to a big-endian signed int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setint(intbe, length)
python
def _setintbe(self, intbe, length=None): """Set bitstring to a big-endian signed int interpretation.""" if length is not None and length % 8 != 0: raise CreationError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) self._setint(intbe, length)
[ "def", "_setintbe", "(", "self", ",", "intbe", ",", "length", "=", "None", ")", ":", "if", "length", "is", "not", "None", "and", "length", "%", "8", "!=", "0", ":", "raise", "CreationError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "self", ".", "_setint", "(", "intbe", ",", "length", ")" ]
Set bitstring to a big-endian signed int interpretation.
[ "Set", "bitstring", "to", "a", "big", "-", "endian", "signed", "int", "interpretation", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1465-L1470
17,857
scott-griffiths/bitstring
bitstring.py
Bits._readintbe
def _readintbe(self, length, start): """Read bits and interpret as a big-endian signed int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readint(length, start)
python
def _readintbe(self, length, start): """Read bits and interpret as a big-endian signed int.""" if length % 8: raise InterpretError("Big-endian integers must be whole-byte. " "Length = {0} bits.", length) return self._readint(length, start)
[ "def", "_readintbe", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "8", ":", "raise", "InterpretError", "(", "\"Big-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "return", "self", ".", "_readint", "(", "length", ",", "start", ")" ]
Read bits and interpret as a big-endian signed int.
[ "Read", "bits", "and", "interpret", "as", "a", "big", "-", "endian", "signed", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1472-L1477
17,858
scott-griffiths/bitstring
bitstring.py
Bits._readuintle
def _readuintle(self, length, start): """Read bits and interpret as a little-endian unsigned int.""" if length % 8: raise InterpretError("Little-endian integers must be whole-byte. " "Length = {0} bits.", length) assert start + length <= self.len absolute_pos = start + self._offset startbyte, offset = divmod(absolute_pos, 8) val = 0 if not offset: endbyte = (absolute_pos + length - 1) // 8 chunksize = 4 # for 'L' format while endbyte - chunksize + 1 >= startbyte: val <<= 8 * chunksize val += struct.unpack('<L', bytes(self._datastore.getbyteslice(endbyte + 1 - chunksize, endbyte + 1)))[0] endbyte -= chunksize for b in xrange(endbyte, startbyte - 1, -1): val <<= 8 val += self._datastore.getbyte(b) else: data = self._slice(start, start + length) assert data.len % 8 == 0 data._reversebytes(0, self.len) for b in bytearray(data.bytes): val <<= 8 val += b return val
python
def _readuintle(self, length, start): """Read bits and interpret as a little-endian unsigned int.""" if length % 8: raise InterpretError("Little-endian integers must be whole-byte. " "Length = {0} bits.", length) assert start + length <= self.len absolute_pos = start + self._offset startbyte, offset = divmod(absolute_pos, 8) val = 0 if not offset: endbyte = (absolute_pos + length - 1) // 8 chunksize = 4 # for 'L' format while endbyte - chunksize + 1 >= startbyte: val <<= 8 * chunksize val += struct.unpack('<L', bytes(self._datastore.getbyteslice(endbyte + 1 - chunksize, endbyte + 1)))[0] endbyte -= chunksize for b in xrange(endbyte, startbyte - 1, -1): val <<= 8 val += self._datastore.getbyte(b) else: data = self._slice(start, start + length) assert data.len % 8 == 0 data._reversebytes(0, self.len) for b in bytearray(data.bytes): val <<= 8 val += b return val
[ "def", "_readuintle", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "8", ":", "raise", "InterpretError", "(", "\"Little-endian integers must be whole-byte. \"", "\"Length = {0} bits.\"", ",", "length", ")", "assert", "start", "+", "length", "<=", "self", ".", "len", "absolute_pos", "=", "start", "+", "self", ".", "_offset", "startbyte", ",", "offset", "=", "divmod", "(", "absolute_pos", ",", "8", ")", "val", "=", "0", "if", "not", "offset", ":", "endbyte", "=", "(", "absolute_pos", "+", "length", "-", "1", ")", "//", "8", "chunksize", "=", "4", "# for 'L' format", "while", "endbyte", "-", "chunksize", "+", "1", ">=", "startbyte", ":", "val", "<<=", "8", "*", "chunksize", "val", "+=", "struct", ".", "unpack", "(", "'<L'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "endbyte", "+", "1", "-", "chunksize", ",", "endbyte", "+", "1", ")", ")", ")", "[", "0", "]", "endbyte", "-=", "chunksize", "for", "b", "in", "xrange", "(", "endbyte", ",", "startbyte", "-", "1", ",", "-", "1", ")", ":", "val", "<<=", "8", "val", "+=", "self", ".", "_datastore", ".", "getbyte", "(", "b", ")", "else", ":", "data", "=", "self", ".", "_slice", "(", "start", ",", "start", "+", "length", ")", "assert", "data", ".", "len", "%", "8", "==", "0", "data", ".", "_reversebytes", "(", "0", ",", "self", ".", "len", ")", "for", "b", "in", "bytearray", "(", "data", ".", "bytes", ")", ":", "val", "<<=", "8", "val", "+=", "b", "return", "val" ]
Read bits and interpret as a little-endian unsigned int.
[ "Read", "bits", "and", "interpret", "as", "a", "little", "-", "endian", "unsigned", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1490-L1516
17,859
scott-griffiths/bitstring
bitstring.py
Bits._readintle
def _readintle(self, length, start): """Read bits and interpret as a little-endian signed int.""" ui = self._readuintle(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
python
def _readintle(self, length, start): """Read bits and interpret as a little-endian signed int.""" ui = self._readuintle(length, start) if not ui >> (length - 1): # Top bit not set, number is positive return ui # Top bit is set, so number is negative tmp = (~(ui - 1)) & ((1 << length) - 1) return -tmp
[ "def", "_readintle", "(", "self", ",", "length", ",", "start", ")", ":", "ui", "=", "self", ".", "_readuintle", "(", "length", ",", "start", ")", "if", "not", "ui", ">>", "(", "length", "-", "1", ")", ":", "# Top bit not set, number is positive", "return", "ui", "# Top bit is set, so number is negative", "tmp", "=", "(", "~", "(", "ui", "-", "1", ")", ")", "&", "(", "(", "1", "<<", "length", ")", "-", "1", ")", "return", "-", "tmp" ]
Read bits and interpret as a little-endian signed int.
[ "Read", "bits", "and", "interpret", "as", "a", "little", "-", "endian", "signed", "int", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1528-L1536
17,860
scott-griffiths/bitstring
bitstring.py
Bits._readfloat
def _readfloat(self, length, start): """Read bits and interpret as a float.""" if not (start + self._offset) % 8: startbyte = (start + self._offset) // 8 if length == 32: f, = struct.unpack('>f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('>d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('>f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('>d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, not {0} bits", length)
python
def _readfloat(self, length, start): """Read bits and interpret as a float.""" if not (start + self._offset) % 8: startbyte = (start + self._offset) // 8 if length == 32: f, = struct.unpack('>f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('>d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('>f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('>d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, not {0} bits", length)
[ "def", "_readfloat", "(", "self", ",", "length", ",", "start", ")", ":", "if", "not", "(", "start", "+", "self", ".", "_offset", ")", "%", "8", ":", "startbyte", "=", "(", "start", "+", "self", ".", "_offset", ")", "//", "8", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>f'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "4", ")", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>d'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "8", ")", ")", ")", "else", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>f'", ",", "self", ".", "_readbytes", "(", "32", ",", "start", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'>d'", ",", "self", ".", "_readbytes", "(", "64", ",", "start", ")", ")", "try", ":", "return", "f", "except", "NameError", ":", "raise", "InterpretError", "(", "\"floats can only be 32 or 64 bits long, not {0} bits\"", ",", "length", ")" ]
Read bits and interpret as a float.
[ "Read", "bits", "and", "interpret", "as", "a", "float", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1557-L1573
17,861
scott-griffiths/bitstring
bitstring.py
Bits._readfloatle
def _readfloatle(self, length, start): """Read bits and interpret as a little-endian float.""" startbyte, offset = divmod(start + self._offset, 8) if not offset: if length == 32: f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('<f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('<d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, " "not {0} bits", length)
python
def _readfloatle(self, length, start): """Read bits and interpret as a little-endian float.""" startbyte, offset = divmod(start + self._offset, 8) if not offset: if length == 32: f, = struct.unpack('<f', bytes(self._datastore.getbyteslice(startbyte, startbyte + 4))) elif length == 64: f, = struct.unpack('<d', bytes(self._datastore.getbyteslice(startbyte, startbyte + 8))) else: if length == 32: f, = struct.unpack('<f', self._readbytes(32, start)) elif length == 64: f, = struct.unpack('<d', self._readbytes(64, start)) try: return f except NameError: raise InterpretError("floats can only be 32 or 64 bits long, " "not {0} bits", length)
[ "def", "_readfloatle", "(", "self", ",", "length", ",", "start", ")", ":", "startbyte", ",", "offset", "=", "divmod", "(", "start", "+", "self", ".", "_offset", ",", "8", ")", "if", "not", "offset", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<f'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "4", ")", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<d'", ",", "bytes", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "startbyte", "+", "8", ")", ")", ")", "else", ":", "if", "length", "==", "32", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<f'", ",", "self", ".", "_readbytes", "(", "32", ",", "start", ")", ")", "elif", "length", "==", "64", ":", "f", ",", "=", "struct", ".", "unpack", "(", "'<d'", ",", "self", ".", "_readbytes", "(", "64", ",", "start", ")", ")", "try", ":", "return", "f", "except", "NameError", ":", "raise", "InterpretError", "(", "\"floats can only be 32 or 64 bits long, \"", "\"not {0} bits\"", ",", "length", ")" ]
Read bits and interpret as a little-endian float.
[ "Read", "bits", "and", "interpret", "as", "a", "little", "-", "endian", "float", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1595-L1612
17,862
scott-griffiths/bitstring
bitstring.py
Bits._setue
def _setue(self, i): """Initialise bitstring with unsigned exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "exponential-Golomb.") if not i: self._setbin_unsafe('1') return tmp = i + 1 leadingzeros = -1 while tmp > 0: tmp >>= 1 leadingzeros += 1 remainingpart = i + 1 - (1 << leadingzeros) binstring = '0' * leadingzeros + '1' + Bits(uint=remainingpart, length=leadingzeros).bin self._setbin_unsafe(binstring)
python
def _setue(self, i): """Initialise bitstring with unsigned exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "exponential-Golomb.") if not i: self._setbin_unsafe('1') return tmp = i + 1 leadingzeros = -1 while tmp > 0: tmp >>= 1 leadingzeros += 1 remainingpart = i + 1 - (1 << leadingzeros) binstring = '0' * leadingzeros + '1' + Bits(uint=remainingpart, length=leadingzeros).bin self._setbin_unsafe(binstring)
[ "def", "_setue", "(", "self", ",", "i", ")", ":", "if", "i", "<", "0", ":", "raise", "CreationError", "(", "\"Cannot use negative initialiser for unsigned \"", "\"exponential-Golomb.\"", ")", "if", "not", "i", ":", "self", ".", "_setbin_unsafe", "(", "'1'", ")", "return", "tmp", "=", "i", "+", "1", "leadingzeros", "=", "-", "1", "while", "tmp", ">", "0", ":", "tmp", ">>=", "1", "leadingzeros", "+=", "1", "remainingpart", "=", "i", "+", "1", "-", "(", "1", "<<", "leadingzeros", ")", "binstring", "=", "'0'", "*", "leadingzeros", "+", "'1'", "+", "Bits", "(", "uint", "=", "remainingpart", ",", "length", "=", "leadingzeros", ")", ".", "bin", "self", ".", "_setbin_unsafe", "(", "binstring", ")" ]
Initialise bitstring with unsigned exponential-Golomb code for integer i. Raises CreationError if i < 0.
[ "Initialise", "bitstring", "with", "unsigned", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1618-L1638
17,863
scott-griffiths/bitstring
bitstring.py
Bits._readue
def _readue(self, pos): """Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ oldpos = pos try: while not self[pos]: pos += 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.") leadingzeros = pos - oldpos codenum = (1 << leadingzeros) - 1 if leadingzeros > 0: if pos + leadingzeros + 1 > self.len: raise ReadError("Read off end of bitstring trying to read code.") codenum += self._readuint(leadingzeros, pos + 1) pos += leadingzeros + 1 else: assert codenum == 0 pos += 1 return codenum, pos
python
def _readue(self, pos): """Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ oldpos = pos try: while not self[pos]: pos += 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.") leadingzeros = pos - oldpos codenum = (1 << leadingzeros) - 1 if leadingzeros > 0: if pos + leadingzeros + 1 > self.len: raise ReadError("Read off end of bitstring trying to read code.") codenum += self._readuint(leadingzeros, pos + 1) pos += leadingzeros + 1 else: assert codenum == 0 pos += 1 return codenum, pos
[ "def", "_readue", "(", "self", ",", "pos", ")", ":", "oldpos", "=", "pos", "try", ":", "while", "not", "self", "[", "pos", "]", ":", "pos", "+=", "1", "except", "IndexError", ":", "raise", "ReadError", "(", "\"Read off end of bitstring trying to read code.\"", ")", "leadingzeros", "=", "pos", "-", "oldpos", "codenum", "=", "(", "1", "<<", "leadingzeros", ")", "-", "1", "if", "leadingzeros", ">", "0", ":", "if", "pos", "+", "leadingzeros", "+", "1", ">", "self", ".", "len", ":", "raise", "ReadError", "(", "\"Read off end of bitstring trying to read code.\"", ")", "codenum", "+=", "self", ".", "_readuint", "(", "leadingzeros", ",", "pos", "+", "1", ")", "pos", "+=", "leadingzeros", "+", "1", "else", ":", "assert", "codenum", "==", "0", "pos", "+=", "1", "return", "codenum", ",", "pos" ]
Return interpretation of next bits as unsigned exponential-Golomb code. Raises ReadError if the end of the bitstring is encountered while reading the code.
[ "Return", "interpretation", "of", "next", "bits", "as", "unsigned", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1640-L1663
17,864
scott-griffiths/bitstring
bitstring.py
Bits._getue
def _getue(self): """Return data as unsigned exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readue(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
python
def _getue(self): """Return data as unsigned exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readue(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
[ "def", "_getue", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readue", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single exponential-Golomb code.\"", ")", "return", "value" ]
Return data as unsigned exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "unsigned", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1665-L1677
17,865
scott-griffiths/bitstring
bitstring.py
Bits._setse
def _setse(self, i): """Initialise bitstring with signed exponential-Golomb code for integer i.""" if i > 0: u = (i * 2) - 1 else: u = -2 * i self._setue(u)
python
def _setse(self, i): """Initialise bitstring with signed exponential-Golomb code for integer i.""" if i > 0: u = (i * 2) - 1 else: u = -2 * i self._setue(u)
[ "def", "_setse", "(", "self", ",", "i", ")", ":", "if", "i", ">", "0", ":", "u", "=", "(", "i", "*", "2", ")", "-", "1", "else", ":", "u", "=", "-", "2", "*", "i", "self", ".", "_setue", "(", "u", ")" ]
Initialise bitstring with signed exponential-Golomb code for integer i.
[ "Initialise", "bitstring", "with", "signed", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1679-L1685
17,866
scott-griffiths/bitstring
bitstring.py
Bits._getse
def _getse(self): """Return data as signed exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readse(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
python
def _getse(self): """Return data as signed exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readse(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single exponential-Golomb code.") return value
[ "def", "_getse", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readse", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single exponential-Golomb code.\"", ")", "return", "value" ]
Return data as signed exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "signed", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1687-L1699
17,867
scott-griffiths/bitstring
bitstring.py
Bits._readse
def _readse(self, pos): """Return interpretation of next bits as a signed exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readue(pos) m = (codenum + 1) // 2 if not codenum % 2: return -m, pos else: return m, pos
python
def _readse(self, pos): """Return interpretation of next bits as a signed exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readue(pos) m = (codenum + 1) // 2 if not codenum % 2: return -m, pos else: return m, pos
[ "def", "_readse", "(", "self", ",", "pos", ")", ":", "codenum", ",", "pos", "=", "self", ".", "_readue", "(", "pos", ")", "m", "=", "(", "codenum", "+", "1", ")", "//", "2", "if", "not", "codenum", "%", "2", ":", "return", "-", "m", ",", "pos", "else", ":", "return", "m", ",", "pos" ]
Return interpretation of next bits as a signed exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code.
[ "Return", "interpretation", "of", "next", "bits", "as", "a", "signed", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1701-L1715
17,868
scott-griffiths/bitstring
bitstring.py
Bits._setuie
def _setuie(self, i): """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "interleaved exponential-Golomb.") self._setbin_unsafe('1' if i == 0 else '0' + '0'.join(bin(i + 1)[3:]) + '1')
python
def _setuie(self, i): """Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i. Raises CreationError if i < 0. """ if i < 0: raise CreationError("Cannot use negative initialiser for unsigned " "interleaved exponential-Golomb.") self._setbin_unsafe('1' if i == 0 else '0' + '0'.join(bin(i + 1)[3:]) + '1')
[ "def", "_setuie", "(", "self", ",", "i", ")", ":", "if", "i", "<", "0", ":", "raise", "CreationError", "(", "\"Cannot use negative initialiser for unsigned \"", "\"interleaved exponential-Golomb.\"", ")", "self", ".", "_setbin_unsafe", "(", "'1'", "if", "i", "==", "0", "else", "'0'", "+", "'0'", ".", "join", "(", "bin", "(", "i", "+", "1", ")", "[", "3", ":", "]", ")", "+", "'1'", ")" ]
Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i. Raises CreationError if i < 0.
[ "Initialise", "bitstring", "with", "unsigned", "interleaved", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1717-L1726
17,869
scott-griffiths/bitstring
bitstring.py
Bits._getuie
def _getuie(self): """Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readuie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
python
def _getuie(self): """Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readuie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
[ "def", "_getuie", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readuie", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single interleaved exponential-Golomb code.\"", ")", "return", "value" ]
Return data as unsigned interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "unsigned", "interleaved", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1748-L1760
17,870
scott-griffiths/bitstring
bitstring.py
Bits._setsie
def _setsie(self, i): """Initialise bitstring with signed interleaved exponential-Golomb code for integer i.""" if not i: self._setbin_unsafe('1') else: self._setuie(abs(i)) self._append(Bits([i < 0]))
python
def _setsie(self, i): """Initialise bitstring with signed interleaved exponential-Golomb code for integer i.""" if not i: self._setbin_unsafe('1') else: self._setuie(abs(i)) self._append(Bits([i < 0]))
[ "def", "_setsie", "(", "self", ",", "i", ")", ":", "if", "not", "i", ":", "self", ".", "_setbin_unsafe", "(", "'1'", ")", "else", ":", "self", ".", "_setuie", "(", "abs", "(", "i", ")", ")", "self", ".", "_append", "(", "Bits", "(", "[", "i", "<", "0", "]", ")", ")" ]
Initialise bitstring with signed interleaved exponential-Golomb code for integer i.
[ "Initialise", "bitstring", "with", "signed", "interleaved", "exponential", "-", "Golomb", "code", "for", "integer", "i", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1762-L1768
17,871
scott-griffiths/bitstring
bitstring.py
Bits._getsie
def _getsie(self): """Return data as signed interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readsie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
python
def _getsie(self): """Return data as signed interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code. """ try: value, newpos = self._readsie(0) if value is None or newpos != self.len: raise ReadError except ReadError: raise InterpretError("Bitstring is not a single interleaved exponential-Golomb code.") return value
[ "def", "_getsie", "(", "self", ")", ":", "try", ":", "value", ",", "newpos", "=", "self", ".", "_readsie", "(", "0", ")", "if", "value", "is", "None", "or", "newpos", "!=", "self", ".", "len", ":", "raise", "ReadError", "except", "ReadError", ":", "raise", "InterpretError", "(", "\"Bitstring is not a single interleaved exponential-Golomb code.\"", ")", "return", "value" ]
Return data as signed interleaved exponential-Golomb code. Raises InterpretError if bitstring is not a single exponential-Golomb code.
[ "Return", "data", "as", "signed", "interleaved", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1770-L1782
17,872
scott-griffiths/bitstring
bitstring.py
Bits._readsie
def _readsie(self, pos): """Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readuie(pos) if not codenum: return 0, pos try: if self[pos]: return -codenum, pos + 1 else: return codenum, pos + 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.")
python
def _readsie(self, pos): """Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code. """ codenum, pos = self._readuie(pos) if not codenum: return 0, pos try: if self[pos]: return -codenum, pos + 1 else: return codenum, pos + 1 except IndexError: raise ReadError("Read off end of bitstring trying to read code.")
[ "def", "_readsie", "(", "self", ",", "pos", ")", ":", "codenum", ",", "pos", "=", "self", ".", "_readuie", "(", "pos", ")", "if", "not", "codenum", ":", "return", "0", ",", "pos", "try", ":", "if", "self", "[", "pos", "]", ":", "return", "-", "codenum", ",", "pos", "+", "1", "else", ":", "return", "codenum", ",", "pos", "+", "1", "except", "IndexError", ":", "raise", "ReadError", "(", "\"Read off end of bitstring trying to read code.\"", ")" ]
Return interpretation of next bits as a signed interleaved exponential-Golomb code. Advances position to after the read code. Raises ReadError if the end of the bitstring is encountered while reading the code.
[ "Return", "interpretation", "of", "next", "bits", "as", "a", "signed", "interleaved", "exponential", "-", "Golomb", "code", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1784-L1802
17,873
scott-griffiths/bitstring
bitstring.py
Bits._setbin_safe
def _setbin_safe(self, binstring): """Reset the bitstring to the value given in binstring.""" binstring = tidy_input_string(binstring) # remove any 0b if present binstring = binstring.replace('0b', '') self._setbin_unsafe(binstring)
python
def _setbin_safe(self, binstring): """Reset the bitstring to the value given in binstring.""" binstring = tidy_input_string(binstring) # remove any 0b if present binstring = binstring.replace('0b', '') self._setbin_unsafe(binstring)
[ "def", "_setbin_safe", "(", "self", ",", "binstring", ")", ":", "binstring", "=", "tidy_input_string", "(", "binstring", ")", "# remove any 0b if present", "binstring", "=", "binstring", ".", "replace", "(", "'0b'", ",", "''", ")", "self", ".", "_setbin_unsafe", "(", "binstring", ")" ]
Reset the bitstring to the value given in binstring.
[ "Reset", "the", "bitstring", "to", "the", "value", "given", "in", "binstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1823-L1828
17,874
scott-griffiths/bitstring
bitstring.py
Bits._setbin_unsafe
def _setbin_unsafe(self, binstring): """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" length = len(binstring) # pad with zeros up to byte boundary if needed boundary = ((length + 7) // 8) * 8 padded_binstring = binstring + '0' * (boundary - length)\ if len(binstring) < boundary else binstring try: bytelist = [int(padded_binstring[x:x + 8], 2) for x in xrange(0, len(padded_binstring), 8)] except ValueError: raise CreationError("Invalid character in bin initialiser {0}.", binstring) self._setbytes_unsafe(bytearray(bytelist), length, 0)
python
def _setbin_unsafe(self, binstring): """Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.""" length = len(binstring) # pad with zeros up to byte boundary if needed boundary = ((length + 7) // 8) * 8 padded_binstring = binstring + '0' * (boundary - length)\ if len(binstring) < boundary else binstring try: bytelist = [int(padded_binstring[x:x + 8], 2) for x in xrange(0, len(padded_binstring), 8)] except ValueError: raise CreationError("Invalid character in bin initialiser {0}.", binstring) self._setbytes_unsafe(bytearray(bytelist), length, 0)
[ "def", "_setbin_unsafe", "(", "self", ",", "binstring", ")", ":", "length", "=", "len", "(", "binstring", ")", "# pad with zeros up to byte boundary if needed", "boundary", "=", "(", "(", "length", "+", "7", ")", "//", "8", ")", "*", "8", "padded_binstring", "=", "binstring", "+", "'0'", "*", "(", "boundary", "-", "length", ")", "if", "len", "(", "binstring", ")", "<", "boundary", "else", "binstring", "try", ":", "bytelist", "=", "[", "int", "(", "padded_binstring", "[", "x", ":", "x", "+", "8", "]", ",", "2", ")", "for", "x", "in", "xrange", "(", "0", ",", "len", "(", "padded_binstring", ")", ",", "8", ")", "]", "except", "ValueError", ":", "raise", "CreationError", "(", "\"Invalid character in bin initialiser {0}.\"", ",", "binstring", ")", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", "bytelist", ")", ",", "length", ",", "0", ")" ]
Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'.
[ "Same", "as", "_setbin_safe", "but", "input", "isn", "t", "sanity", "checked", ".", "binstring", "mustn", "t", "start", "with", "0b", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1830-L1842
17,875
scott-griffiths/bitstring
bitstring.py
Bits._readbin
def _readbin(self, length, start): """Read bits and interpret as a binary string.""" if not length: return '' # Get the byte slice containing our bit slice startbyte, startoffset = divmod(start + self._offset, 8) endbyte = (start + self._offset + length - 1) // 8 b = self._datastore.getbyteslice(startbyte, endbyte + 1) # Convert to a string of '0' and '1's (via a hex string an and int!) try: c = "{:0{}b}".format(int(binascii.hexlify(b), 16), 8*len(b)) except TypeError: # Hack to get Python 2.6 working c = "{0:0{1}b}".format(int(binascii.hexlify(str(b)), 16), 8*len(b)) # Finally chop off any extra bits. return c[startoffset:startoffset + length]
python
def _readbin(self, length, start): """Read bits and interpret as a binary string.""" if not length: return '' # Get the byte slice containing our bit slice startbyte, startoffset = divmod(start + self._offset, 8) endbyte = (start + self._offset + length - 1) // 8 b = self._datastore.getbyteslice(startbyte, endbyte + 1) # Convert to a string of '0' and '1's (via a hex string an and int!) try: c = "{:0{}b}".format(int(binascii.hexlify(b), 16), 8*len(b)) except TypeError: # Hack to get Python 2.6 working c = "{0:0{1}b}".format(int(binascii.hexlify(str(b)), 16), 8*len(b)) # Finally chop off any extra bits. return c[startoffset:startoffset + length]
[ "def", "_readbin", "(", "self", ",", "length", ",", "start", ")", ":", "if", "not", "length", ":", "return", "''", "# Get the byte slice containing our bit slice", "startbyte", ",", "startoffset", "=", "divmod", "(", "start", "+", "self", ".", "_offset", ",", "8", ")", "endbyte", "=", "(", "start", "+", "self", ".", "_offset", "+", "length", "-", "1", ")", "//", "8", "b", "=", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "endbyte", "+", "1", ")", "# Convert to a string of '0' and '1's (via a hex string an and int!)", "try", ":", "c", "=", "\"{:0{}b}\"", ".", "format", "(", "int", "(", "binascii", ".", "hexlify", "(", "b", ")", ",", "16", ")", ",", "8", "*", "len", "(", "b", ")", ")", "except", "TypeError", ":", "# Hack to get Python 2.6 working", "c", "=", "\"{0:0{1}b}\"", ".", "format", "(", "int", "(", "binascii", ".", "hexlify", "(", "str", "(", "b", ")", ")", ",", "16", ")", ",", "8", "*", "len", "(", "b", ")", ")", "# Finally chop off any extra bits.", "return", "c", "[", "startoffset", ":", "startoffset", "+", "length", "]" ]
Read bits and interpret as a binary string.
[ "Read", "bits", "and", "interpret", "as", "a", "binary", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1844-L1859
17,876
scott-griffiths/bitstring
bitstring.py
Bits._setoct
def _setoct(self, octstring): """Reset the bitstring to have the value given in octstring.""" octstring = tidy_input_string(octstring) # remove any 0o if present octstring = octstring.replace('0o', '') binlist = [] for i in octstring: try: if not 0 <= int(i) < 8: raise ValueError binlist.append(OCT_TO_BITS[int(i)]) except ValueError: raise CreationError("Invalid symbol '{0}' in oct initialiser.", i) self._setbin_unsafe(''.join(binlist))
python
def _setoct(self, octstring): """Reset the bitstring to have the value given in octstring.""" octstring = tidy_input_string(octstring) # remove any 0o if present octstring = octstring.replace('0o', '') binlist = [] for i in octstring: try: if not 0 <= int(i) < 8: raise ValueError binlist.append(OCT_TO_BITS[int(i)]) except ValueError: raise CreationError("Invalid symbol '{0}' in oct initialiser.", i) self._setbin_unsafe(''.join(binlist))
[ "def", "_setoct", "(", "self", ",", "octstring", ")", ":", "octstring", "=", "tidy_input_string", "(", "octstring", ")", "# remove any 0o if present", "octstring", "=", "octstring", ".", "replace", "(", "'0o'", ",", "''", ")", "binlist", "=", "[", "]", "for", "i", "in", "octstring", ":", "try", ":", "if", "not", "0", "<=", "int", "(", "i", ")", "<", "8", ":", "raise", "ValueError", "binlist", ".", "append", "(", "OCT_TO_BITS", "[", "int", "(", "i", ")", "]", ")", "except", "ValueError", ":", "raise", "CreationError", "(", "\"Invalid symbol '{0}' in oct initialiser.\"", ",", "i", ")", "self", ".", "_setbin_unsafe", "(", "''", ".", "join", "(", "binlist", ")", ")" ]
Reset the bitstring to have the value given in octstring.
[ "Reset", "the", "bitstring", "to", "have", "the", "value", "given", "in", "octstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1865-L1878
17,877
scott-griffiths/bitstring
bitstring.py
Bits._readoct
def _readoct(self, length, start): """Read bits and interpret as an octal string.""" if length % 3: raise InterpretError("Cannot convert to octal unambiguously - " "not multiple of 3 bits.") if not length: return '' # Get main octal bit by converting from int. # Strip starting 0 or 0o depending on Python version. end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:] if end.endswith('L'): end = end[:-1] middle = '0' * (length // 3 - len(end)) return middle + end
python
def _readoct(self, length, start): """Read bits and interpret as an octal string.""" if length % 3: raise InterpretError("Cannot convert to octal unambiguously - " "not multiple of 3 bits.") if not length: return '' # Get main octal bit by converting from int. # Strip starting 0 or 0o depending on Python version. end = oct(self._readuint(length, start))[LEADING_OCT_CHARS:] if end.endswith('L'): end = end[:-1] middle = '0' * (length // 3 - len(end)) return middle + end
[ "def", "_readoct", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "3", ":", "raise", "InterpretError", "(", "\"Cannot convert to octal unambiguously - \"", "\"not multiple of 3 bits.\"", ")", "if", "not", "length", ":", "return", "''", "# Get main octal bit by converting from int.", "# Strip starting 0 or 0o depending on Python version.", "end", "=", "oct", "(", "self", ".", "_readuint", "(", "length", ",", "start", ")", ")", "[", "LEADING_OCT_CHARS", ":", "]", "if", "end", ".", "endswith", "(", "'L'", ")", ":", "end", "=", "end", "[", ":", "-", "1", "]", "middle", "=", "'0'", "*", "(", "length", "//", "3", "-", "len", "(", "end", ")", ")", "return", "middle", "+", "end" ]
Read bits and interpret as an octal string.
[ "Read", "bits", "and", "interpret", "as", "an", "octal", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1880-L1893
17,878
scott-griffiths/bitstring
bitstring.py
Bits._sethex
def _sethex(self, hexstring): """Reset the bitstring to have the value given in hexstring.""" hexstring = tidy_input_string(hexstring) # remove any 0x if present hexstring = hexstring.replace('0x', '') length = len(hexstring) if length % 2: hexstring += '0' try: try: data = bytearray.fromhex(hexstring) except TypeError: # Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine. data = bytearray.fromhex(unicode(hexstring)) except ValueError: raise CreationError("Invalid symbol in hex initialiser.") self._setbytes_unsafe(data, length * 4, 0)
python
def _sethex(self, hexstring): """Reset the bitstring to have the value given in hexstring.""" hexstring = tidy_input_string(hexstring) # remove any 0x if present hexstring = hexstring.replace('0x', '') length = len(hexstring) if length % 2: hexstring += '0' try: try: data = bytearray.fromhex(hexstring) except TypeError: # Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine. data = bytearray.fromhex(unicode(hexstring)) except ValueError: raise CreationError("Invalid symbol in hex initialiser.") self._setbytes_unsafe(data, length * 4, 0)
[ "def", "_sethex", "(", "self", ",", "hexstring", ")", ":", "hexstring", "=", "tidy_input_string", "(", "hexstring", ")", "# remove any 0x if present", "hexstring", "=", "hexstring", ".", "replace", "(", "'0x'", ",", "''", ")", "length", "=", "len", "(", "hexstring", ")", "if", "length", "%", "2", ":", "hexstring", "+=", "'0'", "try", ":", "try", ":", "data", "=", "bytearray", ".", "fromhex", "(", "hexstring", ")", "except", "TypeError", ":", "# Python 2.6 needs a unicode string (a bug). 2.7 and 3.x work fine.", "data", "=", "bytearray", ".", "fromhex", "(", "unicode", "(", "hexstring", ")", ")", "except", "ValueError", ":", "raise", "CreationError", "(", "\"Invalid symbol in hex initialiser.\"", ")", "self", ".", "_setbytes_unsafe", "(", "data", ",", "length", "*", "4", ",", "0", ")" ]
Reset the bitstring to have the value given in hexstring.
[ "Reset", "the", "bitstring", "to", "have", "the", "value", "given", "in", "hexstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1899-L1915
17,879
scott-griffiths/bitstring
bitstring.py
Bits._readhex
def _readhex(self, length, start): """Read bits and interpret as a hex string.""" if length % 4: raise InterpretError("Cannot convert to hex unambiguously - " "not multiple of 4 bits.") if not length: return '' s = self._slice(start, start + length).tobytes() try: s = s.hex() # Available in Python 3.5 except AttributeError: # This monstrosity is the only thing I could get to work for both 2.6 and 3.1. # TODO: Is utf-8 really what we mean here? s = str(binascii.hexlify(s).decode('utf-8')) # If there's one nibble too many then cut it off return s[:-1] if (length // 4) % 2 else s
python
def _readhex(self, length, start): """Read bits and interpret as a hex string.""" if length % 4: raise InterpretError("Cannot convert to hex unambiguously - " "not multiple of 4 bits.") if not length: return '' s = self._slice(start, start + length).tobytes() try: s = s.hex() # Available in Python 3.5 except AttributeError: # This monstrosity is the only thing I could get to work for both 2.6 and 3.1. # TODO: Is utf-8 really what we mean here? s = str(binascii.hexlify(s).decode('utf-8')) # If there's one nibble too many then cut it off return s[:-1] if (length // 4) % 2 else s
[ "def", "_readhex", "(", "self", ",", "length", ",", "start", ")", ":", "if", "length", "%", "4", ":", "raise", "InterpretError", "(", "\"Cannot convert to hex unambiguously - \"", "\"not multiple of 4 bits.\"", ")", "if", "not", "length", ":", "return", "''", "s", "=", "self", ".", "_slice", "(", "start", ",", "start", "+", "length", ")", ".", "tobytes", "(", ")", "try", ":", "s", "=", "s", ".", "hex", "(", ")", "# Available in Python 3.5", "except", "AttributeError", ":", "# This monstrosity is the only thing I could get to work for both 2.6 and 3.1.", "# TODO: Is utf-8 really what we mean here?", "s", "=", "str", "(", "binascii", ".", "hexlify", "(", "s", ")", ".", "decode", "(", "'utf-8'", ")", ")", "# If there's one nibble too many then cut it off", "return", "s", "[", ":", "-", "1", "]", "if", "(", "length", "//", "4", ")", "%", "2", "else", "s" ]
Read bits and interpret as a hex string.
[ "Read", "bits", "and", "interpret", "as", "a", "hex", "string", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1917-L1932
17,880
scott-griffiths/bitstring
bitstring.py
Bits._ensureinmemory
def _ensureinmemory(self): """Ensure the data is held in memory, not in a file.""" self._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength), self.len, self._offset)
python
def _ensureinmemory(self): """Ensure the data is held in memory, not in a file.""" self._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength), self.len, self._offset)
[ "def", "_ensureinmemory", "(", "self", ")", ":", "self", ".", "_setbytes_unsafe", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "0", ",", "self", ".", "_datastore", ".", "bytelength", ")", ",", "self", ".", "len", ",", "self", ".", "_offset", ")" ]
Ensure the data is held in memory, not in a file.
[ "Ensure", "the", "data", "is", "held", "in", "memory", "not", "in", "a", "file", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1949-L1952
17,881
scott-griffiths/bitstring
bitstring.py
Bits._converttobitstring
def _converttobitstring(cls, bs, offset=0, cache={}): """Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc. """ if isinstance(bs, Bits): return bs try: return cache[(bs, offset)] except KeyError: if isinstance(bs, basestring): b = cls() try: _, tokens = tokenparser(bs) except ValueError as e: raise CreationError(*e.args) if tokens: b._append(Bits._init_with_token(*tokens[0])) b._datastore = offsetcopy(b._datastore, offset) for token in tokens[1:]: b._append(Bits._init_with_token(*token)) assert b._assertsanity() assert b.len == 0 or b._offset == offset if len(cache) < CACHE_SIZE: cache[(bs, offset)] = b return b except TypeError: # Unhashable type pass return cls(bs)
python
def _converttobitstring(cls, bs, offset=0, cache={}): """Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc. """ if isinstance(bs, Bits): return bs try: return cache[(bs, offset)] except KeyError: if isinstance(bs, basestring): b = cls() try: _, tokens = tokenparser(bs) except ValueError as e: raise CreationError(*e.args) if tokens: b._append(Bits._init_with_token(*tokens[0])) b._datastore = offsetcopy(b._datastore, offset) for token in tokens[1:]: b._append(Bits._init_with_token(*token)) assert b._assertsanity() assert b.len == 0 or b._offset == offset if len(cache) < CACHE_SIZE: cache[(bs, offset)] = b return b except TypeError: # Unhashable type pass return cls(bs)
[ "def", "_converttobitstring", "(", "cls", ",", "bs", ",", "offset", "=", "0", ",", "cache", "=", "{", "}", ")", ":", "if", "isinstance", "(", "bs", ",", "Bits", ")", ":", "return", "bs", "try", ":", "return", "cache", "[", "(", "bs", ",", "offset", ")", "]", "except", "KeyError", ":", "if", "isinstance", "(", "bs", ",", "basestring", ")", ":", "b", "=", "cls", "(", ")", "try", ":", "_", ",", "tokens", "=", "tokenparser", "(", "bs", ")", "except", "ValueError", "as", "e", ":", "raise", "CreationError", "(", "*", "e", ".", "args", ")", "if", "tokens", ":", "b", ".", "_append", "(", "Bits", ".", "_init_with_token", "(", "*", "tokens", "[", "0", "]", ")", ")", "b", ".", "_datastore", "=", "offsetcopy", "(", "b", ".", "_datastore", ",", "offset", ")", "for", "token", "in", "tokens", "[", "1", ":", "]", ":", "b", ".", "_append", "(", "Bits", ".", "_init_with_token", "(", "*", "token", ")", ")", "assert", "b", ".", "_assertsanity", "(", ")", "assert", "b", ".", "len", "==", "0", "or", "b", ".", "_offset", "==", "offset", "if", "len", "(", "cache", ")", "<", "CACHE_SIZE", ":", "cache", "[", "(", "bs", ",", "offset", ")", "]", "=", "b", "return", "b", "except", "TypeError", ":", "# Unhashable type", "pass", "return", "cls", "(", "bs", ")" ]
Convert bs to a bitstring and return it. offset gives the suggested bit offset of first significant bit, to optimise append etc.
[ "Convert", "bs", "to", "a", "bitstring", "and", "return", "it", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1955-L1986
17,882
scott-griffiths/bitstring
bitstring.py
Bits._slice
def _slice(self, start, end): """Used internally to get a slice, without error checking.""" if end == start: return self.__class__() offset = self._offset startbyte, newoffset = divmod(start + offset, 8) endbyte = (end + offset - 1) // 8 bs = self.__class__() bs._setbytes_unsafe(self._datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset) return bs
python
def _slice(self, start, end): """Used internally to get a slice, without error checking.""" if end == start: return self.__class__() offset = self._offset startbyte, newoffset = divmod(start + offset, 8) endbyte = (end + offset - 1) // 8 bs = self.__class__() bs._setbytes_unsafe(self._datastore.getbyteslice(startbyte, endbyte + 1), end - start, newoffset) return bs
[ "def", "_slice", "(", "self", ",", "start", ",", "end", ")", ":", "if", "end", "==", "start", ":", "return", "self", ".", "__class__", "(", ")", "offset", "=", "self", ".", "_offset", "startbyte", ",", "newoffset", "=", "divmod", "(", "start", "+", "offset", ",", "8", ")", "endbyte", "=", "(", "end", "+", "offset", "-", "1", ")", "//", "8", "bs", "=", "self", ".", "__class__", "(", ")", "bs", ".", "_setbytes_unsafe", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "startbyte", ",", "endbyte", "+", "1", ")", ",", "end", "-", "start", ",", "newoffset", ")", "return", "bs" ]
Used internally to get a slice, without error checking.
[ "Used", "internally", "to", "get", "a", "slice", "without", "error", "checking", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L1995-L2004
17,883
scott-griffiths/bitstring
bitstring.py
Bits._readtoken
def _readtoken(self, name, pos, length): """Reads a token from the bitstring and returns the result.""" if length is not None and int(length) > self.length - pos: raise ReadError("Reading off the end of the data. " "Tried to read {0} bits when only {1} available.".format(int(length), self.length - pos)) try: val = name_to_read[name](self, length, pos) return val, pos + length except KeyError: if name == 'pad': return None, pos + length raise ValueError("Can't parse token {0}:{1}".format(name, length)) except TypeError: # This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos. return name_to_read[name](self, pos)
python
def _readtoken(self, name, pos, length): """Reads a token from the bitstring and returns the result.""" if length is not None and int(length) > self.length - pos: raise ReadError("Reading off the end of the data. " "Tried to read {0} bits when only {1} available.".format(int(length), self.length - pos)) try: val = name_to_read[name](self, length, pos) return val, pos + length except KeyError: if name == 'pad': return None, pos + length raise ValueError("Can't parse token {0}:{1}".format(name, length)) except TypeError: # This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos. return name_to_read[name](self, pos)
[ "def", "_readtoken", "(", "self", ",", "name", ",", "pos", ",", "length", ")", ":", "if", "length", "is", "not", "None", "and", "int", "(", "length", ")", ">", "self", ".", "length", "-", "pos", ":", "raise", "ReadError", "(", "\"Reading off the end of the data. \"", "\"Tried to read {0} bits when only {1} available.\"", ".", "format", "(", "int", "(", "length", ")", ",", "self", ".", "length", "-", "pos", ")", ")", "try", ":", "val", "=", "name_to_read", "[", "name", "]", "(", "self", ",", "length", ",", "pos", ")", "return", "val", ",", "pos", "+", "length", "except", "KeyError", ":", "if", "name", "==", "'pad'", ":", "return", "None", ",", "pos", "+", "length", "raise", "ValueError", "(", "\"Can't parse token {0}:{1}\"", ".", "format", "(", "name", ",", "length", ")", ")", "except", "TypeError", ":", "# This is for the 'ue', 'se' and 'bool' tokens. They will also return the new pos.", "return", "name_to_read", "[", "name", "]", "(", "self", ",", "pos", ")" ]
Reads a token from the bitstring and returns the result.
[ "Reads", "a", "token", "from", "the", "bitstring", "and", "returns", "the", "result", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2006-L2020
17,884
scott-griffiths/bitstring
bitstring.py
Bits._reverse
def _reverse(self): """Reverse all bits in-place.""" # Reverse the contents of each byte n = [BYTE_REVERSAL_DICT[b] for b in self._datastore.rawbytes] # Then reverse the order of the bytes n.reverse() # The new offset is the number of bits that were unused at the end. newoffset = 8 - (self._offset + self.len) % 8 if newoffset == 8: newoffset = 0 self._setbytes_unsafe(bytearray().join(n), self.length, newoffset)
python
def _reverse(self): """Reverse all bits in-place.""" # Reverse the contents of each byte n = [BYTE_REVERSAL_DICT[b] for b in self._datastore.rawbytes] # Then reverse the order of the bytes n.reverse() # The new offset is the number of bits that were unused at the end. newoffset = 8 - (self._offset + self.len) % 8 if newoffset == 8: newoffset = 0 self._setbytes_unsafe(bytearray().join(n), self.length, newoffset)
[ "def", "_reverse", "(", "self", ")", ":", "# Reverse the contents of each byte", "n", "=", "[", "BYTE_REVERSAL_DICT", "[", "b", "]", "for", "b", "in", "self", ".", "_datastore", ".", "rawbytes", "]", "# Then reverse the order of the bytes", "n", ".", "reverse", "(", ")", "# The new offset is the number of bits that were unused at the end.", "newoffset", "=", "8", "-", "(", "self", ".", "_offset", "+", "self", ".", "len", ")", "%", "8", "if", "newoffset", "==", "8", ":", "newoffset", "=", "0", "self", ".", "_setbytes_unsafe", "(", "bytearray", "(", ")", ".", "join", "(", "n", ")", ",", "self", ".", "length", ",", "newoffset", ")" ]
Reverse all bits in-place.
[ "Reverse", "all", "bits", "in", "-", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2030-L2040
17,885
scott-griffiths/bitstring
bitstring.py
Bits._truncateend
def _truncateend(self, bits): """Truncate bits from the end of the bitstring.""" assert 0 <= bits <= self.len if not bits: return if bits == self.len: self._clear() return newlength_in_bytes = (self._offset + self.len - bits + 7) // 8 self._setbytes_unsafe(self._datastore.getbyteslice(0, newlength_in_bytes), self.len - bits, self._offset) assert self._assertsanity()
python
def _truncateend(self, bits): """Truncate bits from the end of the bitstring.""" assert 0 <= bits <= self.len if not bits: return if bits == self.len: self._clear() return newlength_in_bytes = (self._offset + self.len - bits + 7) // 8 self._setbytes_unsafe(self._datastore.getbyteslice(0, newlength_in_bytes), self.len - bits, self._offset) assert self._assertsanity()
[ "def", "_truncateend", "(", "self", ",", "bits", ")", ":", "assert", "0", "<=", "bits", "<=", "self", ".", "len", "if", "not", "bits", ":", "return", "if", "bits", "==", "self", ".", "len", ":", "self", ".", "_clear", "(", ")", "return", "newlength_in_bytes", "=", "(", "self", ".", "_offset", "+", "self", ".", "len", "-", "bits", "+", "7", ")", "//", "8", "self", ".", "_setbytes_unsafe", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "0", ",", "newlength_in_bytes", ")", ",", "self", ".", "len", "-", "bits", ",", "self", ".", "_offset", ")", "assert", "self", ".", "_assertsanity", "(", ")" ]
Truncate bits from the end of the bitstring.
[ "Truncate", "bits", "from", "the", "end", "of", "the", "bitstring", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2055-L2066
17,886
scott-griffiths/bitstring
bitstring.py
Bits._insert
def _insert(self, bs, pos): """Insert bs at pos.""" assert 0 <= pos <= self.len if pos > self.len // 2: # Inserting nearer end, so cut off end. end = self._slice(pos, self.len) self._truncateend(self.len - pos) self._append(bs) self._append(end) else: # Inserting nearer start, so cut off start. start = self._slice(0, pos) self._truncatestart(pos) self._prepend(bs) self._prepend(start) try: self._pos = pos + bs.len except AttributeError: pass assert self._assertsanity()
python
def _insert(self, bs, pos): """Insert bs at pos.""" assert 0 <= pos <= self.len if pos > self.len // 2: # Inserting nearer end, so cut off end. end = self._slice(pos, self.len) self._truncateend(self.len - pos) self._append(bs) self._append(end) else: # Inserting nearer start, so cut off start. start = self._slice(0, pos) self._truncatestart(pos) self._prepend(bs) self._prepend(start) try: self._pos = pos + bs.len except AttributeError: pass assert self._assertsanity()
[ "def", "_insert", "(", "self", ",", "bs", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<=", "self", ".", "len", "if", "pos", ">", "self", ".", "len", "//", "2", ":", "# Inserting nearer end, so cut off end.", "end", "=", "self", ".", "_slice", "(", "pos", ",", "self", ".", "len", ")", "self", ".", "_truncateend", "(", "self", ".", "len", "-", "pos", ")", "self", ".", "_append", "(", "bs", ")", "self", ".", "_append", "(", "end", ")", "else", ":", "# Inserting nearer start, so cut off start.", "start", "=", "self", ".", "_slice", "(", "0", ",", "pos", ")", "self", ".", "_truncatestart", "(", "pos", ")", "self", ".", "_prepend", "(", "bs", ")", "self", ".", "_prepend", "(", "start", ")", "try", ":", "self", ".", "_pos", "=", "pos", "+", "bs", ".", "len", "except", "AttributeError", ":", "pass", "assert", "self", ".", "_assertsanity", "(", ")" ]
Insert bs at pos.
[ "Insert", "bs", "at", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2068-L2087
17,887
scott-griffiths/bitstring
bitstring.py
Bits._overwrite
def _overwrite(self, bs, pos): """Overwrite with bs at pos.""" assert 0 <= pos < self.len if bs is self: # Just overwriting with self, so do nothing. assert pos == 0 return firstbytepos = (self._offset + pos) // 8 lastbytepos = (self._offset + pos + bs.len - 1) // 8 bytepos, bitoffset = divmod(self._offset + pos, 8) if firstbytepos == lastbytepos: mask = ((1 << bs.len) - 1) << (8 - bs.len - bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) else: # Do first byte mask = (1 << (8 - bitoffset)) - 1 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) # Now do all the full bytes self._datastore.setbyteslice(firstbytepos + 1, lastbytepos, d.getbyteslice(1, lastbytepos - firstbytepos)) # and finally the last byte bitsleft = (self._offset + pos + bs.len) % 8 if not bitsleft: bitsleft = 8 mask = (1 << (8 - bitsleft)) - 1 self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) & mask) self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) | (d.getbyte(d.bytelength - 1) & ~mask)) assert self._assertsanity()
python
def _overwrite(self, bs, pos): """Overwrite with bs at pos.""" assert 0 <= pos < self.len if bs is self: # Just overwriting with self, so do nothing. assert pos == 0 return firstbytepos = (self._offset + pos) // 8 lastbytepos = (self._offset + pos + bs.len - 1) // 8 bytepos, bitoffset = divmod(self._offset + pos, 8) if firstbytepos == lastbytepos: mask = ((1 << bs.len) - 1) << (8 - bs.len - bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) else: # Do first byte mask = (1 << (8 - bitoffset)) - 1 self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) & (~mask)) d = offsetcopy(bs._datastore, bitoffset) self._datastore.setbyte(bytepos, self._datastore.getbyte(bytepos) | (d.getbyte(0) & mask)) # Now do all the full bytes self._datastore.setbyteslice(firstbytepos + 1, lastbytepos, d.getbyteslice(1, lastbytepos - firstbytepos)) # and finally the last byte bitsleft = (self._offset + pos + bs.len) % 8 if not bitsleft: bitsleft = 8 mask = (1 << (8 - bitsleft)) - 1 self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) & mask) self._datastore.setbyte(lastbytepos, self._datastore.getbyte(lastbytepos) | (d.getbyte(d.bytelength - 1) & ~mask)) assert self._assertsanity()
[ "def", "_overwrite", "(", "self", ",", "bs", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "if", "bs", "is", "self", ":", "# Just overwriting with self, so do nothing.", "assert", "pos", "==", "0", "return", "firstbytepos", "=", "(", "self", ".", "_offset", "+", "pos", ")", "//", "8", "lastbytepos", "=", "(", "self", ".", "_offset", "+", "pos", "+", "bs", ".", "len", "-", "1", ")", "//", "8", "bytepos", ",", "bitoffset", "=", "divmod", "(", "self", ".", "_offset", "+", "pos", ",", "8", ")", "if", "firstbytepos", "==", "lastbytepos", ":", "mask", "=", "(", "(", "1", "<<", "bs", ".", "len", ")", "-", "1", ")", "<<", "(", "8", "-", "bs", ".", "len", "-", "bitoffset", ")", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "&", "(", "~", "mask", ")", ")", "d", "=", "offsetcopy", "(", "bs", ".", "_datastore", ",", "bitoffset", ")", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "|", "(", "d", ".", "getbyte", "(", "0", ")", "&", "mask", ")", ")", "else", ":", "# Do first byte", "mask", "=", "(", "1", "<<", "(", "8", "-", "bitoffset", ")", ")", "-", "1", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "&", "(", "~", "mask", ")", ")", "d", "=", "offsetcopy", "(", "bs", ".", "_datastore", ",", "bitoffset", ")", "self", ".", "_datastore", ".", "setbyte", "(", "bytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "bytepos", ")", "|", "(", "d", ".", "getbyte", "(", "0", ")", "&", "mask", ")", ")", "# Now do all the full bytes", "self", ".", "_datastore", ".", "setbyteslice", "(", "firstbytepos", "+", "1", ",", "lastbytepos", ",", "d", ".", "getbyteslice", "(", "1", ",", "lastbytepos", "-", "firstbytepos", ")", ")", "# and finally the last byte", "bitsleft", "=", "(", "self", ".", "_offset", "+", "pos", "+", "bs", ".", "len", ")", "%", "8", "if", "not", "bitsleft", ":", "bitsleft", "=", "8", "mask", "=", "(", "1", "<<", "(", "8", "-", "bitsleft", ")", ")", "-", "1", "self", ".", "_datastore", ".", "setbyte", "(", "lastbytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "lastbytepos", ")", "&", "mask", ")", "self", ".", "_datastore", ".", "setbyte", "(", "lastbytepos", ",", "self", ".", "_datastore", ".", "getbyte", "(", "lastbytepos", ")", "|", "(", "d", ".", "getbyte", "(", "d", ".", "bytelength", "-", "1", ")", "&", "~", "mask", ")", ")", "assert", "self", ".", "_assertsanity", "(", ")" ]
Overwrite with bs at pos.
[ "Overwrite", "with", "bs", "at", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2089-L2120
17,888
scott-griffiths/bitstring
bitstring.py
Bits._delete
def _delete(self, bits, pos): """Delete bits at pos.""" assert 0 <= pos <= self.len assert pos + bits <= self.len if not pos: # Cutting bits off at the start. self._truncatestart(bits) return if pos + bits == self.len: # Cutting bits off at the end. self._truncateend(bits) return if pos > self.len - pos - bits: # More bits before cut point than after it, so do bit shifting # on the final bits. end = self._slice(pos + bits, self.len) assert self.len - pos > 0 self._truncateend(self.len - pos) self._append(end) return # More bits after the cut point than before it. start = self._slice(0, pos) self._truncatestart(pos + bits) self._prepend(start) return
python
def _delete(self, bits, pos): """Delete bits at pos.""" assert 0 <= pos <= self.len assert pos + bits <= self.len if not pos: # Cutting bits off at the start. self._truncatestart(bits) return if pos + bits == self.len: # Cutting bits off at the end. self._truncateend(bits) return if pos > self.len - pos - bits: # More bits before cut point than after it, so do bit shifting # on the final bits. end = self._slice(pos + bits, self.len) assert self.len - pos > 0 self._truncateend(self.len - pos) self._append(end) return # More bits after the cut point than before it. start = self._slice(0, pos) self._truncatestart(pos + bits) self._prepend(start) return
[ "def", "_delete", "(", "self", ",", "bits", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<=", "self", ".", "len", "assert", "pos", "+", "bits", "<=", "self", ".", "len", "if", "not", "pos", ":", "# Cutting bits off at the start.", "self", ".", "_truncatestart", "(", "bits", ")", "return", "if", "pos", "+", "bits", "==", "self", ".", "len", ":", "# Cutting bits off at the end.", "self", ".", "_truncateend", "(", "bits", ")", "return", "if", "pos", ">", "self", ".", "len", "-", "pos", "-", "bits", ":", "# More bits before cut point than after it, so do bit shifting", "# on the final bits.", "end", "=", "self", ".", "_slice", "(", "pos", "+", "bits", ",", "self", ".", "len", ")", "assert", "self", ".", "len", "-", "pos", ">", "0", "self", ".", "_truncateend", "(", "self", ".", "len", "-", "pos", ")", "self", ".", "_append", "(", "end", ")", "return", "# More bits after the cut point than before it.", "start", "=", "self", ".", "_slice", "(", "0", ",", "pos", ")", "self", ".", "_truncatestart", "(", "pos", "+", "bits", ")", "self", ".", "_prepend", "(", "start", ")", "return" ]
Delete bits at pos.
[ "Delete", "bits", "at", "pos", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2122-L2146
17,889
scott-griffiths/bitstring
bitstring.py
Bits._reversebytes
def _reversebytes(self, start, end): """Reverse bytes in-place.""" # Make the start occur on a byte boundary # TODO: We could be cleverer here to avoid changing the offset. newoffset = 8 - (start % 8) if newoffset == 8: newoffset = 0 self._datastore = offsetcopy(self._datastore, newoffset) # Now just reverse the byte data toreverse = bytearray(self._datastore.getbyteslice((newoffset + start) // 8, (newoffset + end) // 8)) toreverse.reverse() self._datastore.setbyteslice((newoffset + start) // 8, (newoffset + end) // 8, toreverse)
python
def _reversebytes(self, start, end): """Reverse bytes in-place.""" # Make the start occur on a byte boundary # TODO: We could be cleverer here to avoid changing the offset. newoffset = 8 - (start % 8) if newoffset == 8: newoffset = 0 self._datastore = offsetcopy(self._datastore, newoffset) # Now just reverse the byte data toreverse = bytearray(self._datastore.getbyteslice((newoffset + start) // 8, (newoffset + end) // 8)) toreverse.reverse() self._datastore.setbyteslice((newoffset + start) // 8, (newoffset + end) // 8, toreverse)
[ "def", "_reversebytes", "(", "self", ",", "start", ",", "end", ")", ":", "# Make the start occur on a byte boundary", "# TODO: We could be cleverer here to avoid changing the offset.", "newoffset", "=", "8", "-", "(", "start", "%", "8", ")", "if", "newoffset", "==", "8", ":", "newoffset", "=", "0", "self", ".", "_datastore", "=", "offsetcopy", "(", "self", ".", "_datastore", ",", "newoffset", ")", "# Now just reverse the byte data", "toreverse", "=", "bytearray", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "(", "newoffset", "+", "start", ")", "//", "8", ",", "(", "newoffset", "+", "end", ")", "//", "8", ")", ")", "toreverse", ".", "reverse", "(", ")", "self", ".", "_datastore", ".", "setbyteslice", "(", "(", "newoffset", "+", "start", ")", "//", "8", ",", "(", "newoffset", "+", "end", ")", "//", "8", ",", "toreverse", ")" ]
Reverse bytes in-place.
[ "Reverse", "bytes", "in", "-", "place", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2148-L2159
17,890
scott-griffiths/bitstring
bitstring.py
Bits._set
def _set(self, pos): """Set bit at pos to 1.""" assert 0 <= pos < self.len self._datastore.setbit(pos)
python
def _set(self, pos): """Set bit at pos to 1.""" assert 0 <= pos < self.len self._datastore.setbit(pos)
[ "def", "_set", "(", "self", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "self", ".", "_datastore", ".", "setbit", "(", "pos", ")" ]
Set bit at pos to 1.
[ "Set", "bit", "at", "pos", "to", "1", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2161-L2164
17,891
scott-griffiths/bitstring
bitstring.py
Bits._unset
def _unset(self, pos): """Set bit at pos to 0.""" assert 0 <= pos < self.len self._datastore.unsetbit(pos)
python
def _unset(self, pos): """Set bit at pos to 0.""" assert 0 <= pos < self.len self._datastore.unsetbit(pos)
[ "def", "_unset", "(", "self", ",", "pos", ")", ":", "assert", "0", "<=", "pos", "<", "self", ".", "len", "self", ".", "_datastore", ".", "unsetbit", "(", "pos", ")" ]
Set bit at pos to 0.
[ "Set", "bit", "at", "pos", "to", "0", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2166-L2169
17,892
scott-griffiths/bitstring
bitstring.py
Bits._invert_all
def _invert_all(self): """Invert every bit.""" set = self._datastore.setbyte get = self._datastore.getbyte for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength): set(p, 256 + ~get(p))
python
def _invert_all(self): """Invert every bit.""" set = self._datastore.setbyte get = self._datastore.getbyte for p in xrange(self._datastore.byteoffset, self._datastore.byteoffset + self._datastore.bytelength): set(p, 256 + ~get(p))
[ "def", "_invert_all", "(", "self", ")", ":", "set", "=", "self", ".", "_datastore", ".", "setbyte", "get", "=", "self", ".", "_datastore", ".", "getbyte", "for", "p", "in", "xrange", "(", "self", ".", "_datastore", ".", "byteoffset", ",", "self", ".", "_datastore", ".", "byteoffset", "+", "self", ".", "_datastore", ".", "bytelength", ")", ":", "set", "(", "p", ",", "256", "+", "~", "get", "(", "p", ")", ")" ]
Invert every bit.
[ "Invert", "every", "bit", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2176-L2181
17,893
scott-griffiths/bitstring
bitstring.py
Bits._ilshift
def _ilshift(self, n): """Shift bits by n to the left in place. Return self.""" assert 0 < n <= self.len self._append(Bits(n)) self._truncatestart(n) return self
python
def _ilshift(self, n): """Shift bits by n to the left in place. Return self.""" assert 0 < n <= self.len self._append(Bits(n)) self._truncatestart(n) return self
[ "def", "_ilshift", "(", "self", ",", "n", ")", ":", "assert", "0", "<", "n", "<=", "self", ".", "len", "self", ".", "_append", "(", "Bits", "(", "n", ")", ")", "self", ".", "_truncatestart", "(", "n", ")", "return", "self" ]
Shift bits by n to the left in place. Return self.
[ "Shift", "bits", "by", "n", "to", "the", "left", "in", "place", ".", "Return", "self", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2183-L2188
17,894
scott-griffiths/bitstring
bitstring.py
Bits._irshift
def _irshift(self, n): """Shift bits by n to the right in place. Return self.""" assert 0 < n <= self.len self._prepend(Bits(n)) self._truncateend(n) return self
python
def _irshift(self, n): """Shift bits by n to the right in place. Return self.""" assert 0 < n <= self.len self._prepend(Bits(n)) self._truncateend(n) return self
[ "def", "_irshift", "(", "self", ",", "n", ")", ":", "assert", "0", "<", "n", "<=", "self", ".", "len", "self", ".", "_prepend", "(", "Bits", "(", "n", ")", ")", "self", ".", "_truncateend", "(", "n", ")", "return", "self" ]
Shift bits by n to the right in place. Return self.
[ "Shift", "bits", "by", "n", "to", "the", "right", "in", "place", ".", "Return", "self", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2190-L2195
17,895
scott-griffiths/bitstring
bitstring.py
Bits._imul
def _imul(self, n): """Concatenate n copies of self in place. Return self.""" assert n >= 0 if not n: self._clear() return self m = 1 old_len = self.len while m * 2 < n: self._append(self) m *= 2 self._append(self[0:(n - m) * old_len]) return self
python
def _imul(self, n): """Concatenate n copies of self in place. Return self.""" assert n >= 0 if not n: self._clear() return self m = 1 old_len = self.len while m * 2 < n: self._append(self) m *= 2 self._append(self[0:(n - m) * old_len]) return self
[ "def", "_imul", "(", "self", ",", "n", ")", ":", "assert", "n", ">=", "0", "if", "not", "n", ":", "self", ".", "_clear", "(", ")", "return", "self", "m", "=", "1", "old_len", "=", "self", ".", "len", "while", "m", "*", "2", "<", "n", ":", "self", ".", "_append", "(", "self", ")", "m", "*=", "2", "self", ".", "_append", "(", "self", "[", "0", ":", "(", "n", "-", "m", ")", "*", "old_len", "]", ")", "return", "self" ]
Concatenate n copies of self in place. Return self.
[ "Concatenate", "n", "copies", "of", "self", "in", "place", ".", "Return", "self", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2197-L2209
17,896
scott-griffiths/bitstring
bitstring.py
Bits._validate_slice
def _validate_slice(self, start, end): """Validate start and end and return them as positive bit positions.""" if start is None: start = 0 elif start < 0: start += self.len if end is None: end = self.len elif end < 0: end += self.len if not 0 <= end <= self.len: raise ValueError("end is not a valid position in the bitstring.") if not 0 <= start <= self.len: raise ValueError("start is not a valid position in the bitstring.") if end < start: raise ValueError("end must not be less than start.") return start, end
python
def _validate_slice(self, start, end): """Validate start and end and return them as positive bit positions.""" if start is None: start = 0 elif start < 0: start += self.len if end is None: end = self.len elif end < 0: end += self.len if not 0 <= end <= self.len: raise ValueError("end is not a valid position in the bitstring.") if not 0 <= start <= self.len: raise ValueError("start is not a valid position in the bitstring.") if end < start: raise ValueError("end must not be less than start.") return start, end
[ "def", "_validate_slice", "(", "self", ",", "start", ",", "end", ")", ":", "if", "start", "is", "None", ":", "start", "=", "0", "elif", "start", "<", "0", ":", "start", "+=", "self", ".", "len", "if", "end", "is", "None", ":", "end", "=", "self", ".", "len", "elif", "end", "<", "0", ":", "end", "+=", "self", ".", "len", "if", "not", "0", "<=", "end", "<=", "self", ".", "len", ":", "raise", "ValueError", "(", "\"end is not a valid position in the bitstring.\"", ")", "if", "not", "0", "<=", "start", "<=", "self", ".", "len", ":", "raise", "ValueError", "(", "\"start is not a valid position in the bitstring.\"", ")", "if", "end", "<", "start", ":", "raise", "ValueError", "(", "\"end must not be less than start.\"", ")", "return", "start", ",", "end" ]
Validate start and end and return them as positive bit positions.
[ "Validate", "start", "and", "end", "and", "return", "them", "as", "positive", "bit", "positions", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2240-L2256
17,897
scott-griffiths/bitstring
bitstring.py
Bits._findbytes
def _findbytes(self, bytes_, start, end, bytealigned): """Quicker version of find when everything's whole byte and byte aligned. """ assert self._datastore.offset == 0 assert bytealigned is True # Extract data bytes from bitstring to be found. bytepos = (start + 7) // 8 found = False p = bytepos finalpos = end // 8 increment = max(1024, len(bytes_) * 10) buffersize = increment + len(bytes_) while p < finalpos: # Read in file or from memory in overlapping chunks and search the chunks. buf = bytearray(self._datastore.getbyteslice(p, min(p + buffersize, finalpos))) pos = buf.find(bytes_) if pos != -1: found = True p += pos break p += increment if not found: return () return (p * 8,)
python
def _findbytes(self, bytes_, start, end, bytealigned): """Quicker version of find when everything's whole byte and byte aligned. """ assert self._datastore.offset == 0 assert bytealigned is True # Extract data bytes from bitstring to be found. bytepos = (start + 7) // 8 found = False p = bytepos finalpos = end // 8 increment = max(1024, len(bytes_) * 10) buffersize = increment + len(bytes_) while p < finalpos: # Read in file or from memory in overlapping chunks and search the chunks. buf = bytearray(self._datastore.getbyteslice(p, min(p + buffersize, finalpos))) pos = buf.find(bytes_) if pos != -1: found = True p += pos break p += increment if not found: return () return (p * 8,)
[ "def", "_findbytes", "(", "self", ",", "bytes_", ",", "start", ",", "end", ",", "bytealigned", ")", ":", "assert", "self", ".", "_datastore", ".", "offset", "==", "0", "assert", "bytealigned", "is", "True", "# Extract data bytes from bitstring to be found.", "bytepos", "=", "(", "start", "+", "7", ")", "//", "8", "found", "=", "False", "p", "=", "bytepos", "finalpos", "=", "end", "//", "8", "increment", "=", "max", "(", "1024", ",", "len", "(", "bytes_", ")", "*", "10", ")", "buffersize", "=", "increment", "+", "len", "(", "bytes_", ")", "while", "p", "<", "finalpos", ":", "# Read in file or from memory in overlapping chunks and search the chunks.", "buf", "=", "bytearray", "(", "self", ".", "_datastore", ".", "getbyteslice", "(", "p", ",", "min", "(", "p", "+", "buffersize", ",", "finalpos", ")", ")", ")", "pos", "=", "buf", ".", "find", "(", "bytes_", ")", "if", "pos", "!=", "-", "1", ":", "found", "=", "True", "p", "+=", "pos", "break", "p", "+=", "increment", "if", "not", "found", ":", "return", "(", ")", "return", "(", "p", "*", "8", ",", ")" ]
Quicker version of find when everything's whole byte and byte aligned.
[ "Quicker", "version", "of", "find", "when", "everything", "s", "whole", "byte", "and", "byte", "aligned", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2352-L2377
17,898
scott-griffiths/bitstring
bitstring.py
Bits._findregex
def _findregex(self, reg_ex, start, end, bytealigned): """Find first occurrence of a compiled regular expression. Note that this doesn't support arbitrary regexes, in particular they must match a known length. """ p = start length = len(reg_ex.pattern) # We grab overlapping chunks of the binary representation and # do an ordinary string search within that. increment = max(4096, length * 10) buffersize = increment + length while p < end: buf = self._readbin(min(buffersize, end - p), p) # Test using regular expressions... m = reg_ex.search(buf) if m: pos = m.start() # pos = buf.find(targetbin) # if pos != -1: # if bytealigned then we only accept byte aligned positions. if not bytealigned or (p + pos) % 8 == 0: return (p + pos,) if bytealigned: # Advance to just beyond the non-byte-aligned match and try again... p += pos + 1 continue p += increment # Not found, return empty tuple return ()
python
def _findregex(self, reg_ex, start, end, bytealigned): """Find first occurrence of a compiled regular expression. Note that this doesn't support arbitrary regexes, in particular they must match a known length. """ p = start length = len(reg_ex.pattern) # We grab overlapping chunks of the binary representation and # do an ordinary string search within that. increment = max(4096, length * 10) buffersize = increment + length while p < end: buf = self._readbin(min(buffersize, end - p), p) # Test using regular expressions... m = reg_ex.search(buf) if m: pos = m.start() # pos = buf.find(targetbin) # if pos != -1: # if bytealigned then we only accept byte aligned positions. if not bytealigned or (p + pos) % 8 == 0: return (p + pos,) if bytealigned: # Advance to just beyond the non-byte-aligned match and try again... p += pos + 1 continue p += increment # Not found, return empty tuple return ()
[ "def", "_findregex", "(", "self", ",", "reg_ex", ",", "start", ",", "end", ",", "bytealigned", ")", ":", "p", "=", "start", "length", "=", "len", "(", "reg_ex", ".", "pattern", ")", "# We grab overlapping chunks of the binary representation and", "# do an ordinary string search within that.", "increment", "=", "max", "(", "4096", ",", "length", "*", "10", ")", "buffersize", "=", "increment", "+", "length", "while", "p", "<", "end", ":", "buf", "=", "self", ".", "_readbin", "(", "min", "(", "buffersize", ",", "end", "-", "p", ")", ",", "p", ")", "# Test using regular expressions...", "m", "=", "reg_ex", ".", "search", "(", "buf", ")", "if", "m", ":", "pos", "=", "m", ".", "start", "(", ")", "# pos = buf.find(targetbin)", "# if pos != -1:", "# if bytealigned then we only accept byte aligned positions.", "if", "not", "bytealigned", "or", "(", "p", "+", "pos", ")", "%", "8", "==", "0", ":", "return", "(", "p", "+", "pos", ",", ")", "if", "bytealigned", ":", "# Advance to just beyond the non-byte-aligned match and try again...", "p", "+=", "pos", "+", "1", "continue", "p", "+=", "increment", "# Not found, return empty tuple", "return", "(", ")" ]
Find first occurrence of a compiled regular expression. Note that this doesn't support arbitrary regexes, in particular they must match a known length.
[ "Find", "first", "occurrence", "of", "a", "compiled", "regular", "expression", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2379-L2409
17,899
scott-griffiths/bitstring
bitstring.py
Bits.find
def find(self, bs, start=None, end=None, bytealigned=None): """Find first occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. >>> BitArray('0xc3e').find('0b1111') (6,) """ bs = Bits(bs) if not bs.len: raise ValueError("Cannot find an empty bitstring.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if bytealigned and not bs.len % 8 and not self._datastore.offset: p = self._findbytes(bs.bytes, start, end, bytealigned) else: p = self._findregex(re.compile(bs._getbin()), start, end, bytealigned) # If called from a class that has a pos, set it try: self._pos = p[0] except (AttributeError, IndexError): pass return p
python
def find(self, bs, start=None, end=None, bytealigned=None): """Find first occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. >>> BitArray('0xc3e').find('0b1111') (6,) """ bs = Bits(bs) if not bs.len: raise ValueError("Cannot find an empty bitstring.") start, end = self._validate_slice(start, end) if bytealigned is None: bytealigned = globals()['bytealigned'] if bytealigned and not bs.len % 8 and not self._datastore.offset: p = self._findbytes(bs.bytes, start, end, bytealigned) else: p = self._findregex(re.compile(bs._getbin()), start, end, bytealigned) # If called from a class that has a pos, set it try: self._pos = p[0] except (AttributeError, IndexError): pass return p
[ "def", "find", "(", "self", ",", "bs", ",", "start", "=", "None", ",", "end", "=", "None", ",", "bytealigned", "=", "None", ")", ":", "bs", "=", "Bits", "(", "bs", ")", "if", "not", "bs", ".", "len", ":", "raise", "ValueError", "(", "\"Cannot find an empty bitstring.\"", ")", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "bytealigned", "is", "None", ":", "bytealigned", "=", "globals", "(", ")", "[", "'bytealigned'", "]", "if", "bytealigned", "and", "not", "bs", ".", "len", "%", "8", "and", "not", "self", ".", "_datastore", ".", "offset", ":", "p", "=", "self", ".", "_findbytes", "(", "bs", ".", "bytes", ",", "start", ",", "end", ",", "bytealigned", ")", "else", ":", "p", "=", "self", ".", "_findregex", "(", "re", ".", "compile", "(", "bs", ".", "_getbin", "(", ")", ")", ",", "start", ",", "end", ",", "bytealigned", ")", "# If called from a class that has a pos, set it", "try", ":", "self", ".", "_pos", "=", "p", "[", "0", "]", "except", "(", "AttributeError", ",", "IndexError", ")", ":", "pass", "return", "p" ]
Find first occurrence of substring bs. Returns a single item tuple with the bit position if found, or an empty tuple if not found. The bit position (pos property) will also be set to the start of the substring if it is found. bs -- The bitstring to find. start -- The bit position to start the search. Defaults to 0. end -- The bit position one past the last bit to search. Defaults to self.len. bytealigned -- If True the bitstring will only be found on byte boundaries. Raises ValueError if bs is empty, if start < 0, if end > self.len or if end < start. >>> BitArray('0xc3e').find('0b1111') (6,)
[ "Find", "first", "occurrence", "of", "substring", "bs", "." ]
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2411-L2447