Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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) //... | [
"Read bits and interpret as an unsigned int."
] |
Please provide a description of the function: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:
... | [
"Reset the bitstring to have given signed int interpretation."
] |
Please provide a description of the function: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 <... | [
"Read bits and interpret as a signed int"
] |
Please provide a description of the function: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, lengt... | [
"Set the bitstring to a big-endian unsigned int interpretation."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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 ... | [
"Read bits and interpret as a little-endian unsigned int."
] |
Please provide a description of the function: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)) & (... | [
"Read bits and interpret as a little-endian signed int."
] |
Please provide a description of the function: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)))
... | [
"Read bits and interpret as a float."
] |
Please provide a description of the function: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)))
... | [
"Read bits and interpret as a little-endian float."
] |
Please provide a description of the function: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 + ... | [
"Initialise bitstring with unsigned exponential-Golomb code for integer i.\n\n Raises CreationError if i < 0.\n\n "
] |
Please provide a description of the function: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
c... | [
"Return interpretation of next bits as unsigned exponential-Golomb code.\n\n Raises ReadError if the end of the bitstring is encountered while\n reading the code.\n\n "
] |
Please provide a description of the function: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 co... | [
"Return data as unsigned exponential-Golomb code.\n\n Raises InterpretError if bitstring is not a single exponential-Golomb code.\n\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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 co... | [
"Return data as signed exponential-Golomb code.\n\n Raises InterpretError if bitstring is not a single exponential-Golomb code.\n\n "
] |
Please provide a description of the function: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.\n\n Advances position to after the read code.\n\n Raises ReadError if the end of the bitstring is encountered while\n reading the code.\n\n "
] |
Please provide a description of the function: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:]) +... | [
"Initialise bitstring with unsigned interleaved exponential-Golomb code for integer i.\n\n Raises CreationError if i < 0.\n\n "
] |
Please provide a description of the function: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 exponen... | [
"Return data as unsigned interleaved exponential-Golomb code.\n\n Raises InterpretError if bitstring is not a single exponential-Golomb code.\n\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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 exponen... | [
"Return data as signed interleaved exponential-Golomb code.\n\n Raises InterpretError if bitstring is not a single exponential-Golomb code.\n\n "
] |
Please provide a description of the function: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
exc... | [
"Return interpretation of next bits as a signed interleaved exponential-Golomb code.\n\n Advances position to after the read code.\n\n Raises ReadError if the end of the bitstring is encountered while\n reading the code.\n\n "
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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... | [
"Same as _setbin_safe, but input isn't sanity checked. binstring mustn't start with '0b'."
] |
Please provide a description of the function: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
... | [
"Read bits and interpret as a binary string."
] |
Please provide a description of the function: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... | [
"Reset the bitstring to have the value given in octstring."
] |
Please provide a description of the function: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 bi... | [
"Read bits and interpret as an octal string."
] |
Please provide a description of the function: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:
... | [
"Reset the bitstring to have the value given in hexstring."
] |
Please provide a description of the function: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._s... | [
"Read bits and interpret as a hex string."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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()
... | [
"Convert bs to a bitstring and return it.\n\n offset gives the suggested bit offset of first significant\n bit, to optimise append etc.\n\n "
] |
Please provide a description of the function:def _copy(self):
s_copy = self.__class__()
s_copy._setbytes_unsafe(self._datastore.getbyteslice(0, self._datastore.bytelength),
self.len, self._offset)
return s_copy | [
"Create and return a new copy of the Bits (always in memory)."
] |
Please provide a description of the function: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._setb... | [
"Used internally to get a slice, without error checking."
] |
Please provide a description of the function: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(lengt... | [
"Reads a token from the bitstring and returns the result."
] |
Please provide a description of the function: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... | [
"Reverse all bits in-place."
] |
Please provide a description of the function: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._... | [
"Truncate bits from the end of the bitstring."
] |
Please provide a description of the function: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... | [
"Insert bs at pos."
] |
Please provide a description of the function: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 = (s... | [
"Overwrite with bs at pos."
] |
Please provide a description of the function: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:
... | [
"Delete bits at pos."
] |
Please provide a description of the function: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._data... | [
"Reverse bytes in-place."
] |
Please provide a description of the function:def _set(self, pos):
assert 0 <= pos < self.len
self._datastore.setbit(pos) | [
"Set bit at pos to 1."
] |
Please provide a description of the function:def _unset(self, pos):
assert 0 <= pos < self.len
self._datastore.unsetbit(pos) | [
"Set bit at pos to 0."
] |
Please provide a description of the function:def _invert(self, pos):
assert 0 <= pos < self.len
self._datastore.invertbit(pos) | [
"Flip bit at pos 1<->0."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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) * ol... | [
"Concatenate n copies of self in place. Return self."
] |
Please provide a description of the function:def _inplace_logical_helper(self, bs, f):
# Give the two bitstrings the same offset (modulo 8)
self_byteoffset, self_bitoffset = divmod(self._offset, 8)
bs_byteoffset, bs_bitoffset = divmod(bs._offset, 8)
if bs_bitoffset != self_bitof... | [
"Helper function containing most of the __ior__, __iand__, __ixor__ code."
] |
Please provide a description of the function: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 ... | [
"Validate start and end and return them as positive bit positions."
] |
Please provide a description of the function: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... | [
"Quicker version of find when everything's whole byte\n and byte aligned.\n\n "
] |
Please provide a description of the function: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, leng... | [
"Find first occurrence of a compiled regular expression.\n\n Note that this doesn't support arbitrary regexes, in particular they\n must match a known length.\n\n "
] |
Please provide a description of the function: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:
... | [
"Find first occurrence of substring bs.\n\n Returns a single item tuple with the bit position if found, or an\n empty tuple if not found. The bit position (pos property) will\n also be set to the start of the substring if it is found.\n\n bs -- The bitstring to find.\n start -- Th... |
Please provide a description of the function:def findall(self, bs, start=None, end=None, count=None, bytealigned=None):
if count is not None and count < 0:
raise ValueError("In findall, count must be >= 0.")
bs = Bits(bs)
start, end = self._validate_slice(start, end)
... | [
"Find all occurrences of bs. Return generator of bit positions.\n\n bs -- The bitstring to find.\n start -- The bit position to start the search. Defaults to 0.\n end -- The bit position one past the last bit to search.\n Defaults to self.len.\n count -- The maximum number ... |
Please provide a description of the function:def rfind(self, bs, start=None, end=None, bytealigned=None):
bs = Bits(bs)
start, end = self._validate_slice(start, end)
if bytealigned is None:
bytealigned = globals()['bytealigned']
if not bs.len:
raise Value... | [
"Find final occurrence of substring bs.\n\n Returns a single item tuple with the bit position if found, or an\n empty tuple if not found. The bit position (pos property) will\n also be set to the start of the substring if it is found.\n\n bs -- The bitstring to find.\n start -- Th... |
Please provide a description of the function:def cut(self, bits, start=None, end=None, count=None):
start, end = self._validate_slice(start, end)
if count is not None and count < 0:
raise ValueError("Cannot cut - count must be >= 0.")
if bits <= 0:
raise ValueErr... | [
"Return bitstring generator by cutting into bits sized chunks.\n\n bits -- The size in bits of the bitstring chunks to generate.\n start -- The bit position to start the first cut. Defaults to 0.\n end -- The bit position one past the last bit to use in the cut.\n Defaults to self... |
Please provide a description of the function:def split(self, delimiter, start=None, end=None, count=None,
bytealigned=None):
delimiter = Bits(delimiter)
if not delimiter.len:
raise ValueError("split delimiter cannot be empty.")
start, end = self._validate_slice... | [
"Return bitstring generator by splittling using a delimiter.\n\n The first item returned is the initial bitstring before the delimiter,\n which may be an empty bitstring.\n\n delimiter -- The bitstring used as the divider.\n start -- The bit position to start the split. Defaults to 0.\n ... |
Please provide a description of the function:def join(self, sequence):
s = self.__class__()
i = iter(sequence)
try:
s._append(Bits(next(i)))
while True:
n = next(i)
s._append(self)
s._append(Bits(n))
except ... | [
"Return concatenation of bitstrings joined by self.\n\n sequence -- A sequence of bitstrings.\n\n "
] |
Please provide a description of the function:def tobytes(self):
d = offsetcopy(self._datastore, 0).rawbytes
# Need to ensure that unused bits at end are set to zero
unusedbits = 8 - self.len % 8
if unusedbits != 8:
d[-1] &= (0xff << unusedbits)
return bytes(d... | [
"Return the bitstring as bytes, padding with zero bits if needed.\n\n Up to seven zero bits will be added at the end to byte align.\n\n "
] |
Please provide a description of the function:def tofile(self, f):
# If the bitstring is file based then we don't want to read it all
# in to memory.
chunksize = 1024 * 1024 # 1 MB chunks
if not self._offset:
a = 0
bytelen = self._datastore.bytelength
... | [
"Write the bitstring to a file object, padding with zero bits if needed.\n\n Up to seven zero bits will be added at the end to byte align.\n\n "
] |
Please provide a description of the function:def startswith(self, prefix, start=None, end=None):
prefix = Bits(prefix)
start, end = self._validate_slice(start, end)
if end < start + prefix.len:
return False
end = start + prefix.len
return self._slice(start, e... | [
"Return whether the current bitstring starts with prefix.\n\n prefix -- The bitstring to search for.\n start -- The bit position to start from. Defaults to 0.\n end -- The bit position to end at. Defaults to self.len.\n\n "
] |
Please provide a description of the function:def endswith(self, suffix, start=None, end=None):
suffix = Bits(suffix)
start, end = self._validate_slice(start, end)
if start + suffix.len > end:
return False
start = end - suffix.len
return self._slice(start, end... | [
"Return whether the current bitstring ends with suffix.\n\n suffix -- The bitstring to search for.\n start -- The bit position to start from. Defaults to 0.\n end -- The bit position to end at. Defaults to self.len.\n\n "
] |
Please provide a description of the function:def all(self, value, pos=None):
value = bool(value)
length = self.len
if pos is None:
pos = xrange(self.len)
for p in pos:
if p < 0:
p += length
if not 0 <= p < length:
... | [
"Return True if one or many bits are all set to value.\n\n value -- If value is True then checks for bits set to 1, otherwise\n checks for bits set to 0.\n pos -- An iterable of bit positions. Negative numbers are treated in\n the same way as slice indices. Defaults to th... |
Please provide a description of the function:def count(self, value):
if not self.len:
return 0
# count the number of 1s (from which it's easy to work out the 0s).
# Don't count the final byte yet.
count = sum(BIT_COUNT[self._datastore.getbyte(i)] for i in xrange(self... | [
"Return count of total number of either zero or one bits.\n\n value -- If True then bits set to 1 are counted, otherwise bits set\n to 0 are counted.\n\n >>> Bits('0xef').count(1)\n 7\n\n "
] |
Please provide a description of the function:def replace(self, old, new, start=None, end=None, count=None,
bytealigned=None):
old = Bits(old)
new = Bits(new)
if not old.len:
raise ValueError("Empty bitstring cannot be replaced.")
start, end = self._va... | [
"Replace all occurrences of old with new in place.\n\n Returns number of replacements made.\n\n old -- The bitstring to replace.\n new -- The replacement bitstring.\n start -- Any occurrences that start before this will not be replaced.\n Defaults to 0.\n end -- An... |
Please provide a description of the function:def insert(self, bs, pos=None):
bs = Bits(bs)
if not bs.len:
return self
if bs is self:
bs = self.__copy__()
if pos is None:
try:
pos = self._pos
except AttributeError:
... | [
"Insert bs at bit position pos.\n\n bs -- The bitstring to insert.\n pos -- The bit position to insert at.\n\n Raises ValueError if pos < 0 or pos > self.len.\n\n "
] |
Please provide a description of the function:def overwrite(self, bs, pos=None):
bs = Bits(bs)
if not bs.len:
return
if pos is None:
try:
pos = self._pos
except AttributeError:
raise TypeError("overwrite require a bit po... | [
"Overwrite with bs at bit position pos.\n\n bs -- The bitstring to overwrite with.\n pos -- The bit position to begin overwriting from.\n\n Raises ValueError if pos < 0 or pos + bs.len > self.len\n\n "
] |
Please provide a description of the function:def append(self, bs):
# The offset is a hint to make bs easily appendable.
bs = self._converttobitstring(bs, offset=(self.len + self._offset) % 8)
self._append(bs) | [
"Append a bitstring to the current bitstring.\n\n bs -- The bitstring to append.\n\n "
] |
Please provide a description of the function:def reverse(self, start=None, end=None):
start, end = self._validate_slice(start, end)
if start == 0 and end == self.len:
self._reverse()
return
s = self._slice(start, end)
s._reverse()
self[start:end] ... | [
"Reverse bits in-place.\n\n start -- Position of first bit to reverse. Defaults to 0.\n end -- One past the position of the last bit to reverse.\n Defaults to self.len.\n\n Using on an empty bitstring will have no effect.\n\n Raises ValueError if start < 0, end > self.len o... |
Please provide a description of the function:def set(self, value, pos=None):
f = self._set if value else self._unset
if pos is None:
pos = xrange(self.len)
try:
length = self.len
for p in pos:
if p < 0:
p += length
... | [
"Set one or many bits to 1 or 0.\n\n value -- If True bits are set to 1, otherwise they are set to 0.\n pos -- Either a single bit position or an iterable of bit positions.\n Negative numbers are treated in the same way as slice indices.\n Defaults to the entire bitstring.\... |
Please provide a description of the function:def invert(self, pos=None):
if pos is None:
self._invert_all()
return
if not isinstance(pos, collections.Iterable):
pos = (pos,)
length = self.len
for p in pos:
if p < 0:
... | [
"Invert one or many bits from 0 to 1 or vice versa.\n\n pos -- Either a single bit position or an iterable of bit positions.\n Negative numbers are treated in the same way as slice indices.\n\n Raises IndexError if pos < -self.len or pos >= self.len.\n\n "
] |
Please provide a description of the function:def ror(self, bits, start=None, end=None):
if not self.len:
raise Error("Cannot rotate an empty bitstring.")
if bits < 0:
raise ValueError("Cannot rotate right by negative amount.")
start, end = self._validate_slice(st... | [
"Rotate bits to the right in-place.\n\n bits -- The number of bits to rotate by.\n start -- Start of slice to rotate. Defaults to 0.\n end -- End of slice to rotate. Defaults to self.len.\n\n Raises ValueError if bits < 0.\n\n "
] |
Please provide a description of the function:def rol(self, bits, start=None, end=None):
if not self.len:
raise Error("Cannot rotate an empty bitstring.")
if bits < 0:
raise ValueError("Cannot rotate left by negative amount.")
start, end = self._validate_slice(sta... | [
"Rotate bits to the left in-place.\n\n bits -- The number of bits to rotate by.\n start -- Start of slice to rotate. Defaults to 0.\n end -- End of slice to rotate. Defaults to self.len.\n\n Raises ValueError if bits < 0.\n\n "
] |
Please provide a description of the function:def byteswap(self, fmt=None, start=None, end=None, repeat=True):
start, end = self._validate_slice(start, end)
if fmt is None or fmt == 0:
# reverse all of the whole bytes.
bytesizes = [(end - start) // 8]
elif isinsta... | [
"Change the endianness in-place. Return number of repeats of fmt done.\n\n fmt -- A compact structure string, an integer number of bytes or\n an iterable of integers. Defaults to 0, which byte reverses the\n whole bitstring.\n start -- Start bit position, defaults to 0.\n ... |
Please provide a description of the function:def _setbitpos(self, pos):
if pos < 0:
raise ValueError("Bit position cannot be negative.")
if pos > self.len:
raise ValueError("Cannot seek past the end of the data.")
self._pos = pos | [
"Move to absolute postion bit in bitstream."
] |
Please provide a description of the function:def read(self, fmt):
if isinstance(fmt, numbers.Integral):
if fmt < 0:
raise ValueError("Cannot read negative amount.")
if fmt > self.len - self._pos:
raise ReadError("Cannot read {0} bits, only {1} ava... | [
"Interpret next bits according to the format string and return result.\n\n fmt -- Token string describing how to interpret the next bits.\n\n Token examples: 'int:12' : 12 bits as a signed integer\n 'uint:8' : 8 bits as an unsigned integer\n 'float:6... |
Please provide a description of the function:def readlist(self, fmt, **kwargs):
value, self._pos = self._readlist(fmt, self._pos, **kwargs)
return value | [
"Interpret next bits according to format string(s) and return list.\n\n fmt -- A single string or list of strings with comma separated tokens\n describing how to interpret the next bits in the bitstring. Items\n can also be integers, for reading new bitstring of the given length.\... |
Please provide a description of the function:def readto(self, bs, bytealigned=None):
if isinstance(bs, numbers.Integral):
raise ValueError("Integers cannot be searched for")
bs = Bits(bs)
oldpos = self._pos
p = self.find(bs, self._pos, bytealigned=bytealigned)
... | [
"Read up to and including next occurrence of bs and return result.\n\n bs -- The bitstring to find. An integer is not permitted.\n bytealigned -- If True the bitstring will only be\n found on byte boundaries.\n\n Raises ValueError if bs is empty.\n Raises ReadError ... |
Please provide a description of the function:def peek(self, fmt):
pos_before = self._pos
value = self.read(fmt)
self._pos = pos_before
return value | [
"Interpret next bits according to format string and return result.\n\n fmt -- Token string describing how to interpret the next bits.\n\n The position in the bitstring is not changed. If not enough bits are\n available then all bits to the end of the bitstring will be used.\n\n Raises Re... |
Please provide a description of the function:def peeklist(self, fmt, **kwargs):
pos = self._pos
return_values = self.readlist(fmt, **kwargs)
self._pos = pos
return return_values | [
"Interpret next bits according to format string(s) and return list.\n\n fmt -- One or more strings with comma separated tokens describing\n how to interpret the next bits in the bitstring.\n kwargs -- A dictionary or keyword-value pairs - the keywords used in the\n forma... |
Please provide a description of the function:def bytealign(self):
skipped = (8 - (self._pos % 8)) % 8
self.pos += self._offset + skipped
assert self._assertsanity()
return skipped | [
"Align to next byte and return number of skipped bits.\n\n Raises ValueError if the end of the bitstring is reached before\n aligning to the next byte.\n\n "
] |
Please provide a description of the function:def prepend(self, bs):
bs = self._converttobitstring(bs)
self._prepend(bs)
self._pos += bs.len | [
"Prepend a bitstring to the current bitstring.\n\n bs -- The bitstring to prepend.\n\n "
] |
Please provide a description of the function:def find_inodes_in_use(fds):
self_pid = os.getpid()
id_fd_assoc = collections.defaultdict(list)
for fd in fds:
st = os.fstat(fd)
id_fd_assoc[(st.st_dev, st.st_ino)].append(fd)
def st_id_candidates(it):
# map proc paths to stat ... | [
"\n Find which of these inodes are in use, and give their open modes.\n\n Does not count the passed fds as an use of the inode they point to,\n but if the current process has the same inodes open with different\n file descriptors these will be listed.\n\n Looks at /proc/*/fd and /proc/*/map_files (Li... |
Please provide a description of the function:def set_idle_priority(pid=None):
if pid is None:
pid = os.getpid()
lib.ioprio_set(
lib.IOPRIO_WHO_PROCESS, pid,
lib.IOPRIO_PRIO_VALUE(lib.IOPRIO_CLASS_IDLE, 0)) | [
"\n Puts a process in the idle io priority class.\n\n If pid is omitted, applies to the current process.\n "
] |
Please provide a description of the function:def futimens(fd, ns):
# ctime can't easily be reset
# also, we have no way to do mandatory locking without
# changing the ctime.
times = ffi.new('struct timespec[2]')
atime, mtime = ns
assert 0 <= atime.tv_nsec < 1e9
assert 0 <= mtime.tv_nse... | [
"\n set inode atime and mtime\n\n ns is (atime, mtime), a pair of struct timespec\n with nanosecond resolution.\n "
] |
Please provide a description of the function:def fopenat(base_fd, path):
return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb') | [
"\n Does openat read-only, then does fdopen to get a file object\n "
] |
Please provide a description of the function:def fopenat_rw(base_fd, path):
return os.fdopen(openat(base_fd, path, os.O_RDWR), 'rb+') | [
"\n Does openat read-write, then does fdopen to get a file object\n "
] |
Please provide a description of the function:def fiemap(fd):
count = 72
fiemap_cbuf = ffi.new(
'char[]',
ffi.sizeof('struct fiemap')
+ count * ffi.sizeof('struct fiemap_extent'))
fiemap_pybuf = ffi.buffer(fiemap_cbuf)
fiemap_ptr = ffi.cast('struct fiemap*', fiemap_cbuf)
... | [
"\n Gets a map of file extents.\n "
] |
Please provide a description of the function:def getflags(fd):
flags_ptr = ffi.new('uint64_t*')
flags_buf = ffi.buffer(flags_ptr)
fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf)
return flags_ptr[0] | [
"\n Gets per-file filesystem flags.\n "
] |
Please provide a description of the function:def editflags(fd, add_flags=0, remove_flags=0):
if add_flags & remove_flags != 0:
raise ValueError(
'Added and removed flags shouldn\'t overlap',
add_flags, remove_flags)
# The ext2progs code uses int or unsigned long,
# the... | [
"\n Sets and unsets per-file filesystem flags.\n "
] |
Please provide a description of the function:def connect(host, username, password, **kwargs):
arguments = ChainMap(kwargs, defaults)
transport = create_transport(host, **arguments)
protocol = ApiProtocol(transport=transport, encoding=arguments['encoding'])
api = arguments['subclass'](protocol=proto... | [
"\n Connect and login to routeros device.\n Upon success return a Api class.\n\n :param host: Hostname to connecto to. May be ipv4,ipv6,FQDN.\n :param username: Username to login with.\n :param password: Password to login with. Only ASCII characters allowed.\n :param timeout: Socket timeout. Defau... |
Please provide a description of the function:def _readSentence(self):
reply_word, words = self.protocol.readSentence()
words = dict(parseWord(word) for word in words)
return reply_word, words | [
"\n Read one sentence and parse words.\n\n :returns: Reply word, dict with attribute words.\n "
] |
Please provide a description of the function:def _readResponse(self):
traps = []
reply_word = None
while reply_word != '!done':
reply_word, words = self._readSentence()
if reply_word == '!trap':
traps.append(TrapError(**words))
elif re... | [
"\n Yield each row of response untill !done is received.\n\n :throws TrapError: If one !trap is received.\n :throws MultiTrapError: If > 1 !trap is received.\n "
] |
Please provide a description of the function:def encodeSentence(self, *words):
encoded = map(self.encodeWord, words)
encoded = b''.join(encoded)
# append EOS (end of sentence) byte
encoded += b'\x00'
return encoded | [
"\n Encode given sentence in API format.\n\n :param words: Words to endoce.\n :returns: Encoded sentence.\n "
] |
Please provide a description of the function:def encodeWord(self, word):
encoded_word = word.encode(encoding=self.encoding, errors='strict')
return Encoder.encodeLength(len(word)) + encoded_word | [
"\n Encode word in API format.\n\n :param word: Word to encode.\n :returns: Encoded word.\n "
] |
Please provide a description of the function:def encodeLength(length):
if length < 128:
ored_length = length
offset = -1
elif length < 16384:
ored_length = length | 0x8000
offset = -2
elif length < 2097152:
ored_length = length... | [
"\n Encode given length in mikrotik format.\n\n :param length: Integer < 268435456.\n :returns: Encoded length.\n "
] |
Please provide a description of the function:def determineLength(length):
integer = ord(length)
if integer < 128:
return 0
elif integer < 192:
return 1
elif integer < 224:
return 2
elif integer < 240:
return 3
else... | [
"\n Given first read byte, determine how many more bytes\n needs to be known in order to get fully encoded length.\n\n :param length: First read byte.\n :return: How many bytes to read.\n "
] |
Please provide a description of the function:def decodeLength(length):
bytes_length = len(length)
if bytes_length < 2:
offset = b'\x00\x00\x00'
XOR = 0
elif bytes_length < 3:
offset = b'\x00\x00'
XOR = 0x8000
elif bytes_length < 4... | [
"\n Decode length based on given bytes.\n\n :param length: Bytes string to decode.\n :return: Decoded length.\n "
] |
Please provide a description of the function:def writeSentence(self, cmd, *words):
encoded = self.encodeSentence(cmd, *words)
self.log('<---', cmd, *words)
self.transport.write(encoded) | [
"\n Write encoded sentence.\n\n :param cmd: Command word.\n :param words: Aditional words.\n "
] |
Please provide a description of the function:def readSentence(self):
sentence = tuple(word for word in iter(self.readWord, b''))
self.log('--->', *sentence)
reply_word, words = sentence[0], sentence[1:]
if reply_word == '!fatal':
self.transport.close()
ra... | [
"\n Read every word untill empty word (NULL byte) is received.\n\n :return: Reply word, tuple with read words.\n "
] |
Please provide a description of the function:def read(self, length):
data = bytearray()
while len(data) != length:
data += self.sock.recv((length - len(data)))
if not data:
raise ConnectionError('Connection unexpectedly closed.')
return data | [
"\n Read as many bytes from socket as specified in length.\n Loop as long as every byte is read unless exception is raised.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.