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,900
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.findall
|
def findall(self, bs, start=None, end=None, count=None, bytealigned=None):
"""Find all occurrences of bs. Return generator of bit positions.
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.
count -- The maximum number of occurrences to find.
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.
Note that all occurrences of bs are found, even if they overlap.
"""
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)
if bytealigned is None:
bytealigned = globals()['bytealigned']
c = 0
if bytealigned and not bs.len % 8 and not self._datastore.offset:
# Use the quick find method
f = self._findbytes
x = bs._getbytes()
else:
f = self._findregex
x = re.compile(bs._getbin())
while True:
p = f(x, start, end, bytealigned)
if not p:
break
if count is not None and c >= count:
return
c += 1
try:
self._pos = p[0]
except AttributeError:
pass
yield p[0]
if bytealigned:
start = p[0] + 8
else:
start = p[0] + 1
if start >= end:
break
return
|
python
|
def findall(self, bs, start=None, end=None, count=None, bytealigned=None):
"""Find all occurrences of bs. Return generator of bit positions.
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.
count -- The maximum number of occurrences to find.
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.
Note that all occurrences of bs are found, even if they overlap.
"""
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)
if bytealigned is None:
bytealigned = globals()['bytealigned']
c = 0
if bytealigned and not bs.len % 8 and not self._datastore.offset:
# Use the quick find method
f = self._findbytes
x = bs._getbytes()
else:
f = self._findregex
x = re.compile(bs._getbin())
while True:
p = f(x, start, end, bytealigned)
if not p:
break
if count is not None and c >= count:
return
c += 1
try:
self._pos = p[0]
except AttributeError:
pass
yield p[0]
if bytealigned:
start = p[0] + 8
else:
start = p[0] + 1
if start >= end:
break
return
|
[
"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",
")",
"if",
"bytealigned",
"is",
"None",
":",
"bytealigned",
"=",
"globals",
"(",
")",
"[",
"'bytealigned'",
"]",
"c",
"=",
"0",
"if",
"bytealigned",
"and",
"not",
"bs",
".",
"len",
"%",
"8",
"and",
"not",
"self",
".",
"_datastore",
".",
"offset",
":",
"# Use the quick find method",
"f",
"=",
"self",
".",
"_findbytes",
"x",
"=",
"bs",
".",
"_getbytes",
"(",
")",
"else",
":",
"f",
"=",
"self",
".",
"_findregex",
"x",
"=",
"re",
".",
"compile",
"(",
"bs",
".",
"_getbin",
"(",
")",
")",
"while",
"True",
":",
"p",
"=",
"f",
"(",
"x",
",",
"start",
",",
"end",
",",
"bytealigned",
")",
"if",
"not",
"p",
":",
"break",
"if",
"count",
"is",
"not",
"None",
"and",
"c",
">=",
"count",
":",
"return",
"c",
"+=",
"1",
"try",
":",
"self",
".",
"_pos",
"=",
"p",
"[",
"0",
"]",
"except",
"AttributeError",
":",
"pass",
"yield",
"p",
"[",
"0",
"]",
"if",
"bytealigned",
":",
"start",
"=",
"p",
"[",
"0",
"]",
"+",
"8",
"else",
":",
"start",
"=",
"p",
"[",
"0",
"]",
"+",
"1",
"if",
"start",
">=",
"end",
":",
"break",
"return"
] |
Find all occurrences of bs. Return generator of bit positions.
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.
count -- The maximum number of occurrences to find.
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.
Note that all occurrences of bs are found, even if they overlap.
|
[
"Find",
"all",
"occurrences",
"of",
"bs",
".",
"Return",
"generator",
"of",
"bit",
"positions",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2449-L2499
|
17,901
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.rfind
|
def rfind(self, bs, start=None, end=None, bytealigned=None):
"""Find final 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 end the reverse search. Defaults to 0.
end -- The bit position one past the first bit to reverse 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.
"""
bs = Bits(bs)
start, end = self._validate_slice(start, end)
if bytealigned is None:
bytealigned = globals()['bytealigned']
if not bs.len:
raise ValueError("Cannot find an empty bitstring.")
# Search chunks starting near the end and then moving back
# until we find bs.
increment = max(8192, bs.len * 80)
buffersize = min(increment + bs.len, end - start)
pos = max(start, end - buffersize)
while True:
found = list(self.findall(bs, start=pos, end=pos + buffersize,
bytealigned=bytealigned))
if not found:
if pos == start:
return ()
pos = max(start, pos - increment)
continue
return (found[-1],)
|
python
|
def rfind(self, bs, start=None, end=None, bytealigned=None):
"""Find final 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 end the reverse search. Defaults to 0.
end -- The bit position one past the first bit to reverse 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.
"""
bs = Bits(bs)
start, end = self._validate_slice(start, end)
if bytealigned is None:
bytealigned = globals()['bytealigned']
if not bs.len:
raise ValueError("Cannot find an empty bitstring.")
# Search chunks starting near the end and then moving back
# until we find bs.
increment = max(8192, bs.len * 80)
buffersize = min(increment + bs.len, end - start)
pos = max(start, end - buffersize)
while True:
found = list(self.findall(bs, start=pos, end=pos + buffersize,
bytealigned=bytealigned))
if not found:
if pos == start:
return ()
pos = max(start, pos - increment)
continue
return (found[-1],)
|
[
"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",
"ValueError",
"(",
"\"Cannot find an empty bitstring.\"",
")",
"# Search chunks starting near the end and then moving back",
"# until we find bs.",
"increment",
"=",
"max",
"(",
"8192",
",",
"bs",
".",
"len",
"*",
"80",
")",
"buffersize",
"=",
"min",
"(",
"increment",
"+",
"bs",
".",
"len",
",",
"end",
"-",
"start",
")",
"pos",
"=",
"max",
"(",
"start",
",",
"end",
"-",
"buffersize",
")",
"while",
"True",
":",
"found",
"=",
"list",
"(",
"self",
".",
"findall",
"(",
"bs",
",",
"start",
"=",
"pos",
",",
"end",
"=",
"pos",
"+",
"buffersize",
",",
"bytealigned",
"=",
"bytealigned",
")",
")",
"if",
"not",
"found",
":",
"if",
"pos",
"==",
"start",
":",
"return",
"(",
")",
"pos",
"=",
"max",
"(",
"start",
",",
"pos",
"-",
"increment",
")",
"continue",
"return",
"(",
"found",
"[",
"-",
"1",
"]",
",",
")"
] |
Find final 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 end the reverse search. Defaults to 0.
end -- The bit position one past the first bit to reverse 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.
|
[
"Find",
"final",
"occurrence",
"of",
"substring",
"bs",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2501-L2538
|
17,902
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.cut
|
def cut(self, bits, start=None, end=None, count=None):
"""Return bitstring generator by cutting into bits sized chunks.
bits -- The size in bits of the bitstring chunks to generate.
start -- The bit position to start the first cut. Defaults to 0.
end -- The bit position one past the last bit to use in the cut.
Defaults to self.len.
count -- If specified then at most count items are generated.
Default is to cut as many times as possible.
"""
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 ValueError("Cannot cut - bits must be >= 0.")
c = 0
while count is None or c < count:
c += 1
nextchunk = self._slice(start, min(start + bits, end))
if nextchunk.len != bits:
return
assert nextchunk._assertsanity()
yield nextchunk
start += bits
return
|
python
|
def cut(self, bits, start=None, end=None, count=None):
"""Return bitstring generator by cutting into bits sized chunks.
bits -- The size in bits of the bitstring chunks to generate.
start -- The bit position to start the first cut. Defaults to 0.
end -- The bit position one past the last bit to use in the cut.
Defaults to self.len.
count -- If specified then at most count items are generated.
Default is to cut as many times as possible.
"""
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 ValueError("Cannot cut - bits must be >= 0.")
c = 0
while count is None or c < count:
c += 1
nextchunk = self._slice(start, min(start + bits, end))
if nextchunk.len != bits:
return
assert nextchunk._assertsanity()
yield nextchunk
start += bits
return
|
[
"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",
"ValueError",
"(",
"\"Cannot cut - bits must be >= 0.\"",
")",
"c",
"=",
"0",
"while",
"count",
"is",
"None",
"or",
"c",
"<",
"count",
":",
"c",
"+=",
"1",
"nextchunk",
"=",
"self",
".",
"_slice",
"(",
"start",
",",
"min",
"(",
"start",
"+",
"bits",
",",
"end",
")",
")",
"if",
"nextchunk",
".",
"len",
"!=",
"bits",
":",
"return",
"assert",
"nextchunk",
".",
"_assertsanity",
"(",
")",
"yield",
"nextchunk",
"start",
"+=",
"bits",
"return"
] |
Return bitstring generator by cutting into bits sized chunks.
bits -- The size in bits of the bitstring chunks to generate.
start -- The bit position to start the first cut. Defaults to 0.
end -- The bit position one past the last bit to use in the cut.
Defaults to self.len.
count -- If specified then at most count items are generated.
Default is to cut as many times as possible.
|
[
"Return",
"bitstring",
"generator",
"by",
"cutting",
"into",
"bits",
"sized",
"chunks",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2540-L2565
|
17,903
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.split
|
def split(self, delimiter, start=None, end=None, count=None,
bytealigned=None):
"""Return bitstring generator by splittling using a delimiter.
The first item returned is the initial bitstring before the delimiter,
which may be an empty bitstring.
delimiter -- The bitstring used as the divider.
start -- The bit position to start the split. Defaults to 0.
end -- The bit position one past the last bit to use in the split.
Defaults to self.len.
count -- If specified then at most count items are generated.
Default is to split as many times as possible.
bytealigned -- If True splits will only occur on byte boundaries.
Raises ValueError if the delimiter is empty.
"""
delimiter = Bits(delimiter)
if not delimiter.len:
raise ValueError("split delimiter cannot be empty.")
start, end = self._validate_slice(start, end)
if bytealigned is None:
bytealigned = globals()['bytealigned']
if count is not None and count < 0:
raise ValueError("Cannot split - count must be >= 0.")
if count == 0:
return
if bytealigned and not delimiter.len % 8 and not self._datastore.offset:
# Use the quick find method
f = self._findbytes
x = delimiter._getbytes()
else:
f = self._findregex
x = re.compile(delimiter._getbin())
found = f(x, start, end, bytealigned)
if not found:
# Initial bits are the whole bitstring being searched
yield self._slice(start, end)
return
# yield the bytes before the first occurrence of the delimiter, even if empty
yield self._slice(start, found[0])
startpos = pos = found[0]
c = 1
while count is None or c < count:
pos += delimiter.len
found = f(x, pos, end, bytealigned)
if not found:
# No more occurrences, so return the rest of the bitstring
yield self._slice(startpos, end)
return
c += 1
yield self._slice(startpos, found[0])
startpos = pos = found[0]
# Have generated count bitstrings, so time to quit.
return
|
python
|
def split(self, delimiter, start=None, end=None, count=None,
bytealigned=None):
"""Return bitstring generator by splittling using a delimiter.
The first item returned is the initial bitstring before the delimiter,
which may be an empty bitstring.
delimiter -- The bitstring used as the divider.
start -- The bit position to start the split. Defaults to 0.
end -- The bit position one past the last bit to use in the split.
Defaults to self.len.
count -- If specified then at most count items are generated.
Default is to split as many times as possible.
bytealigned -- If True splits will only occur on byte boundaries.
Raises ValueError if the delimiter is empty.
"""
delimiter = Bits(delimiter)
if not delimiter.len:
raise ValueError("split delimiter cannot be empty.")
start, end = self._validate_slice(start, end)
if bytealigned is None:
bytealigned = globals()['bytealigned']
if count is not None and count < 0:
raise ValueError("Cannot split - count must be >= 0.")
if count == 0:
return
if bytealigned and not delimiter.len % 8 and not self._datastore.offset:
# Use the quick find method
f = self._findbytes
x = delimiter._getbytes()
else:
f = self._findregex
x = re.compile(delimiter._getbin())
found = f(x, start, end, bytealigned)
if not found:
# Initial bits are the whole bitstring being searched
yield self._slice(start, end)
return
# yield the bytes before the first occurrence of the delimiter, even if empty
yield self._slice(start, found[0])
startpos = pos = found[0]
c = 1
while count is None or c < count:
pos += delimiter.len
found = f(x, pos, end, bytealigned)
if not found:
# No more occurrences, so return the rest of the bitstring
yield self._slice(startpos, end)
return
c += 1
yield self._slice(startpos, found[0])
startpos = pos = found[0]
# Have generated count bitstrings, so time to quit.
return
|
[
"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",
"(",
"start",
",",
"end",
")",
"if",
"bytealigned",
"is",
"None",
":",
"bytealigned",
"=",
"globals",
"(",
")",
"[",
"'bytealigned'",
"]",
"if",
"count",
"is",
"not",
"None",
"and",
"count",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Cannot split - count must be >= 0.\"",
")",
"if",
"count",
"==",
"0",
":",
"return",
"if",
"bytealigned",
"and",
"not",
"delimiter",
".",
"len",
"%",
"8",
"and",
"not",
"self",
".",
"_datastore",
".",
"offset",
":",
"# Use the quick find method",
"f",
"=",
"self",
".",
"_findbytes",
"x",
"=",
"delimiter",
".",
"_getbytes",
"(",
")",
"else",
":",
"f",
"=",
"self",
".",
"_findregex",
"x",
"=",
"re",
".",
"compile",
"(",
"delimiter",
".",
"_getbin",
"(",
")",
")",
"found",
"=",
"f",
"(",
"x",
",",
"start",
",",
"end",
",",
"bytealigned",
")",
"if",
"not",
"found",
":",
"# Initial bits are the whole bitstring being searched",
"yield",
"self",
".",
"_slice",
"(",
"start",
",",
"end",
")",
"return",
"# yield the bytes before the first occurrence of the delimiter, even if empty",
"yield",
"self",
".",
"_slice",
"(",
"start",
",",
"found",
"[",
"0",
"]",
")",
"startpos",
"=",
"pos",
"=",
"found",
"[",
"0",
"]",
"c",
"=",
"1",
"while",
"count",
"is",
"None",
"or",
"c",
"<",
"count",
":",
"pos",
"+=",
"delimiter",
".",
"len",
"found",
"=",
"f",
"(",
"x",
",",
"pos",
",",
"end",
",",
"bytealigned",
")",
"if",
"not",
"found",
":",
"# No more occurrences, so return the rest of the bitstring",
"yield",
"self",
".",
"_slice",
"(",
"startpos",
",",
"end",
")",
"return",
"c",
"+=",
"1",
"yield",
"self",
".",
"_slice",
"(",
"startpos",
",",
"found",
"[",
"0",
"]",
")",
"startpos",
"=",
"pos",
"=",
"found",
"[",
"0",
"]",
"# Have generated count bitstrings, so time to quit.",
"return"
] |
Return bitstring generator by splittling using a delimiter.
The first item returned is the initial bitstring before the delimiter,
which may be an empty bitstring.
delimiter -- The bitstring used as the divider.
start -- The bit position to start the split. Defaults to 0.
end -- The bit position one past the last bit to use in the split.
Defaults to self.len.
count -- If specified then at most count items are generated.
Default is to split as many times as possible.
bytealigned -- If True splits will only occur on byte boundaries.
Raises ValueError if the delimiter is empty.
|
[
"Return",
"bitstring",
"generator",
"by",
"splittling",
"using",
"a",
"delimiter",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2567-L2622
|
17,904
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.join
|
def join(self, sequence):
"""Return concatenation of bitstrings joined by self.
sequence -- A sequence of bitstrings.
"""
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 StopIteration:
pass
return s
|
python
|
def join(self, sequence):
"""Return concatenation of bitstrings joined by self.
sequence -- A sequence of bitstrings.
"""
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 StopIteration:
pass
return s
|
[
"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",
"StopIteration",
":",
"pass",
"return",
"s"
] |
Return concatenation of bitstrings joined by self.
sequence -- A sequence of bitstrings.
|
[
"Return",
"concatenation",
"of",
"bitstrings",
"joined",
"by",
"self",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2624-L2640
|
17,905
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.tobytes
|
def tobytes(self):
"""Return the bitstring as bytes, padding with zero bits if needed.
Up to seven zero bits will be added at the end to byte align.
"""
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)
|
python
|
def tobytes(self):
"""Return the bitstring as bytes, padding with zero bits if needed.
Up to seven zero bits will be added at the end to byte align.
"""
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)
|
[
"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.
Up to seven zero bits will be added at the end to byte align.
|
[
"Return",
"the",
"bitstring",
"as",
"bytes",
"padding",
"with",
"zero",
"bits",
"if",
"needed",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2642-L2653
|
17,906
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.tofile
|
def tofile(self, f):
"""Write the bitstring to a file object, padding with zero bits if needed.
Up to seven zero bits will be added at the end to byte align.
"""
# 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
p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
while len(p) == chunksize:
f.write(p)
a += chunksize
p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
f.write(p)
# Now the final byte, ensuring that unused bits at end are set to 0.
bits_in_final_byte = self.len % 8
if not bits_in_final_byte:
bits_in_final_byte = 8
f.write(self[-bits_in_final_byte:].tobytes())
else:
# Really quite inefficient...
a = 0
b = a + chunksize * 8
while b <= self.len:
f.write(self._slice(a, b)._getbytes())
a += chunksize * 8
b += chunksize * 8
if a != self.len:
f.write(self._slice(a, self.len).tobytes())
|
python
|
def tofile(self, f):
"""Write the bitstring to a file object, padding with zero bits if needed.
Up to seven zero bits will be added at the end to byte align.
"""
# 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
p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
while len(p) == chunksize:
f.write(p)
a += chunksize
p = self._datastore.getbyteslice(a, min(a + chunksize, bytelen - 1))
f.write(p)
# Now the final byte, ensuring that unused bits at end are set to 0.
bits_in_final_byte = self.len % 8
if not bits_in_final_byte:
bits_in_final_byte = 8
f.write(self[-bits_in_final_byte:].tobytes())
else:
# Really quite inefficient...
a = 0
b = a + chunksize * 8
while b <= self.len:
f.write(self._slice(a, b)._getbytes())
a += chunksize * 8
b += chunksize * 8
if a != self.len:
f.write(self._slice(a, self.len).tobytes())
|
[
"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",
"p",
"=",
"self",
".",
"_datastore",
".",
"getbyteslice",
"(",
"a",
",",
"min",
"(",
"a",
"+",
"chunksize",
",",
"bytelen",
"-",
"1",
")",
")",
"while",
"len",
"(",
"p",
")",
"==",
"chunksize",
":",
"f",
".",
"write",
"(",
"p",
")",
"a",
"+=",
"chunksize",
"p",
"=",
"self",
".",
"_datastore",
".",
"getbyteslice",
"(",
"a",
",",
"min",
"(",
"a",
"+",
"chunksize",
",",
"bytelen",
"-",
"1",
")",
")",
"f",
".",
"write",
"(",
"p",
")",
"# Now the final byte, ensuring that unused bits at end are set to 0.",
"bits_in_final_byte",
"=",
"self",
".",
"len",
"%",
"8",
"if",
"not",
"bits_in_final_byte",
":",
"bits_in_final_byte",
"=",
"8",
"f",
".",
"write",
"(",
"self",
"[",
"-",
"bits_in_final_byte",
":",
"]",
".",
"tobytes",
"(",
")",
")",
"else",
":",
"# Really quite inefficient...",
"a",
"=",
"0",
"b",
"=",
"a",
"+",
"chunksize",
"*",
"8",
"while",
"b",
"<=",
"self",
".",
"len",
":",
"f",
".",
"write",
"(",
"self",
".",
"_slice",
"(",
"a",
",",
"b",
")",
".",
"_getbytes",
"(",
")",
")",
"a",
"+=",
"chunksize",
"*",
"8",
"b",
"+=",
"chunksize",
"*",
"8",
"if",
"a",
"!=",
"self",
".",
"len",
":",
"f",
".",
"write",
"(",
"self",
".",
"_slice",
"(",
"a",
",",
"self",
".",
"len",
")",
".",
"tobytes",
"(",
")",
")"
] |
Write the bitstring to a file object, padding with zero bits if needed.
Up to seven zero bits will be added at the end to byte align.
|
[
"Write",
"the",
"bitstring",
"to",
"a",
"file",
"object",
"padding",
"with",
"zero",
"bits",
"if",
"needed",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2655-L2687
|
17,907
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.startswith
|
def startswith(self, prefix, start=None, end=None):
"""Return whether the current bitstring starts with prefix.
prefix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
"""
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, end) == prefix
|
python
|
def startswith(self, prefix, start=None, end=None):
"""Return whether the current bitstring starts with prefix.
prefix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
"""
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, end) == prefix
|
[
"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",
",",
"end",
")",
"==",
"prefix"
] |
Return whether the current bitstring starts with prefix.
prefix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
|
[
"Return",
"whether",
"the",
"current",
"bitstring",
"starts",
"with",
"prefix",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2689-L2702
|
17,908
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.endswith
|
def endswith(self, suffix, start=None, end=None):
"""Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
"""
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) == suffix
|
python
|
def endswith(self, suffix, start=None, end=None):
"""Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
"""
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) == suffix
|
[
"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",
")",
"==",
"suffix"
] |
Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
|
[
"Return",
"whether",
"the",
"current",
"bitstring",
"ends",
"with",
"suffix",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2704-L2717
|
17,909
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.all
|
def all(self, value, pos=None):
"""Return True if one or many bits are all set to value.
value -- If value is True then checks for bits set to 1, otherwise
checks for bits set to 0.
pos -- An iterable of bit positions. Negative numbers are treated in
the same way as slice indices. Defaults to the whole bitstring.
"""
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:
raise IndexError("Bit position {0} out of range.".format(p))
if not self._datastore.getbit(p) is value:
return False
return True
|
python
|
def all(self, value, pos=None):
"""Return True if one or many bits are all set to value.
value -- If value is True then checks for bits set to 1, otherwise
checks for bits set to 0.
pos -- An iterable of bit positions. Negative numbers are treated in
the same way as slice indices. Defaults to the whole bitstring.
"""
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:
raise IndexError("Bit position {0} out of range.".format(p))
if not self._datastore.getbit(p) is value:
return False
return True
|
[
"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",
":",
"raise",
"IndexError",
"(",
"\"Bit position {0} out of range.\"",
".",
"format",
"(",
"p",
")",
")",
"if",
"not",
"self",
".",
"_datastore",
".",
"getbit",
"(",
"p",
")",
"is",
"value",
":",
"return",
"False",
"return",
"True"
] |
Return True if one or many bits are all set to value.
value -- If value is True then checks for bits set to 1, otherwise
checks for bits set to 0.
pos -- An iterable of bit positions. Negative numbers are treated in
the same way as slice indices. Defaults to the whole bitstring.
|
[
"Return",
"True",
"if",
"one",
"or",
"many",
"bits",
"are",
"all",
"set",
"to",
"value",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2719-L2739
|
17,910
|
scott-griffiths/bitstring
|
bitstring.py
|
Bits.count
|
def count(self, value):
"""Return count of total number of either zero or one bits.
value -- If True then bits set to 1 are counted, otherwise bits set
to 0 are counted.
>>> Bits('0xef').count(1)
7
"""
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._datastore.bytelength - 1))
# adjust for bits at start that aren't part of the bitstring
if self._offset:
count -= BIT_COUNT[self._datastore.getbyte(0) >> (8 - self._offset)]
# and count the last 1 - 8 bits at the end.
endbits = self._datastore.bytelength * 8 - (self._offset + self.len)
count += BIT_COUNT[self._datastore.getbyte(self._datastore.bytelength - 1) >> endbits]
return count if value else self.len - count
|
python
|
def count(self, value):
"""Return count of total number of either zero or one bits.
value -- If True then bits set to 1 are counted, otherwise bits set
to 0 are counted.
>>> Bits('0xef').count(1)
7
"""
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._datastore.bytelength - 1))
# adjust for bits at start that aren't part of the bitstring
if self._offset:
count -= BIT_COUNT[self._datastore.getbyte(0) >> (8 - self._offset)]
# and count the last 1 - 8 bits at the end.
endbits = self._datastore.bytelength * 8 - (self._offset + self.len)
count += BIT_COUNT[self._datastore.getbyte(self._datastore.bytelength - 1) >> endbits]
return count if value else self.len - count
|
[
"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",
".",
"_datastore",
".",
"bytelength",
"-",
"1",
")",
")",
"# adjust for bits at start that aren't part of the bitstring",
"if",
"self",
".",
"_offset",
":",
"count",
"-=",
"BIT_COUNT",
"[",
"self",
".",
"_datastore",
".",
"getbyte",
"(",
"0",
")",
">>",
"(",
"8",
"-",
"self",
".",
"_offset",
")",
"]",
"# and count the last 1 - 8 bits at the end.",
"endbits",
"=",
"self",
".",
"_datastore",
".",
"bytelength",
"*",
"8",
"-",
"(",
"self",
".",
"_offset",
"+",
"self",
".",
"len",
")",
"count",
"+=",
"BIT_COUNT",
"[",
"self",
".",
"_datastore",
".",
"getbyte",
"(",
"self",
".",
"_datastore",
".",
"bytelength",
"-",
"1",
")",
">>",
"endbits",
"]",
"return",
"count",
"if",
"value",
"else",
"self",
".",
"len",
"-",
"count"
] |
Return count of total number of either zero or one bits.
value -- If True then bits set to 1 are counted, otherwise bits set
to 0 are counted.
>>> Bits('0xef').count(1)
7
|
[
"Return",
"count",
"of",
"total",
"number",
"of",
"either",
"zero",
"or",
"one",
"bits",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L2763-L2784
|
17,911
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.replace
|
def replace(self, old, new, start=None, end=None, count=None,
bytealigned=None):
"""Replace all occurrences of old with new in place.
Returns number of replacements made.
old -- The bitstring to replace.
new -- The replacement bitstring.
start -- Any occurrences that start before this will not be replaced.
Defaults to 0.
end -- Any occurrences that finish after this will not be replaced.
Defaults to self.len.
count -- The maximum number of replacements to make. Defaults to
replace all occurrences.
bytealigned -- If True replacements will only be made on byte
boundaries.
Raises ValueError if old is empty or if start or end are
out of range.
"""
old = Bits(old)
new = Bits(new)
if not old.len:
raise ValueError("Empty bitstring cannot be replaced.")
start, end = self._validate_slice(start, end)
if bytealigned is None:
bytealigned = globals()['bytealigned']
# Adjust count for use in split()
if count is not None:
count += 1
sections = self.split(old, start, end, count, bytealigned)
lengths = [s.len for s in sections]
if len(lengths) == 1:
# Didn't find anything to replace.
return 0 # no replacements done
if new is self:
# Prevent self assignment woes
new = copy.copy(self)
positions = [lengths[0] + start]
for l in lengths[1:-1]:
# Next position is the previous one plus the length of the next section.
positions.append(positions[-1] + l)
# We have all the positions that need replacements. We do them
# in reverse order so that they won't move around as we replace.
positions.reverse()
try:
# Need to calculate new pos, if this is a bitstream
newpos = self._pos
for p in positions:
self[p:p + old.len] = new
if old.len != new.len:
diff = new.len - old.len
for p in positions:
if p >= newpos:
continue
if p + old.len <= newpos:
newpos += diff
else:
newpos = p
self._pos = newpos
except AttributeError:
for p in positions:
self[p:p + old.len] = new
assert self._assertsanity()
return len(lengths) - 1
|
python
|
def replace(self, old, new, start=None, end=None, count=None,
bytealigned=None):
"""Replace all occurrences of old with new in place.
Returns number of replacements made.
old -- The bitstring to replace.
new -- The replacement bitstring.
start -- Any occurrences that start before this will not be replaced.
Defaults to 0.
end -- Any occurrences that finish after this will not be replaced.
Defaults to self.len.
count -- The maximum number of replacements to make. Defaults to
replace all occurrences.
bytealigned -- If True replacements will only be made on byte
boundaries.
Raises ValueError if old is empty or if start or end are
out of range.
"""
old = Bits(old)
new = Bits(new)
if not old.len:
raise ValueError("Empty bitstring cannot be replaced.")
start, end = self._validate_slice(start, end)
if bytealigned is None:
bytealigned = globals()['bytealigned']
# Adjust count for use in split()
if count is not None:
count += 1
sections = self.split(old, start, end, count, bytealigned)
lengths = [s.len for s in sections]
if len(lengths) == 1:
# Didn't find anything to replace.
return 0 # no replacements done
if new is self:
# Prevent self assignment woes
new = copy.copy(self)
positions = [lengths[0] + start]
for l in lengths[1:-1]:
# Next position is the previous one plus the length of the next section.
positions.append(positions[-1] + l)
# We have all the positions that need replacements. We do them
# in reverse order so that they won't move around as we replace.
positions.reverse()
try:
# Need to calculate new pos, if this is a bitstream
newpos = self._pos
for p in positions:
self[p:p + old.len] = new
if old.len != new.len:
diff = new.len - old.len
for p in positions:
if p >= newpos:
continue
if p + old.len <= newpos:
newpos += diff
else:
newpos = p
self._pos = newpos
except AttributeError:
for p in positions:
self[p:p + old.len] = new
assert self._assertsanity()
return len(lengths) - 1
|
[
"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",
".",
"_validate_slice",
"(",
"start",
",",
"end",
")",
"if",
"bytealigned",
"is",
"None",
":",
"bytealigned",
"=",
"globals",
"(",
")",
"[",
"'bytealigned'",
"]",
"# Adjust count for use in split()",
"if",
"count",
"is",
"not",
"None",
":",
"count",
"+=",
"1",
"sections",
"=",
"self",
".",
"split",
"(",
"old",
",",
"start",
",",
"end",
",",
"count",
",",
"bytealigned",
")",
"lengths",
"=",
"[",
"s",
".",
"len",
"for",
"s",
"in",
"sections",
"]",
"if",
"len",
"(",
"lengths",
")",
"==",
"1",
":",
"# Didn't find anything to replace.",
"return",
"0",
"# no replacements done",
"if",
"new",
"is",
"self",
":",
"# Prevent self assignment woes",
"new",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"positions",
"=",
"[",
"lengths",
"[",
"0",
"]",
"+",
"start",
"]",
"for",
"l",
"in",
"lengths",
"[",
"1",
":",
"-",
"1",
"]",
":",
"# Next position is the previous one plus the length of the next section.",
"positions",
".",
"append",
"(",
"positions",
"[",
"-",
"1",
"]",
"+",
"l",
")",
"# We have all the positions that need replacements. We do them",
"# in reverse order so that they won't move around as we replace.",
"positions",
".",
"reverse",
"(",
")",
"try",
":",
"# Need to calculate new pos, if this is a bitstream",
"newpos",
"=",
"self",
".",
"_pos",
"for",
"p",
"in",
"positions",
":",
"self",
"[",
"p",
":",
"p",
"+",
"old",
".",
"len",
"]",
"=",
"new",
"if",
"old",
".",
"len",
"!=",
"new",
".",
"len",
":",
"diff",
"=",
"new",
".",
"len",
"-",
"old",
".",
"len",
"for",
"p",
"in",
"positions",
":",
"if",
"p",
">=",
"newpos",
":",
"continue",
"if",
"p",
"+",
"old",
".",
"len",
"<=",
"newpos",
":",
"newpos",
"+=",
"diff",
"else",
":",
"newpos",
"=",
"p",
"self",
".",
"_pos",
"=",
"newpos",
"except",
"AttributeError",
":",
"for",
"p",
"in",
"positions",
":",
"self",
"[",
"p",
":",
"p",
"+",
"old",
".",
"len",
"]",
"=",
"new",
"assert",
"self",
".",
"_assertsanity",
"(",
")",
"return",
"len",
"(",
"lengths",
")",
"-",
"1"
] |
Replace all occurrences of old with new in place.
Returns number of replacements made.
old -- The bitstring to replace.
new -- The replacement bitstring.
start -- Any occurrences that start before this will not be replaced.
Defaults to 0.
end -- Any occurrences that finish after this will not be replaced.
Defaults to self.len.
count -- The maximum number of replacements to make. Defaults to
replace all occurrences.
bytealigned -- If True replacements will only be made on byte
boundaries.
Raises ValueError if old is empty or if start or end are
out of range.
|
[
"Replace",
"all",
"occurrences",
"of",
"old",
"with",
"new",
"in",
"place",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3298-L3363
|
17,912
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.insert
|
def insert(self, bs, pos=None):
"""Insert bs at bit position pos.
bs -- The bitstring to insert.
pos -- The bit position to insert at.
Raises ValueError if pos < 0 or pos > self.len.
"""
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:
raise TypeError("insert require a bit position for this type.")
if pos < 0:
pos += self.len
if not 0 <= pos <= self.len:
raise ValueError("Invalid insert position.")
self._insert(bs, pos)
|
python
|
def insert(self, bs, pos=None):
"""Insert bs at bit position pos.
bs -- The bitstring to insert.
pos -- The bit position to insert at.
Raises ValueError if pos < 0 or pos > self.len.
"""
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:
raise TypeError("insert require a bit position for this type.")
if pos < 0:
pos += self.len
if not 0 <= pos <= self.len:
raise ValueError("Invalid insert position.")
self._insert(bs, pos)
|
[
"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",
":",
"raise",
"TypeError",
"(",
"\"insert require a bit position for this type.\"",
")",
"if",
"pos",
"<",
"0",
":",
"pos",
"+=",
"self",
".",
"len",
"if",
"not",
"0",
"<=",
"pos",
"<=",
"self",
".",
"len",
":",
"raise",
"ValueError",
"(",
"\"Invalid insert position.\"",
")",
"self",
".",
"_insert",
"(",
"bs",
",",
"pos",
")"
] |
Insert bs at bit position pos.
bs -- The bitstring to insert.
pos -- The bit position to insert at.
Raises ValueError if pos < 0 or pos > self.len.
|
[
"Insert",
"bs",
"at",
"bit",
"position",
"pos",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3365-L3388
|
17,913
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.overwrite
|
def overwrite(self, bs, pos=None):
"""Overwrite with bs at bit position pos.
bs -- The bitstring to overwrite with.
pos -- The bit position to begin overwriting from.
Raises ValueError if pos < 0 or pos + bs.len > self.len
"""
bs = Bits(bs)
if not bs.len:
return
if pos is None:
try:
pos = self._pos
except AttributeError:
raise TypeError("overwrite require a bit position for this type.")
if pos < 0:
pos += self.len
if pos < 0 or pos + bs.len > self.len:
raise ValueError("Overwrite exceeds boundary of bitstring.")
self._overwrite(bs, pos)
try:
self._pos = pos + bs.len
except AttributeError:
pass
|
python
|
def overwrite(self, bs, pos=None):
"""Overwrite with bs at bit position pos.
bs -- The bitstring to overwrite with.
pos -- The bit position to begin overwriting from.
Raises ValueError if pos < 0 or pos + bs.len > self.len
"""
bs = Bits(bs)
if not bs.len:
return
if pos is None:
try:
pos = self._pos
except AttributeError:
raise TypeError("overwrite require a bit position for this type.")
if pos < 0:
pos += self.len
if pos < 0 or pos + bs.len > self.len:
raise ValueError("Overwrite exceeds boundary of bitstring.")
self._overwrite(bs, pos)
try:
self._pos = pos + bs.len
except AttributeError:
pass
|
[
"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 position for this type.\"",
")",
"if",
"pos",
"<",
"0",
":",
"pos",
"+=",
"self",
".",
"len",
"if",
"pos",
"<",
"0",
"or",
"pos",
"+",
"bs",
".",
"len",
">",
"self",
".",
"len",
":",
"raise",
"ValueError",
"(",
"\"Overwrite exceeds boundary of bitstring.\"",
")",
"self",
".",
"_overwrite",
"(",
"bs",
",",
"pos",
")",
"try",
":",
"self",
".",
"_pos",
"=",
"pos",
"+",
"bs",
".",
"len",
"except",
"AttributeError",
":",
"pass"
] |
Overwrite with bs at bit position pos.
bs -- The bitstring to overwrite with.
pos -- The bit position to begin overwriting from.
Raises ValueError if pos < 0 or pos + bs.len > self.len
|
[
"Overwrite",
"with",
"bs",
"at",
"bit",
"position",
"pos",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3390-L3415
|
17,914
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.append
|
def append(self, bs):
"""Append a bitstring to the current bitstring.
bs -- The bitstring to append.
"""
# The offset is a hint to make bs easily appendable.
bs = self._converttobitstring(bs, offset=(self.len + self._offset) % 8)
self._append(bs)
|
python
|
def append(self, bs):
"""Append a bitstring to the current bitstring.
bs -- The bitstring to append.
"""
# The offset is a hint to make bs easily appendable.
bs = self._converttobitstring(bs, offset=(self.len + self._offset) % 8)
self._append(bs)
|
[
"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.
bs -- The bitstring to append.
|
[
"Append",
"a",
"bitstring",
"to",
"the",
"current",
"bitstring",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3417-L3425
|
17,915
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.reverse
|
def reverse(self, start=None, end=None):
"""Reverse bits in-place.
start -- Position of first bit to reverse. Defaults to 0.
end -- One past the position of the last bit to reverse.
Defaults to self.len.
Using on an empty bitstring will have no effect.
Raises ValueError if start < 0, end > self.len or end < start.
"""
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] = s
|
python
|
def reverse(self, start=None, end=None):
"""Reverse bits in-place.
start -- Position of first bit to reverse. Defaults to 0.
end -- One past the position of the last bit to reverse.
Defaults to self.len.
Using on an empty bitstring will have no effect.
Raises ValueError if start < 0, end > self.len or end < start.
"""
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] = s
|
[
"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",
"]",
"=",
"s"
] |
Reverse bits in-place.
start -- Position of first bit to reverse. Defaults to 0.
end -- One past the position of the last bit to reverse.
Defaults to self.len.
Using on an empty bitstring will have no effect.
Raises ValueError if start < 0, end > self.len or end < start.
|
[
"Reverse",
"bits",
"in",
"-",
"place",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3436-L3454
|
17,916
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.set
|
def set(self, value, pos=None):
"""Set one or many bits to 1 or 0.
value -- If True bits are set to 1, otherwise they are set to 0.
pos -- Either a single bit position or an iterable of bit positions.
Negative numbers are treated in the same way as slice indices.
Defaults to the entire bitstring.
Raises IndexError if pos < -self.len or pos >= self.len.
"""
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
if not 0 <= p < length:
raise IndexError("Bit position {0} out of range.".format(p))
f(p)
except TypeError:
# Single pos
if pos < 0:
pos += self.len
if not 0 <= pos < length:
raise IndexError("Bit position {0} out of range.".format(pos))
f(pos)
|
python
|
def set(self, value, pos=None):
"""Set one or many bits to 1 or 0.
value -- If True bits are set to 1, otherwise they are set to 0.
pos -- Either a single bit position or an iterable of bit positions.
Negative numbers are treated in the same way as slice indices.
Defaults to the entire bitstring.
Raises IndexError if pos < -self.len or pos >= self.len.
"""
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
if not 0 <= p < length:
raise IndexError("Bit position {0} out of range.".format(p))
f(p)
except TypeError:
# Single pos
if pos < 0:
pos += self.len
if not 0 <= pos < length:
raise IndexError("Bit position {0} out of range.".format(pos))
f(pos)
|
[
"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",
"if",
"not",
"0",
"<=",
"p",
"<",
"length",
":",
"raise",
"IndexError",
"(",
"\"Bit position {0} out of range.\"",
".",
"format",
"(",
"p",
")",
")",
"f",
"(",
"p",
")",
"except",
"TypeError",
":",
"# Single pos",
"if",
"pos",
"<",
"0",
":",
"pos",
"+=",
"self",
".",
"len",
"if",
"not",
"0",
"<=",
"pos",
"<",
"length",
":",
"raise",
"IndexError",
"(",
"\"Bit position {0} out of range.\"",
".",
"format",
"(",
"pos",
")",
")",
"f",
"(",
"pos",
")"
] |
Set one or many bits to 1 or 0.
value -- If True bits are set to 1, otherwise they are set to 0.
pos -- Either a single bit position or an iterable of bit positions.
Negative numbers are treated in the same way as slice indices.
Defaults to the entire bitstring.
Raises IndexError if pos < -self.len or pos >= self.len.
|
[
"Set",
"one",
"or",
"many",
"bits",
"to",
"1",
"or",
"0",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3456-L3484
|
17,917
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.invert
|
def invert(self, pos=None):
"""Invert one or many bits from 0 to 1 or vice versa.
pos -- Either a single bit position or an iterable of bit positions.
Negative numbers are treated in the same way as slice indices.
Raises IndexError if pos < -self.len or pos >= self.len.
"""
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:
p += length
if not 0 <= p < length:
raise IndexError("Bit position {0} out of range.".format(p))
self._invert(p)
|
python
|
def invert(self, pos=None):
"""Invert one or many bits from 0 to 1 or vice versa.
pos -- Either a single bit position or an iterable of bit positions.
Negative numbers are treated in the same way as slice indices.
Raises IndexError if pos < -self.len or pos >= self.len.
"""
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:
p += length
if not 0 <= p < length:
raise IndexError("Bit position {0} out of range.".format(p))
self._invert(p)
|
[
"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",
":",
"p",
"+=",
"length",
"if",
"not",
"0",
"<=",
"p",
"<",
"length",
":",
"raise",
"IndexError",
"(",
"\"Bit position {0} out of range.\"",
".",
"format",
"(",
"p",
")",
")",
"self",
".",
"_invert",
"(",
"p",
")"
] |
Invert one or many bits from 0 to 1 or vice versa.
pos -- Either a single bit position or an iterable of bit positions.
Negative numbers are treated in the same way as slice indices.
Raises IndexError if pos < -self.len or pos >= self.len.
|
[
"Invert",
"one",
"or",
"many",
"bits",
"from",
"0",
"to",
"1",
"or",
"vice",
"versa",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3486-L3507
|
17,918
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.ror
|
def ror(self, bits, start=None, end=None):
"""Rotate bits to the right in-place.
bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.
Raises ValueError if bits < 0.
"""
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(start, end)
bits %= (end - start)
if not bits:
return
rhs = self._slice(end - bits, end)
self._delete(bits, end - bits)
self._insert(rhs, start)
|
python
|
def ror(self, bits, start=None, end=None):
"""Rotate bits to the right in-place.
bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.
Raises ValueError if bits < 0.
"""
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(start, end)
bits %= (end - start)
if not bits:
return
rhs = self._slice(end - bits, end)
self._delete(bits, end - bits)
self._insert(rhs, start)
|
[
"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",
"(",
"start",
",",
"end",
")",
"bits",
"%=",
"(",
"end",
"-",
"start",
")",
"if",
"not",
"bits",
":",
"return",
"rhs",
"=",
"self",
".",
"_slice",
"(",
"end",
"-",
"bits",
",",
"end",
")",
"self",
".",
"_delete",
"(",
"bits",
",",
"end",
"-",
"bits",
")",
"self",
".",
"_insert",
"(",
"rhs",
",",
"start",
")"
] |
Rotate bits to the right in-place.
bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.
Raises ValueError if bits < 0.
|
[
"Rotate",
"bits",
"to",
"the",
"right",
"in",
"-",
"place",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3509-L3529
|
17,919
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.rol
|
def rol(self, bits, start=None, end=None):
"""Rotate bits to the left in-place.
bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.
Raises ValueError if bits < 0.
"""
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(start, end)
bits %= (end - start)
if not bits:
return
lhs = self._slice(start, start + bits)
self._delete(bits, start)
self._insert(lhs, end - bits)
|
python
|
def rol(self, bits, start=None, end=None):
"""Rotate bits to the left in-place.
bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.
Raises ValueError if bits < 0.
"""
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(start, end)
bits %= (end - start)
if not bits:
return
lhs = self._slice(start, start + bits)
self._delete(bits, start)
self._insert(lhs, end - bits)
|
[
"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",
"(",
"start",
",",
"end",
")",
"bits",
"%=",
"(",
"end",
"-",
"start",
")",
"if",
"not",
"bits",
":",
"return",
"lhs",
"=",
"self",
".",
"_slice",
"(",
"start",
",",
"start",
"+",
"bits",
")",
"self",
".",
"_delete",
"(",
"bits",
",",
"start",
")",
"self",
".",
"_insert",
"(",
"lhs",
",",
"end",
"-",
"bits",
")"
] |
Rotate bits to the left in-place.
bits -- The number of bits to rotate by.
start -- Start of slice to rotate. Defaults to 0.
end -- End of slice to rotate. Defaults to self.len.
Raises ValueError if bits < 0.
|
[
"Rotate",
"bits",
"to",
"the",
"left",
"in",
"-",
"place",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3531-L3551
|
17,920
|
scott-griffiths/bitstring
|
bitstring.py
|
BitArray.byteswap
|
def byteswap(self, fmt=None, start=None, end=None, repeat=True):
"""Change the endianness in-place. Return number of repeats of fmt done.
fmt -- A compact structure string, an integer number of bytes or
an iterable of integers. Defaults to 0, which byte reverses the
whole bitstring.
start -- Start bit position, defaults to 0.
end -- End bit position, defaults to self.len.
repeat -- If True (the default) the byte swapping pattern is repeated
as much as possible.
"""
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 isinstance(fmt, numbers.Integral):
if fmt < 0:
raise ValueError("Improper byte length {0}.".format(fmt))
bytesizes = [fmt]
elif isinstance(fmt, basestring):
m = STRUCT_PACK_RE.match(fmt)
if not m:
raise ValueError("Cannot parse format string {0}.".format(fmt))
# Split the format string into a list of 'q', '4h' etc.
formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt'))
# Now deal with multiplicative factors, 4h -> hhhh etc.
bytesizes = []
for f in formatlist:
if len(f) == 1:
bytesizes.append(PACK_CODE_SIZE[f])
else:
bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1]))
elif isinstance(fmt, collections.Iterable):
bytesizes = fmt
for bytesize in bytesizes:
if not isinstance(bytesize, numbers.Integral) or bytesize < 0:
raise ValueError("Improper byte length {0}.".format(bytesize))
else:
raise TypeError("Format must be an integer, string or iterable.")
repeats = 0
totalbitsize = 8 * sum(bytesizes)
if not totalbitsize:
return 0
if repeat:
# Try to repeat up to the end of the bitstring.
finalbit = end
else:
# Just try one (set of) byteswap(s).
finalbit = start + totalbitsize
for patternend in xrange(start + totalbitsize, finalbit + 1, totalbitsize):
bytestart = patternend - totalbitsize
for bytesize in bytesizes:
byteend = bytestart + bytesize * 8
self._reversebytes(bytestart, byteend)
bytestart += bytesize * 8
repeats += 1
return repeats
|
python
|
def byteswap(self, fmt=None, start=None, end=None, repeat=True):
"""Change the endianness in-place. Return number of repeats of fmt done.
fmt -- A compact structure string, an integer number of bytes or
an iterable of integers. Defaults to 0, which byte reverses the
whole bitstring.
start -- Start bit position, defaults to 0.
end -- End bit position, defaults to self.len.
repeat -- If True (the default) the byte swapping pattern is repeated
as much as possible.
"""
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 isinstance(fmt, numbers.Integral):
if fmt < 0:
raise ValueError("Improper byte length {0}.".format(fmt))
bytesizes = [fmt]
elif isinstance(fmt, basestring):
m = STRUCT_PACK_RE.match(fmt)
if not m:
raise ValueError("Cannot parse format string {0}.".format(fmt))
# Split the format string into a list of 'q', '4h' etc.
formatlist = re.findall(STRUCT_SPLIT_RE, m.group('fmt'))
# Now deal with multiplicative factors, 4h -> hhhh etc.
bytesizes = []
for f in formatlist:
if len(f) == 1:
bytesizes.append(PACK_CODE_SIZE[f])
else:
bytesizes.extend([PACK_CODE_SIZE[f[-1]]] * int(f[:-1]))
elif isinstance(fmt, collections.Iterable):
bytesizes = fmt
for bytesize in bytesizes:
if not isinstance(bytesize, numbers.Integral) or bytesize < 0:
raise ValueError("Improper byte length {0}.".format(bytesize))
else:
raise TypeError("Format must be an integer, string or iterable.")
repeats = 0
totalbitsize = 8 * sum(bytesizes)
if not totalbitsize:
return 0
if repeat:
# Try to repeat up to the end of the bitstring.
finalbit = end
else:
# Just try one (set of) byteswap(s).
finalbit = start + totalbitsize
for patternend in xrange(start + totalbitsize, finalbit + 1, totalbitsize):
bytestart = patternend - totalbitsize
for bytesize in bytesizes:
byteend = bytestart + bytesize * 8
self._reversebytes(bytestart, byteend)
bytestart += bytesize * 8
repeats += 1
return repeats
|
[
"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",
"isinstance",
"(",
"fmt",
",",
"numbers",
".",
"Integral",
")",
":",
"if",
"fmt",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Improper byte length {0}.\"",
".",
"format",
"(",
"fmt",
")",
")",
"bytesizes",
"=",
"[",
"fmt",
"]",
"elif",
"isinstance",
"(",
"fmt",
",",
"basestring",
")",
":",
"m",
"=",
"STRUCT_PACK_RE",
".",
"match",
"(",
"fmt",
")",
"if",
"not",
"m",
":",
"raise",
"ValueError",
"(",
"\"Cannot parse format string {0}.\"",
".",
"format",
"(",
"fmt",
")",
")",
"# Split the format string into a list of 'q', '4h' etc.",
"formatlist",
"=",
"re",
".",
"findall",
"(",
"STRUCT_SPLIT_RE",
",",
"m",
".",
"group",
"(",
"'fmt'",
")",
")",
"# Now deal with multiplicative factors, 4h -> hhhh etc.",
"bytesizes",
"=",
"[",
"]",
"for",
"f",
"in",
"formatlist",
":",
"if",
"len",
"(",
"f",
")",
"==",
"1",
":",
"bytesizes",
".",
"append",
"(",
"PACK_CODE_SIZE",
"[",
"f",
"]",
")",
"else",
":",
"bytesizes",
".",
"extend",
"(",
"[",
"PACK_CODE_SIZE",
"[",
"f",
"[",
"-",
"1",
"]",
"]",
"]",
"*",
"int",
"(",
"f",
"[",
":",
"-",
"1",
"]",
")",
")",
"elif",
"isinstance",
"(",
"fmt",
",",
"collections",
".",
"Iterable",
")",
":",
"bytesizes",
"=",
"fmt",
"for",
"bytesize",
"in",
"bytesizes",
":",
"if",
"not",
"isinstance",
"(",
"bytesize",
",",
"numbers",
".",
"Integral",
")",
"or",
"bytesize",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Improper byte length {0}.\"",
".",
"format",
"(",
"bytesize",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Format must be an integer, string or iterable.\"",
")",
"repeats",
"=",
"0",
"totalbitsize",
"=",
"8",
"*",
"sum",
"(",
"bytesizes",
")",
"if",
"not",
"totalbitsize",
":",
"return",
"0",
"if",
"repeat",
":",
"# Try to repeat up to the end of the bitstring.",
"finalbit",
"=",
"end",
"else",
":",
"# Just try one (set of) byteswap(s).",
"finalbit",
"=",
"start",
"+",
"totalbitsize",
"for",
"patternend",
"in",
"xrange",
"(",
"start",
"+",
"totalbitsize",
",",
"finalbit",
"+",
"1",
",",
"totalbitsize",
")",
":",
"bytestart",
"=",
"patternend",
"-",
"totalbitsize",
"for",
"bytesize",
"in",
"bytesizes",
":",
"byteend",
"=",
"bytestart",
"+",
"bytesize",
"*",
"8",
"self",
".",
"_reversebytes",
"(",
"bytestart",
",",
"byteend",
")",
"bytestart",
"+=",
"bytesize",
"*",
"8",
"repeats",
"+=",
"1",
"return",
"repeats"
] |
Change the endianness in-place. Return number of repeats of fmt done.
fmt -- A compact structure string, an integer number of bytes or
an iterable of integers. Defaults to 0, which byte reverses the
whole bitstring.
start -- Start bit position, defaults to 0.
end -- End bit position, defaults to self.len.
repeat -- If True (the default) the byte swapping pattern is repeated
as much as possible.
|
[
"Change",
"the",
"endianness",
"in",
"-",
"place",
".",
"Return",
"number",
"of",
"repeats",
"of",
"fmt",
"done",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3553-L3611
|
17,921
|
scott-griffiths/bitstring
|
bitstring.py
|
ConstBitStream._setbitpos
|
def _setbitpos(self, pos):
"""Move to absolute postion bit in bitstream."""
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
|
python
|
def _setbitpos(self, pos):
"""Move to absolute postion bit in bitstream."""
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
|
[
"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.
|
[
"Move",
"to",
"absolute",
"postion",
"bit",
"in",
"bitstream",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3806-L3812
|
17,922
|
scott-griffiths/bitstring
|
bitstring.py
|
ConstBitStream.read
|
def read(self, fmt):
"""Interpret next bits according to the format string and return result.
fmt -- Token string describing how to interpret the next bits.
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' : next bits as unsigned exp-Golomb code
'se' : next bits as signed exp-Golomb code
'uie' : next bits as unsigned interleaved exp-Golomb code
'sie' : next bits as signed interleaved exp-Golomb code
'bits:5' : 5 bits as a bitstring
'bytes:10' : 10 bytes as a bytes object
'bool' : 1 bit as a bool
'pad:3' : 3 bits of padding to ignore - returns None
fmt may also be an integer, which will be treated like the 'bits' token.
The position in the bitstring is advanced to after the read items.
Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.
"""
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} available.",
fmt, self.len - self._pos)
bs = self._slice(self._pos, self._pos + fmt)
self._pos += fmt
return bs
p = self._pos
_, token = tokenparser(fmt)
if len(token) != 1:
self._pos = p
raise ValueError("Format string should be a single token, not {0} "
"tokens - use readlist() instead.".format(len(token)))
name, length, _ = token[0]
if length is None:
length = self.len - self._pos
value, self._pos = self._readtoken(name, self._pos, length)
return value
|
python
|
def read(self, fmt):
"""Interpret next bits according to the format string and return result.
fmt -- Token string describing how to interpret the next bits.
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' : next bits as unsigned exp-Golomb code
'se' : next bits as signed exp-Golomb code
'uie' : next bits as unsigned interleaved exp-Golomb code
'sie' : next bits as signed interleaved exp-Golomb code
'bits:5' : 5 bits as a bitstring
'bytes:10' : 10 bytes as a bytes object
'bool' : 1 bit as a bool
'pad:3' : 3 bits of padding to ignore - returns None
fmt may also be an integer, which will be treated like the 'bits' token.
The position in the bitstring is advanced to after the read items.
Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.
"""
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} available.",
fmt, self.len - self._pos)
bs = self._slice(self._pos, self._pos + fmt)
self._pos += fmt
return bs
p = self._pos
_, token = tokenparser(fmt)
if len(token) != 1:
self._pos = p
raise ValueError("Format string should be a single token, not {0} "
"tokens - use readlist() instead.".format(len(token)))
name, length, _ = token[0]
if length is None:
length = self.len - self._pos
value, self._pos = self._readtoken(name, self._pos, length)
return value
|
[
"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} available.\"",
",",
"fmt",
",",
"self",
".",
"len",
"-",
"self",
".",
"_pos",
")",
"bs",
"=",
"self",
".",
"_slice",
"(",
"self",
".",
"_pos",
",",
"self",
".",
"_pos",
"+",
"fmt",
")",
"self",
".",
"_pos",
"+=",
"fmt",
"return",
"bs",
"p",
"=",
"self",
".",
"_pos",
"_",
",",
"token",
"=",
"tokenparser",
"(",
"fmt",
")",
"if",
"len",
"(",
"token",
")",
"!=",
"1",
":",
"self",
".",
"_pos",
"=",
"p",
"raise",
"ValueError",
"(",
"\"Format string should be a single token, not {0} \"",
"\"tokens - use readlist() instead.\"",
".",
"format",
"(",
"len",
"(",
"token",
")",
")",
")",
"name",
",",
"length",
",",
"_",
"=",
"token",
"[",
"0",
"]",
"if",
"length",
"is",
"None",
":",
"length",
"=",
"self",
".",
"len",
"-",
"self",
".",
"_pos",
"value",
",",
"self",
".",
"_pos",
"=",
"self",
".",
"_readtoken",
"(",
"name",
",",
"self",
".",
"_pos",
",",
"length",
")",
"return",
"value"
] |
Interpret next bits according to the format string and return result.
fmt -- Token string describing how to interpret the next bits.
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' : next bits as unsigned exp-Golomb code
'se' : next bits as signed exp-Golomb code
'uie' : next bits as unsigned interleaved exp-Golomb code
'sie' : next bits as signed interleaved exp-Golomb code
'bits:5' : 5 bits as a bitstring
'bytes:10' : 10 bytes as a bytes object
'bool' : 1 bit as a bool
'pad:3' : 3 bits of padding to ignore - returns None
fmt may also be an integer, which will be treated like the 'bits' token.
The position in the bitstring is advanced to after the read items.
Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.
|
[
"Interpret",
"next",
"bits",
"according",
"to",
"the",
"format",
"string",
"and",
"return",
"result",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3842-L3897
|
17,923
|
scott-griffiths/bitstring
|
bitstring.py
|
ConstBitStream.readto
|
def readto(self, bs, bytealigned=None):
"""Read up to and including next occurrence of bs and return result.
bs -- The bitstring to find. An integer is not permitted.
bytealigned -- If True the bitstring will only be
found on byte boundaries.
Raises ValueError if bs is empty.
Raises ReadError if bs is not found.
"""
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)
if not p:
raise ReadError("Substring not found")
self._pos += bs.len
return self._slice(oldpos, self._pos)
|
python
|
def readto(self, bs, bytealigned=None):
"""Read up to and including next occurrence of bs and return result.
bs -- The bitstring to find. An integer is not permitted.
bytealigned -- If True the bitstring will only be
found on byte boundaries.
Raises ValueError if bs is empty.
Raises ReadError if bs is not found.
"""
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)
if not p:
raise ReadError("Substring not found")
self._pos += bs.len
return self._slice(oldpos, self._pos)
|
[
"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",
")",
"if",
"not",
"p",
":",
"raise",
"ReadError",
"(",
"\"Substring not found\"",
")",
"self",
".",
"_pos",
"+=",
"bs",
".",
"len",
"return",
"self",
".",
"_slice",
"(",
"oldpos",
",",
"self",
".",
"_pos",
")"
] |
Read up to and including next occurrence of bs and return result.
bs -- The bitstring to find. An integer is not permitted.
bytealigned -- If True the bitstring will only be
found on byte boundaries.
Raises ValueError if bs is empty.
Raises ReadError if bs is not found.
|
[
"Read",
"up",
"to",
"and",
"including",
"next",
"occurrence",
"of",
"bs",
"and",
"return",
"result",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3923-L3942
|
17,924
|
scott-griffiths/bitstring
|
bitstring.py
|
ConstBitStream.peek
|
def peek(self, fmt):
"""Interpret next bits according to format string and return result.
fmt -- Token string describing how to interpret the next bits.
The position in the bitstring is not changed. If not enough bits are
available then all bits to the end of the bitstring will be used.
Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.
See the docstring for 'read' for token examples.
"""
pos_before = self._pos
value = self.read(fmt)
self._pos = pos_before
return value
|
python
|
def peek(self, fmt):
"""Interpret next bits according to format string and return result.
fmt -- Token string describing how to interpret the next bits.
The position in the bitstring is not changed. If not enough bits are
available then all bits to the end of the bitstring will be used.
Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.
See the docstring for 'read' for token examples.
"""
pos_before = self._pos
value = self.read(fmt)
self._pos = pos_before
return value
|
[
"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.
fmt -- Token string describing how to interpret the next bits.
The position in the bitstring is not changed. If not enough bits are
available then all bits to the end of the bitstring will be used.
Raises ReadError if not enough bits are available.
Raises ValueError if the format is not understood.
See the docstring for 'read' for token examples.
|
[
"Interpret",
"next",
"bits",
"according",
"to",
"format",
"string",
"and",
"return",
"result",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3944-L3961
|
17,925
|
scott-griffiths/bitstring
|
bitstring.py
|
ConstBitStream.bytealign
|
def bytealign(self):
"""Align to next byte and return number of skipped bits.
Raises ValueError if the end of the bitstring is reached before
aligning to the next byte.
"""
skipped = (8 - (self._pos % 8)) % 8
self.pos += self._offset + skipped
assert self._assertsanity()
return skipped
|
python
|
def bytealign(self):
"""Align to next byte and return number of skipped bits.
Raises ValueError if the end of the bitstring is reached before
aligning to the next byte.
"""
skipped = (8 - (self._pos % 8)) % 8
self.pos += self._offset + skipped
assert self._assertsanity()
return skipped
|
[
"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.
Raises ValueError if the end of the bitstring is reached before
aligning to the next byte.
|
[
"Align",
"to",
"next",
"byte",
"and",
"return",
"number",
"of",
"skipped",
"bits",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L3985-L3995
|
17,926
|
scott-griffiths/bitstring
|
bitstring.py
|
BitStream.prepend
|
def prepend(self, bs):
"""Prepend a bitstring to the current bitstring.
bs -- The bitstring to prepend.
"""
bs = self._converttobitstring(bs)
self._prepend(bs)
self._pos += bs.len
|
python
|
def prepend(self, bs):
"""Prepend a bitstring to the current bitstring.
bs -- The bitstring to prepend.
"""
bs = self._converttobitstring(bs)
self._prepend(bs)
self._pos += bs.len
|
[
"def",
"prepend",
"(",
"self",
",",
"bs",
")",
":",
"bs",
"=",
"self",
".",
"_converttobitstring",
"(",
"bs",
")",
"self",
".",
"_prepend",
"(",
"bs",
")",
"self",
".",
"_pos",
"+=",
"bs",
".",
"len"
] |
Prepend a bitstring to the current bitstring.
bs -- The bitstring to prepend.
|
[
"Prepend",
"a",
"bitstring",
"to",
"the",
"current",
"bitstring",
"."
] |
ab40ae7f0b43fe223a39b63cbc0529b09f3ef653
|
https://github.com/scott-griffiths/bitstring/blob/ab40ae7f0b43fe223a39b63cbc0529b09f3ef653/bitstring.py#L4150-L4158
|
17,927
|
g2p/bedup
|
bedup/dedup.py
|
find_inodes_in_use
|
def find_inodes_in_use(fds):
"""
Find which of these inodes are in use, and give their open modes.
Does not count the passed fds as an use of the inode they point to,
but if the current process has the same inodes open with different
file descriptors these will be listed.
Looks at /proc/*/fd and /proc/*/map_files (Linux 3.3).
Conceivably there are other uses we're missing, to be foolproof
will require support in btrfs itself; a share-same-range ioctl
would work well.
"""
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 identifiers (devno and ino)
for proc_path in it:
try:
st = os.stat(proc_path)
except OSError as e:
# glob opens directories during matching,
# and other processes might close their fds in the meantime.
# This isn't a problem for the immutable-locked use case.
# ESTALE could happen with NFS or Docker
if e.errno in (errno.ENOENT, errno.ESTALE):
continue
raise
st_id = (st.st_dev, st.st_ino)
if st_id not in id_fd_assoc:
continue
yield proc_path, st_id
for proc_path, st_id in st_id_candidates(glob.glob('/proc/[1-9]*/fd/*')):
other_pid, other_fd = map(
int, PROC_PATH_RE.match(proc_path).groups())
original_fds = id_fd_assoc[st_id]
if other_pid == self_pid:
if other_fd in original_fds:
continue
use_info = proc_use_info(proc_path)
if not use_info:
continue
for fd in original_fds:
yield (fd, use_info)
# Requires Linux 3.3
for proc_path, st_id in st_id_candidates(
glob.glob('/proc/[1-9]*/map_files/*')
):
use_info = proc_use_info(proc_path)
if not use_info:
continue
original_fds = id_fd_assoc[st_id]
for fd in original_fds:
yield (fd, use_info)
|
python
|
def find_inodes_in_use(fds):
"""
Find which of these inodes are in use, and give their open modes.
Does not count the passed fds as an use of the inode they point to,
but if the current process has the same inodes open with different
file descriptors these will be listed.
Looks at /proc/*/fd and /proc/*/map_files (Linux 3.3).
Conceivably there are other uses we're missing, to be foolproof
will require support in btrfs itself; a share-same-range ioctl
would work well.
"""
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 identifiers (devno and ino)
for proc_path in it:
try:
st = os.stat(proc_path)
except OSError as e:
# glob opens directories during matching,
# and other processes might close their fds in the meantime.
# This isn't a problem for the immutable-locked use case.
# ESTALE could happen with NFS or Docker
if e.errno in (errno.ENOENT, errno.ESTALE):
continue
raise
st_id = (st.st_dev, st.st_ino)
if st_id not in id_fd_assoc:
continue
yield proc_path, st_id
for proc_path, st_id in st_id_candidates(glob.glob('/proc/[1-9]*/fd/*')):
other_pid, other_fd = map(
int, PROC_PATH_RE.match(proc_path).groups())
original_fds = id_fd_assoc[st_id]
if other_pid == self_pid:
if other_fd in original_fds:
continue
use_info = proc_use_info(proc_path)
if not use_info:
continue
for fd in original_fds:
yield (fd, use_info)
# Requires Linux 3.3
for proc_path, st_id in st_id_candidates(
glob.glob('/proc/[1-9]*/map_files/*')
):
use_info = proc_use_info(proc_path)
if not use_info:
continue
original_fds = id_fd_assoc[st_id]
for fd in original_fds:
yield (fd, use_info)
|
[
"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 identifiers (devno and ino)",
"for",
"proc_path",
"in",
"it",
":",
"try",
":",
"st",
"=",
"os",
".",
"stat",
"(",
"proc_path",
")",
"except",
"OSError",
"as",
"e",
":",
"# glob opens directories during matching,",
"# and other processes might close their fds in the meantime.",
"# This isn't a problem for the immutable-locked use case.",
"# ESTALE could happen with NFS or Docker",
"if",
"e",
".",
"errno",
"in",
"(",
"errno",
".",
"ENOENT",
",",
"errno",
".",
"ESTALE",
")",
":",
"continue",
"raise",
"st_id",
"=",
"(",
"st",
".",
"st_dev",
",",
"st",
".",
"st_ino",
")",
"if",
"st_id",
"not",
"in",
"id_fd_assoc",
":",
"continue",
"yield",
"proc_path",
",",
"st_id",
"for",
"proc_path",
",",
"st_id",
"in",
"st_id_candidates",
"(",
"glob",
".",
"glob",
"(",
"'/proc/[1-9]*/fd/*'",
")",
")",
":",
"other_pid",
",",
"other_fd",
"=",
"map",
"(",
"int",
",",
"PROC_PATH_RE",
".",
"match",
"(",
"proc_path",
")",
".",
"groups",
"(",
")",
")",
"original_fds",
"=",
"id_fd_assoc",
"[",
"st_id",
"]",
"if",
"other_pid",
"==",
"self_pid",
":",
"if",
"other_fd",
"in",
"original_fds",
":",
"continue",
"use_info",
"=",
"proc_use_info",
"(",
"proc_path",
")",
"if",
"not",
"use_info",
":",
"continue",
"for",
"fd",
"in",
"original_fds",
":",
"yield",
"(",
"fd",
",",
"use_info",
")",
"# Requires Linux 3.3",
"for",
"proc_path",
",",
"st_id",
"in",
"st_id_candidates",
"(",
"glob",
".",
"glob",
"(",
"'/proc/[1-9]*/map_files/*'",
")",
")",
":",
"use_info",
"=",
"proc_use_info",
"(",
"proc_path",
")",
"if",
"not",
"use_info",
":",
"continue",
"original_fds",
"=",
"id_fd_assoc",
"[",
"st_id",
"]",
"for",
"fd",
"in",
"original_fds",
":",
"yield",
"(",
"fd",
",",
"use_info",
")"
] |
Find which of these inodes are in use, and give their open modes.
Does not count the passed fds as an use of the inode they point to,
but if the current process has the same inodes open with different
file descriptors these will be listed.
Looks at /proc/*/fd and /proc/*/map_files (Linux 3.3).
Conceivably there are other uses we're missing, to be foolproof
will require support in btrfs itself; a share-same-range ioctl
would work well.
|
[
"Find",
"which",
"of",
"these",
"inodes",
"are",
"in",
"use",
"and",
"give",
"their",
"open",
"modes",
"."
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/dedup.py#L120-L186
|
17,928
|
g2p/bedup
|
bedup/platform/ioprio.py
|
set_idle_priority
|
def set_idle_priority(pid=None):
"""
Puts a process in the idle io priority class.
If pid is omitted, applies to the current process.
"""
if pid is None:
pid = os.getpid()
lib.ioprio_set(
lib.IOPRIO_WHO_PROCESS, pid,
lib.IOPRIO_PRIO_VALUE(lib.IOPRIO_CLASS_IDLE, 0))
|
python
|
def set_idle_priority(pid=None):
"""
Puts a process in the idle io priority class.
If pid is omitted, applies to the current process.
"""
if pid is None:
pid = os.getpid()
lib.ioprio_set(
lib.IOPRIO_WHO_PROCESS, pid,
lib.IOPRIO_PRIO_VALUE(lib.IOPRIO_CLASS_IDLE, 0))
|
[
"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",
")",
")"
] |
Puts a process in the idle io priority class.
If pid is omitted, applies to the current process.
|
[
"Puts",
"a",
"process",
"in",
"the",
"idle",
"io",
"priority",
"class",
"."
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/ioprio.py#L82-L93
|
17,929
|
g2p/bedup
|
bedup/platform/futimens.py
|
futimens
|
def futimens(fd, ns):
"""
set inode atime and mtime
ns is (atime, mtime), a pair of struct timespec
with nanosecond resolution.
"""
# 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_nsec < 1e9
times[0] = atime
times[1] = mtime
if lib.futimens(fd, times) != 0:
raise IOError(
ffi.errno, os.strerror(ffi.errno),
(fd, atime.tv_sec, atime.tv_nsec, mtime.tv_sec, mtime.tv_nsec))
|
python
|
def futimens(fd, ns):
"""
set inode atime and mtime
ns is (atime, mtime), a pair of struct timespec
with nanosecond resolution.
"""
# 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_nsec < 1e9
times[0] = atime
times[1] = mtime
if lib.futimens(fd, times) != 0:
raise IOError(
ffi.errno, os.strerror(ffi.errno),
(fd, atime.tv_sec, atime.tv_nsec, mtime.tv_sec, mtime.tv_nsec))
|
[
"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_nsec",
"<",
"1e9",
"times",
"[",
"0",
"]",
"=",
"atime",
"times",
"[",
"1",
"]",
"=",
"mtime",
"if",
"lib",
".",
"futimens",
"(",
"fd",
",",
"times",
")",
"!=",
"0",
":",
"raise",
"IOError",
"(",
"ffi",
".",
"errno",
",",
"os",
".",
"strerror",
"(",
"ffi",
".",
"errno",
")",
",",
"(",
"fd",
",",
"atime",
".",
"tv_sec",
",",
"atime",
".",
"tv_nsec",
",",
"mtime",
".",
"tv_sec",
",",
"mtime",
".",
"tv_nsec",
")",
")"
] |
set inode atime and mtime
ns is (atime, mtime), a pair of struct timespec
with nanosecond resolution.
|
[
"set",
"inode",
"atime",
"and",
"mtime"
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/futimens.py#L70-L90
|
17,930
|
g2p/bedup
|
bedup/platform/openat.py
|
fopenat
|
def fopenat(base_fd, path):
"""
Does openat read-only, then does fdopen to get a file object
"""
return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')
|
python
|
def fopenat(base_fd, path):
"""
Does openat read-only, then does fdopen to get a file object
"""
return os.fdopen(openat(base_fd, path, os.O_RDONLY), 'rb')
|
[
"def",
"fopenat",
"(",
"base_fd",
",",
"path",
")",
":",
"return",
"os",
".",
"fdopen",
"(",
"openat",
"(",
"base_fd",
",",
"path",
",",
"os",
".",
"O_RDONLY",
")",
",",
"'rb'",
")"
] |
Does openat read-only, then does fdopen to get a file object
|
[
"Does",
"openat",
"read",
"-",
"only",
"then",
"does",
"fdopen",
"to",
"get",
"a",
"file",
"object"
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/openat.py#L44-L49
|
17,931
|
g2p/bedup
|
bedup/platform/openat.py
|
fopenat_rw
|
def fopenat_rw(base_fd, path):
"""
Does openat read-write, then does fdopen to get a file object
"""
return os.fdopen(openat(base_fd, path, os.O_RDWR), 'rb+')
|
python
|
def fopenat_rw(base_fd, path):
"""
Does openat read-write, then does fdopen to get a file object
"""
return os.fdopen(openat(base_fd, path, os.O_RDWR), 'rb+')
|
[
"def",
"fopenat_rw",
"(",
"base_fd",
",",
"path",
")",
":",
"return",
"os",
".",
"fdopen",
"(",
"openat",
"(",
"base_fd",
",",
"path",
",",
"os",
".",
"O_RDWR",
")",
",",
"'rb+'",
")"
] |
Does openat read-write, then does fdopen to get a file object
|
[
"Does",
"openat",
"read",
"-",
"write",
"then",
"does",
"fdopen",
"to",
"get",
"a",
"file",
"object"
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/openat.py#L52-L57
|
17,932
|
g2p/bedup
|
bedup/platform/fiemap.py
|
fiemap
|
def fiemap(fd):
"""
Gets a map of file extents.
"""
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)
assert ffi.sizeof(fiemap_cbuf) <= 4096
while True:
fiemap_ptr.fm_length = lib.FIEMAP_MAX_OFFSET
fiemap_ptr.fm_extent_count = count
fcntl.ioctl(fd, lib.FS_IOC_FIEMAP, fiemap_pybuf)
if fiemap_ptr.fm_mapped_extents == 0:
break
for i in range(fiemap_ptr.fm_mapped_extents):
extent = fiemap_ptr.fm_extents[i]
yield FiemapExtent(
extent.fe_logical, extent.fe_physical,
extent.fe_length, extent.fe_flags)
fiemap_ptr.fm_start = extent.fe_logical + extent.fe_length
|
python
|
def fiemap(fd):
"""
Gets a map of file extents.
"""
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)
assert ffi.sizeof(fiemap_cbuf) <= 4096
while True:
fiemap_ptr.fm_length = lib.FIEMAP_MAX_OFFSET
fiemap_ptr.fm_extent_count = count
fcntl.ioctl(fd, lib.FS_IOC_FIEMAP, fiemap_pybuf)
if fiemap_ptr.fm_mapped_extents == 0:
break
for i in range(fiemap_ptr.fm_mapped_extents):
extent = fiemap_ptr.fm_extents[i]
yield FiemapExtent(
extent.fe_logical, extent.fe_physical,
extent.fe_length, extent.fe_flags)
fiemap_ptr.fm_start = extent.fe_logical + extent.fe_length
|
[
"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",
")",
"assert",
"ffi",
".",
"sizeof",
"(",
"fiemap_cbuf",
")",
"<=",
"4096",
"while",
"True",
":",
"fiemap_ptr",
".",
"fm_length",
"=",
"lib",
".",
"FIEMAP_MAX_OFFSET",
"fiemap_ptr",
".",
"fm_extent_count",
"=",
"count",
"fcntl",
".",
"ioctl",
"(",
"fd",
",",
"lib",
".",
"FS_IOC_FIEMAP",
",",
"fiemap_pybuf",
")",
"if",
"fiemap_ptr",
".",
"fm_mapped_extents",
"==",
"0",
":",
"break",
"for",
"i",
"in",
"range",
"(",
"fiemap_ptr",
".",
"fm_mapped_extents",
")",
":",
"extent",
"=",
"fiemap_ptr",
".",
"fm_extents",
"[",
"i",
"]",
"yield",
"FiemapExtent",
"(",
"extent",
".",
"fe_logical",
",",
"extent",
".",
"fe_physical",
",",
"extent",
".",
"fe_length",
",",
"extent",
".",
"fe_flags",
")",
"fiemap_ptr",
".",
"fm_start",
"=",
"extent",
".",
"fe_logical",
"+",
"extent",
".",
"fe_length"
] |
Gets a map of file extents.
|
[
"Gets",
"a",
"map",
"of",
"file",
"extents",
"."
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/fiemap.py#L93-L118
|
17,933
|
g2p/bedup
|
bedup/platform/chattr.py
|
getflags
|
def getflags(fd):
"""
Gets per-file filesystem flags.
"""
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]
|
python
|
def getflags(fd):
"""
Gets per-file filesystem flags.
"""
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]
|
[
"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",
"]"
] |
Gets per-file filesystem flags.
|
[
"Gets",
"per",
"-",
"file",
"filesystem",
"flags",
"."
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/chattr.py#L74-L82
|
17,934
|
g2p/bedup
|
bedup/platform/chattr.py
|
editflags
|
def editflags(fd, add_flags=0, remove_flags=0):
"""
Sets and unsets per-file filesystem flags.
"""
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 kernel uses an implicit int,
# let's be explicit here.
flags_ptr = ffi.new('uint64_t*')
flags_buf = ffi.buffer(flags_ptr)
fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf)
prev_flags = flags_ptr[0]
flags_ptr[0] |= add_flags
# Python represents negative numbers with an infinite number of
# ones in bitops, so this will work correctly.
flags_ptr[0] &= ~remove_flags
fcntl.ioctl(fd, lib.FS_IOC_SETFLAGS, flags_buf)
return prev_flags & (add_flags | remove_flags)
|
python
|
def editflags(fd, add_flags=0, remove_flags=0):
"""
Sets and unsets per-file filesystem flags.
"""
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 kernel uses an implicit int,
# let's be explicit here.
flags_ptr = ffi.new('uint64_t*')
flags_buf = ffi.buffer(flags_ptr)
fcntl.ioctl(fd, lib.FS_IOC_GETFLAGS, flags_buf)
prev_flags = flags_ptr[0]
flags_ptr[0] |= add_flags
# Python represents negative numbers with an infinite number of
# ones in bitops, so this will work correctly.
flags_ptr[0] &= ~remove_flags
fcntl.ioctl(fd, lib.FS_IOC_SETFLAGS, flags_buf)
return prev_flags & (add_flags | remove_flags)
|
[
"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 kernel uses an implicit int,",
"# let's be explicit here.",
"flags_ptr",
"=",
"ffi",
".",
"new",
"(",
"'uint64_t*'",
")",
"flags_buf",
"=",
"ffi",
".",
"buffer",
"(",
"flags_ptr",
")",
"fcntl",
".",
"ioctl",
"(",
"fd",
",",
"lib",
".",
"FS_IOC_GETFLAGS",
",",
"flags_buf",
")",
"prev_flags",
"=",
"flags_ptr",
"[",
"0",
"]",
"flags_ptr",
"[",
"0",
"]",
"|=",
"add_flags",
"# Python represents negative numbers with an infinite number of",
"# ones in bitops, so this will work correctly.",
"flags_ptr",
"[",
"0",
"]",
"&=",
"~",
"remove_flags",
"fcntl",
".",
"ioctl",
"(",
"fd",
",",
"lib",
".",
"FS_IOC_SETFLAGS",
",",
"flags_buf",
")",
"return",
"prev_flags",
"&",
"(",
"add_flags",
"|",
"remove_flags",
")"
] |
Sets and unsets per-file filesystem flags.
|
[
"Sets",
"and",
"unsets",
"per",
"-",
"file",
"filesystem",
"flags",
"."
] |
9694f6f718844c33017052eb271f68b6c0d0b7d3
|
https://github.com/g2p/bedup/blob/9694f6f718844c33017052eb271f68b6c0d0b7d3/bedup/platform/chattr.py#L85-L107
|
17,935
|
luqasz/librouteros
|
librouteros/__init__.py
|
connect
|
def connect(host, username, password, **kwargs):
"""
Connect and login to routeros device.
Upon success return a Api class.
:param host: Hostname to connecto to. May be ipv4,ipv6,FQDN.
:param username: Username to login with.
:param password: Password to login with. Only ASCII characters allowed.
:param timeout: Socket timeout. Defaults to 10.
:param port: Destination port to be used. Defaults to 8728.
:param saddr: Source address to bind to.
:param subclass: Subclass of Api class. Defaults to Api class from library.
:param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with.
:param login_methods: Tuple with callables to login methods to try in order.
"""
arguments = ChainMap(kwargs, defaults)
transport = create_transport(host, **arguments)
protocol = ApiProtocol(transport=transport, encoding=arguments['encoding'])
api = arguments['subclass'](protocol=protocol)
for method in arguments['login_methods']:
try:
method(api=api, username=username, password=password)
return api
except (TrapError, MultiTrapError):
pass
except (ConnectionError, FatalError):
transport.close()
raise
|
python
|
def connect(host, username, password, **kwargs):
"""
Connect and login to routeros device.
Upon success return a Api class.
:param host: Hostname to connecto to. May be ipv4,ipv6,FQDN.
:param username: Username to login with.
:param password: Password to login with. Only ASCII characters allowed.
:param timeout: Socket timeout. Defaults to 10.
:param port: Destination port to be used. Defaults to 8728.
:param saddr: Source address to bind to.
:param subclass: Subclass of Api class. Defaults to Api class from library.
:param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with.
:param login_methods: Tuple with callables to login methods to try in order.
"""
arguments = ChainMap(kwargs, defaults)
transport = create_transport(host, **arguments)
protocol = ApiProtocol(transport=transport, encoding=arguments['encoding'])
api = arguments['subclass'](protocol=protocol)
for method in arguments['login_methods']:
try:
method(api=api, username=username, password=password)
return api
except (TrapError, MultiTrapError):
pass
except (ConnectionError, FatalError):
transport.close()
raise
|
[
"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",
"=",
"protocol",
")",
"for",
"method",
"in",
"arguments",
"[",
"'login_methods'",
"]",
":",
"try",
":",
"method",
"(",
"api",
"=",
"api",
",",
"username",
"=",
"username",
",",
"password",
"=",
"password",
")",
"return",
"api",
"except",
"(",
"TrapError",
",",
"MultiTrapError",
")",
":",
"pass",
"except",
"(",
"ConnectionError",
",",
"FatalError",
")",
":",
"transport",
".",
"close",
"(",
")",
"raise"
] |
Connect and login to routeros device.
Upon success return a Api class.
:param host: Hostname to connecto to. May be ipv4,ipv6,FQDN.
:param username: Username to login with.
:param password: Password to login with. Only ASCII characters allowed.
:param timeout: Socket timeout. Defaults to 10.
:param port: Destination port to be used. Defaults to 8728.
:param saddr: Source address to bind to.
:param subclass: Subclass of Api class. Defaults to Api class from library.
:param ssl_wrapper: Callable (e.g. ssl.SSLContext instance) to wrap socket with.
:param login_methods: Tuple with callables to login methods to try in order.
|
[
"Connect",
"and",
"login",
"to",
"routeros",
"device",
".",
"Upon",
"success",
"return",
"a",
"Api",
"class",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/__init__.py#L26-L54
|
17,936
|
luqasz/librouteros
|
librouteros/api.py
|
Api._readSentence
|
def _readSentence(self):
"""
Read one sentence and parse words.
:returns: Reply word, dict with attribute words.
"""
reply_word, words = self.protocol.readSentence()
words = dict(parseWord(word) for word in words)
return reply_word, words
|
python
|
def _readSentence(self):
"""
Read one sentence and parse words.
:returns: Reply word, dict with attribute words.
"""
reply_word, words = self.protocol.readSentence()
words = dict(parseWord(word) for word in words)
return reply_word, words
|
[
"def",
"_readSentence",
"(",
"self",
")",
":",
"reply_word",
",",
"words",
"=",
"self",
".",
"protocol",
".",
"readSentence",
"(",
")",
"words",
"=",
"dict",
"(",
"parseWord",
"(",
"word",
")",
"for",
"word",
"in",
"words",
")",
"return",
"reply_word",
",",
"words"
] |
Read one sentence and parse words.
:returns: Reply word, dict with attribute words.
|
[
"Read",
"one",
"sentence",
"and",
"parse",
"words",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/api.py#L29-L37
|
17,937
|
luqasz/librouteros
|
librouteros/api.py
|
Api._readResponse
|
def _readResponse(self):
"""
Yield each row of response untill !done is received.
:throws TrapError: If one !trap is received.
:throws MultiTrapError: If > 1 !trap is received.
"""
traps = []
reply_word = None
while reply_word != '!done':
reply_word, words = self._readSentence()
if reply_word == '!trap':
traps.append(TrapError(**words))
elif reply_word in ('!re', '!done') and words:
yield words
if len(traps) > 1:
raise MultiTrapError(*traps)
elif len(traps) == 1:
raise traps[0]
|
python
|
def _readResponse(self):
"""
Yield each row of response untill !done is received.
:throws TrapError: If one !trap is received.
:throws MultiTrapError: If > 1 !trap is received.
"""
traps = []
reply_word = None
while reply_word != '!done':
reply_word, words = self._readSentence()
if reply_word == '!trap':
traps.append(TrapError(**words))
elif reply_word in ('!re', '!done') and words:
yield words
if len(traps) > 1:
raise MultiTrapError(*traps)
elif len(traps) == 1:
raise traps[0]
|
[
"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",
"reply_word",
"in",
"(",
"'!re'",
",",
"'!done'",
")",
"and",
"words",
":",
"yield",
"words",
"if",
"len",
"(",
"traps",
")",
">",
"1",
":",
"raise",
"MultiTrapError",
"(",
"*",
"traps",
")",
"elif",
"len",
"(",
"traps",
")",
"==",
"1",
":",
"raise",
"traps",
"[",
"0",
"]"
] |
Yield each row of response untill !done is received.
:throws TrapError: If one !trap is received.
:throws MultiTrapError: If > 1 !trap is received.
|
[
"Yield",
"each",
"row",
"of",
"response",
"untill",
"!done",
"is",
"received",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/api.py#L39-L58
|
17,938
|
luqasz/librouteros
|
librouteros/connections.py
|
Encoder.encodeSentence
|
def encodeSentence(self, *words):
"""
Encode given sentence in API format.
:param words: Words to endoce.
:returns: Encoded sentence.
"""
encoded = map(self.encodeWord, words)
encoded = b''.join(encoded)
# append EOS (end of sentence) byte
encoded += b'\x00'
return encoded
|
python
|
def encodeSentence(self, *words):
"""
Encode given sentence in API format.
:param words: Words to endoce.
:returns: Encoded sentence.
"""
encoded = map(self.encodeWord, words)
encoded = b''.join(encoded)
# append EOS (end of sentence) byte
encoded += b'\x00'
return encoded
|
[
"def",
"encodeSentence",
"(",
"self",
",",
"*",
"words",
")",
":",
"encoded",
"=",
"map",
"(",
"self",
".",
"encodeWord",
",",
"words",
")",
"encoded",
"=",
"b''",
".",
"join",
"(",
"encoded",
")",
"# append EOS (end of sentence) byte",
"encoded",
"+=",
"b'\\x00'",
"return",
"encoded"
] |
Encode given sentence in API format.
:param words: Words to endoce.
:returns: Encoded sentence.
|
[
"Encode",
"given",
"sentence",
"in",
"API",
"format",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L14-L25
|
17,939
|
luqasz/librouteros
|
librouteros/connections.py
|
Encoder.encodeWord
|
def encodeWord(self, word):
"""
Encode word in API format.
:param word: Word to encode.
:returns: Encoded word.
"""
encoded_word = word.encode(encoding=self.encoding, errors='strict')
return Encoder.encodeLength(len(word)) + encoded_word
|
python
|
def encodeWord(self, word):
"""
Encode word in API format.
:param word: Word to encode.
:returns: Encoded word.
"""
encoded_word = word.encode(encoding=self.encoding, errors='strict')
return Encoder.encodeLength(len(word)) + encoded_word
|
[
"def",
"encodeWord",
"(",
"self",
",",
"word",
")",
":",
"encoded_word",
"=",
"word",
".",
"encode",
"(",
"encoding",
"=",
"self",
".",
"encoding",
",",
"errors",
"=",
"'strict'",
")",
"return",
"Encoder",
".",
"encodeLength",
"(",
"len",
"(",
"word",
")",
")",
"+",
"encoded_word"
] |
Encode word in API format.
:param word: Word to encode.
:returns: Encoded word.
|
[
"Encode",
"word",
"in",
"API",
"format",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L27-L35
|
17,940
|
luqasz/librouteros
|
librouteros/connections.py
|
Encoder.encodeLength
|
def encodeLength(length):
"""
Encode given length in mikrotik format.
:param length: Integer < 268435456.
:returns: Encoded length.
"""
if length < 128:
ored_length = length
offset = -1
elif length < 16384:
ored_length = length | 0x8000
offset = -2
elif length < 2097152:
ored_length = length | 0xC00000
offset = -3
elif length < 268435456:
ored_length = length | 0xE0000000
offset = -4
else:
raise ConnectionError('Unable to encode length of {}'.format(length))
return pack('!I', ored_length)[offset:]
|
python
|
def encodeLength(length):
"""
Encode given length in mikrotik format.
:param length: Integer < 268435456.
:returns: Encoded length.
"""
if length < 128:
ored_length = length
offset = -1
elif length < 16384:
ored_length = length | 0x8000
offset = -2
elif length < 2097152:
ored_length = length | 0xC00000
offset = -3
elif length < 268435456:
ored_length = length | 0xE0000000
offset = -4
else:
raise ConnectionError('Unable to encode length of {}'.format(length))
return pack('!I', ored_length)[offset:]
|
[
"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",
"|",
"0xC00000",
"offset",
"=",
"-",
"3",
"elif",
"length",
"<",
"268435456",
":",
"ored_length",
"=",
"length",
"|",
"0xE0000000",
"offset",
"=",
"-",
"4",
"else",
":",
"raise",
"ConnectionError",
"(",
"'Unable to encode length of {}'",
".",
"format",
"(",
"length",
")",
")",
"return",
"pack",
"(",
"'!I'",
",",
"ored_length",
")",
"[",
"offset",
":",
"]"
] |
Encode given length in mikrotik format.
:param length: Integer < 268435456.
:returns: Encoded length.
|
[
"Encode",
"given",
"length",
"in",
"mikrotik",
"format",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L38-L60
|
17,941
|
luqasz/librouteros
|
librouteros/connections.py
|
Decoder.determineLength
|
def determineLength(length):
"""
Given first read byte, determine how many more bytes
needs to be known in order to get fully encoded length.
:param length: First read byte.
:return: How many bytes to read.
"""
integer = ord(length)
if integer < 128:
return 0
elif integer < 192:
return 1
elif integer < 224:
return 2
elif integer < 240:
return 3
else:
raise ConnectionError('Unknown controll byte {}'.format(length))
|
python
|
def determineLength(length):
"""
Given first read byte, determine how many more bytes
needs to be known in order to get fully encoded length.
:param length: First read byte.
:return: How many bytes to read.
"""
integer = ord(length)
if integer < 128:
return 0
elif integer < 192:
return 1
elif integer < 224:
return 2
elif integer < 240:
return 3
else:
raise ConnectionError('Unknown controll byte {}'.format(length))
|
[
"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",
":",
"raise",
"ConnectionError",
"(",
"'Unknown controll byte {}'",
".",
"format",
"(",
"length",
")",
")"
] |
Given first read byte, determine how many more bytes
needs to be known in order to get fully encoded length.
:param length: First read byte.
:return: How many bytes to read.
|
[
"Given",
"first",
"read",
"byte",
"determine",
"how",
"many",
"more",
"bytes",
"needs",
"to",
"be",
"known",
"in",
"order",
"to",
"get",
"fully",
"encoded",
"length",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L66-L85
|
17,942
|
luqasz/librouteros
|
librouteros/connections.py
|
Decoder.decodeLength
|
def decodeLength(length):
"""
Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded 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:
offset = b'\x00'
XOR = 0xC00000
elif bytes_length < 5:
offset = b''
XOR = 0xE0000000
else:
raise ConnectionError('Unable to decode length of {}'.format(length))
decoded = unpack('!I', (offset + length))[0]
decoded ^= XOR
return decoded
|
python
|
def decodeLength(length):
"""
Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded 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:
offset = b'\x00'
XOR = 0xC00000
elif bytes_length < 5:
offset = b''
XOR = 0xE0000000
else:
raise ConnectionError('Unable to decode length of {}'.format(length))
decoded = unpack('!I', (offset + length))[0]
decoded ^= XOR
return decoded
|
[
"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",
":",
"offset",
"=",
"b'\\x00'",
"XOR",
"=",
"0xC00000",
"elif",
"bytes_length",
"<",
"5",
":",
"offset",
"=",
"b''",
"XOR",
"=",
"0xE0000000",
"else",
":",
"raise",
"ConnectionError",
"(",
"'Unable to decode length of {}'",
".",
"format",
"(",
"length",
")",
")",
"decoded",
"=",
"unpack",
"(",
"'!I'",
",",
"(",
"offset",
"+",
"length",
")",
")",
"[",
"0",
"]",
"decoded",
"^=",
"XOR",
"return",
"decoded"
] |
Decode length based on given bytes.
:param length: Bytes string to decode.
:return: Decoded length.
|
[
"Decode",
"length",
"based",
"on",
"given",
"bytes",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L88-L114
|
17,943
|
luqasz/librouteros
|
librouteros/connections.py
|
ApiProtocol.writeSentence
|
def writeSentence(self, cmd, *words):
"""
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words.
"""
encoded = self.encodeSentence(cmd, *words)
self.log('<---', cmd, *words)
self.transport.write(encoded)
|
python
|
def writeSentence(self, cmd, *words):
"""
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words.
"""
encoded = self.encodeSentence(cmd, *words)
self.log('<---', cmd, *words)
self.transport.write(encoded)
|
[
"def",
"writeSentence",
"(",
"self",
",",
"cmd",
",",
"*",
"words",
")",
":",
"encoded",
"=",
"self",
".",
"encodeSentence",
"(",
"cmd",
",",
"*",
"words",
")",
"self",
".",
"log",
"(",
"'<---'",
",",
"cmd",
",",
"*",
"words",
")",
"self",
".",
"transport",
".",
"write",
"(",
"encoded",
")"
] |
Write encoded sentence.
:param cmd: Command word.
:param words: Aditional words.
|
[
"Write",
"encoded",
"sentence",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L129-L138
|
17,944
|
luqasz/librouteros
|
librouteros/connections.py
|
SocketTransport.read
|
def read(self, length):
"""
Read as many bytes from socket as specified in length.
Loop as long as every byte is read unless exception is raised.
"""
data = bytearray()
while len(data) != length:
data += self.sock.recv((length - len(data)))
if not data:
raise ConnectionError('Connection unexpectedly closed.')
return data
|
python
|
def read(self, length):
"""
Read as many bytes from socket as specified in length.
Loop as long as every byte is read unless exception is raised.
"""
data = bytearray()
while len(data) != length:
data += self.sock.recv((length - len(data)))
if not data:
raise ConnectionError('Connection unexpectedly closed.')
return data
|
[
"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"
] |
Read as many bytes from socket as specified in length.
Loop as long as every byte is read unless exception is raised.
|
[
"Read",
"as",
"many",
"bytes",
"from",
"socket",
"as",
"specified",
"in",
"length",
".",
"Loop",
"as",
"long",
"as",
"every",
"byte",
"is",
"read",
"unless",
"exception",
"is",
"raised",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L178-L188
|
17,945
|
luqasz/librouteros
|
librouteros/protocol.py
|
parseWord
|
def parseWord(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
value = int(value)
except ValueError:
value = mapping.get(value, value)
return (key, value)
|
python
|
def parseWord(word):
"""
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
"""
mapping = {'yes': True, 'true': True, 'no': False, 'false': False}
_, key, value = word.split('=', 2)
try:
value = int(value)
except ValueError:
value = mapping.get(value, value)
return (key, value)
|
[
"def",
"parseWord",
"(",
"word",
")",
":",
"mapping",
"=",
"{",
"'yes'",
":",
"True",
",",
"'true'",
":",
"True",
",",
"'no'",
":",
"False",
",",
"'false'",
":",
"False",
"}",
"_",
",",
"key",
",",
"value",
"=",
"word",
".",
"split",
"(",
"'='",
",",
"2",
")",
"try",
":",
"value",
"=",
"int",
"(",
"value",
")",
"except",
"ValueError",
":",
"value",
"=",
"mapping",
".",
"get",
"(",
"value",
",",
"value",
")",
"return",
"(",
"key",
",",
"value",
")"
] |
Split given attribute word to key, value pair.
Values are casted to python equivalents.
:param word: API word.
:returns: Key, value pair.
|
[
"Split",
"given",
"attribute",
"word",
"to",
"key",
"value",
"pair",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L1-L16
|
17,946
|
luqasz/librouteros
|
librouteros/protocol.py
|
composeWord
|
def composeWord(key, value):
"""
Create a attribute word from key, value pair.
Values are casted to api equivalents.
"""
mapping = {True: 'yes', False: 'no'}
# this is necesary because 1 == True, 0 == False
if type(value) == int:
value = str(value)
else:
value = mapping.get(value, str(value))
return '={}={}'.format(key, value)
|
python
|
def composeWord(key, value):
"""
Create a attribute word from key, value pair.
Values are casted to api equivalents.
"""
mapping = {True: 'yes', False: 'no'}
# this is necesary because 1 == True, 0 == False
if type(value) == int:
value = str(value)
else:
value = mapping.get(value, str(value))
return '={}={}'.format(key, value)
|
[
"def",
"composeWord",
"(",
"key",
",",
"value",
")",
":",
"mapping",
"=",
"{",
"True",
":",
"'yes'",
",",
"False",
":",
"'no'",
"}",
"# this is necesary because 1 == True, 0 == False",
"if",
"type",
"(",
"value",
")",
"==",
"int",
":",
"value",
"=",
"str",
"(",
"value",
")",
"else",
":",
"value",
"=",
"mapping",
".",
"get",
"(",
"value",
",",
"str",
"(",
"value",
")",
")",
"return",
"'={}={}'",
".",
"format",
"(",
"key",
",",
"value",
")"
] |
Create a attribute word from key, value pair.
Values are casted to api equivalents.
|
[
"Create",
"a",
"attribute",
"word",
"from",
"key",
"value",
"pair",
".",
"Values",
"are",
"casted",
"to",
"api",
"equivalents",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L19-L30
|
17,947
|
luqasz/librouteros
|
librouteros/login.py
|
login_token
|
def login_token(api, username, password):
"""Login using pre routeros 6.43 authorization method."""
sentence = api('/login')
token = tuple(sentence)[0]['ret']
encoded = encode_password(token, password)
tuple(api('/login', **{'name': username, 'response': encoded}))
|
python
|
def login_token(api, username, password):
"""Login using pre routeros 6.43 authorization method."""
sentence = api('/login')
token = tuple(sentence)[0]['ret']
encoded = encode_password(token, password)
tuple(api('/login', **{'name': username, 'response': encoded}))
|
[
"def",
"login_token",
"(",
"api",
",",
"username",
",",
"password",
")",
":",
"sentence",
"=",
"api",
"(",
"'/login'",
")",
"token",
"=",
"tuple",
"(",
"sentence",
")",
"[",
"0",
"]",
"[",
"'ret'",
"]",
"encoded",
"=",
"encode_password",
"(",
"token",
",",
"password",
")",
"tuple",
"(",
"api",
"(",
"'/login'",
",",
"*",
"*",
"{",
"'name'",
":",
"username",
",",
"'response'",
":",
"encoded",
"}",
")",
")"
] |
Login using pre routeros 6.43 authorization method.
|
[
"Login",
"using",
"pre",
"routeros",
"6",
".",
"43",
"authorization",
"method",
"."
] |
59293eb49c07a339af87b0416e4619e78ca5176d
|
https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/login.py#L15-L20
|
17,948
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.check_relations
|
def check_relations(self, relations):
"""Recursive function which checks if a relation is valid."""
for rel in relations:
if not rel:
continue
fields = rel.split('.', 1)
local_field = fields[0]
if local_field not in self.fields:
raise ValueError('Unknown field "{}"'.format(local_field))
field = self.fields[local_field]
if not isinstance(field, BaseRelationship):
raise ValueError('Can only include relationships. "{}" is a "{}"'
.format(field.name, field.__class__.__name__))
field.include_data = True
if len(fields) > 1:
field.schema.check_relations(fields[1:])
|
python
|
def check_relations(self, relations):
"""Recursive function which checks if a relation is valid."""
for rel in relations:
if not rel:
continue
fields = rel.split('.', 1)
local_field = fields[0]
if local_field not in self.fields:
raise ValueError('Unknown field "{}"'.format(local_field))
field = self.fields[local_field]
if not isinstance(field, BaseRelationship):
raise ValueError('Can only include relationships. "{}" is a "{}"'
.format(field.name, field.__class__.__name__))
field.include_data = True
if len(fields) > 1:
field.schema.check_relations(fields[1:])
|
[
"def",
"check_relations",
"(",
"self",
",",
"relations",
")",
":",
"for",
"rel",
"in",
"relations",
":",
"if",
"not",
"rel",
":",
"continue",
"fields",
"=",
"rel",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"local_field",
"=",
"fields",
"[",
"0",
"]",
"if",
"local_field",
"not",
"in",
"self",
".",
"fields",
":",
"raise",
"ValueError",
"(",
"'Unknown field \"{}\"'",
".",
"format",
"(",
"local_field",
")",
")",
"field",
"=",
"self",
".",
"fields",
"[",
"local_field",
"]",
"if",
"not",
"isinstance",
"(",
"field",
",",
"BaseRelationship",
")",
":",
"raise",
"ValueError",
"(",
"'Can only include relationships. \"{}\" is a \"{}\"'",
".",
"format",
"(",
"field",
".",
"name",
",",
"field",
".",
"__class__",
".",
"__name__",
")",
")",
"field",
".",
"include_data",
"=",
"True",
"if",
"len",
"(",
"fields",
")",
">",
"1",
":",
"field",
".",
"schema",
".",
"check_relations",
"(",
"fields",
"[",
"1",
":",
"]",
")"
] |
Recursive function which checks if a relation is valid.
|
[
"Recursive",
"function",
"which",
"checks",
"if",
"a",
"relation",
"is",
"valid",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L102-L120
|
17,949
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.format_json_api_response
|
def format_json_api_response(self, data, many):
"""Post-dump hook that formats serialized data as a top-level JSON API object.
See: http://jsonapi.org/format/#document-top-level
"""
ret = self.format_items(data, many)
ret = self.wrap_response(ret, many)
ret = self.render_included_data(ret)
ret = self.render_meta_document(ret)
return ret
|
python
|
def format_json_api_response(self, data, many):
"""Post-dump hook that formats serialized data as a top-level JSON API object.
See: http://jsonapi.org/format/#document-top-level
"""
ret = self.format_items(data, many)
ret = self.wrap_response(ret, many)
ret = self.render_included_data(ret)
ret = self.render_meta_document(ret)
return ret
|
[
"def",
"format_json_api_response",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"ret",
"=",
"self",
".",
"format_items",
"(",
"data",
",",
"many",
")",
"ret",
"=",
"self",
".",
"wrap_response",
"(",
"ret",
",",
"many",
")",
"ret",
"=",
"self",
".",
"render_included_data",
"(",
"ret",
")",
"ret",
"=",
"self",
".",
"render_meta_document",
"(",
"ret",
")",
"return",
"ret"
] |
Post-dump hook that formats serialized data as a top-level JSON API object.
See: http://jsonapi.org/format/#document-top-level
|
[
"Post",
"-",
"dump",
"hook",
"that",
"formats",
"serialized",
"data",
"as",
"a",
"top",
"-",
"level",
"JSON",
"API",
"object",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L123-L132
|
17,950
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema._do_load
|
def _do_load(self, data, many=None, **kwargs):
"""Override `marshmallow.Schema._do_load` for custom JSON API handling.
Specifically, we do this to format errors as JSON API Error objects,
and to support loading of included data.
"""
many = self.many if many is None else bool(many)
# Store this on the instance so we have access to the included data
# when processing relationships (``included`` is outside of the
# ``data``).
self.included_data = data.get('included', {})
self.document_meta = data.get('meta', {})
try:
result = super(Schema, self)._do_load(data, many, **kwargs)
except ValidationError as err: # strict mode
error_messages = err.messages
if '_schema' in error_messages:
error_messages = error_messages['_schema']
formatted_messages = self.format_errors(error_messages, many=many)
err.messages = formatted_messages
raise err
else:
# On marshmallow 2, _do_load returns a tuple (load_data, errors)
if _MARSHMALLOW_VERSION_INFO[0] < 3:
data, error_messages = result
if '_schema' in error_messages:
error_messages = error_messages['_schema']
formatted_messages = self.format_errors(error_messages, many=many)
return data, formatted_messages
return result
|
python
|
def _do_load(self, data, many=None, **kwargs):
"""Override `marshmallow.Schema._do_load` for custom JSON API handling.
Specifically, we do this to format errors as JSON API Error objects,
and to support loading of included data.
"""
many = self.many if many is None else bool(many)
# Store this on the instance so we have access to the included data
# when processing relationships (``included`` is outside of the
# ``data``).
self.included_data = data.get('included', {})
self.document_meta = data.get('meta', {})
try:
result = super(Schema, self)._do_load(data, many, **kwargs)
except ValidationError as err: # strict mode
error_messages = err.messages
if '_schema' in error_messages:
error_messages = error_messages['_schema']
formatted_messages = self.format_errors(error_messages, many=many)
err.messages = formatted_messages
raise err
else:
# On marshmallow 2, _do_load returns a tuple (load_data, errors)
if _MARSHMALLOW_VERSION_INFO[0] < 3:
data, error_messages = result
if '_schema' in error_messages:
error_messages = error_messages['_schema']
formatted_messages = self.format_errors(error_messages, many=many)
return data, formatted_messages
return result
|
[
"def",
"_do_load",
"(",
"self",
",",
"data",
",",
"many",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"many",
"=",
"self",
".",
"many",
"if",
"many",
"is",
"None",
"else",
"bool",
"(",
"many",
")",
"# Store this on the instance so we have access to the included data",
"# when processing relationships (``included`` is outside of the",
"# ``data``).",
"self",
".",
"included_data",
"=",
"data",
".",
"get",
"(",
"'included'",
",",
"{",
"}",
")",
"self",
".",
"document_meta",
"=",
"data",
".",
"get",
"(",
"'meta'",
",",
"{",
"}",
")",
"try",
":",
"result",
"=",
"super",
"(",
"Schema",
",",
"self",
")",
".",
"_do_load",
"(",
"data",
",",
"many",
",",
"*",
"*",
"kwargs",
")",
"except",
"ValidationError",
"as",
"err",
":",
"# strict mode",
"error_messages",
"=",
"err",
".",
"messages",
"if",
"'_schema'",
"in",
"error_messages",
":",
"error_messages",
"=",
"error_messages",
"[",
"'_schema'",
"]",
"formatted_messages",
"=",
"self",
".",
"format_errors",
"(",
"error_messages",
",",
"many",
"=",
"many",
")",
"err",
".",
"messages",
"=",
"formatted_messages",
"raise",
"err",
"else",
":",
"# On marshmallow 2, _do_load returns a tuple (load_data, errors)",
"if",
"_MARSHMALLOW_VERSION_INFO",
"[",
"0",
"]",
"<",
"3",
":",
"data",
",",
"error_messages",
"=",
"result",
"if",
"'_schema'",
"in",
"error_messages",
":",
"error_messages",
"=",
"error_messages",
"[",
"'_schema'",
"]",
"formatted_messages",
"=",
"self",
".",
"format_errors",
"(",
"error_messages",
",",
"many",
"=",
"many",
")",
"return",
"data",
",",
"formatted_messages",
"return",
"result"
] |
Override `marshmallow.Schema._do_load` for custom JSON API handling.
Specifically, we do this to format errors as JSON API Error objects,
and to support loading of included data.
|
[
"Override",
"marshmallow",
".",
"Schema",
".",
"_do_load",
"for",
"custom",
"JSON",
"API",
"handling",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L229-L260
|
17,951
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema._extract_from_included
|
def _extract_from_included(self, data):
"""Extract included data matching the items in ``data``.
For each item in ``data``, extract the full data from the included
data.
"""
return (item for item in self.included_data
if item['type'] == data['type'] and
str(item['id']) == str(data['id']))
|
python
|
def _extract_from_included(self, data):
"""Extract included data matching the items in ``data``.
For each item in ``data``, extract the full data from the included
data.
"""
return (item for item in self.included_data
if item['type'] == data['type'] and
str(item['id']) == str(data['id']))
|
[
"def",
"_extract_from_included",
"(",
"self",
",",
"data",
")",
":",
"return",
"(",
"item",
"for",
"item",
"in",
"self",
".",
"included_data",
"if",
"item",
"[",
"'type'",
"]",
"==",
"data",
"[",
"'type'",
"]",
"and",
"str",
"(",
"item",
"[",
"'id'",
"]",
")",
"==",
"str",
"(",
"data",
"[",
"'id'",
"]",
")",
")"
] |
Extract included data matching the items in ``data``.
For each item in ``data``, extract the full data from the included
data.
|
[
"Extract",
"included",
"data",
"matching",
"the",
"items",
"in",
"data",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L262-L270
|
17,952
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.inflect
|
def inflect(self, text):
"""Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise
do nothing.
"""
return self.opts.inflect(text) if self.opts.inflect else text
|
python
|
def inflect(self, text):
"""Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise
do nothing.
"""
return self.opts.inflect(text) if self.opts.inflect else text
|
[
"def",
"inflect",
"(",
"self",
",",
"text",
")",
":",
"return",
"self",
".",
"opts",
".",
"inflect",
"(",
"text",
")",
"if",
"self",
".",
"opts",
".",
"inflect",
"else",
"text"
] |
Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise
do nothing.
|
[
"Inflect",
"text",
"if",
"the",
"inflect",
"class",
"Meta",
"option",
"is",
"defined",
"otherwise",
"do",
"nothing",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L272-L276
|
17,953
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.format_errors
|
def format_errors(self, errors, many):
"""Format validation errors as JSON Error objects."""
if not errors:
return {}
if isinstance(errors, (list, tuple)):
return {'errors': errors}
formatted_errors = []
if many:
for index, errors in iteritems(errors):
for field_name, field_errors in iteritems(errors):
formatted_errors.extend([
self.format_error(field_name, message, index=index)
for message in field_errors
])
else:
for field_name, field_errors in iteritems(errors):
formatted_errors.extend([
self.format_error(field_name, message)
for message in field_errors
])
return {'errors': formatted_errors}
|
python
|
def format_errors(self, errors, many):
"""Format validation errors as JSON Error objects."""
if not errors:
return {}
if isinstance(errors, (list, tuple)):
return {'errors': errors}
formatted_errors = []
if many:
for index, errors in iteritems(errors):
for field_name, field_errors in iteritems(errors):
formatted_errors.extend([
self.format_error(field_name, message, index=index)
for message in field_errors
])
else:
for field_name, field_errors in iteritems(errors):
formatted_errors.extend([
self.format_error(field_name, message)
for message in field_errors
])
return {'errors': formatted_errors}
|
[
"def",
"format_errors",
"(",
"self",
",",
"errors",
",",
"many",
")",
":",
"if",
"not",
"errors",
":",
"return",
"{",
"}",
"if",
"isinstance",
"(",
"errors",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"{",
"'errors'",
":",
"errors",
"}",
"formatted_errors",
"=",
"[",
"]",
"if",
"many",
":",
"for",
"index",
",",
"errors",
"in",
"iteritems",
"(",
"errors",
")",
":",
"for",
"field_name",
",",
"field_errors",
"in",
"iteritems",
"(",
"errors",
")",
":",
"formatted_errors",
".",
"extend",
"(",
"[",
"self",
".",
"format_error",
"(",
"field_name",
",",
"message",
",",
"index",
"=",
"index",
")",
"for",
"message",
"in",
"field_errors",
"]",
")",
"else",
":",
"for",
"field_name",
",",
"field_errors",
"in",
"iteritems",
"(",
"errors",
")",
":",
"formatted_errors",
".",
"extend",
"(",
"[",
"self",
".",
"format_error",
"(",
"field_name",
",",
"message",
")",
"for",
"message",
"in",
"field_errors",
"]",
")",
"return",
"{",
"'errors'",
":",
"formatted_errors",
"}"
] |
Format validation errors as JSON Error objects.
|
[
"Format",
"validation",
"errors",
"as",
"JSON",
"Error",
"objects",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L280-L301
|
17,954
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.format_error
|
def format_error(self, field_name, message, index=None):
"""Override-able hook to format a single error message as an Error object.
See: http://jsonapi.org/format/#error-objects
"""
pointer = ['/data']
if index is not None:
pointer.append(str(index))
relationship = isinstance(
self.declared_fields.get(field_name), BaseRelationship,
)
if relationship:
pointer.append('relationships')
elif field_name != 'id':
# JSONAPI identifier is a special field that exists above the attribute object.
pointer.append('attributes')
pointer.append(self.inflect(field_name))
if relationship:
pointer.append('data')
return {
'detail': message,
'source': {
'pointer': '/'.join(pointer),
},
}
|
python
|
def format_error(self, field_name, message, index=None):
"""Override-able hook to format a single error message as an Error object.
See: http://jsonapi.org/format/#error-objects
"""
pointer = ['/data']
if index is not None:
pointer.append(str(index))
relationship = isinstance(
self.declared_fields.get(field_name), BaseRelationship,
)
if relationship:
pointer.append('relationships')
elif field_name != 'id':
# JSONAPI identifier is a special field that exists above the attribute object.
pointer.append('attributes')
pointer.append(self.inflect(field_name))
if relationship:
pointer.append('data')
return {
'detail': message,
'source': {
'pointer': '/'.join(pointer),
},
}
|
[
"def",
"format_error",
"(",
"self",
",",
"field_name",
",",
"message",
",",
"index",
"=",
"None",
")",
":",
"pointer",
"=",
"[",
"'/data'",
"]",
"if",
"index",
"is",
"not",
"None",
":",
"pointer",
".",
"append",
"(",
"str",
"(",
"index",
")",
")",
"relationship",
"=",
"isinstance",
"(",
"self",
".",
"declared_fields",
".",
"get",
"(",
"field_name",
")",
",",
"BaseRelationship",
",",
")",
"if",
"relationship",
":",
"pointer",
".",
"append",
"(",
"'relationships'",
")",
"elif",
"field_name",
"!=",
"'id'",
":",
"# JSONAPI identifier is a special field that exists above the attribute object.",
"pointer",
".",
"append",
"(",
"'attributes'",
")",
"pointer",
".",
"append",
"(",
"self",
".",
"inflect",
"(",
"field_name",
")",
")",
"if",
"relationship",
":",
"pointer",
".",
"append",
"(",
"'data'",
")",
"return",
"{",
"'detail'",
":",
"message",
",",
"'source'",
":",
"{",
"'pointer'",
":",
"'/'",
".",
"join",
"(",
"pointer",
")",
",",
"}",
",",
"}"
] |
Override-able hook to format a single error message as an Error object.
See: http://jsonapi.org/format/#error-objects
|
[
"Override",
"-",
"able",
"hook",
"to",
"format",
"a",
"single",
"error",
"message",
"as",
"an",
"Error",
"object",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L303-L332
|
17,955
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.format_item
|
def format_item(self, item):
"""Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects
"""
# http://jsonapi.org/format/#document-top-level
# Primary data MUST be either... a single resource object, a single resource
# identifier object, or null, for requests that target single resources
if not item:
return None
ret = self.dict_class()
ret[TYPE] = self.opts.type_
# Get the schema attributes so we can confirm `dump-to` values exist
attributes = {
(get_dump_key(self.fields[field]) or field): field
for field in self.fields
}
for field_name, value in iteritems(item):
attribute = attributes[field_name]
if attribute == ID:
ret[ID] = value
elif isinstance(self.fields[attribute], DocumentMeta):
if not self.document_meta:
self.document_meta = self.dict_class()
self.document_meta.update(value)
elif isinstance(self.fields[attribute], ResourceMeta):
if 'meta' not in ret:
ret['meta'] = self.dict_class()
ret['meta'].update(value)
elif isinstance(self.fields[attribute], BaseRelationship):
if value:
if 'relationships' not in ret:
ret['relationships'] = self.dict_class()
ret['relationships'][self.inflect(field_name)] = value
else:
if 'attributes' not in ret:
ret['attributes'] = self.dict_class()
ret['attributes'][self.inflect(field_name)] = value
links = self.get_resource_links(item)
if links:
ret['links'] = links
return ret
|
python
|
def format_item(self, item):
"""Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects
"""
# http://jsonapi.org/format/#document-top-level
# Primary data MUST be either... a single resource object, a single resource
# identifier object, or null, for requests that target single resources
if not item:
return None
ret = self.dict_class()
ret[TYPE] = self.opts.type_
# Get the schema attributes so we can confirm `dump-to` values exist
attributes = {
(get_dump_key(self.fields[field]) or field): field
for field in self.fields
}
for field_name, value in iteritems(item):
attribute = attributes[field_name]
if attribute == ID:
ret[ID] = value
elif isinstance(self.fields[attribute], DocumentMeta):
if not self.document_meta:
self.document_meta = self.dict_class()
self.document_meta.update(value)
elif isinstance(self.fields[attribute], ResourceMeta):
if 'meta' not in ret:
ret['meta'] = self.dict_class()
ret['meta'].update(value)
elif isinstance(self.fields[attribute], BaseRelationship):
if value:
if 'relationships' not in ret:
ret['relationships'] = self.dict_class()
ret['relationships'][self.inflect(field_name)] = value
else:
if 'attributes' not in ret:
ret['attributes'] = self.dict_class()
ret['attributes'][self.inflect(field_name)] = value
links = self.get_resource_links(item)
if links:
ret['links'] = links
return ret
|
[
"def",
"format_item",
"(",
"self",
",",
"item",
")",
":",
"# http://jsonapi.org/format/#document-top-level",
"# Primary data MUST be either... a single resource object, a single resource",
"# identifier object, or null, for requests that target single resources",
"if",
"not",
"item",
":",
"return",
"None",
"ret",
"=",
"self",
".",
"dict_class",
"(",
")",
"ret",
"[",
"TYPE",
"]",
"=",
"self",
".",
"opts",
".",
"type_",
"# Get the schema attributes so we can confirm `dump-to` values exist",
"attributes",
"=",
"{",
"(",
"get_dump_key",
"(",
"self",
".",
"fields",
"[",
"field",
"]",
")",
"or",
"field",
")",
":",
"field",
"for",
"field",
"in",
"self",
".",
"fields",
"}",
"for",
"field_name",
",",
"value",
"in",
"iteritems",
"(",
"item",
")",
":",
"attribute",
"=",
"attributes",
"[",
"field_name",
"]",
"if",
"attribute",
"==",
"ID",
":",
"ret",
"[",
"ID",
"]",
"=",
"value",
"elif",
"isinstance",
"(",
"self",
".",
"fields",
"[",
"attribute",
"]",
",",
"DocumentMeta",
")",
":",
"if",
"not",
"self",
".",
"document_meta",
":",
"self",
".",
"document_meta",
"=",
"self",
".",
"dict_class",
"(",
")",
"self",
".",
"document_meta",
".",
"update",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"self",
".",
"fields",
"[",
"attribute",
"]",
",",
"ResourceMeta",
")",
":",
"if",
"'meta'",
"not",
"in",
"ret",
":",
"ret",
"[",
"'meta'",
"]",
"=",
"self",
".",
"dict_class",
"(",
")",
"ret",
"[",
"'meta'",
"]",
".",
"update",
"(",
"value",
")",
"elif",
"isinstance",
"(",
"self",
".",
"fields",
"[",
"attribute",
"]",
",",
"BaseRelationship",
")",
":",
"if",
"value",
":",
"if",
"'relationships'",
"not",
"in",
"ret",
":",
"ret",
"[",
"'relationships'",
"]",
"=",
"self",
".",
"dict_class",
"(",
")",
"ret",
"[",
"'relationships'",
"]",
"[",
"self",
".",
"inflect",
"(",
"field_name",
")",
"]",
"=",
"value",
"else",
":",
"if",
"'attributes'",
"not",
"in",
"ret",
":",
"ret",
"[",
"'attributes'",
"]",
"=",
"self",
".",
"dict_class",
"(",
")",
"ret",
"[",
"'attributes'",
"]",
"[",
"self",
".",
"inflect",
"(",
"field_name",
")",
"]",
"=",
"value",
"links",
"=",
"self",
".",
"get_resource_links",
"(",
"item",
")",
"if",
"links",
":",
"ret",
"[",
"'links'",
"]",
"=",
"links",
"return",
"ret"
] |
Format a single datum as a Resource object.
See: http://jsonapi.org/format/#document-resource-objects
|
[
"Format",
"a",
"single",
"datum",
"as",
"a",
"Resource",
"object",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L334-L379
|
17,956
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.format_items
|
def format_items(self, data, many):
"""Format data as a Resource object or list of Resource objects.
See: http://jsonapi.org/format/#document-resource-objects
"""
if many:
return [self.format_item(item) for item in data]
else:
return self.format_item(data)
|
python
|
def format_items(self, data, many):
"""Format data as a Resource object or list of Resource objects.
See: http://jsonapi.org/format/#document-resource-objects
"""
if many:
return [self.format_item(item) for item in data]
else:
return self.format_item(data)
|
[
"def",
"format_items",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"if",
"many",
":",
"return",
"[",
"self",
".",
"format_item",
"(",
"item",
")",
"for",
"item",
"in",
"data",
"]",
"else",
":",
"return",
"self",
".",
"format_item",
"(",
"data",
")"
] |
Format data as a Resource object or list of Resource objects.
See: http://jsonapi.org/format/#document-resource-objects
|
[
"Format",
"data",
"as",
"a",
"Resource",
"object",
"or",
"list",
"of",
"Resource",
"objects",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L381-L389
|
17,957
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.get_top_level_links
|
def get_top_level_links(self, data, many):
"""Hook for adding links to the root of the response data."""
self_link = None
if many:
if self.opts.self_url_many:
self_link = self.generate_url(self.opts.self_url_many)
else:
if self.opts.self_url:
self_link = data.get('links', {}).get('self', None)
return {'self': self_link}
|
python
|
def get_top_level_links(self, data, many):
"""Hook for adding links to the root of the response data."""
self_link = None
if many:
if self.opts.self_url_many:
self_link = self.generate_url(self.opts.self_url_many)
else:
if self.opts.self_url:
self_link = data.get('links', {}).get('self', None)
return {'self': self_link}
|
[
"def",
"get_top_level_links",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"self_link",
"=",
"None",
"if",
"many",
":",
"if",
"self",
".",
"opts",
".",
"self_url_many",
":",
"self_link",
"=",
"self",
".",
"generate_url",
"(",
"self",
".",
"opts",
".",
"self_url_many",
")",
"else",
":",
"if",
"self",
".",
"opts",
".",
"self_url",
":",
"self_link",
"=",
"data",
".",
"get",
"(",
"'links'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'self'",
",",
"None",
")",
"return",
"{",
"'self'",
":",
"self_link",
"}"
] |
Hook for adding links to the root of the response data.
|
[
"Hook",
"for",
"adding",
"links",
"to",
"the",
"root",
"of",
"the",
"response",
"data",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L391-L402
|
17,958
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.get_resource_links
|
def get_resource_links(self, item):
"""Hook for adding links to a resource object."""
if self.opts.self_url:
ret = self.dict_class()
kwargs = resolve_params(item, self.opts.self_url_kwargs or {})
ret['self'] = self.generate_url(self.opts.self_url, **kwargs)
return ret
return None
|
python
|
def get_resource_links(self, item):
"""Hook for adding links to a resource object."""
if self.opts.self_url:
ret = self.dict_class()
kwargs = resolve_params(item, self.opts.self_url_kwargs or {})
ret['self'] = self.generate_url(self.opts.self_url, **kwargs)
return ret
return None
|
[
"def",
"get_resource_links",
"(",
"self",
",",
"item",
")",
":",
"if",
"self",
".",
"opts",
".",
"self_url",
":",
"ret",
"=",
"self",
".",
"dict_class",
"(",
")",
"kwargs",
"=",
"resolve_params",
"(",
"item",
",",
"self",
".",
"opts",
".",
"self_url_kwargs",
"or",
"{",
"}",
")",
"ret",
"[",
"'self'",
"]",
"=",
"self",
".",
"generate_url",
"(",
"self",
".",
"opts",
".",
"self_url",
",",
"*",
"*",
"kwargs",
")",
"return",
"ret",
"return",
"None"
] |
Hook for adding links to a resource object.
|
[
"Hook",
"for",
"adding",
"links",
"to",
"a",
"resource",
"object",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L404-L411
|
17,959
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/schema.py
|
Schema.wrap_response
|
def wrap_response(self, data, many):
"""Wrap data and links according to the JSON API """
ret = {'data': data}
# self_url_many is still valid when there isn't any data, but self_url
# may only be included if there is data in the ret
if many or data:
top_level_links = self.get_top_level_links(data, many)
if top_level_links['self']:
ret['links'] = top_level_links
return ret
|
python
|
def wrap_response(self, data, many):
"""Wrap data and links according to the JSON API """
ret = {'data': data}
# self_url_many is still valid when there isn't any data, but self_url
# may only be included if there is data in the ret
if many or data:
top_level_links = self.get_top_level_links(data, many)
if top_level_links['self']:
ret['links'] = top_level_links
return ret
|
[
"def",
"wrap_response",
"(",
"self",
",",
"data",
",",
"many",
")",
":",
"ret",
"=",
"{",
"'data'",
":",
"data",
"}",
"# self_url_many is still valid when there isn't any data, but self_url",
"# may only be included if there is data in the ret",
"if",
"many",
"or",
"data",
":",
"top_level_links",
"=",
"self",
".",
"get_top_level_links",
"(",
"data",
",",
"many",
")",
"if",
"top_level_links",
"[",
"'self'",
"]",
":",
"ret",
"[",
"'links'",
"]",
"=",
"top_level_links",
"return",
"ret"
] |
Wrap data and links according to the JSON API
|
[
"Wrap",
"data",
"and",
"links",
"according",
"to",
"the",
"JSON",
"API"
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L413-L422
|
17,960
|
marshmallow-code/marshmallow-jsonapi
|
marshmallow_jsonapi/fields.py
|
Relationship.extract_value
|
def extract_value(self, data):
"""Extract the id key and validate the request structure."""
errors = []
if 'id' not in data:
errors.append('Must have an `id` field')
if 'type' not in data:
errors.append('Must have a `type` field')
elif data['type'] != self.type_:
errors.append('Invalid `type` specified')
if errors:
raise ValidationError(errors)
# If ``attributes`` is set, we've folded included data into this
# relationship. Unserialize it if we have a schema set; otherwise we
# fall back below to old behaviour of only IDs.
if 'attributes' in data and self.__schema:
result = self.schema.load({'data': data, 'included': self.root.included_data})
return result.data if _MARSHMALLOW_VERSION_INFO[0] < 3 else result
id_value = data.get('id')
if self.__schema:
id_value = self.schema.fields['id'].deserialize(id_value)
return id_value
|
python
|
def extract_value(self, data):
"""Extract the id key and validate the request structure."""
errors = []
if 'id' not in data:
errors.append('Must have an `id` field')
if 'type' not in data:
errors.append('Must have a `type` field')
elif data['type'] != self.type_:
errors.append('Invalid `type` specified')
if errors:
raise ValidationError(errors)
# If ``attributes`` is set, we've folded included data into this
# relationship. Unserialize it if we have a schema set; otherwise we
# fall back below to old behaviour of only IDs.
if 'attributes' in data and self.__schema:
result = self.schema.load({'data': data, 'included': self.root.included_data})
return result.data if _MARSHMALLOW_VERSION_INFO[0] < 3 else result
id_value = data.get('id')
if self.__schema:
id_value = self.schema.fields['id'].deserialize(id_value)
return id_value
|
[
"def",
"extract_value",
"(",
"self",
",",
"data",
")",
":",
"errors",
"=",
"[",
"]",
"if",
"'id'",
"not",
"in",
"data",
":",
"errors",
".",
"append",
"(",
"'Must have an `id` field'",
")",
"if",
"'type'",
"not",
"in",
"data",
":",
"errors",
".",
"append",
"(",
"'Must have a `type` field'",
")",
"elif",
"data",
"[",
"'type'",
"]",
"!=",
"self",
".",
"type_",
":",
"errors",
".",
"append",
"(",
"'Invalid `type` specified'",
")",
"if",
"errors",
":",
"raise",
"ValidationError",
"(",
"errors",
")",
"# If ``attributes`` is set, we've folded included data into this",
"# relationship. Unserialize it if we have a schema set; otherwise we",
"# fall back below to old behaviour of only IDs.",
"if",
"'attributes'",
"in",
"data",
"and",
"self",
".",
"__schema",
":",
"result",
"=",
"self",
".",
"schema",
".",
"load",
"(",
"{",
"'data'",
":",
"data",
",",
"'included'",
":",
"self",
".",
"root",
".",
"included_data",
"}",
")",
"return",
"result",
".",
"data",
"if",
"_MARSHMALLOW_VERSION_INFO",
"[",
"0",
"]",
"<",
"3",
"else",
"result",
"id_value",
"=",
"data",
".",
"get",
"(",
"'id'",
")",
"if",
"self",
".",
"__schema",
":",
"id_value",
"=",
"self",
".",
"schema",
".",
"fields",
"[",
"'id'",
"]",
".",
"deserialize",
"(",
"id_value",
")",
"return",
"id_value"
] |
Extract the id key and validate the request structure.
|
[
"Extract",
"the",
"id",
"key",
"and",
"validate",
"the",
"request",
"structure",
"."
] |
7183c9bb5cdeace4143e6678bab48d433ac439a1
|
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/fields.py#L183-L208
|
17,961
|
thoth-station/python
|
thoth/python/helpers.py
|
fill_package_digests
|
def fill_package_digests(generated_project: Project) -> Project:
"""Temporary fill package digests stated in Pipfile.lock."""
for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages):
if package_version.hashes:
# Already filled from the last run.
continue
if package_version.index:
scanned_hashes = package_version.index.get_package_hashes(
package_version.name, package_version.locked_version
)
else:
for source in generated_project.pipfile.meta.sources.values():
try:
scanned_hashes = source.get_package_hashes(package_version.name, package_version.locked_version)
break
except Exception:
continue
else:
raise ValueError("Unable to find package hashes")
for entry in scanned_hashes:
package_version.hashes.append("sha256:" + entry["sha256"])
return generated_project
|
python
|
def fill_package_digests(generated_project: Project) -> Project:
"""Temporary fill package digests stated in Pipfile.lock."""
for package_version in chain(generated_project.pipfile_lock.packages, generated_project.pipfile_lock.dev_packages):
if package_version.hashes:
# Already filled from the last run.
continue
if package_version.index:
scanned_hashes = package_version.index.get_package_hashes(
package_version.name, package_version.locked_version
)
else:
for source in generated_project.pipfile.meta.sources.values():
try:
scanned_hashes = source.get_package_hashes(package_version.name, package_version.locked_version)
break
except Exception:
continue
else:
raise ValueError("Unable to find package hashes")
for entry in scanned_hashes:
package_version.hashes.append("sha256:" + entry["sha256"])
return generated_project
|
[
"def",
"fill_package_digests",
"(",
"generated_project",
":",
"Project",
")",
"->",
"Project",
":",
"for",
"package_version",
"in",
"chain",
"(",
"generated_project",
".",
"pipfile_lock",
".",
"packages",
",",
"generated_project",
".",
"pipfile_lock",
".",
"dev_packages",
")",
":",
"if",
"package_version",
".",
"hashes",
":",
"# Already filled from the last run.",
"continue",
"if",
"package_version",
".",
"index",
":",
"scanned_hashes",
"=",
"package_version",
".",
"index",
".",
"get_package_hashes",
"(",
"package_version",
".",
"name",
",",
"package_version",
".",
"locked_version",
")",
"else",
":",
"for",
"source",
"in",
"generated_project",
".",
"pipfile",
".",
"meta",
".",
"sources",
".",
"values",
"(",
")",
":",
"try",
":",
"scanned_hashes",
"=",
"source",
".",
"get_package_hashes",
"(",
"package_version",
".",
"name",
",",
"package_version",
".",
"locked_version",
")",
"break",
"except",
"Exception",
":",
"continue",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unable to find package hashes\"",
")",
"for",
"entry",
"in",
"scanned_hashes",
":",
"package_version",
".",
"hashes",
".",
"append",
"(",
"\"sha256:\"",
"+",
"entry",
"[",
"\"sha256\"",
"]",
")",
"return",
"generated_project"
] |
Temporary fill package digests stated in Pipfile.lock.
|
[
"Temporary",
"fill",
"package",
"digests",
"stated",
"in",
"Pipfile",
".",
"lock",
"."
] |
bd2a4a4f552faf54834ce9febea4e2834a1d0bab
|
https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/helpers.py#L26-L50
|
17,962
|
thoth-station/python
|
thoth/python/digests_fetcher.py
|
PythonDigestsFetcher.fetch_digests
|
def fetch_digests(self, package_name: str, package_version: str) -> dict:
"""Fetch digests for the given package in specified version from the given package index."""
report = {}
for source in self._sources:
try:
report[source.url] = source.get_package_hashes(package_name, package_version)
except NotFound as exc:
_LOGGER.debug(
f"Package {package_name} in version {package_version} not "
f"found on index {source.name}: {str(exc)}"
)
return report
|
python
|
def fetch_digests(self, package_name: str, package_version: str) -> dict:
"""Fetch digests for the given package in specified version from the given package index."""
report = {}
for source in self._sources:
try:
report[source.url] = source.get_package_hashes(package_name, package_version)
except NotFound as exc:
_LOGGER.debug(
f"Package {package_name} in version {package_version} not "
f"found on index {source.name}: {str(exc)}"
)
return report
|
[
"def",
"fetch_digests",
"(",
"self",
",",
"package_name",
":",
"str",
",",
"package_version",
":",
"str",
")",
"->",
"dict",
":",
"report",
"=",
"{",
"}",
"for",
"source",
"in",
"self",
".",
"_sources",
":",
"try",
":",
"report",
"[",
"source",
".",
"url",
"]",
"=",
"source",
".",
"get_package_hashes",
"(",
"package_name",
",",
"package_version",
")",
"except",
"NotFound",
"as",
"exc",
":",
"_LOGGER",
".",
"debug",
"(",
"f\"Package {package_name} in version {package_version} not \"",
"f\"found on index {source.name}: {str(exc)}\"",
")",
"return",
"report"
] |
Fetch digests for the given package in specified version from the given package index.
|
[
"Fetch",
"digests",
"for",
"the",
"given",
"package",
"in",
"specified",
"version",
"from",
"the",
"given",
"package",
"index",
"."
] |
bd2a4a4f552faf54834ce9febea4e2834a1d0bab
|
https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/digests_fetcher.py#L44-L57
|
17,963
|
blockstack/pybitcoin
|
pybitcoin/passphrases/legacy.py
|
random_passphrase_from_wordlist
|
def random_passphrase_from_wordlist(phrase_length, wordlist):
""" An extremely entropy efficient passphrase generator.
This function:
-Pulls entropy from the safer alternative to /dev/urandom: /dev/random
-Doesn't rely on random.seed (words are selected right from the entropy)
-Only requires 2 entropy bytes/word for word lists of up to 65536 words
"""
passphrase_words = []
numbytes_of_entropy = phrase_length * 2
entropy = list(dev_random_entropy(numbytes_of_entropy, fallback_to_urandom=True))
bytes_per_word = int(ceil(log(len(wordlist), 2) / 8))
if (phrase_length * bytes_per_word > 64):
raise Exception("Error! This operation requires too much entropy. \
Try a shorter phrase length or word list.")
for i in range(phrase_length):
current_entropy = entropy[i*bytes_per_word:(i+1)*bytes_per_word]
index = int(''.join(current_entropy).encode('hex'), 16) % len(wordlist)
word = wordlist[index]
passphrase_words.append(word)
return " ".join(passphrase_words)
|
python
|
def random_passphrase_from_wordlist(phrase_length, wordlist):
""" An extremely entropy efficient passphrase generator.
This function:
-Pulls entropy from the safer alternative to /dev/urandom: /dev/random
-Doesn't rely on random.seed (words are selected right from the entropy)
-Only requires 2 entropy bytes/word for word lists of up to 65536 words
"""
passphrase_words = []
numbytes_of_entropy = phrase_length * 2
entropy = list(dev_random_entropy(numbytes_of_entropy, fallback_to_urandom=True))
bytes_per_word = int(ceil(log(len(wordlist), 2) / 8))
if (phrase_length * bytes_per_word > 64):
raise Exception("Error! This operation requires too much entropy. \
Try a shorter phrase length or word list.")
for i in range(phrase_length):
current_entropy = entropy[i*bytes_per_word:(i+1)*bytes_per_word]
index = int(''.join(current_entropy).encode('hex'), 16) % len(wordlist)
word = wordlist[index]
passphrase_words.append(word)
return " ".join(passphrase_words)
|
[
"def",
"random_passphrase_from_wordlist",
"(",
"phrase_length",
",",
"wordlist",
")",
":",
"passphrase_words",
"=",
"[",
"]",
"numbytes_of_entropy",
"=",
"phrase_length",
"*",
"2",
"entropy",
"=",
"list",
"(",
"dev_random_entropy",
"(",
"numbytes_of_entropy",
",",
"fallback_to_urandom",
"=",
"True",
")",
")",
"bytes_per_word",
"=",
"int",
"(",
"ceil",
"(",
"log",
"(",
"len",
"(",
"wordlist",
")",
",",
"2",
")",
"/",
"8",
")",
")",
"if",
"(",
"phrase_length",
"*",
"bytes_per_word",
">",
"64",
")",
":",
"raise",
"Exception",
"(",
"\"Error! This operation requires too much entropy. \\\n Try a shorter phrase length or word list.\"",
")",
"for",
"i",
"in",
"range",
"(",
"phrase_length",
")",
":",
"current_entropy",
"=",
"entropy",
"[",
"i",
"*",
"bytes_per_word",
":",
"(",
"i",
"+",
"1",
")",
"*",
"bytes_per_word",
"]",
"index",
"=",
"int",
"(",
"''",
".",
"join",
"(",
"current_entropy",
")",
".",
"encode",
"(",
"'hex'",
")",
",",
"16",
")",
"%",
"len",
"(",
"wordlist",
")",
"word",
"=",
"wordlist",
"[",
"index",
"]",
"passphrase_words",
".",
"append",
"(",
"word",
")",
"return",
"\" \"",
".",
"join",
"(",
"passphrase_words",
")"
] |
An extremely entropy efficient passphrase generator.
This function:
-Pulls entropy from the safer alternative to /dev/urandom: /dev/random
-Doesn't rely on random.seed (words are selected right from the entropy)
-Only requires 2 entropy bytes/word for word lists of up to 65536 words
|
[
"An",
"extremely",
"entropy",
"efficient",
"passphrase",
"generator",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/legacy.py#L15-L41
|
17,964
|
blockstack/pybitcoin
|
pybitcoin/hash.py
|
reverse_hash
|
def reverse_hash(hash, hex_format=True):
""" hash is in hex or binary format
"""
if not hex_format:
hash = hexlify(hash)
return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)]))
|
python
|
def reverse_hash(hash, hex_format=True):
""" hash is in hex or binary format
"""
if not hex_format:
hash = hexlify(hash)
return "".join(reversed([hash[i:i+2] for i in range(0, len(hash), 2)]))
|
[
"def",
"reverse_hash",
"(",
"hash",
",",
"hex_format",
"=",
"True",
")",
":",
"if",
"not",
"hex_format",
":",
"hash",
"=",
"hexlify",
"(",
"hash",
")",
"return",
"\"\"",
".",
"join",
"(",
"reversed",
"(",
"[",
"hash",
"[",
"i",
":",
"i",
"+",
"2",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"hash",
")",
",",
"2",
")",
"]",
")",
")"
] |
hash is in hex or binary format
|
[
"hash",
"is",
"in",
"hex",
"or",
"binary",
"format"
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/hash.py#L45-L50
|
17,965
|
blockstack/pybitcoin
|
pybitcoin/passphrases/passphrase.py
|
get_num_words_with_entropy
|
def get_num_words_with_entropy(bits_of_entropy, wordlist):
""" Gets the number of words randomly selected from a given wordlist that
would result in the number of bits of entropy specified.
"""
entropy_per_word = math.log(len(wordlist))/math.log(2)
num_words = int(math.ceil(bits_of_entropy/entropy_per_word))
return num_words
|
python
|
def get_num_words_with_entropy(bits_of_entropy, wordlist):
""" Gets the number of words randomly selected from a given wordlist that
would result in the number of bits of entropy specified.
"""
entropy_per_word = math.log(len(wordlist))/math.log(2)
num_words = int(math.ceil(bits_of_entropy/entropy_per_word))
return num_words
|
[
"def",
"get_num_words_with_entropy",
"(",
"bits_of_entropy",
",",
"wordlist",
")",
":",
"entropy_per_word",
"=",
"math",
".",
"log",
"(",
"len",
"(",
"wordlist",
")",
")",
"/",
"math",
".",
"log",
"(",
"2",
")",
"num_words",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"bits_of_entropy",
"/",
"entropy_per_word",
")",
")",
"return",
"num_words"
] |
Gets the number of words randomly selected from a given wordlist that
would result in the number of bits of entropy specified.
|
[
"Gets",
"the",
"number",
"of",
"words",
"randomly",
"selected",
"from",
"a",
"given",
"wordlist",
"that",
"would",
"result",
"in",
"the",
"number",
"of",
"bits",
"of",
"entropy",
"specified",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L29-L35
|
17,966
|
blockstack/pybitcoin
|
pybitcoin/passphrases/passphrase.py
|
create_passphrase
|
def create_passphrase(bits_of_entropy=None, num_words=None,
language='english', word_source='wiktionary'):
""" Creates a passphrase that has a certain number of bits of entropy OR
a certain number of words.
"""
wordlist = get_wordlist(language, word_source)
if not num_words:
if not bits_of_entropy:
bits_of_entropy = 80
num_words = get_num_words_with_entropy(bits_of_entropy, wordlist)
return ' '.join(pick_random_words_from_wordlist(wordlist, num_words))
|
python
|
def create_passphrase(bits_of_entropy=None, num_words=None,
language='english', word_source='wiktionary'):
""" Creates a passphrase that has a certain number of bits of entropy OR
a certain number of words.
"""
wordlist = get_wordlist(language, word_source)
if not num_words:
if not bits_of_entropy:
bits_of_entropy = 80
num_words = get_num_words_with_entropy(bits_of_entropy, wordlist)
return ' '.join(pick_random_words_from_wordlist(wordlist, num_words))
|
[
"def",
"create_passphrase",
"(",
"bits_of_entropy",
"=",
"None",
",",
"num_words",
"=",
"None",
",",
"language",
"=",
"'english'",
",",
"word_source",
"=",
"'wiktionary'",
")",
":",
"wordlist",
"=",
"get_wordlist",
"(",
"language",
",",
"word_source",
")",
"if",
"not",
"num_words",
":",
"if",
"not",
"bits_of_entropy",
":",
"bits_of_entropy",
"=",
"80",
"num_words",
"=",
"get_num_words_with_entropy",
"(",
"bits_of_entropy",
",",
"wordlist",
")",
"return",
"' '",
".",
"join",
"(",
"pick_random_words_from_wordlist",
"(",
"wordlist",
",",
"num_words",
")",
")"
] |
Creates a passphrase that has a certain number of bits of entropy OR
a certain number of words.
|
[
"Creates",
"a",
"passphrase",
"that",
"has",
"a",
"certain",
"number",
"of",
"bits",
"of",
"entropy",
"OR",
"a",
"certain",
"number",
"of",
"words",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L42-L54
|
17,967
|
blockstack/pybitcoin
|
pybitcoin/transactions/serialize.py
|
serialize_input
|
def serialize_input(input, signature_script_hex=''):
""" Serializes a transaction input.
"""
if not (isinstance(input, dict) and 'transaction_hash' in input \
and 'output_index' in input):
raise Exception('Required parameters: transaction_hash, output_index')
if is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 64:
raise Exception("Transaction hash '%s' must be 32 bytes" % input['transaction_hash'])
elif not is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 32:
raise Exception("Transaction hash '%s' must be 32 bytes" % hexlify(input['transaction_hash']))
if not 'sequence' in input:
input['sequence'] = UINT_MAX
return ''.join([
flip_endian(input['transaction_hash']),
hexlify(struct.pack('<I', input['output_index'])),
hexlify(variable_length_int(len(signature_script_hex)/2)),
signature_script_hex,
hexlify(struct.pack('<I', input['sequence']))
])
|
python
|
def serialize_input(input, signature_script_hex=''):
""" Serializes a transaction input.
"""
if not (isinstance(input, dict) and 'transaction_hash' in input \
and 'output_index' in input):
raise Exception('Required parameters: transaction_hash, output_index')
if is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 64:
raise Exception("Transaction hash '%s' must be 32 bytes" % input['transaction_hash'])
elif not is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 32:
raise Exception("Transaction hash '%s' must be 32 bytes" % hexlify(input['transaction_hash']))
if not 'sequence' in input:
input['sequence'] = UINT_MAX
return ''.join([
flip_endian(input['transaction_hash']),
hexlify(struct.pack('<I', input['output_index'])),
hexlify(variable_length_int(len(signature_script_hex)/2)),
signature_script_hex,
hexlify(struct.pack('<I', input['sequence']))
])
|
[
"def",
"serialize_input",
"(",
"input",
",",
"signature_script_hex",
"=",
"''",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"input",
",",
"dict",
")",
"and",
"'transaction_hash'",
"in",
"input",
"and",
"'output_index'",
"in",
"input",
")",
":",
"raise",
"Exception",
"(",
"'Required parameters: transaction_hash, output_index'",
")",
"if",
"is_hex",
"(",
"str",
"(",
"input",
"[",
"'transaction_hash'",
"]",
")",
")",
"and",
"len",
"(",
"str",
"(",
"input",
"[",
"'transaction_hash'",
"]",
")",
")",
"!=",
"64",
":",
"raise",
"Exception",
"(",
"\"Transaction hash '%s' must be 32 bytes\"",
"%",
"input",
"[",
"'transaction_hash'",
"]",
")",
"elif",
"not",
"is_hex",
"(",
"str",
"(",
"input",
"[",
"'transaction_hash'",
"]",
")",
")",
"and",
"len",
"(",
"str",
"(",
"input",
"[",
"'transaction_hash'",
"]",
")",
")",
"!=",
"32",
":",
"raise",
"Exception",
"(",
"\"Transaction hash '%s' must be 32 bytes\"",
"%",
"hexlify",
"(",
"input",
"[",
"'transaction_hash'",
"]",
")",
")",
"if",
"not",
"'sequence'",
"in",
"input",
":",
"input",
"[",
"'sequence'",
"]",
"=",
"UINT_MAX",
"return",
"''",
".",
"join",
"(",
"[",
"flip_endian",
"(",
"input",
"[",
"'transaction_hash'",
"]",
")",
",",
"hexlify",
"(",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"input",
"[",
"'output_index'",
"]",
")",
")",
",",
"hexlify",
"(",
"variable_length_int",
"(",
"len",
"(",
"signature_script_hex",
")",
"/",
"2",
")",
")",
",",
"signature_script_hex",
",",
"hexlify",
"(",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"input",
"[",
"'sequence'",
"]",
")",
")",
"]",
")"
] |
Serializes a transaction input.
|
[
"Serializes",
"a",
"transaction",
"input",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L20-L42
|
17,968
|
blockstack/pybitcoin
|
pybitcoin/transactions/serialize.py
|
serialize_output
|
def serialize_output(output):
""" Serializes a transaction output.
"""
if not ('value' in output and 'script_hex' in output):
raise Exception('Invalid output')
return ''.join([
hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites
hexlify(variable_length_int(len(output['script_hex'])/2)),
output['script_hex']
])
|
python
|
def serialize_output(output):
""" Serializes a transaction output.
"""
if not ('value' in output and 'script_hex' in output):
raise Exception('Invalid output')
return ''.join([
hexlify(struct.pack('<Q', output['value'])), # pack into 8 bites
hexlify(variable_length_int(len(output['script_hex'])/2)),
output['script_hex']
])
|
[
"def",
"serialize_output",
"(",
"output",
")",
":",
"if",
"not",
"(",
"'value'",
"in",
"output",
"and",
"'script_hex'",
"in",
"output",
")",
":",
"raise",
"Exception",
"(",
"'Invalid output'",
")",
"return",
"''",
".",
"join",
"(",
"[",
"hexlify",
"(",
"struct",
".",
"pack",
"(",
"'<Q'",
",",
"output",
"[",
"'value'",
"]",
")",
")",
",",
"# pack into 8 bites",
"hexlify",
"(",
"variable_length_int",
"(",
"len",
"(",
"output",
"[",
"'script_hex'",
"]",
")",
"/",
"2",
")",
")",
",",
"output",
"[",
"'script_hex'",
"]",
"]",
")"
] |
Serializes a transaction output.
|
[
"Serializes",
"a",
"transaction",
"output",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L45-L55
|
17,969
|
blockstack/pybitcoin
|
pybitcoin/transactions/serialize.py
|
serialize_transaction
|
def serialize_transaction(inputs, outputs, lock_time=0, version=1):
""" Serializes a transaction.
"""
# add in the inputs
serialized_inputs = ''.join([serialize_input(input) for input in inputs])
# add in the outputs
serialized_outputs = ''.join([serialize_output(output) for output in outputs])
return ''.join([
# add in the version number
hexlify(struct.pack('<I', version)),
# add in the number of inputs
hexlify(variable_length_int(len(inputs))),
# add in the inputs
serialized_inputs,
# add in the number of outputs
hexlify(variable_length_int(len(outputs))),
# add in the outputs
serialized_outputs,
# add in the lock time
hexlify(struct.pack('<I', lock_time)),
])
|
python
|
def serialize_transaction(inputs, outputs, lock_time=0, version=1):
""" Serializes a transaction.
"""
# add in the inputs
serialized_inputs = ''.join([serialize_input(input) for input in inputs])
# add in the outputs
serialized_outputs = ''.join([serialize_output(output) for output in outputs])
return ''.join([
# add in the version number
hexlify(struct.pack('<I', version)),
# add in the number of inputs
hexlify(variable_length_int(len(inputs))),
# add in the inputs
serialized_inputs,
# add in the number of outputs
hexlify(variable_length_int(len(outputs))),
# add in the outputs
serialized_outputs,
# add in the lock time
hexlify(struct.pack('<I', lock_time)),
])
|
[
"def",
"serialize_transaction",
"(",
"inputs",
",",
"outputs",
",",
"lock_time",
"=",
"0",
",",
"version",
"=",
"1",
")",
":",
"# add in the inputs",
"serialized_inputs",
"=",
"''",
".",
"join",
"(",
"[",
"serialize_input",
"(",
"input",
")",
"for",
"input",
"in",
"inputs",
"]",
")",
"# add in the outputs",
"serialized_outputs",
"=",
"''",
".",
"join",
"(",
"[",
"serialize_output",
"(",
"output",
")",
"for",
"output",
"in",
"outputs",
"]",
")",
"return",
"''",
".",
"join",
"(",
"[",
"# add in the version number",
"hexlify",
"(",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"version",
")",
")",
",",
"# add in the number of inputs",
"hexlify",
"(",
"variable_length_int",
"(",
"len",
"(",
"inputs",
")",
")",
")",
",",
"# add in the inputs",
"serialized_inputs",
",",
"# add in the number of outputs",
"hexlify",
"(",
"variable_length_int",
"(",
"len",
"(",
"outputs",
")",
")",
")",
",",
"# add in the outputs",
"serialized_outputs",
",",
"# add in the lock time",
"hexlify",
"(",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"lock_time",
")",
")",
",",
"]",
")"
] |
Serializes a transaction.
|
[
"Serializes",
"a",
"transaction",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L58-L81
|
17,970
|
blockstack/pybitcoin
|
pybitcoin/transactions/serialize.py
|
deserialize_transaction
|
def deserialize_transaction(tx_hex):
"""
Given a serialized transaction, return its inputs, outputs,
locktime, and version
Each input will have:
* transaction_hash: string
* output_index: int
* [optional] sequence: int
* [optional] script_sig: string
Each output will have:
* value: int
* script_hex: string
"""
tx = bitcoin.deserialize(str(tx_hex))
inputs = tx["ins"]
outputs = tx["outs"]
ret_inputs = []
ret_outputs = []
for inp in inputs:
ret_inp = {
"transaction_hash": inp["outpoint"]["hash"],
"output_index": int(inp["outpoint"]["index"]),
}
if "sequence" in inp:
ret_inp["sequence"] = int(inp["sequence"])
if "script" in inp:
ret_inp["script_sig"] = inp["script"]
ret_inputs.append(ret_inp)
for out in outputs:
ret_out = {
"value": out["value"],
"script_hex": out["script"]
}
ret_outputs.append(ret_out)
return ret_inputs, ret_outputs, tx["locktime"], tx["version"]
|
python
|
def deserialize_transaction(tx_hex):
"""
Given a serialized transaction, return its inputs, outputs,
locktime, and version
Each input will have:
* transaction_hash: string
* output_index: int
* [optional] sequence: int
* [optional] script_sig: string
Each output will have:
* value: int
* script_hex: string
"""
tx = bitcoin.deserialize(str(tx_hex))
inputs = tx["ins"]
outputs = tx["outs"]
ret_inputs = []
ret_outputs = []
for inp in inputs:
ret_inp = {
"transaction_hash": inp["outpoint"]["hash"],
"output_index": int(inp["outpoint"]["index"]),
}
if "sequence" in inp:
ret_inp["sequence"] = int(inp["sequence"])
if "script" in inp:
ret_inp["script_sig"] = inp["script"]
ret_inputs.append(ret_inp)
for out in outputs:
ret_out = {
"value": out["value"],
"script_hex": out["script"]
}
ret_outputs.append(ret_out)
return ret_inputs, ret_outputs, tx["locktime"], tx["version"]
|
[
"def",
"deserialize_transaction",
"(",
"tx_hex",
")",
":",
"tx",
"=",
"bitcoin",
".",
"deserialize",
"(",
"str",
"(",
"tx_hex",
")",
")",
"inputs",
"=",
"tx",
"[",
"\"ins\"",
"]",
"outputs",
"=",
"tx",
"[",
"\"outs\"",
"]",
"ret_inputs",
"=",
"[",
"]",
"ret_outputs",
"=",
"[",
"]",
"for",
"inp",
"in",
"inputs",
":",
"ret_inp",
"=",
"{",
"\"transaction_hash\"",
":",
"inp",
"[",
"\"outpoint\"",
"]",
"[",
"\"hash\"",
"]",
",",
"\"output_index\"",
":",
"int",
"(",
"inp",
"[",
"\"outpoint\"",
"]",
"[",
"\"index\"",
"]",
")",
",",
"}",
"if",
"\"sequence\"",
"in",
"inp",
":",
"ret_inp",
"[",
"\"sequence\"",
"]",
"=",
"int",
"(",
"inp",
"[",
"\"sequence\"",
"]",
")",
"if",
"\"script\"",
"in",
"inp",
":",
"ret_inp",
"[",
"\"script_sig\"",
"]",
"=",
"inp",
"[",
"\"script\"",
"]",
"ret_inputs",
".",
"append",
"(",
"ret_inp",
")",
"for",
"out",
"in",
"outputs",
":",
"ret_out",
"=",
"{",
"\"value\"",
":",
"out",
"[",
"\"value\"",
"]",
",",
"\"script_hex\"",
":",
"out",
"[",
"\"script\"",
"]",
"}",
"ret_outputs",
".",
"append",
"(",
"ret_out",
")",
"return",
"ret_inputs",
",",
"ret_outputs",
",",
"tx",
"[",
"\"locktime\"",
"]",
",",
"tx",
"[",
"\"version\"",
"]"
] |
Given a serialized transaction, return its inputs, outputs,
locktime, and version
Each input will have:
* transaction_hash: string
* output_index: int
* [optional] sequence: int
* [optional] script_sig: string
Each output will have:
* value: int
* script_hex: string
|
[
"Given",
"a",
"serialized",
"transaction",
"return",
"its",
"inputs",
"outputs",
"locktime",
"and",
"version"
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L84-L130
|
17,971
|
blockstack/pybitcoin
|
pybitcoin/transactions/utils.py
|
variable_length_int
|
def variable_length_int(i):
""" Encodes integers into variable length integers, which are used in
Bitcoin in order to save space.
"""
if not isinstance(i, (int,long)):
raise Exception('i must be an integer')
if i < (2**8-3):
return chr(i) # pack the integer into one byte
elif i < (2**16):
return chr(253) + struct.pack('<H', i) # pack into 2 bytes
elif i < (2**32):
return chr(254) + struct.pack('<I', i) # pack into 4 bytes
elif i < (2**64):
return chr(255) + struct.pack('<Q', i) # pack into 8 bites
else:
raise Exception('Integer cannot exceed 8 bytes in length.')
|
python
|
def variable_length_int(i):
""" Encodes integers into variable length integers, which are used in
Bitcoin in order to save space.
"""
if not isinstance(i, (int,long)):
raise Exception('i must be an integer')
if i < (2**8-3):
return chr(i) # pack the integer into one byte
elif i < (2**16):
return chr(253) + struct.pack('<H', i) # pack into 2 bytes
elif i < (2**32):
return chr(254) + struct.pack('<I', i) # pack into 4 bytes
elif i < (2**64):
return chr(255) + struct.pack('<Q', i) # pack into 8 bites
else:
raise Exception('Integer cannot exceed 8 bytes in length.')
|
[
"def",
"variable_length_int",
"(",
"i",
")",
":",
"if",
"not",
"isinstance",
"(",
"i",
",",
"(",
"int",
",",
"long",
")",
")",
":",
"raise",
"Exception",
"(",
"'i must be an integer'",
")",
"if",
"i",
"<",
"(",
"2",
"**",
"8",
"-",
"3",
")",
":",
"return",
"chr",
"(",
"i",
")",
"# pack the integer into one byte",
"elif",
"i",
"<",
"(",
"2",
"**",
"16",
")",
":",
"return",
"chr",
"(",
"253",
")",
"+",
"struct",
".",
"pack",
"(",
"'<H'",
",",
"i",
")",
"# pack into 2 bytes",
"elif",
"i",
"<",
"(",
"2",
"**",
"32",
")",
":",
"return",
"chr",
"(",
"254",
")",
"+",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"i",
")",
"# pack into 4 bytes",
"elif",
"i",
"<",
"(",
"2",
"**",
"64",
")",
":",
"return",
"chr",
"(",
"255",
")",
"+",
"struct",
".",
"pack",
"(",
"'<Q'",
",",
"i",
")",
"# pack into 8 bites",
"else",
":",
"raise",
"Exception",
"(",
"'Integer cannot exceed 8 bytes in length.'",
")"
] |
Encodes integers into variable length integers, which are used in
Bitcoin in order to save space.
|
[
"Encodes",
"integers",
"into",
"variable",
"length",
"integers",
"which",
"are",
"used",
"in",
"Bitcoin",
"in",
"order",
"to",
"save",
"space",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/utils.py#L25-L41
|
17,972
|
blockstack/pybitcoin
|
pybitcoin/transactions/scripts.py
|
make_pay_to_address_script
|
def make_pay_to_address_script(address):
""" Takes in an address and returns the script
"""
hash160 = hexlify(b58check_decode(address))
script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160
return script_to_hex(script_string)
|
python
|
def make_pay_to_address_script(address):
""" Takes in an address and returns the script
"""
hash160 = hexlify(b58check_decode(address))
script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160
return script_to_hex(script_string)
|
[
"def",
"make_pay_to_address_script",
"(",
"address",
")",
":",
"hash160",
"=",
"hexlify",
"(",
"b58check_decode",
"(",
"address",
")",
")",
"script_string",
"=",
"'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG'",
"%",
"hash160",
"return",
"script_to_hex",
"(",
"script_string",
")"
] |
Takes in an address and returns the script
|
[
"Takes",
"in",
"an",
"address",
"and",
"returns",
"the",
"script"
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L37-L42
|
17,973
|
blockstack/pybitcoin
|
pybitcoin/transactions/scripts.py
|
make_op_return_script
|
def make_op_return_script(data, format='bin'):
""" Takes in raw ascii data to be embedded and returns a script.
"""
if format == 'hex':
assert(is_hex(data))
hex_data = data
elif format == 'bin':
hex_data = hexlify(data)
else:
raise Exception("Format must be either 'hex' or 'bin'")
num_bytes = count_bytes(hex_data)
if num_bytes > MAX_BYTES_AFTER_OP_RETURN:
raise Exception('Data is %i bytes - must not exceed 40.' % num_bytes)
script_string = 'OP_RETURN %s' % hex_data
return script_to_hex(script_string)
|
python
|
def make_op_return_script(data, format='bin'):
""" Takes in raw ascii data to be embedded and returns a script.
"""
if format == 'hex':
assert(is_hex(data))
hex_data = data
elif format == 'bin':
hex_data = hexlify(data)
else:
raise Exception("Format must be either 'hex' or 'bin'")
num_bytes = count_bytes(hex_data)
if num_bytes > MAX_BYTES_AFTER_OP_RETURN:
raise Exception('Data is %i bytes - must not exceed 40.' % num_bytes)
script_string = 'OP_RETURN %s' % hex_data
return script_to_hex(script_string)
|
[
"def",
"make_op_return_script",
"(",
"data",
",",
"format",
"=",
"'bin'",
")",
":",
"if",
"format",
"==",
"'hex'",
":",
"assert",
"(",
"is_hex",
"(",
"data",
")",
")",
"hex_data",
"=",
"data",
"elif",
"format",
"==",
"'bin'",
":",
"hex_data",
"=",
"hexlify",
"(",
"data",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Format must be either 'hex' or 'bin'\"",
")",
"num_bytes",
"=",
"count_bytes",
"(",
"hex_data",
")",
"if",
"num_bytes",
">",
"MAX_BYTES_AFTER_OP_RETURN",
":",
"raise",
"Exception",
"(",
"'Data is %i bytes - must not exceed 40.'",
"%",
"num_bytes",
")",
"script_string",
"=",
"'OP_RETURN %s'",
"%",
"hex_data",
"return",
"script_to_hex",
"(",
"script_string",
")"
] |
Takes in raw ascii data to be embedded and returns a script.
|
[
"Takes",
"in",
"raw",
"ascii",
"data",
"to",
"be",
"embedded",
"and",
"returns",
"a",
"script",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L44-L60
|
17,974
|
blockstack/pybitcoin
|
pybitcoin/services/bitcoind.py
|
create_bitcoind_service_proxy
|
def create_bitcoind_service_proxy(
rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False):
""" create a bitcoind service proxy
"""
protocol = 'https' if use_https else 'http'
uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password,
server, port)
return AuthServiceProxy(uri)
|
python
|
def create_bitcoind_service_proxy(
rpc_username, rpc_password, server='127.0.0.1', port=8332, use_https=False):
""" create a bitcoind service proxy
"""
protocol = 'https' if use_https else 'http'
uri = '%s://%s:%s@%s:%s' % (protocol, rpc_username, rpc_password,
server, port)
return AuthServiceProxy(uri)
|
[
"def",
"create_bitcoind_service_proxy",
"(",
"rpc_username",
",",
"rpc_password",
",",
"server",
"=",
"'127.0.0.1'",
",",
"port",
"=",
"8332",
",",
"use_https",
"=",
"False",
")",
":",
"protocol",
"=",
"'https'",
"if",
"use_https",
"else",
"'http'",
"uri",
"=",
"'%s://%s:%s@%s:%s'",
"%",
"(",
"protocol",
",",
"rpc_username",
",",
"rpc_password",
",",
"server",
",",
"port",
")",
"return",
"AuthServiceProxy",
"(",
"uri",
")"
] |
create a bitcoind service proxy
|
[
"create",
"a",
"bitcoind",
"service",
"proxy"
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/services/bitcoind.py#L21-L28
|
17,975
|
blockstack/pybitcoin
|
pybitcoin/transactions/network.py
|
get_unspents
|
def get_unspents(address, blockchain_client=BlockchainInfoClient()):
""" Gets the unspent outputs for a given address.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
return blockchain_info.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, ChainComClient):
return chain_com.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)):
return bitcoind.get_unspents(address, blockchain_client)
elif hasattr(blockchain_client, "get_unspents"):
return blockchain_client.get_unspents( address )
elif isinstance(blockchain_client, BlockchainClient):
raise Exception('That blockchain interface is not supported.')
else:
raise Exception('A BlockchainClient object is required')
|
python
|
def get_unspents(address, blockchain_client=BlockchainInfoClient()):
""" Gets the unspent outputs for a given address.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
return blockchain_info.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, ChainComClient):
return chain_com.get_unspents(address, blockchain_client)
elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)):
return bitcoind.get_unspents(address, blockchain_client)
elif hasattr(blockchain_client, "get_unspents"):
return blockchain_client.get_unspents( address )
elif isinstance(blockchain_client, BlockchainClient):
raise Exception('That blockchain interface is not supported.')
else:
raise Exception('A BlockchainClient object is required')
|
[
"def",
"get_unspents",
"(",
"address",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"blockchain_client",
",",
"BlockcypherClient",
")",
":",
"return",
"blockcypher",
".",
"get_unspents",
"(",
"address",
",",
"blockchain_client",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"BlockchainInfoClient",
")",
":",
"return",
"blockchain_info",
".",
"get_unspents",
"(",
"address",
",",
"blockchain_client",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"ChainComClient",
")",
":",
"return",
"chain_com",
".",
"get_unspents",
"(",
"address",
",",
"blockchain_client",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"(",
"BitcoindClient",
",",
"AuthServiceProxy",
")",
")",
":",
"return",
"bitcoind",
".",
"get_unspents",
"(",
"address",
",",
"blockchain_client",
")",
"elif",
"hasattr",
"(",
"blockchain_client",
",",
"\"get_unspents\"",
")",
":",
"return",
"blockchain_client",
".",
"get_unspents",
"(",
"address",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"BlockchainClient",
")",
":",
"raise",
"Exception",
"(",
"'That blockchain interface is not supported.'",
")",
"else",
":",
"raise",
"Exception",
"(",
"'A BlockchainClient object is required'",
")"
] |
Gets the unspent outputs for a given address.
|
[
"Gets",
"the",
"unspent",
"outputs",
"for",
"a",
"given",
"address",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L32-L48
|
17,976
|
blockstack/pybitcoin
|
pybitcoin/transactions/network.py
|
broadcast_transaction
|
def broadcast_transaction(hex_tx, blockchain_client):
""" Dispatches a raw hex transaction to the network.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
return blockchain_info.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, ChainComClient):
return chain_com.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)):
return bitcoind.broadcast_transaction(hex_tx, blockchain_client)
elif hasattr(blockchain_client, "broadcast_transaction"):
return blockchain_client.broadcast_transaction( hex_tx )
elif isinstance(blockchain_client, BlockchainClient):
raise Exception('That blockchain interface is not supported.')
else:
raise Exception('A BlockchainClient object is required')
|
python
|
def broadcast_transaction(hex_tx, blockchain_client):
""" Dispatches a raw hex transaction to the network.
"""
if isinstance(blockchain_client, BlockcypherClient):
return blockcypher.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, BlockchainInfoClient):
return blockchain_info.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, ChainComClient):
return chain_com.broadcast_transaction(hex_tx, blockchain_client)
elif isinstance(blockchain_client, (BitcoindClient, AuthServiceProxy)):
return bitcoind.broadcast_transaction(hex_tx, blockchain_client)
elif hasattr(blockchain_client, "broadcast_transaction"):
return blockchain_client.broadcast_transaction( hex_tx )
elif isinstance(blockchain_client, BlockchainClient):
raise Exception('That blockchain interface is not supported.')
else:
raise Exception('A BlockchainClient object is required')
|
[
"def",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
":",
"if",
"isinstance",
"(",
"blockchain_client",
",",
"BlockcypherClient",
")",
":",
"return",
"blockcypher",
".",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"BlockchainInfoClient",
")",
":",
"return",
"blockchain_info",
".",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"ChainComClient",
")",
":",
"return",
"chain_com",
".",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"(",
"BitcoindClient",
",",
"AuthServiceProxy",
")",
")",
":",
"return",
"bitcoind",
".",
"broadcast_transaction",
"(",
"hex_tx",
",",
"blockchain_client",
")",
"elif",
"hasattr",
"(",
"blockchain_client",
",",
"\"broadcast_transaction\"",
")",
":",
"return",
"blockchain_client",
".",
"broadcast_transaction",
"(",
"hex_tx",
")",
"elif",
"isinstance",
"(",
"blockchain_client",
",",
"BlockchainClient",
")",
":",
"raise",
"Exception",
"(",
"'That blockchain interface is not supported.'",
")",
"else",
":",
"raise",
"Exception",
"(",
"'A BlockchainClient object is required'",
")"
] |
Dispatches a raw hex transaction to the network.
|
[
"Dispatches",
"a",
"raw",
"hex",
"transaction",
"to",
"the",
"network",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L51-L67
|
17,977
|
blockstack/pybitcoin
|
pybitcoin/transactions/network.py
|
make_send_to_address_tx
|
def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds and signs a "send to address" transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs = analyze_private_key(private_key,
blockchain_client)
# get the change address
if not change_address:
change_address = from_address
# create the outputs
outputs = make_pay_to_address_outputs(recipient_address, amount, inputs,
change_address, fee=fee)
# serialize the transaction
unsigned_tx = serialize_transaction(inputs, outputs)
# generate a scriptSig for each input
for i in xrange(0, len(inputs)):
signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
unsigned_tx = signed_tx
# return the signed tx
return signed_tx
|
python
|
def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds and signs a "send to address" transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs = analyze_private_key(private_key,
blockchain_client)
# get the change address
if not change_address:
change_address = from_address
# create the outputs
outputs = make_pay_to_address_outputs(recipient_address, amount, inputs,
change_address, fee=fee)
# serialize the transaction
unsigned_tx = serialize_transaction(inputs, outputs)
# generate a scriptSig for each input
for i in xrange(0, len(inputs)):
signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
unsigned_tx = signed_tx
# return the signed tx
return signed_tx
|
[
"def",
"make_send_to_address_tx",
"(",
"recipient_address",
",",
"amount",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"STANDARD_FEE",
",",
"change_address",
"=",
"None",
")",
":",
"# get out the private key object, sending address, and inputs",
"private_key_obj",
",",
"from_address",
",",
"inputs",
"=",
"analyze_private_key",
"(",
"private_key",
",",
"blockchain_client",
")",
"# get the change address",
"if",
"not",
"change_address",
":",
"change_address",
"=",
"from_address",
"# create the outputs",
"outputs",
"=",
"make_pay_to_address_outputs",
"(",
"recipient_address",
",",
"amount",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"fee",
")",
"# serialize the transaction",
"unsigned_tx",
"=",
"serialize_transaction",
"(",
"inputs",
",",
"outputs",
")",
"# generate a scriptSig for each input",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"inputs",
")",
")",
":",
"signed_tx",
"=",
"sign_transaction",
"(",
"unsigned_tx",
",",
"i",
",",
"private_key_obj",
".",
"to_hex",
"(",
")",
")",
"unsigned_tx",
"=",
"signed_tx",
"# return the signed tx",
"return",
"signed_tx"
] |
Builds and signs a "send to address" transaction.
|
[
"Builds",
"and",
"signs",
"a",
"send",
"to",
"address",
"transaction",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L87-L110
|
17,978
|
blockstack/pybitcoin
|
pybitcoin/transactions/network.py
|
make_op_return_tx
|
def make_op_return_tx(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds and signs an OP_RETURN transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs = analyze_private_key(private_key,
blockchain_client)
# get the change address
if not change_address:
change_address = from_address
# create the outputs
outputs = make_op_return_outputs(data, inputs, change_address,
fee=fee, format=format)
# serialize the transaction
unsigned_tx = serialize_transaction(inputs, outputs)
# generate a scriptSig for each input
for i in xrange(0, len(inputs)):
signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
unsigned_tx = signed_tx
# return the signed tx
return signed_tx
|
python
|
def make_op_return_tx(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds and signs an OP_RETURN transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs = analyze_private_key(private_key,
blockchain_client)
# get the change address
if not change_address:
change_address = from_address
# create the outputs
outputs = make_op_return_outputs(data, inputs, change_address,
fee=fee, format=format)
# serialize the transaction
unsigned_tx = serialize_transaction(inputs, outputs)
# generate a scriptSig for each input
for i in xrange(0, len(inputs)):
signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
unsigned_tx = signed_tx
# return the signed tx
return signed_tx
|
[
"def",
"make_op_return_tx",
"(",
"data",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"change_address",
"=",
"None",
",",
"format",
"=",
"'bin'",
")",
":",
"# get out the private key object, sending address, and inputs",
"private_key_obj",
",",
"from_address",
",",
"inputs",
"=",
"analyze_private_key",
"(",
"private_key",
",",
"blockchain_client",
")",
"# get the change address",
"if",
"not",
"change_address",
":",
"change_address",
"=",
"from_address",
"# create the outputs",
"outputs",
"=",
"make_op_return_outputs",
"(",
"data",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"fee",
",",
"format",
"=",
"format",
")",
"# serialize the transaction",
"unsigned_tx",
"=",
"serialize_transaction",
"(",
"inputs",
",",
"outputs",
")",
"# generate a scriptSig for each input",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"inputs",
")",
")",
":",
"signed_tx",
"=",
"sign_transaction",
"(",
"unsigned_tx",
",",
"i",
",",
"private_key_obj",
".",
"to_hex",
"(",
")",
")",
"unsigned_tx",
"=",
"signed_tx",
"# return the signed tx",
"return",
"signed_tx"
] |
Builds and signs an OP_RETURN transaction.
|
[
"Builds",
"and",
"signs",
"an",
"OP_RETURN",
"transaction",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L113-L136
|
17,979
|
blockstack/pybitcoin
|
pybitcoin/transactions/network.py
|
send_to_address
|
def send_to_address(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds, signs, and dispatches a "send to address" transaction.
"""
# build and sign the tx
signed_tx = make_send_to_address_tx(recipient_address, amount,
private_key, blockchain_client, fee=fee,
change_address=change_address)
# dispatch the signed transction to the network
response = broadcast_transaction(signed_tx, blockchain_client)
# return the response
return response
|
python
|
def send_to_address(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds, signs, and dispatches a "send to address" transaction.
"""
# build and sign the tx
signed_tx = make_send_to_address_tx(recipient_address, amount,
private_key, blockchain_client, fee=fee,
change_address=change_address)
# dispatch the signed transction to the network
response = broadcast_transaction(signed_tx, blockchain_client)
# return the response
return response
|
[
"def",
"send_to_address",
"(",
"recipient_address",
",",
"amount",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"STANDARD_FEE",
",",
"change_address",
"=",
"None",
")",
":",
"# build and sign the tx",
"signed_tx",
"=",
"make_send_to_address_tx",
"(",
"recipient_address",
",",
"amount",
",",
"private_key",
",",
"blockchain_client",
",",
"fee",
"=",
"fee",
",",
"change_address",
"=",
"change_address",
")",
"# dispatch the signed transction to the network",
"response",
"=",
"broadcast_transaction",
"(",
"signed_tx",
",",
"blockchain_client",
")",
"# return the response",
"return",
"response"
] |
Builds, signs, and dispatches a "send to address" transaction.
|
[
"Builds",
"signs",
"and",
"dispatches",
"a",
"send",
"to",
"address",
"transaction",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L139-L151
|
17,980
|
blockstack/pybitcoin
|
pybitcoin/transactions/network.py
|
embed_data_in_blockchain
|
def embed_data_in_blockchain(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds, signs, and dispatches an OP_RETURN transaction.
"""
# build and sign the tx
signed_tx = make_op_return_tx(data, private_key, blockchain_client,
fee=fee, change_address=change_address, format=format)
# dispatch the signed transction to the network
response = broadcast_transaction(signed_tx, blockchain_client)
# return the response
return response
|
python
|
def embed_data_in_blockchain(data, private_key,
blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
change_address=None, format='bin'):
""" Builds, signs, and dispatches an OP_RETURN transaction.
"""
# build and sign the tx
signed_tx = make_op_return_tx(data, private_key, blockchain_client,
fee=fee, change_address=change_address, format=format)
# dispatch the signed transction to the network
response = broadcast_transaction(signed_tx, blockchain_client)
# return the response
return response
|
[
"def",
"embed_data_in_blockchain",
"(",
"data",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"change_address",
"=",
"None",
",",
"format",
"=",
"'bin'",
")",
":",
"# build and sign the tx",
"signed_tx",
"=",
"make_op_return_tx",
"(",
"data",
",",
"private_key",
",",
"blockchain_client",
",",
"fee",
"=",
"fee",
",",
"change_address",
"=",
"change_address",
",",
"format",
"=",
"format",
")",
"# dispatch the signed transction to the network",
"response",
"=",
"broadcast_transaction",
"(",
"signed_tx",
",",
"blockchain_client",
")",
"# return the response",
"return",
"response"
] |
Builds, signs, and dispatches an OP_RETURN transaction.
|
[
"Builds",
"signs",
"and",
"dispatches",
"an",
"OP_RETURN",
"transaction",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L154-L165
|
17,981
|
blockstack/pybitcoin
|
pybitcoin/transactions/network.py
|
sign_all_unsigned_inputs
|
def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex):
"""
Sign a serialized transaction's unsigned inputs
@hex_privkey: private key that should sign inputs
@unsigned_tx_hex: hex transaction with unsigned inputs
Returns: signed hex transaction
"""
inputs, outputs, locktime, version = deserialize_transaction(unsigned_tx_hex)
tx_hex = unsigned_tx_hex
for index in xrange(0, len(inputs)):
if len(inputs[index]['script_sig']) == 0:
# tx with index i signed with privkey
tx_hex = sign_transaction(str(unsigned_tx_hex), index, hex_privkey)
unsigned_tx_hex = tx_hex
return tx_hex
|
python
|
def sign_all_unsigned_inputs(hex_privkey, unsigned_tx_hex):
"""
Sign a serialized transaction's unsigned inputs
@hex_privkey: private key that should sign inputs
@unsigned_tx_hex: hex transaction with unsigned inputs
Returns: signed hex transaction
"""
inputs, outputs, locktime, version = deserialize_transaction(unsigned_tx_hex)
tx_hex = unsigned_tx_hex
for index in xrange(0, len(inputs)):
if len(inputs[index]['script_sig']) == 0:
# tx with index i signed with privkey
tx_hex = sign_transaction(str(unsigned_tx_hex), index, hex_privkey)
unsigned_tx_hex = tx_hex
return tx_hex
|
[
"def",
"sign_all_unsigned_inputs",
"(",
"hex_privkey",
",",
"unsigned_tx_hex",
")",
":",
"inputs",
",",
"outputs",
",",
"locktime",
",",
"version",
"=",
"deserialize_transaction",
"(",
"unsigned_tx_hex",
")",
"tx_hex",
"=",
"unsigned_tx_hex",
"for",
"index",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"inputs",
")",
")",
":",
"if",
"len",
"(",
"inputs",
"[",
"index",
"]",
"[",
"'script_sig'",
"]",
")",
"==",
"0",
":",
"# tx with index i signed with privkey",
"tx_hex",
"=",
"sign_transaction",
"(",
"str",
"(",
"unsigned_tx_hex",
")",
",",
"index",
",",
"hex_privkey",
")",
"unsigned_tx_hex",
"=",
"tx_hex",
"return",
"tx_hex"
] |
Sign a serialized transaction's unsigned inputs
@hex_privkey: private key that should sign inputs
@unsigned_tx_hex: hex transaction with unsigned inputs
Returns: signed hex transaction
|
[
"Sign",
"a",
"serialized",
"transaction",
"s",
"unsigned",
"inputs"
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L187-L205
|
17,982
|
blockstack/pybitcoin
|
pybitcoin/merkle.py
|
calculate_merkle_root
|
def calculate_merkle_root(hashes, hash_function=bin_double_sha256,
hex_format=True):
""" takes in a list of binary hashes, returns a binary hash
"""
if hex_format:
hashes = hex_to_bin_reversed_hashes(hashes)
# keep moving up the merkle tree, constructing one row at a time
while len(hashes) > 1:
hashes = calculate_merkle_pairs(hashes, hash_function)
# get the merkle root
merkle_root = hashes[0]
# if the user wants the merkle root in hex format, convert it
if hex_format:
return bin_to_hex_reversed(merkle_root)
# return the binary merkle root
return merkle_root
|
python
|
def calculate_merkle_root(hashes, hash_function=bin_double_sha256,
hex_format=True):
""" takes in a list of binary hashes, returns a binary hash
"""
if hex_format:
hashes = hex_to_bin_reversed_hashes(hashes)
# keep moving up the merkle tree, constructing one row at a time
while len(hashes) > 1:
hashes = calculate_merkle_pairs(hashes, hash_function)
# get the merkle root
merkle_root = hashes[0]
# if the user wants the merkle root in hex format, convert it
if hex_format:
return bin_to_hex_reversed(merkle_root)
# return the binary merkle root
return merkle_root
|
[
"def",
"calculate_merkle_root",
"(",
"hashes",
",",
"hash_function",
"=",
"bin_double_sha256",
",",
"hex_format",
"=",
"True",
")",
":",
"if",
"hex_format",
":",
"hashes",
"=",
"hex_to_bin_reversed_hashes",
"(",
"hashes",
")",
"# keep moving up the merkle tree, constructing one row at a time",
"while",
"len",
"(",
"hashes",
")",
">",
"1",
":",
"hashes",
"=",
"calculate_merkle_pairs",
"(",
"hashes",
",",
"hash_function",
")",
"# get the merkle root",
"merkle_root",
"=",
"hashes",
"[",
"0",
"]",
"# if the user wants the merkle root in hex format, convert it",
"if",
"hex_format",
":",
"return",
"bin_to_hex_reversed",
"(",
"merkle_root",
")",
"# return the binary merkle root",
"return",
"merkle_root"
] |
takes in a list of binary hashes, returns a binary hash
|
[
"takes",
"in",
"a",
"list",
"of",
"binary",
"hashes",
"returns",
"a",
"binary",
"hash"
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/merkle.py#L23-L38
|
17,983
|
blockstack/pybitcoin
|
pybitcoin/b58check.py
|
b58check_encode
|
def b58check_encode(bin_s, version_byte=0):
""" Takes in a binary string and converts it to a base 58 check string. """
# append the version byte to the beginning
bin_s = chr(int(version_byte)) + bin_s
# calculate the number of leading zeros
num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0))
# add in the checksum add the end
bin_s = bin_s + bin_checksum(bin_s)
# convert from b2 to b16
hex_s = hexlify(bin_s)
# convert from b16 to b58
b58_s = change_charset(hex_s, HEX_KEYSPACE, B58_KEYSPACE)
return B58_KEYSPACE[0] * num_leading_zeros + b58_s
|
python
|
def b58check_encode(bin_s, version_byte=0):
""" Takes in a binary string and converts it to a base 58 check string. """
# append the version byte to the beginning
bin_s = chr(int(version_byte)) + bin_s
# calculate the number of leading zeros
num_leading_zeros = len(re.match(r'^\x00*', bin_s).group(0))
# add in the checksum add the end
bin_s = bin_s + bin_checksum(bin_s)
# convert from b2 to b16
hex_s = hexlify(bin_s)
# convert from b16 to b58
b58_s = change_charset(hex_s, HEX_KEYSPACE, B58_KEYSPACE)
return B58_KEYSPACE[0] * num_leading_zeros + b58_s
|
[
"def",
"b58check_encode",
"(",
"bin_s",
",",
"version_byte",
"=",
"0",
")",
":",
"# append the version byte to the beginning",
"bin_s",
"=",
"chr",
"(",
"int",
"(",
"version_byte",
")",
")",
"+",
"bin_s",
"# calculate the number of leading zeros",
"num_leading_zeros",
"=",
"len",
"(",
"re",
".",
"match",
"(",
"r'^\\x00*'",
",",
"bin_s",
")",
".",
"group",
"(",
"0",
")",
")",
"# add in the checksum add the end",
"bin_s",
"=",
"bin_s",
"+",
"bin_checksum",
"(",
"bin_s",
")",
"# convert from b2 to b16",
"hex_s",
"=",
"hexlify",
"(",
"bin_s",
")",
"# convert from b16 to b58",
"b58_s",
"=",
"change_charset",
"(",
"hex_s",
",",
"HEX_KEYSPACE",
",",
"B58_KEYSPACE",
")",
"return",
"B58_KEYSPACE",
"[",
"0",
"]",
"*",
"num_leading_zeros",
"+",
"b58_s"
] |
Takes in a binary string and converts it to a base 58 check string.
|
[
"Takes",
"in",
"a",
"binary",
"string",
"and",
"converts",
"it",
"to",
"a",
"base",
"58",
"check",
"string",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/b58check.py#L20-L33
|
17,984
|
blockstack/pybitcoin
|
pybitcoin/transactions/outputs.py
|
make_pay_to_address_outputs
|
def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address,
fee=STANDARD_FEE):
""" Builds the outputs for a "pay to address" transaction.
"""
return [
# main output
{ "script_hex": make_pay_to_address_script(to_address), "value": send_amount },
# change output
{ "script_hex": make_pay_to_address_script(change_address),
"value": calculate_change_amount(inputs, send_amount, fee)
}
]
|
python
|
def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address,
fee=STANDARD_FEE):
""" Builds the outputs for a "pay to address" transaction.
"""
return [
# main output
{ "script_hex": make_pay_to_address_script(to_address), "value": send_amount },
# change output
{ "script_hex": make_pay_to_address_script(change_address),
"value": calculate_change_amount(inputs, send_amount, fee)
}
]
|
[
"def",
"make_pay_to_address_outputs",
"(",
"to_address",
",",
"send_amount",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"STANDARD_FEE",
")",
":",
"return",
"[",
"# main output",
"{",
"\"script_hex\"",
":",
"make_pay_to_address_script",
"(",
"to_address",
")",
",",
"\"value\"",
":",
"send_amount",
"}",
",",
"# change output",
"{",
"\"script_hex\"",
":",
"make_pay_to_address_script",
"(",
"change_address",
")",
",",
"\"value\"",
":",
"calculate_change_amount",
"(",
"inputs",
",",
"send_amount",
",",
"fee",
")",
"}",
"]"
] |
Builds the outputs for a "pay to address" transaction.
|
[
"Builds",
"the",
"outputs",
"for",
"a",
"pay",
"to",
"address",
"transaction",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L23-L34
|
17,985
|
blockstack/pybitcoin
|
pybitcoin/transactions/outputs.py
|
make_op_return_outputs
|
def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
""" Builds the outputs for an OP_RETURN transaction.
"""
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amount },
# change output
{ "script_hex": make_pay_to_address_script(change_address),
"value": calculate_change_amount(inputs, send_amount, fee)
}
]
|
python
|
def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
""" Builds the outputs for an OP_RETURN transaction.
"""
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amount },
# change output
{ "script_hex": make_pay_to_address_script(change_address),
"value": calculate_change_amount(inputs, send_amount, fee)
}
]
|
[
"def",
"make_op_return_outputs",
"(",
"data",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"send_amount",
"=",
"0",
",",
"format",
"=",
"'bin'",
")",
":",
"return",
"[",
"# main output",
"{",
"\"script_hex\"",
":",
"make_op_return_script",
"(",
"data",
",",
"format",
"=",
"format",
")",
",",
"\"value\"",
":",
"send_amount",
"}",
",",
"# change output",
"{",
"\"script_hex\"",
":",
"make_pay_to_address_script",
"(",
"change_address",
")",
",",
"\"value\"",
":",
"calculate_change_amount",
"(",
"inputs",
",",
"send_amount",
",",
"fee",
")",
"}",
"]"
] |
Builds the outputs for an OP_RETURN transaction.
|
[
"Builds",
"the",
"outputs",
"for",
"an",
"OP_RETURN",
"transaction",
"."
] |
92c8da63c40f7418594b1ce395990c3f5a4787cc
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L36-L47
|
17,986
|
caktus/django-timepiece
|
timepiece/utils/__init__.py
|
add_timezone
|
def add_timezone(value, tz=None):
"""If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used.
"""
tz = tz or timezone.get_current_timezone()
try:
if timezone.is_naive(value):
return timezone.make_aware(value, tz)
except AttributeError: # 'datetime.date' object has no attribute 'tzinfo'
dt = datetime.datetime.combine(value, datetime.time())
return timezone.make_aware(dt, tz)
return value
|
python
|
def add_timezone(value, tz=None):
"""If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used.
"""
tz = tz or timezone.get_current_timezone()
try:
if timezone.is_naive(value):
return timezone.make_aware(value, tz)
except AttributeError: # 'datetime.date' object has no attribute 'tzinfo'
dt = datetime.datetime.combine(value, datetime.time())
return timezone.make_aware(dt, tz)
return value
|
[
"def",
"add_timezone",
"(",
"value",
",",
"tz",
"=",
"None",
")",
":",
"tz",
"=",
"tz",
"or",
"timezone",
".",
"get_current_timezone",
"(",
")",
"try",
":",
"if",
"timezone",
".",
"is_naive",
"(",
"value",
")",
":",
"return",
"timezone",
".",
"make_aware",
"(",
"value",
",",
"tz",
")",
"except",
"AttributeError",
":",
"# 'datetime.date' object has no attribute 'tzinfo'",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"value",
",",
"datetime",
".",
"time",
"(",
")",
")",
"return",
"timezone",
".",
"make_aware",
"(",
"dt",
",",
"tz",
")",
"return",
"value"
] |
If the value is naive, then the timezone is added to it.
If no timezone is given, timezone.get_current_timezone() is used.
|
[
"If",
"the",
"value",
"is",
"naive",
"then",
"the",
"timezone",
"is",
"added",
"to",
"it",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L16-L28
|
17,987
|
caktus/django-timepiece
|
timepiece/utils/__init__.py
|
get_active_entry
|
def get_active_entry(user, select_for_update=False):
"""Returns the user's currently-active entry, or None."""
entries = apps.get_model('entries', 'Entry').no_join
if select_for_update:
entries = entries.select_for_update()
entries = entries.filter(user=user, end_time__isnull=True)
if not entries.exists():
return None
if entries.count() > 1:
raise ActiveEntryError('Only one active entry is allowed.')
return entries[0]
|
python
|
def get_active_entry(user, select_for_update=False):
"""Returns the user's currently-active entry, or None."""
entries = apps.get_model('entries', 'Entry').no_join
if select_for_update:
entries = entries.select_for_update()
entries = entries.filter(user=user, end_time__isnull=True)
if not entries.exists():
return None
if entries.count() > 1:
raise ActiveEntryError('Only one active entry is allowed.')
return entries[0]
|
[
"def",
"get_active_entry",
"(",
"user",
",",
"select_for_update",
"=",
"False",
")",
":",
"entries",
"=",
"apps",
".",
"get_model",
"(",
"'entries'",
",",
"'Entry'",
")",
".",
"no_join",
"if",
"select_for_update",
":",
"entries",
"=",
"entries",
".",
"select_for_update",
"(",
")",
"entries",
"=",
"entries",
".",
"filter",
"(",
"user",
"=",
"user",
",",
"end_time__isnull",
"=",
"True",
")",
"if",
"not",
"entries",
".",
"exists",
"(",
")",
":",
"return",
"None",
"if",
"entries",
".",
"count",
"(",
")",
">",
"1",
":",
"raise",
"ActiveEntryError",
"(",
"'Only one active entry is allowed.'",
")",
"return",
"entries",
"[",
"0",
"]"
] |
Returns the user's currently-active entry, or None.
|
[
"Returns",
"the",
"user",
"s",
"currently",
"-",
"active",
"entry",
"or",
"None",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L31-L42
|
17,988
|
caktus/django-timepiece
|
timepiece/utils/__init__.py
|
get_month_start
|
def get_month_start(day=None):
"""Returns the first day of the given month."""
day = add_timezone(day or datetime.date.today())
return day.replace(day=1)
|
python
|
def get_month_start(day=None):
"""Returns the first day of the given month."""
day = add_timezone(day or datetime.date.today())
return day.replace(day=1)
|
[
"def",
"get_month_start",
"(",
"day",
"=",
"None",
")",
":",
"day",
"=",
"add_timezone",
"(",
"day",
"or",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"return",
"day",
".",
"replace",
"(",
"day",
"=",
"1",
")"
] |
Returns the first day of the given month.
|
[
"Returns",
"the",
"first",
"day",
"of",
"the",
"given",
"month",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L64-L67
|
17,989
|
caktus/django-timepiece
|
timepiece/utils/__init__.py
|
get_setting
|
def get_setting(name, **kwargs):
"""Returns the user-defined value for the setting, or a default value."""
if hasattr(settings, name): # Try user-defined settings first.
return getattr(settings, name)
if 'default' in kwargs: # Fall back to a specified default value.
return kwargs['default']
if hasattr(defaults, name): # If that's not given, look in defaults file.
return getattr(defaults, name)
msg = '{0} must be specified in your project settings.'.format(name)
raise AttributeError(msg)
|
python
|
def get_setting(name, **kwargs):
"""Returns the user-defined value for the setting, or a default value."""
if hasattr(settings, name): # Try user-defined settings first.
return getattr(settings, name)
if 'default' in kwargs: # Fall back to a specified default value.
return kwargs['default']
if hasattr(defaults, name): # If that's not given, look in defaults file.
return getattr(defaults, name)
msg = '{0} must be specified in your project settings.'.format(name)
raise AttributeError(msg)
|
[
"def",
"get_setting",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"settings",
",",
"name",
")",
":",
"# Try user-defined settings first.",
"return",
"getattr",
"(",
"settings",
",",
"name",
")",
"if",
"'default'",
"in",
"kwargs",
":",
"# Fall back to a specified default value.",
"return",
"kwargs",
"[",
"'default'",
"]",
"if",
"hasattr",
"(",
"defaults",
",",
"name",
")",
":",
"# If that's not given, look in defaults file.",
"return",
"getattr",
"(",
"defaults",
",",
"name",
")",
"msg",
"=",
"'{0} must be specified in your project settings.'",
".",
"format",
"(",
"name",
")",
"raise",
"AttributeError",
"(",
"msg",
")"
] |
Returns the user-defined value for the setting, or a default value.
|
[
"Returns",
"the",
"user",
"-",
"defined",
"value",
"for",
"the",
"setting",
"or",
"a",
"default",
"value",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L73-L82
|
17,990
|
caktus/django-timepiece
|
timepiece/utils/__init__.py
|
get_week_start
|
def get_week_start(day=None):
"""Returns the Monday of the given week."""
day = add_timezone(day or datetime.date.today())
days_since_monday = day.weekday()
if days_since_monday != 0:
day = day - relativedelta(days=days_since_monday)
return day
|
python
|
def get_week_start(day=None):
"""Returns the Monday of the given week."""
day = add_timezone(day or datetime.date.today())
days_since_monday = day.weekday()
if days_since_monday != 0:
day = day - relativedelta(days=days_since_monday)
return day
|
[
"def",
"get_week_start",
"(",
"day",
"=",
"None",
")",
":",
"day",
"=",
"add_timezone",
"(",
"day",
"or",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"days_since_monday",
"=",
"day",
".",
"weekday",
"(",
")",
"if",
"days_since_monday",
"!=",
"0",
":",
"day",
"=",
"day",
"-",
"relativedelta",
"(",
"days",
"=",
"days_since_monday",
")",
"return",
"day"
] |
Returns the Monday of the given week.
|
[
"Returns",
"the",
"Monday",
"of",
"the",
"given",
"week",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L85-L91
|
17,991
|
caktus/django-timepiece
|
timepiece/utils/__init__.py
|
get_year_start
|
def get_year_start(day=None):
"""Returns January 1 of the given year."""
day = add_timezone(day or datetime.date.today())
return day.replace(month=1).replace(day=1)
|
python
|
def get_year_start(day=None):
"""Returns January 1 of the given year."""
day = add_timezone(day or datetime.date.today())
return day.replace(month=1).replace(day=1)
|
[
"def",
"get_year_start",
"(",
"day",
"=",
"None",
")",
":",
"day",
"=",
"add_timezone",
"(",
"day",
"or",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"return",
"day",
".",
"replace",
"(",
"month",
"=",
"1",
")",
".",
"replace",
"(",
"day",
"=",
"1",
")"
] |
Returns January 1 of the given year.
|
[
"Returns",
"January",
"1",
"of",
"the",
"given",
"year",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L94-L97
|
17,992
|
caktus/django-timepiece
|
timepiece/utils/__init__.py
|
to_datetime
|
def to_datetime(date):
"""Transforms a date or datetime object into a date object."""
return datetime.datetime(date.year, date.month, date.day)
|
python
|
def to_datetime(date):
"""Transforms a date or datetime object into a date object."""
return datetime.datetime(date.year, date.month, date.day)
|
[
"def",
"to_datetime",
"(",
"date",
")",
":",
"return",
"datetime",
".",
"datetime",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
")"
] |
Transforms a date or datetime object into a date object.
|
[
"Transforms",
"a",
"date",
"or",
"datetime",
"object",
"into",
"a",
"date",
"object",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L100-L102
|
17,993
|
caktus/django-timepiece
|
timepiece/reports/views.py
|
report_estimation_accuracy
|
def report_estimation_accuracy(request):
"""
Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.
"""
contracts = ProjectContract.objects.filter(
status=ProjectContract.STATUS_COMPLETE,
type=ProjectContract.PROJECT_FIXED
)
data = [('Target (hrs)', 'Actual (hrs)', 'Point Label')]
for c in contracts:
if c.contracted_hours() == 0:
continue
pt_label = "%s (%.2f%%)" % (c.name,
c.hours_worked / c.contracted_hours() * 100)
data.append((c.contracted_hours(), c.hours_worked, pt_label))
chart_max = max([max(x[0], x[1]) for x in data[1:]]) # max of all targets & actuals
return render(request, 'timepiece/reports/estimation_accuracy.html', {
'data': json.dumps(data, cls=DecimalEncoder),
'chart_max': chart_max,
})
|
python
|
def report_estimation_accuracy(request):
"""
Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.
"""
contracts = ProjectContract.objects.filter(
status=ProjectContract.STATUS_COMPLETE,
type=ProjectContract.PROJECT_FIXED
)
data = [('Target (hrs)', 'Actual (hrs)', 'Point Label')]
for c in contracts:
if c.contracted_hours() == 0:
continue
pt_label = "%s (%.2f%%)" % (c.name,
c.hours_worked / c.contracted_hours() * 100)
data.append((c.contracted_hours(), c.hours_worked, pt_label))
chart_max = max([max(x[0], x[1]) for x in data[1:]]) # max of all targets & actuals
return render(request, 'timepiece/reports/estimation_accuracy.html', {
'data': json.dumps(data, cls=DecimalEncoder),
'chart_max': chart_max,
})
|
[
"def",
"report_estimation_accuracy",
"(",
"request",
")",
":",
"contracts",
"=",
"ProjectContract",
".",
"objects",
".",
"filter",
"(",
"status",
"=",
"ProjectContract",
".",
"STATUS_COMPLETE",
",",
"type",
"=",
"ProjectContract",
".",
"PROJECT_FIXED",
")",
"data",
"=",
"[",
"(",
"'Target (hrs)'",
",",
"'Actual (hrs)'",
",",
"'Point Label'",
")",
"]",
"for",
"c",
"in",
"contracts",
":",
"if",
"c",
".",
"contracted_hours",
"(",
")",
"==",
"0",
":",
"continue",
"pt_label",
"=",
"\"%s (%.2f%%)\"",
"%",
"(",
"c",
".",
"name",
",",
"c",
".",
"hours_worked",
"/",
"c",
".",
"contracted_hours",
"(",
")",
"*",
"100",
")",
"data",
".",
"append",
"(",
"(",
"c",
".",
"contracted_hours",
"(",
")",
",",
"c",
".",
"hours_worked",
",",
"pt_label",
")",
")",
"chart_max",
"=",
"max",
"(",
"[",
"max",
"(",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
")",
"for",
"x",
"in",
"data",
"[",
"1",
":",
"]",
"]",
")",
"# max of all targets & actuals",
"return",
"render",
"(",
"request",
",",
"'timepiece/reports/estimation_accuracy.html'",
",",
"{",
"'data'",
":",
"json",
".",
"dumps",
"(",
"data",
",",
"cls",
"=",
"DecimalEncoder",
")",
",",
"'chart_max'",
":",
"chart_max",
",",
"}",
")"
] |
Idea from Software Estimation, Demystifying the Black Art, McConnel 2006 Fig 3-3.
|
[
"Idea",
"from",
"Software",
"Estimation",
"Demystifying",
"the",
"Black",
"Art",
"McConnel",
"2006",
"Fig",
"3",
"-",
"3",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L468-L487
|
17,994
|
caktus/django-timepiece
|
timepiece/reports/views.py
|
ReportMixin.get_context_data
|
def get_context_data(self, **kwargs):
"""Processes form data to get relevant entries & date_headers."""
context = super(ReportMixin, self).get_context_data(**kwargs)
form = self.get_form()
if form.is_valid():
data = form.cleaned_data
start, end = form.save()
entryQ = self.get_entry_query(start, end, data)
trunc = data['trunc']
if entryQ:
vals = ('pk', 'activity', 'project', 'project__name',
'project__status', 'project__type__label')
entries = Entry.objects.date_trunc(
trunc, extra_values=vals).filter(entryQ)
else:
entries = Entry.objects.none()
end = end - relativedelta(days=1)
date_headers = generate_dates(start, end, by=trunc)
context.update({
'from_date': start,
'to_date': end,
'date_headers': date_headers,
'entries': entries,
'filter_form': form,
'trunc': trunc,
})
else:
context.update({
'from_date': None,
'to_date': None,
'date_headers': [],
'entries': Entry.objects.none(),
'filter_form': form,
'trunc': '',
})
return context
|
python
|
def get_context_data(self, **kwargs):
"""Processes form data to get relevant entries & date_headers."""
context = super(ReportMixin, self).get_context_data(**kwargs)
form = self.get_form()
if form.is_valid():
data = form.cleaned_data
start, end = form.save()
entryQ = self.get_entry_query(start, end, data)
trunc = data['trunc']
if entryQ:
vals = ('pk', 'activity', 'project', 'project__name',
'project__status', 'project__type__label')
entries = Entry.objects.date_trunc(
trunc, extra_values=vals).filter(entryQ)
else:
entries = Entry.objects.none()
end = end - relativedelta(days=1)
date_headers = generate_dates(start, end, by=trunc)
context.update({
'from_date': start,
'to_date': end,
'date_headers': date_headers,
'entries': entries,
'filter_form': form,
'trunc': trunc,
})
else:
context.update({
'from_date': None,
'to_date': None,
'date_headers': [],
'entries': Entry.objects.none(),
'filter_form': form,
'trunc': '',
})
return context
|
[
"def",
"get_context_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"super",
"(",
"ReportMixin",
",",
"self",
")",
".",
"get_context_data",
"(",
"*",
"*",
"kwargs",
")",
"form",
"=",
"self",
".",
"get_form",
"(",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"data",
"=",
"form",
".",
"cleaned_data",
"start",
",",
"end",
"=",
"form",
".",
"save",
"(",
")",
"entryQ",
"=",
"self",
".",
"get_entry_query",
"(",
"start",
",",
"end",
",",
"data",
")",
"trunc",
"=",
"data",
"[",
"'trunc'",
"]",
"if",
"entryQ",
":",
"vals",
"=",
"(",
"'pk'",
",",
"'activity'",
",",
"'project'",
",",
"'project__name'",
",",
"'project__status'",
",",
"'project__type__label'",
")",
"entries",
"=",
"Entry",
".",
"objects",
".",
"date_trunc",
"(",
"trunc",
",",
"extra_values",
"=",
"vals",
")",
".",
"filter",
"(",
"entryQ",
")",
"else",
":",
"entries",
"=",
"Entry",
".",
"objects",
".",
"none",
"(",
")",
"end",
"=",
"end",
"-",
"relativedelta",
"(",
"days",
"=",
"1",
")",
"date_headers",
"=",
"generate_dates",
"(",
"start",
",",
"end",
",",
"by",
"=",
"trunc",
")",
"context",
".",
"update",
"(",
"{",
"'from_date'",
":",
"start",
",",
"'to_date'",
":",
"end",
",",
"'date_headers'",
":",
"date_headers",
",",
"'entries'",
":",
"entries",
",",
"'filter_form'",
":",
"form",
",",
"'trunc'",
":",
"trunc",
",",
"}",
")",
"else",
":",
"context",
".",
"update",
"(",
"{",
"'from_date'",
":",
"None",
",",
"'to_date'",
":",
"None",
",",
"'date_headers'",
":",
"[",
"]",
",",
"'entries'",
":",
"Entry",
".",
"objects",
".",
"none",
"(",
")",
",",
"'filter_form'",
":",
"form",
",",
"'trunc'",
":",
"''",
",",
"}",
")",
"return",
"context"
] |
Processes form data to get relevant entries & date_headers.
|
[
"Processes",
"form",
"data",
"to",
"get",
"relevant",
"entries",
"&",
"date_headers",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L36-L74
|
17,995
|
caktus/django-timepiece
|
timepiece/reports/views.py
|
ReportMixin.get_entry_query
|
def get_entry_query(self, start, end, data):
"""Builds Entry query from form data."""
# Entry types.
incl_billable = data.get('billable', True)
incl_nonbillable = data.get('non_billable', True)
incl_leave = data.get('paid_leave', True)
# If no types are selected, shortcut & return nothing.
if not any((incl_billable, incl_nonbillable, incl_leave)):
return None
# All entries must meet time period requirements.
basicQ = Q(end_time__gte=start, end_time__lt=end)
# Filter by project for HourlyReport.
projects = data.get('projects', None)
basicQ &= Q(project__in=projects) if projects else Q()
# Filter by user, activity, and project type for BillableReport.
if 'users' in data:
basicQ &= Q(user__in=data.get('users'))
if 'activities' in data:
basicQ &= Q(activity__in=data.get('activities'))
if 'project_types' in data:
basicQ &= Q(project__type__in=data.get('project_types'))
# If all types are selected, no further filtering is required.
if all((incl_billable, incl_nonbillable, incl_leave)):
return basicQ
# Filter by whether a project is billable or non-billable.
billableQ = None
if incl_billable and not incl_nonbillable:
billableQ = Q(activity__billable=True, project__type__billable=True)
if incl_nonbillable and not incl_billable:
billableQ = Q(activity__billable=False) | Q(project__type__billable=False)
# Filter by whether the entry is paid leave.
leave_ids = utils.get_setting('TIMEPIECE_PAID_LEAVE_PROJECTS').values()
leaveQ = Q(project__in=leave_ids)
if incl_leave:
extraQ = (leaveQ | billableQ) if billableQ else leaveQ
else:
extraQ = (~leaveQ & billableQ) if billableQ else ~leaveQ
return basicQ & extraQ
|
python
|
def get_entry_query(self, start, end, data):
"""Builds Entry query from form data."""
# Entry types.
incl_billable = data.get('billable', True)
incl_nonbillable = data.get('non_billable', True)
incl_leave = data.get('paid_leave', True)
# If no types are selected, shortcut & return nothing.
if not any((incl_billable, incl_nonbillable, incl_leave)):
return None
# All entries must meet time period requirements.
basicQ = Q(end_time__gte=start, end_time__lt=end)
# Filter by project for HourlyReport.
projects = data.get('projects', None)
basicQ &= Q(project__in=projects) if projects else Q()
# Filter by user, activity, and project type for BillableReport.
if 'users' in data:
basicQ &= Q(user__in=data.get('users'))
if 'activities' in data:
basicQ &= Q(activity__in=data.get('activities'))
if 'project_types' in data:
basicQ &= Q(project__type__in=data.get('project_types'))
# If all types are selected, no further filtering is required.
if all((incl_billable, incl_nonbillable, incl_leave)):
return basicQ
# Filter by whether a project is billable or non-billable.
billableQ = None
if incl_billable and not incl_nonbillable:
billableQ = Q(activity__billable=True, project__type__billable=True)
if incl_nonbillable and not incl_billable:
billableQ = Q(activity__billable=False) | Q(project__type__billable=False)
# Filter by whether the entry is paid leave.
leave_ids = utils.get_setting('TIMEPIECE_PAID_LEAVE_PROJECTS').values()
leaveQ = Q(project__in=leave_ids)
if incl_leave:
extraQ = (leaveQ | billableQ) if billableQ else leaveQ
else:
extraQ = (~leaveQ & billableQ) if billableQ else ~leaveQ
return basicQ & extraQ
|
[
"def",
"get_entry_query",
"(",
"self",
",",
"start",
",",
"end",
",",
"data",
")",
":",
"# Entry types.",
"incl_billable",
"=",
"data",
".",
"get",
"(",
"'billable'",
",",
"True",
")",
"incl_nonbillable",
"=",
"data",
".",
"get",
"(",
"'non_billable'",
",",
"True",
")",
"incl_leave",
"=",
"data",
".",
"get",
"(",
"'paid_leave'",
",",
"True",
")",
"# If no types are selected, shortcut & return nothing.",
"if",
"not",
"any",
"(",
"(",
"incl_billable",
",",
"incl_nonbillable",
",",
"incl_leave",
")",
")",
":",
"return",
"None",
"# All entries must meet time period requirements.",
"basicQ",
"=",
"Q",
"(",
"end_time__gte",
"=",
"start",
",",
"end_time__lt",
"=",
"end",
")",
"# Filter by project for HourlyReport.",
"projects",
"=",
"data",
".",
"get",
"(",
"'projects'",
",",
"None",
")",
"basicQ",
"&=",
"Q",
"(",
"project__in",
"=",
"projects",
")",
"if",
"projects",
"else",
"Q",
"(",
")",
"# Filter by user, activity, and project type for BillableReport.",
"if",
"'users'",
"in",
"data",
":",
"basicQ",
"&=",
"Q",
"(",
"user__in",
"=",
"data",
".",
"get",
"(",
"'users'",
")",
")",
"if",
"'activities'",
"in",
"data",
":",
"basicQ",
"&=",
"Q",
"(",
"activity__in",
"=",
"data",
".",
"get",
"(",
"'activities'",
")",
")",
"if",
"'project_types'",
"in",
"data",
":",
"basicQ",
"&=",
"Q",
"(",
"project__type__in",
"=",
"data",
".",
"get",
"(",
"'project_types'",
")",
")",
"# If all types are selected, no further filtering is required.",
"if",
"all",
"(",
"(",
"incl_billable",
",",
"incl_nonbillable",
",",
"incl_leave",
")",
")",
":",
"return",
"basicQ",
"# Filter by whether a project is billable or non-billable.",
"billableQ",
"=",
"None",
"if",
"incl_billable",
"and",
"not",
"incl_nonbillable",
":",
"billableQ",
"=",
"Q",
"(",
"activity__billable",
"=",
"True",
",",
"project__type__billable",
"=",
"True",
")",
"if",
"incl_nonbillable",
"and",
"not",
"incl_billable",
":",
"billableQ",
"=",
"Q",
"(",
"activity__billable",
"=",
"False",
")",
"|",
"Q",
"(",
"project__type__billable",
"=",
"False",
")",
"# Filter by whether the entry is paid leave.",
"leave_ids",
"=",
"utils",
".",
"get_setting",
"(",
"'TIMEPIECE_PAID_LEAVE_PROJECTS'",
")",
".",
"values",
"(",
")",
"leaveQ",
"=",
"Q",
"(",
"project__in",
"=",
"leave_ids",
")",
"if",
"incl_leave",
":",
"extraQ",
"=",
"(",
"leaveQ",
"|",
"billableQ",
")",
"if",
"billableQ",
"else",
"leaveQ",
"else",
":",
"extraQ",
"=",
"(",
"~",
"leaveQ",
"&",
"billableQ",
")",
"if",
"billableQ",
"else",
"~",
"leaveQ",
"return",
"basicQ",
"&",
"extraQ"
] |
Builds Entry query from form data.
|
[
"Builds",
"Entry",
"query",
"from",
"form",
"data",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L76-L121
|
17,996
|
caktus/django-timepiece
|
timepiece/reports/views.py
|
ReportMixin.get_headers
|
def get_headers(self, date_headers, from_date, to_date, trunc):
"""Adjust date headers & get range headers."""
date_headers = list(date_headers)
# Earliest date should be no earlier than from_date.
if date_headers and date_headers[0] < from_date:
date_headers[0] = from_date
# When organizing by week or month, create a list of the range for
# each date header.
if date_headers and trunc != 'day':
count = len(date_headers)
range_headers = [0] * count
for i in range(count - 1):
range_headers[i] = (
date_headers[i], date_headers[i + 1] - relativedelta(days=1))
range_headers[count - 1] = (date_headers[count - 1], to_date)
else:
range_headers = date_headers
return date_headers, range_headers
|
python
|
def get_headers(self, date_headers, from_date, to_date, trunc):
"""Adjust date headers & get range headers."""
date_headers = list(date_headers)
# Earliest date should be no earlier than from_date.
if date_headers and date_headers[0] < from_date:
date_headers[0] = from_date
# When organizing by week or month, create a list of the range for
# each date header.
if date_headers and trunc != 'day':
count = len(date_headers)
range_headers = [0] * count
for i in range(count - 1):
range_headers[i] = (
date_headers[i], date_headers[i + 1] - relativedelta(days=1))
range_headers[count - 1] = (date_headers[count - 1], to_date)
else:
range_headers = date_headers
return date_headers, range_headers
|
[
"def",
"get_headers",
"(",
"self",
",",
"date_headers",
",",
"from_date",
",",
"to_date",
",",
"trunc",
")",
":",
"date_headers",
"=",
"list",
"(",
"date_headers",
")",
"# Earliest date should be no earlier than from_date.",
"if",
"date_headers",
"and",
"date_headers",
"[",
"0",
"]",
"<",
"from_date",
":",
"date_headers",
"[",
"0",
"]",
"=",
"from_date",
"# When organizing by week or month, create a list of the range for",
"# each date header.",
"if",
"date_headers",
"and",
"trunc",
"!=",
"'day'",
":",
"count",
"=",
"len",
"(",
"date_headers",
")",
"range_headers",
"=",
"[",
"0",
"]",
"*",
"count",
"for",
"i",
"in",
"range",
"(",
"count",
"-",
"1",
")",
":",
"range_headers",
"[",
"i",
"]",
"=",
"(",
"date_headers",
"[",
"i",
"]",
",",
"date_headers",
"[",
"i",
"+",
"1",
"]",
"-",
"relativedelta",
"(",
"days",
"=",
"1",
")",
")",
"range_headers",
"[",
"count",
"-",
"1",
"]",
"=",
"(",
"date_headers",
"[",
"count",
"-",
"1",
"]",
",",
"to_date",
")",
"else",
":",
"range_headers",
"=",
"date_headers",
"return",
"date_headers",
",",
"range_headers"
] |
Adjust date headers & get range headers.
|
[
"Adjust",
"date",
"headers",
"&",
"get",
"range",
"headers",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L123-L142
|
17,997
|
caktus/django-timepiece
|
timepiece/reports/views.py
|
ReportMixin.get_previous_month
|
def get_previous_month(self):
"""Returns date range for the previous full month."""
end = utils.get_month_start() - relativedelta(days=1)
end = utils.to_datetime(end)
start = utils.get_month_start(end)
return start, end
|
python
|
def get_previous_month(self):
"""Returns date range for the previous full month."""
end = utils.get_month_start() - relativedelta(days=1)
end = utils.to_datetime(end)
start = utils.get_month_start(end)
return start, end
|
[
"def",
"get_previous_month",
"(",
"self",
")",
":",
"end",
"=",
"utils",
".",
"get_month_start",
"(",
")",
"-",
"relativedelta",
"(",
"days",
"=",
"1",
")",
"end",
"=",
"utils",
".",
"to_datetime",
"(",
"end",
")",
"start",
"=",
"utils",
".",
"get_month_start",
"(",
"end",
")",
"return",
"start",
",",
"end"
] |
Returns date range for the previous full month.
|
[
"Returns",
"date",
"range",
"for",
"the",
"previous",
"full",
"month",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L144-L149
|
17,998
|
caktus/django-timepiece
|
timepiece/reports/views.py
|
HourlyReport.convert_context_to_csv
|
def convert_context_to_csv(self, context):
"""Convert the context dictionary into a CSV file."""
content = []
date_headers = context['date_headers']
headers = ['Name']
headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
headers.append('Total')
content.append(headers)
summaries = context['summaries']
summary = summaries.get(self.export, [])
for rows, totals in summary:
for name, user_id, hours in rows:
data = [name]
data.extend(hours)
content.append(data)
total = ['Totals']
total.extend(totals)
content.append(total)
return content
|
python
|
def convert_context_to_csv(self, context):
"""Convert the context dictionary into a CSV file."""
content = []
date_headers = context['date_headers']
headers = ['Name']
headers.extend([date.strftime('%m/%d/%Y') for date in date_headers])
headers.append('Total')
content.append(headers)
summaries = context['summaries']
summary = summaries.get(self.export, [])
for rows, totals in summary:
for name, user_id, hours in rows:
data = [name]
data.extend(hours)
content.append(data)
total = ['Totals']
total.extend(totals)
content.append(total)
return content
|
[
"def",
"convert_context_to_csv",
"(",
"self",
",",
"context",
")",
":",
"content",
"=",
"[",
"]",
"date_headers",
"=",
"context",
"[",
"'date_headers'",
"]",
"headers",
"=",
"[",
"'Name'",
"]",
"headers",
".",
"extend",
"(",
"[",
"date",
".",
"strftime",
"(",
"'%m/%d/%Y'",
")",
"for",
"date",
"in",
"date_headers",
"]",
")",
"headers",
".",
"append",
"(",
"'Total'",
")",
"content",
".",
"append",
"(",
"headers",
")",
"summaries",
"=",
"context",
"[",
"'summaries'",
"]",
"summary",
"=",
"summaries",
".",
"get",
"(",
"self",
".",
"export",
",",
"[",
"]",
")",
"for",
"rows",
",",
"totals",
"in",
"summary",
":",
"for",
"name",
",",
"user_id",
",",
"hours",
"in",
"rows",
":",
"data",
"=",
"[",
"name",
"]",
"data",
".",
"extend",
"(",
"hours",
")",
"content",
".",
"append",
"(",
"data",
")",
"total",
"=",
"[",
"'Totals'",
"]",
"total",
".",
"extend",
"(",
"totals",
")",
"content",
".",
"append",
"(",
"total",
")",
"return",
"content"
] |
Convert the context dictionary into a CSV file.
|
[
"Convert",
"the",
"context",
"dictionary",
"into",
"a",
"CSV",
"file",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L155-L177
|
17,999
|
caktus/django-timepiece
|
timepiece/reports/views.py
|
HourlyReport.defaults
|
def defaults(self):
"""Default filter form data when no GET data is provided."""
# Set default date span to previous week.
(start, end) = get_week_window(timezone.now() - relativedelta(days=7))
return {
'from_date': start,
'to_date': end,
'billable': True,
'non_billable': False,
'paid_leave': False,
'trunc': 'day',
'projects': [],
}
|
python
|
def defaults(self):
"""Default filter form data when no GET data is provided."""
# Set default date span to previous week.
(start, end) = get_week_window(timezone.now() - relativedelta(days=7))
return {
'from_date': start,
'to_date': end,
'billable': True,
'non_billable': False,
'paid_leave': False,
'trunc': 'day',
'projects': [],
}
|
[
"def",
"defaults",
"(",
"self",
")",
":",
"# Set default date span to previous week.",
"(",
"start",
",",
"end",
")",
"=",
"get_week_window",
"(",
"timezone",
".",
"now",
"(",
")",
"-",
"relativedelta",
"(",
"days",
"=",
"7",
")",
")",
"return",
"{",
"'from_date'",
":",
"start",
",",
"'to_date'",
":",
"end",
",",
"'billable'",
":",
"True",
",",
"'non_billable'",
":",
"False",
",",
"'paid_leave'",
":",
"False",
",",
"'trunc'",
":",
"'day'",
",",
"'projects'",
":",
"[",
"]",
",",
"}"
] |
Default filter form data when no GET data is provided.
|
[
"Default",
"filter",
"form",
"data",
"when",
"no",
"GET",
"data",
"is",
"provided",
"."
] |
52515dec027664890efbc535429e1ba1ee152f40
|
https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L180-L192
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.