uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0ae2e5867dbafe1c9227f4be | train | class | class msg_getheaders:
__slots__ = ("hashstop", "locator",)
msgtype = b"getheaders"
def __init__(self):
self.locator = CBlockLocator()
self.hashstop = 0
def deserialize(self, f):
self.locator = CBlockLocator()
self.locator.deserialize(f)
self.hashstop = deser_uin... | class msg_getheaders:
| __slots__ = ("hashstop", "locator",)
msgtype = b"getheaders"
def __init__(self):
self.locator = CBlockLocator()
self.hashstop = 0
def deserialize(self, f):
self.locator = CBlockLocator()
self.locator.deserialize(f)
self.hashstop = deser_uint256(f)
def seria... | serialize(self):
return b""
def __repr__(self):
return "msg_sendheaders()"
# getheaders message has
# number of entries
# vector of hashes
# hash_stop (hash of last desired block header, 0 to get as many as possible)
class msg_getheaders:
| 64 | 64 | 152 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_getheaders | msg_getheaders | 1,448 | 1,469 | 1,448 | 1,448 | 93f6b4df67d8eebc853eed520ef56b21237b5e8a | bigcode/the-stack | train |
7d17bcef45c3d418f7bcda79 | train | class | class msg_filteradd:
__slots__ = ("data")
msgtype = b"filteradd"
def __init__(self, data):
self.data = data
def deserialize(self, f):
self.data = deser_string(f)
def serialize(self):
r = b""
r += ser_string(self.data)
return r
def __repr__(self):
... | class msg_filteradd:
| __slots__ = ("data")
msgtype = b"filteradd"
def __init__(self, data):
self.data = data
def deserialize(self, f):
self.data = deser_string(f)
def serialize(self):
r = b""
r += ser_string(self.data)
return r
def __repr__(self):
return "msg_filter... | ("<B", self.nFlags)
return r
def __repr__(self):
return "msg_filterload(data={}, nHashFuncs={}, nTweak={}, nFlags={})".format(
self.data, self.nHashFuncs, self.nTweak, self.nFlags)
class msg_filteradd:
| 64 | 64 | 96 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_filteradd | msg_filteradd | 1,544 | 1,560 | 1,544 | 1,544 | 7c5c75ac3370dc9ca18106fb93fc2f6bf47c32e1 | bigcode/the-stack | train |
bd2de1fd67e05c17eb4e814b | train | class | class msg_sendaddrv2:
__slots__ = ()
msgtype = b"sendaddrv2"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_sendaddrv2()"
| class msg_sendaddrv2:
| __slots__ = ()
msgtype = b"sendaddrv2"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_sendaddrv2()"
| = deser_vector(f, CAddress, "deserialize_v2")
def serialize(self):
return ser_vector(self.addrs, "serialize_v2")
def __repr__(self):
return "msg_addrv2(addrs=%s)" % (repr(self.addrs))
class msg_sendaddrv2:
| 64 | 64 | 71 | 7 | 57 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_sendaddrv2 | msg_sendaddrv2 | 1,175 | 1,189 | 1,175 | 1,175 | 112556f0d037d0c06445233d2077afc94a9ee715 | bigcode/the-stack | train |
36a6283f95b02d17dd8e8988 | train | class | class PrefilledTransaction:
__slots__ = ("index", "tx")
def __init__(self, index=0, tx = None):
self.index = index
self.tx = tx
def deserialize(self, f):
self.index = deser_compact_size(f)
self.tx = CTransaction()
self.tx.deserialize(f)
def serialize(self, with... | class PrefilledTransaction:
| __slots__ = ("index", "tx")
def __init__(self, index=0, tx = None):
self.index = index
self.tx = tx
def deserialize(self, f):
self.index = deser_compact_size(f)
self.tx = CTransaction()
self.tx.deserialize(f)
def serialize(self, with_witness=True):
r = ... | nTime=%s nBits=%08x nNonce=%08x vtx=%s)" \
% (self.nVersion, self.hashPrevBlock, self.hashMerkleRoot,
time.ctime(self.nTime), self.nBits, self.nNonce, repr(self.vtx))
class PrefilledTransaction:
| 64 | 64 | 196 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | PrefilledTransaction | PrefilledTransaction | 792 | 820 | 792 | 792 | 423ce7e3cea7c9e2122c7ac9e9b31d7e96750cc7 | bigcode/the-stack | train |
b76fad035fa41ca52c2fc9fb | train | class | class P2PHeaderAndShortIDs:
__slots__ = ("header", "nonce", "prefilled_txn", "prefilled_txn_length",
"shortids", "shortids_length")
def __init__(self):
self.header = CBlockHeader()
self.nonce = 0
self.shortids_length = 0
self.shortids = []
self.prefilled... | class P2PHeaderAndShortIDs:
| __slots__ = ("header", "nonce", "prefilled_txn", "prefilled_txn_length",
"shortids", "shortids_length")
def __init__(self):
self.header = CBlockHeader()
self.nonce = 0
self.shortids_length = 0
self.shortids = []
self.prefilled_txn_length = 0
self... | ):
r = b""
r += ser_compact_size(self.index)
if with_witness:
r += self.tx.serialize_with_witness()
else:
r += self.tx.serialize_without_witness()
return r
def serialize_without_witness(self):
return self.serialize(with_witness=False)
def... | 140 | 140 | 469 | 9 | 131 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | P2PHeaderAndShortIDs | P2PHeaderAndShortIDs | 824 | 863 | 824 | 824 | 07ce60c0bfde8155dd21da69f3ec809782b5cdbe | bigcode/the-stack | train |
fae2e4b287039570dc0596b9 | train | class | class msg_inv:
__slots__ = ("inv",)
msgtype = b"inv"
def __init__(self, inv=None):
if inv is None:
self.inv = []
else:
self.inv = inv
def deserialize(self, f):
self.inv = deser_vector(f, CInv)
def serialize(self):
return ser_vector(self.inv)... | class msg_inv:
| __slots__ = ("inv",)
msgtype = b"inv"
def __init__(self, inv=None):
if inv is None:
self.inv = []
else:
self.inv = inv
def deserialize(self, f):
self.inv = deser_vector(f, CInv)
def serialize(self):
return ser_vector(self.inv)
def __rep... | = ()
msgtype = b"sendaddrv2"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_sendaddrv2()"
class msg_inv:
| 64 | 64 | 103 | 4 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_inv | msg_inv | 1,192 | 1,209 | 1,192 | 1,192 | 1f3048ecaa9ed73f55eacd9cfb34ae96dd4b6392 | bigcode/the-stack | train |
0f006cc33d9c52d3372e0cb2 | train | function | def calculate_shortid(k0, k1, tx_hash):
expected_shortid = siphash256(k0, k1, tx_hash)
expected_shortid &= 0x0000ffffffffffff
return expected_shortid
| def calculate_shortid(k0, k1, tx_hash):
| expected_shortid = siphash256(k0, k1, tx_hash)
expected_shortid &= 0x0000ffffffffffff
return expected_shortid
| AndShortWitnessIDs(P2PHeaderAndShortIDs):
__slots__ = ()
def serialize(self):
return super().serialize(with_witness=True)
# Calculate the BIP 152-compact blocks shortid for a given transaction hash
def calculate_shortid(k0, k1, tx_hash):
| 64 | 64 | 49 | 13 | 50 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | calculate_shortid | calculate_shortid | 874 | 877 | 874 | 874 | dd6d35ee418faf4d18b997b8834e1cf7606bb321 | bigcode/the-stack | train |
8208f66e34666bac2b8728db | train | class | class COutPoint:
__slots__ = ("hash", "n")
def __init__(self, hash=0, n=0):
self.hash = hash
self.n = n
def deserialize(self, f):
self.hash = deser_uint256(f)
self.n = struct.unpack("<I", f.read(4))[0]
def serialize(self):
r = b""
r += ser_uint256(self.... | class COutPoint:
| __slots__ = ("hash", "n")
def __init__(self, hash=0, n=0):
self.hash = hash
self.n = n
def deserialize(self, f):
self.hash = deser_uint256(f)
self.n = struct.unpack("<I", f.read(4))[0]
def serialize(self):
r = b""
r += ser_uint256(self.hash)
r +... | i", 0) # Bitcoin Core ignores version field. Set it to 0.
r += ser_uint256_vector(self.vHave)
return r
def __repr__(self):
return "CBlockLocator(vHave=%s)" % (repr(self.vHave))
class COutPoint:
| 64 | 64 | 139 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | COutPoint | COutPoint | 363 | 381 | 363 | 363 | 9b9b1ce1d0d7d56e0127c632e3732e0abf29d24f | bigcode/the-stack | train |
51ade63b60a6c466eb6d793d | train | function | def deser_string_vector(f):
nit = deser_compact_size(f)
r = []
for _ in range(nit):
t = deser_string(f)
r.append(t)
return r
| def deser_string_vector(f):
| nit = deser_compact_size(f)
r = []
for _ in range(nit):
t = deser_string(f)
r.append(t)
return r
| _ in range(nit):
t = deser_uint256(f)
r.append(t)
return r
def ser_uint256_vector(l):
r = ser_compact_size(len(l))
for i in l:
r += ser_uint256(i)
return r
def deser_string_vector(f):
| 64 | 64 | 43 | 6 | 57 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | deser_string_vector | deser_string_vector | 177 | 183 | 177 | 177 | febcabb479c90eced1c7529108b6ef055ab9e847 | bigcode/the-stack | train |
a4febb3ae8eb427e2410fc52 | train | class | class msg_getblocks:
__slots__ = ("locator", "hashstop")
msgtype = b"getblocks"
def __init__(self):
self.locator = CBlockLocator()
self.hashstop = 0
def deserialize(self, f):
self.locator = CBlockLocator()
self.locator.deserialize(f)
self.hashstop = deser_uint25... | class msg_getblocks:
| __slots__ = ("locator", "hashstop")
msgtype = b"getblocks"
def __init__(self):
self.locator = CBlockLocator()
self.hashstop = 0
def deserialize(self, f):
self.locator = CBlockLocator()
self.locator.deserialize(f)
self.hashstop = deser_uint256(f)
def seriali... | inv is not None else []
def deserialize(self, f):
self.inv = deser_vector(f, CInv)
def serialize(self):
return ser_vector(self.inv)
def __repr__(self):
return "msg_getdata(inv=%s)" % (repr(self.inv))
class msg_getblocks:
| 64 | 64 | 151 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_getblocks | msg_getblocks | 1,229 | 1,250 | 1,229 | 1,229 | c4cbee137467a56c1b8d9172817b792b5d8ba0f3 | bigcode/the-stack | train |
959753f7390ed4cf93653824 | train | class | class CMerkleBlock:
__slots__ = ("header", "txn")
def __init__(self):
self.header = CBlockHeader()
self.txn = CPartialMerkleTree()
def deserialize(self, f):
self.header.deserialize(f)
self.txn.deserialize(f)
def serialize(self):
r = b""
r += self.header... | class CMerkleBlock:
| __slots__ = ("header", "txn")
def __init__(self):
self.header = CBlockHeader()
self.txn = CPartialMerkleTree()
def deserialize(self, f):
self.header.deserialize(f)
self.txn.deserialize(f)
def serialize(self):
r = b""
r += self.header.serialize()
... | += ser_string(bytes(vBytesArray))
return r
def __repr__(self):
return "CPartialMerkleTree(nTransactions=%d, vHash=%s, vBits=%s)" % (self.nTransactions, repr(self.vHash), repr(self.vBits))
class CMerkleBlock:
| 64 | 64 | 126 | 6 | 58 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | CMerkleBlock | CMerkleBlock | 1,042 | 1,060 | 1,042 | 1,042 | 908242e34fbdfe1fc3b23efd436356bf788bea51 | bigcode/the-stack | train |
947cfdc3fee57ba675e91a16 | train | class | class msg_getdata:
__slots__ = ("inv",)
msgtype = b"getdata"
def __init__(self, inv=None):
self.inv = inv if inv is not None else []
def deserialize(self, f):
self.inv = deser_vector(f, CInv)
def serialize(self):
return ser_vector(self.inv)
def __repr__(self):
... | class msg_getdata:
| __slots__ = ("inv",)
msgtype = b"getdata"
def __init__(self, inv=None):
self.inv = inv if inv is not None else []
def deserialize(self, f):
self.inv = deser_vector(f, CInv)
def serialize(self):
return ser_vector(self.inv)
def __repr__(self):
return "msg_getdat... | :
self.inv = inv
def deserialize(self, f):
self.inv = deser_vector(f, CInv)
def serialize(self):
return ser_vector(self.inv)
def __repr__(self):
return "msg_inv(inv=%s)" % (repr(self.inv))
class msg_getdata:
| 64 | 64 | 98 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_getdata | msg_getdata | 1,212 | 1,226 | 1,212 | 1,212 | 499027063add8137dbca1bf53ed17dcc271e0f6f | bigcode/the-stack | train |
1d5055b899d5f379f1fb8344 | train | class | class msg_getcfilters:
__slots__ = ("filter_type", "start_height", "stop_hash")
msgtype = b"getcfilters"
def __init__(self, filter_type, start_height, stop_hash):
self.filter_type = filter_type
self.start_height = start_height
self.stop_hash = stop_hash
def deserialize(self, f... | class msg_getcfilters:
| __slots__ = ("filter_type", "start_height", "stop_hash")
msgtype = b"getcfilters"
def __init__(self, filter_type, start_height, stop_hash):
self.filter_type = filter_type
self.start_height = start_height
self.stop_hash = stop_hash
def deserialize(self, f):
self.filter_... |
def __repr__(self):
return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions))
class msg_no_witness_blocktxn(msg_blocktxn):
__slots__ = ()
def serialize(self):
return self.block_transactions.serialize(with_witness=False)
class msg_getcfilters:
| 65 | 65 | 218 | 6 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_getcfilters | msg_getcfilters | 1,687 | 1,710 | 1,687 | 1,687 | ae1c126efdf7146b9c6e1068cc35fc130d4fc10a | bigcode/the-stack | train |
301a3297ce645375a1407768 | train | function | def hash256(s):
return sha256(sha256(s))
| def hash256(s):
| return sha256(sha256(s))
| xffffffff >> 2
MSG_WITNESS_TX = MSG_TX | MSG_WITNESS_FLAG
FILTER_TYPE_BASIC = 0
WITNESS_SCALE_FACTOR = 4
# Serialization/deserialization tools
def sha256(s):
return hashlib.new('sha256', s).digest()
def hash256(s):
| 64 | 64 | 14 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | hash256 | hash256 | 71 | 72 | 71 | 71 | d53e1d8d5b5d0556060a0efca20f663e01b96916 | bigcode/the-stack | train |
bc5c25ed98815ea1f9af7c8f | train | function | def ser_string(s):
return ser_compact_size(len(s)) + s
| def ser_string(s):
| return ser_compact_size(len(s)) + s
| struct.unpack("<I", f.read(4))[0]
elif nit == 255:
nit = struct.unpack("<Q", f.read(8))[0]
return nit
def deser_string(f):
nit = deser_compact_size(f)
return f.read(nit)
def ser_string(s):
| 64 | 64 | 17 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | ser_string | ser_string | 100 | 101 | 100 | 100 | 5309412d59ce6a2ef284a2e13835aefd25c7ef86 | bigcode/the-stack | train |
593415a03223011fb6c2f4dd | train | function | def uint256_from_compact(c):
nbytes = (c >> 24) & 0xFF
v = (c & 0xFFFFFF) << (8 * (nbytes - 3))
return v
| def uint256_from_compact(c):
| nbytes = (c >> 24) & 0xFF
v = (c & 0xFFFFFF) << (8 * (nbytes - 3))
return v
|
return rs
def uint256_from_str(s):
r = 0
t = struct.unpack("<IIIIIIII", s[:32])
for i in range(8):
r += t[i] << (i * 32)
return r
def uint256_from_compact(c):
| 64 | 64 | 50 | 8 | 55 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | uint256_from_compact | uint256_from_compact | 127 | 130 | 127 | 127 | f3af217c76e8624ca574d08e2feea039f3fea516 | bigcode/the-stack | train |
d91929d87ae6ea372c297b58 | train | class | class msg_getblocktxn:
__slots__ = ("block_txn_request",)
msgtype = b"getblocktxn"
def __init__(self):
self.block_txn_request = None
def deserialize(self, f):
self.block_txn_request = BlockTransactionsRequest()
self.block_txn_request.deserialize(f)
def serialize(self):
... | class msg_getblocktxn:
| __slots__ = ("block_txn_request",)
msgtype = b"getblocktxn"
def __init__(self):
self.block_txn_request = None
def deserialize(self, f):
self.block_txn_request = BlockTransactionsRequest()
self.block_txn_request.deserialize(f)
def serialize(self):
r = b""
r ... | ids.deserialize(f)
def serialize(self):
r = b""
r += self.header_and_shortids.serialize()
return r
def __repr__(self):
return "msg_cmpctblock(HeaderAndShortIDs=%s)" % repr(self.header_and_shortids)
class msg_getblocktxn:
| 64 | 64 | 126 | 6 | 58 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_getblocktxn | msg_getblocktxn | 1,641 | 1,658 | 1,641 | 1,641 | 45c94743cd956f58b3551668b533e936a8fed8c9 | bigcode/the-stack | train |
a072fdfe095aa33c50b3ef1e | train | class | class msg_wtxidrelay:
__slots__ = ()
msgtype = b"wtxidrelay"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_wtxidrelay()"
| class msg_wtxidrelay:
| __slots__ = ()
msgtype = b"wtxidrelay"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_wtxidrelay()"
| Transaction()):
self.tx = tx
def deserialize(self, f):
self.tx.deserialize(f)
def serialize(self):
return self.tx.serialize_with_witness()
def __repr__(self):
return "msg_tx(tx=%s)" % (repr(self.tx))
class msg_wtxidrelay:
| 64 | 64 | 71 | 7 | 57 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_wtxidrelay | msg_wtxidrelay | 1,269 | 1,283 | 1,269 | 1,269 | 164e52d695c49591821b834e3aac8f8c68bbeeb0 | bigcode/the-stack | train |
363c7a36be25e510487ec304 | train | class | class msg_headers:
__slots__ = ("headers",)
msgtype = b"headers"
def __init__(self, headers=None):
self.headers = headers if headers is not None else []
def deserialize(self, f):
# comment in bitcoind indicates these should be deserialized as blocks
blocks = deser_vector(f, CBl... | class msg_headers:
| __slots__ = ("headers",)
msgtype = b"headers"
def __init__(self, headers=None):
self.headers = headers if headers is not None else []
def deserialize(self, f):
# comment in bitcoind indicates these should be deserialized as blocks
blocks = deser_vector(f, CBlock)
for x ... | _uint256(self.hashstop)
return r
def __repr__(self):
return "msg_getheaders(locator=%s, stop=%064x)" \
% (repr(self.locator), self.hashstop)
# headers message has
# <count> <vector of block headers>
class msg_headers:
| 64 | 64 | 138 | 4 | 60 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_headers | msg_headers | 1,474 | 1,492 | 1,474 | 1,474 | 4d917793cde326ce305ab670e0485e04fd4210ed | bigcode/the-stack | train |
3d0f391f52892e8fce1e1820 | train | class | class CScriptWitness:
__slots__ = ("stack",)
def __init__(self):
# stack is a vector of strings
self.stack = []
def __repr__(self):
return "CScriptWitness(%s)" % \
(",".join([x.hex() for x in self.stack]))
def is_null(self):
if self.stack:
re... | class CScriptWitness:
| __slots__ = ("stack",)
def __init__(self):
# stack is a vector of strings
self.stack = []
def __repr__(self):
return "CScriptWitness(%s)" % \
(",".join([x.hex() for x in self.stack]))
def is_null(self):
if self.stack:
return False
ret... | .scriptPubKey)
return r
def __repr__(self):
return "CTxOut(nValue=%i.%08i scriptPubKey=%s)" \
% (self.nValue // COIN, self.nValue % COIN,
self.scriptPubKey.hex())
class CScriptWitness:
| 64 | 64 | 86 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | CScriptWitness | CScriptWitness | 437 | 451 | 437 | 437 | a8c655cb4aa15519749ad0c38063ed034b99220e | bigcode/the-stack | train |
0f468c166673f4f0114197a0 | train | class | class msg_sendcmpct:
__slots__ = ("announce", "version")
msgtype = b"sendcmpct"
def __init__(self, announce=False, version=1):
self.announce = announce
self.version = version
def deserialize(self, f):
self.announce = struct.unpack("<?", f.read(1))[0]
self.version = stru... | class msg_sendcmpct:
| __slots__ = ("announce", "version")
msgtype = b"sendcmpct"
def __init__(self, announce=False, version=1):
self.announce = announce
self.version = version
def deserialize(self, f):
self.announce = struct.unpack("<?", f.read(1))[0]
self.version = struct.unpack("<Q", f.rea... | ))[0]
def serialize(self):
r = b""
r += struct.pack("<Q", self.feerate)
return r
def __repr__(self):
return "msg_feefilter(feerate=%08x)" % self.feerate
class msg_sendcmpct:
| 64 | 64 | 164 | 6 | 57 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_sendcmpct | msg_sendcmpct | 1,599 | 1,618 | 1,599 | 1,599 | 0b3980db8df29ac9360ceeec4d3fa602b2358d8d | bigcode/the-stack | train |
b8e23acf60dab9eddffdcec4 | train | class | class msg_generic:
__slots__ = ("data")
def __init__(self, msgtype, data=None):
self.msgtype = msgtype
self.data = data
def serialize(self):
return self.data
def __repr__(self):
return "msg_generic()"
| class msg_generic:
| __slots__ = ("data")
def __init__(self, msgtype, data=None):
self.msgtype = msgtype
self.data = data
def serialize(self):
return self.data
def __repr__(self):
return "msg_generic()"
| .block.serialize()
def __repr__(self):
return "msg_block(block=%s)" % (repr(self.block))
# for cases where a user needs tighter control over what is sent over the wire
# note that the user must supply the name of the msgtype, and the data
class msg_generic:
| 64 | 64 | 63 | 4 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_generic | msg_generic | 1,315 | 1,326 | 1,315 | 1,315 | 9d9cc9b26a9a3d76124ebc7650956c62329eaa6c | bigcode/the-stack | train |
0eb3b830ceecb4fac053ddb7 | train | class | class msg_block:
__slots__ = ("block",)
msgtype = b"block"
def __init__(self, block=None):
if block is None:
self.block = CBlock()
else:
self.block = block
def deserialize(self, f):
self.block.deserialize(f)
def serialize(self):
return self.... | class msg_block:
| __slots__ = ("block",)
msgtype = b"block"
def __init__(self, block=None):
if block is None:
self.block = CBlock()
else:
self.block = block
def deserialize(self, f):
self.block.deserialize(f)
def serialize(self):
return self.block.serialize()... | ):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_wtxidrelay()"
class msg_no_witness_tx(msg_tx):
__slots__ = ()
def serialize(self):
return self.tx.serialize_without_witness()
class msg_block:
| 64 | 64 | 99 | 4 | 60 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_block | msg_block | 1,293 | 1,310 | 1,293 | 1,293 | 2061dffb65e4f0db90ede95436a1213bdd75f064 | bigcode/the-stack | train |
4855e1b2c8374b93cfa7541e | train | class | class msg_merkleblock:
__slots__ = ("merkleblock",)
msgtype = b"merkleblock"
def __init__(self, merkleblock=None):
if merkleblock is None:
self.merkleblock = CMerkleBlock()
else:
self.merkleblock = merkleblock
def deserialize(self, f):
self.merkleblock.d... | class msg_merkleblock:
| __slots__ = ("merkleblock",)
msgtype = b"merkleblock"
def __init__(self, merkleblock=None):
if merkleblock is None:
self.merkleblock = CMerkleBlock()
else:
self.merkleblock = merkleblock
def deserialize(self, f):
self.merkleblock.deserialize(f)
def ... | blocks:
self.headers.append(CBlockHeader(x))
def serialize(self):
blocks = [CBlock(x) for x in self.headers]
return ser_vector(blocks)
def __repr__(self):
return "msg_headers(headers=%s)" % repr(self.headers)
class msg_merkleblock:
| 64 | 64 | 133 | 6 | 58 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_merkleblock | msg_merkleblock | 1,495 | 1,512 | 1,495 | 1,495 | 096e8fdae19ec541b5e104b3ad657e5e32d1ade7 | bigcode/the-stack | train |
b4ec8fce2a9fa082a504acd2 | train | class | class CBlockHeader:
__slots__ = ("hash", "hashMerkleRoot", "hashPrevBlock", "nBits", "nNonce",
"nTime", "nVersion", "sha256",
"is_part", "hashWitnessMerkleRoot")
def __init__(self, header=None, is_part=False):
self.is_part = is_part
if header is None:
... | class CBlockHeader:
| __slots__ = ("hash", "hashMerkleRoot", "hashPrevBlock", "nBits", "nNonce",
"nTime", "nVersion", "sha256",
"is_part", "hashWitnessMerkleRoot")
def __init__(self, header=None, is_part=False):
self.is_part = is_part
if header is None:
self.set_null()
... | .hash = hash256(self.serialize_without_witness())[::-1].hex()
def is_valid(self):
self.calc_sha256()
for tout in self.vout:
if tout.nValue < 0 or tout.nValue > 21000000 * COIN:
return False
return True
# Calculate the transaction weight using witness and non... | 230 | 230 | 769 | 5 | 225 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | CBlockHeader | CBlockHeader | 625 | 706 | 625 | 625 | 9f4038dae1bae3e6c0386fee68df5bd371d3ace2 | bigcode/the-stack | train |
935d7db3d2f2117242b3e2fb | train | class | class msg_sendheaders:
__slots__ = ()
msgtype = b"sendheaders"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_sendheaders()"
| class msg_sendheaders:
| __slots__ = ()
msgtype = b"sendheaders"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_sendheaders()"
| self.vec = vec or []
def deserialize(self, f):
self.vec = deser_vector(f, CInv)
def serialize(self):
return ser_vector(self.vec)
def __repr__(self):
return "msg_notfound(vec=%s)" % (repr(self.vec))
class msg_sendheaders:
| 64 | 64 | 65 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_sendheaders | msg_sendheaders | 1,427 | 1,441 | 1,427 | 1,427 | 244ea7d706e9ab2812cf537843645fe89a63db38 | bigcode/the-stack | train |
8449b971546dbe6e33073cc0 | train | class | class msg_addrv2:
__slots__ = ("addrs",)
msgtype = b"addrv2"
def __init__(self):
self.addrs = []
def deserialize(self, f):
self.addrs = deser_vector(f, CAddress, "deserialize_v2")
def serialize(self):
return ser_vector(self.addrs, "serialize_v2")
def __repr__(self):
... | class msg_addrv2:
| __slots__ = ("addrs",)
msgtype = b"addrv2"
def __init__(self):
self.addrs = []
def deserialize(self, f):
self.addrs = deser_vector(f, CAddress, "deserialize_v2")
def serialize(self):
return ser_vector(self.addrs, "serialize_v2")
def __repr__(self):
return "msg... | = []
def deserialize(self, f):
self.addrs = deser_vector(f, CAddress)
def serialize(self):
return ser_vector(self.addrs)
def __repr__(self):
return "msg_addr(addrs=%s)" % (repr(self.addrs))
class msg_addrv2:
| 64 | 64 | 107 | 6 | 58 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_addrv2 | msg_addrv2 | 1,158 | 1,172 | 1,158 | 1,158 | c363ce7f04d940190be5b7aa9655f31dadd732d8 | bigcode/the-stack | train |
f29a29b512d558af9c144937 | train | class | class msg_no_witness_tx(msg_tx):
__slots__ = ()
def serialize(self):
return self.tx.serialize_without_witness()
| class msg_no_witness_tx(msg_tx):
| __slots__ = ()
def serialize(self):
return self.tx.serialize_without_witness()
| = b"wtxidrelay"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_wtxidrelay()"
class msg_no_witness_tx(msg_tx):
| 64 | 64 | 29 | 9 | 54 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_no_witness_tx | msg_no_witness_tx | 1,286 | 1,290 | 1,286 | 1,286 | e389fd486d06500d733eba87013791c9e91cd07b | bigcode/the-stack | train |
85a3e014d24543b2ed5bc5ad | train | class | class msg_filterload:
__slots__ = ("data", "nHashFuncs", "nTweak", "nFlags")
msgtype = b"filterload"
def __init__(self, data=b'00', nHashFuncs=0, nTweak=0, nFlags=0):
self.data = data
self.nHashFuncs = nHashFuncs
self.nTweak = nTweak
self.nFlags = nFlags
def deserialize... | class msg_filterload:
| __slots__ = ("data", "nHashFuncs", "nTweak", "nFlags")
msgtype = b"filterload"
def __init__(self, data=b'00', nHashFuncs=0, nTweak=0, nFlags=0):
self.data = data
self.nHashFuncs = nHashFuncs
self.nTweak = nTweak
self.nFlags = nFlags
def deserialize(self, f):
sel... | leBlock()
else:
self.merkleblock = merkleblock
def deserialize(self, f):
self.merkleblock.deserialize(f)
def serialize(self):
return self.merkleblock.serialize()
def __repr__(self):
return "msg_merkleblock(merkleblock=%s)" % (repr(self.merkleblock))
class msg_f... | 82 | 82 | 276 | 5 | 77 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_filterload | msg_filterload | 1,515 | 1,541 | 1,515 | 1,515 | d5bd34d969f8b3c73836bd76b010ad44654afbfa | bigcode/the-stack | train |
2cc954b9354b67deb57abf90 | train | class | class msg_no_witness_block(msg_block):
__slots__ = ()
def serialize(self):
return self.block.serialize(with_witness=False)
| class msg_no_witness_block(msg_block):
| __slots__ = ()
def serialize(self):
return self.block.serialize(with_witness=False)
| = ("data")
def __init__(self, msgtype, data=None):
self.msgtype = msgtype
self.data = data
def serialize(self):
return self.data
def __repr__(self):
return "msg_generic()"
class msg_no_witness_block(msg_block):
| 64 | 64 | 30 | 9 | 54 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_no_witness_block | msg_no_witness_block | 1,329 | 1,332 | 1,329 | 1,329 | 20dee0c9f2d86bbb54499b4b6cd23fe00ce4b3ae | bigcode/the-stack | train |
824300ffa8553dbdab642c34 | train | class | class BlockTransactions:
__slots__ = ("blockhash", "transactions")
def __init__(self, blockhash=0, transactions = None):
self.blockhash = blockhash
self.transactions = transactions if transactions is not None else []
def deserialize(self, f):
self.blockhash = deser_uint256(f)
... | class BlockTransactions:
| __slots__ = ("blockhash", "transactions")
def __init__(self, blockhash=0, transactions = None):
self.blockhash = blockhash
self.transactions = transactions if transactions is not None else []
def deserialize(self, f):
self.blockhash = deser_uint256(f)
self.transactions = de... | .indexes:
absolute_indexes.append(x+last_index+1)
last_index = absolute_indexes[-1]
return absolute_indexes
def __repr__(self):
return "BlockTransactionsRequest(hash=%064x indexes=%s)" % (self.blockhash, repr(self.indexes))
class BlockTransactions:
| 64 | 64 | 177 | 4 | 60 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | BlockTransactions | BlockTransactions | 988 | 1,009 | 988 | 988 | fa4565dcb37a34d361d4455e645b5fc0397f03cc | bigcode/the-stack | train |
cefeeaddd0067f2b5930dfc9 | train | class | class CInv:
__slots__ = ("hash", "type")
typemap = {
0: "Error",
MSG_TX: "TX",
MSG_BLOCK: "Block",
MSG_TX | MSG_WITNESS_FLAG: "WitnessTx",
MSG_BLOCK | MSG_WITNESS_FLAG: "WitnessBlock",
MSG_FILTERED_BLOCK: "filtered Block",
MSG_CMPCT_BLOCK: "CompactBlock",... | class CInv:
| __slots__ = ("hash", "type")
typemap = {
0: "Error",
MSG_TX: "TX",
MSG_BLOCK: "Block",
MSG_TX | MSG_WITNESS_FLAG: "WitnessTx",
MSG_BLOCK | MSG_WITNESS_FLAG: "WitnessBlock",
MSG_FILTERED_BLOCK: "filtered Block",
MSG_CMPCT_BLOCK: "CompactBlock",
MSG... | )] + self.I2P_PAD, True)
r += struct.pack(">H", self.port)
return r
def __repr__(self):
return ("CAddress(nServices=%i net=%s addr=%s port=%i)"
% (self.nServices, self.ADDRV2_NET_NAME[self.net], self.ip, self.port))
class CInv:
| 77 | 77 | 258 | 4 | 73 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | CInv | CInv | 307 | 340 | 307 | 307 | 2bce69bcd778676ae623352d31847d286649ce25 | bigcode/the-stack | train |
6f65ba7adf931697148700f0 | train | class | class msg_blocktxn:
__slots__ = ("block_transactions",)
msgtype = b"blocktxn"
def __init__(self):
self.block_transactions = BlockTransactions()
def deserialize(self, f):
self.block_transactions.deserialize(f)
def serialize(self):
r = b""
r += self.block_transaction... | class msg_blocktxn:
| __slots__ = ("block_transactions",)
msgtype = b"blocktxn"
def __init__(self):
self.block_transactions = BlockTransactions()
def deserialize(self, f):
self.block_transactions.deserialize(f)
def serialize(self):
r = b""
r += self.block_transactions.serialize()
... | _request.deserialize(f)
def serialize(self):
r = b""
r += self.block_txn_request.serialize()
return r
def __repr__(self):
return "msg_getblocktxn(block_txn_request=%s)" % (repr(self.block_txn_request))
class msg_blocktxn:
| 64 | 64 | 101 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_blocktxn | msg_blocktxn | 1,661 | 1,677 | 1,661 | 1,661 | bbf117cb56d2570f1c14196dcf6bc4be3b1915b1 | bigcode/the-stack | train |
420cf27b3bec378f57d920d5 | train | function | def sha256(s):
return hashlib.new('sha256', s).digest()
| def sha256(s):
| return hashlib.new('sha256', s).digest()
| _WITNESS_FLAG = 1 << 30
MSG_TYPE_MASK = 0xffffffff >> 2
MSG_WITNESS_TX = MSG_TX | MSG_WITNESS_FLAG
FILTER_TYPE_BASIC = 0
WITNESS_SCALE_FACTOR = 4
# Serialization/deserialization tools
def sha256(s):
| 64 | 64 | 17 | 5 | 58 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | sha256 | sha256 | 68 | 69 | 68 | 68 | d856fa315d3189b434c52c9b9666fcbc8c1d528c | bigcode/the-stack | train |
d17555bbac6232da0abf49c0 | train | class | class msg_no_witness_blocktxn(msg_blocktxn):
__slots__ = ()
def serialize(self):
return self.block_transactions.serialize(with_witness=False)
| class msg_no_witness_blocktxn(msg_blocktxn):
| __slots__ = ()
def serialize(self):
return self.block_transactions.serialize(with_witness=False)
| .block_transactions.deserialize(f)
def serialize(self):
r = b""
r += self.block_transactions.serialize()
return r
def __repr__(self):
return "msg_blocktxn(block_transactions=%s)" % (repr(self.block_transactions))
class msg_no_witness_blocktxn(msg_blocktxn):
| 64 | 64 | 33 | 11 | 53 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_no_witness_blocktxn | msg_no_witness_blocktxn | 1,680 | 1,684 | 1,680 | 1,680 | 40ea3c0bef736d28d43ed2a6a1bba97ac1a766c5 | bigcode/the-stack | train |
90a93c6391fb5afc4514bd2d | train | function | def uint256_from_str(s):
r = 0
t = struct.unpack("<IIIIIIII", s[:32])
for i in range(8):
r += t[i] << (i * 32)
return r
| def uint256_from_str(s):
| r = 0
t = struct.unpack("<IIIIIIII", s[:32])
for i in range(8):
r += t[i] << (i * 32)
return r
| t << (i * 32)
return r
def ser_uint256(u):
rs = b""
for _ in range(8):
rs += struct.pack("<I", u & 0xFFFFFFFF)
u >>= 32
return rs
def uint256_from_str(s):
| 64 | 64 | 51 | 7 | 56 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | uint256_from_str | uint256_from_str | 119 | 124 | 119 | 119 | 1542beb9f545ee20bd3180690796d7e47d01324f | bigcode/the-stack | train |
a968526fc71e6eef165cd6c2 | train | function | def deser_uint256_vector(f):
nit = deser_compact_size(f)
r = []
for _ in range(nit):
t = deser_uint256(f)
r.append(t)
return r
| def deser_uint256_vector(f):
| nit = deser_compact_size(f)
r = []
for _ in range(nit):
t = deser_uint256(f)
r.append(t)
return r
| ).
def ser_vector(l, ser_function_name=None):
r = ser_compact_size(len(l))
for i in l:
if ser_function_name:
r += getattr(i, ser_function_name)()
else:
r += i.serialize()
return r
def deser_uint256_vector(f):
| 64 | 64 | 45 | 7 | 56 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | deser_uint256_vector | deser_uint256_vector | 161 | 167 | 161 | 161 | 3b669c743542540c7f47ea9cf7ce392aac2ef0f2 | bigcode/the-stack | train |
2b21f04b712c25ee38802921 | train | class | class CTxIn:
__slots__ = ("nSequence", "prevout", "scriptSig")
def __init__(self, outpoint=None, scriptSig=b"", nSequence=0):
if outpoint is None:
self.prevout = COutPoint()
else:
self.prevout = outpoint
self.scriptSig = scriptSig
self.nSequence = nSequen... | class CTxIn:
| __slots__ = ("nSequence", "prevout", "scriptSig")
def __init__(self, outpoint=None, scriptSig=b"", nSequence=0):
if outpoint is None:
self.prevout = COutPoint()
else:
self.prevout = outpoint
self.scriptSig = scriptSig
self.nSequence = nSequence
def d... | (self):
r = b""
r += ser_uint256(self.hash)
r += struct.pack("<I", self.n)
return r
def __repr__(self):
return "COutPoint(hash=%064x n=%i)" % (self.hash, self.n)
class CTxIn:
| 66 | 66 | 223 | 5 | 61 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | CTxIn | CTxIn | 384 | 411 | 384 | 384 | cdd4b710ebd5197b9d64ceb02b7255d3be3136ad | bigcode/the-stack | train |
dd091cdd7e25180a4dbcdf89 | train | class | class msg_feefilter:
__slots__ = ("feerate",)
msgtype = b"feefilter"
def __init__(self, feerate=0):
self.feerate = feerate
def deserialize(self, f):
self.feerate = struct.unpack("<Q", f.read(8))[0]
def serialize(self):
r = b""
r += struct.pack("<Q", self.feerate)
... | class msg_feefilter:
| __slots__ = ("feerate",)
msgtype = b"feefilter"
def __init__(self, feerate=0):
self.feerate = feerate
def deserialize(self, f):
self.feerate = struct.unpack("<Q", f.read(8))[0]
def serialize(self):
r = b""
r += struct.pack("<Q", self.feerate)
return r
... | slots__ = ()
msgtype = b"filterclear"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_filterclear()"
class msg_feefilter:
| 64 | 64 | 129 | 6 | 57 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_feefilter | msg_feefilter | 1,580 | 1,596 | 1,580 | 1,580 | 2bdc9647d3b452fb123bc77edaa46e29e32bcb8f | bigcode/the-stack | train |
33257e03acadcbabbe811fea | train | class | class CTransaction:
__slots__ = ("hash", "nLockTime", "nVersion", "sha256", "vin", "vout",
"wit")
def __init__(self, tx=None):
if tx is None:
self.nVersion = 1
self.vin = []
self.vout = []
self.wit = CTxWitness()
self.nLockTim... | class CTransaction:
| __slots__ = ("hash", "nLockTime", "nVersion", "sha256", "vin", "vout",
"wit")
def __init__(self, tx=None):
if tx is None:
self.nVersion = 1
self.vin = []
self.vout = []
self.wit = CTxWitness()
self.nLockTime = 0
se... | self.scriptWitness.stack = deser_string_vector(f)
def serialize(self):
return ser_string_vector(self.scriptWitness.stack)
def __repr__(self):
return repr(self.scriptWitness)
def is_null(self):
return self.scriptWitness.is_null()
class CTxWitness:
__slots__ = ("vtxinwit",)
... | 256 | 256 | 1,098 | 4 | 251 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | CTransaction | CTransaction | 503 | 622 | 503 | 503 | 2e1aef1a2df3377ca96b938659d85f8de0d070ed | bigcode/the-stack | train |
cd855dc3b376d35b901bb8e7 | train | function | def tx_from_hex(hex_string):
"""Deserialize from hex string to a transaction object"""
return from_hex(CTransaction(), hex_string)
| def tx_from_hex(hex_string):
| """Deserialize from hex string to a transaction object"""
return from_hex(CTransaction(), hex_string)
| Note that there is no complementary helper like e.g. `to_hex` for the
inverse operation. To serialize a message object to a hex string, simply
use obj.serialize().hex()"""
obj.deserialize(BytesIO(bytes.fromhex(hex_string)))
return obj
def tx_from_hex(hex_string):
| 64 | 64 | 28 | 7 | 56 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | tx_from_hex | tx_from_hex | 203 | 205 | 203 | 203 | aef660381c3177b1a103cdb7bb5d0b5dbf260f6d | bigcode/the-stack | train |
9d808071415538236394c8c1 | train | class | class msg_getcfheaders:
__slots__ = ("filter_type", "start_height", "stop_hash")
msgtype = b"getcfheaders"
def __init__(self, filter_type, start_height, stop_hash):
self.filter_type = filter_type
self.start_height = start_height
self.stop_hash = stop_hash
def deserialize(self,... | class msg_getcfheaders:
| __slots__ = ("filter_type", "start_height", "stop_hash")
msgtype = b"getcfheaders"
def __init__(self, filter_type, start_height, stop_hash):
self.filter_type = filter_type
self.start_height = start_height
self.stop_hash = stop_hash
def deserialize(self, f):
self.filter... | r += ser_uint256(self.block_hash)
r += ser_string(self.filter_data)
return r
def __repr__(self):
return "msg_cfilter(filter_type={:#x}, block_hash={:x})".format(
self.filter_type, self.block_hash)
class msg_getcfheaders:
| 65 | 65 | 219 | 6 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_getcfheaders | msg_getcfheaders | 1,737 | 1,760 | 1,737 | 1,737 | 1b46960d559516970b7b3c8dfd210983215f2170 | bigcode/the-stack | train |
0807ec025494748137e97e96 | train | class | class msg_filterclear:
__slots__ = ()
msgtype = b"filterclear"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_filterclear()"
| class msg_filterclear:
| __slots__ = ()
msgtype = b"filterclear"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_filterclear()"
| def deserialize(self, f):
self.data = deser_string(f)
def serialize(self):
r = b""
r += ser_string(self.data)
return r
def __repr__(self):
return "msg_filteradd(data={})".format(self.data)
class msg_filterclear:
| 64 | 64 | 65 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_filterclear | msg_filterclear | 1,563 | 1,577 | 1,563 | 1,563 | 14dcb57a3a4b97950ecdbb79bd85d02bc3d72100 | bigcode/the-stack | train |
7ee8d053b11cfb2cb49e558f | train | class | class msg_cfheaders:
__slots__ = ("filter_type", "stop_hash", "prev_header", "hashes")
msgtype = b"cfheaders"
def __init__(self, filter_type=None, stop_hash=None, prev_header=None, hashes=None):
self.filter_type = filter_type
self.stop_hash = stop_hash
self.prev_header = prev_heade... | class msg_cfheaders:
| __slots__ = ("filter_type", "stop_hash", "prev_header", "hashes")
msgtype = b"cfheaders"
def __init__(self, filter_type=None, stop_hash=None, prev_header=None, hashes=None):
self.filter_type = filter_type
self.stop_hash = stop_hash
self.prev_header = prev_header
self.hashes... | ("<I", self.start_height)
r += ser_uint256(self.stop_hash)
return r
def __repr__(self):
return "msg_getcfheaders(filter_type={:#x}, start_height={}, stop_hash={:x})".format(
self.filter_type, self.start_height, self.stop_hash)
class msg_cfheaders:
| 71 | 71 | 239 | 5 | 66 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_cfheaders | msg_cfheaders | 1,762 | 1,788 | 1,762 | 1,762 | a586e11001814193e42e4870778a52299159121c | bigcode/the-stack | train |
5b53ba60b3fdfa9dcedf9376 | train | class | class CTxWitness:
__slots__ = ("vtxinwit",)
def __init__(self):
self.vtxinwit = []
def deserialize(self, f):
for i in range(len(self.vtxinwit)):
self.vtxinwit[i].deserialize(f)
def serialize(self):
r = b""
# This is different than the usual vector serializa... | class CTxWitness:
| __slots__ = ("vtxinwit",)
def __init__(self):
self.vtxinwit = []
def deserialize(self, f):
for i in range(len(self.vtxinwit)):
self.vtxinwit[i].deserialize(f)
def serialize(self):
r = b""
# This is different than the usual vector serialization --
# ... | deserialize(self, f):
self.scriptWitness.stack = deser_string_vector(f)
def serialize(self):
return ser_string_vector(self.scriptWitness.stack)
def __repr__(self):
return repr(self.scriptWitness)
def is_null(self):
return self.scriptWitness.is_null()
class CTxWitness:
| 64 | 64 | 199 | 5 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | CTxWitness | CTxWitness | 473 | 500 | 473 | 473 | 9f3b8fcd6419bba46da06b2e934ab59622d66a39 | bigcode/the-stack | train |
b26439e7db0ae895f3dfe699 | train | function | def ser_compact_size(l):
r = b""
if l < 253:
r = struct.pack("B", l)
elif l < 0x10000:
r = struct.pack("<BH", 253, l)
elif l < 0x100000000:
r = struct.pack("<BI", 254, l)
else:
r = struct.pack("<BQ", 255, l)
return r
| def ser_compact_size(l):
| r = b""
if l < 253:
r = struct.pack("B", l)
elif l < 0x10000:
r = struct.pack("<BH", 253, l)
elif l < 0x100000000:
r = struct.pack("<BI", 254, l)
else:
r = struct.pack("<BQ", 255, l)
return r
| ITNESS_FLAG
FILTER_TYPE_BASIC = 0
WITNESS_SCALE_FACTOR = 4
# Serialization/deserialization tools
def sha256(s):
return hashlib.new('sha256', s).digest()
def hash256(s):
return sha256(sha256(s))
def ser_compact_size(l):
| 64 | 64 | 97 | 7 | 57 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | ser_compact_size | ser_compact_size | 74 | 84 | 74 | 74 | 0fd42c0eb00457f0aa992da1600c4d7a1b83176d | bigcode/the-stack | train |
c63ea8046fcddd919ddfb628 | train | class | class HeaderAndShortIDs:
__slots__ = ("header", "nonce", "prefilled_txn", "shortids", "use_witness")
def __init__(self, p2pheaders_and_shortids = None):
self.header = CBlockHeader()
self.nonce = 0
self.shortids = []
self.prefilled_txn = []
self.use_witness = False
... | class HeaderAndShortIDs:
| __slots__ = ("header", "nonce", "prefilled_txn", "shortids", "use_witness")
def __init__(self, p2pheaders_and_shortids = None):
self.header = CBlockHeader()
self.nonce = 0
self.shortids = []
self.prefilled_txn = []
self.use_witness = False
if p2pheaders_and_shor... | , prefilled_txn_length=%d, prefilledtxn=%s" % (repr(self.header), self.nonce, self.shortids_length, repr(self.shortids), self.prefilled_txn_length, repr(self.prefilled_txn))
# P2P version of the above that will use witness serialization (for compact
# block version 2)
class P2PHeaderAndShortWitnessIDs(P2PHeaderAndSho... | 211 | 211 | 706 | 6 | 205 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | HeaderAndShortIDs | HeaderAndShortIDs | 882 | 944 | 882 | 882 | 6322e13a26411daf2cdd1305d935a0d29a8c1975 | bigcode/the-stack | train |
43f213572350b51bce09823c | train | function | def ser_uint256(u):
rs = b""
for _ in range(8):
rs += struct.pack("<I", u & 0xFFFFFFFF)
u >>= 32
return rs
| def ser_uint256(u):
| rs = b""
for _ in range(8):
rs += struct.pack("<I", u & 0xFFFFFFFF)
u >>= 32
return rs
| act_size(len(s)) + s
def deser_uint256(f):
r = 0
for i in range(8):
t = struct.unpack("<I", f.read(4))[0]
r += t << (i * 32)
return r
def ser_uint256(u):
| 64 | 64 | 45 | 6 | 57 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | ser_uint256 | ser_uint256 | 111 | 116 | 111 | 111 | 18bfab2d051c62fd5e0b45f502d0937f8e5c988a | bigcode/the-stack | train |
b40a57700b7a57e7adb1c680 | train | class | class msg_addr:
__slots__ = ("addrs",)
msgtype = b"addr"
def __init__(self):
self.addrs = []
def deserialize(self, f):
self.addrs = deser_vector(f, CAddress)
def serialize(self):
return ser_vector(self.addrs)
def __repr__(self):
return "msg_addr(addrs=%s)" % (... | class msg_addr:
| __slots__ = ("addrs",)
msgtype = b"addr"
def __init__(self):
self.addrs = []
def deserialize(self, f):
self.addrs = deser_vector(f, CAddress)
def serialize(self):
return ser_vector(self.addrs)
def __repr__(self):
return "msg_addr(addrs=%s)" % (repr(self.addrs)... | __slots__ = ()
msgtype = b"verack"
def __init__(self):
pass
def deserialize(self, f):
pass
def serialize(self):
return b""
def __repr__(self):
return "msg_verack()"
class msg_addr:
| 64 | 64 | 91 | 4 | 59 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_addr | msg_addr | 1,141 | 1,155 | 1,141 | 1,141 | 69a0349dcb15aae16d4f36c90547fa2ae482f009 | bigcode/the-stack | train |
b421c5726f4367f9660b1d31 | train | class | class msg_cmpctblock:
__slots__ = ("header_and_shortids",)
msgtype = b"cmpctblock"
def __init__(self, header_and_shortids = None):
self.header_and_shortids = header_and_shortids
def deserialize(self, f):
self.header_and_shortids = P2PHeaderAndShortIDs()
self.header_and_shortids... | class msg_cmpctblock:
| __slots__ = ("header_and_shortids",)
msgtype = b"cmpctblock"
def __init__(self, header_and_shortids = None):
self.header_and_shortids = header_and_shortids
def deserialize(self, f):
self.header_and_shortids = P2PHeaderAndShortIDs()
self.header_and_shortids.deserialize(f)
d... | r += struct.pack("<?", self.announce)
r += struct.pack("<Q", self.version)
return r
def __repr__(self):
return "msg_sendcmpct(announce=%s, version=%lu)" % (self.announce, self.version)
class msg_cmpctblock:
| 64 | 64 | 139 | 6 | 58 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | msg_cmpctblock | msg_cmpctblock | 1,621 | 1,638 | 1,621 | 1,621 | 544768bee9d47e609eb41a56d463957263a8a4e5 | bigcode/the-stack | train |
f7dce7fd038330e394a331d7 | train | function | def deser_vector(f, c, deser_function_name=None):
nit = deser_compact_size(f)
r = []
for _ in range(nit):
t = c()
if deser_function_name:
getattr(t, deser_function_name)(f)
else:
t.deserialize(f)
r.append(t)
return r
| def deser_vector(f, c, deser_function_name=None):
| nit = deser_compact_size(f)
r = []
for _ in range(nit):
t = c()
if deser_function_name:
getattr(t, deser_function_name)(f)
else:
t.deserialize(f)
r.append(t)
return r
| 0xFF
v = (c & 0xFFFFFF) << (8 * (nbytes - 3))
return v
# deser_function_name: Allow for an alternate deserialization function on the
# entries in the vector.
def deser_vector(f, c, deser_function_name=None):
| 64 | 64 | 71 | 12 | 52 | dmuralov/particl-core | test/functional/test_framework/messages.py | Python | deser_vector | deser_vector | 135 | 145 | 135 | 135 | d4a375ce1a495d07ba5e7b4ffd426cda57ab7b7d | bigcode/the-stack | train |
eb5557bbca0df5d664875b0e | train | class | class Team(models.Model):
users: models.ManyToManyField = models.ManyToManyField(User, blank=True)
api_token: models.CharField = models.CharField(
max_length=200, null=True, blank=True
)
signup_token: models.CharField = models.CharField(
max_length=200, null=True, blank=True
)
ap... | class Team(models.Model):
| users: models.ManyToManyField = models.ManyToManyField(User, blank=True)
api_token: models.CharField = models.CharField(
max_length=200, null=True, blank=True
)
signup_token: models.CharField = models.CharField(
max_length=200, null=True, blank=True
)
app_urls: ArrayField = Array... | Table', 'breakdown': '$browser'}
)
DashboardItem.objects.create(team=team, name='Daily Active Users', type='ActionsLineGraph', filters={TREND_FILTER_TYPE_EVENTS: [{'id': '$pageview', 'math': 'dau', 'type': TREND_FILTER_TYPE_EVENTS}]})
return team
class Team(models.Model):
| 73 | 73 | 244 | 5 | 67 | Jujhar/posthog | posthog/models/team.py | Python | Team | Team | 36 | 62 | 36 | 36 | 7bae3ab557118fce71fc62e44624fefbfdcb0919 | bigcode/the-stack | train |
4c50bd5a7707f467e24b239f | train | class | class TeamManager(models.Manager):
def create_with_data(self, users: Optional[List[User]], **kwargs):
kwargs["api_token"] = kwargs.get("api_token", secrets.token_urlsafe(32))
kwargs["signup_token"] = kwargs.get("signup_token", secrets.token_urlsafe(22))
team = Team.objects.create(**kwargs)
... | class TeamManager(models.Manager):
| def create_with_data(self, users: Optional[List[User]], **kwargs):
kwargs["api_token"] = kwargs.get("api_token", secrets.token_urlsafe(32))
kwargs["signup_token"] = kwargs.get("signup_token", secrets.token_urlsafe(22))
team = Team.objects.create(**kwargs)
if users:
team.u... | from django.db import models
from django.contrib.postgres.fields import JSONField, ArrayField
from .action import Action
from .action_step import ActionStep
from .dashboard import DashboardItem
from .user import User
from posthog.constants import TREND_FILTER_TYPE_EVENTS
from typing import Optional, List
import secret... | 73 | 84 | 282 | 6 | 66 | Jujhar/posthog | posthog/models/team.py | Python | TeamManager | TeamManager | 13 | 33 | 13 | 13 | cb4d0caa2ba61640593bf8e097002da50da0d97b | bigcode/the-stack | train |
8211dfcd82b5cd3f01814adc | train | function | def retrive_definition(word):
#Removing the case-sensitivity from the program
#For example 'Rain' and 'rain' will give same output
#Converting all letters to lower because out data is in that format
word = word.lower()
#Check for non existing words
#1st elif: To make sure the program return the... | def retrive_definition(word):
#Removing the case-sensitivity from the program
#For example 'Rain' and 'rain' will give same output
#Converting all letters to lower because out data is in that format
| word = word.lower()
#Check for non existing words
#1st elif: To make sure the program return the definition of words that start with a capital letter (e.g. Delhi, Texas)
#2nd elif: To make sure the program return the definition of acronyms (e.g. USA, NATO)
#3rd elif: To find a similar word
#-- ... | #Loading the json data as python dictionary
#Try typing "type(data)" in terminal after executing first two line of this snippet
data = json.load(open(r"C:\Users\admin\Downloads\data.json"))
#Function for retriving definition
def retrive_definition(word):
#Removing the case-sensitivity from the program
#For exam... | 99 | 99 | 330 | 49 | 49 | theprogrammedwords/pyDictionary | dictionary_7.py | Python | retrive_definition | retrive_definition | 9 | 35 | 9 | 12 | 4951086f4c8db11eaa222daae360d5e0a5515eca | bigcode/the-stack | train |
63fd6096a185b861e8fd8199 | train | function | def script():
import docopt
arguments = docopt.docopt(__doc__)
g = GiffGaff(
arguments['USER'],
getpass.getpass('Password for %s: ' % arguments['USER'])
)
if arguments['balance']:
for k, v in g.balance().items():
print("%s: %s" % (k, v))
elif arguments['rece... | def script():
| import docopt
arguments = docopt.docopt(__doc__)
g = GiffGaff(
arguments['USER'],
getpass.getpass('Password for %s: ' % arguments['USER'])
)
if arguments['balance']:
for k, v in g.balance().items():
print("%s: %s" % (k, v))
elif arguments['receipts']:
... | datetime.datetime.strftime(o['date'], '%Y-%m-%d'), o['id']))
if not os.path.exists(path) and o['paid_with'] == 'VISA':
print("Downloading to %s" % path)
self.vat_receipt(o['id'], path)
def script():
| 64 | 64 | 107 | 3 | 61 | lentinj/scrapegaff | scrapegaff.py | Python | script | script | 101 | 114 | 101 | 101 | 03e568c13d3d9ba979397ceb46ce4f41cfaf5e4e | bigcode/the-stack | train |
46d8b8e237f34f218a279495 | train | class | class GiffGaff():
base_url = "https://www.giffgaff.com"
def _page(self, path, post_data=None, xhr=False, debug=False):
HTTPConnection.debuglevel = 1 if debug else 0
if not hasattr(self, '_s'):
self._s = requests.Session()
self._s.keep_alive = False
url = self.bas... | class GiffGaff():
| base_url = "https://www.giffgaff.com"
def _page(self, path, post_data=None, xhr=False, debug=False):
HTTPConnection.debuglevel = 1 if debug else 0
if not hasattr(self, '_s'):
self._s = requests.Session()
self._s.keep_alive = False
url = self.base_url + path
... | """GiffGaff API interface.
Usage:
giffgaff USER balance
giffgaff USER receipts
"""
import datetime
import getpass
import os
import os.path
import logging
import re
from http.client import HTTPConnection
from lxml import html, etree
import requests
class GiffGaff():
| 71 | 232 | 776 | 6 | 64 | lentinj/scrapegaff | scrapegaff.py | Python | GiffGaff | GiffGaff | 19 | 98 | 19 | 19 | 947d06998670ecfe1e04ea2f694fb3683fabb568 | bigcode/the-stack | train |
c68cbf8f65d2341a07efb05f | train | class | class UserAdmin(BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None, {"fields": ('email', 'password'), }),
(_('Personal Info'), {'fields': ('name',)}),
(
_('Permissions'),
{'fields': ('is_active', 'is_staff', 'is_superuser')}... | class UserAdmin(BaseUserAdmin):
| ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None, {"fields": ('email', 'password'), }),
(_('Personal Info'), {'fields': ('name',)}),
(
_('Permissions'),
{'fields': ('is_active', 'is_staff', 'is_superuser')}
),
(_('Importan... | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from core import models
class UserAdmin(BaseUserAdmin):
| 40 | 64 | 97 | 7 | 32 | akashjadhav3/django-recipe-app-api | app/core/admin.py | Python | UserAdmin | UserAdmin | 8 | 19 | 8 | 8 | 7d9e9df3d2d92fd3b97a58e4609b71d71359d47a | bigcode/the-stack | train |
aa72c47177dc6800b9399e0b | train | class | @engine.configure(name="MultihostEngine")
class MultihostEngine(engine.Engine):
"""Deploy multihost cloud with existing engines.
Sample configuration:
{
"type": "MultihostEngine",
"controller": {
"type": "DevstackEngine",
"provider": {
... | @engine.configure(name="MultihostEngine")
class MultihostEngine(engine.Engine):
| """Deploy multihost cloud with existing engines.
Sample configuration:
{
"type": "MultihostEngine",
"controller": {
"type": "DevstackEngine",
"provider": {
"type": "DummyProvider"
}
},
"... | file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CO... | 162 | 162 | 542 | 18 | 143 | hellboy2k8/rally | rally/deployment/engines/multihost.py | Python | MultihostEngine | MultihostEngine | 27 | 101 | 27 | 28 | 42c1fe380256f8e2151ebf4d41ff55385bb7c8a5 | bigcode/the-stack | train |
0cfbd26d6b195e284cc560ea | train | class | class VirtualNetworkGatewaysOperations(object):
"""VirtualNetworkGatewaysOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this o... | class VirtualNetworkGatewaysOperations(object):
| """VirtualNetworkGatewaysOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.ne... | c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# ---------------------------------... | 256 | 256 | 24,433 | 8 | 248 | vbarbaresi/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_09_01/operations/_virtual_network_gateways_operations.py | Python | VirtualNetworkGatewaysOperations | VirtualNetworkGatewaysOperations | 28 | 2,267 | 28 | 28 | 0fef70a8add96d0d40a3991142be6146e83c57f7 | bigcode/the-stack | train |
1980183630aaa73c1b53ad5f | train | function | def setup_logging(level: str = "INFO"):
"""A convenience function that sets up logging for developing and debugging recipes in Jupyter,
iPython, or another interactive context.
:param level: One of (in decreasing level of detail) ``"DEBUG"``, ``"INFO"``, or ``"WARNING"``.
Defaults to ``"INFO"``.
... | def setup_logging(level: str = "INFO"):
| """A convenience function that sets up logging for developing and debugging recipes in Jupyter,
iPython, or another interactive context.
:param level: One of (in decreasing level of detail) ``"DEBUG"``, ``"INFO"``, or ``"WARNING"``.
Defaults to ``"INFO"``.
"""
import logging
try:
... | .base import BaseRecipe
from .reference_hdf_zarr import HDFReferenceRecipe
from .xarray_zarr import XarrayZarrRecipe
__all__ = ["BaseRecipe", "XarrayZarrRecipe", "HDFReferenceRecipe"]
def setup_logging(level: str = "INFO"):
| 63 | 64 | 194 | 10 | 53 | rwegener2/pangeo-forge-recipes | pangeo_forge_recipes/recipes/__init__.py | Python | setup_logging | setup_logging | 8 | 32 | 8 | 8 | b8b6b607a8e1a86815c52f37d987172751e3aed7 | bigcode/the-stack | train |
977852dc2bb0363b3fa7dcbf | train | class | class KeyVaultPreparer(AzureMgmtPreparer):
def __init__(
self,
name_prefix=random.choice(ascii_letters).lower(),
sku=DEFAULT_SKU,
permissions=DEFAULT_PERMISSIONS,
enabled_for_deployment=True,
enabled_for_disk_encryption=True,
enabled_for_template_deployment=Tr... | class KeyVaultPreparer(AzureMgmtPreparer):
| def __init__(
self,
name_prefix=random.choice(ascii_letters).lower(),
sku=DEFAULT_SKU,
permissions=DEFAULT_PERMISSIONS,
enabled_for_deployment=True,
enabled_for_disk_encryption=True,
enabled_for_template_deployment=True,
enable_soft_delete=None,
... | the MIT License.
# ------------------------------------
import time
import random
from string import ascii_letters
from azure.mgmt.keyvault import KeyVaultManagementClient
from azure.mgmt.keyvault.models import (
SecretPermissions,
KeyPermissions,
CertificatePermissions,
StoragePermissions,
Permi... | 256 | 256 | 877 | 11 | 245 | vbarbaresi/azure-sdk-for-python | tools/azure-sdk-tools/devtools_testutils/keyvault_preparer.py | Python | KeyVaultPreparer | KeyVaultPreparer | 48 | 148 | 48 | 48 | 0e0c3415c3be81ac9aeceb7d54dff0aad59e0fd8 | bigcode/the-stack | train |
849f239e0f2d9facf1d0b360 | train | function | @client.event
async def on_ready():
print (f'\n\nLogged in as: {client.user.name} - {client.user.id}\nVersion: {discord.__version__}\n')
# Create an asynchronous task to change the status.
client.loop.create_task(status_task())
print(f'Successfully logged in and running...!')
| @client.event
async def on_ready():
| print (f'\n\nLogged in as: {client.user.name} - {client.user.id}\nVersion: {discord.__version__}\n')
# Create an asynchronous task to change the status.
client.loop.create_task(status_task())
print(f'Successfully logged in and running...!')
| 0], type=status[1]))
await asyncio.sleep(180)
# ============= LOAD COGS =============
if __name__ == '__main__':
for extension in initial_extensions:
client.load_extension(extension)
# Print information about the bot if it successfully activates.
@client.event
async def on_ready():
| 64 | 64 | 73 | 9 | 55 | theHoncho/spacefed | bot.py | Python | on_ready | on_ready | 52 | 58 | 52 | 53 | 4b83b424ba50259e741b70f7c73c7e6fe27a1057 | bigcode/the-stack | train |
8bbe7a0d969ead78737e5ece | train | function | async def status_task():
while True:
status = random.choice(statuses)
await client.change_presence(activity=discord.Activity(name=status[0], type=status[1]))
await asyncio.sleep(180)
| async def status_task():
| while True:
status = random.choice(statuses)
await client.change_presence(activity=discord.Activity(name=status[0], type=status[1]))
await asyncio.sleep(180)
| prefixes)(bot, message)
# Create an array of the cogs that need loading.
initial_extensions = []
# Set the prefix.
client = commands.Bot(command_prefix = get_prefix, description = "Space Federation bot")
# ============= FUNCTIONS =============
# Loop through the status choices.
async def status_task():
| 64 | 64 | 43 | 5 | 59 | theHoncho/spacefed | bot.py | Python | status_task | status_task | 39 | 43 | 39 | 39 | 6a4c20d8c6ea33555ea3513d431cd5d2a3a0f0d4 | bigcode/the-stack | train |
e472855a1cf48aa6335f3cd0 | train | function | def get_prefix(bot, message):
# ENV
#prefixes = os.getenv('PREFIXES').split(' ')
# LOCAL
prefixes = config['discord']['prefixes']
return commands.when_mentioned_or(*prefixes)(bot, message)
| def get_prefix(bot, message):
# ENV
#prefixes = os.getenv('PREFIXES').split(' ')
# LOCAL
| prefixes = config['discord']['prefixes']
return commands.when_mentioned_or(*prefixes)(bot, message)
| ],
['the assembly debate', 2]]
# ============= INITIALIZE BOT CLIENT =============
# Define the prefix for the bot, tagging the bot also works.
def get_prefix(bot, message):
# ENV
#prefixes = os.getenv('PREFIXES').split(' ')
# LOCAL
| 63 | 64 | 54 | 29 | 34 | theHoncho/spacefed | bot.py | Python | get_prefix | get_prefix | 22 | 28 | 22 | 25 | 7a9345d5b1d3abe12f9190f7aebbed56bc18c676 | bigcode/the-stack | train |
6d767fe21c8703a9f9cc40ec | train | function | def main():
args = parse_args()
return args.func(args)
| def main():
| args = parse_args()
return args.func(args)
| "-t",
"--threshold",
type=float,
default=0.2,
help="Comparison threshold. "
"Variations larger than this threshold will be reported as failures. "
"Default 0.2 (20%%).",
)
return parser.parse_args()
def main():
| 64 | 64 | 15 | 3 | 61 | laithsakka/velox | scripts/benchmark-runner.py | Python | main | main | 272 | 274 | 272 | 272 | 5fce3490a5d85f85b415246020fa89f54d16df99 | bigcode/the-stack | train |
a19ae6c33f1b4d3f1101e083 | train | function | def run(args):
files = execute(_FIND_BINARIES_CMD % args.path)
if not files:
print("No benchmark binaries found in path '%s'. Aborting..." % args.path)
return 1
if args.dump_path:
os.makedirs(args.dump_path, exist_ok=True)
print("Benchmark-runner found %i benchmarks binaries to... | def run(args):
| files = execute(_FIND_BINARIES_CMD % args.path)
if not files:
print("No benchmark binaries found in path '%s'. Aborting..." % args.path)
return 1
if args.dump_path:
os.makedirs(args.dump_path, exist_ok=True)
print("Benchmark-runner found %i benchmarks binaries to execute." % le... | =subprocess.PIPE, shell=True)
result = [line.strip().decode("ascii") for line in process.stdout.readlines()]
if process.wait() != 0:
raise subprocess.SubprocessError(
"'{}' returned a non-zero code ({}).".format(cmd, process.returncode)
)
return result
def run(args):
| 71 | 71 | 239 | 4 | 66 | laithsakka/velox | scripts/benchmark-runner.py | Python | run | run | 68 | 98 | 68 | 68 | ece142c03451079d8cec22a368dce0f810954ce2 | bigcode/the-stack | train |
3ae782f0b315e3f472ed7ae5 | train | function | def color_yellow(text) -> str:
return "\033[93m{}\033[00m".format(text) if sys.stdout.isatty() else text
| def color_yellow(text) -> str:
| return "\033[93m{}\033[00m".format(text) if sys.stdout.isatty() else text
| " --bm_json_verbose %s"
_OUTPUT_NUM_COLS = 100
# Cosmetic helper functions.
def color_red(text) -> str:
return "\033[91m{}\033[00m".format(text) if sys.stdout.isatty() else text
def color_yellow(text) -> str:
| 64 | 64 | 35 | 9 | 54 | laithsakka/velox | scripts/benchmark-runner.py | Python | color_yellow | color_yellow | 36 | 37 | 36 | 36 | c8dff9d76e1d90dcb9cbaef4353c9fe825607935 | bigcode/the-stack | train |
ba3215f6121c1960fc60ce8e | train | function | def bold(text) -> str:
return "\033[1m{}\033[00m".format(text) if sys.stdout.isatty() else text
| def bold(text) -> str:
| return "\033[1m{}\033[00m".format(text) if sys.stdout.isatty() else text
| 033[93m{}\033[00m".format(text) if sys.stdout.isatty() else text
def color_green(text) -> str:
return "\033[92m{}\033[00m".format(text) if sys.stdout.isatty() else text
def bold(text) -> str:
| 64 | 64 | 33 | 7 | 56 | laithsakka/velox | scripts/benchmark-runner.py | Python | bold | bold | 44 | 45 | 44 | 44 | ac37a797e8dd0910caec56dc4a1301f586058f84 | bigcode/the-stack | train |
fbf694dec482253208ffed55 | train | function | def execute(cmd, print_stdout=False):
"""
Executes an external process using Popen.
Either print the process output or return it in a list (based on print_stdout).
"""
result = None
if print_stdout:
process = subprocess.Popen(cmd, stdout=sys.stdout, shell=True)
else:
process... | def execute(cmd, print_stdout=False):
| """
Executes an external process using Popen.
Either print the process output or return it in a list (based on print_stdout).
"""
result = None
if print_stdout:
process = subprocess.Popen(cmd, stdout=sys.stdout, shell=True)
else:
process = subprocess.Popen(cmd, stdout=subpro... | 033[92m{}\033[00m".format(text) if sys.stdout.isatty() else text
def bold(text) -> str:
return "\033[1m{}\033[00m".format(text) if sys.stdout.isatty() else text
def execute(cmd, print_stdout=False):
| 64 | 64 | 141 | 8 | 55 | laithsakka/velox | scripts/benchmark-runner.py | Python | execute | execute | 48 | 65 | 48 | 48 | ab7f97771dbe1dc5b0fd4fc9234afc897fd689b5 | bigcode/the-stack | train |
4fcc718d50648926a36a932a | train | function | def color_red(text) -> str:
return "\033[91m{}\033[00m".format(text) if sys.stdout.isatty() else text
| def color_red(text) -> str:
| return "\033[91m{}\033[00m".format(text) if sys.stdout.isatty() else text
| MARK_CMD = "%s --bm_max_secs 10 --bm_max_trials 1000000"
_BENCHMARK_WITH_DUMP_CMD = _BENCHMARK_CMD + " --bm_json_verbose %s"
_OUTPUT_NUM_COLS = 100
# Cosmetic helper functions.
def color_red(text) -> str:
| 64 | 64 | 34 | 8 | 56 | laithsakka/velox | scripts/benchmark-runner.py | Python | color_red | color_red | 32 | 33 | 32 | 32 | 61f1fafa74d0649473d0bb9852fdf716659edb2d | bigcode/the-stack | train |
058a7024be2c02c19b9b3472 | train | function | def get_benchmark_handle(file_path, name):
if name[0] == "%":
name = name[1:]
return "{}/{}".format(os.path.basename(file_path), name)
| def get_benchmark_handle(file_path, name):
| if name[0] == "%":
name = name[1:]
return "{}/{}".format(os.path.basename(file_path), name)
| _name)
else:
print("Executing '%s':" % file_name)
cmd = _BENCHMARK_CMD % file_path
print("$ %s" % cmd)
execute(cmd, print_stdout=True)
print()
return 0
def get_benchmark_handle(file_path, name):
| 64 | 64 | 40 | 10 | 53 | laithsakka/velox | scripts/benchmark-runner.py | Python | get_benchmark_handle | get_benchmark_handle | 101 | 104 | 101 | 101 | d95aa00224bb1b0669a25d239325eaa73b7b3d65 | bigcode/the-stack | train |
64c395bf4b867ce6917ab2ca | train | function | def compare(args):
print(
"=> Starting comparison using {} ({}%) as threshold.".format(
args.threshold, args.threshold * 100
)
)
print("=> Values are reported as percentage normalized to the largest values:")
print("=> (positive means speedup; negative means regression).")... | def compare(args):
| print(
"=> Starting comparison using {} ({}%) as threshold.".format(
args.threshold, args.threshold * 100
)
)
print("=> Values are reported as percentage normalized to the largest values:")
print("=> (positive means speedup; negative means regression).")
# Read file l... | Fail")
failures.append(benchmark_handle)
else:
status = color_green("✓ Pass")
passes.append(benchmark_handle)
suffix = "({} vs {}) {:+.2f}%".format(
fmt_runtime(baseline_result), fmt_runtime(target_result), delta * 100
)
# Prefix len... | 138 | 138 | 463 | 4 | 133 | laithsakka/velox | scripts/benchmark-runner.py | Python | compare | compare | 167 | 226 | 167 | 167 | a1ee1488a0f2401b3697227855767532ad85135c | bigcode/the-stack | train |
3025e9c87cd73fd63f931e14 | train | function | def fmt_runtime(time_ns):
if time_ns < 1000:
return "{:.2f}ns".format(time_ns)
time_usec = time_ns / 1000
if time_usec < 1000:
return "{:.2f}us".format(time_usec)
else:
return "{:.2f}ms".format(time_usec / 1000)
| def fmt_runtime(time_ns):
| if time_ns < 1000:
return "{:.2f}ns".format(time_ns)
time_usec = time_ns / 1000
if time_usec < 1000:
return "{:.2f}us".format(time_usec)
else:
return "{:.2f}ms".format(time_usec / 1000)
| cmd)
execute(cmd, print_stdout=True)
print()
return 0
def get_benchmark_handle(file_path, name):
if name[0] == "%":
name = name[1:]
return "{}/{}".format(os.path.basename(file_path), name)
def fmt_runtime(time_ns):
| 64 | 64 | 81 | 6 | 58 | laithsakka/velox | scripts/benchmark-runner.py | Python | fmt_runtime | fmt_runtime | 107 | 115 | 107 | 107 | a7f49653c319d03abe84e616575c659058b8d39d | bigcode/the-stack | train |
96782588f995f9716c9d4a1a | train | function | def parse_args():
parser = argparse.ArgumentParser(description="Velox Benchmark Runner Utility.")
parser.set_defaults(func=lambda _: parser.print_help())
subparsers = parser.add_subparsers(help="Please specify one of the subcommands.")
parser_run = subparsers.add_parser("run", help="Run benchmarks and... | def parse_args():
| parser = argparse.ArgumentParser(description="Velox Benchmark Runner Utility.")
parser.set_defaults(func=lambda _: parser.print_help())
subparsers = parser.add_subparsers(help="Please specify one of the subcommands.")
parser_run = subparsers.add_parser("run", help="Run benchmarks and dump results.")
... | format(len(all_faster)) if all_faster else ""
)
print(color_green(" Pass: %d%s " % (len(all_passes), faster_summary)))
print_list(all_faster)
if all_failures:
print(color_red(" Fail: %d" % len(all_failures)))
print_list(all_failures)
return 1
return 0
def parse... | 87 | 87 | 293 | 4 | 82 | laithsakka/velox | scripts/benchmark-runner.py | Python | parse_args | parse_args | 229 | 269 | 229 | 229 | c2d637c7e80c46f8ff4e3ab0806f58bbe6f789f7 | bigcode/the-stack | train |
6123ea90c6bae9720e5afd4d | train | function | def color_green(text) -> str:
return "\033[92m{}\033[00m".format(text) if sys.stdout.isatty() else text
| def color_green(text) -> str:
| return "\033[92m{}\033[00m".format(text) if sys.stdout.isatty() else text
| 91m{}\033[00m".format(text) if sys.stdout.isatty() else text
def color_yellow(text) -> str:
return "\033[93m{}\033[00m".format(text) if sys.stdout.isatty() else text
def color_green(text) -> str:
| 64 | 64 | 34 | 8 | 55 | laithsakka/velox | scripts/benchmark-runner.py | Python | color_green | color_green | 40 | 41 | 40 | 40 | b1ab31a5ec5f3ef2d052d1ced628b213c5dab967 | bigcode/the-stack | train |
c7d1a4492cc5df8a524041a4 | train | function | def compare_file(args, target_data, baseline_data):
baseline_map = {}
for row in baseline_data:
baseline_map[get_benchmark_handle(row[0], row[1])] = row[2]
passes = []
faster = []
failures = []
for row in target_data:
# Folly benchmark exports line separators by mistake as an e... | def compare_file(args, target_data, baseline_data):
| baseline_map = {}
for row in baseline_data:
baseline_map[get_benchmark_handle(row[0], row[1])] = row[2]
passes = []
faster = []
failures = []
for row in target_data:
# Folly benchmark exports line separators by mistake as an entry on
# the json file.
if row[1] =... | name = name[1:]
return "{}/{}".format(os.path.basename(file_path), name)
def fmt_runtime(time_ns):
if time_ns < 1000:
return "{:.2f}ns".format(time_ns)
time_usec = time_ns / 1000
if time_usec < 1000:
return "{:.2f}us".format(time_usec)
else:
return "{:.2f}ms".format(time_... | 112 | 112 | 374 | 11 | 101 | laithsakka/velox | scripts/benchmark-runner.py | Python | compare_file | compare_file | 118 | 164 | 118 | 118 | 579f5149e3baf3be1fdcd5de2a0a81769329d104 | bigcode/the-stack | train |
cf63bf8fec5791b76739846a | train | class | class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Tutor'
db.create_table('tutors_tutor', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('last_updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=... | class Migration(SchemaMigration):
| def forwards(self, orm):
# Adding model 'Tutor'
db.create_table('tutors_tutor', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('last_updated', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
('name', self.g... | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
| 37 | 256 | 1,527 | 6 | 30 | skule/skule_tutors2 | tutors/migrations/0001_initial.py | Python | Migration | Migration | 8 | 101 | 8 | 9 | ab46f621750e2416ea699a5f3dd6a9ece5a59711 | bigcode/the-stack | train |
8aa28df1fed5b4f140aa9860 | train | class | class WeaponBase(WeaponBaseBase.WeaponBaseBase):
__module__ = __name__
ignoreGround = False
def __init__(self):
if __builtins__.has_key('localAvatar'):
av = localAvatar
else:
av = self
WeaponBaseBase.WeaponBaseBase.__init__(self, av, self.cr)
self.pro... | class WeaponBase(WeaponBaseBase.WeaponBaseBase):
| __module__ = __name__
ignoreGround = False
def __init__(self):
if __builtins__.has_key('localAvatar'):
av = localAvatar
else:
av = self
WeaponBaseBase.WeaponBaseBase.__init__(self, av, self.cr)
self.prop = None
self.ammoSequence = 0
se... | # uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.battle.WeaponBase
import math
from pandac.PandaModules import *
from direct.distributed.ClockDelta import globalClockDelta
from ... | 209 | 256 | 5,654 | 12 | 196 | itsyaboyrocket/pirates | pirates/battle/WeaponBase.py | Python | WeaponBase | WeaponBase | 18 | 511 | 18 | 18 | 6574fc4722a43ac38b56c41078fd9bb563dea247 | bigcode/the-stack | train |
27900c6e81126580beeec390 | train | function | def main():
audio = pyaudio.PyAudio()
stream = audio.open(format=Constants.FORMAT, rate=Constants.RATE, channels=Constants.CHANNELS, input=True, frames_per_buffer=Constants.CHUNK)
print("Recording...")
frames = []
for i in range(0, int(Constants.RATE / Constants.CHUNK * Constants.RECORD_SECONDS... | def main():
| audio = pyaudio.PyAudio()
stream = audio.open(format=Constants.FORMAT, rate=Constants.RATE, channels=Constants.CHANNELS, input=True, frames_per_buffer=Constants.CHUNK)
print("Recording...")
frames = []
for i in range(0, int(Constants.RATE / Constants.CHUNK * Constants.RECORD_SECONDS)):
... | import pyaudio
import wave
class Constants:
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = 'recorded.wav'
def main():
| 64 | 64 | 184 | 3 | 61 | Sanjay-Ganeshan/webcam-mouse | fetch_mic.py | Python | main | main | 17 | 38 | 17 | 17 | 70c5c5df4f80f23cda88e772d80223c976bebc42 | bigcode/the-stack | train |
f95979a10156e76906bdecda | train | class | class Constants:
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = 'recorded.wav'
| class Constants:
| FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = 'recorded.wav'
| # Written by Julie
import os
import argparse
import pyaudio
import wave
class Constants:
| 22 | 64 | 53 | 3 | 18 | Sanjay-Ganeshan/webcam-mouse | fetch_mic.py | Python | Constants | Constants | 8 | 14 | 8 | 8 | 5855e5e1f58548014114539bb6a0384b08713811 | bigcode/the-stack | train |
7a89ca2a6e6d28eddced1310 | train | class | class Kill(ExtensionUI):
""" terminate a module in background by id """
Name = "kill"
def __init__(self, parse_args=None, root=None):
self.parse_args = parse_args
self.root = root
self.register_command("do_kill", self.do_kill)
self.register_command("help_kill", self.help_k... | class Kill(ExtensionUI):
| """ terminate a module in background by id """
Name = "kill"
def __init__(self, parse_args=None, root=None):
self.parse_args = parse_args
self.root = root
self.register_command("do_kill", self.do_kill)
self.register_command("help_kill", self.help_kill)
self.registe... | the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT ... | 109 | 109 | 365 | 6 | 103 | rafonsecad/wifipumpkin3 | wifipumpkin3/extensions/kill.py | Python | Kill | Kill | 26 | 79 | 26 | 26 | 293fcec6bce47754963c256050f96c235d2ef95b | bigcode/the-stack | train |
0910cb853b691ad81e757b62 | train | class | class CutLinesPolarizationSurveyDetail(ActivityDetailBase):
__mapper_args__ = {
'polymorphic_identity': 'cut_lines_polarization_survey', ## type code
}
## NO TABLE FOR THIS TYPE
def __repr__(self):
return '<CutLinesPolarizationSurveyDetail %r>' % self.activity_detail_id
| class CutLinesPolarizationSurveyDetail(ActivityDetailBase):
| __mapper_args__ = {
'polymorphic_identity': 'cut_lines_polarization_survey', ## type code
}
## NO TABLE FOR THIS TYPE
def __repr__(self):
return '<CutLinesPolarizationSurveyDetail %r>' % self.activity_detail_id
| UUID
from sqlalchemy.schema import FetchedValue
from sqlalchemy.ext.associationproxy import association_proxy
from app.api.utils.models_mixins import Base
from app.extensions import db
from app.api.now_applications.models.activity_detail.activity_detail_base import ActivityDetailBase
class CutLinesPolarizationSurvey... | 64 | 64 | 74 | 11 | 52 | parc-jason/mds | services/core-api/app/api/now_applications/models/activity_detail/cut_lines_polarization_survey_detail.py | Python | CutLinesPolarizationSurveyDetail | CutLinesPolarizationSurveyDetail | 11 | 19 | 11 | 11 | 340372fefcab76cd3571674e0f9a8df3f79337ed | bigcode/the-stack | train |
33b237705666504abc1cf0a3 | train | class | class RocketClient(instagram_web_api.Client):
def __init__(self):
super(RocketClient, self).__init__(auto_patch=True, drop_incompat_keys=False)
@staticmethod
def _extract_rhx_gis(html):
options = string.ascii_lowercase + string.digits
text = ''.join([random.choice(options) for _ in range(8)])
... | class RocketClient(instagram_web_api.Client):
| def __init__(self):
super(RocketClient, self).__init__(auto_patch=True, drop_incompat_keys=False)
@staticmethod
def _extract_rhx_gis(html):
options = string.ascii_lowercase + string.digits
text = ''.join([random.choice(options) for _ in range(8)])
return hashlib.md5(text.encode()).hexdigest... | import hashlib, string, random, instagram_web_api
class RocketClient(instagram_web_api.Client):
| 20 | 64 | 91 | 9 | 10 | cjwood0/RocketBot | RocketClient.py | Python | RocketClient | RocketClient | 3 | 11 | 3 | 3 | 83c925a146c9654f5dfa1d7438def676372a5513 | bigcode/the-stack | train |
8d73265dad2f53b3ba4ff0ea | train | class | class CubeService(ObjectService):
""" Service to handle Object Updates for TM1 Cubes
"""
def __init__(self, rest: RestService):
# to avoid Circular dependency of modules
from TM1py.Services.AnnotationService import AnnotationService
super().__init__(rest)
self.cells = CellS... | class CubeService(ObjectService):
| """ Service to handle Object Updates for TM1 Cubes
"""
def __init__(self, rest: RestService):
# to avoid Circular dependency of modules
from TM1py.Services.AnnotationService import AnnotationService
super().__init__(rest)
self.cells = CellService(rest)
self.views = ... | # -*- coding: utf-8 -*-
import json
import random
from typing import List, Iterable, Dict
from requests import Response
from TM1py.Objects.Cube import Cube
from TM1py.Services.CellService import CellService
from TM1py.Services.ObjectService import ObjectService
from TM1py.Services.RestService import RestService
from ... | 110 | 256 | 2,818 | 6 | 103 | adscheevel/tm1py | TM1py/Services/CubeService.py | Python | CubeService | CubeService | 16 | 315 | 16 | 16 | 7f006ae7c7736ee556f6ede8195f394461bc544a | bigcode/the-stack | train |
2de904120193b22fcf59a054 | train | class | class Verilator(BaseRunner):
def __init__(self):
super().__init__(
"verilator", "verilator", {
"preprocessing", "parsing", "elaboration", "simulation",
"simulation_without_run"
})
self.c_extensions = ['.cc', '.c', '.cpp', '.h', '.hpp']
... | class Verilator(BaseRunner):
| def __init__(self):
super().__init__(
"verilator", "verilator", {
"preprocessing", "parsing", "elaboration", "simulation",
"simulation_without_run"
})
self.c_extensions = ['.cc', '.c', '.cpp', '.h', '.hpp']
self.allowed_extensions.exte... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
import os
import shutil
import shlex
from Bas... | 97 | 212 | 707 | 6 | 90 | shioyadan/sv-tests | tools/runners/Verilator.py | Python | Verilator | Verilator | 19 | 98 | 19 | 19 | ca4b1bd014cd8565dbdeed98b5d9a69293b37805 | bigcode/the-stack | train |
bb0151749e52a2a8a80c8ba0 | train | class | class Configuration(resource.Resource):
def __init__(self):
super().__init__()
async def render_post(self, request):
# Creating a dictionary from a message received from a sensor
data = [MessageToDict(proto_config_pb2.ProtoConfig().FromString(request.payload))]
# Create the fil... | class Configuration(resource.Resource):
| def __init__(self):
super().__init__()
async def render_post(self, request):
# Creating a dictionary from a message received from a sensor
data = [MessageToDict(proto_config_pb2.ProtoConfig().FromString(request.payload))]
# Create the file "Configuration.txt" and save the date i... | file.close()
# returning "ACK" to the sensor
return aiocoap.Message(mtype=aiocoap.ACK, code=aiocoap.Code.CREATED,
token=request.token, payload="")
# Configuration - Class used to handle Configuration messages sent by the sensor
class Configuration(resource.Resour... | 64 | 64 | 161 | 5 | 58 | efento/NB-IoT-sensors-integration | NB-IoT-sensors-integration.py | Python | Configuration | Configuration | 90 | 107 | 90 | 91 | c169641ec0731bfc948b1426e8d369c883fd87e2 | bigcode/the-stack | train |
2367eb61fd8219f944a6882b | train | class | class Time(resource.Resource):
def __init__(self):
super().__init__()
async def render_post(self, request):
time_stamp = int(time.time())
time_stamp_hex = hex(time_stamp)
print(time_stamp_hex)
# returning timestamp to the sensor
return aiocoap.Message(mtype=aio... | class Time(resource.Resource):
| def __init__(self):
super().__init__()
async def render_post(self, request):
time_stamp = int(time.time())
time_stamp_hex = hex(time_stamp)
print(time_stamp_hex)
# returning timestamp to the sensor
return aiocoap.Message(mtype=aiocoap.ACK, code=aiocoap.Code.CREA... | file.close()
# returning "ACK" to the sensor
return aiocoap.Message(mtype=aiocoap.ACK, code=aiocoap.Code.CREATED,
token=request.token, payload="")
# Time - Class used to handle Time messages sent by the sensor
class Time(resource.Resource):
| 64 | 64 | 98 | 5 | 58 | efento/NB-IoT-sensors-integration | NB-IoT-sensors-integration.py | Python | Time | Time | 111 | 123 | 111 | 112 | dfcf22e0fcc2b2d5687036d9b8522041a4a1b8c5 | bigcode/the-stack | train |
9d4ba2aec534f5fa2cacb2af | train | class | class DeviceInfo(resource.Resource):
def __init__(self):
super().__init__()
async def render_post(self, request):
# Creating a dictionary from a message received from a sensor
data = [MessageToDict(proto_device_info_pb2.ProtoDeviceInfo().FromString(request.payload))]
# Create t... | class DeviceInfo(resource.Resource):
| def __init__(self):
super().__init__()
async def render_post(self, request):
# Creating a dictionary from a message received from a sensor
data = [MessageToDict(proto_device_info_pb2.ProtoDeviceInfo().FromString(request.payload))]
# Create the file "Deviceinfo.txt" and save the ... | # returning "ACK" to the sensor
return aiocoap.Message(mtype=aiocoap.ACK, code=aiocoap.Code.CREATED,
token=request.token, payload="")
# DeviceInfo - Class used to handle Device Info messages sent by the sensor
class DeviceInfo(resource.Resource):
| 64 | 64 | 168 | 6 | 57 | efento/NB-IoT-sensors-integration | NB-IoT-sensors-integration.py | Python | DeviceInfo | DeviceInfo | 69 | 86 | 69 | 70 | 4ed897306de9d95c703a3ac5d767dd4441b4df2a | bigcode/the-stack | train |
98159f73de930c39188ce7bd | train | class | class Measurements(resource.Resource):
def __init__(self):
super().__init__()
async def render_post(self, request):
# Creating a dictionary from a message received from a sensor
data = [MessageToDict(proto_measurements_pb2.ProtoMeasurements().FromString(request.payload))]
reco... | class Measurements(resource.Resource):
| def __init__(self):
super().__init__()
async def render_post(self, request):
# Creating a dictionary from a message received from a sensor
data = [MessageToDict(proto_measurements_pb2.ProtoMeasurements().FromString(request.payload))]
record = []
# iterating through 'da... | Enter your database host, database user, database password and database name
DATABASE_HOST = 'host_name';
DATABASE_USER = 'database_user';
DATABASE_PASSWORD = 'database_password';
DATABASE_NAME = 'database_name';
# Making the initial connection:
conn = psycopg2.connect(
dbname=DATABASE_NAME,
user=DATABASE_USE... | 101 | 101 | 338 | 5 | 95 | efento/NB-IoT-sensors-integration | NB-IoT-sensors-integration.py | Python | Measurements | Measurements | 29 | 65 | 29 | 30 | 98106ba37be47eb812aee8a22a9042f9e461bbd6 | bigcode/the-stack | train |
63dfc69aa459221001438b06 | train | function | def main():
# Resource tree creation
root = resource.Site()
# Set up “m” endpoint, which will be receiving measurements sent by Efento NB-IoT sensor using POST method
root.add_resource(["m"], Measurements())
# Set up “i” endpoint, which will be receiving device info messages sent by Efento NB-IoT se... | def main():
# Resource tree creation
| root = resource.Site()
# Set up “m” endpoint, which will be receiving measurements sent by Efento NB-IoT sensor using POST method
root.add_resource(["m"], Measurements())
# Set up “i” endpoint, which will be receiving device info messages sent by Efento NB-IoT sensor using POST method
root.add_resou... | _stamp)
print(time_stamp_hex)
# returning timestamp to the sensor
return aiocoap.Message(mtype=aiocoap.ACK, code=aiocoap.Code.CREATED,
token=request.token, payload=bytearray.fromhex(time_stamp_hex[2:]))
def main():
# Resource tree creation
| 66 | 67 | 226 | 9 | 57 | efento/NB-IoT-sensors-integration | NB-IoT-sensors-integration.py | Python | main | main | 126 | 141 | 126 | 127 | 9fcb70dbdfda9a8e127b0380ca599a17ec6df533 | bigcode/the-stack | train |
a4e921684e833cff30186319 | train | function | @click.command("init", short_help="create runway.yml")
@options.debug
@options.no_color
@options.verbose
@click.pass_context
def init(ctx, **_):
# type: (click.Context, Any) -> None
"""Create an example runway.yml file in the currect directory."""
runway_yml = Path.cwd() / "runway.yml"
LOGGER.verbose("... | @click.command("init", short_help="create runway.yml")
@options.debug
@options.no_color
@options.verbose
@click.pass_context
def init(ctx, **_):
# type: (click.Context, Any) -> None
| """Create an example runway.yml file in the currect directory."""
runway_yml = Path.cwd() / "runway.yml"
LOGGER.verbose("checking for preexisting runway.yml file...")
if runway_yml.is_file():
LOGGER.error(
"There is already a %s file in the current directory", runway_yml.name
... | # - etc...
regions:
- us-east-1
"""
@click.command("init", short_help="create runway.yml")
@options.debug
@options.no_color
@options.verbose
@click.pass_context
def init(ctx, **_):
# type: (click.Context, Any) -> None
| 64 | 64 | 198 | 49 | 15 | troyready/runway | runway/_cli/commands/_init.py | Python | init | init | 30 | 53 | 30 | 36 | 62d665a0f66b5d73d41984f7de000cedd25f339f | bigcode/the-stack | train |
32132ae670ba851405d732dc | train | function | def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
| def ensure_dir(f):
| d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
| .write(string)
def write_pickle(filename, data): # NOTE - cannot pickle lambda or nested functions
with open(filename,'wb') as f:
pickle.dump(data, f)
def read_pickle(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
def ensure_dir(f):
| 64 | 64 | 26 | 5 | 59 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | ensure_dir | ensure_dir | 75 | 78 | 75 | 75 | 603b8c6d55704a3c3f675444c1366b19f36210bf | bigcode/the-stack | train |
c075ce8e29d5890229f5175e | train | function | def irange(start, end, step=1):
n = start
while n < end:
yield n
n += step
| def irange(start, end, step=1):
| n = start
while n < end:
yield n
n += step
| # NOTE - it may be because of set iteration
def implies(a, b):
return not a or b
##################################################
def flatten(iterable_of_iterables):
return (item for iterables in iterable_of_iterables for item in iterables)
def irange(start, end, step=1):
| 64 | 64 | 31 | 11 | 53 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | irange | irange | 34 | 38 | 34 | 34 | c34d2141fc789d2131834820a2b3d2bd9dc5512e | bigcode/the-stack | train |
e1ba826f82e0cb88a3e4abfc | train | function | def write(filename, string):
with open(filename, 'w') as f:
f.write(string)
| def write(filename, string):
| with open(filename, 'w') as f:
f.write(string)
| ):
return item
return None
def random_sequence(sequence):
indices = range(len(sequence))
shuffle(indices)
for i in indices:
yield sequence[i]
##################################################
def read(filename):
with open(filename, 'r') as f:
return f.read()
def write(filename, string):
| 64 | 64 | 22 | 6 | 58 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | write | write | 63 | 65 | 63 | 63 | 57cc088e3b36fcd04e4c9b24f351419d0efe9168 | bigcode/the-stack | train |
3c30b728dbf0e36e4b322128 | train | function | def argmin(function, sequence):
values = list(sequence)
scores = [function(x) for x in values]
return values[scores.index(min(scores))]
| def argmin(function, sequence):
| values = list(sequence)
scores = [function(x) for x in values]
return values[scores.index(min(scores))]
| def flatten(iterable_of_iterables):
return (item for iterables in iterable_of_iterables for item in iterables)
def irange(start, end, step=1):
n = start
while n < end:
yield n
n += step
def argmin(function, sequence):
| 64 | 64 | 34 | 7 | 56 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | argmin | argmin | 40 | 43 | 40 | 40 | e92bf206d613b4a7990bf2ba2f4fefa52f46e254 | bigcode/the-stack | train |
2ee0a51a0ea95081ef6961e7 | train | function | def header(s, n=10):
return '\n' + n*'-' + s + n*'-'+'\n'
| def header(s, n=10):
| return '\n' + n*'-' + s + n*'-'+'\n'
| to 100000000
INT_INF = 1000000 # 1e6
INF = float('inf')
SEPARATOR = '\n'+85*'-'+'\n'
def separator(n=85):
return '\n'+n*'-'+'\n'
def header(s, n=10):
| 64 | 64 | 28 | 8 | 56 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | header | header | 15 | 16 | 15 | 15 | 0380bfcb38e58bddd71b65856ca89ff6ad8e776c | bigcode/the-stack | train |
08a9e9f27c625db287bb6969 | train | function | def safe_remove(p):
if os.path.exists(p):
os.remove(p)
| def safe_remove(p):
| if os.path.exists(p):
os.remove(p)
| ') as f:
pickle.dump(data, f)
def read_pickle(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.exists(d):
os.makedirs(d)
def safe_remove(p):
| 64 | 64 | 17 | 5 | 59 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | safe_remove | safe_remove | 80 | 82 | 80 | 80 | 77cd03ac6eed77ece1bf146cde61404ae5b488c6 | bigcode/the-stack | train |
9ab0dcead2cfa26fb9e74192 | train | function | def read(filename):
with open(filename, 'r') as f:
return f.read()
| def read(filename):
| with open(filename, 'r') as f:
return f.read()
| cores.index(min(scores))]
def first(function, iterable):
for item in iterable:
if function(item):
return item
return None
def random_sequence(sequence):
indices = range(len(sequence))
shuffle(indices)
for i in indices:
yield sequence[i]
##################################################
def r... | 64 | 64 | 20 | 4 | 60 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | read | read | 59 | 61 | 59 | 59 | c0e67b18fd40fe661f17658dc7c745513f475701 | bigcode/the-stack | train |
20b512ab57eed73e34beb8bc | train | function | def separator(n=85):
return '\n'+n*'-'+'\n'
| def separator(n=85):
| return '\n'+n*'-'+'\n'
| import pickle
from random import shuffle
# WARNING: overflow on h^add! Costs clamped to 100000000
INT_INF = 1000000 # 1e6
INF = float('inf')
SEPARATOR = '\n'+85*'-'+'\n'
def separator(n=85):
| 64 | 64 | 18 | 6 | 58 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | separator | separator | 12 | 13 | 12 | 12 | c0398b74299ba5b8cb031bc612bb5544ef4344c5 | bigcode/the-stack | train |
7deac2c391ba6daa55626c56 | train | function | def read_pickle(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
| def read_pickle(filename):
| with open(filename, 'rb') as f:
return pickle.load(f)
| f.read()
def write(filename, string):
with open(filename, 'w') as f:
f.write(string)
def write_pickle(filename, data): # NOTE - cannot pickle lambda or nested functions
with open(filename,'wb') as f:
pickle.dump(data, f)
def read_pickle(filename):
| 64 | 64 | 22 | 5 | 59 | nishadg246/stripstream-ivan-nishad | stripstream/utils.py | Python | read_pickle | read_pickle | 71 | 73 | 71 | 71 | 8cbd708733860149aec2d3511b4d014d2707fa55 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.