id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,000 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.HandleBlockReceived | def HandleBlockReceived(self, inventory):
"""
Process a Block inventory payload.
Args:
inventory (neo.Network.Inventory):
"""
block = IOHelper.AsSerializableWithType(inventory, 'neo.Core.Block.Block')
if not block:
return
blockhash = block.Hash.ToBytes()
try:
if blockhash in BC.Default().BlockRequests:
BC.Default().BlockRequests.remove(blockhash)
except KeyError:
pass
try:
if blockhash in self.myblockrequests:
# logger.debug(f"{self.prefix} received block: {block.Index}")
self.heart_beat(HEARTBEAT_BLOCKS)
self.myblockrequests.remove(blockhash)
except KeyError:
pass
self.leader.InventoryReceived(block) | python | def HandleBlockReceived(self, inventory):
block = IOHelper.AsSerializableWithType(inventory, 'neo.Core.Block.Block')
if not block:
return
blockhash = block.Hash.ToBytes()
try:
if blockhash in BC.Default().BlockRequests:
BC.Default().BlockRequests.remove(blockhash)
except KeyError:
pass
try:
if blockhash in self.myblockrequests:
# logger.debug(f"{self.prefix} received block: {block.Index}")
self.heart_beat(HEARTBEAT_BLOCKS)
self.myblockrequests.remove(blockhash)
except KeyError:
pass
self.leader.InventoryReceived(block) | [
"def",
"HandleBlockReceived",
"(",
"self",
",",
"inventory",
")",
":",
"block",
"=",
"IOHelper",
".",
"AsSerializableWithType",
"(",
"inventory",
",",
"'neo.Core.Block.Block'",
")",
"if",
"not",
"block",
":",
"return",
"blockhash",
"=",
"block",
".",
"Hash",
"... | Process a Block inventory payload.
Args:
inventory (neo.Network.Inventory): | [
"Process",
"a",
"Block",
"inventory",
"payload",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L670-L694 |
229,001 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.HandleGetDataMessageReceived | def HandleGetDataMessageReceived(self, payload):
"""
Process a InvPayload payload.
Args:
payload (neo.Network.Inventory):
"""
inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload')
if not inventory:
return
for hash in inventory.Hashes:
hash = hash.encode('utf-8')
item = None
# try to get the inventory to send from relay cache
if hash in self.leader.RelayCache.keys():
item = self.leader.RelayCache[hash]
if inventory.Type == InventoryType.TXInt:
if not item:
item, index = BC.Default().GetTransaction(hash)
if not item:
item = self.leader.GetTransaction(hash)
if item:
message = Message(command='tx', payload=item, print_payload=False)
self.SendSerializedMessage(message)
elif inventory.Type == InventoryType.BlockInt:
if not item:
item = BC.Default().GetBlock(hash)
if item:
message = Message(command='block', payload=item, print_payload=False)
self.SendSerializedMessage(message)
elif inventory.Type == InventoryType.ConsensusInt:
if item:
self.SendSerializedMessage(Message(command='consensus', payload=item, print_payload=False)) | python | def HandleGetDataMessageReceived(self, payload):
inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.InvPayload.InvPayload')
if not inventory:
return
for hash in inventory.Hashes:
hash = hash.encode('utf-8')
item = None
# try to get the inventory to send from relay cache
if hash in self.leader.RelayCache.keys():
item = self.leader.RelayCache[hash]
if inventory.Type == InventoryType.TXInt:
if not item:
item, index = BC.Default().GetTransaction(hash)
if not item:
item = self.leader.GetTransaction(hash)
if item:
message = Message(command='tx', payload=item, print_payload=False)
self.SendSerializedMessage(message)
elif inventory.Type == InventoryType.BlockInt:
if not item:
item = BC.Default().GetBlock(hash)
if item:
message = Message(command='block', payload=item, print_payload=False)
self.SendSerializedMessage(message)
elif inventory.Type == InventoryType.ConsensusInt:
if item:
self.SendSerializedMessage(Message(command='consensus', payload=item, print_payload=False)) | [
"def",
"HandleGetDataMessageReceived",
"(",
"self",
",",
"payload",
")",
":",
"inventory",
"=",
"IOHelper",
".",
"AsSerializableWithType",
"(",
"payload",
",",
"'neo.Network.Payloads.InvPayload.InvPayload'",
")",
"if",
"not",
"inventory",
":",
"return",
"for",
"hash",... | Process a InvPayload payload.
Args:
payload (neo.Network.Inventory): | [
"Process",
"a",
"InvPayload",
"payload",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L786-L824 |
229,002 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.HandleGetBlocksMessageReceived | def HandleGetBlocksMessageReceived(self, payload):
"""
Process a GetBlocksPayload payload.
Args:
payload (neo.Network.Payloads.GetBlocksPayload):
"""
if not self.leader.ServiceEnabled:
return
inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.GetBlocksPayload.GetBlocksPayload')
if not inventory:
return
blockchain = BC.Default()
hash = inventory.HashStart[0]
if not blockchain.GetHeader(hash):
return
hashes = []
hcount = 0
while hash != inventory.HashStop and hcount < 500:
hash = blockchain.GetNextBlockHash(hash)
if hash is None:
break
hashes.append(hash)
hcount += 1
if hcount > 0:
self.SendSerializedMessage(Message('inv', InvPayload(type=InventoryType.Block, hashes=hashes))) | python | def HandleGetBlocksMessageReceived(self, payload):
if not self.leader.ServiceEnabled:
return
inventory = IOHelper.AsSerializableWithType(payload, 'neo.Network.Payloads.GetBlocksPayload.GetBlocksPayload')
if not inventory:
return
blockchain = BC.Default()
hash = inventory.HashStart[0]
if not blockchain.GetHeader(hash):
return
hashes = []
hcount = 0
while hash != inventory.HashStop and hcount < 500:
hash = blockchain.GetNextBlockHash(hash)
if hash is None:
break
hashes.append(hash)
hcount += 1
if hcount > 0:
self.SendSerializedMessage(Message('inv', InvPayload(type=InventoryType.Block, hashes=hashes))) | [
"def",
"HandleGetBlocksMessageReceived",
"(",
"self",
",",
"payload",
")",
":",
"if",
"not",
"self",
".",
"leader",
".",
"ServiceEnabled",
":",
"return",
"inventory",
"=",
"IOHelper",
".",
"AsSerializableWithType",
"(",
"payload",
",",
"'neo.Network.Payloads.GetBloc... | Process a GetBlocksPayload payload.
Args:
payload (neo.Network.Payloads.GetBlocksPayload): | [
"Process",
"a",
"GetBlocksPayload",
"payload",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L826-L854 |
229,003 | CityOfZion/neo-python | neo/Network/NeoNode.py | NeoNode.Relay | def Relay(self, inventory):
"""
Wrap the inventory in a InvPayload object and send it over the write to the remote node.
Args:
inventory:
Returns:
bool: True (fixed)
"""
inventory = InvPayload(type=inventory.InventoryType, hashes=[inventory.Hash.ToBytes()])
m = Message("inv", inventory)
self.SendSerializedMessage(m)
return True | python | def Relay(self, inventory):
inventory = InvPayload(type=inventory.InventoryType, hashes=[inventory.Hash.ToBytes()])
m = Message("inv", inventory)
self.SendSerializedMessage(m)
return True | [
"def",
"Relay",
"(",
"self",
",",
"inventory",
")",
":",
"inventory",
"=",
"InvPayload",
"(",
"type",
"=",
"inventory",
".",
"InventoryType",
",",
"hashes",
"=",
"[",
"inventory",
".",
"Hash",
".",
"ToBytes",
"(",
")",
"]",
")",
"m",
"=",
"Message",
... | Wrap the inventory in a InvPayload object and send it over the write to the remote node.
Args:
inventory:
Returns:
bool: True (fixed) | [
"Wrap",
"the",
"inventory",
"in",
"a",
"InvPayload",
"object",
"and",
"send",
"it",
"over",
"the",
"write",
"to",
"the",
"remote",
"node",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NeoNode.py#L856-L870 |
229,004 | CityOfZion/neo-python | neo/IO/Helper.py | Helper.DeserializeTX | def DeserializeTX(buffer):
"""
Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction:
"""
mstream = MemoryStream(buffer)
reader = BinaryReader(mstream)
tx = Transaction.DeserializeFrom(reader)
return tx | python | def DeserializeTX(buffer):
mstream = MemoryStream(buffer)
reader = BinaryReader(mstream)
tx = Transaction.DeserializeFrom(reader)
return tx | [
"def",
"DeserializeTX",
"(",
"buffer",
")",
":",
"mstream",
"=",
"MemoryStream",
"(",
"buffer",
")",
"reader",
"=",
"BinaryReader",
"(",
"mstream",
")",
"tx",
"=",
"Transaction",
".",
"DeserializeFrom",
"(",
"reader",
")",
"return",
"tx"
] | Deserialize the stream into a Transaction object.
Args:
buffer (BytesIO): stream to deserialize the Transaction from.
Returns:
neo.Core.TX.Transaction: | [
"Deserialize",
"the",
"stream",
"into",
"a",
"Transaction",
"object",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/IO/Helper.py#L42-L57 |
229,005 | CityOfZion/neo-python | neo/Core/State/UnspentCoinState.py | UnspentCoinState.FromTXOutputsConfirmed | def FromTXOutputsConfirmed(outputs):
"""
Get unspent outputs from a list of transaction outputs.
Args:
outputs (list): of neo.Core.TX.Transaction.TransactionOutput items.
Returns:
UnspentCoinState:
"""
uns = UnspentCoinState()
uns.Items = [0] * len(outputs)
for i in range(0, len(outputs)):
uns.Items[i] = int(CoinState.Confirmed)
return uns | python | def FromTXOutputsConfirmed(outputs):
uns = UnspentCoinState()
uns.Items = [0] * len(outputs)
for i in range(0, len(outputs)):
uns.Items[i] = int(CoinState.Confirmed)
return uns | [
"def",
"FromTXOutputsConfirmed",
"(",
"outputs",
")",
":",
"uns",
"=",
"UnspentCoinState",
"(",
")",
"uns",
".",
"Items",
"=",
"[",
"0",
"]",
"*",
"len",
"(",
"outputs",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"outputs",
")",
")"... | Get unspent outputs from a list of transaction outputs.
Args:
outputs (list): of neo.Core.TX.Transaction.TransactionOutput items.
Returns:
UnspentCoinState: | [
"Get",
"unspent",
"outputs",
"from",
"a",
"list",
"of",
"transaction",
"outputs",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/UnspentCoinState.py#L27-L41 |
229,006 | CityOfZion/neo-python | neo/Core/State/UnspentCoinState.py | UnspentCoinState.IsAllSpent | def IsAllSpent(self):
"""
Flag indicating if all balance is spend.
Returns:
bool:
"""
for item in self.Items:
if item == CoinState.Confirmed:
return False
return True | python | def IsAllSpent(self):
for item in self.Items:
if item == CoinState.Confirmed:
return False
return True | [
"def",
"IsAllSpent",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"Items",
":",
"if",
"item",
"==",
"CoinState",
".",
"Confirmed",
":",
"return",
"False",
"return",
"True"
] | Flag indicating if all balance is spend.
Returns:
bool: | [
"Flag",
"indicating",
"if",
"all",
"balance",
"is",
"spend",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/UnspentCoinState.py#L55-L65 |
229,007 | CityOfZion/neo-python | neo/Core/TX/Transaction.py | Transaction.Hash | def Hash(self):
"""
Get the hash of the transaction.
Returns:
UInt256:
"""
if not self.__hash:
ba = bytearray(binascii.unhexlify(self.GetHashData()))
hash = Crypto.Hash256(ba)
self.__hash = UInt256(data=hash)
return self.__hash | python | def Hash(self):
if not self.__hash:
ba = bytearray(binascii.unhexlify(self.GetHashData()))
hash = Crypto.Hash256(ba)
self.__hash = UInt256(data=hash)
return self.__hash | [
"def",
"Hash",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__hash",
":",
"ba",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"self",
".",
"GetHashData",
"(",
")",
")",
")",
"hash",
"=",
"Crypto",
".",
"Hash256",
"(",
"ba",
")",
... | Get the hash of the transaction.
Returns:
UInt256: | [
"Get",
"the",
"hash",
"of",
"the",
"transaction",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L278-L289 |
229,008 | CityOfZion/neo-python | neo/Core/TX/Transaction.py | Transaction.References | def References(self):
"""
Get all references.
Returns:
dict:
Key (UInt256): input PrevHash
Value (TransactionOutput): object.
"""
if self.__references is None:
refs = {}
# group by the input prevhash
for hash, group in groupby(self.inputs, lambda x: x.PrevHash):
tx, height = GetBlockchain().GetTransaction(hash.ToBytes())
if tx is not None:
for input in group:
refs[input] = tx.outputs[input.PrevIndex]
self.__references = refs
return self.__references | python | def References(self):
if self.__references is None:
refs = {}
# group by the input prevhash
for hash, group in groupby(self.inputs, lambda x: x.PrevHash):
tx, height = GetBlockchain().GetTransaction(hash.ToBytes())
if tx is not None:
for input in group:
refs[input] = tx.outputs[input.PrevIndex]
self.__references = refs
return self.__references | [
"def",
"References",
"(",
"self",
")",
":",
"if",
"self",
".",
"__references",
"is",
"None",
":",
"refs",
"=",
"{",
"}",
"# group by the input prevhash",
"for",
"hash",
",",
"group",
"in",
"groupby",
"(",
"self",
".",
"inputs",
",",
"lambda",
"x",
":",
... | Get all references.
Returns:
dict:
Key (UInt256): input PrevHash
Value (TransactionOutput): object. | [
"Get",
"all",
"references",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L337-L360 |
229,009 | CityOfZion/neo-python | neo/Core/TX/Transaction.py | Transaction.NetworkFee | def NetworkFee(self):
"""
Get the network fee.
Returns:
Fixed8:
"""
if self._network_fee is None:
input = Fixed8(0)
for coin_ref in self.References.values():
if coin_ref.AssetId == GetBlockchain().SystemCoin().Hash:
input = input + coin_ref.Value
output = Fixed8(0)
for tx_output in self.outputs:
if tx_output.AssetId == GetBlockchain().SystemCoin().Hash:
output = output + tx_output.Value
self._network_fee = input - output - self.SystemFee()
# logger.info("Determined network fee to be %s " % (self.__network_fee.value))
return self._network_fee | python | def NetworkFee(self):
if self._network_fee is None:
input = Fixed8(0)
for coin_ref in self.References.values():
if coin_ref.AssetId == GetBlockchain().SystemCoin().Hash:
input = input + coin_ref.Value
output = Fixed8(0)
for tx_output in self.outputs:
if tx_output.AssetId == GetBlockchain().SystemCoin().Hash:
output = output + tx_output.Value
self._network_fee = input - output - self.SystemFee()
# logger.info("Determined network fee to be %s " % (self.__network_fee.value))
return self._network_fee | [
"def",
"NetworkFee",
"(",
"self",
")",
":",
"if",
"self",
".",
"_network_fee",
"is",
"None",
":",
"input",
"=",
"Fixed8",
"(",
"0",
")",
"for",
"coin_ref",
"in",
"self",
".",
"References",
".",
"values",
"(",
")",
":",
"if",
"coin_ref",
".",
"AssetId... | Get the network fee.
Returns:
Fixed8: | [
"Get",
"the",
"network",
"fee",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L384-L409 |
229,010 | CityOfZion/neo-python | neo/Core/TX/Transaction.py | Transaction.DeserializeFromBufer | def DeserializeFromBufer(buffer, offset=0):
"""
Deserialize object instance from the specified buffer.
Args:
buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
offset: UNUSED
Returns:
Transaction:
"""
mstream = StreamManager.GetStream(buffer)
reader = BinaryReader(mstream)
tx = Transaction.DeserializeFrom(reader)
StreamManager.ReleaseStream(mstream)
return tx | python | def DeserializeFromBufer(buffer, offset=0):
mstream = StreamManager.GetStream(buffer)
reader = BinaryReader(mstream)
tx = Transaction.DeserializeFrom(reader)
StreamManager.ReleaseStream(mstream)
return tx | [
"def",
"DeserializeFromBufer",
"(",
"buffer",
",",
"offset",
"=",
"0",
")",
":",
"mstream",
"=",
"StreamManager",
".",
"GetStream",
"(",
"buffer",
")",
"reader",
"=",
"BinaryReader",
"(",
"mstream",
")",
"tx",
"=",
"Transaction",
".",
"DeserializeFrom",
"(",... | Deserialize object instance from the specified buffer.
Args:
buffer (bytes, bytearray, BytesIO): (Optional) data to create the stream from.
offset: UNUSED
Returns:
Transaction: | [
"Deserialize",
"object",
"instance",
"from",
"the",
"specified",
"buffer",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L435-L451 |
229,011 | CityOfZion/neo-python | neo/Core/TX/Transaction.py | Transaction.DeserializeUnsigned | def DeserializeUnsigned(self, reader):
"""
Deserialize object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: if transaction type is incorrect.
"""
txtype = reader.ReadByte()
if txtype != int.from_bytes(self.Type, 'little'):
raise Exception('incorrect type {}, wanted {}'.format(txtype, int.from_bytes(self.Type, 'little')))
self.DeserializeUnsignedWithoutType(reader) | python | def DeserializeUnsigned(self, reader):
txtype = reader.ReadByte()
if txtype != int.from_bytes(self.Type, 'little'):
raise Exception('incorrect type {}, wanted {}'.format(txtype, int.from_bytes(self.Type, 'little')))
self.DeserializeUnsignedWithoutType(reader) | [
"def",
"DeserializeUnsigned",
"(",
"self",
",",
"reader",
")",
":",
"txtype",
"=",
"reader",
".",
"ReadByte",
"(",
")",
"if",
"txtype",
"!=",
"int",
".",
"from_bytes",
"(",
"self",
".",
"Type",
",",
"'little'",
")",
":",
"raise",
"Exception",
"(",
"'in... | Deserialize object.
Args:
reader (neo.IO.BinaryReader):
Raises:
Exception: if transaction type is incorrect. | [
"Deserialize",
"object",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L512-L525 |
229,012 | CityOfZion/neo-python | neo/Core/TX/Transaction.py | Transaction.DeserializeUnsignedWithoutType | def DeserializeUnsignedWithoutType(self, reader):
"""
Deserialize object without reading transaction type data.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadByte()
self.DeserializeExclusiveData(reader)
self.Attributes = reader.ReadSerializableArray('neo.Core.TX.TransactionAttribute.TransactionAttribute',
max=self.MAX_TX_ATTRIBUTES)
self.inputs = reader.ReadSerializableArray('neo.Core.CoinReference.CoinReference')
self.outputs = reader.ReadSerializableArray('neo.Core.TX.Transaction.TransactionOutput') | python | def DeserializeUnsignedWithoutType(self, reader):
self.Version = reader.ReadByte()
self.DeserializeExclusiveData(reader)
self.Attributes = reader.ReadSerializableArray('neo.Core.TX.TransactionAttribute.TransactionAttribute',
max=self.MAX_TX_ATTRIBUTES)
self.inputs = reader.ReadSerializableArray('neo.Core.CoinReference.CoinReference')
self.outputs = reader.ReadSerializableArray('neo.Core.TX.Transaction.TransactionOutput') | [
"def",
"DeserializeUnsignedWithoutType",
"(",
"self",
",",
"reader",
")",
":",
"self",
".",
"Version",
"=",
"reader",
".",
"ReadByte",
"(",
")",
"self",
".",
"DeserializeExclusiveData",
"(",
"reader",
")",
"self",
".",
"Attributes",
"=",
"reader",
".",
"Read... | Deserialize object without reading transaction type data.
Args:
reader (neo.IO.BinaryReader): | [
"Deserialize",
"object",
"without",
"reading",
"transaction",
"type",
"data",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L527-L539 |
229,013 | CityOfZion/neo-python | neo/Core/TX/Transaction.py | Transaction.GetTransactionResults | def GetTransactionResults(self):
"""
Get the execution results of the transaction.
Returns:
None: if the transaction has no references.
list: of TransactionResult objects.
"""
if self.References is None:
return None
results = []
realresults = []
for ref_output in self.References.values():
results.append(TransactionResult(ref_output.AssetId, ref_output.Value))
for output in self.outputs:
results.append(TransactionResult(output.AssetId, output.Value * Fixed8(-1)))
for key, group in groupby(results, lambda x: x.AssetId):
sum = Fixed8(0)
for item in group:
sum = sum + item.Amount
if sum != Fixed8.Zero():
realresults.append(TransactionResult(key, sum))
return realresults | python | def GetTransactionResults(self):
if self.References is None:
return None
results = []
realresults = []
for ref_output in self.References.values():
results.append(TransactionResult(ref_output.AssetId, ref_output.Value))
for output in self.outputs:
results.append(TransactionResult(output.AssetId, output.Value * Fixed8(-1)))
for key, group in groupby(results, lambda x: x.AssetId):
sum = Fixed8(0)
for item in group:
sum = sum + item.Amount
if sum != Fixed8.Zero():
realresults.append(TransactionResult(key, sum))
return realresults | [
"def",
"GetTransactionResults",
"(",
"self",
")",
":",
"if",
"self",
".",
"References",
"is",
"None",
":",
"return",
"None",
"results",
"=",
"[",
"]",
"realresults",
"=",
"[",
"]",
"for",
"ref_output",
"in",
"self",
".",
"References",
".",
"values",
"(",... | Get the execution results of the transaction.
Returns:
None: if the transaction has no references.
list: of TransactionResult objects. | [
"Get",
"the",
"execution",
"results",
"of",
"the",
"transaction",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/TX/Transaction.py#L736-L763 |
229,014 | CityOfZion/neo-python | neo/SmartContract/ContractParameter.py | ContractParameter.ToParameter | def ToParameter(item: StackItem):
"""
Convert a StackItem to a ContractParameter object
Args:
item (neo.VM.InteropService.StackItem) The item to convert to a ContractParameter object
Returns:
ContractParameter
"""
if isinstance(item, Array) or isinstance(item, Struct):
items = item.GetArray()
output = [ContractParameter.ToParameter(subitem) for subitem in items]
return ContractParameter(type=ContractParameterType.Array, value=output)
elif isinstance(item, Boolean):
return ContractParameter(type=ContractParameterType.Boolean, value=item.GetBoolean())
elif isinstance(item, ByteArray):
return ContractParameter(type=ContractParameterType.ByteArray, value=item.GetByteArray())
elif isinstance(item, Integer):
return ContractParameter(type=ContractParameterType.Integer, value=str(item.GetBigInteger()))
elif isinstance(item, InteropInterface):
return ContractParameter(type=ContractParameterType.InteropInterface, value=item.GetInterface()) | python | def ToParameter(item: StackItem):
if isinstance(item, Array) or isinstance(item, Struct):
items = item.GetArray()
output = [ContractParameter.ToParameter(subitem) for subitem in items]
return ContractParameter(type=ContractParameterType.Array, value=output)
elif isinstance(item, Boolean):
return ContractParameter(type=ContractParameterType.Boolean, value=item.GetBoolean())
elif isinstance(item, ByteArray):
return ContractParameter(type=ContractParameterType.ByteArray, value=item.GetByteArray())
elif isinstance(item, Integer):
return ContractParameter(type=ContractParameterType.Integer, value=str(item.GetBigInteger()))
elif isinstance(item, InteropInterface):
return ContractParameter(type=ContractParameterType.InteropInterface, value=item.GetInterface()) | [
"def",
"ToParameter",
"(",
"item",
":",
"StackItem",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"Array",
")",
"or",
"isinstance",
"(",
"item",
",",
"Struct",
")",
":",
"items",
"=",
"item",
".",
"GetArray",
"(",
")",
"output",
"=",
"[",
"Contrac... | Convert a StackItem to a ContractParameter object
Args:
item (neo.VM.InteropService.StackItem) The item to convert to a ContractParameter object
Returns:
ContractParameter | [
"Convert",
"a",
"StackItem",
"to",
"a",
"ContractParameter",
"object"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/ContractParameter.py#L27-L53 |
229,015 | CityOfZion/neo-python | neo/SmartContract/ContractParameter.py | ContractParameter.ToJson | def ToJson(self, auto_hex=True):
"""
Converts a ContractParameter instance to a json representation
Returns:
dict: a dictionary representation of the contract parameter
"""
jsn = {}
jsn['type'] = str(ContractParameterType(self.Type))
if self.Type == ContractParameterType.Signature:
jsn['value'] = self.Value.hex()
elif self.Type == ContractParameterType.ByteArray:
if auto_hex:
jsn['value'] = self.Value.hex()
else:
jsn['value'] = self.Value
elif self.Type == ContractParameterType.Boolean:
jsn['value'] = self.Value
elif self.Type == ContractParameterType.String:
jsn['value'] = str(self.Value)
elif self.Type == ContractParameterType.Integer:
jsn['value'] = self.Value
# @TODO, see ``FromJson``, not sure if this is working properly
elif self.Type == ContractParameterType.PublicKey:
jsn['value'] = self.Value.ToString()
elif self.Type in [ContractParameterType.Hash160,
ContractParameterType.Hash256]:
jsn['value'] = self.Value.ToString()
elif self.Type == ContractParameterType.Array:
res = []
for item in self.Value:
if item:
res.append(item.ToJson(auto_hex=auto_hex))
jsn['value'] = res
elif self.Type == ContractParameterType.InteropInterface:
try:
jsn['value'] = self.Value.ToJson()
except Exception as e:
pass
return jsn | python | def ToJson(self, auto_hex=True):
jsn = {}
jsn['type'] = str(ContractParameterType(self.Type))
if self.Type == ContractParameterType.Signature:
jsn['value'] = self.Value.hex()
elif self.Type == ContractParameterType.ByteArray:
if auto_hex:
jsn['value'] = self.Value.hex()
else:
jsn['value'] = self.Value
elif self.Type == ContractParameterType.Boolean:
jsn['value'] = self.Value
elif self.Type == ContractParameterType.String:
jsn['value'] = str(self.Value)
elif self.Type == ContractParameterType.Integer:
jsn['value'] = self.Value
# @TODO, see ``FromJson``, not sure if this is working properly
elif self.Type == ContractParameterType.PublicKey:
jsn['value'] = self.Value.ToString()
elif self.Type in [ContractParameterType.Hash160,
ContractParameterType.Hash256]:
jsn['value'] = self.Value.ToString()
elif self.Type == ContractParameterType.Array:
res = []
for item in self.Value:
if item:
res.append(item.ToJson(auto_hex=auto_hex))
jsn['value'] = res
elif self.Type == ContractParameterType.InteropInterface:
try:
jsn['value'] = self.Value.ToJson()
except Exception as e:
pass
return jsn | [
"def",
"ToJson",
"(",
"self",
",",
"auto_hex",
"=",
"True",
")",
":",
"jsn",
"=",
"{",
"}",
"jsn",
"[",
"'type'",
"]",
"=",
"str",
"(",
"ContractParameterType",
"(",
"self",
".",
"Type",
")",
")",
"if",
"self",
".",
"Type",
"==",
"ContractParameterTy... | Converts a ContractParameter instance to a json representation
Returns:
dict: a dictionary representation of the contract parameter | [
"Converts",
"a",
"ContractParameter",
"instance",
"to",
"a",
"json",
"representation"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/ContractParameter.py#L81-L130 |
229,016 | CityOfZion/neo-python | neo/SmartContract/ContractParameter.py | ContractParameter.ToVM | def ToVM(self):
"""
Used for turning a ContractParameter item into somethnig consumable by the VM
Returns:
"""
if self.Type == ContractParameterType.String:
return str(self.Value).encode('utf-8').hex()
elif self.Type == ContractParameterType.Integer and isinstance(self.Value, int):
return BigInteger(self.Value)
return self.Value | python | def ToVM(self):
if self.Type == ContractParameterType.String:
return str(self.Value).encode('utf-8').hex()
elif self.Type == ContractParameterType.Integer and isinstance(self.Value, int):
return BigInteger(self.Value)
return self.Value | [
"def",
"ToVM",
"(",
"self",
")",
":",
"if",
"self",
".",
"Type",
"==",
"ContractParameterType",
".",
"String",
":",
"return",
"str",
"(",
"self",
".",
"Value",
")",
".",
"encode",
"(",
"'utf-8'",
")",
".",
"hex",
"(",
")",
"elif",
"self",
".",
"Typ... | Used for turning a ContractParameter item into somethnig consumable by the VM
Returns: | [
"Used",
"for",
"turning",
"a",
"ContractParameter",
"item",
"into",
"somethnig",
"consumable",
"by",
"the",
"VM"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/ContractParameter.py#L132-L143 |
229,017 | CityOfZion/neo-python | neo/SmartContract/ContractParameter.py | ContractParameter.FromJson | def FromJson(json):
"""
Convert a json object to a ContractParameter object
Args:
item (dict): The item to convert to a ContractParameter object
Returns:
ContractParameter
"""
type = ContractParameterType.FromString(json['type'])
value = json['value']
param = ContractParameter(type=type, value=None)
if type == ContractParameterType.Signature or type == ContractParameterType.ByteArray:
param.Value = bytearray.fromhex(value)
elif type == ContractParameterType.Boolean:
param.Value = bool(value)
elif type == ContractParameterType.Integer:
param.Value = int(value)
elif type == ContractParameterType.Hash160:
param.Value = UInt160.ParseString(value)
elif type == ContractParameterType.Hash256:
param.Value = UInt256.ParseString(value)
# @TODO Not sure if this is working...
elif type == ContractParameterType.PublicKey:
param.Value = ECDSA.decode_secp256r1(value).G
elif type == ContractParameterType.String:
param.Value = str(value)
elif type == ContractParameterType.Array:
val = [ContractParameter.FromJson(item) for item in value]
param.Value = val
return param | python | def FromJson(json):
type = ContractParameterType.FromString(json['type'])
value = json['value']
param = ContractParameter(type=type, value=None)
if type == ContractParameterType.Signature or type == ContractParameterType.ByteArray:
param.Value = bytearray.fromhex(value)
elif type == ContractParameterType.Boolean:
param.Value = bool(value)
elif type == ContractParameterType.Integer:
param.Value = int(value)
elif type == ContractParameterType.Hash160:
param.Value = UInt160.ParseString(value)
elif type == ContractParameterType.Hash256:
param.Value = UInt256.ParseString(value)
# @TODO Not sure if this is working...
elif type == ContractParameterType.PublicKey:
param.Value = ECDSA.decode_secp256r1(value).G
elif type == ContractParameterType.String:
param.Value = str(value)
elif type == ContractParameterType.Array:
val = [ContractParameter.FromJson(item) for item in value]
param.Value = val
return param | [
"def",
"FromJson",
"(",
"json",
")",
":",
"type",
"=",
"ContractParameterType",
".",
"FromString",
"(",
"json",
"[",
"'type'",
"]",
")",
"value",
"=",
"json",
"[",
"'value'",
"]",
"param",
"=",
"ContractParameter",
"(",
"type",
"=",
"type",
",",
"value",... | Convert a json object to a ContractParameter object
Args:
item (dict): The item to convert to a ContractParameter object
Returns:
ContractParameter | [
"Convert",
"a",
"json",
"object",
"to",
"a",
"ContractParameter",
"object"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/ContractParameter.py#L146-L188 |
229,018 | CityOfZion/neo-python | neo/Wallets/Coin.py | Coin.CoinFromRef | def CoinFromRef(coin_ref, tx_output, state=CoinState.Unconfirmed, transaction=None):
"""
Get a Coin object using a CoinReference.
Args:
coin_ref (neo.Core.CoinReference): an object representing a single UTXO / transaction input.
tx_output (neo.Core.Transaction.TransactionOutput): an object representing a transaction output.
state (neo.Core.State.CoinState):
Returns:
Coin: self.
"""
coin = Coin(coin_reference=coin_ref, tx_output=tx_output, state=state)
coin._transaction = transaction
return coin | python | def CoinFromRef(coin_ref, tx_output, state=CoinState.Unconfirmed, transaction=None):
coin = Coin(coin_reference=coin_ref, tx_output=tx_output, state=state)
coin._transaction = transaction
return coin | [
"def",
"CoinFromRef",
"(",
"coin_ref",
",",
"tx_output",
",",
"state",
"=",
"CoinState",
".",
"Unconfirmed",
",",
"transaction",
"=",
"None",
")",
":",
"coin",
"=",
"Coin",
"(",
"coin_reference",
"=",
"coin_ref",
",",
"tx_output",
"=",
"tx_output",
",",
"s... | Get a Coin object using a CoinReference.
Args:
coin_ref (neo.Core.CoinReference): an object representing a single UTXO / transaction input.
tx_output (neo.Core.Transaction.TransactionOutput): an object representing a transaction output.
state (neo.Core.State.CoinState):
Returns:
Coin: self. | [
"Get",
"a",
"Coin",
"object",
"using",
"a",
"CoinReference",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/Coin.py#L22-L36 |
229,019 | CityOfZion/neo-python | neo/Core/CoinReference.py | CoinReference.Equals | def Equals(self, other):
"""
Test for equality.
Args:
other (obj):
Returns:
bool: True `other` equals self.
"""
if other is None:
return False
if other.PrevHash.ToBytes() == self.PrevHash.ToBytes() and other.PrevIndex == self.PrevIndex:
return True
return False | python | def Equals(self, other):
if other is None:
return False
if other.PrevHash.ToBytes() == self.PrevHash.ToBytes() and other.PrevIndex == self.PrevIndex:
return True
return False | [
"def",
"Equals",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"None",
":",
"return",
"False",
"if",
"other",
".",
"PrevHash",
".",
"ToBytes",
"(",
")",
"==",
"self",
".",
"PrevHash",
".",
"ToBytes",
"(",
")",
"and",
"other",
".",
"Prev... | Test for equality.
Args:
other (obj):
Returns:
bool: True `other` equals self. | [
"Test",
"for",
"equality",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/CoinReference.py#L52-L66 |
229,020 | CityOfZion/neo-python | neo/Core/Helper.py | Helper.GetHashData | def GetHashData(hashable):
"""
Get the data used for hashing.
Args:
hashable (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin
Returns:
bytes:
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
hashable.SerializeUnsigned(writer)
ms.flush()
retVal = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retVal | python | def GetHashData(hashable):
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
hashable.SerializeUnsigned(writer)
ms.flush()
retVal = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retVal | [
"def",
"GetHashData",
"(",
"hashable",
")",
":",
"ms",
"=",
"StreamManager",
".",
"GetStream",
"(",
")",
"writer",
"=",
"BinaryWriter",
"(",
"ms",
")",
"hashable",
".",
"SerializeUnsigned",
"(",
"writer",
")",
"ms",
".",
"flush",
"(",
")",
"retVal",
"=",... | Get the data used for hashing.
Args:
hashable (neo.IO.Mixins.SerializableMixin): object extending SerializableMixin
Returns:
bytes: | [
"Get",
"the",
"data",
"used",
"for",
"hashing",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Helper.py#L36-L52 |
229,021 | CityOfZion/neo-python | neo/Core/Helper.py | Helper.Sign | def Sign(verifiable, keypair):
"""
Sign the `verifiable` object with the private key from `keypair`.
Args:
verifiable:
keypair (neocore.KeyPair):
Returns:
bool: True if successfully signed. False otherwise.
"""
prikey = bytes(keypair.PrivateKey)
hashdata = verifiable.GetHashData()
res = Crypto.Default().Sign(hashdata, prikey)
return res | python | def Sign(verifiable, keypair):
prikey = bytes(keypair.PrivateKey)
hashdata = verifiable.GetHashData()
res = Crypto.Default().Sign(hashdata, prikey)
return res | [
"def",
"Sign",
"(",
"verifiable",
",",
"keypair",
")",
":",
"prikey",
"=",
"bytes",
"(",
"keypair",
".",
"PrivateKey",
")",
"hashdata",
"=",
"verifiable",
".",
"GetHashData",
"(",
")",
"res",
"=",
"Crypto",
".",
"Default",
"(",
")",
".",
"Sign",
"(",
... | Sign the `verifiable` object with the private key from `keypair`.
Args:
verifiable:
keypair (neocore.KeyPair):
Returns:
bool: True if successfully signed. False otherwise. | [
"Sign",
"the",
"verifiable",
"object",
"with",
"the",
"private",
"key",
"from",
"keypair",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Helper.py#L55-L69 |
229,022 | CityOfZion/neo-python | neo/Core/Helper.py | Helper.AddrStrToScriptHash | def AddrStrToScriptHash(address):
"""
Convert a public address to a script hash.
Args:
address (str): base 58 check encoded public address.
Raises:
ValueError: if the address length of address version is incorrect.
Exception: if the address checksum fails.
Returns:
UInt160:
"""
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != settings.ADDRESS_VERSION:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21]) | python | def AddrStrToScriptHash(address):
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != settings.ADDRESS_VERSION:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21]) | [
"def",
"AddrStrToScriptHash",
"(",
"address",
")",
":",
"data",
"=",
"b58decode",
"(",
"address",
")",
"if",
"len",
"(",
"data",
")",
"!=",
"25",
":",
"raise",
"ValueError",
"(",
"'Not correct Address, wrong length.'",
")",
"if",
"data",
"[",
"0",
"]",
"!=... | Convert a public address to a script hash.
Args:
address (str): base 58 check encoded public address.
Raises:
ValueError: if the address length of address version is incorrect.
Exception: if the address checksum fails.
Returns:
UInt160: | [
"Convert",
"a",
"public",
"address",
"to",
"a",
"script",
"hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Helper.py#L114-L137 |
229,023 | CityOfZion/neo-python | neo/Core/Helper.py | Helper.RawBytesToScriptHash | def RawBytesToScriptHash(raw):
"""
Get a hash of the provided raw bytes using the ripemd160 algorithm.
Args:
raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC'
Returns:
UInt160:
"""
rawh = binascii.unhexlify(raw)
rawhashstr = binascii.unhexlify(bytes(Crypto.Hash160(rawh), encoding='utf-8'))
return UInt160(data=rawhashstr) | python | def RawBytesToScriptHash(raw):
rawh = binascii.unhexlify(raw)
rawhashstr = binascii.unhexlify(bytes(Crypto.Hash160(rawh), encoding='utf-8'))
return UInt160(data=rawhashstr) | [
"def",
"RawBytesToScriptHash",
"(",
"raw",
")",
":",
"rawh",
"=",
"binascii",
".",
"unhexlify",
"(",
"raw",
")",
"rawhashstr",
"=",
"binascii",
".",
"unhexlify",
"(",
"bytes",
"(",
"Crypto",
".",
"Hash160",
"(",
"rawh",
")",
",",
"encoding",
"=",
"'utf-8... | Get a hash of the provided raw bytes using the ripemd160 algorithm.
Args:
raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC'
Returns:
UInt160: | [
"Get",
"a",
"hash",
"of",
"the",
"provided",
"raw",
"bytes",
"using",
"the",
"ripemd160",
"algorithm",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Helper.py#L153-L165 |
229,024 | CityOfZion/neo-python | neo/Core/Helper.py | Helper.VerifyScripts | def VerifyScripts(verifiable):
"""
Verify the scripts of the provided `verifiable` object.
Args:
verifiable (neo.IO.Mixins.VerifiableMixin):
Returns:
bool: True if verification is successful. False otherwise.
"""
try:
hashes = verifiable.GetScriptHashesForVerifying()
except Exception as e:
logger.debug("couldn't get script hashes %s " % e)
return False
if len(hashes) != len(verifiable.Scripts):
logger.debug(f"hash - verification script length mismatch ({len(hashes)}/{len(verifiable.Scripts)})")
return False
blockchain = GetBlockchain()
for i in range(0, len(hashes)):
verification = verifiable.Scripts[i].VerificationScript
if len(verification) == 0:
sb = ScriptBuilder()
sb.EmitAppCall(hashes[i].Data)
verification = sb.ms.getvalue()
else:
verification_hash = Crypto.ToScriptHash(verification, unhex=False)
if hashes[i] != verification_hash:
logger.debug(f"hash {hashes[i]} does not match verification hash {verification_hash}")
return False
state_reader = GetStateReader()
script_table = CachedScriptTable(DBCollection(blockchain._db, DBPrefix.ST_Contract, ContractState))
engine = ApplicationEngine(TriggerType.Verification, verifiable, script_table, state_reader, Fixed8.Zero())
engine.LoadScript(verification)
invocation = verifiable.Scripts[i].InvocationScript
engine.LoadScript(invocation)
try:
success = engine.Execute()
state_reader.ExecutionCompleted(engine, success)
except Exception as e:
state_reader.ExecutionCompleted(engine, False, e)
if engine.ResultStack.Count != 1 or not engine.ResultStack.Pop().GetBoolean():
Helper.EmitServiceEvents(state_reader)
if engine.ResultStack.Count > 0:
logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count} bool value: {engine.ResultStack.Pop().GetBoolean()}")
else:
logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count}")
return False
Helper.EmitServiceEvents(state_reader)
return True | python | def VerifyScripts(verifiable):
try:
hashes = verifiable.GetScriptHashesForVerifying()
except Exception as e:
logger.debug("couldn't get script hashes %s " % e)
return False
if len(hashes) != len(verifiable.Scripts):
logger.debug(f"hash - verification script length mismatch ({len(hashes)}/{len(verifiable.Scripts)})")
return False
blockchain = GetBlockchain()
for i in range(0, len(hashes)):
verification = verifiable.Scripts[i].VerificationScript
if len(verification) == 0:
sb = ScriptBuilder()
sb.EmitAppCall(hashes[i].Data)
verification = sb.ms.getvalue()
else:
verification_hash = Crypto.ToScriptHash(verification, unhex=False)
if hashes[i] != verification_hash:
logger.debug(f"hash {hashes[i]} does not match verification hash {verification_hash}")
return False
state_reader = GetStateReader()
script_table = CachedScriptTable(DBCollection(blockchain._db, DBPrefix.ST_Contract, ContractState))
engine = ApplicationEngine(TriggerType.Verification, verifiable, script_table, state_reader, Fixed8.Zero())
engine.LoadScript(verification)
invocation = verifiable.Scripts[i].InvocationScript
engine.LoadScript(invocation)
try:
success = engine.Execute()
state_reader.ExecutionCompleted(engine, success)
except Exception as e:
state_reader.ExecutionCompleted(engine, False, e)
if engine.ResultStack.Count != 1 or not engine.ResultStack.Pop().GetBoolean():
Helper.EmitServiceEvents(state_reader)
if engine.ResultStack.Count > 0:
logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count} bool value: {engine.ResultStack.Pop().GetBoolean()}")
else:
logger.debug(f"Result stack failure! Count: {engine.ResultStack.Count}")
return False
Helper.EmitServiceEvents(state_reader)
return True | [
"def",
"VerifyScripts",
"(",
"verifiable",
")",
":",
"try",
":",
"hashes",
"=",
"verifiable",
".",
"GetScriptHashesForVerifying",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"\"couldn't get script hashes %s \"",
"%",
"e",
")",
... | Verify the scripts of the provided `verifiable` object.
Args:
verifiable (neo.IO.Mixins.VerifiableMixin):
Returns:
bool: True if verification is successful. False otherwise. | [
"Verify",
"the",
"scripts",
"of",
"the",
"provided",
"verifiable",
"object",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Helper.py#L168-L227 |
229,025 | CityOfZion/neo-python | neo/Core/State/AssetState.py | AssetState.GetName | def GetName(self):
"""
Get the asset name based on its type.
Returns:
str: 'NEO' or 'NEOGas'
"""
if self.AssetType == AssetType.GoverningToken:
return "NEO"
elif self.AssetType == AssetType.UtilityToken:
return "NEOGas"
if type(self.Name) is bytes:
return self.Name.decode('utf-8')
return self.Name | python | def GetName(self):
if self.AssetType == AssetType.GoverningToken:
return "NEO"
elif self.AssetType == AssetType.UtilityToken:
return "NEOGas"
if type(self.Name) is bytes:
return self.Name.decode('utf-8')
return self.Name | [
"def",
"GetName",
"(",
"self",
")",
":",
"if",
"self",
".",
"AssetType",
"==",
"AssetType",
".",
"GoverningToken",
":",
"return",
"\"NEO\"",
"elif",
"self",
".",
"AssetType",
"==",
"AssetType",
".",
"UtilityToken",
":",
"return",
"\"NEOGas\"",
"if",
"type",
... | Get the asset name based on its type.
Returns:
str: 'NEO' or 'NEOGas' | [
"Get",
"the",
"asset",
"name",
"based",
"on",
"its",
"type",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/AssetState.py#L161-L175 |
229,026 | CityOfZion/neo-python | neo/Core/Blockchain.py | Blockchain.GenesisBlock | def GenesisBlock() -> Block:
"""
Create the GenesisBlock.
Returns:
BLock:
"""
prev_hash = UInt256(data=bytearray(32))
timestamp = int(datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp())
index = 0
consensus_data = 2083236893 # Pay tribute To Bitcoin
next_consensus = Blockchain.GetConsensusAddress(Blockchain.StandbyValidators())
script = Witness(bytearray(0), bytearray(PUSHT))
mt = MinerTransaction()
mt.Nonce = 2083236893
output = TransactionOutput(
Blockchain.SystemShare().Hash,
Blockchain.SystemShare().Amount,
Crypto.ToScriptHash(Contract.CreateMultiSigRedeemScript(int(len(Blockchain.StandbyValidators()) / 2) + 1,
Blockchain.StandbyValidators()))
)
it = IssueTransaction([], [output], [], [script])
return Block(prev_hash, timestamp, index, consensus_data,
next_consensus, script,
[mt, Blockchain.SystemShare(), Blockchain.SystemCoin(), it],
True) | python | def GenesisBlock() -> Block:
prev_hash = UInt256(data=bytearray(32))
timestamp = int(datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp())
index = 0
consensus_data = 2083236893 # Pay tribute To Bitcoin
next_consensus = Blockchain.GetConsensusAddress(Blockchain.StandbyValidators())
script = Witness(bytearray(0), bytearray(PUSHT))
mt = MinerTransaction()
mt.Nonce = 2083236893
output = TransactionOutput(
Blockchain.SystemShare().Hash,
Blockchain.SystemShare().Amount,
Crypto.ToScriptHash(Contract.CreateMultiSigRedeemScript(int(len(Blockchain.StandbyValidators()) / 2) + 1,
Blockchain.StandbyValidators()))
)
it = IssueTransaction([], [output], [], [script])
return Block(prev_hash, timestamp, index, consensus_data,
next_consensus, script,
[mt, Blockchain.SystemShare(), Blockchain.SystemCoin(), it],
True) | [
"def",
"GenesisBlock",
"(",
")",
"->",
"Block",
":",
"prev_hash",
"=",
"UInt256",
"(",
"data",
"=",
"bytearray",
"(",
"32",
")",
")",
"timestamp",
"=",
"int",
"(",
"datetime",
"(",
"2016",
",",
"7",
",",
"15",
",",
"15",
",",
"8",
",",
"21",
",",... | Create the GenesisBlock.
Returns:
BLock: | [
"Create",
"the",
"GenesisBlock",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Blockchain.py#L99-L128 |
229,027 | CityOfZion/neo-python | neo/Core/Blockchain.py | Blockchain.Default | def Default() -> 'Blockchain':
"""
Get the default registered blockchain instance.
Returns:
obj: Currently set to `neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain`.
"""
if Blockchain._instance is None:
Blockchain._instance = Blockchain()
Blockchain.GenesisBlock().RebuildMerkleRoot()
return Blockchain._instance | python | def Default() -> 'Blockchain':
if Blockchain._instance is None:
Blockchain._instance = Blockchain()
Blockchain.GenesisBlock().RebuildMerkleRoot()
return Blockchain._instance | [
"def",
"Default",
"(",
")",
"->",
"'Blockchain'",
":",
"if",
"Blockchain",
".",
"_instance",
"is",
"None",
":",
"Blockchain",
".",
"_instance",
"=",
"Blockchain",
"(",
")",
"Blockchain",
".",
"GenesisBlock",
"(",
")",
".",
"RebuildMerkleRoot",
"(",
")",
"r... | Get the default registered blockchain instance.
Returns:
obj: Currently set to `neo.Implementations.Blockchains.LevelDB.LevelDBBlockchain`. | [
"Get",
"the",
"default",
"registered",
"blockchain",
"instance",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Blockchain.py#L131-L142 |
229,028 | CityOfZion/neo-python | neo/Core/Blockchain.py | Blockchain.GetConsensusAddress | def GetConsensusAddress(validators):
"""
Get the script hash of the consensus node.
Args:
validators (list): of Ellipticcurve.ECPoint's
Returns:
UInt160:
"""
vlen = len(validators)
script = Contract.CreateMultiSigRedeemScript(vlen - int((vlen - 1) / 3), validators)
return Crypto.ToScriptHash(script) | python | def GetConsensusAddress(validators):
vlen = len(validators)
script = Contract.CreateMultiSigRedeemScript(vlen - int((vlen - 1) / 3), validators)
return Crypto.ToScriptHash(script) | [
"def",
"GetConsensusAddress",
"(",
"validators",
")",
":",
"vlen",
"=",
"len",
"(",
"validators",
")",
"script",
"=",
"Contract",
".",
"CreateMultiSigRedeemScript",
"(",
"vlen",
"-",
"int",
"(",
"(",
"vlen",
"-",
"1",
")",
"/",
"3",
")",
",",
"validators... | Get the script hash of the consensus node.
Args:
validators (list): of Ellipticcurve.ECPoint's
Returns:
UInt160: | [
"Get",
"the",
"script",
"hash",
"of",
"the",
"consensus",
"node",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Blockchain.py#L359-L371 |
229,029 | CityOfZion/neo-python | neo/Core/Blockchain.py | Blockchain.GetSysFeeAmountByHeight | def GetSysFeeAmountByHeight(self, height):
"""
Get the system fee for the specified block.
Args:
height (int): block height.
Returns:
int:
"""
hash = self.GetBlockHash(height)
return self.GetSysFeeAmount(hash) | python | def GetSysFeeAmountByHeight(self, height):
hash = self.GetBlockHash(height)
return self.GetSysFeeAmount(hash) | [
"def",
"GetSysFeeAmountByHeight",
"(",
"self",
",",
"height",
")",
":",
"hash",
"=",
"self",
".",
"GetBlockHash",
"(",
"height",
")",
"return",
"self",
".",
"GetSysFeeAmount",
"(",
"hash",
")"
] | Get the system fee for the specified block.
Args:
height (int): block height.
Returns:
int: | [
"Get",
"the",
"system",
"fee",
"for",
"the",
"specified",
"block",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Blockchain.py#L414-L425 |
229,030 | CityOfZion/neo-python | neo/Core/Blockchain.py | Blockchain.DeregisterBlockchain | def DeregisterBlockchain():
"""
Remove the default blockchain instance.
"""
Blockchain.SECONDS_PER_BLOCK = 15
Blockchain.DECREMENT_INTERVAL = 2000000
Blockchain.GENERATION_AMOUNT = [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Blockchain._blockchain = None
Blockchain._validators = []
Blockchain._genesis_block = None
Blockchain._instance = None
Blockchain._blockrequests = set()
Blockchain._paused = False
Blockchain.BlockSearchTries = 0
Blockchain.CACHELIM = 4000
Blockchain.CMISSLIM = 5
Blockchain.LOOPTIME = .1
Blockchain.PersistCompleted = Events()
Blockchain.Notify = Events()
Blockchain._instance = None | python | def DeregisterBlockchain():
Blockchain.SECONDS_PER_BLOCK = 15
Blockchain.DECREMENT_INTERVAL = 2000000
Blockchain.GENERATION_AMOUNT = [8, 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Blockchain._blockchain = None
Blockchain._validators = []
Blockchain._genesis_block = None
Blockchain._instance = None
Blockchain._blockrequests = set()
Blockchain._paused = False
Blockchain.BlockSearchTries = 0
Blockchain.CACHELIM = 4000
Blockchain.CMISSLIM = 5
Blockchain.LOOPTIME = .1
Blockchain.PersistCompleted = Events()
Blockchain.Notify = Events()
Blockchain._instance = None | [
"def",
"DeregisterBlockchain",
"(",
")",
":",
"Blockchain",
".",
"SECONDS_PER_BLOCK",
"=",
"15",
"Blockchain",
".",
"DECREMENT_INTERVAL",
"=",
"2000000",
"Blockchain",
".",
"GENERATION_AMOUNT",
"=",
"[",
"8",
",",
"7",
",",
"6",
",",
"5",
",",
"4",
",",
"3... | Remove the default blockchain instance. | [
"Remove",
"the",
"default",
"blockchain",
"instance",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Blockchain.py#L474-L493 |
229,031 | CityOfZion/neo-python | neo/logging.py | LogManager.config_stdio | def config_stdio(self, log_configurations: Optional[List[LogConfiguration]] = None, default_level=logging.INFO) -> None:
"""
Configure the stdio `StreamHandler` levels on the specified loggers.
If no log configurations are specified then the `default_level` will be applied to all handlers.
Args:
log_configurations: a list of (component name, log level) tuples
default_level: logging level to apply when no log_configurations are specified
"""
# no configuration specified, apply `default_level` to the stdio handler of all known loggers
if not log_configurations:
for logger in self.loggers.values():
self._restrict_output(logger, default_level)
# only apply specified configuration to the stdio `StreamHandler` of the specific component
else:
for component, level in log_configurations:
try:
logger = self.loggers[self.root + component]
except KeyError:
raise ValueError("Failed to configure component. Invalid name: {}".format(component))
self._restrict_output(logger, level) | python | def config_stdio(self, log_configurations: Optional[List[LogConfiguration]] = None, default_level=logging.INFO) -> None:
# no configuration specified, apply `default_level` to the stdio handler of all known loggers
if not log_configurations:
for logger in self.loggers.values():
self._restrict_output(logger, default_level)
# only apply specified configuration to the stdio `StreamHandler` of the specific component
else:
for component, level in log_configurations:
try:
logger = self.loggers[self.root + component]
except KeyError:
raise ValueError("Failed to configure component. Invalid name: {}".format(component))
self._restrict_output(logger, level) | [
"def",
"config_stdio",
"(",
"self",
",",
"log_configurations",
":",
"Optional",
"[",
"List",
"[",
"LogConfiguration",
"]",
"]",
"=",
"None",
",",
"default_level",
"=",
"logging",
".",
"INFO",
")",
"->",
"None",
":",
"# no configuration specified, apply `default_le... | Configure the stdio `StreamHandler` levels on the specified loggers.
If no log configurations are specified then the `default_level` will be applied to all handlers.
Args:
log_configurations: a list of (component name, log level) tuples
default_level: logging level to apply when no log_configurations are specified | [
"Configure",
"the",
"stdio",
"StreamHandler",
"levels",
"on",
"the",
"specified",
"loggers",
".",
"If",
"no",
"log",
"configurations",
"are",
"specified",
"then",
"the",
"default_level",
"will",
"be",
"applied",
"to",
"all",
"handlers",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/logging.py#L63-L83 |
229,032 | CityOfZion/neo-python | neo/logging.py | LogManager.getLogger | def getLogger(self, component_name: str = None) -> logging.Logger:
"""
Get the logger instance matching ``component_name`` or create a new one if non-existent.
Args:
component_name: a neo-python component name. e.g. network, vm, db
Returns:
a logger for the specified component.
"""
logger_name = self.root + (component_name if component_name else 'generic')
_logger = self.loggers.get(logger_name)
if not _logger:
_logger = logging.getLogger(logger_name)
stdio_handler = logging.StreamHandler()
stdio_handler.setFormatter(LogFormatter())
stdio_handler.setLevel(logging.INFO)
_logger.addHandler(stdio_handler)
_logger.setLevel(logging.DEBUG)
self.loggers[logger_name] = _logger
return _logger | python | def getLogger(self, component_name: str = None) -> logging.Logger:
logger_name = self.root + (component_name if component_name else 'generic')
_logger = self.loggers.get(logger_name)
if not _logger:
_logger = logging.getLogger(logger_name)
stdio_handler = logging.StreamHandler()
stdio_handler.setFormatter(LogFormatter())
stdio_handler.setLevel(logging.INFO)
_logger.addHandler(stdio_handler)
_logger.setLevel(logging.DEBUG)
self.loggers[logger_name] = _logger
return _logger | [
"def",
"getLogger",
"(",
"self",
",",
"component_name",
":",
"str",
"=",
"None",
")",
"->",
"logging",
".",
"Logger",
":",
"logger_name",
"=",
"self",
".",
"root",
"+",
"(",
"component_name",
"if",
"component_name",
"else",
"'generic'",
")",
"_logger",
"="... | Get the logger instance matching ``component_name`` or create a new one if non-existent.
Args:
component_name: a neo-python component name. e.g. network, vm, db
Returns:
a logger for the specified component. | [
"Get",
"the",
"logger",
"instance",
"matching",
"component_name",
"or",
"create",
"a",
"new",
"one",
"if",
"non",
"-",
"existent",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/logging.py#L109-L130 |
229,033 | CityOfZion/neo-python | neo/VM/ExecutionEngine.py | ExecutionEngine.write_log | def write_log(self, message):
"""
Write a line to the VM instruction log file.
Args:
message (str): string message to write to file.
"""
if self._is_write_log and self.log_file and not self.log_file.closed:
self.log_file.write(message + '\n') | python | def write_log(self, message):
if self._is_write_log and self.log_file and not self.log_file.closed:
self.log_file.write(message + '\n') | [
"def",
"write_log",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"_is_write_log",
"and",
"self",
".",
"log_file",
"and",
"not",
"self",
".",
"log_file",
".",
"closed",
":",
"self",
".",
"log_file",
".",
"write",
"(",
"message",
"+",
"'\\n'... | Write a line to the VM instruction log file.
Args:
message (str): string message to write to file. | [
"Write",
"a",
"line",
"to",
"the",
"VM",
"instruction",
"log",
"file",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/VM/ExecutionEngine.py#L47-L55 |
229,034 | CityOfZion/neo-python | neo/Prompt/Commands/Wallet.py | ShowUnspentCoins | def ShowUnspentCoins(wallet, asset_id=None, from_addr=None, watch_only=False, do_count=False):
"""
Show unspent coin objects in the wallet.
Args:
wallet (neo.Wallet): wallet to show unspent coins from.
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
watch_only (bool): indicate if this shows coins that are in 'watch only' addresses.
do_count (bool): if True only show a count of unspent assets.
Returns:
list: a list of unspent ``neo.Wallet.Coin`` in the wallet
"""
if wallet is None:
print("Please open a wallet.")
return
watch_only_flag = 64 if watch_only else 0
if asset_id:
unspents = wallet.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr, watch_only_val=watch_only_flag)
else:
unspents = wallet.FindUnspentCoins(from_addr=from_addr, watch_only_val=watch_only)
if do_count:
print('\n-----------------------------------------------')
print('Total Unspent: %s' % len(unspents))
return unspents
for unspent in unspents:
print('\n-----------------------------------------------')
print(json.dumps(unspent.ToJson(), indent=4))
if not unspents:
print("No unspent assets matching the arguments.")
return unspents | python | def ShowUnspentCoins(wallet, asset_id=None, from_addr=None, watch_only=False, do_count=False):
if wallet is None:
print("Please open a wallet.")
return
watch_only_flag = 64 if watch_only else 0
if asset_id:
unspents = wallet.FindUnspentCoinsByAsset(asset_id, from_addr=from_addr, watch_only_val=watch_only_flag)
else:
unspents = wallet.FindUnspentCoins(from_addr=from_addr, watch_only_val=watch_only)
if do_count:
print('\n-----------------------------------------------')
print('Total Unspent: %s' % len(unspents))
return unspents
for unspent in unspents:
print('\n-----------------------------------------------')
print(json.dumps(unspent.ToJson(), indent=4))
if not unspents:
print("No unspent assets matching the arguments.")
return unspents | [
"def",
"ShowUnspentCoins",
"(",
"wallet",
",",
"asset_id",
"=",
"None",
",",
"from_addr",
"=",
"None",
",",
"watch_only",
"=",
"False",
",",
"do_count",
"=",
"False",
")",
":",
"if",
"wallet",
"is",
"None",
":",
"print",
"(",
"\"Please open a wallet.\"",
"... | Show unspent coin objects in the wallet.
Args:
wallet (neo.Wallet): wallet to show unspent coins from.
asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain.
from_addr (UInt160): a bytearray (len 20) representing an address.
watch_only (bool): indicate if this shows coins that are in 'watch only' addresses.
do_count (bool): if True only show a count of unspent assets.
Returns:
list: a list of unspent ``neo.Wallet.Coin`` in the wallet | [
"Show",
"unspent",
"coin",
"objects",
"in",
"the",
"wallet",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Prompt/Commands/Wallet.py#L375-L412 |
229,035 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.FromDBInstance | def FromDBInstance(db_token):
"""
Get a NEP5Token instance from a database token.
Args:
db_token (neo.Implementations.Wallets.peewee.Models.NEP5Token):
Returns:
NEP5Token: self.
"""
hash_ar = bytearray(binascii.unhexlify(db_token.ContractHash))
hash_ar.reverse()
hash = UInt160(data=hash_ar)
token = NEP5Token(script=None)
token.SetScriptHash(hash)
token.name = db_token.Name
token.symbol = db_token.Symbol
token.decimals = db_token.Decimals
return token | python | def FromDBInstance(db_token):
hash_ar = bytearray(binascii.unhexlify(db_token.ContractHash))
hash_ar.reverse()
hash = UInt160(data=hash_ar)
token = NEP5Token(script=None)
token.SetScriptHash(hash)
token.name = db_token.Name
token.symbol = db_token.Symbol
token.decimals = db_token.Decimals
return token | [
"def",
"FromDBInstance",
"(",
"db_token",
")",
":",
"hash_ar",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"db_token",
".",
"ContractHash",
")",
")",
"hash_ar",
".",
"reverse",
"(",
")",
"hash",
"=",
"UInt160",
"(",
"data",
"=",
"hash_ar",
... | Get a NEP5Token instance from a database token.
Args:
db_token (neo.Implementations.Wallets.peewee.Models.NEP5Token):
Returns:
NEP5Token: self. | [
"Get",
"a",
"NEP5Token",
"instance",
"from",
"a",
"database",
"token",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L44-L62 |
229,036 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.Address | def Address(self):
"""
Get the wallet address associated with the token.
Returns:
str: base58 encoded string representing the wallet address.
"""
if self._address is None:
self._address = Crypto.ToAddress(self.ScriptHash)
return self._address | python | def Address(self):
if self._address is None:
self._address = Crypto.ToAddress(self.ScriptHash)
return self._address | [
"def",
"Address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_address",
"is",
"None",
":",
"self",
".",
"_address",
"=",
"Crypto",
".",
"ToAddress",
"(",
"self",
".",
"ScriptHash",
")",
"return",
"self",
".",
"_address"
] | Get the wallet address associated with the token.
Returns:
str: base58 encoded string representing the wallet address. | [
"Get",
"the",
"wallet",
"address",
"associated",
"with",
"the",
"token",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L65-L74 |
229,037 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.GetBalance | def GetBalance(self, wallet, address, as_string=False):
"""
Get the token balance.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
address (str): public address of the account to get the token balance of.
as_string (bool): whether the return value should be a string. Default is False, returning an integer.
Returns:
int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed.
"""
addr = PromptUtils.parse_param(address, wallet)
if isinstance(addr, UInt160):
addr = addr.Data
sb = ScriptBuilder()
sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr])
tx, fee, results, num_ops, engine_success = test_invoke(sb.ToArray(), wallet, [])
if engine_success:
try:
val = results[0].GetBigInteger()
precision_divisor = pow(10, self.decimals)
balance = Decimal(val) / Decimal(precision_divisor)
if as_string:
formatter_str = '.%sf' % self.decimals
balance_str = format(balance, formatter_str)
return balance_str
return balance
except Exception as e:
logger.error("could not get balance: %s " % e)
traceback.print_stack()
else:
addr_str = Crypto.ToAddress(UInt160(data=addr))
logger.error(
f"Could not get balance of address {addr_str} for token contract {self.ScriptHash}. VM execution failed. Make sure the contract exists on the network and that it adheres to the NEP-5 standard")
return 0 | python | def GetBalance(self, wallet, address, as_string=False):
addr = PromptUtils.parse_param(address, wallet)
if isinstance(addr, UInt160):
addr = addr.Data
sb = ScriptBuilder()
sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'balanceOf', [addr])
tx, fee, results, num_ops, engine_success = test_invoke(sb.ToArray(), wallet, [])
if engine_success:
try:
val = results[0].GetBigInteger()
precision_divisor = pow(10, self.decimals)
balance = Decimal(val) / Decimal(precision_divisor)
if as_string:
formatter_str = '.%sf' % self.decimals
balance_str = format(balance, formatter_str)
return balance_str
return balance
except Exception as e:
logger.error("could not get balance: %s " % e)
traceback.print_stack()
else:
addr_str = Crypto.ToAddress(UInt160(data=addr))
logger.error(
f"Could not get balance of address {addr_str} for token contract {self.ScriptHash}. VM execution failed. Make sure the contract exists on the network and that it adheres to the NEP-5 standard")
return 0 | [
"def",
"GetBalance",
"(",
"self",
",",
"wallet",
",",
"address",
",",
"as_string",
"=",
"False",
")",
":",
"addr",
"=",
"PromptUtils",
".",
"parse_param",
"(",
"address",
",",
"wallet",
")",
"if",
"isinstance",
"(",
"addr",
",",
"UInt160",
")",
":",
"a... | Get the token balance.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
address (str): public address of the account to get the token balance of.
as_string (bool): whether the return value should be a string. Default is False, returning an integer.
Returns:
int/str: token balance value as int (default), token balanace as string if `as_string` is set to True. 0 if balance retrieval failed. | [
"Get",
"the",
"token",
"balance",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L118-L155 |
229,038 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.Transfer | def Transfer(self, wallet, from_addr, to_addr, amount, tx_attributes=None):
"""
Transfer a specified amount of the NEP5Token to another address.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
from_addr (str): public address of the account to transfer the given amount from.
to_addr (str): public address of the account to transfer the given amount to.
amount (int): quantity to send.
tx_attributes (list): a list of TransactionAtribute objects.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluationstack results.
"""
if not tx_attributes:
tx_attributes = []
sb = ScriptBuilder()
sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'transfer',
[PromptUtils.parse_param(from_addr, wallet), PromptUtils.parse_param(to_addr, wallet),
PromptUtils.parse_param(amount)])
tx, fee, results, num_ops, engine_success = test_invoke(sb.ToArray(), wallet, [], from_addr=from_addr, invoke_attrs=tx_attributes)
return tx, fee, results | python | def Transfer(self, wallet, from_addr, to_addr, amount, tx_attributes=None):
if not tx_attributes:
tx_attributes = []
sb = ScriptBuilder()
sb.EmitAppCallWithOperationAndArgs(self.ScriptHash, 'transfer',
[PromptUtils.parse_param(from_addr, wallet), PromptUtils.parse_param(to_addr, wallet),
PromptUtils.parse_param(amount)])
tx, fee, results, num_ops, engine_success = test_invoke(sb.ToArray(), wallet, [], from_addr=from_addr, invoke_attrs=tx_attributes)
return tx, fee, results | [
"def",
"Transfer",
"(",
"self",
",",
"wallet",
",",
"from_addr",
",",
"to_addr",
",",
"amount",
",",
"tx_attributes",
"=",
"None",
")",
":",
"if",
"not",
"tx_attributes",
":",
"tx_attributes",
"=",
"[",
"]",
"sb",
"=",
"ScriptBuilder",
"(",
")",
"sb",
... | Transfer a specified amount of the NEP5Token to another address.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
from_addr (str): public address of the account to transfer the given amount from.
to_addr (str): public address of the account to transfer the given amount to.
amount (int): quantity to send.
tx_attributes (list): a list of TransactionAtribute objects.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluationstack results. | [
"Transfer",
"a",
"specified",
"amount",
"of",
"the",
"NEP5Token",
"to",
"another",
"address",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L157-L184 |
229,039 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.TransferFrom | def TransferFrom(self, wallet, from_addr, to_addr, amount):
"""
Transfer a specified amount of a token from the wallet specified in the `from_addr` to the `to_addr`
if the originator `wallet` has been approved to do so.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
from_addr (str): public address of the account to transfer the given amount from.
to_addr (str): public address of the account to transfer the given amount to.
amount (int): quantity to send.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results.
"""
invoke_args = [self.ScriptHash.ToString(), 'transferFrom',
[PromptUtils.parse_param(from_addr, wallet), PromptUtils.parse_param(to_addr, wallet), PromptUtils.parse_param(amount)]]
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True)
return tx, fee, results | python | def TransferFrom(self, wallet, from_addr, to_addr, amount):
invoke_args = [self.ScriptHash.ToString(), 'transferFrom',
[PromptUtils.parse_param(from_addr, wallet), PromptUtils.parse_param(to_addr, wallet), PromptUtils.parse_param(amount)]]
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True)
return tx, fee, results | [
"def",
"TransferFrom",
"(",
"self",
",",
"wallet",
",",
"from_addr",
",",
"to_addr",
",",
"amount",
")",
":",
"invoke_args",
"=",
"[",
"self",
".",
"ScriptHash",
".",
"ToString",
"(",
")",
",",
"'transferFrom'",
",",
"[",
"PromptUtils",
".",
"parse_param",... | Transfer a specified amount of a token from the wallet specified in the `from_addr` to the `to_addr`
if the originator `wallet` has been approved to do so.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
from_addr (str): public address of the account to transfer the given amount from.
to_addr (str): public address of the account to transfer the given amount to.
amount (int): quantity to send.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results. | [
"Transfer",
"a",
"specified",
"amount",
"of",
"a",
"token",
"from",
"the",
"wallet",
"specified",
"in",
"the",
"from_addr",
"to",
"the",
"to_addr",
"if",
"the",
"originator",
"wallet",
"has",
"been",
"approved",
"to",
"do",
"so",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L186-L208 |
229,040 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.Allowance | def Allowance(self, wallet, owner_addr, requestor_addr):
"""
Return the amount of tokens that the `requestor_addr` account can transfer from the `owner_addr` account.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
owner_addr (str): public address of the account to transfer the given amount from.
requestor_addr (str): public address of the account that requests the transfer.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results.
"""
invoke_args = [self.ScriptHash.ToString(), 'allowance',
[PromptUtils.parse_param(owner_addr, wallet), PromptUtils.parse_param(requestor_addr, wallet)]]
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True)
return tx, fee, results | python | def Allowance(self, wallet, owner_addr, requestor_addr):
invoke_args = [self.ScriptHash.ToString(), 'allowance',
[PromptUtils.parse_param(owner_addr, wallet), PromptUtils.parse_param(requestor_addr, wallet)]]
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True)
return tx, fee, results | [
"def",
"Allowance",
"(",
"self",
",",
"wallet",
",",
"owner_addr",
",",
"requestor_addr",
")",
":",
"invoke_args",
"=",
"[",
"self",
".",
"ScriptHash",
".",
"ToString",
"(",
")",
",",
"'allowance'",
",",
"[",
"PromptUtils",
".",
"parse_param",
"(",
"owner_... | Return the amount of tokens that the `requestor_addr` account can transfer from the `owner_addr` account.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
owner_addr (str): public address of the account to transfer the given amount from.
requestor_addr (str): public address of the account that requests the transfer.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results. | [
"Return",
"the",
"amount",
"of",
"tokens",
"that",
"the",
"requestor_addr",
"account",
"can",
"transfer",
"from",
"the",
"owner_addr",
"account",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L210-L230 |
229,041 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.Mint | def Mint(self, wallet, mint_to_addr, attachment_args, invoke_attrs=None):
"""
Call the "mintTokens" function of the smart contract.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
mint_to_addr (str): public address of the account to mint the tokens to.
attachment_args: (list): a list of arguments used to attach neo and/or gas to an invoke, eg ['--attach-gas=10.0','--attach-neo=3']
invoke_attrs: (list): a list of TransactionAttributes to be attached to the mint transaction
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results.
"""
invoke_args = [self.ScriptHash.ToString(), 'mintTokens', []]
invoke_args = invoke_args + attachment_args
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True, from_addr=mint_to_addr, invoke_attrs=invoke_attrs)
return tx, fee, results | python | def Mint(self, wallet, mint_to_addr, attachment_args, invoke_attrs=None):
invoke_args = [self.ScriptHash.ToString(), 'mintTokens', []]
invoke_args = invoke_args + attachment_args
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True, from_addr=mint_to_addr, invoke_attrs=invoke_attrs)
return tx, fee, results | [
"def",
"Mint",
"(",
"self",
",",
"wallet",
",",
"mint_to_addr",
",",
"attachment_args",
",",
"invoke_attrs",
"=",
"None",
")",
":",
"invoke_args",
"=",
"[",
"self",
".",
"ScriptHash",
".",
"ToString",
"(",
")",
",",
"'mintTokens'",
",",
"[",
"]",
"]",
... | Call the "mintTokens" function of the smart contract.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
mint_to_addr (str): public address of the account to mint the tokens to.
attachment_args: (list): a list of arguments used to attach neo and/or gas to an invoke, eg ['--attach-gas=10.0','--attach-neo=3']
invoke_attrs: (list): a list of TransactionAttributes to be attached to the mint transaction
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results. | [
"Call",
"the",
"mintTokens",
"function",
"of",
"the",
"smart",
"contract",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L255-L276 |
229,042 | CityOfZion/neo-python | neo/Wallets/NEP5Token.py | NEP5Token.CrowdsaleRegister | def CrowdsaleRegister(self, wallet, register_addresses, from_addr=None):
"""
Register for a crowd sale.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
register_addresses (list): list of public addresses to register for the sale.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results.
"""
invoke_args = [self.ScriptHash.ToString(), 'crowdsale_register',
[PromptUtils.parse_param(p, wallet) for p in register_addresses]]
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True, from_addr)
return tx, fee, results | python | def CrowdsaleRegister(self, wallet, register_addresses, from_addr=None):
invoke_args = [self.ScriptHash.ToString(), 'crowdsale_register',
[PromptUtils.parse_param(p, wallet) for p in register_addresses]]
tx, fee, results, num_ops, engine_success = TestInvokeContract(wallet, invoke_args, None, True, from_addr)
return tx, fee, results | [
"def",
"CrowdsaleRegister",
"(",
"self",
",",
"wallet",
",",
"register_addresses",
",",
"from_addr",
"=",
"None",
")",
":",
"invoke_args",
"=",
"[",
"self",
".",
"ScriptHash",
".",
"ToString",
"(",
")",
",",
"'crowdsale_register'",
",",
"[",
"PromptUtils",
"... | Register for a crowd sale.
Args:
wallet (neo.Wallets.Wallet): a wallet instance.
register_addresses (list): list of public addresses to register for the sale.
Returns:
tuple:
InvocationTransaction: the transaction.
int: the transaction fee.
list: the neo VM evaluation stack results. | [
"Register",
"for",
"a",
"crowd",
"sale",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Wallets/NEP5Token.py#L278-L297 |
229,043 | CityOfZion/neo-python | neo/Core/State/SpentCoinState.py | SpentCoinState.DeleteIndex | def DeleteIndex(self, index):
"""
Remove a spent coin based on its index.
Args:
index (int):
"""
to_remove = None
for i in self.Items:
if i.index == index:
to_remove = i
if to_remove:
self.Items.remove(to_remove) | python | def DeleteIndex(self, index):
to_remove = None
for i in self.Items:
if i.index == index:
to_remove = i
if to_remove:
self.Items.remove(to_remove) | [
"def",
"DeleteIndex",
"(",
"self",
",",
"index",
")",
":",
"to_remove",
"=",
"None",
"for",
"i",
"in",
"self",
".",
"Items",
":",
"if",
"i",
".",
"index",
"==",
"index",
":",
"to_remove",
"=",
"i",
"if",
"to_remove",
":",
"self",
".",
"Items",
".",... | Remove a spent coin based on its index.
Args:
index (int): | [
"Remove",
"a",
"spent",
"coin",
"based",
"on",
"its",
"index",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/State/SpentCoinState.py#L115-L128 |
229,044 | CityOfZion/neo-python | neo/api/JSONRPC/JsonRpcApi.py | JsonRpcApi.get_peers | def get_peers(self):
"""Get all known nodes and their 'state' """
node = NodeLeader.Instance()
result = {"connected": [], "unconnected": [], "bad": []}
connected_peers = []
for peer in node.Peers:
result['connected'].append({"address": peer.host,
"port": peer.port})
connected_peers.append("{}:{}".format(peer.host, peer.port))
for addr in node.DEAD_ADDRS:
host, port = addr.rsplit(':', 1)
result['bad'].append({"address": host, "port": port})
# "UnconnectedPeers" is never used. So a check is needed to
# verify that a given address:port does not belong to a connected peer
for addr in node.KNOWN_ADDRS:
host, port = addr.rsplit(':', 1)
if addr not in connected_peers:
result['unconnected'].append({"address": host,
"port": int(port)})
return result | python | def get_peers(self):
node = NodeLeader.Instance()
result = {"connected": [], "unconnected": [], "bad": []}
connected_peers = []
for peer in node.Peers:
result['connected'].append({"address": peer.host,
"port": peer.port})
connected_peers.append("{}:{}".format(peer.host, peer.port))
for addr in node.DEAD_ADDRS:
host, port = addr.rsplit(':', 1)
result['bad'].append({"address": host, "port": port})
# "UnconnectedPeers" is never used. So a check is needed to
# verify that a given address:port does not belong to a connected peer
for addr in node.KNOWN_ADDRS:
host, port = addr.rsplit(':', 1)
if addr not in connected_peers:
result['unconnected'].append({"address": host,
"port": int(port)})
return result | [
"def",
"get_peers",
"(",
"self",
")",
":",
"node",
"=",
"NodeLeader",
".",
"Instance",
"(",
")",
"result",
"=",
"{",
"\"connected\"",
":",
"[",
"]",
",",
"\"unconnected\"",
":",
"[",
"]",
",",
"\"bad\"",
":",
"[",
"]",
"}",
"connected_peers",
"=",
"[... | Get all known nodes and their 'state' | [
"Get",
"all",
"known",
"nodes",
"and",
"their",
"state"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/api/JSONRPC/JsonRpcApi.py#L452-L475 |
229,045 | CityOfZion/neo-python | neo/api/JSONRPC/JsonRpcApi.py | JsonRpcApi.list_address | def list_address(self):
"""Get information about all the addresses present on the open wallet"""
result = []
for addrStr in self.wallet.Addresses:
addr = self.wallet.GetAddress(addrStr)
result.append({
"address": addrStr,
"haskey": not addr.IsWatchOnly,
"label": None,
"watchonly": addr.IsWatchOnly,
})
return result | python | def list_address(self):
result = []
for addrStr in self.wallet.Addresses:
addr = self.wallet.GetAddress(addrStr)
result.append({
"address": addrStr,
"haskey": not addr.IsWatchOnly,
"label": None,
"watchonly": addr.IsWatchOnly,
})
return result | [
"def",
"list_address",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"for",
"addrStr",
"in",
"self",
".",
"wallet",
".",
"Addresses",
":",
"addr",
"=",
"self",
".",
"wallet",
".",
"GetAddress",
"(",
"addrStr",
")",
"result",
".",
"append",
"(",
"{"... | Get information about all the addresses present on the open wallet | [
"Get",
"information",
"about",
"all",
"the",
"addresses",
"present",
"on",
"the",
"open",
"wallet"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/api/JSONRPC/JsonRpcApi.py#L497-L508 |
229,046 | CityOfZion/neo-python | neo/SmartContract/Contract.py | Contract.CreateSignatureContract | def CreateSignatureContract(publicKey):
"""
Create a signature contract.
Args:
publicKey (edcsa.Curve.point): e.g. KeyPair.PublicKey.
Returns:
neo.SmartContract.Contract: a Contract instance.
"""
script = Contract.CreateSignatureRedeemScript(publicKey)
params = b'\x00'
encoded = publicKey.encode_point(True)
pubkey_hash = Crypto.ToScriptHash(encoded, unhex=True)
return Contract(script, params, pubkey_hash) | python | def CreateSignatureContract(publicKey):
script = Contract.CreateSignatureRedeemScript(publicKey)
params = b'\x00'
encoded = publicKey.encode_point(True)
pubkey_hash = Crypto.ToScriptHash(encoded, unhex=True)
return Contract(script, params, pubkey_hash) | [
"def",
"CreateSignatureContract",
"(",
"publicKey",
")",
":",
"script",
"=",
"Contract",
".",
"CreateSignatureRedeemScript",
"(",
"publicKey",
")",
"params",
"=",
"b'\\x00'",
"encoded",
"=",
"publicKey",
".",
"encode_point",
"(",
"True",
")",
"pubkey_hash",
"=",
... | Create a signature contract.
Args:
publicKey (edcsa.Curve.point): e.g. KeyPair.PublicKey.
Returns:
neo.SmartContract.Contract: a Contract instance. | [
"Create",
"a",
"signature",
"contract",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/SmartContract/Contract.py#L124-L139 |
229,047 | CityOfZion/neo-python | neo/Core/BlockBase.py | BlockBase.Hash | def Hash(self):
"""
Get the hash value of the Blockbase.
Returns:
UInt256: containing the hash of the data.
"""
if not self.__hash:
hashdata = self.RawData()
ba = bytearray(binascii.unhexlify(hashdata))
hash = bin_dbl_sha256(ba)
self.__hash = UInt256(data=hash)
return self.__hash | python | def Hash(self):
if not self.__hash:
hashdata = self.RawData()
ba = bytearray(binascii.unhexlify(hashdata))
hash = bin_dbl_sha256(ba)
self.__hash = UInt256(data=hash)
return self.__hash | [
"def",
"Hash",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__hash",
":",
"hashdata",
"=",
"self",
".",
"RawData",
"(",
")",
"ba",
"=",
"bytearray",
"(",
"binascii",
".",
"unhexlify",
"(",
"hashdata",
")",
")",
"hash",
"=",
"bin_dbl_sha256",
"("... | Get the hash value of the Blockbase.
Returns:
UInt256: containing the hash of the data. | [
"Get",
"the",
"hash",
"value",
"of",
"the",
"Blockbase",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/BlockBase.py#L49-L62 |
229,048 | CityOfZion/neo-python | neo/Core/BlockBase.py | BlockBase.DeserializeUnsigned | def DeserializeUnsigned(self, reader):
"""
Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader):
"""
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = reader.ReadUInt32()
self.Index = reader.ReadUInt32()
self.ConsensusData = reader.ReadUInt64()
self.NextConsensus = reader.ReadUInt160() | python | def DeserializeUnsigned(self, reader):
self.Version = reader.ReadUInt32()
self.PrevHash = reader.ReadUInt256()
self.MerkleRoot = reader.ReadUInt256()
self.Timestamp = reader.ReadUInt32()
self.Index = reader.ReadUInt32()
self.ConsensusData = reader.ReadUInt64()
self.NextConsensus = reader.ReadUInt160() | [
"def",
"DeserializeUnsigned",
"(",
"self",
",",
"reader",
")",
":",
"self",
".",
"Version",
"=",
"reader",
".",
"ReadUInt32",
"(",
")",
"self",
".",
"PrevHash",
"=",
"reader",
".",
"ReadUInt256",
"(",
")",
"self",
".",
"MerkleRoot",
"=",
"reader",
".",
... | Deserialize unsigned data only.
Args:
reader (neo.IO.BinaryReader): | [
"Deserialize",
"unsigned",
"data",
"only",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/BlockBase.py#L130-L143 |
229,049 | CityOfZion/neo-python | neo/Core/BlockBase.py | BlockBase.SerializeUnsigned | def SerializeUnsigned(self, writer):
"""
Serialize unsigned data only.
Args:
writer (neo.IO.BinaryWriter):
"""
writer.WriteUInt32(self.Version)
writer.WriteUInt256(self.PrevHash)
writer.WriteUInt256(self.MerkleRoot)
writer.WriteUInt32(self.Timestamp)
writer.WriteUInt32(self.Index)
writer.WriteUInt64(self.ConsensusData)
writer.WriteUInt160(self.NextConsensus) | python | def SerializeUnsigned(self, writer):
writer.WriteUInt32(self.Version)
writer.WriteUInt256(self.PrevHash)
writer.WriteUInt256(self.MerkleRoot)
writer.WriteUInt32(self.Timestamp)
writer.WriteUInt32(self.Index)
writer.WriteUInt64(self.ConsensusData)
writer.WriteUInt160(self.NextConsensus) | [
"def",
"SerializeUnsigned",
"(",
"self",
",",
"writer",
")",
":",
"writer",
".",
"WriteUInt32",
"(",
"self",
".",
"Version",
")",
"writer",
".",
"WriteUInt256",
"(",
"self",
".",
"PrevHash",
")",
"writer",
".",
"WriteUInt256",
"(",
"self",
".",
"MerkleRoot... | Serialize unsigned data only.
Args:
writer (neo.IO.BinaryWriter): | [
"Serialize",
"unsigned",
"data",
"only",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/BlockBase.py#L145-L158 |
229,050 | CityOfZion/neo-python | neo/Core/BlockBase.py | BlockBase.GetScriptHashesForVerifying | def GetScriptHashesForVerifying(self):
"""
Get the script hash used for verification.
Raises:
Exception: if the verification script is invalid, or no header could be retrieved from the Blockchain.
Returns:
list: with a single UInt160 representing the next consensus node.
"""
# if this is the genesis block, we dont have a prev hash!
if self.PrevHash.Data == bytearray(32):
# logger.info("verificiation script %s" %(self.Script.ToJson()))
if type(self.Script.VerificationScript) is bytes:
return [bytearray(self.Script.VerificationScript)]
elif type(self.Script.VerificationScript) is bytearray:
return [self.Script.VerificationScript]
else:
raise Exception('Invalid Verification script')
prev_header = GetBlockchain().GetHeader(self.PrevHash.ToBytes())
if prev_header is None:
raise Exception('Invalid operation')
return [prev_header.NextConsensus] | python | def GetScriptHashesForVerifying(self):
# if this is the genesis block, we dont have a prev hash!
if self.PrevHash.Data == bytearray(32):
# logger.info("verificiation script %s" %(self.Script.ToJson()))
if type(self.Script.VerificationScript) is bytes:
return [bytearray(self.Script.VerificationScript)]
elif type(self.Script.VerificationScript) is bytearray:
return [self.Script.VerificationScript]
else:
raise Exception('Invalid Verification script')
prev_header = GetBlockchain().GetHeader(self.PrevHash.ToBytes())
if prev_header is None:
raise Exception('Invalid operation')
return [prev_header.NextConsensus] | [
"def",
"GetScriptHashesForVerifying",
"(",
"self",
")",
":",
"# if this is the genesis block, we dont have a prev hash!",
"if",
"self",
".",
"PrevHash",
".",
"Data",
"==",
"bytearray",
"(",
"32",
")",
":",
"# logger.info(\"verificiation script %s\" %(self.Script.ToJ... | Get the script hash used for verification.
Raises:
Exception: if the verification script is invalid, or no header could be retrieved from the Blockchain.
Returns:
list: with a single UInt160 representing the next consensus node. | [
"Get",
"the",
"script",
"hash",
"used",
"for",
"verification",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/BlockBase.py#L169-L192 |
229,051 | CityOfZion/neo-python | neo/Core/BlockBase.py | BlockBase.Verify | def Verify(self):
"""
Verify block using the verification script.
Returns:
bool: True if valid. False otherwise.
"""
if not self.Hash.ToBytes() == GetGenesis().Hash.ToBytes():
return False
bc = GetBlockchain()
if not bc.ContainsBlock(self.Index):
return False
if self.Index > 0:
prev_header = GetBlockchain().GetHeader(self.PrevHash.ToBytes())
if prev_header is None:
return False
if prev_header.Index + 1 != self.Index:
return False
if prev_header.Timestamp >= self.Timestamp:
return False
# this should be done to actually verify the block
if not Helper.VerifyScripts(self):
return False
return True | python | def Verify(self):
if not self.Hash.ToBytes() == GetGenesis().Hash.ToBytes():
return False
bc = GetBlockchain()
if not bc.ContainsBlock(self.Index):
return False
if self.Index > 0:
prev_header = GetBlockchain().GetHeader(self.PrevHash.ToBytes())
if prev_header is None:
return False
if prev_header.Index + 1 != self.Index:
return False
if prev_header.Timestamp >= self.Timestamp:
return False
# this should be done to actually verify the block
if not Helper.VerifyScripts(self):
return False
return True | [
"def",
"Verify",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"Hash",
".",
"ToBytes",
"(",
")",
"==",
"GetGenesis",
"(",
")",
".",
"Hash",
".",
"ToBytes",
"(",
")",
":",
"return",
"False",
"bc",
"=",
"GetBlockchain",
"(",
")",
"if",
"not",
"b... | Verify block using the verification script.
Returns:
bool: True if valid. False otherwise. | [
"Verify",
"block",
"using",
"the",
"verification",
"script",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/BlockBase.py#L228-L259 |
229,052 | CityOfZion/neo-python | neo/Core/Block.py | Block.FullTransactions | def FullTransactions(self):
"""
Get the list of full Transaction objects.
Note: Transactions can be trimmed to contain only the header and the hash. This will get the full data if
trimmed transactions are found.
Returns:
list: of neo.Core.TX.Transaction.Transaction objects.
"""
is_trimmed = False
try:
tx = self.Transactions[0]
if type(tx) is str:
is_trimmed = True
except Exception as e:
pass
if not is_trimmed:
return self.Transactions
txs = []
for hash in self.Transactions:
tx, height = GetBlockchain().GetTransaction(hash)
txs.append(tx)
self.Transactions = txs
return self.Transactions | python | def FullTransactions(self):
is_trimmed = False
try:
tx = self.Transactions[0]
if type(tx) is str:
is_trimmed = True
except Exception as e:
pass
if not is_trimmed:
return self.Transactions
txs = []
for hash in self.Transactions:
tx, height = GetBlockchain().GetTransaction(hash)
txs.append(tx)
self.Transactions = txs
return self.Transactions | [
"def",
"FullTransactions",
"(",
"self",
")",
":",
"is_trimmed",
"=",
"False",
"try",
":",
"tx",
"=",
"self",
".",
"Transactions",
"[",
"0",
"]",
"if",
"type",
"(",
"tx",
")",
"is",
"str",
":",
"is_trimmed",
"=",
"True",
"except",
"Exception",
"as",
"... | Get the list of full Transaction objects.
Note: Transactions can be trimmed to contain only the header and the hash. This will get the full data if
trimmed transactions are found.
Returns:
list: of neo.Core.TX.Transaction.Transaction objects. | [
"Get",
"the",
"list",
"of",
"full",
"Transaction",
"objects",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Block.py#L72-L100 |
229,053 | CityOfZion/neo-python | neo/Core/Block.py | Block.Header | def Header(self):
"""
Get the block header.
Returns:
neo.Core.Header:
"""
if not self._header:
self._header = Header(self.PrevHash, self.MerkleRoot, self.Timestamp,
self.Index, self.ConsensusData, self.NextConsensus, self.Script)
return self._header | python | def Header(self):
if not self._header:
self._header = Header(self.PrevHash, self.MerkleRoot, self.Timestamp,
self.Index, self.ConsensusData, self.NextConsensus, self.Script)
return self._header | [
"def",
"Header",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_header",
":",
"self",
".",
"_header",
"=",
"Header",
"(",
"self",
".",
"PrevHash",
",",
"self",
".",
"MerkleRoot",
",",
"self",
".",
"Timestamp",
",",
"self",
".",
"Index",
",",
"s... | Get the block header.
Returns:
neo.Core.Header: | [
"Get",
"the",
"block",
"header",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Block.py#L103-L114 |
229,054 | CityOfZion/neo-python | neo/Core/Block.py | Block.TotalFees | def TotalFees(self):
"""
Get the total transaction fees in the block.
Returns:
Fixed8:
"""
amount = Fixed8.Zero()
for tx in self.Transactions:
amount += tx.SystemFee()
return amount | python | def TotalFees(self):
amount = Fixed8.Zero()
for tx in self.Transactions:
amount += tx.SystemFee()
return amount | [
"def",
"TotalFees",
"(",
"self",
")",
":",
"amount",
"=",
"Fixed8",
".",
"Zero",
"(",
")",
"for",
"tx",
"in",
"self",
".",
"Transactions",
":",
"amount",
"+=",
"tx",
".",
"SystemFee",
"(",
")",
"return",
"amount"
] | Get the total transaction fees in the block.
Returns:
Fixed8: | [
"Get",
"the",
"total",
"transaction",
"fees",
"in",
"the",
"block",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Block.py#L129-L139 |
229,055 | CityOfZion/neo-python | neo/Core/Block.py | Block.FromTrimmedData | def FromTrimmedData(byts):
"""
Deserialize a block from raw bytes.
Args:
byts:
Returns:
Block:
"""
block = Block()
block.__is_trimmed = True
ms = StreamManager.GetStream(byts)
reader = BinaryReader(ms)
block.DeserializeUnsigned(reader)
reader.ReadByte()
witness = Witness()
witness.Deserialize(reader)
block.Script = witness
bc = GetBlockchain()
tx_list = []
for tx_hash in reader.ReadHashes():
tx = bc.GetTransaction(tx_hash)[0]
if not tx:
raise Exception("Could not find transaction!\n Are you running code against a valid Blockchain instance?\n Tests that accesses transactions or size of a block but inherit from NeoTestCase instead of BlockchainFixtureTestCase will not work.")
tx_list.append(tx)
if len(tx_list) < 1:
raise Exception("Invalid block, no transactions found for block %s " % block.Index)
block.Transactions = tx_list
StreamManager.ReleaseStream(ms)
return block | python | def FromTrimmedData(byts):
block = Block()
block.__is_trimmed = True
ms = StreamManager.GetStream(byts)
reader = BinaryReader(ms)
block.DeserializeUnsigned(reader)
reader.ReadByte()
witness = Witness()
witness.Deserialize(reader)
block.Script = witness
bc = GetBlockchain()
tx_list = []
for tx_hash in reader.ReadHashes():
tx = bc.GetTransaction(tx_hash)[0]
if not tx:
raise Exception("Could not find transaction!\n Are you running code against a valid Blockchain instance?\n Tests that accesses transactions or size of a block but inherit from NeoTestCase instead of BlockchainFixtureTestCase will not work.")
tx_list.append(tx)
if len(tx_list) < 1:
raise Exception("Invalid block, no transactions found for block %s " % block.Index)
block.Transactions = tx_list
StreamManager.ReleaseStream(ms)
return block | [
"def",
"FromTrimmedData",
"(",
"byts",
")",
":",
"block",
"=",
"Block",
"(",
")",
"block",
".",
"__is_trimmed",
"=",
"True",
"ms",
"=",
"StreamManager",
".",
"GetStream",
"(",
"byts",
")",
"reader",
"=",
"BinaryReader",
"(",
"ms",
")",
"block",
".",
"D... | Deserialize a block from raw bytes.
Args:
byts:
Returns:
Block: | [
"Deserialize",
"a",
"block",
"from",
"raw",
"bytes",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Block.py#L209-L245 |
229,056 | CityOfZion/neo-python | neo/Core/Block.py | Block.RebuildMerkleRoot | def RebuildMerkleRoot(self):
"""Rebuild the merkle root of the block"""
logger.debug("Rebuilding merkle root!")
if self.Transactions is not None and len(self.Transactions) > 0:
self.MerkleRoot = MerkleTree.ComputeRoot([tx.Hash for tx in self.Transactions]) | python | def RebuildMerkleRoot(self):
logger.debug("Rebuilding merkle root!")
if self.Transactions is not None and len(self.Transactions) > 0:
self.MerkleRoot = MerkleTree.ComputeRoot([tx.Hash for tx in self.Transactions]) | [
"def",
"RebuildMerkleRoot",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Rebuilding merkle root!\"",
")",
"if",
"self",
".",
"Transactions",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"Transactions",
")",
">",
"0",
":",
"self",
".",
"... | Rebuild the merkle root of the block | [
"Rebuild",
"the",
"merkle",
"root",
"of",
"the",
"block"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Block.py#L256-L260 |
229,057 | CityOfZion/neo-python | neo/Core/Block.py | Block.Trim | def Trim(self):
"""
Returns a byte array that contains only the block header and transaction hash.
Returns:
bytes:
"""
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
self.SerializeUnsigned(writer)
writer.WriteByte(1)
self.Script.Serialize(writer)
writer.WriteHashes([tx.Hash.ToBytes() for tx in self.Transactions])
retVal = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retVal | python | def Trim(self):
ms = StreamManager.GetStream()
writer = BinaryWriter(ms)
self.SerializeUnsigned(writer)
writer.WriteByte(1)
self.Script.Serialize(writer)
writer.WriteHashes([tx.Hash.ToBytes() for tx in self.Transactions])
retVal = ms.ToArray()
StreamManager.ReleaseStream(ms)
return retVal | [
"def",
"Trim",
"(",
"self",
")",
":",
"ms",
"=",
"StreamManager",
".",
"GetStream",
"(",
")",
"writer",
"=",
"BinaryWriter",
"(",
"ms",
")",
"self",
".",
"SerializeUnsigned",
"(",
"writer",
")",
"writer",
".",
"WriteByte",
"(",
"1",
")",
"self",
".",
... | Returns a byte array that contains only the block header and transaction hash.
Returns:
bytes: | [
"Returns",
"a",
"byte",
"array",
"that",
"contains",
"only",
"the",
"block",
"header",
"and",
"transaction",
"hash",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Block.py#L288-L304 |
229,058 | CityOfZion/neo-python | neo/Core/Block.py | Block.Verify | def Verify(self, completely=False):
"""
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
"""
res = super(Block, self).Verify()
if not res:
return False
from neo.Blockchain import GetBlockchain, GetConsensusAddress
# first TX has to be a miner transaction. other tx after that cant be miner tx
if self.Transactions[0].Type != TransactionType.MinerTransaction:
return False
for tx in self.Transactions[1:]:
if tx.Type == TransactionType.MinerTransaction:
return False
if completely:
bc = GetBlockchain()
if self.NextConsensus != GetConsensusAddress(bc.GetValidators(self.Transactions).ToArray()):
return False
for tx in self.Transactions:
if not tx.Verify():
pass
logger.error("Blocks cannot be fully validated at this moment. please pass completely=False")
raise NotImplementedError()
# do this below!
# foreach(Transaction tx in Transactions)
# if (!tx.Verify(Transactions.Where(p = > !p.Hash.Equals(tx.Hash)))) return false;
# Transaction tx_gen = Transactions.FirstOrDefault(p= > p.Type == TransactionType.MinerTransaction);
# if (tx_gen?.Outputs.Sum(p = > p.Value) != CalculateNetFee(Transactions)) return false;
return True | python | def Verify(self, completely=False):
res = super(Block, self).Verify()
if not res:
return False
from neo.Blockchain import GetBlockchain, GetConsensusAddress
# first TX has to be a miner transaction. other tx after that cant be miner tx
if self.Transactions[0].Type != TransactionType.MinerTransaction:
return False
for tx in self.Transactions[1:]:
if tx.Type == TransactionType.MinerTransaction:
return False
if completely:
bc = GetBlockchain()
if self.NextConsensus != GetConsensusAddress(bc.GetValidators(self.Transactions).ToArray()):
return False
for tx in self.Transactions:
if not tx.Verify():
pass
logger.error("Blocks cannot be fully validated at this moment. please pass completely=False")
raise NotImplementedError()
# do this below!
# foreach(Transaction tx in Transactions)
# if (!tx.Verify(Transactions.Where(p = > !p.Hash.Equals(tx.Hash)))) return false;
# Transaction tx_gen = Transactions.FirstOrDefault(p= > p.Type == TransactionType.MinerTransaction);
# if (tx_gen?.Outputs.Sum(p = > p.Value) != CalculateNetFee(Transactions)) return false;
return True | [
"def",
"Verify",
"(",
"self",
",",
"completely",
"=",
"False",
")",
":",
"res",
"=",
"super",
"(",
"Block",
",",
"self",
")",
".",
"Verify",
"(",
")",
"if",
"not",
"res",
":",
"return",
"False",
"from",
"neo",
".",
"Blockchain",
"import",
"GetBlockch... | Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise. | [
"Verify",
"the",
"integrity",
"of",
"the",
"block",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Core/Block.py#L306-L346 |
229,059 | CityOfZion/neo-python | neo/Prompt/Utils.py | get_token | def get_token(wallet: 'Wallet', token_str: str) -> 'NEP5Token.NEP5Token':
"""
Try to get a NEP-5 token based on the symbol or script_hash
Args:
wallet: wallet instance
token_str: symbol or script_hash (accepts script hash with or without 0x prefix)
Raises:
ValueError: if token is not found
Returns:
NEP5Token instance if found.
"""
if token_str.startswith('0x'):
token_str = token_str[2:]
token = None
for t in wallet.GetTokens().values():
if token_str in [t.symbol, t.ScriptHash.ToString()]:
token = t
break
if not isinstance(token, NEP5Token.NEP5Token):
raise ValueError("The given token argument does not represent a known NEP5 token")
return token | python | def get_token(wallet: 'Wallet', token_str: str) -> 'NEP5Token.NEP5Token':
if token_str.startswith('0x'):
token_str = token_str[2:]
token = None
for t in wallet.GetTokens().values():
if token_str in [t.symbol, t.ScriptHash.ToString()]:
token = t
break
if not isinstance(token, NEP5Token.NEP5Token):
raise ValueError("The given token argument does not represent a known NEP5 token")
return token | [
"def",
"get_token",
"(",
"wallet",
":",
"'Wallet'",
",",
"token_str",
":",
"str",
")",
"->",
"'NEP5Token.NEP5Token'",
":",
"if",
"token_str",
".",
"startswith",
"(",
"'0x'",
")",
":",
"token_str",
"=",
"token_str",
"[",
"2",
":",
"]",
"token",
"=",
"None... | Try to get a NEP-5 token based on the symbol or script_hash
Args:
wallet: wallet instance
token_str: symbol or script_hash (accepts script hash with or without 0x prefix)
Raises:
ValueError: if token is not found
Returns:
NEP5Token instance if found. | [
"Try",
"to",
"get",
"a",
"NEP",
"-",
"5",
"token",
"based",
"on",
"the",
"symbol",
"or",
"script_hash"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Prompt/Utils.py#L359-L383 |
229,060 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.Instance | def Instance(reactor=None):
"""
Get the local node instance.
Args:
reactor: (optional) custom reactor to use in NodeLeader.
Returns:
NodeLeader: instance.
"""
if NodeLeader._LEAD is None:
NodeLeader._LEAD = NodeLeader(reactor)
return NodeLeader._LEAD | python | def Instance(reactor=None):
if NodeLeader._LEAD is None:
NodeLeader._LEAD = NodeLeader(reactor)
return NodeLeader._LEAD | [
"def",
"Instance",
"(",
"reactor",
"=",
"None",
")",
":",
"if",
"NodeLeader",
".",
"_LEAD",
"is",
"None",
":",
"NodeLeader",
".",
"_LEAD",
"=",
"NodeLeader",
"(",
"reactor",
")",
"return",
"NodeLeader",
".",
"_LEAD"
] | Get the local node instance.
Args:
reactor: (optional) custom reactor to use in NodeLeader.
Returns:
NodeLeader: instance. | [
"Get",
"the",
"local",
"node",
"instance",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L65-L77 |
229,061 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.Setup | def Setup(self):
"""
Initialize the local node.
Returns:
"""
self.Peers = [] # active nodes that we're connected to
self.KNOWN_ADDRS = [] # node addresses that we've learned about from other nodes
self.DEAD_ADDRS = [] # addresses that were performing poorly or we could not establish a connection to
self.MissionsGlobal = []
self.NodeId = random.randint(1294967200, 4294967200) | python | def Setup(self):
self.Peers = [] # active nodes that we're connected to
self.KNOWN_ADDRS = [] # node addresses that we've learned about from other nodes
self.DEAD_ADDRS = [] # addresses that were performing poorly or we could not establish a connection to
self.MissionsGlobal = []
self.NodeId = random.randint(1294967200, 4294967200) | [
"def",
"Setup",
"(",
"self",
")",
":",
"self",
".",
"Peers",
"=",
"[",
"]",
"# active nodes that we're connected to",
"self",
".",
"KNOWN_ADDRS",
"=",
"[",
"]",
"# node addresses that we've learned about from other nodes",
"self",
".",
"DEAD_ADDRS",
"=",
"[",
"]",
... | Initialize the local node.
Returns: | [
"Initialize",
"the",
"local",
"node",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L160-L171 |
229,062 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.check_bcr_catchup | def check_bcr_catchup(self):
"""we're exceeding data request speed vs receive + process"""
logger.debug(f"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}")
# test, perhaps there's some race condition between slow startup and throttle sync, otherwise blocks will never go down
for peer in self.Peers: # type: NeoNode
peer.stop_block_loop(cancel=False)
peer.stop_peerinfo_loop(cancel=False)
peer.stop_header_loop(cancel=False)
if len(BC.Default().BlockRequests) > 0:
for peer in self.Peers:
peer.keep_alive()
peer.health_check(HEARTBEAT_BLOCKS)
peer_bcr_len = len(peer.myblockrequests)
# if a peer has cleared its queue then reset heartbeat status to avoid timing out when resuming from "check_bcr" if there's 1 or more really slow peer(s)
if peer_bcr_len == 0:
peer.start_outstanding_data_request[HEARTBEAT_BLOCKS] = 0
print(f"{peer.prefix} request count: {peer_bcr_len}")
if peer_bcr_len == 1:
next_hash = BC.Default().GetHeaderHash(self.CurrentBlockheight + 1)
print(f"{peer.prefix} {peer.myblockrequests} {next_hash}")
else:
# we're done catching up. Stop own loop and restart peers
self.stop_check_bcr_loop()
self.check_bcr_loop = None
logger.debug("BlockRequests have caught up...resuming sync")
for peer in self.Peers:
peer.ProtocolReady() # this starts all loops again
# give a little bit of time between startup of peers
time.sleep(2) | python | def check_bcr_catchup(self):
logger.debug(f"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}")
# test, perhaps there's some race condition between slow startup and throttle sync, otherwise blocks will never go down
for peer in self.Peers: # type: NeoNode
peer.stop_block_loop(cancel=False)
peer.stop_peerinfo_loop(cancel=False)
peer.stop_header_loop(cancel=False)
if len(BC.Default().BlockRequests) > 0:
for peer in self.Peers:
peer.keep_alive()
peer.health_check(HEARTBEAT_BLOCKS)
peer_bcr_len = len(peer.myblockrequests)
# if a peer has cleared its queue then reset heartbeat status to avoid timing out when resuming from "check_bcr" if there's 1 or more really slow peer(s)
if peer_bcr_len == 0:
peer.start_outstanding_data_request[HEARTBEAT_BLOCKS] = 0
print(f"{peer.prefix} request count: {peer_bcr_len}")
if peer_bcr_len == 1:
next_hash = BC.Default().GetHeaderHash(self.CurrentBlockheight + 1)
print(f"{peer.prefix} {peer.myblockrequests} {next_hash}")
else:
# we're done catching up. Stop own loop and restart peers
self.stop_check_bcr_loop()
self.check_bcr_loop = None
logger.debug("BlockRequests have caught up...resuming sync")
for peer in self.Peers:
peer.ProtocolReady() # this starts all loops again
# give a little bit of time between startup of peers
time.sleep(2) | [
"def",
"check_bcr_catchup",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"f\"Checking if BlockRequests has caught up {len(BC.Default().BlockRequests)}\"",
")",
"# test, perhaps there's some race condition between slow startup and throttle sync, otherwise blocks will never go down",
... | we're exceeding data request speed vs receive + process | [
"we",
"re",
"exceeding",
"data",
"request",
"speed",
"vs",
"receive",
"+",
"process"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L206-L237 |
229,063 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.Start | def Start(self, seed_list: List[str] = None, skip_seeds: bool = False) -> None:
"""
Start connecting to the seed list.
Args:
seed_list: a list of host:port strings if not supplied use list from `protocol.xxx.json`
skip_seeds: skip connecting to seed list
"""
if not seed_list:
seed_list = settings.SEED_LIST
logger.debug("Starting up nodeleader")
if not skip_seeds:
logger.debug("Attempting to connect to seed list...")
for bootstrap in seed_list:
if not is_ip_address(bootstrap):
host, port = bootstrap.split(':')
bootstrap = f"{hostname_to_ip(host)}:{port}"
addr = Address(bootstrap)
self.KNOWN_ADDRS.append(addr)
self.SetupConnection(addr)
logger.debug("Starting up nodeleader: starting peer, mempool, and blockheight check loops")
# check in on peers every 10 seconds
self.start_peer_check_loop()
self.start_memcheck_loop()
self.start_blockheight_loop()
if settings.ACCEPT_INCOMING_PEERS and not self.incoming_server_running:
class OneShotFactory(Factory):
def __init__(self, leader):
self.leader = leader
def buildProtocol(self, addr):
print(f"building new protocol for addr: {addr}")
self.leader.AddKnownAddress(Address(f"{addr.host}:{addr.port}"))
p = NeoNode(incoming_client=True)
p.factory = self
return p
def listen_err(err):
print(f"Failed start listening server for reason: {err.value}")
def listen_ok(value):
self.incoming_server_running = True
logger.debug(f"Starting up nodeleader: setting up listen server on port: {settings.NODE_PORT}")
server_endpoint = TCP4ServerEndpoint(self.reactor, settings.NODE_PORT)
listenport_deferred = server_endpoint.listen(OneShotFactory(leader=self))
listenport_deferred.addCallback(listen_ok)
listenport_deferred.addErrback(listen_err) | python | def Start(self, seed_list: List[str] = None, skip_seeds: bool = False) -> None:
if not seed_list:
seed_list = settings.SEED_LIST
logger.debug("Starting up nodeleader")
if not skip_seeds:
logger.debug("Attempting to connect to seed list...")
for bootstrap in seed_list:
if not is_ip_address(bootstrap):
host, port = bootstrap.split(':')
bootstrap = f"{hostname_to_ip(host)}:{port}"
addr = Address(bootstrap)
self.KNOWN_ADDRS.append(addr)
self.SetupConnection(addr)
logger.debug("Starting up nodeleader: starting peer, mempool, and blockheight check loops")
# check in on peers every 10 seconds
self.start_peer_check_loop()
self.start_memcheck_loop()
self.start_blockheight_loop()
if settings.ACCEPT_INCOMING_PEERS and not self.incoming_server_running:
class OneShotFactory(Factory):
def __init__(self, leader):
self.leader = leader
def buildProtocol(self, addr):
print(f"building new protocol for addr: {addr}")
self.leader.AddKnownAddress(Address(f"{addr.host}:{addr.port}"))
p = NeoNode(incoming_client=True)
p.factory = self
return p
def listen_err(err):
print(f"Failed start listening server for reason: {err.value}")
def listen_ok(value):
self.incoming_server_running = True
logger.debug(f"Starting up nodeleader: setting up listen server on port: {settings.NODE_PORT}")
server_endpoint = TCP4ServerEndpoint(self.reactor, settings.NODE_PORT)
listenport_deferred = server_endpoint.listen(OneShotFactory(leader=self))
listenport_deferred.addCallback(listen_ok)
listenport_deferred.addErrback(listen_err) | [
"def",
"Start",
"(",
"self",
",",
"seed_list",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"skip_seeds",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"if",
"not",
"seed_list",
":",
"seed_list",
"=",
"settings",
".",
"SEED_LIST",
"logger",
"... | Start connecting to the seed list.
Args:
seed_list: a list of host:port strings if not supplied use list from `protocol.xxx.json`
skip_seeds: skip connecting to seed list | [
"Start",
"connecting",
"to",
"the",
"seed",
"list",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L243-L293 |
229,064 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.Shutdown | def Shutdown(self):
"""Disconnect all connected peers."""
logger.debug("Nodeleader shutting down")
self.stop_peer_check_loop()
self.peer_check_loop_deferred = None
self.stop_check_bcr_loop()
self.check_bcr_loop_deferred = None
self.stop_memcheck_loop()
self.memcheck_loop_deferred = None
self.stop_blockheight_loop()
self.blockheight_loop_deferred = None
for p in self.Peers:
p.Disconnect() | python | def Shutdown(self):
logger.debug("Nodeleader shutting down")
self.stop_peer_check_loop()
self.peer_check_loop_deferred = None
self.stop_check_bcr_loop()
self.check_bcr_loop_deferred = None
self.stop_memcheck_loop()
self.memcheck_loop_deferred = None
self.stop_blockheight_loop()
self.blockheight_loop_deferred = None
for p in self.Peers:
p.Disconnect() | [
"def",
"Shutdown",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Nodeleader shutting down\"",
")",
"self",
".",
"stop_peer_check_loop",
"(",
")",
"self",
".",
"peer_check_loop_deferred",
"=",
"None",
"self",
".",
"stop_check_bcr_loop",
"(",
")",
"self",... | Disconnect all connected peers. | [
"Disconnect",
"all",
"connected",
"peers",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L343-L360 |
229,065 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.AddConnectedPeer | def AddConnectedPeer(self, peer):
"""
Add a new connect peer to the known peers list.
Args:
peer (NeoNode): instance.
"""
# if present
self.RemoveFromQueue(peer.address)
self.AddKnownAddress(peer.address)
if len(self.Peers) > settings.CONNECTED_PEER_MAX:
peer.Disconnect("Max connected peers reached", isDead=False)
if peer not in self.Peers:
self.Peers.append(peer)
else:
# either peer is already in the list and it has reconnected before it timed out on our side
# or it's trying to connect multiple times
# or we hit the max connected peer count
self.RemoveKnownAddress(peer.address)
peer.Disconnect() | python | def AddConnectedPeer(self, peer):
# if present
self.RemoveFromQueue(peer.address)
self.AddKnownAddress(peer.address)
if len(self.Peers) > settings.CONNECTED_PEER_MAX:
peer.Disconnect("Max connected peers reached", isDead=False)
if peer not in self.Peers:
self.Peers.append(peer)
else:
# either peer is already in the list and it has reconnected before it timed out on our side
# or it's trying to connect multiple times
# or we hit the max connected peer count
self.RemoveKnownAddress(peer.address)
peer.Disconnect() | [
"def",
"AddConnectedPeer",
"(",
"self",
",",
"peer",
")",
":",
"# if present",
"self",
".",
"RemoveFromQueue",
"(",
"peer",
".",
"address",
")",
"self",
".",
"AddKnownAddress",
"(",
"peer",
".",
"address",
")",
"if",
"len",
"(",
"self",
".",
"Peers",
")"... | Add a new connect peer to the known peers list.
Args:
peer (NeoNode): instance. | [
"Add",
"a",
"new",
"connect",
"peer",
"to",
"the",
"known",
"peers",
"list",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L362-L383 |
229,066 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.RemoveConnectedPeer | def RemoveConnectedPeer(self, peer):
"""
Remove a connected peer from the known peers list.
Args:
peer (NeoNode): instance.
"""
if peer in self.Peers:
self.Peers.remove(peer) | python | def RemoveConnectedPeer(self, peer):
if peer in self.Peers:
self.Peers.remove(peer) | [
"def",
"RemoveConnectedPeer",
"(",
"self",
",",
"peer",
")",
":",
"if",
"peer",
"in",
"self",
".",
"Peers",
":",
"self",
".",
"Peers",
".",
"remove",
"(",
"peer",
")"
] | Remove a connected peer from the known peers list.
Args:
peer (NeoNode): instance. | [
"Remove",
"a",
"connected",
"peer",
"from",
"the",
"known",
"peers",
"list",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L385-L393 |
229,067 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader._monitor_for_zero_connected_peers | def _monitor_for_zero_connected_peers(self):
"""
Track if we lost connection to all peers.
Give some retries threshold to allow peers that are in the process of connecting or in the queue to be connected to run
"""
if len(self.Peers) == 0 and len(self.connection_queue) == 0:
if self.peer_zero_count > 2:
logger.debug("Peer count 0 exceeded max retries threshold, restarting...")
self.Restart()
else:
logger.debug(
f"Peer count is 0, allow for retries or queued connections to be established {self.peer_zero_count}")
self.peer_zero_count += 1 | python | def _monitor_for_zero_connected_peers(self):
if len(self.Peers) == 0 and len(self.connection_queue) == 0:
if self.peer_zero_count > 2:
logger.debug("Peer count 0 exceeded max retries threshold, restarting...")
self.Restart()
else:
logger.debug(
f"Peer count is 0, allow for retries or queued connections to be established {self.peer_zero_count}")
self.peer_zero_count += 1 | [
"def",
"_monitor_for_zero_connected_peers",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"Peers",
")",
"==",
"0",
"and",
"len",
"(",
"self",
".",
"connection_queue",
")",
"==",
"0",
":",
"if",
"self",
".",
"peer_zero_count",
">",
"2",
":",
"lo... | Track if we lost connection to all peers.
Give some retries threshold to allow peers that are in the process of connecting or in the queue to be connected to run | [
"Track",
"if",
"we",
"lost",
"connection",
"to",
"all",
"peers",
".",
"Give",
"some",
"retries",
"threshold",
"to",
"allow",
"peers",
"that",
"are",
"in",
"the",
"process",
"of",
"connecting",
"or",
"in",
"the",
"queue",
"to",
"be",
"connected",
"to",
"r... | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L473-L486 |
229,068 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.InventoryReceived | def InventoryReceived(self, inventory):
"""
Process a received inventory.
Args:
inventory (neo.Network.Inventory): expect a Block type.
Returns:
bool: True if processed and verified. False otherwise.
"""
if inventory.Hash.ToBytes() in self._MissedBlocks:
self._MissedBlocks.remove(inventory.Hash.ToBytes())
if inventory is MinerTransaction:
return False
if type(inventory) is Block:
if BC.Default() is None:
return False
if BC.Default().ContainsBlock(inventory.Index):
return False
if not BC.Default().AddBlock(inventory):
return False
else:
if not inventory.Verify(self.MemPool.values()):
return False | python | def InventoryReceived(self, inventory):
if inventory.Hash.ToBytes() in self._MissedBlocks:
self._MissedBlocks.remove(inventory.Hash.ToBytes())
if inventory is MinerTransaction:
return False
if type(inventory) is Block:
if BC.Default() is None:
return False
if BC.Default().ContainsBlock(inventory.Index):
return False
if not BC.Default().AddBlock(inventory):
return False
else:
if not inventory.Verify(self.MemPool.values()):
return False | [
"def",
"InventoryReceived",
"(",
"self",
",",
"inventory",
")",
":",
"if",
"inventory",
".",
"Hash",
".",
"ToBytes",
"(",
")",
"in",
"self",
".",
"_MissedBlocks",
":",
"self",
".",
"_MissedBlocks",
".",
"remove",
"(",
"inventory",
".",
"Hash",
".",
"ToBy... | Process a received inventory.
Args:
inventory (neo.Network.Inventory): expect a Block type.
Returns:
bool: True if processed and verified. False otherwise. | [
"Process",
"a",
"received",
"inventory",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L497-L525 |
229,069 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.AddTransaction | def AddTransaction(self, tx):
"""
Add a transaction to the memory pool.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully added. False otherwise.
"""
if BC.Default() is None:
return False
if tx.Hash.ToBytes() in self.MemPool.keys():
return False
if BC.Default().ContainsTransaction(tx.Hash):
return False
if not tx.Verify(self.MemPool.values()):
logger.error("Verifying tx result... failed")
return False
self.MemPool[tx.Hash.ToBytes()] = tx
return True | python | def AddTransaction(self, tx):
if BC.Default() is None:
return False
if tx.Hash.ToBytes() in self.MemPool.keys():
return False
if BC.Default().ContainsTransaction(tx.Hash):
return False
if not tx.Verify(self.MemPool.values()):
logger.error("Verifying tx result... failed")
return False
self.MemPool[tx.Hash.ToBytes()] = tx
return True | [
"def",
"AddTransaction",
"(",
"self",
",",
"tx",
")",
":",
"if",
"BC",
".",
"Default",
"(",
")",
"is",
"None",
":",
"return",
"False",
"if",
"tx",
".",
"Hash",
".",
"ToBytes",
"(",
")",
"in",
"self",
".",
"MemPool",
".",
"keys",
"(",
")",
":",
... | Add a transaction to the memory pool.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully added. False otherwise. | [
"Add",
"a",
"transaction",
"to",
"the",
"memory",
"pool",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L595-L620 |
229,070 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.RemoveTransaction | def RemoveTransaction(self, tx):
"""
Remove a transaction from the memory pool if it is found on the blockchain.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully removed. False otherwise.
"""
if BC.Default() is None:
return False
if not BC.Default().ContainsTransaction(tx.Hash):
return False
if tx.Hash.ToBytes() in self.MemPool:
del self.MemPool[tx.Hash.ToBytes()]
return True
return False | python | def RemoveTransaction(self, tx):
if BC.Default() is None:
return False
if not BC.Default().ContainsTransaction(tx.Hash):
return False
if tx.Hash.ToBytes() in self.MemPool:
del self.MemPool[tx.Hash.ToBytes()]
return True
return False | [
"def",
"RemoveTransaction",
"(",
"self",
",",
"tx",
")",
":",
"if",
"BC",
".",
"Default",
"(",
")",
"is",
"None",
":",
"return",
"False",
"if",
"not",
"BC",
".",
"Default",
"(",
")",
".",
"ContainsTransaction",
"(",
"tx",
".",
"Hash",
")",
":",
"re... | Remove a transaction from the memory pool if it is found on the blockchain.
Args:
tx (neo.Core.TX.Transaction): instance.
Returns:
bool: True if successfully removed. False otherwise. | [
"Remove",
"a",
"transaction",
"from",
"the",
"memory",
"pool",
"if",
"it",
"is",
"found",
"on",
"the",
"blockchain",
"."
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L622-L642 |
229,071 | CityOfZion/neo-python | neo/Network/NodeLeader.py | NodeLeader.BlockheightCheck | def BlockheightCheck(self):
"""
Checks the current blockheight and finds the peer that prevents advancement
"""
if self.CurrentBlockheight == BC.Default().Height:
if len(self.Peers) > 0:
logger.debug("Blockheight is not advancing ...")
next_hash = BC.Default().GetHeaderHash(self.CurrentBlockheight + 1)
culprit_found = False
for peer in self.Peers:
if next_hash in peer.myblockrequests:
culprit_found = True
peer.Disconnect()
break
# this happens when we're connecting to other nodes that are stuck themselves
if not culprit_found:
for peer in self.Peers:
peer.Disconnect()
else:
self.CurrentBlockheight = BC.Default().Height | python | def BlockheightCheck(self):
if self.CurrentBlockheight == BC.Default().Height:
if len(self.Peers) > 0:
logger.debug("Blockheight is not advancing ...")
next_hash = BC.Default().GetHeaderHash(self.CurrentBlockheight + 1)
culprit_found = False
for peer in self.Peers:
if next_hash in peer.myblockrequests:
culprit_found = True
peer.Disconnect()
break
# this happens when we're connecting to other nodes that are stuck themselves
if not culprit_found:
for peer in self.Peers:
peer.Disconnect()
else:
self.CurrentBlockheight = BC.Default().Height | [
"def",
"BlockheightCheck",
"(",
"self",
")",
":",
"if",
"self",
".",
"CurrentBlockheight",
"==",
"BC",
".",
"Default",
"(",
")",
".",
"Height",
":",
"if",
"len",
"(",
"self",
".",
"Peers",
")",
">",
"0",
":",
"logger",
".",
"debug",
"(",
"\"Blockheig... | Checks the current blockheight and finds the peer that prevents advancement | [
"Checks",
"the",
"current",
"blockheight",
"and",
"finds",
"the",
"peer",
"that",
"prevents",
"advancement"
] | fe90f62e123d720d4281c79af0598d9df9e776fb | https://github.com/CityOfZion/neo-python/blob/fe90f62e123d720d4281c79af0598d9df9e776fb/neo/Network/NodeLeader.py#L659-L679 |
229,072 | aluzzardi/wssh | wssh/server.py | WSSHBridge.open | def open(self, hostname, port=22, username=None, password=None,
private_key=None, key_passphrase=None,
allow_agent=False, timeout=None):
""" Open a connection to a remote SSH server
In order to connect, either one of these credentials must be
supplied:
* Password
Password-based authentication
* Private Key
Authenticate using SSH Keys.
If the private key is encrypted, it will attempt to
load it using the passphrase
* Agent
Authenticate using the *local* SSH agent. This is the
one running alongside wsshd on the server side.
"""
try:
pkey = None
if private_key:
pkey = self._load_private_key(private_key, key_passphrase)
self._ssh.connect(
hostname=hostname,
port=port,
username=username,
password=password,
pkey=pkey,
timeout=timeout,
allow_agent=allow_agent,
look_for_keys=False)
except socket.gaierror as e:
self._websocket.send(json.dumps({'error':
'Could not resolve hostname {0}: {1}'.format(
hostname, e.args[1])}))
raise
except Exception as e:
self._websocket.send(json.dumps({'error': e.message or str(e)}))
raise | python | def open(self, hostname, port=22, username=None, password=None,
private_key=None, key_passphrase=None,
allow_agent=False, timeout=None):
try:
pkey = None
if private_key:
pkey = self._load_private_key(private_key, key_passphrase)
self._ssh.connect(
hostname=hostname,
port=port,
username=username,
password=password,
pkey=pkey,
timeout=timeout,
allow_agent=allow_agent,
look_for_keys=False)
except socket.gaierror as e:
self._websocket.send(json.dumps({'error':
'Could not resolve hostname {0}: {1}'.format(
hostname, e.args[1])}))
raise
except Exception as e:
self._websocket.send(json.dumps({'error': e.message or str(e)}))
raise | [
"def",
"open",
"(",
"self",
",",
"hostname",
",",
"port",
"=",
"22",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"private_key",
"=",
"None",
",",
"key_passphrase",
"=",
"None",
",",
"allow_agent",
"=",
"False",
",",
"timeout",
"=",... | Open a connection to a remote SSH server
In order to connect, either one of these credentials must be
supplied:
* Password
Password-based authentication
* Private Key
Authenticate using SSH Keys.
If the private key is encrypted, it will attempt to
load it using the passphrase
* Agent
Authenticate using the *local* SSH agent. This is the
one running alongside wsshd on the server side. | [
"Open",
"a",
"connection",
"to",
"a",
"remote",
"SSH",
"server"
] | 4ccde12af67a0d7a121294ec6c4a5ec3c17de425 | https://github.com/aluzzardi/wssh/blob/4ccde12af67a0d7a121294ec6c4a5ec3c17de425/wssh/server.py#L69-L106 |
229,073 | aluzzardi/wssh | wssh/server.py | WSSHBridge._bridge | def _bridge(self, channel):
""" Full-duplex bridge between a websocket and a SSH channel """
channel.setblocking(False)
channel.settimeout(0.0)
self._tasks = [
gevent.spawn(self._forward_inbound, channel),
gevent.spawn(self._forward_outbound, channel)
]
gevent.joinall(self._tasks) | python | def _bridge(self, channel):
channel.setblocking(False)
channel.settimeout(0.0)
self._tasks = [
gevent.spawn(self._forward_inbound, channel),
gevent.spawn(self._forward_outbound, channel)
]
gevent.joinall(self._tasks) | [
"def",
"_bridge",
"(",
"self",
",",
"channel",
")",
":",
"channel",
".",
"setblocking",
"(",
"False",
")",
"channel",
".",
"settimeout",
"(",
"0.0",
")",
"self",
".",
"_tasks",
"=",
"[",
"gevent",
".",
"spawn",
"(",
"self",
".",
"_forward_inbound",
","... | Full-duplex bridge between a websocket and a SSH channel | [
"Full",
"-",
"duplex",
"bridge",
"between",
"a",
"websocket",
"and",
"a",
"SSH",
"channel"
] | 4ccde12af67a0d7a121294ec6c4a5ec3c17de425 | https://github.com/aluzzardi/wssh/blob/4ccde12af67a0d7a121294ec6c4a5ec3c17de425/wssh/server.py#L137-L145 |
229,074 | aluzzardi/wssh | wssh/server.py | WSSHBridge.close | def close(self):
""" Terminate a bridge session """
gevent.killall(self._tasks, block=True)
self._tasks = []
self._ssh.close() | python | def close(self):
gevent.killall(self._tasks, block=True)
self._tasks = []
self._ssh.close() | [
"def",
"close",
"(",
"self",
")",
":",
"gevent",
".",
"killall",
"(",
"self",
".",
"_tasks",
",",
"block",
"=",
"True",
")",
"self",
".",
"_tasks",
"=",
"[",
"]",
"self",
".",
"_ssh",
".",
"close",
"(",
")"
] | Terminate a bridge session | [
"Terminate",
"a",
"bridge",
"session"
] | 4ccde12af67a0d7a121294ec6c4a5ec3c17de425 | https://github.com/aluzzardi/wssh/blob/4ccde12af67a0d7a121294ec6c4a5ec3c17de425/wssh/server.py#L147-L151 |
229,075 | aluzzardi/wssh | wssh/server.py | WSSHBridge.shell | def shell(self, term='xterm'):
""" Start an interactive shell session
This method invokes a shell on the remote SSH server and proxies
traffic to/from both peers.
You must connect to a SSH server using ssh_connect()
prior to starting the session.
"""
channel = self._ssh.invoke_shell(term)
self._bridge(channel)
channel.close() | python | def shell(self, term='xterm'):
channel = self._ssh.invoke_shell(term)
self._bridge(channel)
channel.close() | [
"def",
"shell",
"(",
"self",
",",
"term",
"=",
"'xterm'",
")",
":",
"channel",
"=",
"self",
".",
"_ssh",
".",
"invoke_shell",
"(",
"term",
")",
"self",
".",
"_bridge",
"(",
"channel",
")",
"channel",
".",
"close",
"(",
")"
] | Start an interactive shell session
This method invokes a shell on the remote SSH server and proxies
traffic to/from both peers.
You must connect to a SSH server using ssh_connect()
prior to starting the session. | [
"Start",
"an",
"interactive",
"shell",
"session"
] | 4ccde12af67a0d7a121294ec6c4a5ec3c17de425 | https://github.com/aluzzardi/wssh/blob/4ccde12af67a0d7a121294ec6c4a5ec3c17de425/wssh/server.py#L169-L180 |
229,076 | xflr6/graphviz | graphviz/backend.py | command | def command(engine, format, filepath=None, renderer=None, formatter=None):
"""Return args list for ``subprocess.Popen`` and name of the rendered file."""
if formatter is not None and renderer is None:
raise RequiredArgumentError('formatter given without renderer')
if engine not in ENGINES:
raise ValueError('unknown engine: %r' % engine)
if format not in FORMATS:
raise ValueError('unknown format: %r' % format)
if renderer is not None and renderer not in RENDERERS:
raise ValueError('unknown renderer: %r' % renderer)
if formatter is not None and formatter not in FORMATTERS:
raise ValueError('unknown formatter: %r' % formatter)
format_arg = [s for s in (format, renderer, formatter) if s is not None]
suffix = '.'.join(reversed(format_arg))
format_arg = ':'.join(format_arg)
cmd = [engine, '-T%s' % format_arg]
rendered = None
if filepath is not None:
cmd.extend(['-O', filepath])
rendered = '%s.%s' % (filepath, suffix)
return cmd, rendered | python | def command(engine, format, filepath=None, renderer=None, formatter=None):
if formatter is not None and renderer is None:
raise RequiredArgumentError('formatter given without renderer')
if engine not in ENGINES:
raise ValueError('unknown engine: %r' % engine)
if format not in FORMATS:
raise ValueError('unknown format: %r' % format)
if renderer is not None and renderer not in RENDERERS:
raise ValueError('unknown renderer: %r' % renderer)
if formatter is not None and formatter not in FORMATTERS:
raise ValueError('unknown formatter: %r' % formatter)
format_arg = [s for s in (format, renderer, formatter) if s is not None]
suffix = '.'.join(reversed(format_arg))
format_arg = ':'.join(format_arg)
cmd = [engine, '-T%s' % format_arg]
rendered = None
if filepath is not None:
cmd.extend(['-O', filepath])
rendered = '%s.%s' % (filepath, suffix)
return cmd, rendered | [
"def",
"command",
"(",
"engine",
",",
"format",
",",
"filepath",
"=",
"None",
",",
"renderer",
"=",
"None",
",",
"formatter",
"=",
"None",
")",
":",
"if",
"formatter",
"is",
"not",
"None",
"and",
"renderer",
"is",
"None",
":",
"raise",
"RequiredArgumentE... | Return args list for ``subprocess.Popen`` and name of the rendered file. | [
"Return",
"args",
"list",
"for",
"subprocess",
".",
"Popen",
"and",
"name",
"of",
"the",
"rendered",
"file",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/backend.py#L99-L123 |
229,077 | xflr6/graphviz | graphviz/backend.py | render | def render(engine, format, filepath, renderer=None, formatter=None, quiet=False):
"""Render file with Graphviz ``engine`` into ``format``, return result filename.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'``, ...).
filepath: Path to the DOT source file to render.
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
quiet (bool): Suppress ``stderr`` output.
Returns:
The (possibly relative) path of the rendered file.
Raises:
ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
"""
cmd, rendered = command(engine, format, filepath, renderer, formatter)
run(cmd, capture_output=True, check=True, quiet=quiet)
return rendered | python | def render(engine, format, filepath, renderer=None, formatter=None, quiet=False):
cmd, rendered = command(engine, format, filepath, renderer, formatter)
run(cmd, capture_output=True, check=True, quiet=quiet)
return rendered | [
"def",
"render",
"(",
"engine",
",",
"format",
",",
"filepath",
",",
"renderer",
"=",
"None",
",",
"formatter",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"cmd",
",",
"rendered",
"=",
"command",
"(",
"engine",
",",
"format",
",",
"filepath",
... | Render file with Graphviz ``engine`` into ``format``, return result filename.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'``, ...).
filepath: Path to the DOT source file to render.
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
quiet (bool): Suppress ``stderr`` output.
Returns:
The (possibly relative) path of the rendered file.
Raises:
ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero. | [
"Render",
"file",
"with",
"Graphviz",
"engine",
"into",
"format",
"return",
"result",
"filename",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/backend.py#L164-L184 |
229,078 | xflr6/graphviz | graphviz/backend.py | pipe | def pipe(engine, format, data, renderer=None, formatter=None, quiet=False):
"""Return ``data`` piped through Graphviz ``engine`` into ``format``.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'``, ...).
data: The binary (encoded) DOT source string to render.
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
quiet (bool): Suppress ``stderr`` output.
Returns:
Binary (encoded) stdout of the layout command.
Raises:
ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
"""
cmd, _ = command(engine, format, None, renderer, formatter)
out, _ = run(cmd, input=data, capture_output=True, check=True, quiet=quiet)
return out | python | def pipe(engine, format, data, renderer=None, formatter=None, quiet=False):
cmd, _ = command(engine, format, None, renderer, formatter)
out, _ = run(cmd, input=data, capture_output=True, check=True, quiet=quiet)
return out | [
"def",
"pipe",
"(",
"engine",
",",
"format",
",",
"data",
",",
"renderer",
"=",
"None",
",",
"formatter",
"=",
"None",
",",
"quiet",
"=",
"False",
")",
":",
"cmd",
",",
"_",
"=",
"command",
"(",
"engine",
",",
"format",
",",
"None",
",",
"renderer"... | Return ``data`` piped through Graphviz ``engine`` into ``format``.
Args:
engine: The layout commmand used for rendering (``'dot'``, ``'neato'``, ...).
format: The output format used for rendering (``'pdf'``, ``'png'``, ...).
data: The binary (encoded) DOT source string to render.
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
quiet (bool): Suppress ``stderr`` output.
Returns:
Binary (encoded) stdout of the layout command.
Raises:
ValueError: If ``engine``, ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero. | [
"Return",
"data",
"piped",
"through",
"Graphviz",
"engine",
"into",
"format",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/backend.py#L187-L207 |
229,079 | xflr6/graphviz | graphviz/backend.py | version | def version():
"""Return the version number tuple from the ``stderr`` output of ``dot -V``.
Returns:
Two or three ``int`` version ``tuple``.
Raises:
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
RuntimmeError: If the output cannot be parsed into a version number.
"""
cmd = ['dot', '-V']
out, _ = run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
info = out.decode('ascii')
ma = re.search(r'graphviz version (\d+\.\d+(?:\.\d+)?) ', info)
if ma is None:
raise RuntimeError
return tuple(int(d) for d in ma.group(1).split('.')) | python | def version():
cmd = ['dot', '-V']
out, _ = run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
info = out.decode('ascii')
ma = re.search(r'graphviz version (\d+\.\d+(?:\.\d+)?) ', info)
if ma is None:
raise RuntimeError
return tuple(int(d) for d in ma.group(1).split('.')) | [
"def",
"version",
"(",
")",
":",
"cmd",
"=",
"[",
"'dot'",
",",
"'-V'",
"]",
"out",
",",
"_",
"=",
"run",
"(",
"cmd",
",",
"check",
"=",
"True",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
... | Return the version number tuple from the ``stderr`` output of ``dot -V``.
Returns:
Two or three ``int`` version ``tuple``.
Raises:
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
RuntimmeError: If the output cannot be parsed into a version number. | [
"Return",
"the",
"version",
"number",
"tuple",
"from",
"the",
"stderr",
"output",
"of",
"dot",
"-",
"V",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/backend.py#L210-L227 |
229,080 | xflr6/graphviz | graphviz/files.py | File.pipe | def pipe(self, format=None, renderer=None, formatter=None):
"""Return the source piped through the Graphviz layout command.
Args:
format: The output format used for rendering (``'pdf'``, ``'png'``, etc.).
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
Returns:
Binary (encoded) stdout of the layout command.
Raises:
ValueError: If ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
"""
if format is None:
format = self._format
data = text_type(self.source).encode(self._encoding)
out = backend.pipe(self._engine, format, data, renderer, formatter)
return out | python | def pipe(self, format=None, renderer=None, formatter=None):
if format is None:
format = self._format
data = text_type(self.source).encode(self._encoding)
out = backend.pipe(self._engine, format, data, renderer, formatter)
return out | [
"def",
"pipe",
"(",
"self",
",",
"format",
"=",
"None",
",",
"renderer",
"=",
"None",
",",
"formatter",
"=",
"None",
")",
":",
"if",
"format",
"is",
"None",
":",
"format",
"=",
"self",
".",
"_format",
"data",
"=",
"text_type",
"(",
"self",
".",
"so... | Return the source piped through the Graphviz layout command.
Args:
format: The output format used for rendering (``'pdf'``, ``'png'``, etc.).
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
Returns:
Binary (encoded) stdout of the layout command.
Raises:
ValueError: If ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero. | [
"Return",
"the",
"source",
"piped",
"through",
"the",
"Graphviz",
"layout",
"command",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/files.py#L108-L130 |
229,081 | xflr6/graphviz | graphviz/files.py | File.save | def save(self, filename=None, directory=None):
"""Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Returns:
The (possibly relative) path of the saved source file.
"""
if filename is not None:
self.filename = filename
if directory is not None:
self.directory = directory
filepath = self.filepath
tools.mkdirs(filepath)
data = text_type(self.source)
with io.open(filepath, 'w', encoding=self.encoding) as fd:
fd.write(data)
if not data.endswith(u'\n'):
fd.write(u'\n')
return filepath | python | def save(self, filename=None, directory=None):
if filename is not None:
self.filename = filename
if directory is not None:
self.directory = directory
filepath = self.filepath
tools.mkdirs(filepath)
data = text_type(self.source)
with io.open(filepath, 'w', encoding=self.encoding) as fd:
fd.write(data)
if not data.endswith(u'\n'):
fd.write(u'\n')
return filepath | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"directory",
"=",
"None",
")",
":",
"if",
"filename",
"is",
"not",
"None",
":",
"self",
".",
"filename",
"=",
"filename",
"if",
"directory",
"is",
"not",
"None",
":",
"self",
".",
"direct... | Save the DOT source to file. Ensure the file ends with a newline.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
Returns:
The (possibly relative) path of the saved source file. | [
"Save",
"the",
"DOT",
"source",
"to",
"file",
".",
"Ensure",
"the",
"file",
"ends",
"with",
"a",
"newline",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/files.py#L136-L160 |
229,082 | xflr6/graphviz | graphviz/files.py | File.render | def render(self, filename=None, directory=None, view=False, cleanup=False,
format=None, renderer=None, formatter=None):
"""Save the source to file and render with the Graphviz engine.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
view (bool): Open the rendered result with the default application.
cleanup (bool): Delete the source file after rendering.
format: The output format used for rendering (``'pdf'``, ``'png'``, etc.).
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
Returns:
The (possibly relative) path of the rendered file.
Raises:
ValueError: If ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
RuntimeError: If viewer opening is requested but not supported.
"""
filepath = self.save(filename, directory)
if format is None:
format = self._format
rendered = backend.render(self._engine, format, filepath, renderer, formatter)
if cleanup:
os.remove(filepath)
if view:
self._view(rendered, self._format)
return rendered | python | def render(self, filename=None, directory=None, view=False, cleanup=False,
format=None, renderer=None, formatter=None):
filepath = self.save(filename, directory)
if format is None:
format = self._format
rendered = backend.render(self._engine, format, filepath, renderer, formatter)
if cleanup:
os.remove(filepath)
if view:
self._view(rendered, self._format)
return rendered | [
"def",
"render",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"view",
"=",
"False",
",",
"cleanup",
"=",
"False",
",",
"format",
"=",
"None",
",",
"renderer",
"=",
"None",
",",
"formatter",
"=",
"None",
")",
":",
"... | Save the source to file and render with the Graphviz engine.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
view (bool): Open the rendered result with the default application.
cleanup (bool): Delete the source file after rendering.
format: The output format used for rendering (``'pdf'``, ``'png'``, etc.).
renderer: The output renderer used for rendering (``'cairo'``, ``'gd'``, ...).
formatter: The output formatter used for rendering (``'cairo'``, ``'gd'``, ...).
Returns:
The (possibly relative) path of the rendered file.
Raises:
ValueError: If ``format``, ``renderer``, or ``formatter`` are not known.
graphviz.RequiredArgumentError: If ``formatter`` is given but ``renderer`` is None.
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
RuntimeError: If viewer opening is requested but not supported. | [
"Save",
"the",
"source",
"to",
"file",
"and",
"render",
"with",
"the",
"Graphviz",
"engine",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/files.py#L162-L196 |
229,083 | xflr6/graphviz | graphviz/files.py | File.view | def view(self, filename=None, directory=None, cleanup=False):
"""Save the source to file, open the rendered result in a viewer.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
cleanup (bool): Delete the source file after rendering.
Returns:
The (possibly relative) path of the rendered file.
Raises:
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
RuntimeError: If opening the viewer is not supported.
Short-cut method for calling :meth:`.render` with ``view=True``.
"""
return self.render(filename=filename, directory=directory, view=True,
cleanup=cleanup) | python | def view(self, filename=None, directory=None, cleanup=False):
return self.render(filename=filename, directory=directory, view=True,
cleanup=cleanup) | [
"def",
"view",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"directory",
"=",
"None",
",",
"cleanup",
"=",
"False",
")",
":",
"return",
"self",
".",
"render",
"(",
"filename",
"=",
"filename",
",",
"directory",
"=",
"directory",
",",
"view",
"=",
... | Save the source to file, open the rendered result in a viewer.
Args:
filename: Filename for saving the source (defaults to ``name`` + ``'.gv'``)
directory: (Sub)directory for source saving and rendering.
cleanup (bool): Delete the source file after rendering.
Returns:
The (possibly relative) path of the rendered file.
Raises:
graphviz.ExecutableNotFound: If the Graphviz executable is not found.
subprocess.CalledProcessError: If the exit status is non-zero.
RuntimeError: If opening the viewer is not supported.
Short-cut method for calling :meth:`.render` with ``view=True``. | [
"Save",
"the",
"source",
"to",
"file",
"open",
"the",
"rendered",
"result",
"in",
"a",
"viewer",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/files.py#L198-L215 |
229,084 | xflr6/graphviz | graphviz/files.py | File._view | def _view(self, filepath, format):
"""Start the right viewer based on file format and platform."""
methodnames = [
'_view_%s_%s' % (format, backend.PLATFORM),
'_view_%s' % backend.PLATFORM,
]
for name in methodnames:
view_method = getattr(self, name, None)
if view_method is not None:
break
else:
raise RuntimeError('%r has no built-in viewer support for %r '
'on %r platform' % (self.__class__, format, backend.PLATFORM))
view_method(filepath) | python | def _view(self, filepath, format):
methodnames = [
'_view_%s_%s' % (format, backend.PLATFORM),
'_view_%s' % backend.PLATFORM,
]
for name in methodnames:
view_method = getattr(self, name, None)
if view_method is not None:
break
else:
raise RuntimeError('%r has no built-in viewer support for %r '
'on %r platform' % (self.__class__, format, backend.PLATFORM))
view_method(filepath) | [
"def",
"_view",
"(",
"self",
",",
"filepath",
",",
"format",
")",
":",
"methodnames",
"=",
"[",
"'_view_%s_%s'",
"%",
"(",
"format",
",",
"backend",
".",
"PLATFORM",
")",
",",
"'_view_%s'",
"%",
"backend",
".",
"PLATFORM",
",",
"]",
"for",
"name",
"in"... | Start the right viewer based on file format and platform. | [
"Start",
"the",
"right",
"viewer",
"based",
"on",
"file",
"format",
"and",
"platform",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/files.py#L217-L230 |
229,085 | xflr6/graphviz | graphviz/files.py | Source.from_file | def from_file(cls, filename, directory=None,
format=None, engine=None, encoding=File._encoding):
"""Return an instance with the source string read from the given file.
Args:
filename: Filename for loading/saving the source.
directory: (Sub)directory for source loading/saving and rendering.
format: Rendering output format (``'pdf'``, ``'png'``, ...).
engine: Layout command used (``'dot'``, ``'neato'``, ...).
encoding: Encoding for loading/saving the source.
"""
filepath = os.path.join(directory or '', filename)
if encoding is None:
encoding = locale.getpreferredencoding()
with io.open(filepath, encoding=encoding) as fd:
source = fd.read()
return cls(source, filename, directory, format, engine, encoding) | python | def from_file(cls, filename, directory=None,
format=None, engine=None, encoding=File._encoding):
filepath = os.path.join(directory or '', filename)
if encoding is None:
encoding = locale.getpreferredencoding()
with io.open(filepath, encoding=encoding) as fd:
source = fd.read()
return cls(source, filename, directory, format, engine, encoding) | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
",",
"directory",
"=",
"None",
",",
"format",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"encoding",
"=",
"File",
".",
"_encoding",
")",
":",
"filepath",
"=",
"os",
".",
"path",
".",
"join",
"(",
... | Return an instance with the source string read from the given file.
Args:
filename: Filename for loading/saving the source.
directory: (Sub)directory for source loading/saving and rendering.
format: Rendering output format (``'pdf'``, ``'png'``, ...).
engine: Layout command used (``'dot'``, ``'neato'``, ...).
encoding: Encoding for loading/saving the source. | [
"Return",
"an",
"instance",
"with",
"the",
"source",
"string",
"read",
"from",
"the",
"given",
"file",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/files.py#L255-L271 |
229,086 | xflr6/graphviz | graphviz/lang.py | quote | def quote(identifier,
html=HTML_STRING.match, valid_id=ID.match, dot_keywords=KEYWORDS):
"""Return DOT identifier from string, quote if needed.
>>> quote('')
'""'
>>> quote('spam')
'spam'
>>> quote('spam spam')
'"spam spam"'
>>> quote('-4.2')
'-4.2'
>>> quote('.42')
'.42'
>>> quote('<<b>spam</b>>')
'<<b>spam</b>>'
>>> quote(nohtml('<>'))
'"<>"'
"""
if html(identifier) and not isinstance(identifier, NoHtml):
pass
elif not valid_id(identifier) or identifier.lower() in dot_keywords:
return '"%s"' % identifier.replace('"', '\\"')
return identifier | python | def quote(identifier,
html=HTML_STRING.match, valid_id=ID.match, dot_keywords=KEYWORDS):
if html(identifier) and not isinstance(identifier, NoHtml):
pass
elif not valid_id(identifier) or identifier.lower() in dot_keywords:
return '"%s"' % identifier.replace('"', '\\"')
return identifier | [
"def",
"quote",
"(",
"identifier",
",",
"html",
"=",
"HTML_STRING",
".",
"match",
",",
"valid_id",
"=",
"ID",
".",
"match",
",",
"dot_keywords",
"=",
"KEYWORDS",
")",
":",
"if",
"html",
"(",
"identifier",
")",
"and",
"not",
"isinstance",
"(",
"identifier... | Return DOT identifier from string, quote if needed.
>>> quote('')
'""'
>>> quote('spam')
'spam'
>>> quote('spam spam')
'"spam spam"'
>>> quote('-4.2')
'-4.2'
>>> quote('.42')
'.42'
>>> quote('<<b>spam</b>>')
'<<b>spam</b>>'
>>> quote(nohtml('<>'))
'"<>"' | [
"Return",
"DOT",
"identifier",
"from",
"string",
"quote",
"if",
"needed",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/lang.py#L23-L52 |
229,087 | xflr6/graphviz | graphviz/lang.py | quote_edge | def quote_edge(identifier):
"""Return DOT edge statement node_id from string, quote if needed.
>>> quote_edge('spam')
'spam'
>>> quote_edge('spam spam:eggs eggs')
'"spam spam":"eggs eggs"'
>>> quote_edge('spam:eggs:s')
'spam:eggs:s'
"""
node, _, rest = identifier.partition(':')
parts = [quote(node)]
if rest:
port, _, compass = rest.partition(':')
parts.append(quote(port))
if compass:
parts.append(compass)
return ':'.join(parts) | python | def quote_edge(identifier):
node, _, rest = identifier.partition(':')
parts = [quote(node)]
if rest:
port, _, compass = rest.partition(':')
parts.append(quote(port))
if compass:
parts.append(compass)
return ':'.join(parts) | [
"def",
"quote_edge",
"(",
"identifier",
")",
":",
"node",
",",
"_",
",",
"rest",
"=",
"identifier",
".",
"partition",
"(",
"':'",
")",
"parts",
"=",
"[",
"quote",
"(",
"node",
")",
"]",
"if",
"rest",
":",
"port",
",",
"_",
",",
"compass",
"=",
"r... | Return DOT edge statement node_id from string, quote if needed.
>>> quote_edge('spam')
'spam'
>>> quote_edge('spam spam:eggs eggs')
'"spam spam":"eggs eggs"'
>>> quote_edge('spam:eggs:s')
'spam:eggs:s' | [
"Return",
"DOT",
"edge",
"statement",
"node_id",
"from",
"string",
"quote",
"if",
"needed",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/lang.py#L55-L74 |
229,088 | xflr6/graphviz | graphviz/lang.py | a_list | def a_list(label=None, kwargs=None, attributes=None):
"""Return assembled DOT a_list string.
>>> a_list('spam', {'spam': None, 'ham': 'ham ham', 'eggs': ''})
'label=spam eggs="" ham="ham ham"'
"""
result = ['label=%s' % quote(label)] if label is not None else []
if kwargs:
items = ['%s=%s' % (quote(k), quote(v))
for k, v in tools.mapping_items(kwargs) if v is not None]
result.extend(items)
if attributes:
if hasattr(attributes, 'items'):
attributes = tools.mapping_items(attributes)
items = ['%s=%s' % (quote(k), quote(v))
for k, v in attributes if v is not None]
result.extend(items)
return ' '.join(result) | python | def a_list(label=None, kwargs=None, attributes=None):
result = ['label=%s' % quote(label)] if label is not None else []
if kwargs:
items = ['%s=%s' % (quote(k), quote(v))
for k, v in tools.mapping_items(kwargs) if v is not None]
result.extend(items)
if attributes:
if hasattr(attributes, 'items'):
attributes = tools.mapping_items(attributes)
items = ['%s=%s' % (quote(k), quote(v))
for k, v in attributes if v is not None]
result.extend(items)
return ' '.join(result) | [
"def",
"a_list",
"(",
"label",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"result",
"=",
"[",
"'label=%s'",
"%",
"quote",
"(",
"label",
")",
"]",
"if",
"label",
"is",
"not",
"None",
"else",
"[",
"]",
"if",
... | Return assembled DOT a_list string.
>>> a_list('spam', {'spam': None, 'ham': 'ham ham', 'eggs': ''})
'label=spam eggs="" ham="ham ham"' | [
"Return",
"assembled",
"DOT",
"a_list",
"string",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/lang.py#L77-L94 |
229,089 | xflr6/graphviz | graphviz/lang.py | attr_list | def attr_list(label=None, kwargs=None, attributes=None):
"""Return assembled DOT attribute list string.
Sorts ``kwargs`` and ``attributes`` if they are plain dicts (to avoid
unpredictable order from hash randomization in Python 3 versions).
>>> attr_list()
''
>>> attr_list('spam spam', kwargs={'eggs': 'eggs', 'ham': 'ham ham'})
' [label="spam spam" eggs=eggs ham="ham ham"]'
>>> attr_list(kwargs={'spam': None, 'eggs': ''})
' [eggs=""]'
"""
content = a_list(label, kwargs, attributes)
if not content:
return ''
return ' [%s]' % content | python | def attr_list(label=None, kwargs=None, attributes=None):
content = a_list(label, kwargs, attributes)
if not content:
return ''
return ' [%s]' % content | [
"def",
"attr_list",
"(",
"label",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"attributes",
"=",
"None",
")",
":",
"content",
"=",
"a_list",
"(",
"label",
",",
"kwargs",
",",
"attributes",
")",
"if",
"not",
"content",
":",
"return",
"''",
"return",
... | Return assembled DOT attribute list string.
Sorts ``kwargs`` and ``attributes`` if they are plain dicts (to avoid
unpredictable order from hash randomization in Python 3 versions).
>>> attr_list()
''
>>> attr_list('spam spam', kwargs={'eggs': 'eggs', 'ham': 'ham ham'})
' [label="spam spam" eggs=eggs ham="ham ham"]'
>>> attr_list(kwargs={'spam': None, 'eggs': ''})
' [eggs=""]' | [
"Return",
"assembled",
"DOT",
"attribute",
"list",
"string",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/lang.py#L97-L115 |
229,090 | xflr6/graphviz | graphviz/dot.py | Dot.edge | def edge(self, tail_name, head_name, label=None, _attributes=None, **attrs):
"""Create an edge between two nodes.
Args:
tail_name: Start node identifier.
head_name: End node identifier.
label: Caption to be displayed near the edge.
attrs: Any additional edge attributes (must be strings).
"""
tail_name = self._quote_edge(tail_name)
head_name = self._quote_edge(head_name)
attr_list = self._attr_list(label, attrs, _attributes)
line = self._edge % (tail_name, head_name, attr_list)
self.body.append(line) | python | def edge(self, tail_name, head_name, label=None, _attributes=None, **attrs):
tail_name = self._quote_edge(tail_name)
head_name = self._quote_edge(head_name)
attr_list = self._attr_list(label, attrs, _attributes)
line = self._edge % (tail_name, head_name, attr_list)
self.body.append(line) | [
"def",
"edge",
"(",
"self",
",",
"tail_name",
",",
"head_name",
",",
"label",
"=",
"None",
",",
"_attributes",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"tail_name",
"=",
"self",
".",
"_quote_edge",
"(",
"tail_name",
")",
"head_name",
"=",
"self",... | Create an edge between two nodes.
Args:
tail_name: Start node identifier.
head_name: End node identifier.
label: Caption to be displayed near the edge.
attrs: Any additional edge attributes (must be strings). | [
"Create",
"an",
"edge",
"between",
"two",
"nodes",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/dot.py#L135-L148 |
229,091 | xflr6/graphviz | graphviz/dot.py | Dot.edges | def edges(self, tail_head_iter):
"""Create a bunch of edges.
Args:
tail_head_iter: Iterable of ``(tail_name, head_name)`` pairs.
"""
edge = self._edge_plain
quote = self._quote_edge
lines = (edge % (quote(t), quote(h)) for t, h in tail_head_iter)
self.body.extend(lines) | python | def edges(self, tail_head_iter):
edge = self._edge_plain
quote = self._quote_edge
lines = (edge % (quote(t), quote(h)) for t, h in tail_head_iter)
self.body.extend(lines) | [
"def",
"edges",
"(",
"self",
",",
"tail_head_iter",
")",
":",
"edge",
"=",
"self",
".",
"_edge_plain",
"quote",
"=",
"self",
".",
"_quote_edge",
"lines",
"=",
"(",
"edge",
"%",
"(",
"quote",
"(",
"t",
")",
",",
"quote",
"(",
"h",
")",
")",
"for",
... | Create a bunch of edges.
Args:
tail_head_iter: Iterable of ``(tail_name, head_name)`` pairs. | [
"Create",
"a",
"bunch",
"of",
"edges",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/dot.py#L150-L159 |
229,092 | xflr6/graphviz | graphviz/tools.py | mkdirs | def mkdirs(filename, mode=0o777):
"""Recursively create directories up to the path of ``filename`` as needed."""
dirname = os.path.dirname(filename)
if not dirname:
return
_compat.makedirs(dirname, mode=mode, exist_ok=True) | python | def mkdirs(filename, mode=0o777):
dirname = os.path.dirname(filename)
if not dirname:
return
_compat.makedirs(dirname, mode=mode, exist_ok=True) | [
"def",
"mkdirs",
"(",
"filename",
",",
"mode",
"=",
"0o777",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"not",
"dirname",
":",
"return",
"_compat",
".",
"makedirs",
"(",
"dirname",
",",
"mode",
"=",
"mode... | Recursively create directories up to the path of ``filename`` as needed. | [
"Recursively",
"create",
"directories",
"up",
"to",
"the",
"path",
"of",
"filename",
"as",
"needed",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/tools.py#L26-L31 |
229,093 | xflr6/graphviz | graphviz/tools.py | mapping_items | def mapping_items(mapping, _iteritems=_compat.iteritems):
"""Return an iterator over the ``mapping`` items, sort if it's a plain dict.
>>> list(mapping_items({'spam': 0, 'ham': 1, 'eggs': 2}))
[('eggs', 2), ('ham', 1), ('spam', 0)]
>>> from collections import OrderedDict
>>> list(mapping_items(OrderedDict(enumerate(['spam', 'ham', 'eggs']))))
[(0, 'spam'), (1, 'ham'), (2, 'eggs')]
"""
if type(mapping) is dict:
return iter(sorted(_iteritems(mapping)))
return _iteritems(mapping) | python | def mapping_items(mapping, _iteritems=_compat.iteritems):
if type(mapping) is dict:
return iter(sorted(_iteritems(mapping)))
return _iteritems(mapping) | [
"def",
"mapping_items",
"(",
"mapping",
",",
"_iteritems",
"=",
"_compat",
".",
"iteritems",
")",
":",
"if",
"type",
"(",
"mapping",
")",
"is",
"dict",
":",
"return",
"iter",
"(",
"sorted",
"(",
"_iteritems",
"(",
"mapping",
")",
")",
")",
"return",
"_... | Return an iterator over the ``mapping`` items, sort if it's a plain dict.
>>> list(mapping_items({'spam': 0, 'ham': 1, 'eggs': 2}))
[('eggs', 2), ('ham', 1), ('spam', 0)]
>>> from collections import OrderedDict
>>> list(mapping_items(OrderedDict(enumerate(['spam', 'ham', 'eggs']))))
[(0, 'spam'), (1, 'ham'), (2, 'eggs')] | [
"Return",
"an",
"iterator",
"over",
"the",
"mapping",
"items",
"sort",
"if",
"it",
"s",
"a",
"plain",
"dict",
"."
] | 7376095ef1e47abad7e0b0361b6c9720b706e7a0 | https://github.com/xflr6/graphviz/blob/7376095ef1e47abad7e0b0361b6c9720b706e7a0/graphviz/tools.py#L34-L46 |
229,094 | ithaka/apiron | apiron/client.py | ServiceCaller.get_adapted_session | def get_adapted_session(adapter):
"""
Mounts an adapter capable of communication over HTTP or HTTPS to the supplied session.
:param adapter:
A :class:`requests.adapters.HTTPAdapter` instance
:return:
The adapted :class:`requests.Session` instance
"""
session = requests.Session()
session.mount("http://", adapter)
session.mount("https://", adapter)
return session | python | def get_adapted_session(adapter):
session = requests.Session()
session.mount("http://", adapter)
session.mount("https://", adapter)
return session | [
"def",
"get_adapted_session",
"(",
"adapter",
")",
":",
"session",
"=",
"requests",
".",
"Session",
"(",
")",
"session",
".",
"mount",
"(",
"\"http://\"",
",",
"adapter",
")",
"session",
".",
"mount",
"(",
"\"https://\"",
",",
"adapter",
")",
"return",
"se... | Mounts an adapter capable of communication over HTTP or HTTPS to the supplied session.
:param adapter:
A :class:`requests.adapters.HTTPAdapter` instance
:return:
The adapted :class:`requests.Session` instance | [
"Mounts",
"an",
"adapter",
"capable",
"of",
"communication",
"over",
"HTTP",
"or",
"HTTPS",
"to",
"the",
"supplied",
"session",
"."
] | e9dce3629b164098247843f7684ef10a3e032ee6 | https://github.com/ithaka/apiron/blob/e9dce3629b164098247843f7684ef10a3e032ee6/apiron/client.py#L61-L73 |
229,095 | ithaka/apiron | apiron/endpoint/endpoint.py | Endpoint.get_formatted_path | def get_formatted_path(self, **kwargs):
"""
Format this endpoint's path with the supplied keyword arguments
:return:
The fully-formatted path
:rtype:
str
"""
self._validate_path_placeholders(self.path_placeholders, kwargs)
return self.path.format(**kwargs) | python | def get_formatted_path(self, **kwargs):
self._validate_path_placeholders(self.path_placeholders, kwargs)
return self.path.format(**kwargs) | [
"def",
"get_formatted_path",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_validate_path_placeholders",
"(",
"self",
".",
"path_placeholders",
",",
"kwargs",
")",
"return",
"self",
".",
"path",
".",
"format",
"(",
"*",
"*",
"kwargs",
")"
] | Format this endpoint's path with the supplied keyword arguments
:return:
The fully-formatted path
:rtype:
str | [
"Format",
"this",
"endpoint",
"s",
"path",
"with",
"the",
"supplied",
"keyword",
"arguments"
] | e9dce3629b164098247843f7684ef10a3e032ee6 | https://github.com/ithaka/apiron/blob/e9dce3629b164098247843f7684ef10a3e032ee6/apiron/endpoint/endpoint.py#L79-L90 |
229,096 | ithaka/apiron | apiron/endpoint/endpoint.py | Endpoint.path_placeholders | def path_placeholders(self):
"""
The formattable placeholders from this endpoint's path, in the order they appear.
Example:
>>> endpoint = Endpoint(path='/api/{foo}/{bar}')
>>> endpoint.path_placeholders
['foo', 'bar']
"""
parser = string.Formatter()
return [placeholder_name for _, placeholder_name, _, _ in parser.parse(self.path) if placeholder_name] | python | def path_placeholders(self):
parser = string.Formatter()
return [placeholder_name for _, placeholder_name, _, _ in parser.parse(self.path) if placeholder_name] | [
"def",
"path_placeholders",
"(",
"self",
")",
":",
"parser",
"=",
"string",
".",
"Formatter",
"(",
")",
"return",
"[",
"placeholder_name",
"for",
"_",
",",
"placeholder_name",
",",
"_",
",",
"_",
"in",
"parser",
".",
"parse",
"(",
"self",
".",
"path",
... | The formattable placeholders from this endpoint's path, in the order they appear.
Example:
>>> endpoint = Endpoint(path='/api/{foo}/{bar}')
>>> endpoint.path_placeholders
['foo', 'bar'] | [
"The",
"formattable",
"placeholders",
"from",
"this",
"endpoint",
"s",
"path",
"in",
"the",
"order",
"they",
"appear",
"."
] | e9dce3629b164098247843f7684ef10a3e032ee6 | https://github.com/ithaka/apiron/blob/e9dce3629b164098247843f7684ef10a3e032ee6/apiron/endpoint/endpoint.py#L93-L105 |
229,097 | ithaka/apiron | apiron/endpoint/endpoint.py | Endpoint.get_merged_params | def get_merged_params(self, supplied_params=None):
"""
Merge this endpoint's default parameters with the supplied parameters
:param dict supplied_params:
A dictionary of query parameter, value pairs
:return:
A dictionary of this endpoint's default parameters, merged with the supplied parameters.
Any default parameters which have a value supplied are overridden.
:rtype:
dict
:raises apiron.exceptions.UnfulfilledParameterException:
When a required parameter for this endpoint is not a default param and is not supplied by the caller
"""
supplied_params = supplied_params or {}
empty_params = {
param: supplied_params[param] for param in supplied_params if supplied_params[param] in (None, "")
}
if empty_params:
warnings.warn(
"The {path} endpoint "
"was called with empty parameters: {empty_params}".format(path=self.path, empty_params=empty_params),
RuntimeWarning,
stacklevel=5,
)
unfulfilled_params = {
param for param in self.required_params if param not in supplied_params and param not in self.default_params
}
if unfulfilled_params:
raise UnfulfilledParameterException(self.path, unfulfilled_params)
merged_params = self.default_params.copy()
merged_params.update(supplied_params)
return merged_params | python | def get_merged_params(self, supplied_params=None):
supplied_params = supplied_params or {}
empty_params = {
param: supplied_params[param] for param in supplied_params if supplied_params[param] in (None, "")
}
if empty_params:
warnings.warn(
"The {path} endpoint "
"was called with empty parameters: {empty_params}".format(path=self.path, empty_params=empty_params),
RuntimeWarning,
stacklevel=5,
)
unfulfilled_params = {
param for param in self.required_params if param not in supplied_params and param not in self.default_params
}
if unfulfilled_params:
raise UnfulfilledParameterException(self.path, unfulfilled_params)
merged_params = self.default_params.copy()
merged_params.update(supplied_params)
return merged_params | [
"def",
"get_merged_params",
"(",
"self",
",",
"supplied_params",
"=",
"None",
")",
":",
"supplied_params",
"=",
"supplied_params",
"or",
"{",
"}",
"empty_params",
"=",
"{",
"param",
":",
"supplied_params",
"[",
"param",
"]",
"for",
"param",
"in",
"supplied_par... | Merge this endpoint's default parameters with the supplied parameters
:param dict supplied_params:
A dictionary of query parameter, value pairs
:return:
A dictionary of this endpoint's default parameters, merged with the supplied parameters.
Any default parameters which have a value supplied are overridden.
:rtype:
dict
:raises apiron.exceptions.UnfulfilledParameterException:
When a required parameter for this endpoint is not a default param and is not supplied by the caller | [
"Merge",
"this",
"endpoint",
"s",
"default",
"parameters",
"with",
"the",
"supplied",
"parameters"
] | e9dce3629b164098247843f7684ef10a3e032ee6 | https://github.com/ithaka/apiron/blob/e9dce3629b164098247843f7684ef10a3e032ee6/apiron/endpoint/endpoint.py#L115-L151 |
229,098 | ithaka/apiron | apiron/endpoint/json.py | JsonEndpoint.format_response | def format_response(self, response):
"""
Extracts JSON data from the response
:param requests.Response response:
The original response from :mod:`requests`
:return:
The response's JSON content
:rtype:
:class:`dict` if ``preserve_order`` is ``False``
:rtype:
:class:`collections.OrderedDict` if ``preserve_order`` is ``True``
"""
return response.json(object_pairs_hook=collections.OrderedDict if self.preserve_order else None) | python | def format_response(self, response):
return response.json(object_pairs_hook=collections.OrderedDict if self.preserve_order else None) | [
"def",
"format_response",
"(",
"self",
",",
"response",
")",
":",
"return",
"response",
".",
"json",
"(",
"object_pairs_hook",
"=",
"collections",
".",
"OrderedDict",
"if",
"self",
".",
"preserve_order",
"else",
"None",
")"
] | Extracts JSON data from the response
:param requests.Response response:
The original response from :mod:`requests`
:return:
The response's JSON content
:rtype:
:class:`dict` if ``preserve_order`` is ``False``
:rtype:
:class:`collections.OrderedDict` if ``preserve_order`` is ``True`` | [
"Extracts",
"JSON",
"data",
"from",
"the",
"response"
] | e9dce3629b164098247843f7684ef10a3e032ee6 | https://github.com/ithaka/apiron/blob/e9dce3629b164098247843f7684ef10a3e032ee6/apiron/endpoint/json.py#L18-L32 |
229,099 | datastax/python-driver | setup.py | pre_build_check | def pre_build_check():
"""
Try to verify build tools
"""
if os.environ.get('CASS_DRIVER_NO_PRE_BUILD_CHECK'):
return True
try:
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
from distutils.dist import Distribution
# base build_ext just to emulate compiler option setup
be = build_ext(Distribution())
be.initialize_options()
be.finalize_options()
# First, make sure we have a Python include directory
have_python_include = any(os.path.isfile(os.path.join(p, 'Python.h')) for p in be.include_dirs)
if not have_python_include:
sys.stderr.write("Did not find 'Python.h' in %s.\n" % (be.include_dirs,))
return False
compiler = new_compiler(compiler=be.compiler)
customize_compiler(compiler)
try:
# We must be able to initialize the compiler if it has that method
if hasattr(compiler, "initialize"):
compiler.initialize()
except:
return False
executables = []
if compiler.compiler_type in ('unix', 'cygwin'):
executables = [compiler.executables[exe][0] for exe in ('compiler_so', 'linker_so')]
elif compiler.compiler_type == 'nt':
executables = [getattr(compiler, exe) for exe in ('cc', 'linker')]
if executables:
from distutils.spawn import find_executable
for exe in executables:
if not find_executable(exe):
sys.stderr.write("Failed to find %s for compiler type %s.\n" % (exe, compiler.compiler_type))
return False
except Exception as exc:
sys.stderr.write('%s\n' % str(exc))
sys.stderr.write("Failed pre-build check. Attempting anyway.\n")
# if we are unable to positively id the compiler type, or one of these assumptions fails,
# just proceed as we would have without the check
return True | python | def pre_build_check():
if os.environ.get('CASS_DRIVER_NO_PRE_BUILD_CHECK'):
return True
try:
from distutils.ccompiler import new_compiler
from distutils.sysconfig import customize_compiler
from distutils.dist import Distribution
# base build_ext just to emulate compiler option setup
be = build_ext(Distribution())
be.initialize_options()
be.finalize_options()
# First, make sure we have a Python include directory
have_python_include = any(os.path.isfile(os.path.join(p, 'Python.h')) for p in be.include_dirs)
if not have_python_include:
sys.stderr.write("Did not find 'Python.h' in %s.\n" % (be.include_dirs,))
return False
compiler = new_compiler(compiler=be.compiler)
customize_compiler(compiler)
try:
# We must be able to initialize the compiler if it has that method
if hasattr(compiler, "initialize"):
compiler.initialize()
except:
return False
executables = []
if compiler.compiler_type in ('unix', 'cygwin'):
executables = [compiler.executables[exe][0] for exe in ('compiler_so', 'linker_so')]
elif compiler.compiler_type == 'nt':
executables = [getattr(compiler, exe) for exe in ('cc', 'linker')]
if executables:
from distutils.spawn import find_executable
for exe in executables:
if not find_executable(exe):
sys.stderr.write("Failed to find %s for compiler type %s.\n" % (exe, compiler.compiler_type))
return False
except Exception as exc:
sys.stderr.write('%s\n' % str(exc))
sys.stderr.write("Failed pre-build check. Attempting anyway.\n")
# if we are unable to positively id the compiler type, or one of these assumptions fails,
# just proceed as we would have without the check
return True | [
"def",
"pre_build_check",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'CASS_DRIVER_NO_PRE_BUILD_CHECK'",
")",
":",
"return",
"True",
"try",
":",
"from",
"distutils",
".",
"ccompiler",
"import",
"new_compiler",
"from",
"distutils",
".",
"syscon... | Try to verify build tools | [
"Try",
"to",
"verify",
"build",
"tools"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/setup.py#L325-L377 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.