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
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
2,900
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/asset.py
Asset.new_withdraw_ong_transaction
def new_withdraw_ong_transaction(self, b58_claimer_address: str, b58_recv_address: str, amount: int, b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction: """ This interface is used to generate a Transaction object that allow one account to withdraw an amount of ong and transfer them to receive address. :param b58_claimer_address: a base58 encode address which is used to indicate who is the claimer. :param b58_recv_address: a base58 encode address which is used to indicate who receive the claimed ong. :param amount: the amount of asset that will be claimed. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which can be used for withdraw ong. """ if not isinstance(b58_claimer_address, str) or not isinstance(b58_recv_address, str) or not isinstance( b58_payer_address, str): raise SDKException(ErrorCode.param_err('the data type of base58 encode address should be the string.')) if len(b58_claimer_address) != 34 or len(b58_recv_address) != 34 or len(b58_payer_address) != 34: raise SDKException(ErrorCode.param_err('the length of base58 encode address should be 34 bytes.')) if amount <= 0: raise SDKException(ErrorCode.other_error('the amount should be greater than than zero.')) if gas_price < 0: raise SDKException(ErrorCode.other_error('the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException(ErrorCode.other_error('the gas limit should be equal or greater than zero.')) ont_contract_address = self.get_asset_address('ont') ong_contract_address = self.get_asset_address("ong") args = {"sender": Address.b58decode(b58_claimer_address).to_bytes(), "from": ont_contract_address, "to": Address.b58decode(b58_recv_address).to_bytes(), "value": amount} invoke_code = build_native_invoke_code(ong_contract_address, b'\x00', "transferFrom", args) payer_array = Address.b58decode(b58_payer_address).to_bytes() return Transaction(0, 0xd1, int(time()), gas_price, gas_limit, payer_array, invoke_code, bytearray(), list())
python
def new_withdraw_ong_transaction(self, b58_claimer_address: str, b58_recv_address: str, amount: int, b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction: if not isinstance(b58_claimer_address, str) or not isinstance(b58_recv_address, str) or not isinstance( b58_payer_address, str): raise SDKException(ErrorCode.param_err('the data type of base58 encode address should be the string.')) if len(b58_claimer_address) != 34 or len(b58_recv_address) != 34 or len(b58_payer_address) != 34: raise SDKException(ErrorCode.param_err('the length of base58 encode address should be 34 bytes.')) if amount <= 0: raise SDKException(ErrorCode.other_error('the amount should be greater than than zero.')) if gas_price < 0: raise SDKException(ErrorCode.other_error('the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException(ErrorCode.other_error('the gas limit should be equal or greater than zero.')) ont_contract_address = self.get_asset_address('ont') ong_contract_address = self.get_asset_address("ong") args = {"sender": Address.b58decode(b58_claimer_address).to_bytes(), "from": ont_contract_address, "to": Address.b58decode(b58_recv_address).to_bytes(), "value": amount} invoke_code = build_native_invoke_code(ong_contract_address, b'\x00', "transferFrom", args) payer_array = Address.b58decode(b58_payer_address).to_bytes() return Transaction(0, 0xd1, int(time()), gas_price, gas_limit, payer_array, invoke_code, bytearray(), list())
[ "def", "new_withdraw_ong_transaction", "(", "self", ",", "b58_claimer_address", ":", "str", ",", "b58_recv_address", ":", "str", ",", "amount", ":", "int", ",", "b58_payer_address", ":", "str", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "Transaction", ":", "if", "not", "isinstance", "(", "b58_claimer_address", ",", "str", ")", "or", "not", "isinstance", "(", "b58_recv_address", ",", "str", ")", "or", "not", "isinstance", "(", "b58_payer_address", ",", "str", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the data type of base58 encode address should be the string.'", ")", ")", "if", "len", "(", "b58_claimer_address", ")", "!=", "34", "or", "len", "(", "b58_recv_address", ")", "!=", "34", "or", "len", "(", "b58_payer_address", ")", "!=", "34", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the length of base58 encode address should be 34 bytes.'", ")", ")", "if", "amount", "<=", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the amount should be greater than than zero.'", ")", ")", "if", "gas_price", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the gas price should be equal or greater than zero.'", ")", ")", "if", "gas_limit", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the gas limit should be equal or greater than zero.'", ")", ")", "ont_contract_address", "=", "self", ".", "get_asset_address", "(", "'ont'", ")", "ong_contract_address", "=", "self", ".", "get_asset_address", "(", "\"ong\"", ")", "args", "=", "{", "\"sender\"", ":", "Address", ".", "b58decode", "(", "b58_claimer_address", ")", ".", "to_bytes", "(", ")", ",", "\"from\"", ":", "ont_contract_address", ",", "\"to\"", ":", "Address", ".", "b58decode", "(", "b58_recv_address", ")", ".", "to_bytes", "(", ")", ",", "\"value\"", ":", "amount", "}", "invoke_code", "=", "build_native_invoke_code", "(", "ong_contract_address", ",", "b'\\x00'", ",", "\"transferFrom\"", ",", "args", ")", "payer_array", "=", "Address", ".", "b58decode", "(", "b58_payer_address", ")", ".", "to_bytes", "(", ")", "return", "Transaction", "(", "0", ",", "0xd1", ",", "int", "(", "time", "(", ")", ")", ",", "gas_price", ",", "gas_limit", ",", "payer_array", ",", "invoke_code", ",", "bytearray", "(", ")", ",", "list", "(", ")", ")" ]
This interface is used to generate a Transaction object that allow one account to withdraw an amount of ong and transfer them to receive address. :param b58_claimer_address: a base58 encode address which is used to indicate who is the claimer. :param b58_recv_address: a base58 encode address which is used to indicate who receive the claimed ong. :param amount: the amount of asset that will be claimed. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: a Transaction object which can be used for withdraw ong.
[ "This", "interface", "is", "used", "to", "generate", "a", "Transaction", "object", "that", "allow", "one", "account", "to", "withdraw", "an", "amount", "of", "ong", "and", "transfer", "them", "to", "receive", "address", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/asset.py#L226-L257
2,901
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/asset.py
Asset.transfer
def transfer(self, asset: str, from_acct: Account, b58_to_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int): """ This interface is used to send a transfer transaction that only for ONT or ONG. :param asset: a string which is used to indicate which asset we want to transfer. :param from_acct: a Account object which indicate where the asset from. :param b58_to_address: a base58 encode address which indicate where the asset to. :param amount: the amount of asset that will be transferred. :param payer: a Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: hexadecimal transaction hash value. """ tx = self.new_transfer_transaction(asset, from_acct.get_address_base58(), b58_to_address, amount, payer.get_address_base58(), gas_limit, gas_price) tx.sign_transaction(from_acct) if from_acct.get_address_base58() != payer.get_address_base58(): tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
python
def transfer(self, asset: str, from_acct: Account, b58_to_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int): tx = self.new_transfer_transaction(asset, from_acct.get_address_base58(), b58_to_address, amount, payer.get_address_base58(), gas_limit, gas_price) tx.sign_transaction(from_acct) if from_acct.get_address_base58() != payer.get_address_base58(): tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
[ "def", "transfer", "(", "self", ",", "asset", ":", "str", ",", "from_acct", ":", "Account", ",", "b58_to_address", ":", "str", ",", "amount", ":", "int", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", ":", "tx", "=", "self", ".", "new_transfer_transaction", "(", "asset", ",", "from_acct", ".", "get_address_base58", "(", ")", ",", "b58_to_address", ",", "amount", ",", "payer", ".", "get_address_base58", "(", ")", ",", "gas_limit", ",", "gas_price", ")", "tx", ".", "sign_transaction", "(", "from_acct", ")", "if", "from_acct", ".", "get_address_base58", "(", ")", "!=", "payer", ".", "get_address_base58", "(", ")", ":", "tx", ".", "add_sign_transaction", "(", "payer", ")", "return", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")" ]
This interface is used to send a transfer transaction that only for ONT or ONG. :param asset: a string which is used to indicate which asset we want to transfer. :param from_acct: a Account object which indicate where the asset from. :param b58_to_address: a base58 encode address which indicate where the asset to. :param amount: the amount of asset that will be transferred. :param payer: a Account object which indicate who will pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "send", "a", "transfer", "transaction", "that", "only", "for", "ONT", "or", "ONG", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/asset.py#L259-L278
2,902
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/asset.py
Asset.withdraw_ong
def withdraw_ong(self, claimer: Account, b58_recv_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to withdraw a amount of ong and transfer them to receive address. :param claimer: the owner of ong that remained to claim. :param b58_recv_address: the address that received the ong. :param amount: the amount of ong want to claim. :param payer: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: hexadecimal transaction hash value. """ if claimer is None: raise SDKException(ErrorCode.param_err('the claimer should not be None.')) if payer is None: raise SDKException(ErrorCode.param_err('the payer should not be None.')) if amount <= 0: raise SDKException(ErrorCode.other_error('the amount should be greater than than zero.')) if gas_price < 0: raise SDKException(ErrorCode.other_error('the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException(ErrorCode.other_error('the gas limit should be equal or greater than zero.')) b58_claimer = claimer.get_address_base58() b58_payer = payer.get_address_base58() tx = self.new_withdraw_ong_transaction(b58_claimer, b58_recv_address, amount, b58_payer, gas_limit, gas_price) tx.sign_transaction(claimer) if claimer.get_address_base58() != payer.get_address_base58(): tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
python
def withdraw_ong(self, claimer: Account, b58_recv_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int) -> str: if claimer is None: raise SDKException(ErrorCode.param_err('the claimer should not be None.')) if payer is None: raise SDKException(ErrorCode.param_err('the payer should not be None.')) if amount <= 0: raise SDKException(ErrorCode.other_error('the amount should be greater than than zero.')) if gas_price < 0: raise SDKException(ErrorCode.other_error('the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException(ErrorCode.other_error('the gas limit should be equal or greater than zero.')) b58_claimer = claimer.get_address_base58() b58_payer = payer.get_address_base58() tx = self.new_withdraw_ong_transaction(b58_claimer, b58_recv_address, amount, b58_payer, gas_limit, gas_price) tx.sign_transaction(claimer) if claimer.get_address_base58() != payer.get_address_base58(): tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
[ "def", "withdraw_ong", "(", "self", ",", "claimer", ":", "Account", ",", "b58_recv_address", ":", "str", ",", "amount", ":", "int", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "str", ":", "if", "claimer", "is", "None", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the claimer should not be None.'", ")", ")", "if", "payer", "is", "None", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the payer should not be None.'", ")", ")", "if", "amount", "<=", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the amount should be greater than than zero.'", ")", ")", "if", "gas_price", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the gas price should be equal or greater than zero.'", ")", ")", "if", "gas_limit", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the gas limit should be equal or greater than zero.'", ")", ")", "b58_claimer", "=", "claimer", ".", "get_address_base58", "(", ")", "b58_payer", "=", "payer", ".", "get_address_base58", "(", ")", "tx", "=", "self", ".", "new_withdraw_ong_transaction", "(", "b58_claimer", ",", "b58_recv_address", ",", "amount", ",", "b58_payer", ",", "gas_limit", ",", "gas_price", ")", "tx", ".", "sign_transaction", "(", "claimer", ")", "if", "claimer", ".", "get_address_base58", "(", ")", "!=", "payer", ".", "get_address_base58", "(", ")", ":", "tx", ".", "add_sign_transaction", "(", "payer", ")", "return", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")" ]
This interface is used to withdraw a amount of ong and transfer them to receive address. :param claimer: the owner of ong that remained to claim. :param b58_recv_address: the address that received the ong. :param amount: the amount of ong want to claim. :param payer: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: hexadecimal transaction hash value.
[ "This", "interface", "is", "used", "to", "withdraw", "a", "amount", "of", "ong", "and", "transfer", "them", "to", "receive", "address", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/asset.py#L280-L309
2,903
ontio/ontology-python-sdk
ontology/smart_contract/native_contract/asset.py
Asset.approve
def approve(self, asset, sender: Account, b58_recv_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int) -> str: """ This is an interface used to send an approve transaction which allow receiver to spend a amount of ONT or ONG asset in sender's account. :param asset: a string which is used to indicate what asset we want to approve. :param sender: an Account class that send the approve transaction. :param b58_recv_address: a base58 encode address which indicate where the approve to. :param amount: the amount of asset want to approve. :param payer: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: hexadecimal transaction hash value. """ if sender is None: raise SDKException(ErrorCode.param_err('the sender should not be None.')) if payer is None: raise SDKException(ErrorCode.param_err('the payer should not be None.')) if amount <= 0: raise SDKException(ErrorCode.other_error('the amount should be greater than than zero.')) if gas_price < 0: raise SDKException(ErrorCode.other_error('the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException(ErrorCode.other_error('the gas limit should be equal or greater than zero.')) b58_sender_address = sender.get_address_base58() b58_payer_address = payer.get_address_base58() tx = self.new_approve_transaction(asset, b58_sender_address, b58_recv_address, amount, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(sender) if sender.get_address_base58() != payer.get_address_base58(): tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
python
def approve(self, asset, sender: Account, b58_recv_address: str, amount: int, payer: Account, gas_limit: int, gas_price: int) -> str: if sender is None: raise SDKException(ErrorCode.param_err('the sender should not be None.')) if payer is None: raise SDKException(ErrorCode.param_err('the payer should not be None.')) if amount <= 0: raise SDKException(ErrorCode.other_error('the amount should be greater than than zero.')) if gas_price < 0: raise SDKException(ErrorCode.other_error('the gas price should be equal or greater than zero.')) if gas_limit < 0: raise SDKException(ErrorCode.other_error('the gas limit should be equal or greater than zero.')) b58_sender_address = sender.get_address_base58() b58_payer_address = payer.get_address_base58() tx = self.new_approve_transaction(asset, b58_sender_address, b58_recv_address, amount, b58_payer_address, gas_limit, gas_price) tx.sign_transaction(sender) if sender.get_address_base58() != payer.get_address_base58(): tx.add_sign_transaction(payer) return self.__sdk.get_network().send_raw_transaction(tx)
[ "def", "approve", "(", "self", ",", "asset", ",", "sender", ":", "Account", ",", "b58_recv_address", ":", "str", ",", "amount", ":", "int", ",", "payer", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "str", ":", "if", "sender", "is", "None", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the sender should not be None.'", ")", ")", "if", "payer", "is", "None", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_err", "(", "'the payer should not be None.'", ")", ")", "if", "amount", "<=", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the amount should be greater than than zero.'", ")", ")", "if", "gas_price", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the gas price should be equal or greater than zero.'", ")", ")", "if", "gas_limit", "<", "0", ":", "raise", "SDKException", "(", "ErrorCode", ".", "other_error", "(", "'the gas limit should be equal or greater than zero.'", ")", ")", "b58_sender_address", "=", "sender", ".", "get_address_base58", "(", ")", "b58_payer_address", "=", "payer", ".", "get_address_base58", "(", ")", "tx", "=", "self", ".", "new_approve_transaction", "(", "asset", ",", "b58_sender_address", ",", "b58_recv_address", ",", "amount", ",", "b58_payer_address", ",", "gas_limit", ",", "gas_price", ")", "tx", ".", "sign_transaction", "(", "sender", ")", "if", "sender", ".", "get_address_base58", "(", ")", "!=", "payer", ".", "get_address_base58", "(", ")", ":", "tx", ".", "add_sign_transaction", "(", "payer", ")", "return", "self", ".", "__sdk", ".", "get_network", "(", ")", ".", "send_raw_transaction", "(", "tx", ")" ]
This is an interface used to send an approve transaction which allow receiver to spend a amount of ONT or ONG asset in sender's account. :param asset: a string which is used to indicate what asset we want to approve. :param sender: an Account class that send the approve transaction. :param b58_recv_address: a base58 encode address which indicate where the approve to. :param amount: the amount of asset want to approve. :param payer: an Account class that used to pay for the transaction. :param gas_limit: an int value that indicate the gas limit. :param gas_price: an int value that indicate the gas price. :return: hexadecimal transaction hash value.
[ "This", "is", "an", "interface", "used", "to", "send", "an", "approve", "transaction", "which", "allow", "receiver", "to", "spend", "a", "amount", "of", "ONT", "or", "ONG", "asset", "in", "sender", "s", "account", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/smart_contract/native_contract/asset.py#L311-L343
2,904
ontio/ontology-python-sdk
ontology/wallet/wallet.py
WalletData.remove_account
def remove_account(self, address: str): """ This interface is used to remove account from WalletData. :param address: a string address. """ account = self.get_account_by_b58_address(address) if account is None: raise SDKException(ErrorCode.get_account_by_address_err) self.accounts.remove(account)
python
def remove_account(self, address: str): account = self.get_account_by_b58_address(address) if account is None: raise SDKException(ErrorCode.get_account_by_address_err) self.accounts.remove(account)
[ "def", "remove_account", "(", "self", ",", "address", ":", "str", ")", ":", "account", "=", "self", ".", "get_account_by_b58_address", "(", "address", ")", "if", "account", "is", "None", ":", "raise", "SDKException", "(", "ErrorCode", ".", "get_account_by_address_err", ")", "self", ".", "accounts", ".", "remove", "(", "account", ")" ]
This interface is used to remove account from WalletData. :param address: a string address.
[ "This", "interface", "is", "used", "to", "remove", "account", "from", "WalletData", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet.py#L101-L110
2,905
ontio/ontology-python-sdk
ontology/wallet/wallet.py
WalletData.set_default_account_by_index
def set_default_account_by_index(self, index: int): """ This interface is used to set default account by given index. :param index: an int value that indicate the account object in account list. """ if index >= len(self.accounts): raise SDKException(ErrorCode.param_error) for acct in self.accounts: acct.is_default = False self.accounts[index].is_default = True self.default_account_address = self.accounts[index].b58_address
python
def set_default_account_by_index(self, index: int): if index >= len(self.accounts): raise SDKException(ErrorCode.param_error) for acct in self.accounts: acct.is_default = False self.accounts[index].is_default = True self.default_account_address = self.accounts[index].b58_address
[ "def", "set_default_account_by_index", "(", "self", ",", "index", ":", "int", ")", ":", "if", "index", ">=", "len", "(", "self", ".", "accounts", ")", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_error", ")", "for", "acct", "in", "self", ".", "accounts", ":", "acct", ".", "is_default", "=", "False", "self", ".", "accounts", "[", "index", "]", ".", "is_default", "=", "True", "self", ".", "default_account_address", "=", "self", ".", "accounts", "[", "index", "]", ".", "b58_address" ]
This interface is used to set default account by given index. :param index: an int value that indicate the account object in account list.
[ "This", "interface", "is", "used", "to", "set", "default", "account", "by", "given", "index", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet.py#L120-L131
2,906
ontio/ontology-python-sdk
ontology/wallet/wallet.py
WalletData.set_default_account_by_address
def set_default_account_by_address(self, b58_address: str): """ This interface is used to set default account by given base58 encode address. :param b58_address: a base58 encode address. """ flag = True index = -1 for acct in self.accounts: index += 1 if acct.b58_address == b58_address: flag = False break if flag: raise SDKException(ErrorCode.get_account_by_address_err) for i in range(len(self.accounts)): self.accounts[i].is_default = False self.accounts[index].is_default = True self.default_account_address = b58_address
python
def set_default_account_by_address(self, b58_address: str): flag = True index = -1 for acct in self.accounts: index += 1 if acct.b58_address == b58_address: flag = False break if flag: raise SDKException(ErrorCode.get_account_by_address_err) for i in range(len(self.accounts)): self.accounts[i].is_default = False self.accounts[index].is_default = True self.default_account_address = b58_address
[ "def", "set_default_account_by_address", "(", "self", ",", "b58_address", ":", "str", ")", ":", "flag", "=", "True", "index", "=", "-", "1", "for", "acct", "in", "self", ".", "accounts", ":", "index", "+=", "1", "if", "acct", ".", "b58_address", "==", "b58_address", ":", "flag", "=", "False", "break", "if", "flag", ":", "raise", "SDKException", "(", "ErrorCode", ".", "get_account_by_address_err", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "accounts", ")", ")", ":", "self", ".", "accounts", "[", "i", "]", ".", "is_default", "=", "False", "self", ".", "accounts", "[", "index", "]", ".", "is_default", "=", "True", "self", ".", "default_account_address", "=", "b58_address" ]
This interface is used to set default account by given base58 encode address. :param b58_address: a base58 encode address.
[ "This", "interface", "is", "used", "to", "set", "default", "account", "by", "given", "base58", "encode", "address", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet.py#L133-L151
2,907
ontio/ontology-python-sdk
ontology/wallet/wallet.py
WalletData.set_default_identity_by_index
def set_default_identity_by_index(self, index: int): """ This interface is used to set default account by given an index value. :param index: an int value that indicate the position of an account object in account list. """ identities_len = len(self.identities) if index >= identities_len: raise SDKException(ErrorCode.param_error) for i in range(identities_len): self.identities[i].is_default = False if i == index: self.identities[index].is_default = True
python
def set_default_identity_by_index(self, index: int): identities_len = len(self.identities) if index >= identities_len: raise SDKException(ErrorCode.param_error) for i in range(identities_len): self.identities[i].is_default = False if i == index: self.identities[index].is_default = True
[ "def", "set_default_identity_by_index", "(", "self", ",", "index", ":", "int", ")", ":", "identities_len", "=", "len", "(", "self", ".", "identities", ")", "if", "index", ">=", "identities_len", ":", "raise", "SDKException", "(", "ErrorCode", ".", "param_error", ")", "for", "i", "in", "range", "(", "identities_len", ")", ":", "self", ".", "identities", "[", "i", "]", ".", "is_default", "=", "False", "if", "i", "==", "index", ":", "self", ".", "identities", "[", "index", "]", ".", "is_default", "=", "True" ]
This interface is used to set default account by given an index value. :param index: an int value that indicate the position of an account object in account list.
[ "This", "interface", "is", "used", "to", "set", "default", "account", "by", "given", "an", "index", "value", "." ]
ac88bdda941896c5d2ced08422a9c5179d3f9b19
https://github.com/ontio/ontology-python-sdk/blob/ac88bdda941896c5d2ced08422a9c5179d3f9b19/ontology/wallet/wallet.py#L230-L242
2,908
openvax/gtfparse
gtfparse/read_gtf.py
read_gtf
def read_gtf( filepath_or_buffer, expand_attribute_column=True, infer_biotype_column=False, column_converters={}, usecols=None, features=None, chunksize=1024 * 1024): """ Parse a GTF into a dictionary mapping column names to sequences of values. Parameters ---------- filepath_or_buffer : str or buffer object Path to GTF file (may be gzip compressed) or buffer object such as StringIO expand_attribute_column : bool Replace strings of semi-colon separated key-value values in the 'attribute' column with one column per distinct key, with a list of values for each row (using None for rows where key didn't occur). infer_biotype_column : bool Due to the annoying ambiguity of the second GTF column across multiple Ensembl releases, figure out if an older GTF's source column is actually the gene_biotype or transcript_biotype. column_converters : dict, optional Dictionary mapping column names to conversion functions. Will replace empty strings with None and otherwise passes them to given conversion function. usecols : list of str or None Restrict which columns are loaded to the give set. If None, then load all columns. features : set of str or None Drop rows which aren't one of the features in the supplied set chunksize : int """ if isinstance(filepath_or_buffer, string_types) and not exists(filepath_or_buffer): raise ValueError("GTF file does not exist: %s" % filepath_or_buffer) if expand_attribute_column: result_df = parse_gtf_and_expand_attributes( filepath_or_buffer, chunksize=chunksize, restrict_attribute_columns=usecols) else: result_df = parse_gtf(result_df, features=features) for column_name, column_type in list(column_converters.items()): result_df[column_name] = [ column_type(string_value) if len(string_value) > 0 else None for string_value in result_df[column_name] ] # Hackishly infer whether the values in the 'source' column of this GTF # are actually representing a biotype by checking for the most common # gene_biotype and transcript_biotype value 'protein_coding' if infer_biotype_column: unique_source_values = set(result_df["source"]) if "protein_coding" in unique_source_values: column_names = set(result_df.columns) # Disambiguate between the two biotypes by checking if # gene_biotype is already present in another column. If it is, # the 2nd column is the transcript_biotype (otherwise, it's the # gene_biotype) if "gene_biotype" not in column_names: logging.info("Using column 'source' to replace missing 'gene_biotype'") result_df["gene_biotype"] = result_df["source"] if "transcript_biotype" not in column_names: logging.info("Using column 'source' to replace missing 'transcript_biotype'") result_df["transcript_biotype"] = result_df["source"] if usecols is not None: column_names = set(result_df.columns) valid_columns = [c for c in usecols if c in column_names] result_df = result_df[valid_columns] return result_df
python
def read_gtf( filepath_or_buffer, expand_attribute_column=True, infer_biotype_column=False, column_converters={}, usecols=None, features=None, chunksize=1024 * 1024): if isinstance(filepath_or_buffer, string_types) and not exists(filepath_or_buffer): raise ValueError("GTF file does not exist: %s" % filepath_or_buffer) if expand_attribute_column: result_df = parse_gtf_and_expand_attributes( filepath_or_buffer, chunksize=chunksize, restrict_attribute_columns=usecols) else: result_df = parse_gtf(result_df, features=features) for column_name, column_type in list(column_converters.items()): result_df[column_name] = [ column_type(string_value) if len(string_value) > 0 else None for string_value in result_df[column_name] ] # Hackishly infer whether the values in the 'source' column of this GTF # are actually representing a biotype by checking for the most common # gene_biotype and transcript_biotype value 'protein_coding' if infer_biotype_column: unique_source_values = set(result_df["source"]) if "protein_coding" in unique_source_values: column_names = set(result_df.columns) # Disambiguate between the two biotypes by checking if # gene_biotype is already present in another column. If it is, # the 2nd column is the transcript_biotype (otherwise, it's the # gene_biotype) if "gene_biotype" not in column_names: logging.info("Using column 'source' to replace missing 'gene_biotype'") result_df["gene_biotype"] = result_df["source"] if "transcript_biotype" not in column_names: logging.info("Using column 'source' to replace missing 'transcript_biotype'") result_df["transcript_biotype"] = result_df["source"] if usecols is not None: column_names = set(result_df.columns) valid_columns = [c for c in usecols if c in column_names] result_df = result_df[valid_columns] return result_df
[ "def", "read_gtf", "(", "filepath_or_buffer", ",", "expand_attribute_column", "=", "True", ",", "infer_biotype_column", "=", "False", ",", "column_converters", "=", "{", "}", ",", "usecols", "=", "None", ",", "features", "=", "None", ",", "chunksize", "=", "1024", "*", "1024", ")", ":", "if", "isinstance", "(", "filepath_or_buffer", ",", "string_types", ")", "and", "not", "exists", "(", "filepath_or_buffer", ")", ":", "raise", "ValueError", "(", "\"GTF file does not exist: %s\"", "%", "filepath_or_buffer", ")", "if", "expand_attribute_column", ":", "result_df", "=", "parse_gtf_and_expand_attributes", "(", "filepath_or_buffer", ",", "chunksize", "=", "chunksize", ",", "restrict_attribute_columns", "=", "usecols", ")", "else", ":", "result_df", "=", "parse_gtf", "(", "result_df", ",", "features", "=", "features", ")", "for", "column_name", ",", "column_type", "in", "list", "(", "column_converters", ".", "items", "(", ")", ")", ":", "result_df", "[", "column_name", "]", "=", "[", "column_type", "(", "string_value", ")", "if", "len", "(", "string_value", ")", ">", "0", "else", "None", "for", "string_value", "in", "result_df", "[", "column_name", "]", "]", "# Hackishly infer whether the values in the 'source' column of this GTF", "# are actually representing a biotype by checking for the most common", "# gene_biotype and transcript_biotype value 'protein_coding'", "if", "infer_biotype_column", ":", "unique_source_values", "=", "set", "(", "result_df", "[", "\"source\"", "]", ")", "if", "\"protein_coding\"", "in", "unique_source_values", ":", "column_names", "=", "set", "(", "result_df", ".", "columns", ")", "# Disambiguate between the two biotypes by checking if", "# gene_biotype is already present in another column. If it is,", "# the 2nd column is the transcript_biotype (otherwise, it's the", "# gene_biotype)", "if", "\"gene_biotype\"", "not", "in", "column_names", ":", "logging", ".", "info", "(", "\"Using column 'source' to replace missing 'gene_biotype'\"", ")", "result_df", "[", "\"gene_biotype\"", "]", "=", "result_df", "[", "\"source\"", "]", "if", "\"transcript_biotype\"", "not", "in", "column_names", ":", "logging", ".", "info", "(", "\"Using column 'source' to replace missing 'transcript_biotype'\"", ")", "result_df", "[", "\"transcript_biotype\"", "]", "=", "result_df", "[", "\"source\"", "]", "if", "usecols", "is", "not", "None", ":", "column_names", "=", "set", "(", "result_df", ".", "columns", ")", "valid_columns", "=", "[", "c", "for", "c", "in", "usecols", "if", "c", "in", "column_names", "]", "result_df", "=", "result_df", "[", "valid_columns", "]", "return", "result_df" ]
Parse a GTF into a dictionary mapping column names to sequences of values. Parameters ---------- filepath_or_buffer : str or buffer object Path to GTF file (may be gzip compressed) or buffer object such as StringIO expand_attribute_column : bool Replace strings of semi-colon separated key-value values in the 'attribute' column with one column per distinct key, with a list of values for each row (using None for rows where key didn't occur). infer_biotype_column : bool Due to the annoying ambiguity of the second GTF column across multiple Ensembl releases, figure out if an older GTF's source column is actually the gene_biotype or transcript_biotype. column_converters : dict, optional Dictionary mapping column names to conversion functions. Will replace empty strings with None and otherwise passes them to given conversion function. usecols : list of str or None Restrict which columns are loaded to the give set. If None, then load all columns. features : set of str or None Drop rows which aren't one of the features in the supplied set chunksize : int
[ "Parse", "a", "GTF", "into", "a", "dictionary", "mapping", "column", "names", "to", "sequences", "of", "values", "." ]
c79cab0c2a5ac3d08de9f932fa29a56d334a712b
https://github.com/openvax/gtfparse/blob/c79cab0c2a5ac3d08de9f932fa29a56d334a712b/gtfparse/read_gtf.py#L165-L247
2,909
openvax/gtfparse
gtfparse/create_missing_features.py
create_missing_features
def create_missing_features( dataframe, unique_keys={}, extra_columns={}, missing_value=None): """ Helper function used to construct a missing feature such as 'transcript' or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have transcript_id and gene_id annotations which allow us to construct those missing features. Parameters ---------- dataframe : pandas.DataFrame Should contain at least the core GTF columns, such as "seqname", "start", and "end" unique_keys : dict Mapping from feature names to the name of the column which should act as a unique key for that feature. Example: {"gene": "gene_id"} extra_columns : dict By default the constructed feature row will include only the 8 core columns and its unique key. Any other columns that should be included should be associated with the feature name in this dict. missing_value : any Which value to fill in for columns that we don't infer values for. Returns original dataframe along with all extra rows created for missing features. """ extra_dataframes = [] existing_features = set(dataframe["feature"]) existing_columns = set(dataframe.keys()) for (feature_name, groupby_key) in unique_keys.items(): if feature_name in existing_features: logging.info( "Feature '%s' already exists in GTF data" % feature_name) continue logging.info("Creating rows for missing feature '%s'" % feature_name) # don't include rows where the groupby key was missing empty_key_values = dataframe[groupby_key].map( lambda x: x == "" or x is None) row_groups = dataframe[~empty_key_values].groupby(groupby_key) # Each group corresponds to a unique feature entry for which the # other columns may or may not be uniquely defined. Start off by # assuming the values for every column are missing and fill them in # where possible. feature_values = OrderedDict([ (column_name, [missing_value] * row_groups.ngroups) for column_name in dataframe.keys() ]) # User specifies which non-required columns should we try to infer # values for feature_columns = list(extra_columns.get(feature_name, [])) for i, (feature_id, group) in enumerate(row_groups): # fill in the required columns by assuming that this feature # is the union of all intervals of other features that were # tagged with its unique ID (e.g. union of exons which had a # particular gene_id). feature_values["feature"][i] = feature_name feature_values[groupby_key][i] = feature_id # set the source to 'gtfparse' to indicate that we made this # entry up from other data feature_values["source"][i] = "gtfparse" feature_values["start"][i] = group["start"].min() feature_values["end"][i] = group["end"].max() # assume that seqname and strand are the same for all other # entries in the GTF which shared this unique ID feature_values["seqname"][i] = group["seqname"].iat[0] feature_values["strand"][i] = group["strand"].iat[0] # there's probably no rigorous way to set the values of # 'score' or 'frame' columns so leave them empty for column_name in feature_columns: if column_name not in existing_columns: raise ValueError( "Column '%s' does not exist in GTF, columns = %s" % ( column_name, existing_columns)) # expect that all entries related to a reconstructed feature # are related and are thus within the same interval of # positions on the same chromosome unique_values = group[column_name].dropna().unique() if len(unique_values) == 1: feature_values[column_name][i] = unique_values[0] extra_dataframes.append(pd.DataFrame(feature_values)) return pd.concat([dataframe] + extra_dataframes, ignore_index=True)
python
def create_missing_features( dataframe, unique_keys={}, extra_columns={}, missing_value=None): extra_dataframes = [] existing_features = set(dataframe["feature"]) existing_columns = set(dataframe.keys()) for (feature_name, groupby_key) in unique_keys.items(): if feature_name in existing_features: logging.info( "Feature '%s' already exists in GTF data" % feature_name) continue logging.info("Creating rows for missing feature '%s'" % feature_name) # don't include rows where the groupby key was missing empty_key_values = dataframe[groupby_key].map( lambda x: x == "" or x is None) row_groups = dataframe[~empty_key_values].groupby(groupby_key) # Each group corresponds to a unique feature entry for which the # other columns may or may not be uniquely defined. Start off by # assuming the values for every column are missing and fill them in # where possible. feature_values = OrderedDict([ (column_name, [missing_value] * row_groups.ngroups) for column_name in dataframe.keys() ]) # User specifies which non-required columns should we try to infer # values for feature_columns = list(extra_columns.get(feature_name, [])) for i, (feature_id, group) in enumerate(row_groups): # fill in the required columns by assuming that this feature # is the union of all intervals of other features that were # tagged with its unique ID (e.g. union of exons which had a # particular gene_id). feature_values["feature"][i] = feature_name feature_values[groupby_key][i] = feature_id # set the source to 'gtfparse' to indicate that we made this # entry up from other data feature_values["source"][i] = "gtfparse" feature_values["start"][i] = group["start"].min() feature_values["end"][i] = group["end"].max() # assume that seqname and strand are the same for all other # entries in the GTF which shared this unique ID feature_values["seqname"][i] = group["seqname"].iat[0] feature_values["strand"][i] = group["strand"].iat[0] # there's probably no rigorous way to set the values of # 'score' or 'frame' columns so leave them empty for column_name in feature_columns: if column_name not in existing_columns: raise ValueError( "Column '%s' does not exist in GTF, columns = %s" % ( column_name, existing_columns)) # expect that all entries related to a reconstructed feature # are related and are thus within the same interval of # positions on the same chromosome unique_values = group[column_name].dropna().unique() if len(unique_values) == 1: feature_values[column_name][i] = unique_values[0] extra_dataframes.append(pd.DataFrame(feature_values)) return pd.concat([dataframe] + extra_dataframes, ignore_index=True)
[ "def", "create_missing_features", "(", "dataframe", ",", "unique_keys", "=", "{", "}", ",", "extra_columns", "=", "{", "}", ",", "missing_value", "=", "None", ")", ":", "extra_dataframes", "=", "[", "]", "existing_features", "=", "set", "(", "dataframe", "[", "\"feature\"", "]", ")", "existing_columns", "=", "set", "(", "dataframe", ".", "keys", "(", ")", ")", "for", "(", "feature_name", ",", "groupby_key", ")", "in", "unique_keys", ".", "items", "(", ")", ":", "if", "feature_name", "in", "existing_features", ":", "logging", ".", "info", "(", "\"Feature '%s' already exists in GTF data\"", "%", "feature_name", ")", "continue", "logging", ".", "info", "(", "\"Creating rows for missing feature '%s'\"", "%", "feature_name", ")", "# don't include rows where the groupby key was missing", "empty_key_values", "=", "dataframe", "[", "groupby_key", "]", ".", "map", "(", "lambda", "x", ":", "x", "==", "\"\"", "or", "x", "is", "None", ")", "row_groups", "=", "dataframe", "[", "~", "empty_key_values", "]", ".", "groupby", "(", "groupby_key", ")", "# Each group corresponds to a unique feature entry for which the", "# other columns may or may not be uniquely defined. Start off by", "# assuming the values for every column are missing and fill them in", "# where possible.", "feature_values", "=", "OrderedDict", "(", "[", "(", "column_name", ",", "[", "missing_value", "]", "*", "row_groups", ".", "ngroups", ")", "for", "column_name", "in", "dataframe", ".", "keys", "(", ")", "]", ")", "# User specifies which non-required columns should we try to infer", "# values for", "feature_columns", "=", "list", "(", "extra_columns", ".", "get", "(", "feature_name", ",", "[", "]", ")", ")", "for", "i", ",", "(", "feature_id", ",", "group", ")", "in", "enumerate", "(", "row_groups", ")", ":", "# fill in the required columns by assuming that this feature", "# is the union of all intervals of other features that were", "# tagged with its unique ID (e.g. union of exons which had a", "# particular gene_id).", "feature_values", "[", "\"feature\"", "]", "[", "i", "]", "=", "feature_name", "feature_values", "[", "groupby_key", "]", "[", "i", "]", "=", "feature_id", "# set the source to 'gtfparse' to indicate that we made this", "# entry up from other data", "feature_values", "[", "\"source\"", "]", "[", "i", "]", "=", "\"gtfparse\"", "feature_values", "[", "\"start\"", "]", "[", "i", "]", "=", "group", "[", "\"start\"", "]", ".", "min", "(", ")", "feature_values", "[", "\"end\"", "]", "[", "i", "]", "=", "group", "[", "\"end\"", "]", ".", "max", "(", ")", "# assume that seqname and strand are the same for all other", "# entries in the GTF which shared this unique ID", "feature_values", "[", "\"seqname\"", "]", "[", "i", "]", "=", "group", "[", "\"seqname\"", "]", ".", "iat", "[", "0", "]", "feature_values", "[", "\"strand\"", "]", "[", "i", "]", "=", "group", "[", "\"strand\"", "]", ".", "iat", "[", "0", "]", "# there's probably no rigorous way to set the values of", "# 'score' or 'frame' columns so leave them empty", "for", "column_name", "in", "feature_columns", ":", "if", "column_name", "not", "in", "existing_columns", ":", "raise", "ValueError", "(", "\"Column '%s' does not exist in GTF, columns = %s\"", "%", "(", "column_name", ",", "existing_columns", ")", ")", "# expect that all entries related to a reconstructed feature", "# are related and are thus within the same interval of", "# positions on the same chromosome", "unique_values", "=", "group", "[", "column_name", "]", ".", "dropna", "(", ")", ".", "unique", "(", ")", "if", "len", "(", "unique_values", ")", "==", "1", ":", "feature_values", "[", "column_name", "]", "[", "i", "]", "=", "unique_values", "[", "0", "]", "extra_dataframes", ".", "append", "(", "pd", ".", "DataFrame", "(", "feature_values", ")", ")", "return", "pd", ".", "concat", "(", "[", "dataframe", "]", "+", "extra_dataframes", ",", "ignore_index", "=", "True", ")" ]
Helper function used to construct a missing feature such as 'transcript' or 'gene'. Some GTF files only have 'exon' and 'CDS' entries, but have transcript_id and gene_id annotations which allow us to construct those missing features. Parameters ---------- dataframe : pandas.DataFrame Should contain at least the core GTF columns, such as "seqname", "start", and "end" unique_keys : dict Mapping from feature names to the name of the column which should act as a unique key for that feature. Example: {"gene": "gene_id"} extra_columns : dict By default the constructed feature row will include only the 8 core columns and its unique key. Any other columns that should be included should be associated with the feature name in this dict. missing_value : any Which value to fill in for columns that we don't infer values for. Returns original dataframe along with all extra rows created for missing features.
[ "Helper", "function", "used", "to", "construct", "a", "missing", "feature", "such", "as", "transcript", "or", "gene", ".", "Some", "GTF", "files", "only", "have", "exon", "and", "CDS", "entries", "but", "have", "transcript_id", "and", "gene_id", "annotations", "which", "allow", "us", "to", "construct", "those", "missing", "features", "." ]
c79cab0c2a5ac3d08de9f932fa29a56d334a712b
https://github.com/openvax/gtfparse/blob/c79cab0c2a5ac3d08de9f932fa29a56d334a712b/gtfparse/create_missing_features.py#L25-L121
2,910
MichaelAquilina/S4
s4/clients/__init__.py
SyncClient.get_action
def get_action(self, key): """ returns the action to perform on this key based on its state before the last sync. """ index_local_timestamp = self.get_index_local_timestamp(key) real_local_timestamp = self.get_real_local_timestamp(key) remote_timestamp = self.get_remote_timestamp(key) return get_sync_state( index_local_timestamp, real_local_timestamp, remote_timestamp )
python
def get_action(self, key): index_local_timestamp = self.get_index_local_timestamp(key) real_local_timestamp = self.get_real_local_timestamp(key) remote_timestamp = self.get_remote_timestamp(key) return get_sync_state( index_local_timestamp, real_local_timestamp, remote_timestamp )
[ "def", "get_action", "(", "self", ",", "key", ")", ":", "index_local_timestamp", "=", "self", ".", "get_index_local_timestamp", "(", "key", ")", "real_local_timestamp", "=", "self", ".", "get_real_local_timestamp", "(", "key", ")", "remote_timestamp", "=", "self", ".", "get_remote_timestamp", "(", "key", ")", "return", "get_sync_state", "(", "index_local_timestamp", ",", "real_local_timestamp", ",", "remote_timestamp", ")" ]
returns the action to perform on this key based on its state before the last sync.
[ "returns", "the", "action", "to", "perform", "on", "this", "key", "based", "on", "its", "state", "before", "the", "last", "sync", "." ]
05d74697e6ec683f0329c983f7c3f05ab75fd57e
https://github.com/MichaelAquilina/S4/blob/05d74697e6ec683f0329c983f7c3f05ab75fd57e/s4/clients/__init__.py#L191-L201
2,911
MichaelAquilina/S4
s4/clients/local.py
LocalSyncClient.lock
def lock(self, timeout=10): """ Advisory lock. Use to ensure that only one LocalSyncClient is working on the Target at the same time. """ logger.debug("Locking %s", self.lock_file) if not os.path.exists(self.lock_file): self.ensure_path(self.lock_file) with open(self.lock_file, "w"): os.utime(self.lock_file) self._lock.acquire(timeout=timeout)
python
def lock(self, timeout=10): logger.debug("Locking %s", self.lock_file) if not os.path.exists(self.lock_file): self.ensure_path(self.lock_file) with open(self.lock_file, "w"): os.utime(self.lock_file) self._lock.acquire(timeout=timeout)
[ "def", "lock", "(", "self", ",", "timeout", "=", "10", ")", ":", "logger", ".", "debug", "(", "\"Locking %s\"", ",", "self", ".", "lock_file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "lock_file", ")", ":", "self", ".", "ensure_path", "(", "self", ".", "lock_file", ")", "with", "open", "(", "self", ".", "lock_file", ",", "\"w\"", ")", ":", "os", ".", "utime", "(", "self", ".", "lock_file", ")", "self", ".", "_lock", ".", "acquire", "(", "timeout", "=", "timeout", ")" ]
Advisory lock. Use to ensure that only one LocalSyncClient is working on the Target at the same time.
[ "Advisory", "lock", ".", "Use", "to", "ensure", "that", "only", "one", "LocalSyncClient", "is", "working", "on", "the", "Target", "at", "the", "same", "time", "." ]
05d74697e6ec683f0329c983f7c3f05ab75fd57e
https://github.com/MichaelAquilina/S4/blob/05d74697e6ec683f0329c983f7c3f05ab75fd57e/s4/clients/local.py#L65-L75
2,912
MichaelAquilina/S4
s4/clients/local.py
LocalSyncClient.unlock
def unlock(self): """ Unlock the active advisory lock. """ logger.debug("Releasing lock %s", self.lock_file) self._lock.release() try: os.unlink(self.lock_file) except FileNotFoundError: pass
python
def unlock(self): logger.debug("Releasing lock %s", self.lock_file) self._lock.release() try: os.unlink(self.lock_file) except FileNotFoundError: pass
[ "def", "unlock", "(", "self", ")", ":", "logger", ".", "debug", "(", "\"Releasing lock %s\"", ",", "self", ".", "lock_file", ")", "self", ".", "_lock", ".", "release", "(", ")", "try", ":", "os", ".", "unlink", "(", "self", ".", "lock_file", ")", "except", "FileNotFoundError", ":", "pass" ]
Unlock the active advisory lock.
[ "Unlock", "the", "active", "advisory", "lock", "." ]
05d74697e6ec683f0329c983f7c3f05ab75fd57e
https://github.com/MichaelAquilina/S4/blob/05d74697e6ec683f0329c983f7c3f05ab75fd57e/s4/clients/local.py#L77-L86
2,913
gazpachoking/jsonref
proxytypes.py
ProxyMetaClass._no_proxy
def _no_proxy(method): """ Returns a wrapped version of `method`, such that proxying is turned off during the method call. """ @wraps(method) def wrapper(self, *args, **kwargs): notproxied = _oga(self, "__notproxied__") _osa(self, "__notproxied__", True) try: return method(self, *args, **kwargs) finally: _osa(self, "__notproxied__", notproxied) return wrapper
python
def _no_proxy(method): @wraps(method) def wrapper(self, *args, **kwargs): notproxied = _oga(self, "__notproxied__") _osa(self, "__notproxied__", True) try: return method(self, *args, **kwargs) finally: _osa(self, "__notproxied__", notproxied) return wrapper
[ "def", "_no_proxy", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "notproxied", "=", "_oga", "(", "self", ",", "\"__notproxied__\"", ")", "_osa", "(", "self", ",", "\"__notproxied__\"", ",", "True", ")", "try", ":", "return", "method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "finally", ":", "_osa", "(", "self", ",", "\"__notproxied__\"", ",", "notproxied", ")", "return", "wrapper" ]
Returns a wrapped version of `method`, such that proxying is turned off during the method call.
[ "Returns", "a", "wrapped", "version", "of", "method", "such", "that", "proxying", "is", "turned", "off", "during", "the", "method", "call", "." ]
066132e527f8115f75bcadfd0eca12f8973a6309
https://github.com/gazpachoking/jsonref/blob/066132e527f8115f75bcadfd0eca12f8973a6309/proxytypes.py#L122-L138
2,914
gazpachoking/jsonref
proxytypes.py
Proxy._should_proxy
def _should_proxy(self, attr): """ Determines whether `attr` should be looked up on the proxied object, or the proxy itself. """ if attr in type(self).__notproxied__: return False if _oga(self, "__notproxied__") is True: return False return True
python
def _should_proxy(self, attr): if attr in type(self).__notproxied__: return False if _oga(self, "__notproxied__") is True: return False return True
[ "def", "_should_proxy", "(", "self", ",", "attr", ")", ":", "if", "attr", "in", "type", "(", "self", ")", ".", "__notproxied__", ":", "return", "False", "if", "_oga", "(", "self", ",", "\"__notproxied__\"", ")", "is", "True", ":", "return", "False", "return", "True" ]
Determines whether `attr` should be looked up on the proxied object, or the proxy itself.
[ "Determines", "whether", "attr", "should", "be", "looked", "up", "on", "the", "proxied", "object", "or", "the", "proxy", "itself", "." ]
066132e527f8115f75bcadfd0eca12f8973a6309
https://github.com/gazpachoking/jsonref/blob/066132e527f8115f75bcadfd0eca12f8973a6309/proxytypes.py#L161-L171
2,915
gazpachoking/jsonref
proxytypes.py
Proxy.add_proxy_meth
def add_proxy_meth(cls, name, func, arg_pos=0): """ Add a method `name` to the class, which returns the value of `func`, called with the proxied value inserted at `arg_pos` """ @wraps(func) def proxied(self, *args, **kwargs): args = list(args) args.insert(arg_pos, self.__subject__) result = func(*args, **kwargs) return result setattr(cls, name, proxied)
python
def add_proxy_meth(cls, name, func, arg_pos=0): @wraps(func) def proxied(self, *args, **kwargs): args = list(args) args.insert(arg_pos, self.__subject__) result = func(*args, **kwargs) return result setattr(cls, name, proxied)
[ "def", "add_proxy_meth", "(", "cls", ",", "name", ",", "func", ",", "arg_pos", "=", "0", ")", ":", "@", "wraps", "(", "func", ")", "def", "proxied", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "args", ".", "insert", "(", "arg_pos", ",", "self", ".", "__subject__", ")", "result", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "result", "setattr", "(", "cls", ",", "name", ",", "proxied", ")" ]
Add a method `name` to the class, which returns the value of `func`, called with the proxied value inserted at `arg_pos`
[ "Add", "a", "method", "name", "to", "the", "class", "which", "returns", "the", "value", "of", "func", "called", "with", "the", "proxied", "value", "inserted", "at", "arg_pos" ]
066132e527f8115f75bcadfd0eca12f8973a6309
https://github.com/gazpachoking/jsonref/blob/066132e527f8115f75bcadfd0eca12f8973a6309/proxytypes.py#L192-L206
2,916
gazpachoking/jsonref
jsonref.py
load_uri
def load_uri(uri, base_uri=None, loader=None, jsonschema=False, load_on_repr=True): """ Load JSON data from ``uri`` with JSON references proxied to their referent data. :param uri: URI to fetch the JSON from :param kwargs: This function takes any of the keyword arguments from :meth:`JsonRef.replace_refs` """ if loader is None: loader = jsonloader if base_uri is None: base_uri = uri return JsonRef.replace_refs( loader(uri), base_uri=base_uri, loader=loader, jsonschema=jsonschema, load_on_repr=load_on_repr, )
python
def load_uri(uri, base_uri=None, loader=None, jsonschema=False, load_on_repr=True): if loader is None: loader = jsonloader if base_uri is None: base_uri = uri return JsonRef.replace_refs( loader(uri), base_uri=base_uri, loader=loader, jsonschema=jsonschema, load_on_repr=load_on_repr, )
[ "def", "load_uri", "(", "uri", ",", "base_uri", "=", "None", ",", "loader", "=", "None", ",", "jsonschema", "=", "False", ",", "load_on_repr", "=", "True", ")", ":", "if", "loader", "is", "None", ":", "loader", "=", "jsonloader", "if", "base_uri", "is", "None", ":", "base_uri", "=", "uri", "return", "JsonRef", ".", "replace_refs", "(", "loader", "(", "uri", ")", ",", "base_uri", "=", "base_uri", ",", "loader", "=", "loader", ",", "jsonschema", "=", "jsonschema", ",", "load_on_repr", "=", "load_on_repr", ",", ")" ]
Load JSON data from ``uri`` with JSON references proxied to their referent data. :param uri: URI to fetch the JSON from :param kwargs: This function takes any of the keyword arguments from :meth:`JsonRef.replace_refs`
[ "Load", "JSON", "data", "from", "uri", "with", "JSON", "references", "proxied", "to", "their", "referent", "data", "." ]
066132e527f8115f75bcadfd0eca12f8973a6309
https://github.com/gazpachoking/jsonref/blob/066132e527f8115f75bcadfd0eca12f8973a6309/jsonref.py#L372-L394
2,917
gazpachoking/jsonref
jsonref.py
JsonRef.resolve_pointer
def resolve_pointer(self, document, pointer): """ Resolve a json pointer ``pointer`` within the referenced ``document``. :argument document: the referent document :argument str pointer: a json pointer URI fragment to resolve within it """ # Do only split at single forward slashes which are not prefixed by a caret parts = re.split(r"(?<!\^)/", unquote(pointer.lstrip("/"))) if pointer else [] for part in parts: # Restore escaped slashes and carets replacements = {r"^/": r"/", r"^^": r"^"} part = re.sub( "|".join(re.escape(key) for key in replacements.keys()), lambda k: replacements[k.group(0)], part, ) if isinstance(document, Sequence): # Try to turn an array index to an int try: part = int(part) except ValueError: pass try: document = document[part] except (TypeError, LookupError) as e: self._error("Unresolvable JSON pointer: %r" % pointer, cause=e) return document
python
def resolve_pointer(self, document, pointer): # Do only split at single forward slashes which are not prefixed by a caret parts = re.split(r"(?<!\^)/", unquote(pointer.lstrip("/"))) if pointer else [] for part in parts: # Restore escaped slashes and carets replacements = {r"^/": r"/", r"^^": r"^"} part = re.sub( "|".join(re.escape(key) for key in replacements.keys()), lambda k: replacements[k.group(0)], part, ) if isinstance(document, Sequence): # Try to turn an array index to an int try: part = int(part) except ValueError: pass try: document = document[part] except (TypeError, LookupError) as e: self._error("Unresolvable JSON pointer: %r" % pointer, cause=e) return document
[ "def", "resolve_pointer", "(", "self", ",", "document", ",", "pointer", ")", ":", "# Do only split at single forward slashes which are not prefixed by a caret", "parts", "=", "re", ".", "split", "(", "r\"(?<!\\^)/\"", ",", "unquote", "(", "pointer", ".", "lstrip", "(", "\"/\"", ")", ")", ")", "if", "pointer", "else", "[", "]", "for", "part", "in", "parts", ":", "# Restore escaped slashes and carets", "replacements", "=", "{", "r\"^/\"", ":", "r\"/\"", ",", "r\"^^\"", ":", "r\"^\"", "}", "part", "=", "re", ".", "sub", "(", "\"|\"", ".", "join", "(", "re", ".", "escape", "(", "key", ")", "for", "key", "in", "replacements", ".", "keys", "(", ")", ")", ",", "lambda", "k", ":", "replacements", "[", "k", ".", "group", "(", "0", ")", "]", ",", "part", ",", ")", "if", "isinstance", "(", "document", ",", "Sequence", ")", ":", "# Try to turn an array index to an int", "try", ":", "part", "=", "int", "(", "part", ")", "except", "ValueError", ":", "pass", "try", ":", "document", "=", "document", "[", "part", "]", "except", "(", "TypeError", ",", "LookupError", ")", "as", "e", ":", "self", ".", "_error", "(", "\"Unresolvable JSON pointer: %r\"", "%", "pointer", ",", "cause", "=", "e", ")", "return", "document" ]
Resolve a json pointer ``pointer`` within the referenced ``document``. :argument document: the referent document :argument str pointer: a json pointer URI fragment to resolve within it
[ "Resolve", "a", "json", "pointer", "pointer", "within", "the", "referenced", "document", "." ]
066132e527f8115f75bcadfd0eca12f8973a6309
https://github.com/gazpachoking/jsonref/blob/066132e527f8115f75bcadfd0eca12f8973a6309/jsonref.py#L191-L220
2,918
Iotic-Labs/py-ubjson
ubjson/encoder.py
dump
def dump(obj, fp, container_count=False, sort_keys=False, no_float32=True, default=None): """Writes the given object as UBJSON to the provided file-like object Args: obj: The object to encode fp: write([size])-able object container_count (bool): Specify length for container types (including for empty ones). This can aid decoding speed depending on implementation but requires a bit more space and encoding speed could be reduced if getting length of any of the containers is expensive. sort_keys (bool): Sort keys of mappings no_float32 (bool): Never use float32 to store float numbers (other than for zero). Disabling this might save space at the loss of precision. default (callable): Called for objects which cannot be serialised. Should return a UBJSON-encodable version of the object or raise an EncoderException. Raises: EncoderException: If an encoding failure occured. The following Python types and interfaces (ABCs) are supported (as are any subclasses): +------------------------------+-----------------------------------+ | Python | UBJSON | +==============================+===================================+ | (3) str | string | | (2) unicode | | +------------------------------+-----------------------------------+ | None | null | +------------------------------+-----------------------------------+ | bool | true, false | +------------------------------+-----------------------------------+ | (3) int | uint8, int8, int16, int32, int64, | | (2) int, long | high_precision | +------------------------------+-----------------------------------+ | float | float32, float64, high_precision | +------------------------------+-----------------------------------+ | Decimal | high_precision | +------------------------------+-----------------------------------+ | (3) bytes, bytearray | array (type, uint8) | | (2) str | array (type, uint8) | +------------------------------+-----------------------------------+ | (3) collections.abc.Mapping | object | | (2) collections.Mapping | | +------------------------------+-----------------------------------+ | (3) collections.abc.Sequence | array | | (2) collections.Sequence | | +------------------------------+-----------------------------------+ Notes: - Items are resolved in the order of this table, e.g. if the item implements both Mapping and Sequence interfaces, it will be encoded as a mapping. - None and bool do not use an isinstance check - Numbers in brackets denote Python version. - Only unicode strings in Python 2 are encoded as strings, i.e. for compatibility with e.g. Python 3 one MUST NOT use str in Python 2 (as that will be interpreted as a byte array). - Mapping keys have to be strings: str for Python3 and unicode or str in Python 2. - float conversion rules (depending on no_float32 setting): float32: 1.18e-38 <= abs(value) <= 3.4e38 or value == 0 float64: 2.23e-308 <= abs(value) < 1.8e308 For other values Decimal is used. """ if not callable(fp.write): raise TypeError('fp.write not callable') fp_write = fp.write __encode_value(fp_write, obj, {}, container_count, sort_keys, no_float32, default)
python
def dump(obj, fp, container_count=False, sort_keys=False, no_float32=True, default=None): if not callable(fp.write): raise TypeError('fp.write not callable') fp_write = fp.write __encode_value(fp_write, obj, {}, container_count, sort_keys, no_float32, default)
[ "def", "dump", "(", "obj", ",", "fp", ",", "container_count", "=", "False", ",", "sort_keys", "=", "False", ",", "no_float32", "=", "True", ",", "default", "=", "None", ")", ":", "if", "not", "callable", "(", "fp", ".", "write", ")", ":", "raise", "TypeError", "(", "'fp.write not callable'", ")", "fp_write", "=", "fp", ".", "write", "__encode_value", "(", "fp_write", ",", "obj", ",", "{", "}", ",", "container_count", ",", "sort_keys", ",", "no_float32", ",", "default", ")" ]
Writes the given object as UBJSON to the provided file-like object Args: obj: The object to encode fp: write([size])-able object container_count (bool): Specify length for container types (including for empty ones). This can aid decoding speed depending on implementation but requires a bit more space and encoding speed could be reduced if getting length of any of the containers is expensive. sort_keys (bool): Sort keys of mappings no_float32 (bool): Never use float32 to store float numbers (other than for zero). Disabling this might save space at the loss of precision. default (callable): Called for objects which cannot be serialised. Should return a UBJSON-encodable version of the object or raise an EncoderException. Raises: EncoderException: If an encoding failure occured. The following Python types and interfaces (ABCs) are supported (as are any subclasses): +------------------------------+-----------------------------------+ | Python | UBJSON | +==============================+===================================+ | (3) str | string | | (2) unicode | | +------------------------------+-----------------------------------+ | None | null | +------------------------------+-----------------------------------+ | bool | true, false | +------------------------------+-----------------------------------+ | (3) int | uint8, int8, int16, int32, int64, | | (2) int, long | high_precision | +------------------------------+-----------------------------------+ | float | float32, float64, high_precision | +------------------------------+-----------------------------------+ | Decimal | high_precision | +------------------------------+-----------------------------------+ | (3) bytes, bytearray | array (type, uint8) | | (2) str | array (type, uint8) | +------------------------------+-----------------------------------+ | (3) collections.abc.Mapping | object | | (2) collections.Mapping | | +------------------------------+-----------------------------------+ | (3) collections.abc.Sequence | array | | (2) collections.Sequence | | +------------------------------+-----------------------------------+ Notes: - Items are resolved in the order of this table, e.g. if the item implements both Mapping and Sequence interfaces, it will be encoded as a mapping. - None and bool do not use an isinstance check - Numbers in brackets denote Python version. - Only unicode strings in Python 2 are encoded as strings, i.e. for compatibility with e.g. Python 3 one MUST NOT use str in Python 2 (as that will be interpreted as a byte array). - Mapping keys have to be strings: str for Python3 and unicode or str in Python 2. - float conversion rules (depending on no_float32 setting): float32: 1.18e-38 <= abs(value) <= 3.4e38 or value == 0 float64: 2.23e-308 <= abs(value) < 1.8e308 For other values Decimal is used.
[ "Writes", "the", "given", "object", "as", "UBJSON", "to", "the", "provided", "file", "-", "like", "object" ]
80dcacbc7bba1759c69759fb3109ac1c6574da68
https://github.com/Iotic-Labs/py-ubjson/blob/80dcacbc7bba1759c69759fb3109ac1c6574da68/ubjson/encoder.py#L233-L305
2,919
Iotic-Labs/py-ubjson
ez_setup.py
_resolve_version
def _resolve_version(version): """ Resolve LATEST version """ if version is not LATEST: return version resp = urlopen('https://pypi.python.org/pypi/setuptools/json') with contextlib.closing(resp): try: charset = resp.info().get_content_charset() except Exception: # Python 2 compat; assume UTF-8 charset = 'UTF-8' reader = codecs.getreader(charset) doc = json.load(reader(resp)) return str(doc['info']['version'])
python
def _resolve_version(version): if version is not LATEST: return version resp = urlopen('https://pypi.python.org/pypi/setuptools/json') with contextlib.closing(resp): try: charset = resp.info().get_content_charset() except Exception: # Python 2 compat; assume UTF-8 charset = 'UTF-8' reader = codecs.getreader(charset) doc = json.load(reader(resp)) return str(doc['info']['version'])
[ "def", "_resolve_version", "(", "version", ")", ":", "if", "version", "is", "not", "LATEST", ":", "return", "version", "resp", "=", "urlopen", "(", "'https://pypi.python.org/pypi/setuptools/json'", ")", "with", "contextlib", ".", "closing", "(", "resp", ")", ":", "try", ":", "charset", "=", "resp", ".", "info", "(", ")", ".", "get_content_charset", "(", ")", "except", "Exception", ":", "# Python 2 compat; assume UTF-8", "charset", "=", "'UTF-8'", "reader", "=", "codecs", ".", "getreader", "(", "charset", ")", "doc", "=", "json", ".", "load", "(", "reader", "(", "resp", ")", ")", "return", "str", "(", "doc", "[", "'info'", "]", "[", "'version'", "]", ")" ]
Resolve LATEST version
[ "Resolve", "LATEST", "version" ]
80dcacbc7bba1759c69759fb3109ac1c6574da68
https://github.com/Iotic-Labs/py-ubjson/blob/80dcacbc7bba1759c69759fb3109ac1c6574da68/ez_setup.py#L340-L357
2,920
Iotic-Labs/py-ubjson
ubjson/decoder.py
load
def load(fp, no_bytes=False, object_hook=None, object_pairs_hook=None, intern_object_keys=False): """Decodes and returns UBJSON from the given file-like object Args: fp: read([size])-able object no_bytes (bool): If set, typed UBJSON arrays (uint8) will not be converted to a bytes instance and instead treated like any other array (i.e. result in a list). object_hook (callable): Called with the result of any object literal decoded (instead of dict). object_pairs_hook (callable): Called with the result of any object literal decoded with an ordered list of pairs (instead of dict). Takes precedence over object_hook. intern_object_keys (bool): If set, object keys are interned which can provide a memory saving when many repeated keys are used. NOTE: This is not supported in Python2 (since interning does not apply to unicode) and wil be ignored. Returns: Decoded object Raises: DecoderException: If an encoding failure occured. UBJSON types are mapped to Python types as follows. Numbers in brackets denote Python version. +----------------------------------+---------------+ | UBJSON | Python | +==================================+===============+ | object | dict | +----------------------------------+---------------+ | array | list | +----------------------------------+---------------+ | string | (3) str | | | (2) unicode | +----------------------------------+---------------+ | uint8, int8, int16, int32, int64 | (3) int | | | (2) int, long | +----------------------------------+---------------+ | float32, float64 | float | +----------------------------------+---------------+ | high_precision | Decimal | +----------------------------------+---------------+ | array (typed, uint8) | (3) bytes | | | (2) str | +----------------------------------+---------------+ | true | True | +----------------------------------+---------------+ | false | False | +----------------------------------+---------------+ | null | None | +----------------------------------+---------------+ """ if object_pairs_hook is None and object_hook is None: object_hook = __object_hook_noop if not callable(fp.read): raise TypeError('fp.read not callable') fp_read = fp.read marker = fp_read(1) try: try: return __METHOD_MAP[marker](fp_read, marker) except KeyError: pass if marker == ARRAY_START: return __decode_array(fp_read, bool(no_bytes), object_hook, object_pairs_hook, intern_object_keys) elif marker == OBJECT_START: return __decode_object(fp_read, bool(no_bytes), object_hook, object_pairs_hook, intern_object_keys) else: raise DecoderException('Invalid marker') except DecoderException as ex: raise_from(DecoderException(ex.args[0], fp), ex)
python
def load(fp, no_bytes=False, object_hook=None, object_pairs_hook=None, intern_object_keys=False): if object_pairs_hook is None and object_hook is None: object_hook = __object_hook_noop if not callable(fp.read): raise TypeError('fp.read not callable') fp_read = fp.read marker = fp_read(1) try: try: return __METHOD_MAP[marker](fp_read, marker) except KeyError: pass if marker == ARRAY_START: return __decode_array(fp_read, bool(no_bytes), object_hook, object_pairs_hook, intern_object_keys) elif marker == OBJECT_START: return __decode_object(fp_read, bool(no_bytes), object_hook, object_pairs_hook, intern_object_keys) else: raise DecoderException('Invalid marker') except DecoderException as ex: raise_from(DecoderException(ex.args[0], fp), ex)
[ "def", "load", "(", "fp", ",", "no_bytes", "=", "False", ",", "object_hook", "=", "None", ",", "object_pairs_hook", "=", "None", ",", "intern_object_keys", "=", "False", ")", ":", "if", "object_pairs_hook", "is", "None", "and", "object_hook", "is", "None", ":", "object_hook", "=", "__object_hook_noop", "if", "not", "callable", "(", "fp", ".", "read", ")", ":", "raise", "TypeError", "(", "'fp.read not callable'", ")", "fp_read", "=", "fp", ".", "read", "marker", "=", "fp_read", "(", "1", ")", "try", ":", "try", ":", "return", "__METHOD_MAP", "[", "marker", "]", "(", "fp_read", ",", "marker", ")", "except", "KeyError", ":", "pass", "if", "marker", "==", "ARRAY_START", ":", "return", "__decode_array", "(", "fp_read", ",", "bool", "(", "no_bytes", ")", ",", "object_hook", ",", "object_pairs_hook", ",", "intern_object_keys", ")", "elif", "marker", "==", "OBJECT_START", ":", "return", "__decode_object", "(", "fp_read", ",", "bool", "(", "no_bytes", ")", ",", "object_hook", ",", "object_pairs_hook", ",", "intern_object_keys", ")", "else", ":", "raise", "DecoderException", "(", "'Invalid marker'", ")", "except", "DecoderException", "as", "ex", ":", "raise_from", "(", "DecoderException", "(", "ex", ".", "args", "[", "0", "]", ",", "fp", ")", ",", "ex", ")" ]
Decodes and returns UBJSON from the given file-like object Args: fp: read([size])-able object no_bytes (bool): If set, typed UBJSON arrays (uint8) will not be converted to a bytes instance and instead treated like any other array (i.e. result in a list). object_hook (callable): Called with the result of any object literal decoded (instead of dict). object_pairs_hook (callable): Called with the result of any object literal decoded with an ordered list of pairs (instead of dict). Takes precedence over object_hook. intern_object_keys (bool): If set, object keys are interned which can provide a memory saving when many repeated keys are used. NOTE: This is not supported in Python2 (since interning does not apply to unicode) and wil be ignored. Returns: Decoded object Raises: DecoderException: If an encoding failure occured. UBJSON types are mapped to Python types as follows. Numbers in brackets denote Python version. +----------------------------------+---------------+ | UBJSON | Python | +==================================+===============+ | object | dict | +----------------------------------+---------------+ | array | list | +----------------------------------+---------------+ | string | (3) str | | | (2) unicode | +----------------------------------+---------------+ | uint8, int8, int16, int32, int64 | (3) int | | | (2) int, long | +----------------------------------+---------------+ | float32, float64 | float | +----------------------------------+---------------+ | high_precision | Decimal | +----------------------------------+---------------+ | array (typed, uint8) | (3) bytes | | | (2) str | +----------------------------------+---------------+ | true | True | +----------------------------------+---------------+ | false | False | +----------------------------------+---------------+ | null | None | +----------------------------------+---------------+
[ "Decodes", "and", "returns", "UBJSON", "from", "the", "given", "file", "-", "like", "object" ]
80dcacbc7bba1759c69759fb3109ac1c6574da68
https://github.com/Iotic-Labs/py-ubjson/blob/80dcacbc7bba1759c69759fb3109ac1c6574da68/ubjson/decoder.py#L307-L383
2,921
jborean93/requests-credssp
requests_credssp/asn_structures.py
TSRequest.check_error_code
def check_error_code(self): """ For CredSSP version of 3 or newer, the server can response with an NtStatus error code with details of what error occurred. This method will check if the error code exists and throws an NTStatusException if it is no STATUS_SUCCESS. """ # start off with STATUS_SUCCESS as a baseline status = NtStatusCodes.STATUS_SUCCESS error_code = self['errorCode'] if error_code.isValue: # ASN.1 Integer is stored as an signed integer, we need to # convert it to a unsigned integer status = ctypes.c_uint32(error_code).value if status != NtStatusCodes.STATUS_SUCCESS: raise NTStatusException(status)
python
def check_error_code(self): # start off with STATUS_SUCCESS as a baseline status = NtStatusCodes.STATUS_SUCCESS error_code = self['errorCode'] if error_code.isValue: # ASN.1 Integer is stored as an signed integer, we need to # convert it to a unsigned integer status = ctypes.c_uint32(error_code).value if status != NtStatusCodes.STATUS_SUCCESS: raise NTStatusException(status)
[ "def", "check_error_code", "(", "self", ")", ":", "# start off with STATUS_SUCCESS as a baseline", "status", "=", "NtStatusCodes", ".", "STATUS_SUCCESS", "error_code", "=", "self", "[", "'errorCode'", "]", "if", "error_code", ".", "isValue", ":", "# ASN.1 Integer is stored as an signed integer, we need to", "# convert it to a unsigned integer", "status", "=", "ctypes", ".", "c_uint32", "(", "error_code", ")", ".", "value", "if", "status", "!=", "NtStatusCodes", ".", "STATUS_SUCCESS", ":", "raise", "NTStatusException", "(", "status", ")" ]
For CredSSP version of 3 or newer, the server can response with an NtStatus error code with details of what error occurred. This method will check if the error code exists and throws an NTStatusException if it is no STATUS_SUCCESS.
[ "For", "CredSSP", "version", "of", "3", "or", "newer", "the", "server", "can", "response", "with", "an", "NtStatus", "error", "code", "with", "details", "of", "what", "error", "occurred", ".", "This", "method", "will", "check", "if", "the", "error", "code", "exists", "and", "throws", "an", "NTStatusException", "if", "it", "is", "no", "STATUS_SUCCESS", "." ]
470db8d74dff919da67cf382e9ff784d4e8dd053
https://github.com/jborean93/requests-credssp/blob/470db8d74dff919da67cf382e9ff784d4e8dd053/requests_credssp/asn_structures.py#L108-L125
2,922
jborean93/requests-credssp
requests_credssp/spnego.py
GSSAPIContext.get_mechs_available
def get_mechs_available(): """ Returns a list of auth mechanisms that are available to the local GSSAPI instance. Because we are interacting with Windows, we only care if SPNEGO, Kerberos and NTLM are available where NTLM is the only wildcard that may not be available by default. The only NTLM implementation that works properly is gss-ntlmssp and part of this test is to verify the gss-ntlmssp OID GSS_NTLMSSP_RESET_CRYPTO_OID_LENGTH is implemented which is required for SPNEGO and NTLM to work properly. :return: list - A list of supported mechs available in the installed version of GSSAPI """ ntlm_oid = GSSAPIContext._AUTH_MECHANISMS['ntlm'] ntlm_mech = gssapi.OID.from_int_seq(ntlm_oid) # GSS_NTLMSSP_RESET_CRYPTO_OID_LENGTH # github.com/simo5/gss-ntlmssp/blob/master/src/gssapi_ntlmssp.h#L68 reset_mech = gssapi.OID.from_int_seq("1.3.6.1.4.1.7165.655.1.3") try: # we don't actually care about the account used here so just use # a random username and password ntlm_context = GSSAPIContext._get_security_context( gssapi.NameType.user, ntlm_mech, "http@server", "username", "password" ) ntlm_context.step() set_sec_context_option(reset_mech, context=ntlm_context, value=b"\x00" * 4) except gssapi.exceptions.GSSError as exc: # failed to init NTLM and verify gss-ntlmssp is available, this # means NTLM is either not available or won't work # (not gss-ntlmssp) so we return kerberos as the only available # mechanism for the GSSAPI Context log.debug("Failed to init test NTLM context with GSSAPI: %s" % str(exc)) return ['kerberos'] else: return ['auto', 'kerberos', 'ntlm']
python
def get_mechs_available(): ntlm_oid = GSSAPIContext._AUTH_MECHANISMS['ntlm'] ntlm_mech = gssapi.OID.from_int_seq(ntlm_oid) # GSS_NTLMSSP_RESET_CRYPTO_OID_LENGTH # github.com/simo5/gss-ntlmssp/blob/master/src/gssapi_ntlmssp.h#L68 reset_mech = gssapi.OID.from_int_seq("1.3.6.1.4.1.7165.655.1.3") try: # we don't actually care about the account used here so just use # a random username and password ntlm_context = GSSAPIContext._get_security_context( gssapi.NameType.user, ntlm_mech, "http@server", "username", "password" ) ntlm_context.step() set_sec_context_option(reset_mech, context=ntlm_context, value=b"\x00" * 4) except gssapi.exceptions.GSSError as exc: # failed to init NTLM and verify gss-ntlmssp is available, this # means NTLM is either not available or won't work # (not gss-ntlmssp) so we return kerberos as the only available # mechanism for the GSSAPI Context log.debug("Failed to init test NTLM context with GSSAPI: %s" % str(exc)) return ['kerberos'] else: return ['auto', 'kerberos', 'ntlm']
[ "def", "get_mechs_available", "(", ")", ":", "ntlm_oid", "=", "GSSAPIContext", ".", "_AUTH_MECHANISMS", "[", "'ntlm'", "]", "ntlm_mech", "=", "gssapi", ".", "OID", ".", "from_int_seq", "(", "ntlm_oid", ")", "# GSS_NTLMSSP_RESET_CRYPTO_OID_LENGTH", "# github.com/simo5/gss-ntlmssp/blob/master/src/gssapi_ntlmssp.h#L68", "reset_mech", "=", "gssapi", ".", "OID", ".", "from_int_seq", "(", "\"1.3.6.1.4.1.7165.655.1.3\"", ")", "try", ":", "# we don't actually care about the account used here so just use", "# a random username and password", "ntlm_context", "=", "GSSAPIContext", ".", "_get_security_context", "(", "gssapi", ".", "NameType", ".", "user", ",", "ntlm_mech", ",", "\"http@server\"", ",", "\"username\"", ",", "\"password\"", ")", "ntlm_context", ".", "step", "(", ")", "set_sec_context_option", "(", "reset_mech", ",", "context", "=", "ntlm_context", ",", "value", "=", "b\"\\x00\"", "*", "4", ")", "except", "gssapi", ".", "exceptions", ".", "GSSError", "as", "exc", ":", "# failed to init NTLM and verify gss-ntlmssp is available, this", "# means NTLM is either not available or won't work", "# (not gss-ntlmssp) so we return kerberos as the only available", "# mechanism for the GSSAPI Context", "log", ".", "debug", "(", "\"Failed to init test NTLM context with GSSAPI: %s\"", "%", "str", "(", "exc", ")", ")", "return", "[", "'kerberos'", "]", "else", ":", "return", "[", "'auto'", ",", "'kerberos'", ",", "'ntlm'", "]" ]
Returns a list of auth mechanisms that are available to the local GSSAPI instance. Because we are interacting with Windows, we only care if SPNEGO, Kerberos and NTLM are available where NTLM is the only wildcard that may not be available by default. The only NTLM implementation that works properly is gss-ntlmssp and part of this test is to verify the gss-ntlmssp OID GSS_NTLMSSP_RESET_CRYPTO_OID_LENGTH is implemented which is required for SPNEGO and NTLM to work properly. :return: list - A list of supported mechs available in the installed version of GSSAPI
[ "Returns", "a", "list", "of", "auth", "mechanisms", "that", "are", "available", "to", "the", "local", "GSSAPI", "instance", ".", "Because", "we", "are", "interacting", "with", "Windows", "we", "only", "care", "if", "SPNEGO", "Kerberos", "and", "NTLM", "are", "available", "where", "NTLM", "is", "the", "only", "wildcard", "that", "may", "not", "be", "available", "by", "default", "." ]
470db8d74dff919da67cf382e9ff784d4e8dd053
https://github.com/jborean93/requests-credssp/blob/470db8d74dff919da67cf382e9ff784d4e8dd053/requests_credssp/spnego.py#L397-L440
2,923
jborean93/requests-credssp
requests_credssp/credssp.py
CredSSPContext.wrap
def wrap(self, data): """ Encrypts the data in preparation for sending to the server. The data is encrypted using the TLS channel negotiated between the client and the server. :param data: a byte string of data to encrypt :return: a byte string of the encrypted data """ length = self.tls_connection.send(data) encrypted_data = b'' counter = 0 while True: try: encrypted_chunk = \ self.tls_connection.bio_read(self.BIO_BUFFER_SIZE) except SSL.WantReadError: break encrypted_data += encrypted_chunk # in case of a borked TLS connection, break the loop if the current # buffer counter is > the length of the original message plus the # the size of the buffer (to be careful) counter += self.BIO_BUFFER_SIZE if counter > length + self.BIO_BUFFER_SIZE: break return encrypted_data
python
def wrap(self, data): length = self.tls_connection.send(data) encrypted_data = b'' counter = 0 while True: try: encrypted_chunk = \ self.tls_connection.bio_read(self.BIO_BUFFER_SIZE) except SSL.WantReadError: break encrypted_data += encrypted_chunk # in case of a borked TLS connection, break the loop if the current # buffer counter is > the length of the original message plus the # the size of the buffer (to be careful) counter += self.BIO_BUFFER_SIZE if counter > length + self.BIO_BUFFER_SIZE: break return encrypted_data
[ "def", "wrap", "(", "self", ",", "data", ")", ":", "length", "=", "self", ".", "tls_connection", ".", "send", "(", "data", ")", "encrypted_data", "=", "b''", "counter", "=", "0", "while", "True", ":", "try", ":", "encrypted_chunk", "=", "self", ".", "tls_connection", ".", "bio_read", "(", "self", ".", "BIO_BUFFER_SIZE", ")", "except", "SSL", ".", "WantReadError", ":", "break", "encrypted_data", "+=", "encrypted_chunk", "# in case of a borked TLS connection, break the loop if the current", "# buffer counter is > the length of the original message plus the", "# the size of the buffer (to be careful)", "counter", "+=", "self", ".", "BIO_BUFFER_SIZE", "if", "counter", ">", "length", "+", "self", ".", "BIO_BUFFER_SIZE", ":", "break", "return", "encrypted_data" ]
Encrypts the data in preparation for sending to the server. The data is encrypted using the TLS channel negotiated between the client and the server. :param data: a byte string of data to encrypt :return: a byte string of the encrypted data
[ "Encrypts", "the", "data", "in", "preparation", "for", "sending", "to", "the", "server", ".", "The", "data", "is", "encrypted", "using", "the", "TLS", "channel", "negotiated", "between", "the", "client", "and", "the", "server", "." ]
470db8d74dff919da67cf382e9ff784d4e8dd053
https://github.com/jborean93/requests-credssp/blob/470db8d74dff919da67cf382e9ff784d4e8dd053/requests_credssp/credssp.py#L296-L324
2,924
jborean93/requests-credssp
requests_credssp/credssp.py
CredSSPContext.unwrap
def unwrap(self, encrypted_data): """ Decrypts the data send by the server using the TLS channel negotiated between the client and the server. :param encrypted_data: the byte string of the encrypted data :return: a byte string of the decrypted data """ length = self.tls_connection.bio_write(encrypted_data) data = b'' counter = 0 while True: try: data_chunk = self.tls_connection.recv(self.BIO_BUFFER_SIZE) except SSL.WantReadError: break data += data_chunk counter += self.BIO_BUFFER_SIZE if counter > length: break return data
python
def unwrap(self, encrypted_data): length = self.tls_connection.bio_write(encrypted_data) data = b'' counter = 0 while True: try: data_chunk = self.tls_connection.recv(self.BIO_BUFFER_SIZE) except SSL.WantReadError: break data += data_chunk counter += self.BIO_BUFFER_SIZE if counter > length: break return data
[ "def", "unwrap", "(", "self", ",", "encrypted_data", ")", ":", "length", "=", "self", ".", "tls_connection", ".", "bio_write", "(", "encrypted_data", ")", "data", "=", "b''", "counter", "=", "0", "while", "True", ":", "try", ":", "data_chunk", "=", "self", ".", "tls_connection", ".", "recv", "(", "self", ".", "BIO_BUFFER_SIZE", ")", "except", "SSL", ".", "WantReadError", ":", "break", "data", "+=", "data_chunk", "counter", "+=", "self", ".", "BIO_BUFFER_SIZE", "if", "counter", ">", "length", ":", "break", "return", "data" ]
Decrypts the data send by the server using the TLS channel negotiated between the client and the server. :param encrypted_data: the byte string of the encrypted data :return: a byte string of the decrypted data
[ "Decrypts", "the", "data", "send", "by", "the", "server", "using", "the", "TLS", "channel", "negotiated", "between", "the", "client", "and", "the", "server", "." ]
470db8d74dff919da67cf382e9ff784d4e8dd053
https://github.com/jborean93/requests-credssp/blob/470db8d74dff919da67cf382e9ff784d4e8dd053/requests_credssp/credssp.py#L326-L349
2,925
jborean93/requests-credssp
requests_credssp/credssp.py
CredSSPContext._get_subject_public_key
def _get_subject_public_key(cert): """ Returns the SubjectPublicKey asn.1 field of the SubjectPublicKeyInfo field of the server's certificate. This is used in the server verification steps to thwart MitM attacks. :param cert: X509 certificate from pyOpenSSL .get_peer_certificate() :return: byte string of the asn.1 DER encoded SubjectPublicKey field """ public_key = cert.get_pubkey() cryptographic_key = public_key.to_cryptography_key() subject_public_key = cryptographic_key.public_bytes(Encoding.DER, PublicFormat.PKCS1) return subject_public_key
python
def _get_subject_public_key(cert): public_key = cert.get_pubkey() cryptographic_key = public_key.to_cryptography_key() subject_public_key = cryptographic_key.public_bytes(Encoding.DER, PublicFormat.PKCS1) return subject_public_key
[ "def", "_get_subject_public_key", "(", "cert", ")", ":", "public_key", "=", "cert", ".", "get_pubkey", "(", ")", "cryptographic_key", "=", "public_key", ".", "to_cryptography_key", "(", ")", "subject_public_key", "=", "cryptographic_key", ".", "public_bytes", "(", "Encoding", ".", "DER", ",", "PublicFormat", ".", "PKCS1", ")", "return", "subject_public_key" ]
Returns the SubjectPublicKey asn.1 field of the SubjectPublicKeyInfo field of the server's certificate. This is used in the server verification steps to thwart MitM attacks. :param cert: X509 certificate from pyOpenSSL .get_peer_certificate() :return: byte string of the asn.1 DER encoded SubjectPublicKey field
[ "Returns", "the", "SubjectPublicKey", "asn", ".", "1", "field", "of", "the", "SubjectPublicKeyInfo", "field", "of", "the", "server", "s", "certificate", ".", "This", "is", "used", "in", "the", "server", "verification", "steps", "to", "thwart", "MitM", "attacks", "." ]
470db8d74dff919da67cf382e9ff784d4e8dd053
https://github.com/jborean93/requests-credssp/blob/470db8d74dff919da67cf382e9ff784d4e8dd053/requests_credssp/credssp.py#L352-L365
2,926
msuozzo/Lector
lector/reader.py
_KindleCloudReaderBrowser._to_reader_home
def _to_reader_home(self): """Navigate to the Cloud Reader library page. Raises: BrowserError: If the KCR homepage could not be loaded. ConnectionError: If there was a connection error. """ # NOTE: Prevents QueryInterface error caused by getting a URL # while switched to an iframe self.switch_to_default_content() self.get(_KindleCloudReaderBrowser._CLOUD_READER_URL) if self.title == u'Problem loading page': raise ConnectionError # Wait for either the login page or the reader to load login_or_reader_loaded = lambda br: ( br.find_elements_by_id('amzn_kcr') or br.find_elements_by_id('KindleLibraryIFrame')) self._wait(5).until(login_or_reader_loaded) try: self._wait(5).until(lambda br: br.title == u'Amazon.com Sign In') except TimeoutException: raise BrowserError('Failed to load Kindle Cloud Reader.') else: self._login()
python
def _to_reader_home(self): # NOTE: Prevents QueryInterface error caused by getting a URL # while switched to an iframe self.switch_to_default_content() self.get(_KindleCloudReaderBrowser._CLOUD_READER_URL) if self.title == u'Problem loading page': raise ConnectionError # Wait for either the login page or the reader to load login_or_reader_loaded = lambda br: ( br.find_elements_by_id('amzn_kcr') or br.find_elements_by_id('KindleLibraryIFrame')) self._wait(5).until(login_or_reader_loaded) try: self._wait(5).until(lambda br: br.title == u'Amazon.com Sign In') except TimeoutException: raise BrowserError('Failed to load Kindle Cloud Reader.') else: self._login()
[ "def", "_to_reader_home", "(", "self", ")", ":", "# NOTE: Prevents QueryInterface error caused by getting a URL", "# while switched to an iframe", "self", ".", "switch_to_default_content", "(", ")", "self", ".", "get", "(", "_KindleCloudReaderBrowser", ".", "_CLOUD_READER_URL", ")", "if", "self", ".", "title", "==", "u'Problem loading page'", ":", "raise", "ConnectionError", "# Wait for either the login page or the reader to load", "login_or_reader_loaded", "=", "lambda", "br", ":", "(", "br", ".", "find_elements_by_id", "(", "'amzn_kcr'", ")", "or", "br", ".", "find_elements_by_id", "(", "'KindleLibraryIFrame'", ")", ")", "self", ".", "_wait", "(", "5", ")", ".", "until", "(", "login_or_reader_loaded", ")", "try", ":", "self", ".", "_wait", "(", "5", ")", ".", "until", "(", "lambda", "br", ":", "br", ".", "title", "==", "u'Amazon.com Sign In'", ")", "except", "TimeoutException", ":", "raise", "BrowserError", "(", "'Failed to load Kindle Cloud Reader.'", ")", "else", ":", "self", ".", "_login", "(", ")" ]
Navigate to the Cloud Reader library page. Raises: BrowserError: If the KCR homepage could not be loaded. ConnectionError: If there was a connection error.
[ "Navigate", "to", "the", "Cloud", "Reader", "library", "page", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L199-L225
2,927
msuozzo/Lector
lector/reader.py
_KindleCloudReaderBrowser._login
def _login(self, max_tries=2): """Logs in to Kindle Cloud Reader. Args: max_tries: The maximum number of login attempts that will be made. Raises: BrowserError: If method called when browser not at a signin URL. LoginError: If login unsuccessful after `max_tries` attempts. """ if not self.current_url.startswith(_KindleCloudReaderBrowser._SIGNIN_URL): raise BrowserError( 'Current url "%s" is not a signin url ("%s")' % (self.current_url, _KindleCloudReaderBrowser._SIGNIN_URL)) email_field_loaded = lambda br: br.find_elements_by_id('ap_email') self._wait().until(email_field_loaded) tries = 0 while tries < max_tries: # Enter the username email_elem = self.find_element_by_id('ap_email') email_elem.clear() email_elem.send_keys(self._uname) # Enter the password pword_elem = self.find_element_by_id('ap_password') pword_elem.clear() pword_elem.send_keys(self._pword) def creds_entered(_): """Returns whether the credentials were properly entered.""" email_ok = email_elem.get_attribute('value') == self._uname pword_ok = pword_elem.get_attribute('value') == self._pword return email_ok and pword_ok kcr_page_loaded = lambda br: br.title == u'Kindle Cloud Reader' try: self._wait(5).until(creds_entered) self.find_element_by_id('signInSubmit-input').click() self._wait(5).until(kcr_page_loaded) except TimeoutException: tries += 1 else: return raise LoginError
python
def _login(self, max_tries=2): if not self.current_url.startswith(_KindleCloudReaderBrowser._SIGNIN_URL): raise BrowserError( 'Current url "%s" is not a signin url ("%s")' % (self.current_url, _KindleCloudReaderBrowser._SIGNIN_URL)) email_field_loaded = lambda br: br.find_elements_by_id('ap_email') self._wait().until(email_field_loaded) tries = 0 while tries < max_tries: # Enter the username email_elem = self.find_element_by_id('ap_email') email_elem.clear() email_elem.send_keys(self._uname) # Enter the password pword_elem = self.find_element_by_id('ap_password') pword_elem.clear() pword_elem.send_keys(self._pword) def creds_entered(_): """Returns whether the credentials were properly entered.""" email_ok = email_elem.get_attribute('value') == self._uname pword_ok = pword_elem.get_attribute('value') == self._pword return email_ok and pword_ok kcr_page_loaded = lambda br: br.title == u'Kindle Cloud Reader' try: self._wait(5).until(creds_entered) self.find_element_by_id('signInSubmit-input').click() self._wait(5).until(kcr_page_loaded) except TimeoutException: tries += 1 else: return raise LoginError
[ "def", "_login", "(", "self", ",", "max_tries", "=", "2", ")", ":", "if", "not", "self", ".", "current_url", ".", "startswith", "(", "_KindleCloudReaderBrowser", ".", "_SIGNIN_URL", ")", ":", "raise", "BrowserError", "(", "'Current url \"%s\" is not a signin url (\"%s\")'", "%", "(", "self", ".", "current_url", ",", "_KindleCloudReaderBrowser", ".", "_SIGNIN_URL", ")", ")", "email_field_loaded", "=", "lambda", "br", ":", "br", ".", "find_elements_by_id", "(", "'ap_email'", ")", "self", ".", "_wait", "(", ")", ".", "until", "(", "email_field_loaded", ")", "tries", "=", "0", "while", "tries", "<", "max_tries", ":", "# Enter the username", "email_elem", "=", "self", ".", "find_element_by_id", "(", "'ap_email'", ")", "email_elem", ".", "clear", "(", ")", "email_elem", ".", "send_keys", "(", "self", ".", "_uname", ")", "# Enter the password", "pword_elem", "=", "self", ".", "find_element_by_id", "(", "'ap_password'", ")", "pword_elem", ".", "clear", "(", ")", "pword_elem", ".", "send_keys", "(", "self", ".", "_pword", ")", "def", "creds_entered", "(", "_", ")", ":", "\"\"\"Returns whether the credentials were properly entered.\"\"\"", "email_ok", "=", "email_elem", ".", "get_attribute", "(", "'value'", ")", "==", "self", ".", "_uname", "pword_ok", "=", "pword_elem", ".", "get_attribute", "(", "'value'", ")", "==", "self", ".", "_pword", "return", "email_ok", "and", "pword_ok", "kcr_page_loaded", "=", "lambda", "br", ":", "br", ".", "title", "==", "u'Kindle Cloud Reader'", "try", ":", "self", ".", "_wait", "(", "5", ")", ".", "until", "(", "creds_entered", ")", "self", ".", "find_element_by_id", "(", "'signInSubmit-input'", ")", ".", "click", "(", ")", "self", ".", "_wait", "(", "5", ")", ".", "until", "(", "kcr_page_loaded", ")", "except", "TimeoutException", ":", "tries", "+=", "1", "else", ":", "return", "raise", "LoginError" ]
Logs in to Kindle Cloud Reader. Args: max_tries: The maximum number of login attempts that will be made. Raises: BrowserError: If method called when browser not at a signin URL. LoginError: If login unsuccessful after `max_tries` attempts.
[ "Logs", "in", "to", "Kindle", "Cloud", "Reader", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L227-L274
2,928
msuozzo/Lector
lector/reader.py
_KindleCloudReaderBrowser._to_reader_frame
def _to_reader_frame(self): """Navigate to the KindleReader iframe.""" reader_frame = 'KindleReaderIFrame' frame_loaded = lambda br: br.find_elements_by_id(reader_frame) self._wait().until(frame_loaded) self.switch_to.frame(reader_frame) # pylint: disable=no-member reader_loaded = lambda br: br.find_elements_by_id('kindleReader_header') self._wait().until(reader_loaded)
python
def _to_reader_frame(self): reader_frame = 'KindleReaderIFrame' frame_loaded = lambda br: br.find_elements_by_id(reader_frame) self._wait().until(frame_loaded) self.switch_to.frame(reader_frame) # pylint: disable=no-member reader_loaded = lambda br: br.find_elements_by_id('kindleReader_header') self._wait().until(reader_loaded)
[ "def", "_to_reader_frame", "(", "self", ")", ":", "reader_frame", "=", "'KindleReaderIFrame'", "frame_loaded", "=", "lambda", "br", ":", "br", ".", "find_elements_by_id", "(", "reader_frame", ")", "self", ".", "_wait", "(", ")", ".", "until", "(", "frame_loaded", ")", "self", ".", "switch_to", ".", "frame", "(", "reader_frame", ")", "# pylint: disable=no-member", "reader_loaded", "=", "lambda", "br", ":", "br", ".", "find_elements_by_id", "(", "'kindleReader_header'", ")", "self", ".", "_wait", "(", ")", ".", "until", "(", "reader_loaded", ")" ]
Navigate to the KindleReader iframe.
[ "Navigate", "to", "the", "KindleReader", "iframe", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L276-L286
2,929
msuozzo/Lector
lector/reader.py
_KindleCloudReaderBrowser._wait_for_js
def _wait_for_js(self): """Wait for the Kindle Cloud Reader JS modules to initialize. These modules provide the interface used to execute API queries. """ # Wait for the Module Manager to load mod_mgr_script = ur"return window.hasOwnProperty('KindleModuleManager');" mod_mgr_loaded = lambda br: br.execute_script(mod_mgr_script) self._wait(5).until(mod_mgr_loaded) # Wait for the DB Client to load db_client_script = dedent(ur""" var done = arguments[0]; if (!window.hasOwnProperty('KindleModuleManager') || !KindleModuleManager .isModuleInitialized(Kindle.MODULE.DB_CLIENT)) { done(false); } else { KindleModuleManager .getModuleSync(Kindle.MODULE.DB_CLIENT) .getAppDb() .getAllBooks() .done(function(books) { done(!!books.length); }); } """) db_client_loaded = lambda br: br.execute_async_script(db_client_script) self._wait(5).until(db_client_loaded)
python
def _wait_for_js(self): # Wait for the Module Manager to load mod_mgr_script = ur"return window.hasOwnProperty('KindleModuleManager');" mod_mgr_loaded = lambda br: br.execute_script(mod_mgr_script) self._wait(5).until(mod_mgr_loaded) # Wait for the DB Client to load db_client_script = dedent(ur""" var done = arguments[0]; if (!window.hasOwnProperty('KindleModuleManager') || !KindleModuleManager .isModuleInitialized(Kindle.MODULE.DB_CLIENT)) { done(false); } else { KindleModuleManager .getModuleSync(Kindle.MODULE.DB_CLIENT) .getAppDb() .getAllBooks() .done(function(books) { done(!!books.length); }); } """) db_client_loaded = lambda br: br.execute_async_script(db_client_script) self._wait(5).until(db_client_loaded)
[ "def", "_wait_for_js", "(", "self", ")", ":", "# Wait for the Module Manager to load", "mod_mgr_script", "=", "ur\"return window.hasOwnProperty('KindleModuleManager');\"", "mod_mgr_loaded", "=", "lambda", "br", ":", "br", ".", "execute_script", "(", "mod_mgr_script", ")", "self", ".", "_wait", "(", "5", ")", ".", "until", "(", "mod_mgr_loaded", ")", "# Wait for the DB Client to load", "db_client_script", "=", "dedent", "(", "ur\"\"\"\n var done = arguments[0];\n if (!window.hasOwnProperty('KindleModuleManager') ||\n !KindleModuleManager\n .isModuleInitialized(Kindle.MODULE.DB_CLIENT)) {\n done(false);\n } else {\n KindleModuleManager\n .getModuleSync(Kindle.MODULE.DB_CLIENT)\n .getAppDb()\n .getAllBooks()\n .done(function(books) { done(!!books.length); });\n }\n \"\"\"", ")", "db_client_loaded", "=", "lambda", "br", ":", "br", ".", "execute_async_script", "(", "db_client_script", ")", "self", ".", "_wait", "(", "5", ")", ".", "until", "(", "db_client_loaded", ")" ]
Wait for the Kindle Cloud Reader JS modules to initialize. These modules provide the interface used to execute API queries.
[ "Wait", "for", "the", "Kindle", "Cloud", "Reader", "JS", "modules", "to", "initialize", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L288-L314
2,930
msuozzo/Lector
lector/reader.py
KindleCloudReaderAPI._get_api_call
def _get_api_call(self, function_name, *args): """Runs an api call with javascript-formatted arguments. Args: function_name: The name of the KindleAPI call to run. *args: Javascript-formatted arguments to pass to the API call. Returns: The result of the API call. Raises: APIError: If the API call fails or times out. """ api_call = dedent(""" var done = arguments[0]; KindleAPI.%(api_call)s(%(args)s).always(function(a) { done(a); }); """) % { 'api_call': function_name, 'args': ', '.join(args) } script = '\n'.join((api.API_SCRIPT, api_call)) try: return self._browser.execute_async_script(script) except TimeoutException: # FIXME: KCR will occassionally not load library and fall over raise APIError
python
def _get_api_call(self, function_name, *args): api_call = dedent(""" var done = arguments[0]; KindleAPI.%(api_call)s(%(args)s).always(function(a) { done(a); }); """) % { 'api_call': function_name, 'args': ', '.join(args) } script = '\n'.join((api.API_SCRIPT, api_call)) try: return self._browser.execute_async_script(script) except TimeoutException: # FIXME: KCR will occassionally not load library and fall over raise APIError
[ "def", "_get_api_call", "(", "self", ",", "function_name", ",", "*", "args", ")", ":", "api_call", "=", "dedent", "(", "\"\"\"\n var done = arguments[0];\n KindleAPI.%(api_call)s(%(args)s).always(function(a) {\n done(a);\n });\n \"\"\"", ")", "%", "{", "'api_call'", ":", "function_name", ",", "'args'", ":", "', '", ".", "join", "(", "args", ")", "}", "script", "=", "'\\n'", ".", "join", "(", "(", "api", ".", "API_SCRIPT", ",", "api_call", ")", ")", "try", ":", "return", "self", ".", "_browser", ".", "execute_async_script", "(", "script", ")", "except", "TimeoutException", ":", "# FIXME: KCR will occassionally not load library and fall over", "raise", "APIError" ]
Runs an api call with javascript-formatted arguments. Args: function_name: The name of the KindleAPI call to run. *args: Javascript-formatted arguments to pass to the API call. Returns: The result of the API call. Raises: APIError: If the API call fails or times out.
[ "Runs", "an", "api", "call", "with", "javascript", "-", "formatted", "arguments", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L328-L355
2,931
msuozzo/Lector
lector/reader.py
KindleCloudReaderAPI.get_book_metadata
def get_book_metadata(self, asin): """Returns a book's metadata. Args: asin: The ASIN of the book to be queried. Returns: A `KindleBook` instance corresponding to the book associated with `asin`. """ kbm = self._get_api_call('get_book_metadata', '"%s"' % asin) return KindleCloudReaderAPI._kbm_to_book(kbm)
python
def get_book_metadata(self, asin): kbm = self._get_api_call('get_book_metadata', '"%s"' % asin) return KindleCloudReaderAPI._kbm_to_book(kbm)
[ "def", "get_book_metadata", "(", "self", ",", "asin", ")", ":", "kbm", "=", "self", ".", "_get_api_call", "(", "'get_book_metadata'", ",", "'\"%s\"'", "%", "asin", ")", "return", "KindleCloudReaderAPI", ".", "_kbm_to_book", "(", "kbm", ")" ]
Returns a book's metadata. Args: asin: The ASIN of the book to be queried. Returns: A `KindleBook` instance corresponding to the book associated with `asin`.
[ "Returns", "a", "book", "s", "metadata", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L387-L398
2,932
msuozzo/Lector
lector/reader.py
KindleCloudReaderAPI.get_book_progress
def get_book_progress(self, asin): """Returns the progress data available for a book. NOTE: A summary of the two progress formats can be found in the docstring for `ReadingProgress`. Args: asin: The asin of the book to be queried. Returns: A `ReadingProgress` instance corresponding to the book associated with `asin`. """ kbp = self._get_api_call('get_book_progress', '"%s"' % asin) return KindleCloudReaderAPI._kbp_to_progress(kbp)
python
def get_book_progress(self, asin): kbp = self._get_api_call('get_book_progress', '"%s"' % asin) return KindleCloudReaderAPI._kbp_to_progress(kbp)
[ "def", "get_book_progress", "(", "self", ",", "asin", ")", ":", "kbp", "=", "self", ".", "_get_api_call", "(", "'get_book_progress'", ",", "'\"%s\"'", "%", "asin", ")", "return", "KindleCloudReaderAPI", ".", "_kbp_to_progress", "(", "kbp", ")" ]
Returns the progress data available for a book. NOTE: A summary of the two progress formats can be found in the docstring for `ReadingProgress`. Args: asin: The asin of the book to be queried. Returns: A `ReadingProgress` instance corresponding to the book associated with `asin`.
[ "Returns", "the", "progress", "data", "available", "for", "a", "book", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L410-L424
2,933
msuozzo/Lector
lector/reader.py
KindleCloudReaderAPI.get_library_progress
def get_library_progress(self): """Returns the reading progress for all books in the kindle library. Returns: A mapping of ASINs to `ReadingProgress` instances corresponding to the books in the current user's library. """ kbp_dict = self._get_api_call('get_library_progress') return {asin: KindleCloudReaderAPI._kbp_to_progress(kbp) for asin, kbp in kbp_dict.iteritems()}
python
def get_library_progress(self): kbp_dict = self._get_api_call('get_library_progress') return {asin: KindleCloudReaderAPI._kbp_to_progress(kbp) for asin, kbp in kbp_dict.iteritems()}
[ "def", "get_library_progress", "(", "self", ")", ":", "kbp_dict", "=", "self", ".", "_get_api_call", "(", "'get_library_progress'", ")", "return", "{", "asin", ":", "KindleCloudReaderAPI", ".", "_kbp_to_progress", "(", "kbp", ")", "for", "asin", ",", "kbp", "in", "kbp_dict", ".", "iteritems", "(", ")", "}" ]
Returns the reading progress for all books in the kindle library. Returns: A mapping of ASINs to `ReadingProgress` instances corresponding to the books in the current user's library.
[ "Returns", "the", "reading", "progress", "for", "all", "books", "in", "the", "kindle", "library", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L426-L435
2,934
msuozzo/Lector
lector/reader.py
KindleCloudReaderAPI.get_instance
def get_instance(*args, **kwargs): """Context manager for an instance of `KindleCloudReaderAPI`.""" inst = KindleCloudReaderAPI(*args, **kwargs) try: yield inst except Exception: raise finally: inst.close()
python
def get_instance(*args, **kwargs): inst = KindleCloudReaderAPI(*args, **kwargs) try: yield inst except Exception: raise finally: inst.close()
[ "def", "get_instance", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "inst", "=", "KindleCloudReaderAPI", "(", "*", "args", ",", "*", "*", "kwargs", ")", "try", ":", "yield", "inst", "except", "Exception", ":", "raise", "finally", ":", "inst", ".", "close", "(", ")" ]
Context manager for an instance of `KindleCloudReaderAPI`.
[ "Context", "manager", "for", "an", "instance", "of", "KindleCloudReaderAPI", "." ]
1570f7734a1c68f294648f44088a7ccb09c26241
https://github.com/msuozzo/Lector/blob/1570f7734a1c68f294648f44088a7ccb09c26241/lector/reader.py#L443-L452
2,935
alexanderlukanin13/coolname
coolname/loader.py
load_config
def load_config(path): """ Loads configuration from a path. Path can be a json file, or a directory containing config.json and zero or more *.txt files with word lists or phrase lists. Returns config dict. Raises InitializationError when something is wrong. """ path = os.path.abspath(path) if os.path.isdir(path): config, wordlists = _load_data(path) elif os.path.isfile(path): config = _load_config(path) wordlists = {} else: raise InitializationError('File or directory not found: {0}'.format(path)) for name, wordlist in wordlists.items(): if name in config: raise InitializationError("Conflict: list {!r} is defined both in config " "and in *.txt file. If it's a {!r} list, " "you should remove it from config." .format(name, _CONF.TYPE.WORDS)) config[name] = wordlist return config
python
def load_config(path): path = os.path.abspath(path) if os.path.isdir(path): config, wordlists = _load_data(path) elif os.path.isfile(path): config = _load_config(path) wordlists = {} else: raise InitializationError('File or directory not found: {0}'.format(path)) for name, wordlist in wordlists.items(): if name in config: raise InitializationError("Conflict: list {!r} is defined both in config " "and in *.txt file. If it's a {!r} list, " "you should remove it from config." .format(name, _CONF.TYPE.WORDS)) config[name] = wordlist return config
[ "def", "load_config", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "config", ",", "wordlists", "=", "_load_data", "(", "path", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "config", "=", "_load_config", "(", "path", ")", "wordlists", "=", "{", "}", "else", ":", "raise", "InitializationError", "(", "'File or directory not found: {0}'", ".", "format", "(", "path", ")", ")", "for", "name", ",", "wordlist", "in", "wordlists", ".", "items", "(", ")", ":", "if", "name", "in", "config", ":", "raise", "InitializationError", "(", "\"Conflict: list {!r} is defined both in config \"", "\"and in *.txt file. If it's a {!r} list, \"", "\"you should remove it from config.\"", ".", "format", "(", "name", ",", "_CONF", ".", "TYPE", ".", "WORDS", ")", ")", "config", "[", "name", "]", "=", "wordlist", "return", "config" ]
Loads configuration from a path. Path can be a json file, or a directory containing config.json and zero or more *.txt files with word lists or phrase lists. Returns config dict. Raises InitializationError when something is wrong.
[ "Loads", "configuration", "from", "a", "path", "." ]
416cc39254ab9e921fd5be77dfe6cdafbad0300c
https://github.com/alexanderlukanin13/coolname/blob/416cc39254ab9e921fd5be77dfe6cdafbad0300c/coolname/loader.py#L19-L45
2,936
alexanderlukanin13/coolname
coolname/loader.py
_load_wordlist
def _load_wordlist(name, stream): """ Loads list of words or phrases from file. Returns "words" or "phrases" dictionary, the same as used in config. Raises Exception if file is missing or invalid. """ items = [] max_length = None multiword = False multiword_start = None number_of_words = None for i, line in enumerate(stream, start=1): line = line.strip() if not line or line.startswith('#'): continue # Is it an option line, e.g. 'max_length = 10'? if '=' in line: if items: raise ConfigurationError('Invalid assignment at list {!r} line {}: {!r} ' '(options must be defined before words)' .format(name, i, line)) try: option, option_value = _parse_option(line) except ValueError as ex: raise ConfigurationError('Invalid assignment at list {!r} line {}: {!r} ' '({})' .format(name, i, line, ex)) if option == _CONF.FIELD.MAX_LENGTH: max_length = option_value elif option == _CONF.FIELD.NUMBER_OF_WORDS: number_of_words = option_value continue # pragma: no cover # Parse words if not multiword and _WORD_REGEX.match(line): if max_length is not None and len(line) > max_length: raise ConfigurationError('Word is too long at list {!r} line {}: {!r}' .format(name, i, line)) items.append(line) elif _PHRASE_REGEX.match(line): if not multiword: multiword = True multiword_start = len(items) phrase = tuple(line.split(' ')) if number_of_words is not None and len(phrase) != number_of_words: raise ConfigurationError('Phrase has {} word(s) (while number_of_words={}) ' 'at list {!r} line {}: {!r}' .format(len(phrase), number_of_words, name, i, line)) if max_length is not None and sum(len(x) for x in phrase) > max_length: raise ConfigurationError('Phrase is too long at list {!r} line {}: {!r}' .format(name, i, line)) items.append(phrase) else: raise ConfigurationError('Invalid syntax at list {!r} line {}: {!r}' .format(name, i, line)) if multiword: # If in phrase mode, convert everything to tuples for i in range(0, multiword_start): items[i] = (items[i], ) result = { _CONF.FIELD.TYPE: _CONF.TYPE.PHRASES, _CONF.FIELD.PHRASES: items } if number_of_words is not None: result[_CONF.FIELD.NUMBER_OF_WORDS] = number_of_words else: result = { _CONF.FIELD.TYPE: _CONF.TYPE.WORDS, _CONF.FIELD.WORDS: items } if max_length is not None: result[_CONF.FIELD.MAX_LENGTH] = max_length return result
python
def _load_wordlist(name, stream): items = [] max_length = None multiword = False multiword_start = None number_of_words = None for i, line in enumerate(stream, start=1): line = line.strip() if not line or line.startswith('#'): continue # Is it an option line, e.g. 'max_length = 10'? if '=' in line: if items: raise ConfigurationError('Invalid assignment at list {!r} line {}: {!r} ' '(options must be defined before words)' .format(name, i, line)) try: option, option_value = _parse_option(line) except ValueError as ex: raise ConfigurationError('Invalid assignment at list {!r} line {}: {!r} ' '({})' .format(name, i, line, ex)) if option == _CONF.FIELD.MAX_LENGTH: max_length = option_value elif option == _CONF.FIELD.NUMBER_OF_WORDS: number_of_words = option_value continue # pragma: no cover # Parse words if not multiword and _WORD_REGEX.match(line): if max_length is not None and len(line) > max_length: raise ConfigurationError('Word is too long at list {!r} line {}: {!r}' .format(name, i, line)) items.append(line) elif _PHRASE_REGEX.match(line): if not multiword: multiword = True multiword_start = len(items) phrase = tuple(line.split(' ')) if number_of_words is not None and len(phrase) != number_of_words: raise ConfigurationError('Phrase has {} word(s) (while number_of_words={}) ' 'at list {!r} line {}: {!r}' .format(len(phrase), number_of_words, name, i, line)) if max_length is not None and sum(len(x) for x in phrase) > max_length: raise ConfigurationError('Phrase is too long at list {!r} line {}: {!r}' .format(name, i, line)) items.append(phrase) else: raise ConfigurationError('Invalid syntax at list {!r} line {}: {!r}' .format(name, i, line)) if multiword: # If in phrase mode, convert everything to tuples for i in range(0, multiword_start): items[i] = (items[i], ) result = { _CONF.FIELD.TYPE: _CONF.TYPE.PHRASES, _CONF.FIELD.PHRASES: items } if number_of_words is not None: result[_CONF.FIELD.NUMBER_OF_WORDS] = number_of_words else: result = { _CONF.FIELD.TYPE: _CONF.TYPE.WORDS, _CONF.FIELD.WORDS: items } if max_length is not None: result[_CONF.FIELD.MAX_LENGTH] = max_length return result
[ "def", "_load_wordlist", "(", "name", ",", "stream", ")", ":", "items", "=", "[", "]", "max_length", "=", "None", "multiword", "=", "False", "multiword_start", "=", "None", "number_of_words", "=", "None", "for", "i", ",", "line", "in", "enumerate", "(", "stream", ",", "start", "=", "1", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "not", "line", "or", "line", ".", "startswith", "(", "'#'", ")", ":", "continue", "# Is it an option line, e.g. 'max_length = 10'?", "if", "'='", "in", "line", ":", "if", "items", ":", "raise", "ConfigurationError", "(", "'Invalid assignment at list {!r} line {}: {!r} '", "'(options must be defined before words)'", ".", "format", "(", "name", ",", "i", ",", "line", ")", ")", "try", ":", "option", ",", "option_value", "=", "_parse_option", "(", "line", ")", "except", "ValueError", "as", "ex", ":", "raise", "ConfigurationError", "(", "'Invalid assignment at list {!r} line {}: {!r} '", "'({})'", ".", "format", "(", "name", ",", "i", ",", "line", ",", "ex", ")", ")", "if", "option", "==", "_CONF", ".", "FIELD", ".", "MAX_LENGTH", ":", "max_length", "=", "option_value", "elif", "option", "==", "_CONF", ".", "FIELD", ".", "NUMBER_OF_WORDS", ":", "number_of_words", "=", "option_value", "continue", "# pragma: no cover", "# Parse words", "if", "not", "multiword", "and", "_WORD_REGEX", ".", "match", "(", "line", ")", ":", "if", "max_length", "is", "not", "None", "and", "len", "(", "line", ")", ">", "max_length", ":", "raise", "ConfigurationError", "(", "'Word is too long at list {!r} line {}: {!r}'", ".", "format", "(", "name", ",", "i", ",", "line", ")", ")", "items", ".", "append", "(", "line", ")", "elif", "_PHRASE_REGEX", ".", "match", "(", "line", ")", ":", "if", "not", "multiword", ":", "multiword", "=", "True", "multiword_start", "=", "len", "(", "items", ")", "phrase", "=", "tuple", "(", "line", ".", "split", "(", "' '", ")", ")", "if", "number_of_words", "is", "not", "None", "and", "len", "(", "phrase", ")", "!=", "number_of_words", ":", "raise", "ConfigurationError", "(", "'Phrase has {} word(s) (while number_of_words={}) '", "'at list {!r} line {}: {!r}'", ".", "format", "(", "len", "(", "phrase", ")", ",", "number_of_words", ",", "name", ",", "i", ",", "line", ")", ")", "if", "max_length", "is", "not", "None", "and", "sum", "(", "len", "(", "x", ")", "for", "x", "in", "phrase", ")", ">", "max_length", ":", "raise", "ConfigurationError", "(", "'Phrase is too long at list {!r} line {}: {!r}'", ".", "format", "(", "name", ",", "i", ",", "line", ")", ")", "items", ".", "append", "(", "phrase", ")", "else", ":", "raise", "ConfigurationError", "(", "'Invalid syntax at list {!r} line {}: {!r}'", ".", "format", "(", "name", ",", "i", ",", "line", ")", ")", "if", "multiword", ":", "# If in phrase mode, convert everything to tuples", "for", "i", "in", "range", "(", "0", ",", "multiword_start", ")", ":", "items", "[", "i", "]", "=", "(", "items", "[", "i", "]", ",", ")", "result", "=", "{", "_CONF", ".", "FIELD", ".", "TYPE", ":", "_CONF", ".", "TYPE", ".", "PHRASES", ",", "_CONF", ".", "FIELD", ".", "PHRASES", ":", "items", "}", "if", "number_of_words", "is", "not", "None", ":", "result", "[", "_CONF", ".", "FIELD", ".", "NUMBER_OF_WORDS", "]", "=", "number_of_words", "else", ":", "result", "=", "{", "_CONF", ".", "FIELD", ".", "TYPE", ":", "_CONF", ".", "TYPE", ".", "WORDS", ",", "_CONF", ".", "FIELD", ".", "WORDS", ":", "items", "}", "if", "max_length", "is", "not", "None", ":", "result", "[", "_CONF", ".", "FIELD", ".", "MAX_LENGTH", "]", "=", "max_length", "return", "result" ]
Loads list of words or phrases from file. Returns "words" or "phrases" dictionary, the same as used in config. Raises Exception if file is missing or invalid.
[ "Loads", "list", "of", "words", "or", "phrases", "from", "file", "." ]
416cc39254ab9e921fd5be77dfe6cdafbad0300c
https://github.com/alexanderlukanin13/coolname/blob/416cc39254ab9e921fd5be77dfe6cdafbad0300c/coolname/loader.py#L110-L182
2,937
alexanderlukanin13/coolname
coolname/impl.py
_create_lists
def _create_lists(config, results, current, stack, inside_cartesian=None): """ An ugly recursive method to transform config dict into a tree of AbstractNestedList. """ # Have we done it already? try: return results[current] except KeyError: pass # Check recursion depth and detect loops if current in stack: raise ConfigurationError('Rule {!r} is recursive: {!r}'.format(stack[0], stack)) if len(stack) > 99: raise ConfigurationError('Rule {!r} is too deep'.format(stack[0])) # Track recursion depth stack.append(current) try: # Check what kind of list we have listdef = config[current] list_type = listdef[_CONF.FIELD.TYPE] # 1. List of words if list_type == _CONF.TYPE.WORDS: results[current] = WordList(listdef['words']) # List of phrases elif list_type == _CONF.TYPE.PHRASES: results[current] = PhraseList(listdef['phrases']) # 2. Simple list of lists elif list_type == _CONF.TYPE.NESTED: results[current] = NestedList([_create_lists(config, results, x, stack, inside_cartesian=inside_cartesian) for x in listdef[_CONF.FIELD.LISTS]]) # 3. Cartesian list of lists elif list_type == _CONF.TYPE.CARTESIAN: if inside_cartesian is not None: raise ConfigurationError("Cartesian list {!r} contains another Cartesian list " "{!r}. Nested Cartesian lists are not allowed." .format(inside_cartesian, current)) results[current] = CartesianList([_create_lists(config, results, x, stack, inside_cartesian=current) for x in listdef[_CONF.FIELD.LISTS]]) # 4. Scalar elif list_type == _CONF.TYPE.CONST: results[current] = Scalar(listdef[_CONF.FIELD.VALUE]) # Unknown type else: raise InitializationError("Unknown list type: {!r}".format(list_type)) # Return the result return results[current] finally: stack.pop()
python
def _create_lists(config, results, current, stack, inside_cartesian=None): # Have we done it already? try: return results[current] except KeyError: pass # Check recursion depth and detect loops if current in stack: raise ConfigurationError('Rule {!r} is recursive: {!r}'.format(stack[0], stack)) if len(stack) > 99: raise ConfigurationError('Rule {!r} is too deep'.format(stack[0])) # Track recursion depth stack.append(current) try: # Check what kind of list we have listdef = config[current] list_type = listdef[_CONF.FIELD.TYPE] # 1. List of words if list_type == _CONF.TYPE.WORDS: results[current] = WordList(listdef['words']) # List of phrases elif list_type == _CONF.TYPE.PHRASES: results[current] = PhraseList(listdef['phrases']) # 2. Simple list of lists elif list_type == _CONF.TYPE.NESTED: results[current] = NestedList([_create_lists(config, results, x, stack, inside_cartesian=inside_cartesian) for x in listdef[_CONF.FIELD.LISTS]]) # 3. Cartesian list of lists elif list_type == _CONF.TYPE.CARTESIAN: if inside_cartesian is not None: raise ConfigurationError("Cartesian list {!r} contains another Cartesian list " "{!r}. Nested Cartesian lists are not allowed." .format(inside_cartesian, current)) results[current] = CartesianList([_create_lists(config, results, x, stack, inside_cartesian=current) for x in listdef[_CONF.FIELD.LISTS]]) # 4. Scalar elif list_type == _CONF.TYPE.CONST: results[current] = Scalar(listdef[_CONF.FIELD.VALUE]) # Unknown type else: raise InitializationError("Unknown list type: {!r}".format(list_type)) # Return the result return results[current] finally: stack.pop()
[ "def", "_create_lists", "(", "config", ",", "results", ",", "current", ",", "stack", ",", "inside_cartesian", "=", "None", ")", ":", "# Have we done it already?", "try", ":", "return", "results", "[", "current", "]", "except", "KeyError", ":", "pass", "# Check recursion depth and detect loops", "if", "current", "in", "stack", ":", "raise", "ConfigurationError", "(", "'Rule {!r} is recursive: {!r}'", ".", "format", "(", "stack", "[", "0", "]", ",", "stack", ")", ")", "if", "len", "(", "stack", ")", ">", "99", ":", "raise", "ConfigurationError", "(", "'Rule {!r} is too deep'", ".", "format", "(", "stack", "[", "0", "]", ")", ")", "# Track recursion depth", "stack", ".", "append", "(", "current", ")", "try", ":", "# Check what kind of list we have", "listdef", "=", "config", "[", "current", "]", "list_type", "=", "listdef", "[", "_CONF", ".", "FIELD", ".", "TYPE", "]", "# 1. List of words", "if", "list_type", "==", "_CONF", ".", "TYPE", ".", "WORDS", ":", "results", "[", "current", "]", "=", "WordList", "(", "listdef", "[", "'words'", "]", ")", "# List of phrases", "elif", "list_type", "==", "_CONF", ".", "TYPE", ".", "PHRASES", ":", "results", "[", "current", "]", "=", "PhraseList", "(", "listdef", "[", "'phrases'", "]", ")", "# 2. Simple list of lists", "elif", "list_type", "==", "_CONF", ".", "TYPE", ".", "NESTED", ":", "results", "[", "current", "]", "=", "NestedList", "(", "[", "_create_lists", "(", "config", ",", "results", ",", "x", ",", "stack", ",", "inside_cartesian", "=", "inside_cartesian", ")", "for", "x", "in", "listdef", "[", "_CONF", ".", "FIELD", ".", "LISTS", "]", "]", ")", "# 3. Cartesian list of lists", "elif", "list_type", "==", "_CONF", ".", "TYPE", ".", "CARTESIAN", ":", "if", "inside_cartesian", "is", "not", "None", ":", "raise", "ConfigurationError", "(", "\"Cartesian list {!r} contains another Cartesian list \"", "\"{!r}. Nested Cartesian lists are not allowed.\"", ".", "format", "(", "inside_cartesian", ",", "current", ")", ")", "results", "[", "current", "]", "=", "CartesianList", "(", "[", "_create_lists", "(", "config", ",", "results", ",", "x", ",", "stack", ",", "inside_cartesian", "=", "current", ")", "for", "x", "in", "listdef", "[", "_CONF", ".", "FIELD", ".", "LISTS", "]", "]", ")", "# 4. Scalar", "elif", "list_type", "==", "_CONF", ".", "TYPE", ".", "CONST", ":", "results", "[", "current", "]", "=", "Scalar", "(", "listdef", "[", "_CONF", ".", "FIELD", ".", "VALUE", "]", ")", "# Unknown type", "else", ":", "raise", "InitializationError", "(", "\"Unknown list type: {!r}\"", ".", "format", "(", "list_type", ")", ")", "# Return the result", "return", "results", "[", "current", "]", "finally", ":", "stack", ".", "pop", "(", ")" ]
An ugly recursive method to transform config dict into a tree of AbstractNestedList.
[ "An", "ugly", "recursive", "method", "to", "transform", "config", "dict", "into", "a", "tree", "of", "AbstractNestedList", "." ]
416cc39254ab9e921fd5be77dfe6cdafbad0300c
https://github.com/alexanderlukanin13/coolname/blob/416cc39254ab9e921fd5be77dfe6cdafbad0300c/coolname/impl.py#L508-L559
2,938
alexanderlukanin13/coolname
coolname/impl.py
RandomGenerator.generate
def generate(self, pattern=None): """ Generates and returns random name as a list of strings. """ lst = self._lists[pattern] while True: result = lst[self._randrange(lst.length)] # 1. Check that there are no duplicates # 2. Check that there are no duplicate prefixes # 3. Check max slug length n = len(result) if (self._ensure_unique and len(set(result)) != n or self._check_prefix and len(set(x[:self._check_prefix] for x in result)) != n or self._max_slug_length and sum(len(x) for x in result) + n - 1 > self._max_slug_length): continue return result
python
def generate(self, pattern=None): lst = self._lists[pattern] while True: result = lst[self._randrange(lst.length)] # 1. Check that there are no duplicates # 2. Check that there are no duplicate prefixes # 3. Check max slug length n = len(result) if (self._ensure_unique and len(set(result)) != n or self._check_prefix and len(set(x[:self._check_prefix] for x in result)) != n or self._max_slug_length and sum(len(x) for x in result) + n - 1 > self._max_slug_length): continue return result
[ "def", "generate", "(", "self", ",", "pattern", "=", "None", ")", ":", "lst", "=", "self", ".", "_lists", "[", "pattern", "]", "while", "True", ":", "result", "=", "lst", "[", "self", ".", "_randrange", "(", "lst", ".", "length", ")", "]", "# 1. Check that there are no duplicates", "# 2. Check that there are no duplicate prefixes", "# 3. Check max slug length", "n", "=", "len", "(", "result", ")", "if", "(", "self", ".", "_ensure_unique", "and", "len", "(", "set", "(", "result", ")", ")", "!=", "n", "or", "self", ".", "_check_prefix", "and", "len", "(", "set", "(", "x", "[", ":", "self", ".", "_check_prefix", "]", "for", "x", "in", "result", ")", ")", "!=", "n", "or", "self", ".", "_max_slug_length", "and", "sum", "(", "len", "(", "x", ")", "for", "x", "in", "result", ")", "+", "n", "-", "1", ">", "self", ".", "_max_slug_length", ")", ":", "continue", "return", "result" ]
Generates and returns random name as a list of strings.
[ "Generates", "and", "returns", "random", "name", "as", "a", "list", "of", "strings", "." ]
416cc39254ab9e921fd5be77dfe6cdafbad0300c
https://github.com/alexanderlukanin13/coolname/blob/416cc39254ab9e921fd5be77dfe6cdafbad0300c/coolname/impl.py#L306-L321
2,939
alexanderlukanin13/coolname
coolname/impl.py
RandomGenerator._dump
def _dump(self, stream, pattern=None, object_ids=False): """Dumps current tree into a text stream.""" return self._lists[pattern]._dump(stream, '', object_ids=object_ids)
python
def _dump(self, stream, pattern=None, object_ids=False): return self._lists[pattern]._dump(stream, '', object_ids=object_ids)
[ "def", "_dump", "(", "self", ",", "stream", ",", "pattern", "=", "None", ",", "object_ids", "=", "False", ")", ":", "return", "self", ".", "_lists", "[", "pattern", "]", ".", "_dump", "(", "stream", ",", "''", ",", "object_ids", "=", "object_ids", ")" ]
Dumps current tree into a text stream.
[ "Dumps", "current", "tree", "into", "a", "text", "stream", "." ]
416cc39254ab9e921fd5be77dfe6cdafbad0300c
https://github.com/alexanderlukanin13/coolname/blob/416cc39254ab9e921fd5be77dfe6cdafbad0300c/coolname/impl.py#L337-L339
2,940
kvesteri/postgresql-audit
postgresql_audit/migrations.py
alter_column
def alter_column(conn, table, column_name, func, schema=None): """ Run given callable against given table and given column in activity table jsonb data columns. This function is useful when you want to reflect type changes in your schema to activity table. In the following example we change the data type of User's age column from string to integer. :: from alembic import op from postgresql_audit import alter_column def upgrade(): op.alter_column( 'user', 'age', type_=sa.Integer ) alter_column( op, 'user', 'age', lambda value, activity_table: sa.cast(value, sa.Integer) ) :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to run the column name changes against :param column_name: Name of the column to run callable against :param func: A callable to run against specific column in activity table jsonb data columns. The callable should take two parameters the jsonb value corresponding to given column_name and activity table object. :param schema: Optional name of schema to use. """ activity_table = get_activity_table(schema=schema) query = ( activity_table .update() .values( old_data=( activity_table.c.old_data + sa.cast(sa.func.json_build_object( column_name, func( activity_table.c.old_data[column_name], activity_table ) ), JSONB) ), changed_data=( activity_table.c.changed_data + sa.cast(sa.func.json_build_object( column_name, func( activity_table.c.changed_data[column_name], activity_table ) ), JSONB) ) ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
python
def alter_column(conn, table, column_name, func, schema=None): activity_table = get_activity_table(schema=schema) query = ( activity_table .update() .values( old_data=( activity_table.c.old_data + sa.cast(sa.func.json_build_object( column_name, func( activity_table.c.old_data[column_name], activity_table ) ), JSONB) ), changed_data=( activity_table.c.changed_data + sa.cast(sa.func.json_build_object( column_name, func( activity_table.c.changed_data[column_name], activity_table ) ), JSONB) ) ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
[ "def", "alter_column", "(", "conn", ",", "table", ",", "column_name", ",", "func", ",", "schema", "=", "None", ")", ":", "activity_table", "=", "get_activity_table", "(", "schema", "=", "schema", ")", "query", "=", "(", "activity_table", ".", "update", "(", ")", ".", "values", "(", "old_data", "=", "(", "activity_table", ".", "c", ".", "old_data", "+", "sa", ".", "cast", "(", "sa", ".", "func", ".", "json_build_object", "(", "column_name", ",", "func", "(", "activity_table", ".", "c", ".", "old_data", "[", "column_name", "]", ",", "activity_table", ")", ")", ",", "JSONB", ")", ")", ",", "changed_data", "=", "(", "activity_table", ".", "c", ".", "changed_data", "+", "sa", ".", "cast", "(", "sa", ".", "func", ".", "json_build_object", "(", "column_name", ",", "func", "(", "activity_table", ".", "c", ".", "changed_data", "[", "column_name", "]", ",", "activity_table", ")", ")", ",", "JSONB", ")", ")", ")", ".", "where", "(", "activity_table", ".", "c", ".", "table_name", "==", "table", ")", ")", "return", "conn", ".", "execute", "(", "query", ")" ]
Run given callable against given table and given column in activity table jsonb data columns. This function is useful when you want to reflect type changes in your schema to activity table. In the following example we change the data type of User's age column from string to integer. :: from alembic import op from postgresql_audit import alter_column def upgrade(): op.alter_column( 'user', 'age', type_=sa.Integer ) alter_column( op, 'user', 'age', lambda value, activity_table: sa.cast(value, sa.Integer) ) :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to run the column name changes against :param column_name: Name of the column to run callable against :param func: A callable to run against specific column in activity table jsonb data columns. The callable should take two parameters the jsonb value corresponding to given column_name and activity table object. :param schema: Optional name of schema to use.
[ "Run", "given", "callable", "against", "given", "table", "and", "given", "column", "in", "activity", "table", "jsonb", "data", "columns", ".", "This", "function", "is", "useful", "when", "you", "want", "to", "reflect", "type", "changes", "in", "your", "schema", "to", "activity", "table", "." ]
91b497ced2e04dd44bb757b02983d2a64a2b1514
https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/migrations.py#L20-L93
2,941
kvesteri/postgresql-audit
postgresql_audit/migrations.py
change_column_name
def change_column_name( conn, table, old_column_name, new_column_name, schema=None ): """ Changes given `activity` jsonb data column key. This function is useful when you want to reflect column name changes to activity table. :: from alembic import op from postgresql_audit import change_column_name def upgrade(): op.alter_column( 'my_table', 'my_column', new_column_name='some_column' ) change_column_name(op, 'my_table', 'my_column', 'some_column') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to run the column name changes against :param old_column_name: Name of the column to change :param new_column_name: New colum name :param schema: Optional name of schema to use. """ activity_table = get_activity_table(schema=schema) query = ( activity_table .update() .values( old_data=jsonb_change_key_name( activity_table.c.old_data, old_column_name, new_column_name ), changed_data=jsonb_change_key_name( activity_table.c.changed_data, old_column_name, new_column_name ) ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
python
def change_column_name( conn, table, old_column_name, new_column_name, schema=None ): activity_table = get_activity_table(schema=schema) query = ( activity_table .update() .values( old_data=jsonb_change_key_name( activity_table.c.old_data, old_column_name, new_column_name ), changed_data=jsonb_change_key_name( activity_table.c.changed_data, old_column_name, new_column_name ) ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
[ "def", "change_column_name", "(", "conn", ",", "table", ",", "old_column_name", ",", "new_column_name", ",", "schema", "=", "None", ")", ":", "activity_table", "=", "get_activity_table", "(", "schema", "=", "schema", ")", "query", "=", "(", "activity_table", ".", "update", "(", ")", ".", "values", "(", "old_data", "=", "jsonb_change_key_name", "(", "activity_table", ".", "c", ".", "old_data", ",", "old_column_name", ",", "new_column_name", ")", ",", "changed_data", "=", "jsonb_change_key_name", "(", "activity_table", ".", "c", ".", "changed_data", ",", "old_column_name", ",", "new_column_name", ")", ")", ".", "where", "(", "activity_table", ".", "c", ".", "table_name", "==", "table", ")", ")", "return", "conn", ".", "execute", "(", "query", ")" ]
Changes given `activity` jsonb data column key. This function is useful when you want to reflect column name changes to activity table. :: from alembic import op from postgresql_audit import change_column_name def upgrade(): op.alter_column( 'my_table', 'my_column', new_column_name='some_column' ) change_column_name(op, 'my_table', 'my_column', 'some_column') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to run the column name changes against :param old_column_name: Name of the column to change :param new_column_name: New colum name :param schema: Optional name of schema to use.
[ "Changes", "given", "activity", "jsonb", "data", "column", "key", ".", "This", "function", "is", "useful", "when", "you", "want", "to", "reflect", "column", "name", "changes", "to", "activity", "table", "." ]
91b497ced2e04dd44bb757b02983d2a64a2b1514
https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/migrations.py#L96-L153
2,942
kvesteri/postgresql-audit
postgresql_audit/migrations.py
add_column
def add_column(conn, table, column_name, default_value=None, schema=None): """ Adds given column to `activity` table jsonb data columns. In the following example we reflect the changes made to our schema to activity table. :: import sqlalchemy as sa from alembic import op from postgresql_audit import add_column def upgrade(): op.add_column('article', sa.Column('created_at', sa.DateTime())) add_column(op, 'article', 'created_at') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to remove the column from :param column_name: Name of the column to add :param default_value: The default value of the column :param schema: Optional name of schema to use. """ activity_table = get_activity_table(schema=schema) data = {column_name: default_value} query = ( activity_table .update() .values( old_data=sa.case( [ ( sa.cast(activity_table.c.old_data, sa.Text) != '{}', activity_table.c.old_data + data ), ], else_=sa.cast({}, JSONB) ), changed_data=sa.case( [ ( sa.and_( sa.cast( activity_table.c.changed_data, sa.Text ) != '{}', activity_table.c.verb != 'update' ), activity_table.c.changed_data + data ) ], else_=activity_table.c.changed_data ), ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
python
def add_column(conn, table, column_name, default_value=None, schema=None): activity_table = get_activity_table(schema=schema) data = {column_name: default_value} query = ( activity_table .update() .values( old_data=sa.case( [ ( sa.cast(activity_table.c.old_data, sa.Text) != '{}', activity_table.c.old_data + data ), ], else_=sa.cast({}, JSONB) ), changed_data=sa.case( [ ( sa.and_( sa.cast( activity_table.c.changed_data, sa.Text ) != '{}', activity_table.c.verb != 'update' ), activity_table.c.changed_data + data ) ], else_=activity_table.c.changed_data ), ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
[ "def", "add_column", "(", "conn", ",", "table", ",", "column_name", ",", "default_value", "=", "None", ",", "schema", "=", "None", ")", ":", "activity_table", "=", "get_activity_table", "(", "schema", "=", "schema", ")", "data", "=", "{", "column_name", ":", "default_value", "}", "query", "=", "(", "activity_table", ".", "update", "(", ")", ".", "values", "(", "old_data", "=", "sa", ".", "case", "(", "[", "(", "sa", ".", "cast", "(", "activity_table", ".", "c", ".", "old_data", ",", "sa", ".", "Text", ")", "!=", "'{}'", ",", "activity_table", ".", "c", ".", "old_data", "+", "data", ")", ",", "]", ",", "else_", "=", "sa", ".", "cast", "(", "{", "}", ",", "JSONB", ")", ")", ",", "changed_data", "=", "sa", ".", "case", "(", "[", "(", "sa", ".", "and_", "(", "sa", ".", "cast", "(", "activity_table", ".", "c", ".", "changed_data", ",", "sa", ".", "Text", ")", "!=", "'{}'", ",", "activity_table", ".", "c", ".", "verb", "!=", "'update'", ")", ",", "activity_table", ".", "c", ".", "changed_data", "+", "data", ")", "]", ",", "else_", "=", "activity_table", ".", "c", ".", "changed_data", ")", ",", ")", ".", "where", "(", "activity_table", ".", "c", ".", "table_name", "==", "table", ")", ")", "return", "conn", ".", "execute", "(", "query", ")" ]
Adds given column to `activity` table jsonb data columns. In the following example we reflect the changes made to our schema to activity table. :: import sqlalchemy as sa from alembic import op from postgresql_audit import add_column def upgrade(): op.add_column('article', sa.Column('created_at', sa.DateTime())) add_column(op, 'article', 'created_at') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to remove the column from :param column_name: Name of the column to add :param default_value: The default value of the column :param schema: Optional name of schema to use.
[ "Adds", "given", "column", "to", "activity", "table", "jsonb", "data", "columns", "." ]
91b497ced2e04dd44bb757b02983d2a64a2b1514
https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/migrations.py#L156-L220
2,943
kvesteri/postgresql-audit
postgresql_audit/migrations.py
remove_column
def remove_column(conn, table, column_name, schema=None): """ Removes given `activity` jsonb data column key. This function is useful when you are doing schema changes that require removing a column. Let's say you've been using PostgreSQL-Audit for a while for a table called article. Now you want to remove one audited column called 'created_at' from this table. :: from alembic import op from postgresql_audit import remove_column def upgrade(): op.remove_column('article', 'created_at') remove_column(op, 'article', 'created_at') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to remove the column from :param column_name: Name of the column to remove :param schema: Optional name of schema to use. """ activity_table = get_activity_table(schema=schema) remove = sa.cast(column_name, sa.Text) query = ( activity_table .update() .values( old_data=activity_table.c.old_data - remove, changed_data=activity_table.c.changed_data - remove, ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
python
def remove_column(conn, table, column_name, schema=None): activity_table = get_activity_table(schema=schema) remove = sa.cast(column_name, sa.Text) query = ( activity_table .update() .values( old_data=activity_table.c.old_data - remove, changed_data=activity_table.c.changed_data - remove, ) .where(activity_table.c.table_name == table) ) return conn.execute(query)
[ "def", "remove_column", "(", "conn", ",", "table", ",", "column_name", ",", "schema", "=", "None", ")", ":", "activity_table", "=", "get_activity_table", "(", "schema", "=", "schema", ")", "remove", "=", "sa", ".", "cast", "(", "column_name", ",", "sa", ".", "Text", ")", "query", "=", "(", "activity_table", ".", "update", "(", ")", ".", "values", "(", "old_data", "=", "activity_table", ".", "c", ".", "old_data", "-", "remove", ",", "changed_data", "=", "activity_table", ".", "c", ".", "changed_data", "-", "remove", ",", ")", ".", "where", "(", "activity_table", ".", "c", ".", "table_name", "==", "table", ")", ")", "return", "conn", ".", "execute", "(", "query", ")" ]
Removes given `activity` jsonb data column key. This function is useful when you are doing schema changes that require removing a column. Let's say you've been using PostgreSQL-Audit for a while for a table called article. Now you want to remove one audited column called 'created_at' from this table. :: from alembic import op from postgresql_audit import remove_column def upgrade(): op.remove_column('article', 'created_at') remove_column(op, 'article', 'created_at') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param table: The table to remove the column from :param column_name: Name of the column to remove :param schema: Optional name of schema to use.
[ "Removes", "given", "activity", "jsonb", "data", "column", "key", ".", "This", "function", "is", "useful", "when", "you", "are", "doing", "schema", "changes", "that", "require", "removing", "a", "column", "." ]
91b497ced2e04dd44bb757b02983d2a64a2b1514
https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/migrations.py#L223-L264
2,944
kvesteri/postgresql-audit
postgresql_audit/migrations.py
rename_table
def rename_table(conn, old_table_name, new_table_name, schema=None): """ Renames given table in activity table. You should remember to call this function whenever you rename a versioned table. :: from alembic import op from postgresql_audit import rename_table def upgrade(): op.rename_table('article', 'article_v2') rename_table(op, 'article', 'article_v2') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param old_table_name: The name of table to rename :param new_table_name: New name of the renamed table :param schema: Optional name of schema to use. """ activity_table = get_activity_table(schema=schema) query = ( activity_table .update() .values(table_name=new_table_name) .where(activity_table.c.table_name == old_table_name) ) return conn.execute(query)
python
def rename_table(conn, old_table_name, new_table_name, schema=None): activity_table = get_activity_table(schema=schema) query = ( activity_table .update() .values(table_name=new_table_name) .where(activity_table.c.table_name == old_table_name) ) return conn.execute(query)
[ "def", "rename_table", "(", "conn", ",", "old_table_name", ",", "new_table_name", ",", "schema", "=", "None", ")", ":", "activity_table", "=", "get_activity_table", "(", "schema", "=", "schema", ")", "query", "=", "(", "activity_table", ".", "update", "(", ")", ".", "values", "(", "table_name", "=", "new_table_name", ")", ".", "where", "(", "activity_table", ".", "c", ".", "table_name", "==", "old_table_name", ")", ")", "return", "conn", ".", "execute", "(", "query", ")" ]
Renames given table in activity table. You should remember to call this function whenever you rename a versioned table. :: from alembic import op from postgresql_audit import rename_table def upgrade(): op.rename_table('article', 'article_v2') rename_table(op, 'article', 'article_v2') :param conn: An object that is able to execute SQL (either SQLAlchemy Connection, Engine or Alembic Operations object) :param old_table_name: The name of table to rename :param new_table_name: New name of the renamed table :param schema: Optional name of schema to use.
[ "Renames", "given", "table", "in", "activity", "table", ".", "You", "should", "remember", "to", "call", "this", "function", "whenever", "you", "rename", "a", "versioned", "table", "." ]
91b497ced2e04dd44bb757b02983d2a64a2b1514
https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/migrations.py#L267-L300
2,945
kvesteri/postgresql-audit
postgresql_audit/base.py
VersioningManager.instrument_versioned_classes
def instrument_versioned_classes(self, mapper, cls): """ Collect versioned class and add it to pending_classes list. :mapper mapper: SQLAlchemy mapper object :cls cls: SQLAlchemy declarative class """ if hasattr(cls, '__versioned__') and cls not in self.pending_classes: self.pending_classes.add(cls)
python
def instrument_versioned_classes(self, mapper, cls): if hasattr(cls, '__versioned__') and cls not in self.pending_classes: self.pending_classes.add(cls)
[ "def", "instrument_versioned_classes", "(", "self", ",", "mapper", ",", "cls", ")", ":", "if", "hasattr", "(", "cls", ",", "'__versioned__'", ")", "and", "cls", "not", "in", "self", ".", "pending_classes", ":", "self", ".", "pending_classes", ".", "add", "(", "cls", ")" ]
Collect versioned class and add it to pending_classes list. :mapper mapper: SQLAlchemy mapper object :cls cls: SQLAlchemy declarative class
[ "Collect", "versioned", "class", "and", "add", "it", "to", "pending_classes", "list", "." ]
91b497ced2e04dd44bb757b02983d2a64a2b1514
https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/base.py#L346-L354
2,946
kvesteri/postgresql-audit
postgresql_audit/base.py
VersioningManager.configure_versioned_classes
def configure_versioned_classes(self): """ Configures all versioned classes that were collected during instrumentation process. """ for cls in self.pending_classes: self.audit_table(cls.__table__, cls.__versioned__.get('exclude')) assign_actor(self.base, self.transaction_cls, self.actor_cls)
python
def configure_versioned_classes(self): for cls in self.pending_classes: self.audit_table(cls.__table__, cls.__versioned__.get('exclude')) assign_actor(self.base, self.transaction_cls, self.actor_cls)
[ "def", "configure_versioned_classes", "(", "self", ")", ":", "for", "cls", "in", "self", ".", "pending_classes", ":", "self", ".", "audit_table", "(", "cls", ".", "__table__", ",", "cls", ".", "__versioned__", ".", "get", "(", "'exclude'", ")", ")", "assign_actor", "(", "self", ".", "base", ",", "self", ".", "transaction_cls", ",", "self", ".", "actor_cls", ")" ]
Configures all versioned classes that were collected during instrumentation process.
[ "Configures", "all", "versioned", "classes", "that", "were", "collected", "during", "instrumentation", "process", "." ]
91b497ced2e04dd44bb757b02983d2a64a2b1514
https://github.com/kvesteri/postgresql-audit/blob/91b497ced2e04dd44bb757b02983d2a64a2b1514/postgresql_audit/base.py#L356-L363
2,947
mfcovington/pubmed-lookup
pubmed_lookup/command_line.py
pubmed_citation
def pubmed_citation(args=sys.argv[1:], out=sys.stdout): """Get a citation via the command line using a PubMed ID or PubMed URL""" parser = argparse.ArgumentParser( description='Get a citation using a PubMed ID or PubMed URL') parser.add_argument('query', help='PubMed ID or PubMed URL') parser.add_argument( '-m', '--mini', action='store_true', help='get mini citation') parser.add_argument( '-e', '--email', action='store', help='set user email', default='') args = parser.parse_args(args=args) lookup = PubMedLookup(args.query, args.email) publication = Publication(lookup, resolve_doi=False) if args.mini: out.write(publication.cite_mini() + '\n') else: out.write(publication.cite() + '\n')
python
def pubmed_citation(args=sys.argv[1:], out=sys.stdout): parser = argparse.ArgumentParser( description='Get a citation using a PubMed ID or PubMed URL') parser.add_argument('query', help='PubMed ID or PubMed URL') parser.add_argument( '-m', '--mini', action='store_true', help='get mini citation') parser.add_argument( '-e', '--email', action='store', help='set user email', default='') args = parser.parse_args(args=args) lookup = PubMedLookup(args.query, args.email) publication = Publication(lookup, resolve_doi=False) if args.mini: out.write(publication.cite_mini() + '\n') else: out.write(publication.cite() + '\n')
[ "def", "pubmed_citation", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ",", "out", "=", "sys", ".", "stdout", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Get a citation using a PubMed ID or PubMed URL'", ")", "parser", ".", "add_argument", "(", "'query'", ",", "help", "=", "'PubMed ID or PubMed URL'", ")", "parser", ".", "add_argument", "(", "'-m'", ",", "'--mini'", ",", "action", "=", "'store_true'", ",", "help", "=", "'get mini citation'", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "'--email'", ",", "action", "=", "'store'", ",", "help", "=", "'set user email'", ",", "default", "=", "''", ")", "args", "=", "parser", ".", "parse_args", "(", "args", "=", "args", ")", "lookup", "=", "PubMedLookup", "(", "args", ".", "query", ",", "args", ".", "email", ")", "publication", "=", "Publication", "(", "lookup", ",", "resolve_doi", "=", "False", ")", "if", "args", ".", "mini", ":", "out", ".", "write", "(", "publication", ".", "cite_mini", "(", ")", "+", "'\\n'", ")", "else", ":", "out", ".", "write", "(", "publication", ".", "cite", "(", ")", "+", "'\\n'", ")" ]
Get a citation via the command line using a PubMed ID or PubMed URL
[ "Get", "a", "citation", "via", "the", "command", "line", "using", "a", "PubMed", "ID", "or", "PubMed", "URL" ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/command_line.py#L7-L26
2,948
mfcovington/pubmed-lookup
pubmed_lookup/command_line.py
pubmed_url
def pubmed_url(args=sys.argv[1:], resolve_doi=True, out=sys.stdout): """ Get a publication URL via the command line using a PubMed ID or PubMed URL """ parser = argparse.ArgumentParser( description='Get a publication URL using a PubMed ID or PubMed URL') parser.add_argument('query', help='PubMed ID or PubMed URL') parser.add_argument( '-d', '--doi', action='store_false', help='get DOI URL') parser.add_argument( '-e', '--email', action='store', help='set user email', default='') args = parser.parse_args(args=args) lookup = PubMedLookup(args.query, args.email) publication = Publication(lookup, resolve_doi=args.doi) out.write(publication.url + '\n')
python
def pubmed_url(args=sys.argv[1:], resolve_doi=True, out=sys.stdout): parser = argparse.ArgumentParser( description='Get a publication URL using a PubMed ID or PubMed URL') parser.add_argument('query', help='PubMed ID or PubMed URL') parser.add_argument( '-d', '--doi', action='store_false', help='get DOI URL') parser.add_argument( '-e', '--email', action='store', help='set user email', default='') args = parser.parse_args(args=args) lookup = PubMedLookup(args.query, args.email) publication = Publication(lookup, resolve_doi=args.doi) out.write(publication.url + '\n')
[ "def", "pubmed_url", "(", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", ",", "resolve_doi", "=", "True", ",", "out", "=", "sys", ".", "stdout", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Get a publication URL using a PubMed ID or PubMed URL'", ")", "parser", ".", "add_argument", "(", "'query'", ",", "help", "=", "'PubMed ID or PubMed URL'", ")", "parser", ".", "add_argument", "(", "'-d'", ",", "'--doi'", ",", "action", "=", "'store_false'", ",", "help", "=", "'get DOI URL'", ")", "parser", ".", "add_argument", "(", "'-e'", ",", "'--email'", ",", "action", "=", "'store'", ",", "help", "=", "'set user email'", ",", "default", "=", "''", ")", "args", "=", "parser", ".", "parse_args", "(", "args", "=", "args", ")", "lookup", "=", "PubMedLookup", "(", "args", ".", "query", ",", "args", ".", "email", ")", "publication", "=", "Publication", "(", "lookup", ",", "resolve_doi", "=", "args", ".", "doi", ")", "out", ".", "write", "(", "publication", ".", "url", "+", "'\\n'", ")" ]
Get a publication URL via the command line using a PubMed ID or PubMed URL
[ "Get", "a", "publication", "URL", "via", "the", "command", "line", "using", "a", "PubMed", "ID", "or", "PubMed", "URL" ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/command_line.py#L29-L47
2,949
mfcovington/pubmed-lookup
pubmed_lookup/pubmed_lookup.py
Publication.authors_et_al
def authors_et_al(self, max_authors=5): """ Return string with a truncated author list followed by 'et al.' """ author_list = self._author_list if len(author_list) <= max_authors: authors_et_al = self.authors else: authors_et_al = ", ".join( self._author_list[:max_authors]) + ", et al." return authors_et_al
python
def authors_et_al(self, max_authors=5): author_list = self._author_list if len(author_list) <= max_authors: authors_et_al = self.authors else: authors_et_al = ", ".join( self._author_list[:max_authors]) + ", et al." return authors_et_al
[ "def", "authors_et_al", "(", "self", ",", "max_authors", "=", "5", ")", ":", "author_list", "=", "self", ".", "_author_list", "if", "len", "(", "author_list", ")", "<=", "max_authors", ":", "authors_et_al", "=", "self", ".", "authors", "else", ":", "authors_et_al", "=", "\", \"", ".", "join", "(", "self", ".", "_author_list", "[", ":", "max_authors", "]", ")", "+", "\", et al.\"", "return", "authors_et_al" ]
Return string with a truncated author list followed by 'et al.'
[ "Return", "string", "with", "a", "truncated", "author", "list", "followed", "by", "et", "al", "." ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L48-L58
2,950
mfcovington/pubmed-lookup
pubmed_lookup/pubmed_lookup.py
Publication.parse_abstract
def parse_abstract(xml_dict): """ Parse PubMed XML dictionary to retrieve abstract. """ key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Abstract', 'AbstractText'] abstract_xml = reduce(dict.get, key_path, xml_dict) abstract_paragraphs = [] if isinstance(abstract_xml, str): abstract_paragraphs.append(abstract_xml) elif isinstance(abstract_xml, dict): abstract_text = abstract_xml.get('#text') try: abstract_label = abstract_xml['@Label'] except KeyError: abstract_paragraphs.append(abstract_text) else: abstract_paragraphs.append( "{}: {}".format(abstract_label, abstract_text)) elif isinstance(abstract_xml, list): for abstract_section in abstract_xml: try: abstract_text = abstract_section['#text'] except KeyError: abstract_text = abstract_section try: abstract_label = abstract_section['@Label'] except KeyError: abstract_paragraphs.append(abstract_text) else: abstract_paragraphs.append( "{}: {}".format(abstract_label, abstract_text)) else: raise RuntimeError("Error parsing abstract.") return "\n\n".join(abstract_paragraphs)
python
def parse_abstract(xml_dict): key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Abstract', 'AbstractText'] abstract_xml = reduce(dict.get, key_path, xml_dict) abstract_paragraphs = [] if isinstance(abstract_xml, str): abstract_paragraphs.append(abstract_xml) elif isinstance(abstract_xml, dict): abstract_text = abstract_xml.get('#text') try: abstract_label = abstract_xml['@Label'] except KeyError: abstract_paragraphs.append(abstract_text) else: abstract_paragraphs.append( "{}: {}".format(abstract_label, abstract_text)) elif isinstance(abstract_xml, list): for abstract_section in abstract_xml: try: abstract_text = abstract_section['#text'] except KeyError: abstract_text = abstract_section try: abstract_label = abstract_section['@Label'] except KeyError: abstract_paragraphs.append(abstract_text) else: abstract_paragraphs.append( "{}: {}".format(abstract_label, abstract_text)) else: raise RuntimeError("Error parsing abstract.") return "\n\n".join(abstract_paragraphs)
[ "def", "parse_abstract", "(", "xml_dict", ")", ":", "key_path", "=", "[", "'PubmedArticleSet'", ",", "'PubmedArticle'", ",", "'MedlineCitation'", ",", "'Article'", ",", "'Abstract'", ",", "'AbstractText'", "]", "abstract_xml", "=", "reduce", "(", "dict", ".", "get", ",", "key_path", ",", "xml_dict", ")", "abstract_paragraphs", "=", "[", "]", "if", "isinstance", "(", "abstract_xml", ",", "str", ")", ":", "abstract_paragraphs", ".", "append", "(", "abstract_xml", ")", "elif", "isinstance", "(", "abstract_xml", ",", "dict", ")", ":", "abstract_text", "=", "abstract_xml", ".", "get", "(", "'#text'", ")", "try", ":", "abstract_label", "=", "abstract_xml", "[", "'@Label'", "]", "except", "KeyError", ":", "abstract_paragraphs", ".", "append", "(", "abstract_text", ")", "else", ":", "abstract_paragraphs", ".", "append", "(", "\"{}: {}\"", ".", "format", "(", "abstract_label", ",", "abstract_text", ")", ")", "elif", "isinstance", "(", "abstract_xml", ",", "list", ")", ":", "for", "abstract_section", "in", "abstract_xml", ":", "try", ":", "abstract_text", "=", "abstract_section", "[", "'#text'", "]", "except", "KeyError", ":", "abstract_text", "=", "abstract_section", "try", ":", "abstract_label", "=", "abstract_section", "[", "'@Label'", "]", "except", "KeyError", ":", "abstract_paragraphs", ".", "append", "(", "abstract_text", ")", "else", ":", "abstract_paragraphs", ".", "append", "(", "\"{}: {}\"", ".", "format", "(", "abstract_label", ",", "abstract_text", ")", ")", "else", ":", "raise", "RuntimeError", "(", "\"Error parsing abstract.\"", ")", "return", "\"\\n\\n\"", ".", "join", "(", "abstract_paragraphs", ")" ]
Parse PubMed XML dictionary to retrieve abstract.
[ "Parse", "PubMed", "XML", "dictionary", "to", "retrieve", "abstract", "." ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L107-L148
2,951
mfcovington/pubmed-lookup
pubmed_lookup/pubmed_lookup.py
Publication.get_pubmed_xml
def get_pubmed_xml(self): """ Use a PubMed ID to retrieve PubMed metadata in XML form. """ url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/' \ 'efetch.fcgi?db=pubmed&rettype=abstract&id={}' \ .format(self.pmid) try: response = urlopen(url) except URLError: xml_dict = '' else: xml = response.read().decode() xml_dict = xmltodict.parse(xml) return xml_dict
python
def get_pubmed_xml(self): url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/' \ 'efetch.fcgi?db=pubmed&rettype=abstract&id={}' \ .format(self.pmid) try: response = urlopen(url) except URLError: xml_dict = '' else: xml = response.read().decode() xml_dict = xmltodict.parse(xml) return xml_dict
[ "def", "get_pubmed_xml", "(", "self", ")", ":", "url", "=", "'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/'", "'efetch.fcgi?db=pubmed&rettype=abstract&id={}'", ".", "format", "(", "self", ".", "pmid", ")", "try", ":", "response", "=", "urlopen", "(", "url", ")", "except", "URLError", ":", "xml_dict", "=", "''", "else", ":", "xml", "=", "response", ".", "read", "(", ")", ".", "decode", "(", ")", "xml_dict", "=", "xmltodict", ".", "parse", "(", "xml", ")", "return", "xml_dict" ]
Use a PubMed ID to retrieve PubMed metadata in XML form.
[ "Use", "a", "PubMed", "ID", "to", "retrieve", "PubMed", "metadata", "in", "XML", "form", "." ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L150-L166
2,952
mfcovington/pubmed-lookup
pubmed_lookup/pubmed_lookup.py
Publication.set_abstract
def set_abstract(self, xml_dict): """ If record has an abstract, extract it from PubMed's XML data """ if self.record.get('HasAbstract') == 1 and xml_dict: self.abstract = self.parse_abstract(xml_dict) else: self.abstract = ''
python
def set_abstract(self, xml_dict): if self.record.get('HasAbstract') == 1 and xml_dict: self.abstract = self.parse_abstract(xml_dict) else: self.abstract = ''
[ "def", "set_abstract", "(", "self", ",", "xml_dict", ")", ":", "if", "self", ".", "record", ".", "get", "(", "'HasAbstract'", ")", "==", "1", "and", "xml_dict", ":", "self", ".", "abstract", "=", "self", ".", "parse_abstract", "(", "xml_dict", ")", "else", ":", "self", ".", "abstract", "=", "''" ]
If record has an abstract, extract it from PubMed's XML data
[ "If", "record", "has", "an", "abstract", "extract", "it", "from", "PubMed", "s", "XML", "data" ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L168-L175
2,953
mfcovington/pubmed-lookup
pubmed_lookup/pubmed_lookup.py
Publication.set_article_url
def set_article_url(self, resolve_doi=True): """ If record has a DOI, set article URL based on where the DOI points. """ if 'DOI' in self.record: doi_url = "/".join(['http://dx.doi.org', self.record['DOI']]) if resolve_doi: try: response = urlopen(doi_url) except URLError: self.url = '' else: self.url = response.geturl() else: self.url = doi_url else: self.url = ''
python
def set_article_url(self, resolve_doi=True): if 'DOI' in self.record: doi_url = "/".join(['http://dx.doi.org', self.record['DOI']]) if resolve_doi: try: response = urlopen(doi_url) except URLError: self.url = '' else: self.url = response.geturl() else: self.url = doi_url else: self.url = ''
[ "def", "set_article_url", "(", "self", ",", "resolve_doi", "=", "True", ")", ":", "if", "'DOI'", "in", "self", ".", "record", ":", "doi_url", "=", "\"/\"", ".", "join", "(", "[", "'http://dx.doi.org'", ",", "self", ".", "record", "[", "'DOI'", "]", "]", ")", "if", "resolve_doi", ":", "try", ":", "response", "=", "urlopen", "(", "doi_url", ")", "except", "URLError", ":", "self", ".", "url", "=", "''", "else", ":", "self", ".", "url", "=", "response", ".", "geturl", "(", ")", "else", ":", "self", ".", "url", "=", "doi_url", "else", ":", "self", ".", "url", "=", "''" ]
If record has a DOI, set article URL based on where the DOI points.
[ "If", "record", "has", "a", "DOI", "set", "article", "URL", "based", "on", "where", "the", "DOI", "points", "." ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L177-L195
2,954
mfcovington/pubmed-lookup
pubmed_lookup/pubmed_lookup.py
Publication.set_pub_year_month_day
def set_pub_year_month_day(self, xml_dict): """ Set publication year, month, day from PubMed's XML data """ key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Journal', 'JournalIssue', 'PubDate'] pubdate_xml = reduce(dict.get, key_path, xml_dict) if isinstance(pubdate_xml, dict): self.year = pubdate_xml.get('Year') month_short = pubdate_xml.get('Month') self.day = pubdate_xml.get('Day') try: self.month = datetime.datetime.strptime( month_short, "%b").month except (ValueError, TypeError): self.month = '' else: self.year = '' self.month = '' self.day = ''
python
def set_pub_year_month_day(self, xml_dict): key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Journal', 'JournalIssue', 'PubDate'] pubdate_xml = reduce(dict.get, key_path, xml_dict) if isinstance(pubdate_xml, dict): self.year = pubdate_xml.get('Year') month_short = pubdate_xml.get('Month') self.day = pubdate_xml.get('Day') try: self.month = datetime.datetime.strptime( month_short, "%b").month except (ValueError, TypeError): self.month = '' else: self.year = '' self.month = '' self.day = ''
[ "def", "set_pub_year_month_day", "(", "self", ",", "xml_dict", ")", ":", "key_path", "=", "[", "'PubmedArticleSet'", ",", "'PubmedArticle'", ",", "'MedlineCitation'", ",", "'Article'", ",", "'Journal'", ",", "'JournalIssue'", ",", "'PubDate'", "]", "pubdate_xml", "=", "reduce", "(", "dict", ".", "get", ",", "key_path", ",", "xml_dict", ")", "if", "isinstance", "(", "pubdate_xml", ",", "dict", ")", ":", "self", ".", "year", "=", "pubdate_xml", ".", "get", "(", "'Year'", ")", "month_short", "=", "pubdate_xml", ".", "get", "(", "'Month'", ")", "self", ".", "day", "=", "pubdate_xml", ".", "get", "(", "'Day'", ")", "try", ":", "self", ".", "month", "=", "datetime", ".", "datetime", ".", "strptime", "(", "month_short", ",", "\"%b\"", ")", ".", "month", "except", "(", "ValueError", ",", "TypeError", ")", ":", "self", ".", "month", "=", "''", "else", ":", "self", ".", "year", "=", "''", "self", ".", "month", "=", "''", "self", ".", "day", "=", "''" ]
Set publication year, month, day from PubMed's XML data
[ "Set", "publication", "year", "month", "day", "from", "PubMed", "s", "XML", "data" ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L197-L219
2,955
mfcovington/pubmed-lookup
pubmed_lookup/pubmed_lookup.py
PubMedLookup.get_pubmed_record
def get_pubmed_record(pmid): """Get PubMed record from PubMed ID.""" handle = Entrez.esummary(db="pubmed", id=pmid) record = Entrez.read(handle) return record
python
def get_pubmed_record(pmid): handle = Entrez.esummary(db="pubmed", id=pmid) record = Entrez.read(handle) return record
[ "def", "get_pubmed_record", "(", "pmid", ")", ":", "handle", "=", "Entrez", ".", "esummary", "(", "db", "=", "\"pubmed\"", ",", "id", "=", "pmid", ")", "record", "=", "Entrez", ".", "read", "(", "handle", ")", "return", "record" ]
Get PubMed record from PubMed ID.
[ "Get", "PubMed", "record", "from", "PubMed", "ID", "." ]
b0aa2945b354f0945db73da22dd15ea628212da8
https://github.com/mfcovington/pubmed-lookup/blob/b0aa2945b354f0945db73da22dd15ea628212da8/pubmed_lookup/pubmed_lookup.py#L257-L261
2,956
UCSBarchlab/PyRTL
pyrtl/simulation.py
Simulation._initialize
def _initialize(self, register_value_map=None, memory_value_map=None, default_value=None): """ Sets the wire, register, and memory values to default or as specified. :param register_value_map: is a map of {Register: value}. :param memory_value_map: is a map of maps {Memory: {address: Value}}. :param default_value: is the value that all unspecified registers and memories will default to. If no default_value is specified, it will use the value stored in the object (default to 0) """ if default_value is None: default_value = self.default_value # set registers to their values reg_set = self.block.wirevector_subset(Register) if register_value_map is not None: for r in reg_set: self.value[r] = self.regvalue[r] = register_value_map.get(r, default_value) # set constants to their set values for w in self.block.wirevector_subset(Const): self.value[w] = w.val assert isinstance(w.val, numbers.Integral) # for now # set memories to their passed values for mem_net in self.block.logic_subset('m@'): memid = mem_net.op_param[1].id if memid not in self.memvalue: self.memvalue[memid] = {} if memory_value_map is not None: for (mem, mem_map) in memory_value_map.items(): if isinstance(mem, RomBlock): raise PyrtlError('error, one or more of the memories in the map is a RomBlock') if isinstance(self.block, PostSynthBlock): mem = self.block.mem_map[mem] # pylint: disable=maybe-no-member self.memvalue[mem.id] = mem_map max_addr_val, max_bit_val = 2**mem.addrwidth, 2**mem.bitwidth for (addr, val) in mem_map.items(): if addr < 0 or addr >= max_addr_val: raise PyrtlError('error, address %s in %s outside of bounds' % (str(addr), mem.name)) if val < 0 or val >= max_bit_val: raise PyrtlError('error, %s at %s in %s outside of bounds' % (str(val), str(addr), mem.name)) # set all other variables to default value for w in self.block.wirevector_set: if w not in self.value: self.value[w] = default_value self.ordered_nets = tuple((i for i in self.block)) self.reg_update_nets = tuple((self.block.logic_subset('r'))) self.mem_update_nets = tuple((self.block.logic_subset('@')))
python
def _initialize(self, register_value_map=None, memory_value_map=None, default_value=None): if default_value is None: default_value = self.default_value # set registers to their values reg_set = self.block.wirevector_subset(Register) if register_value_map is not None: for r in reg_set: self.value[r] = self.regvalue[r] = register_value_map.get(r, default_value) # set constants to their set values for w in self.block.wirevector_subset(Const): self.value[w] = w.val assert isinstance(w.val, numbers.Integral) # for now # set memories to their passed values for mem_net in self.block.logic_subset('m@'): memid = mem_net.op_param[1].id if memid not in self.memvalue: self.memvalue[memid] = {} if memory_value_map is not None: for (mem, mem_map) in memory_value_map.items(): if isinstance(mem, RomBlock): raise PyrtlError('error, one or more of the memories in the map is a RomBlock') if isinstance(self.block, PostSynthBlock): mem = self.block.mem_map[mem] # pylint: disable=maybe-no-member self.memvalue[mem.id] = mem_map max_addr_val, max_bit_val = 2**mem.addrwidth, 2**mem.bitwidth for (addr, val) in mem_map.items(): if addr < 0 or addr >= max_addr_val: raise PyrtlError('error, address %s in %s outside of bounds' % (str(addr), mem.name)) if val < 0 or val >= max_bit_val: raise PyrtlError('error, %s at %s in %s outside of bounds' % (str(val), str(addr), mem.name)) # set all other variables to default value for w in self.block.wirevector_set: if w not in self.value: self.value[w] = default_value self.ordered_nets = tuple((i for i in self.block)) self.reg_update_nets = tuple((self.block.logic_subset('r'))) self.mem_update_nets = tuple((self.block.logic_subset('@')))
[ "def", "_initialize", "(", "self", ",", "register_value_map", "=", "None", ",", "memory_value_map", "=", "None", ",", "default_value", "=", "None", ")", ":", "if", "default_value", "is", "None", ":", "default_value", "=", "self", ".", "default_value", "# set registers to their values", "reg_set", "=", "self", ".", "block", ".", "wirevector_subset", "(", "Register", ")", "if", "register_value_map", "is", "not", "None", ":", "for", "r", "in", "reg_set", ":", "self", ".", "value", "[", "r", "]", "=", "self", ".", "regvalue", "[", "r", "]", "=", "register_value_map", ".", "get", "(", "r", ",", "default_value", ")", "# set constants to their set values", "for", "w", "in", "self", ".", "block", ".", "wirevector_subset", "(", "Const", ")", ":", "self", ".", "value", "[", "w", "]", "=", "w", ".", "val", "assert", "isinstance", "(", "w", ".", "val", ",", "numbers", ".", "Integral", ")", "# for now", "# set memories to their passed values", "for", "mem_net", "in", "self", ".", "block", ".", "logic_subset", "(", "'m@'", ")", ":", "memid", "=", "mem_net", ".", "op_param", "[", "1", "]", ".", "id", "if", "memid", "not", "in", "self", ".", "memvalue", ":", "self", ".", "memvalue", "[", "memid", "]", "=", "{", "}", "if", "memory_value_map", "is", "not", "None", ":", "for", "(", "mem", ",", "mem_map", ")", "in", "memory_value_map", ".", "items", "(", ")", ":", "if", "isinstance", "(", "mem", ",", "RomBlock", ")", ":", "raise", "PyrtlError", "(", "'error, one or more of the memories in the map is a RomBlock'", ")", "if", "isinstance", "(", "self", ".", "block", ",", "PostSynthBlock", ")", ":", "mem", "=", "self", ".", "block", ".", "mem_map", "[", "mem", "]", "# pylint: disable=maybe-no-member", "self", ".", "memvalue", "[", "mem", ".", "id", "]", "=", "mem_map", "max_addr_val", ",", "max_bit_val", "=", "2", "**", "mem", ".", "addrwidth", ",", "2", "**", "mem", ".", "bitwidth", "for", "(", "addr", ",", "val", ")", "in", "mem_map", ".", "items", "(", ")", ":", "if", "addr", "<", "0", "or", "addr", ">=", "max_addr_val", ":", "raise", "PyrtlError", "(", "'error, address %s in %s outside of bounds'", "%", "(", "str", "(", "addr", ")", ",", "mem", ".", "name", ")", ")", "if", "val", "<", "0", "or", "val", ">=", "max_bit_val", ":", "raise", "PyrtlError", "(", "'error, %s at %s in %s outside of bounds'", "%", "(", "str", "(", "val", ")", ",", "str", "(", "addr", ")", ",", "mem", ".", "name", ")", ")", "# set all other variables to default value", "for", "w", "in", "self", ".", "block", ".", "wirevector_set", ":", "if", "w", "not", "in", "self", ".", "value", ":", "self", ".", "value", "[", "w", "]", "=", "default_value", "self", ".", "ordered_nets", "=", "tuple", "(", "(", "i", "for", "i", "in", "self", ".", "block", ")", ")", "self", ".", "reg_update_nets", "=", "tuple", "(", "(", "self", ".", "block", ".", "logic_subset", "(", "'r'", ")", ")", ")", "self", ".", "mem_update_nets", "=", "tuple", "(", "(", "self", ".", "block", ".", "logic_subset", "(", "'@'", ")", ")", ")" ]
Sets the wire, register, and memory values to default or as specified. :param register_value_map: is a map of {Register: value}. :param memory_value_map: is a map of maps {Memory: {address: Value}}. :param default_value: is the value that all unspecified registers and memories will default to. If no default_value is specified, it will use the value stored in the object (default to 0)
[ "Sets", "the", "wire", "register", "and", "memory", "values", "to", "default", "or", "as", "specified", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L96-L150
2,957
UCSBarchlab/PyRTL
pyrtl/simulation.py
Simulation.step
def step(self, provided_inputs): """ Take the simulation forward one cycle :param provided_inputs: a dictionary mapping wirevectors to their values for this step All input wires must be in the provided_inputs in order for the simulation to accept these values Example: if we have inputs named 'a' and 'x', we can call: sim.step({'a': 1, 'x': 23}) to simulate a cycle with values 1 and 23 respectively """ # Check that all Input have a corresponding provided_input input_set = self.block.wirevector_subset(Input) supplied_inputs = set() for i in provided_inputs: if isinstance(i, WireVector): name = i.name else: name = i sim_wire = self.block.wirevector_by_name[name] if sim_wire not in input_set: raise PyrtlError( 'step provided a value for input for "%s" which is ' 'not a known input ' % name) if not isinstance(provided_inputs[i], numbers.Integral) or provided_inputs[i] < 0: raise PyrtlError( 'step provided an input "%s" which is not a valid ' 'positive integer' % provided_inputs[i]) if len(bin(provided_inputs[i]))-2 > sim_wire.bitwidth: raise PyrtlError( 'the bitwidth for "%s" is %d, but the provided input ' '%d requires %d bits to represent' % (name, sim_wire.bitwidth, provided_inputs[i], len(bin(provided_inputs[i]))-2)) self.value[sim_wire] = provided_inputs[i] supplied_inputs.add(sim_wire) # Check that only inputs are specified, and set the values if input_set != supplied_inputs: for i in input_set.difference(supplied_inputs): raise PyrtlError('Input "%s" has no input value specified' % i.name) self.value.update(self.regvalue) # apply register updates from previous step for net in self.ordered_nets: self._execute(net) # Do all of the mem operations based off the new values changed in _execute() for net in self.mem_update_nets: self._mem_update(net) # at the end of the step, record the values to the trace # print self.value # Helpful Debug Print if self.tracer is not None: self.tracer.add_step(self.value) # Do all of the reg updates based off of the new values for net in self.reg_update_nets: argval = self.value[net.args[0]] self.regvalue[net.dests[0]] = self._sanitize(argval, net.dests[0]) # finally, if any of the rtl_assert assertions are failing then we should # raise the appropriate exceptions check_rtl_assertions(self)
python
def step(self, provided_inputs): # Check that all Input have a corresponding provided_input input_set = self.block.wirevector_subset(Input) supplied_inputs = set() for i in provided_inputs: if isinstance(i, WireVector): name = i.name else: name = i sim_wire = self.block.wirevector_by_name[name] if sim_wire not in input_set: raise PyrtlError( 'step provided a value for input for "%s" which is ' 'not a known input ' % name) if not isinstance(provided_inputs[i], numbers.Integral) or provided_inputs[i] < 0: raise PyrtlError( 'step provided an input "%s" which is not a valid ' 'positive integer' % provided_inputs[i]) if len(bin(provided_inputs[i]))-2 > sim_wire.bitwidth: raise PyrtlError( 'the bitwidth for "%s" is %d, but the provided input ' '%d requires %d bits to represent' % (name, sim_wire.bitwidth, provided_inputs[i], len(bin(provided_inputs[i]))-2)) self.value[sim_wire] = provided_inputs[i] supplied_inputs.add(sim_wire) # Check that only inputs are specified, and set the values if input_set != supplied_inputs: for i in input_set.difference(supplied_inputs): raise PyrtlError('Input "%s" has no input value specified' % i.name) self.value.update(self.regvalue) # apply register updates from previous step for net in self.ordered_nets: self._execute(net) # Do all of the mem operations based off the new values changed in _execute() for net in self.mem_update_nets: self._mem_update(net) # at the end of the step, record the values to the trace # print self.value # Helpful Debug Print if self.tracer is not None: self.tracer.add_step(self.value) # Do all of the reg updates based off of the new values for net in self.reg_update_nets: argval = self.value[net.args[0]] self.regvalue[net.dests[0]] = self._sanitize(argval, net.dests[0]) # finally, if any of the rtl_assert assertions are failing then we should # raise the appropriate exceptions check_rtl_assertions(self)
[ "def", "step", "(", "self", ",", "provided_inputs", ")", ":", "# Check that all Input have a corresponding provided_input", "input_set", "=", "self", ".", "block", ".", "wirevector_subset", "(", "Input", ")", "supplied_inputs", "=", "set", "(", ")", "for", "i", "in", "provided_inputs", ":", "if", "isinstance", "(", "i", ",", "WireVector", ")", ":", "name", "=", "i", ".", "name", "else", ":", "name", "=", "i", "sim_wire", "=", "self", ".", "block", ".", "wirevector_by_name", "[", "name", "]", "if", "sim_wire", "not", "in", "input_set", ":", "raise", "PyrtlError", "(", "'step provided a value for input for \"%s\" which is '", "'not a known input '", "%", "name", ")", "if", "not", "isinstance", "(", "provided_inputs", "[", "i", "]", ",", "numbers", ".", "Integral", ")", "or", "provided_inputs", "[", "i", "]", "<", "0", ":", "raise", "PyrtlError", "(", "'step provided an input \"%s\" which is not a valid '", "'positive integer'", "%", "provided_inputs", "[", "i", "]", ")", "if", "len", "(", "bin", "(", "provided_inputs", "[", "i", "]", ")", ")", "-", "2", ">", "sim_wire", ".", "bitwidth", ":", "raise", "PyrtlError", "(", "'the bitwidth for \"%s\" is %d, but the provided input '", "'%d requires %d bits to represent'", "%", "(", "name", ",", "sim_wire", ".", "bitwidth", ",", "provided_inputs", "[", "i", "]", ",", "len", "(", "bin", "(", "provided_inputs", "[", "i", "]", ")", ")", "-", "2", ")", ")", "self", ".", "value", "[", "sim_wire", "]", "=", "provided_inputs", "[", "i", "]", "supplied_inputs", ".", "add", "(", "sim_wire", ")", "# Check that only inputs are specified, and set the values", "if", "input_set", "!=", "supplied_inputs", ":", "for", "i", "in", "input_set", ".", "difference", "(", "supplied_inputs", ")", ":", "raise", "PyrtlError", "(", "'Input \"%s\" has no input value specified'", "%", "i", ".", "name", ")", "self", ".", "value", ".", "update", "(", "self", ".", "regvalue", ")", "# apply register updates from previous step", "for", "net", "in", "self", ".", "ordered_nets", ":", "self", ".", "_execute", "(", "net", ")", "# Do all of the mem operations based off the new values changed in _execute()", "for", "net", "in", "self", ".", "mem_update_nets", ":", "self", ".", "_mem_update", "(", "net", ")", "# at the end of the step, record the values to the trace", "# print self.value # Helpful Debug Print", "if", "self", ".", "tracer", "is", "not", "None", ":", "self", ".", "tracer", ".", "add_step", "(", "self", ".", "value", ")", "# Do all of the reg updates based off of the new values", "for", "net", "in", "self", ".", "reg_update_nets", ":", "argval", "=", "self", ".", "value", "[", "net", ".", "args", "[", "0", "]", "]", "self", ".", "regvalue", "[", "net", ".", "dests", "[", "0", "]", "]", "=", "self", ".", "_sanitize", "(", "argval", ",", "net", ".", "dests", "[", "0", "]", ")", "# finally, if any of the rtl_assert assertions are failing then we should", "# raise the appropriate exceptions", "check_rtl_assertions", "(", "self", ")" ]
Take the simulation forward one cycle :param provided_inputs: a dictionary mapping wirevectors to their values for this step All input wires must be in the provided_inputs in order for the simulation to accept these values Example: if we have inputs named 'a' and 'x', we can call: sim.step({'a': 1, 'x': 23}) to simulate a cycle with values 1 and 23 respectively
[ "Take", "the", "simulation", "forward", "one", "cycle" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L152-L218
2,958
UCSBarchlab/PyRTL
pyrtl/simulation.py
Simulation._execute
def _execute(self, net): """Handle the combinational logic update rules for the given net. This function, along with edge_update, defined the semantics of the primitive ops. Function updates self.value accordingly. """ if net.op in 'r@': return # registers and memory write ports have no logic function elif net.op in self.simple_func: argvals = (self.value[arg] for arg in net.args) result = self.simple_func[net.op](*argvals) elif net.op == 'c': result = 0 for arg in net.args: result = result << len(arg) result = result | self.value[arg] elif net.op == 's': result = 0 source = self.value[net.args[0]] for b in net.op_param[::-1]: result = (result << 1) | (0x1 & (source >> b)) elif net.op == 'm': # memories act async for reads memid = net.op_param[0] mem = net.op_param[1] read_addr = self.value[net.args[0]] if isinstance(mem, RomBlock): result = mem._get_read_data(read_addr) else: result = self.memvalue[memid].get(read_addr, self.default_value) else: raise PyrtlInternalError('error, unknown op type') self.value[net.dests[0]] = self._sanitize(result, net.dests[0])
python
def _execute(self, net): if net.op in 'r@': return # registers and memory write ports have no logic function elif net.op in self.simple_func: argvals = (self.value[arg] for arg in net.args) result = self.simple_func[net.op](*argvals) elif net.op == 'c': result = 0 for arg in net.args: result = result << len(arg) result = result | self.value[arg] elif net.op == 's': result = 0 source = self.value[net.args[0]] for b in net.op_param[::-1]: result = (result << 1) | (0x1 & (source >> b)) elif net.op == 'm': # memories act async for reads memid = net.op_param[0] mem = net.op_param[1] read_addr = self.value[net.args[0]] if isinstance(mem, RomBlock): result = mem._get_read_data(read_addr) else: result = self.memvalue[memid].get(read_addr, self.default_value) else: raise PyrtlInternalError('error, unknown op type') self.value[net.dests[0]] = self._sanitize(result, net.dests[0])
[ "def", "_execute", "(", "self", ",", "net", ")", ":", "if", "net", ".", "op", "in", "'r@'", ":", "return", "# registers and memory write ports have no logic function", "elif", "net", ".", "op", "in", "self", ".", "simple_func", ":", "argvals", "=", "(", "self", ".", "value", "[", "arg", "]", "for", "arg", "in", "net", ".", "args", ")", "result", "=", "self", ".", "simple_func", "[", "net", ".", "op", "]", "(", "*", "argvals", ")", "elif", "net", ".", "op", "==", "'c'", ":", "result", "=", "0", "for", "arg", "in", "net", ".", "args", ":", "result", "=", "result", "<<", "len", "(", "arg", ")", "result", "=", "result", "|", "self", ".", "value", "[", "arg", "]", "elif", "net", ".", "op", "==", "'s'", ":", "result", "=", "0", "source", "=", "self", ".", "value", "[", "net", ".", "args", "[", "0", "]", "]", "for", "b", "in", "net", ".", "op_param", "[", ":", ":", "-", "1", "]", ":", "result", "=", "(", "result", "<<", "1", ")", "|", "(", "0x1", "&", "(", "source", ">>", "b", ")", ")", "elif", "net", ".", "op", "==", "'m'", ":", "# memories act async for reads", "memid", "=", "net", ".", "op_param", "[", "0", "]", "mem", "=", "net", ".", "op_param", "[", "1", "]", "read_addr", "=", "self", ".", "value", "[", "net", ".", "args", "[", "0", "]", "]", "if", "isinstance", "(", "mem", ",", "RomBlock", ")", ":", "result", "=", "mem", ".", "_get_read_data", "(", "read_addr", ")", "else", ":", "result", "=", "self", ".", "memvalue", "[", "memid", "]", ".", "get", "(", "read_addr", ",", "self", ".", "default_value", ")", "else", ":", "raise", "PyrtlInternalError", "(", "'error, unknown op type'", ")", "self", ".", "value", "[", "net", ".", "dests", "[", "0", "]", "]", "=", "self", ".", "_sanitize", "(", "result", ",", "net", ".", "dests", "[", "0", "]", ")" ]
Handle the combinational logic update rules for the given net. This function, along with edge_update, defined the semantics of the primitive ops. Function updates self.value accordingly.
[ "Handle", "the", "combinational", "logic", "update", "rules", "for", "the", "given", "net", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L253-L286
2,959
UCSBarchlab/PyRTL
pyrtl/simulation.py
FastSimulation.step
def step(self, provided_inputs): """ Run the simulation for a cycle :param provided_inputs: a dictionary mapping WireVectors (or their names) to their values for this step eg: {wire: 3, "wire_name": 17} """ # validate_inputs for wire, value in provided_inputs.items(): wire = self.block.get_wirevector_by_name(wire) if isinstance(wire, str) else wire if value > wire.bitmask or value < 0: raise PyrtlError("Wire {} has value {} which cannot be represented" " using its bitwidth".format(wire, value)) # building the simulation data ins = {self._to_name(wire): value for wire, value in provided_inputs.items()} ins.update(self.regs) ins.update(self.mems) # propagate through logic self.regs, self.outs, mem_writes = self.sim_func(ins) for mem, addr, value in mem_writes: self.mems[mem][addr] = value # for tracer compatibility self.context = self.outs.copy() self.context.update(ins) # also gets old register values if self.tracer is not None: self.tracer.add_fast_step(self) # check the rtl assertions check_rtl_assertions(self)
python
def step(self, provided_inputs): # validate_inputs for wire, value in provided_inputs.items(): wire = self.block.get_wirevector_by_name(wire) if isinstance(wire, str) else wire if value > wire.bitmask or value < 0: raise PyrtlError("Wire {} has value {} which cannot be represented" " using its bitwidth".format(wire, value)) # building the simulation data ins = {self._to_name(wire): value for wire, value in provided_inputs.items()} ins.update(self.regs) ins.update(self.mems) # propagate through logic self.regs, self.outs, mem_writes = self.sim_func(ins) for mem, addr, value in mem_writes: self.mems[mem][addr] = value # for tracer compatibility self.context = self.outs.copy() self.context.update(ins) # also gets old register values if self.tracer is not None: self.tracer.add_fast_step(self) # check the rtl assertions check_rtl_assertions(self)
[ "def", "step", "(", "self", ",", "provided_inputs", ")", ":", "# validate_inputs", "for", "wire", ",", "value", "in", "provided_inputs", ".", "items", "(", ")", ":", "wire", "=", "self", ".", "block", ".", "get_wirevector_by_name", "(", "wire", ")", "if", "isinstance", "(", "wire", ",", "str", ")", "else", "wire", "if", "value", ">", "wire", ".", "bitmask", "or", "value", "<", "0", ":", "raise", "PyrtlError", "(", "\"Wire {} has value {} which cannot be represented\"", "\" using its bitwidth\"", ".", "format", "(", "wire", ",", "value", ")", ")", "# building the simulation data", "ins", "=", "{", "self", ".", "_to_name", "(", "wire", ")", ":", "value", "for", "wire", ",", "value", "in", "provided_inputs", ".", "items", "(", ")", "}", "ins", ".", "update", "(", "self", ".", "regs", ")", "ins", ".", "update", "(", "self", ".", "mems", ")", "# propagate through logic", "self", ".", "regs", ",", "self", ".", "outs", ",", "mem_writes", "=", "self", ".", "sim_func", "(", "ins", ")", "for", "mem", ",", "addr", ",", "value", "in", "mem_writes", ":", "self", ".", "mems", "[", "mem", "]", "[", "addr", "]", "=", "value", "# for tracer compatibility", "self", ".", "context", "=", "self", ".", "outs", ".", "copy", "(", ")", "self", ".", "context", ".", "update", "(", "ins", ")", "# also gets old register values", "if", "self", ".", "tracer", "is", "not", "None", ":", "self", ".", "tracer", ".", "add_fast_step", "(", "self", ")", "# check the rtl assertions", "check_rtl_assertions", "(", "self", ")" ]
Run the simulation for a cycle :param provided_inputs: a dictionary mapping WireVectors (or their names) to their values for this step eg: {wire: 3, "wire_name": 17}
[ "Run", "the", "simulation", "for", "a", "cycle" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L404-L436
2,960
UCSBarchlab/PyRTL
pyrtl/simulation.py
FastSimulation.inspect_mem
def inspect_mem(self, mem): """ Get the values in a map during the current simulation cycle. :param mem: the memory to inspect :return: {address: value} Note that this returns the current memory state. Modifying the dictonary will also modify the state in the simulator """ if isinstance(mem, RomBlock): raise PyrtlError("ROM blocks are not stored in the simulation object") return self.mems[self._mem_varname(mem)]
python
def inspect_mem(self, mem): if isinstance(mem, RomBlock): raise PyrtlError("ROM blocks are not stored in the simulation object") return self.mems[self._mem_varname(mem)]
[ "def", "inspect_mem", "(", "self", ",", "mem", ")", ":", "if", "isinstance", "(", "mem", ",", "RomBlock", ")", ":", "raise", "PyrtlError", "(", "\"ROM blocks are not stored in the simulation object\"", ")", "return", "self", ".", "mems", "[", "self", ".", "_mem_varname", "(", "mem", ")", "]" ]
Get the values in a map during the current simulation cycle. :param mem: the memory to inspect :return: {address: value} Note that this returns the current memory state. Modifying the dictonary will also modify the state in the simulator
[ "Get", "the", "values", "in", "a", "map", "during", "the", "current", "simulation", "cycle", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L457-L468
2,961
UCSBarchlab/PyRTL
pyrtl/simulation.py
FastSimulation._arg_varname
def _arg_varname(self, wire): """ Input, Const, and Registers have special input values """ if isinstance(wire, (Input, Register)): return 'd[' + repr(wire.name) + ']' # passed in elif isinstance(wire, Const): return str(wire.val) # hardcoded else: return self._varname(wire)
python
def _arg_varname(self, wire): if isinstance(wire, (Input, Register)): return 'd[' + repr(wire.name) + ']' # passed in elif isinstance(wire, Const): return str(wire.val) # hardcoded else: return self._varname(wire)
[ "def", "_arg_varname", "(", "self", ",", "wire", ")", ":", "if", "isinstance", "(", "wire", ",", "(", "Input", ",", "Register", ")", ")", ":", "return", "'d['", "+", "repr", "(", "wire", ".", "name", ")", "+", "']'", "# passed in", "elif", "isinstance", "(", "wire", ",", "Const", ")", ":", "return", "str", "(", "wire", ".", "val", ")", "# hardcoded", "else", ":", "return", "self", ".", "_varname", "(", "wire", ")" ]
Input, Const, and Registers have special input values
[ "Input", "Const", "and", "Registers", "have", "special", "input", "values" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L483-L492
2,962
UCSBarchlab/PyRTL
pyrtl/simulation.py
_WaveRendererBase._render_val_with_prev
def _render_val_with_prev(self, w, n, current_val, symbol_len): """Return a string encoding the given value in a waveform. :param w: The WireVector we are rendering to a waveform :param n: An integer from 0 to segment_len-1 :param current_val: the value to be rendered :param symbol_len: and integer for how big to draw the current value Returns a string of printed length symbol_len that will draw the representation of current_val. The input prior_val is used to render transitions. """ sl = symbol_len-1 if len(w) > 1: out = self._revstart if current_val != self.prior_val: out += self._x + hex(current_val).rstrip('L').ljust(sl)[:sl] elif n == 0: out += hex(current_val).rstrip('L').ljust(symbol_len)[:symbol_len] else: out += ' '*symbol_len out += self._revstop else: pretty_map = { (0, 0): self._low + self._low * sl, (0, 1): self._up + self._high * sl, (1, 0): self._down + self._low * sl, (1, 1): self._high + self._high * sl, } out = pretty_map[(self.prior_val, current_val)] return out
python
def _render_val_with_prev(self, w, n, current_val, symbol_len): sl = symbol_len-1 if len(w) > 1: out = self._revstart if current_val != self.prior_val: out += self._x + hex(current_val).rstrip('L').ljust(sl)[:sl] elif n == 0: out += hex(current_val).rstrip('L').ljust(symbol_len)[:symbol_len] else: out += ' '*symbol_len out += self._revstop else: pretty_map = { (0, 0): self._low + self._low * sl, (0, 1): self._up + self._high * sl, (1, 0): self._down + self._low * sl, (1, 1): self._high + self._high * sl, } out = pretty_map[(self.prior_val, current_val)] return out
[ "def", "_render_val_with_prev", "(", "self", ",", "w", ",", "n", ",", "current_val", ",", "symbol_len", ")", ":", "sl", "=", "symbol_len", "-", "1", "if", "len", "(", "w", ")", ">", "1", ":", "out", "=", "self", ".", "_revstart", "if", "current_val", "!=", "self", ".", "prior_val", ":", "out", "+=", "self", ".", "_x", "+", "hex", "(", "current_val", ")", ".", "rstrip", "(", "'L'", ")", ".", "ljust", "(", "sl", ")", "[", ":", "sl", "]", "elif", "n", "==", "0", ":", "out", "+=", "hex", "(", "current_val", ")", ".", "rstrip", "(", "'L'", ")", ".", "ljust", "(", "symbol_len", ")", "[", ":", "symbol_len", "]", "else", ":", "out", "+=", "' '", "*", "symbol_len", "out", "+=", "self", ".", "_revstop", "else", ":", "pretty_map", "=", "{", "(", "0", ",", "0", ")", ":", "self", ".", "_low", "+", "self", ".", "_low", "*", "sl", ",", "(", "0", ",", "1", ")", ":", "self", ".", "_up", "+", "self", ".", "_high", "*", "sl", ",", "(", "1", ",", "0", ")", ":", "self", ".", "_down", "+", "self", ".", "_low", "*", "sl", ",", "(", "1", ",", "1", ")", ":", "self", ".", "_high", "+", "self", ".", "_high", "*", "sl", ",", "}", "out", "=", "pretty_map", "[", "(", "self", ".", "prior_val", ",", "current_val", ")", "]", "return", "out" ]
Return a string encoding the given value in a waveform. :param w: The WireVector we are rendering to a waveform :param n: An integer from 0 to segment_len-1 :param current_val: the value to be rendered :param symbol_len: and integer for how big to draw the current value Returns a string of printed length symbol_len that will draw the representation of current_val. The input prior_val is used to render transitions.
[ "Return", "a", "string", "encoding", "the", "given", "value", "in", "a", "waveform", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L664-L694
2,963
UCSBarchlab/PyRTL
pyrtl/simulation.py
SimulationTrace.add_step
def add_step(self, value_map): """ Add the values in value_map to the end of the trace. """ if len(self.trace) == 0: raise PyrtlError('error, simulation trace needs at least 1 signal to track ' '(by default, unnamed signals are not traced -- try either passing ' 'a name to a WireVector or setting a "wirevector_subset" option)') for wire in self.trace: tracelist = self.trace[wire] wirevec = self._wires[wire] tracelist.append(value_map[wirevec])
python
def add_step(self, value_map): if len(self.trace) == 0: raise PyrtlError('error, simulation trace needs at least 1 signal to track ' '(by default, unnamed signals are not traced -- try either passing ' 'a name to a WireVector or setting a "wirevector_subset" option)') for wire in self.trace: tracelist = self.trace[wire] wirevec = self._wires[wire] tracelist.append(value_map[wirevec])
[ "def", "add_step", "(", "self", ",", "value_map", ")", ":", "if", "len", "(", "self", ".", "trace", ")", "==", "0", ":", "raise", "PyrtlError", "(", "'error, simulation trace needs at least 1 signal to track '", "'(by default, unnamed signals are not traced -- try either passing '", "'a name to a WireVector or setting a \"wirevector_subset\" option)'", ")", "for", "wire", "in", "self", ".", "trace", ":", "tracelist", "=", "self", ".", "trace", "[", "wire", "]", "wirevec", "=", "self", ".", "_wires", "[", "wire", "]", "tracelist", ".", "append", "(", "value_map", "[", "wirevec", "]", ")" ]
Add the values in value_map to the end of the trace.
[ "Add", "the", "values", "in", "value_map", "to", "the", "end", "of", "the", "trace", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L794-L803
2,964
UCSBarchlab/PyRTL
pyrtl/simulation.py
SimulationTrace.add_fast_step
def add_fast_step(self, fastsim): """ Add the fastsim context to the trace. """ for wire_name in self.trace: self.trace[wire_name].append(fastsim.context[wire_name])
python
def add_fast_step(self, fastsim): for wire_name in self.trace: self.trace[wire_name].append(fastsim.context[wire_name])
[ "def", "add_fast_step", "(", "self", ",", "fastsim", ")", ":", "for", "wire_name", "in", "self", ".", "trace", ":", "self", ".", "trace", "[", "wire_name", "]", ".", "append", "(", "fastsim", ".", "context", "[", "wire_name", "]", ")" ]
Add the fastsim context to the trace.
[ "Add", "the", "fastsim", "context", "to", "the", "trace", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L810-L813
2,965
UCSBarchlab/PyRTL
pyrtl/simulation.py
SimulationTrace.print_vcd
def print_vcd(self, file=sys.stdout, include_clock=False): """ Print the trace out as a VCD File for use in other tools. :param file: file to open and output vcd dump to. :param include_clock: boolean specifying if the implicit clk should be included. Dumps the current trace to file as a "value change dump" file. The file parameter defaults to _stdout_ and the include_clock defaults to True. Examples :: sim_trace.print_vcd() sim_trace.print_vcd("my_waveform.vcd", include_clock=False) """ # dump header info # file_timestamp = time.strftime("%a, %d %b %Y %H:%M:%S (UTC/GMT)", time.gmtime()) # print >>file, " ".join(["$date", file_timestamp, "$end"]) self.internal_names = _VerilogSanitizer('_vcd_tmp_') for wire in self.wires_to_track: self.internal_names.make_valid_string(wire.name) def _varname(wireName): """ Converts WireVector names to internal names """ return self.internal_names[wireName] print(' '.join(['$timescale', '1ns', '$end']), file=file) print(' '.join(['$scope', 'module logic', '$end']), file=file) def print_trace_strs(time): for wn in sorted(self.trace, key=_trace_sort_key): print(' '.join([str(bin(self.trace[wn][time]))[1:], _varname(wn)]), file=file) # dump variables if include_clock: print(' '.join(['$var', 'wire', '1', 'clk', 'clk', '$end']), file=file) for wn in sorted(self.trace, key=_trace_sort_key): print(' '.join(['$var', 'wire', str(self._wires[wn].bitwidth), _varname(wn), _varname(wn), '$end']), file=file) print(' '.join(['$upscope', '$end']), file=file) print(' '.join(['$enddefinitions', '$end']), file=file) print(' '.join(['$dumpvars']), file=file) print_trace_strs(0) print(' '.join(['$end']), file=file) # dump values endtime = max([len(self.trace[w]) for w in self.trace]) for timestamp in range(endtime): print(''.join(['#', str(timestamp*10)]), file=file) print_trace_strs(timestamp) if include_clock: print('b1 clk', file=file) print('', file=file) print(''.join(['#', str(timestamp*10+5)]), file=file) print('b0 clk', file=file) print('', file=file) print(''.join(['#', str(endtime*10)]), file=file) file.flush()
python
def print_vcd(self, file=sys.stdout, include_clock=False): # dump header info # file_timestamp = time.strftime("%a, %d %b %Y %H:%M:%S (UTC/GMT)", time.gmtime()) # print >>file, " ".join(["$date", file_timestamp, "$end"]) self.internal_names = _VerilogSanitizer('_vcd_tmp_') for wire in self.wires_to_track: self.internal_names.make_valid_string(wire.name) def _varname(wireName): """ Converts WireVector names to internal names """ return self.internal_names[wireName] print(' '.join(['$timescale', '1ns', '$end']), file=file) print(' '.join(['$scope', 'module logic', '$end']), file=file) def print_trace_strs(time): for wn in sorted(self.trace, key=_trace_sort_key): print(' '.join([str(bin(self.trace[wn][time]))[1:], _varname(wn)]), file=file) # dump variables if include_clock: print(' '.join(['$var', 'wire', '1', 'clk', 'clk', '$end']), file=file) for wn in sorted(self.trace, key=_trace_sort_key): print(' '.join(['$var', 'wire', str(self._wires[wn].bitwidth), _varname(wn), _varname(wn), '$end']), file=file) print(' '.join(['$upscope', '$end']), file=file) print(' '.join(['$enddefinitions', '$end']), file=file) print(' '.join(['$dumpvars']), file=file) print_trace_strs(0) print(' '.join(['$end']), file=file) # dump values endtime = max([len(self.trace[w]) for w in self.trace]) for timestamp in range(endtime): print(''.join(['#', str(timestamp*10)]), file=file) print_trace_strs(timestamp) if include_clock: print('b1 clk', file=file) print('', file=file) print(''.join(['#', str(timestamp*10+5)]), file=file) print('b0 clk', file=file) print('', file=file) print(''.join(['#', str(endtime*10)]), file=file) file.flush()
[ "def", "print_vcd", "(", "self", ",", "file", "=", "sys", ".", "stdout", ",", "include_clock", "=", "False", ")", ":", "# dump header info", "# file_timestamp = time.strftime(\"%a, %d %b %Y %H:%M:%S (UTC/GMT)\", time.gmtime())", "# print >>file, \" \".join([\"$date\", file_timestamp, \"$end\"])", "self", ".", "internal_names", "=", "_VerilogSanitizer", "(", "'_vcd_tmp_'", ")", "for", "wire", "in", "self", ".", "wires_to_track", ":", "self", ".", "internal_names", ".", "make_valid_string", "(", "wire", ".", "name", ")", "def", "_varname", "(", "wireName", ")", ":", "\"\"\" Converts WireVector names to internal names \"\"\"", "return", "self", ".", "internal_names", "[", "wireName", "]", "print", "(", "' '", ".", "join", "(", "[", "'$timescale'", ",", "'1ns'", ",", "'$end'", "]", ")", ",", "file", "=", "file", ")", "print", "(", "' '", ".", "join", "(", "[", "'$scope'", ",", "'module logic'", ",", "'$end'", "]", ")", ",", "file", "=", "file", ")", "def", "print_trace_strs", "(", "time", ")", ":", "for", "wn", "in", "sorted", "(", "self", ".", "trace", ",", "key", "=", "_trace_sort_key", ")", ":", "print", "(", "' '", ".", "join", "(", "[", "str", "(", "bin", "(", "self", ".", "trace", "[", "wn", "]", "[", "time", "]", ")", ")", "[", "1", ":", "]", ",", "_varname", "(", "wn", ")", "]", ")", ",", "file", "=", "file", ")", "# dump variables", "if", "include_clock", ":", "print", "(", "' '", ".", "join", "(", "[", "'$var'", ",", "'wire'", ",", "'1'", ",", "'clk'", ",", "'clk'", ",", "'$end'", "]", ")", ",", "file", "=", "file", ")", "for", "wn", "in", "sorted", "(", "self", ".", "trace", ",", "key", "=", "_trace_sort_key", ")", ":", "print", "(", "' '", ".", "join", "(", "[", "'$var'", ",", "'wire'", ",", "str", "(", "self", ".", "_wires", "[", "wn", "]", ".", "bitwidth", ")", ",", "_varname", "(", "wn", ")", ",", "_varname", "(", "wn", ")", ",", "'$end'", "]", ")", ",", "file", "=", "file", ")", "print", "(", "' '", ".", "join", "(", "[", "'$upscope'", ",", "'$end'", "]", ")", ",", "file", "=", "file", ")", "print", "(", "' '", ".", "join", "(", "[", "'$enddefinitions'", ",", "'$end'", "]", ")", ",", "file", "=", "file", ")", "print", "(", "' '", ".", "join", "(", "[", "'$dumpvars'", "]", ")", ",", "file", "=", "file", ")", "print_trace_strs", "(", "0", ")", "print", "(", "' '", ".", "join", "(", "[", "'$end'", "]", ")", ",", "file", "=", "file", ")", "# dump values", "endtime", "=", "max", "(", "[", "len", "(", "self", ".", "trace", "[", "w", "]", ")", "for", "w", "in", "self", ".", "trace", "]", ")", "for", "timestamp", "in", "range", "(", "endtime", ")", ":", "print", "(", "''", ".", "join", "(", "[", "'#'", ",", "str", "(", "timestamp", "*", "10", ")", "]", ")", ",", "file", "=", "file", ")", "print_trace_strs", "(", "timestamp", ")", "if", "include_clock", ":", "print", "(", "'b1 clk'", ",", "file", "=", "file", ")", "print", "(", "''", ",", "file", "=", "file", ")", "print", "(", "''", ".", "join", "(", "[", "'#'", ",", "str", "(", "timestamp", "*", "10", "+", "5", ")", "]", ")", ",", "file", "=", "file", ")", "print", "(", "'b0 clk'", ",", "file", "=", "file", ")", "print", "(", "''", ",", "file", "=", "file", ")", "print", "(", "''", ".", "join", "(", "[", "'#'", ",", "str", "(", "endtime", "*", "10", ")", "]", ")", ",", "file", "=", "file", ")", "file", ".", "flush", "(", ")" ]
Print the trace out as a VCD File for use in other tools. :param file: file to open and output vcd dump to. :param include_clock: boolean specifying if the implicit clk should be included. Dumps the current trace to file as a "value change dump" file. The file parameter defaults to _stdout_ and the include_clock defaults to True. Examples :: sim_trace.print_vcd() sim_trace.print_vcd("my_waveform.vcd", include_clock=False)
[ "Print", "the", "trace", "out", "as", "a", "VCD", "File", "for", "use", "in", "other", "tools", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L843-L899
2,966
UCSBarchlab/PyRTL
pyrtl/simulation.py
SimulationTrace.render_trace
def render_trace( self, trace_list=None, file=sys.stdout, render_cls=default_renderer(), symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True): """ Render the trace to a file using unicode and ASCII escape sequences. :param trace_list: A list of signals to be output in the specified order. :param file: The place to write output, default to stdout. :param render_cls: A class that translates traces into output bytes. :param symbol_len: The "length" of each rendered cycle in characters. :param segment_size: Traces are broken in the segments of this number of cycles. :param segment_delim: The character to be output between segments. :param extra_line: A Boolean to determin if we should print a blank line between signals. The resulting output can be viewed directly on the terminal or looked at with "more" or "less -R" which both should handle the ASCII escape sequences used in rendering. render_trace takes the following optional arguments. """ if _currently_in_ipython(): from IPython.display import display, HTML, Javascript # pylint: disable=import-error from .inputoutput import trace_to_html htmlstring = trace_to_html(self, trace_list=trace_list, sortkey=_trace_sort_key) html_elem = HTML(htmlstring) display(html_elem) # print(htmlstring) js_stuff = """ $.when( $.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/skins/default.js"), $.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/wavedrom.min.js"), $.Deferred(function( deferred ){ $( deferred.resolve ); })).done(function(){ WaveDrom.ProcessAll(); });""" display(Javascript(js_stuff)) else: self.render_trace_to_text( trace_list=trace_list, file=file, render_cls=render_cls, symbol_len=symbol_len, segment_size=segment_size, segment_delim=segment_delim, extra_line=extra_line)
python
def render_trace( self, trace_list=None, file=sys.stdout, render_cls=default_renderer(), symbol_len=5, segment_size=5, segment_delim=' ', extra_line=True): if _currently_in_ipython(): from IPython.display import display, HTML, Javascript # pylint: disable=import-error from .inputoutput import trace_to_html htmlstring = trace_to_html(self, trace_list=trace_list, sortkey=_trace_sort_key) html_elem = HTML(htmlstring) display(html_elem) # print(htmlstring) js_stuff = """ $.when( $.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/skins/default.js"), $.getScript("https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/wavedrom.min.js"), $.Deferred(function( deferred ){ $( deferred.resolve ); })).done(function(){ WaveDrom.ProcessAll(); });""" display(Javascript(js_stuff)) else: self.render_trace_to_text( trace_list=trace_list, file=file, render_cls=render_cls, symbol_len=symbol_len, segment_size=segment_size, segment_delim=segment_delim, extra_line=extra_line)
[ "def", "render_trace", "(", "self", ",", "trace_list", "=", "None", ",", "file", "=", "sys", ".", "stdout", ",", "render_cls", "=", "default_renderer", "(", ")", ",", "symbol_len", "=", "5", ",", "segment_size", "=", "5", ",", "segment_delim", "=", "' '", ",", "extra_line", "=", "True", ")", ":", "if", "_currently_in_ipython", "(", ")", ":", "from", "IPython", ".", "display", "import", "display", ",", "HTML", ",", "Javascript", "# pylint: disable=import-error", "from", ".", "inputoutput", "import", "trace_to_html", "htmlstring", "=", "trace_to_html", "(", "self", ",", "trace_list", "=", "trace_list", ",", "sortkey", "=", "_trace_sort_key", ")", "html_elem", "=", "HTML", "(", "htmlstring", ")", "display", "(", "html_elem", ")", "# print(htmlstring)", "js_stuff", "=", "\"\"\"\n $.when(\n $.getScript(\"https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/skins/default.js\"),\n $.getScript(\"https://cdnjs.cloudflare.com/ajax/libs/wavedrom/1.6.2/wavedrom.min.js\"),\n $.Deferred(function( deferred ){\n $( deferred.resolve );\n })).done(function(){\n WaveDrom.ProcessAll();\n });\"\"\"", "display", "(", "Javascript", "(", "js_stuff", ")", ")", "else", ":", "self", ".", "render_trace_to_text", "(", "trace_list", "=", "trace_list", ",", "file", "=", "file", ",", "render_cls", "=", "render_cls", ",", "symbol_len", "=", "symbol_len", ",", "segment_size", "=", "segment_size", ",", "segment_delim", "=", "segment_delim", ",", "extra_line", "=", "extra_line", ")" ]
Render the trace to a file using unicode and ASCII escape sequences. :param trace_list: A list of signals to be output in the specified order. :param file: The place to write output, default to stdout. :param render_cls: A class that translates traces into output bytes. :param symbol_len: The "length" of each rendered cycle in characters. :param segment_size: Traces are broken in the segments of this number of cycles. :param segment_delim: The character to be output between segments. :param extra_line: A Boolean to determin if we should print a blank line between signals. The resulting output can be viewed directly on the terminal or looked at with "more" or "less -R" which both should handle the ASCII escape sequences used in rendering. render_trace takes the following optional arguments.
[ "Render", "the", "trace", "to", "a", "file", "using", "unicode", "and", "ASCII", "escape", "sequences", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/simulation.py#L901-L941
2,967
UCSBarchlab/PyRTL
pyrtl/rtllib/muxes.py
prioritized_mux
def prioritized_mux(selects, vals): """ Returns the value in the first wire for which its select bit is 1 :param [WireVector] selects: a list of WireVectors signaling whether a wire should be chosen :param [WireVector] vals: values to return when the corresponding select value is 1 :return: WireVector If none of the items are high, the last val is returned """ if len(selects) != len(vals): raise pyrtl.PyrtlError("Number of select and val signals must match") if len(vals) == 0: raise pyrtl.PyrtlError("Must have a signal to mux") if len(vals) == 1: return vals[0] else: half = len(vals) // 2 return pyrtl.select(pyrtl.rtl_any(*selects[:half]), truecase=prioritized_mux(selects[:half], vals[:half]), falsecase=prioritized_mux(selects[half:], vals[half:]))
python
def prioritized_mux(selects, vals): if len(selects) != len(vals): raise pyrtl.PyrtlError("Number of select and val signals must match") if len(vals) == 0: raise pyrtl.PyrtlError("Must have a signal to mux") if len(vals) == 1: return vals[0] else: half = len(vals) // 2 return pyrtl.select(pyrtl.rtl_any(*selects[:half]), truecase=prioritized_mux(selects[:half], vals[:half]), falsecase=prioritized_mux(selects[half:], vals[half:]))
[ "def", "prioritized_mux", "(", "selects", ",", "vals", ")", ":", "if", "len", "(", "selects", ")", "!=", "len", "(", "vals", ")", ":", "raise", "pyrtl", ".", "PyrtlError", "(", "\"Number of select and val signals must match\"", ")", "if", "len", "(", "vals", ")", "==", "0", ":", "raise", "pyrtl", ".", "PyrtlError", "(", "\"Must have a signal to mux\"", ")", "if", "len", "(", "vals", ")", "==", "1", ":", "return", "vals", "[", "0", "]", "else", ":", "half", "=", "len", "(", "vals", ")", "//", "2", "return", "pyrtl", ".", "select", "(", "pyrtl", ".", "rtl_any", "(", "*", "selects", "[", ":", "half", "]", ")", ",", "truecase", "=", "prioritized_mux", "(", "selects", "[", ":", "half", "]", ",", "vals", "[", ":", "half", "]", ")", ",", "falsecase", "=", "prioritized_mux", "(", "selects", "[", "half", ":", "]", ",", "vals", "[", "half", ":", "]", ")", ")" ]
Returns the value in the first wire for which its select bit is 1 :param [WireVector] selects: a list of WireVectors signaling whether a wire should be chosen :param [WireVector] vals: values to return when the corresponding select value is 1 :return: WireVector If none of the items are high, the last val is returned
[ "Returns", "the", "value", "in", "the", "first", "wire", "for", "which", "its", "select", "bit", "is", "1" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L4-L26
2,968
UCSBarchlab/PyRTL
pyrtl/rtllib/muxes.py
demux
def demux(select): """ Demultiplexes a wire of arbitrary bitwidth :param WireVector select: indicates which wire to set on :return (WireVector, ...): a tuple of wires corresponding to each demultiplexed wire """ if len(select) == 1: return _demux_2(select) wires = demux(select[:-1]) sel = select[-1] not_select = ~sel zero_wires = tuple(not_select & w for w in wires) one_wires = tuple(sel & w for w in wires) return zero_wires + one_wires
python
def demux(select): if len(select) == 1: return _demux_2(select) wires = demux(select[:-1]) sel = select[-1] not_select = ~sel zero_wires = tuple(not_select & w for w in wires) one_wires = tuple(sel & w for w in wires) return zero_wires + one_wires
[ "def", "demux", "(", "select", ")", ":", "if", "len", "(", "select", ")", "==", "1", ":", "return", "_demux_2", "(", "select", ")", "wires", "=", "demux", "(", "select", "[", ":", "-", "1", "]", ")", "sel", "=", "select", "[", "-", "1", "]", "not_select", "=", "~", "sel", "zero_wires", "=", "tuple", "(", "not_select", "&", "w", "for", "w", "in", "wires", ")", "one_wires", "=", "tuple", "(", "sel", "&", "w", "for", "w", "in", "wires", ")", "return", "zero_wires", "+", "one_wires" ]
Demultiplexes a wire of arbitrary bitwidth :param WireVector select: indicates which wire to set on :return (WireVector, ...): a tuple of wires corresponding to each demultiplexed wire
[ "Demultiplexes", "a", "wire", "of", "arbitrary", "bitwidth" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L190-L205
2,969
UCSBarchlab/PyRTL
pyrtl/rtllib/muxes.py
MultiSelector.finalize
def finalize(self): """ Connects the wires. """ self._check_finalized() self._final = True for dest_w, values in self.dest_instrs_info.items(): mux_vals = dict(zip(self.instructions, values)) dest_w <<= sparse_mux(self.signal_wire, mux_vals)
python
def finalize(self): self._check_finalized() self._final = True for dest_w, values in self.dest_instrs_info.items(): mux_vals = dict(zip(self.instructions, values)) dest_w <<= sparse_mux(self.signal_wire, mux_vals)
[ "def", "finalize", "(", "self", ")", ":", "self", ".", "_check_finalized", "(", ")", "self", ".", "_final", "=", "True", "for", "dest_w", ",", "values", "in", "self", ".", "dest_instrs_info", ".", "items", "(", ")", ":", "mux_vals", "=", "dict", "(", "zip", "(", "self", ".", "instructions", ",", "values", ")", ")", "dest_w", "<<=", "sparse_mux", "(", "self", ".", "signal_wire", ",", "mux_vals", ")" ]
Connects the wires.
[ "Connects", "the", "wires", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/muxes.py#L178-L187
2,970
UCSBarchlab/PyRTL
pyrtl/wire.py
WireVector.bitmask
def bitmask(self): """ A property holding a bitmask of the same length as this WireVector. Specifically it is an integer with a number of bits set to 1 equal to the bitwidth of the WireVector. It is often times useful to "mask" an integer such that it fits in the the number of bits of a WireVector. As a convenience for this, the `bitmask` property is provided. As an example, if there was a 3-bit WireVector `a`, a call to `a.bitmask()` should return 0b111 or 0x7.""" if "_bitmask" not in self.__dict__: self._bitmask = (1 << len(self)) - 1 return self._bitmask
python
def bitmask(self): if "_bitmask" not in self.__dict__: self._bitmask = (1 << len(self)) - 1 return self._bitmask
[ "def", "bitmask", "(", "self", ")", ":", "if", "\"_bitmask\"", "not", "in", "self", ".", "__dict__", ":", "self", ".", "_bitmask", "=", "(", "1", "<<", "len", "(", "self", ")", ")", "-", "1", "return", "self", ".", "_bitmask" ]
A property holding a bitmask of the same length as this WireVector. Specifically it is an integer with a number of bits set to 1 equal to the bitwidth of the WireVector. It is often times useful to "mask" an integer such that it fits in the the number of bits of a WireVector. As a convenience for this, the `bitmask` property is provided. As an example, if there was a 3-bit WireVector `a`, a call to `a.bitmask()` should return 0b111 or 0x7.
[ "A", "property", "holding", "a", "bitmask", "of", "the", "same", "length", "as", "this", "WireVector", ".", "Specifically", "it", "is", "an", "integer", "with", "a", "number", "of", "bits", "set", "to", "1", "equal", "to", "the", "bitwidth", "of", "the", "WireVector", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/wire.py#L427-L438
2,971
usrlocalben/pydux
pydux/log_middleware.py
log_middleware
def log_middleware(store): """log all actions to console as they are dispatched""" def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
python
def log_middleware(store): def wrapper(next_): def log_dispatch(action): print('Dispatch Action:', action) return next_(action) return log_dispatch return wrapper
[ "def", "log_middleware", "(", "store", ")", ":", "def", "wrapper", "(", "next_", ")", ":", "def", "log_dispatch", "(", "action", ")", ":", "print", "(", "'Dispatch Action:'", ",", "action", ")", "return", "next_", "(", "action", ")", "return", "log_dispatch", "return", "wrapper" ]
log all actions to console as they are dispatched
[ "log", "all", "actions", "to", "console", "as", "they", "are", "dispatched" ]
943ca1c75357b9289f55f17ff2d997a66a3313a4
https://github.com/usrlocalben/pydux/blob/943ca1c75357b9289f55f17ff2d997a66a3313a4/pydux/log_middleware.py#L6-L13
2,972
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation.inspect
def inspect(self, w): """Get the latest value of the wire given, if possible.""" if isinstance(w, WireVector): w = w.name try: vals = self.tracer.trace[w] except KeyError: pass else: if not vals: raise PyrtlError('No context available. Please run a simulation step') return vals[-1] raise PyrtlError('CompiledSimulation does not support inspecting internal WireVectors')
python
def inspect(self, w): if isinstance(w, WireVector): w = w.name try: vals = self.tracer.trace[w] except KeyError: pass else: if not vals: raise PyrtlError('No context available. Please run a simulation step') return vals[-1] raise PyrtlError('CompiledSimulation does not support inspecting internal WireVectors')
[ "def", "inspect", "(", "self", ",", "w", ")", ":", "if", "isinstance", "(", "w", ",", "WireVector", ")", ":", "w", "=", "w", ".", "name", "try", ":", "vals", "=", "self", ".", "tracer", ".", "trace", "[", "w", "]", "except", "KeyError", ":", "pass", "else", ":", "if", "not", "vals", ":", "raise", "PyrtlError", "(", "'No context available. Please run a simulation step'", ")", "return", "vals", "[", "-", "1", "]", "raise", "PyrtlError", "(", "'CompiledSimulation does not support inspecting internal WireVectors'", ")" ]
Get the latest value of the wire given, if possible.
[ "Get", "the", "latest", "value", "of", "the", "wire", "given", "if", "possible", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L110-L122
2,973
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation.run
def run(self, inputs): """Run many steps of the simulation. The argument is a list of input mappings for each step, and its length is the number of steps to be executed. """ steps = len(inputs) # create i/o arrays of the appropriate length ibuf_type = ctypes.c_uint64*(steps*self._ibufsz) obuf_type = ctypes.c_uint64*(steps*self._obufsz) ibuf = ibuf_type() obuf = obuf_type() # these array will be passed to _crun self._crun.argtypes = [ctypes.c_uint64, ibuf_type, obuf_type] # build the input array for n, inmap in enumerate(inputs): for w in inmap: if isinstance(w, WireVector): name = w.name else: name = w start, count = self._inputpos[name] start += n*self._ibufsz val = inmap[w] if val >= 1 << self._inputbw[name]: raise PyrtlError( 'Wire {} has value {} which cannot be represented ' 'using its bitwidth'.format(name, val)) # pack input for pos in range(start, start+count): ibuf[pos] = val & ((1 << 64)-1) val >>= 64 # run the simulation self._crun(steps, ibuf, obuf) # save traced wires for name in self.tracer.trace: rname = self._probe_mapping.get(name, name) if rname in self._outputpos: start, count = self._outputpos[rname] buf, sz = obuf, self._obufsz elif rname in self._inputpos: start, count = self._inputpos[rname] buf, sz = ibuf, self._ibufsz else: raise PyrtlInternalError('Untraceable wire in tracer') res = [] for n in range(steps): val = 0 # unpack output for pos in reversed(range(start, start+count)): val <<= 64 val |= buf[pos] res.append(val) start += sz self.tracer.trace[name].extend(res)
python
def run(self, inputs): steps = len(inputs) # create i/o arrays of the appropriate length ibuf_type = ctypes.c_uint64*(steps*self._ibufsz) obuf_type = ctypes.c_uint64*(steps*self._obufsz) ibuf = ibuf_type() obuf = obuf_type() # these array will be passed to _crun self._crun.argtypes = [ctypes.c_uint64, ibuf_type, obuf_type] # build the input array for n, inmap in enumerate(inputs): for w in inmap: if isinstance(w, WireVector): name = w.name else: name = w start, count = self._inputpos[name] start += n*self._ibufsz val = inmap[w] if val >= 1 << self._inputbw[name]: raise PyrtlError( 'Wire {} has value {} which cannot be represented ' 'using its bitwidth'.format(name, val)) # pack input for pos in range(start, start+count): ibuf[pos] = val & ((1 << 64)-1) val >>= 64 # run the simulation self._crun(steps, ibuf, obuf) # save traced wires for name in self.tracer.trace: rname = self._probe_mapping.get(name, name) if rname in self._outputpos: start, count = self._outputpos[rname] buf, sz = obuf, self._obufsz elif rname in self._inputpos: start, count = self._inputpos[rname] buf, sz = ibuf, self._ibufsz else: raise PyrtlInternalError('Untraceable wire in tracer') res = [] for n in range(steps): val = 0 # unpack output for pos in reversed(range(start, start+count)): val <<= 64 val |= buf[pos] res.append(val) start += sz self.tracer.trace[name].extend(res)
[ "def", "run", "(", "self", ",", "inputs", ")", ":", "steps", "=", "len", "(", "inputs", ")", "# create i/o arrays of the appropriate length", "ibuf_type", "=", "ctypes", ".", "c_uint64", "*", "(", "steps", "*", "self", ".", "_ibufsz", ")", "obuf_type", "=", "ctypes", ".", "c_uint64", "*", "(", "steps", "*", "self", ".", "_obufsz", ")", "ibuf", "=", "ibuf_type", "(", ")", "obuf", "=", "obuf_type", "(", ")", "# these array will be passed to _crun", "self", ".", "_crun", ".", "argtypes", "=", "[", "ctypes", ".", "c_uint64", ",", "ibuf_type", ",", "obuf_type", "]", "# build the input array", "for", "n", ",", "inmap", "in", "enumerate", "(", "inputs", ")", ":", "for", "w", "in", "inmap", ":", "if", "isinstance", "(", "w", ",", "WireVector", ")", ":", "name", "=", "w", ".", "name", "else", ":", "name", "=", "w", "start", ",", "count", "=", "self", ".", "_inputpos", "[", "name", "]", "start", "+=", "n", "*", "self", ".", "_ibufsz", "val", "=", "inmap", "[", "w", "]", "if", "val", ">=", "1", "<<", "self", ".", "_inputbw", "[", "name", "]", ":", "raise", "PyrtlError", "(", "'Wire {} has value {} which cannot be represented '", "'using its bitwidth'", ".", "format", "(", "name", ",", "val", ")", ")", "# pack input", "for", "pos", "in", "range", "(", "start", ",", "start", "+", "count", ")", ":", "ibuf", "[", "pos", "]", "=", "val", "&", "(", "(", "1", "<<", "64", ")", "-", "1", ")", "val", ">>=", "64", "# run the simulation", "self", ".", "_crun", "(", "steps", ",", "ibuf", ",", "obuf", ")", "# save traced wires", "for", "name", "in", "self", ".", "tracer", ".", "trace", ":", "rname", "=", "self", ".", "_probe_mapping", ".", "get", "(", "name", ",", "name", ")", "if", "rname", "in", "self", ".", "_outputpos", ":", "start", ",", "count", "=", "self", ".", "_outputpos", "[", "rname", "]", "buf", ",", "sz", "=", "obuf", ",", "self", ".", "_obufsz", "elif", "rname", "in", "self", ".", "_inputpos", ":", "start", ",", "count", "=", "self", ".", "_inputpos", "[", "rname", "]", "buf", ",", "sz", "=", "ibuf", ",", "self", ".", "_ibufsz", "else", ":", "raise", "PyrtlInternalError", "(", "'Untraceable wire in tracer'", ")", "res", "=", "[", "]", "for", "n", "in", "range", "(", "steps", ")", ":", "val", "=", "0", "# unpack output", "for", "pos", "in", "reversed", "(", "range", "(", "start", ",", "start", "+", "count", ")", ")", ":", "val", "<<=", "64", "val", "|=", "buf", "[", "pos", "]", "res", ".", "append", "(", "val", ")", "start", "+=", "sz", "self", ".", "tracer", ".", "trace", "[", "name", "]", ".", "extend", "(", "res", ")" ]
Run many steps of the simulation. The argument is a list of input mappings for each step, and its length is the number of steps to be executed.
[ "Run", "many", "steps", "of", "the", "simulation", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L131-L188
2,974
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation._traceable
def _traceable(self, wv): """Check if wv is able to be traced If it is traceable due to a probe, record that probe in _probe_mapping. """ if isinstance(wv, (Input, Output)): return True for net in self.block.logic: if net.op == 'w' and net.args[0].name == wv.name and isinstance(net.dests[0], Output): self._probe_mapping[wv.name] = net.dests[0].name return True return False
python
def _traceable(self, wv): if isinstance(wv, (Input, Output)): return True for net in self.block.logic: if net.op == 'w' and net.args[0].name == wv.name and isinstance(net.dests[0], Output): self._probe_mapping[wv.name] = net.dests[0].name return True return False
[ "def", "_traceable", "(", "self", ",", "wv", ")", ":", "if", "isinstance", "(", "wv", ",", "(", "Input", ",", "Output", ")", ")", ":", "return", "True", "for", "net", "in", "self", ".", "block", ".", "logic", ":", "if", "net", ".", "op", "==", "'w'", "and", "net", ".", "args", "[", "0", "]", ".", "name", "==", "wv", ".", "name", "and", "isinstance", "(", "net", ".", "dests", "[", "0", "]", ",", "Output", ")", ":", "self", ".", "_probe_mapping", "[", "wv", ".", "name", "]", "=", "net", ".", "dests", "[", "0", "]", ".", "name", "return", "True", "return", "False" ]
Check if wv is able to be traced If it is traceable due to a probe, record that probe in _probe_mapping.
[ "Check", "if", "wv", "is", "able", "to", "be", "traced" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L190-L201
2,975
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation._remove_untraceable
def _remove_untraceable(self): """Remove from the tracer those wires that CompiledSimulation cannot track. Create _probe_mapping for wires only traceable via probes. """ self._probe_mapping = {} wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)} self.tracer.wires_to_track = wvs self.tracer._wires = {wv.name: wv for wv in wvs} self.tracer.trace.__init__(wvs)
python
def _remove_untraceable(self): self._probe_mapping = {} wvs = {wv for wv in self.tracer.wires_to_track if self._traceable(wv)} self.tracer.wires_to_track = wvs self.tracer._wires = {wv.name: wv for wv in wvs} self.tracer.trace.__init__(wvs)
[ "def", "_remove_untraceable", "(", "self", ")", ":", "self", ".", "_probe_mapping", "=", "{", "}", "wvs", "=", "{", "wv", "for", "wv", "in", "self", ".", "tracer", ".", "wires_to_track", "if", "self", ".", "_traceable", "(", "wv", ")", "}", "self", ".", "tracer", ".", "wires_to_track", "=", "wvs", "self", ".", "tracer", ".", "_wires", "=", "{", "wv", ".", "name", ":", "wv", "for", "wv", "in", "wvs", "}", "self", ".", "tracer", ".", "trace", ".", "__init__", "(", "wvs", ")" ]
Remove from the tracer those wires that CompiledSimulation cannot track. Create _probe_mapping for wires only traceable via probes.
[ "Remove", "from", "the", "tracer", "those", "wires", "that", "CompiledSimulation", "cannot", "track", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L203-L212
2,976
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation._create_dll
def _create_dll(self): """Create a dynamically-linked library implementing the simulation logic.""" self._dir = tempfile.mkdtemp() with open(path.join(self._dir, 'pyrtlsim.c'), 'w') as f: self._create_code(lambda s: f.write(s+'\n')) if platform.system() == 'Darwin': shared = '-dynamiclib' else: shared = '-shared' subprocess.check_call([ 'gcc', '-O0', '-march=native', '-std=c99', '-m64', shared, '-fPIC', path.join(self._dir, 'pyrtlsim.c'), '-o', path.join(self._dir, 'pyrtlsim.so'), ], shell=(platform.system() == 'Windows')) self._dll = ctypes.CDLL(path.join(self._dir, 'pyrtlsim.so')) self._crun = self._dll.sim_run_all self._crun.restype = None
python
def _create_dll(self): self._dir = tempfile.mkdtemp() with open(path.join(self._dir, 'pyrtlsim.c'), 'w') as f: self._create_code(lambda s: f.write(s+'\n')) if platform.system() == 'Darwin': shared = '-dynamiclib' else: shared = '-shared' subprocess.check_call([ 'gcc', '-O0', '-march=native', '-std=c99', '-m64', shared, '-fPIC', path.join(self._dir, 'pyrtlsim.c'), '-o', path.join(self._dir, 'pyrtlsim.so'), ], shell=(platform.system() == 'Windows')) self._dll = ctypes.CDLL(path.join(self._dir, 'pyrtlsim.so')) self._crun = self._dll.sim_run_all self._crun.restype = None
[ "def", "_create_dll", "(", "self", ")", ":", "self", ".", "_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "with", "open", "(", "path", ".", "join", "(", "self", ".", "_dir", ",", "'pyrtlsim.c'", ")", ",", "'w'", ")", "as", "f", ":", "self", ".", "_create_code", "(", "lambda", "s", ":", "f", ".", "write", "(", "s", "+", "'\\n'", ")", ")", "if", "platform", ".", "system", "(", ")", "==", "'Darwin'", ":", "shared", "=", "'-dynamiclib'", "else", ":", "shared", "=", "'-shared'", "subprocess", ".", "check_call", "(", "[", "'gcc'", ",", "'-O0'", ",", "'-march=native'", ",", "'-std=c99'", ",", "'-m64'", ",", "shared", ",", "'-fPIC'", ",", "path", ".", "join", "(", "self", ".", "_dir", ",", "'pyrtlsim.c'", ")", ",", "'-o'", ",", "path", ".", "join", "(", "self", ".", "_dir", ",", "'pyrtlsim.so'", ")", ",", "]", ",", "shell", "=", "(", "platform", ".", "system", "(", ")", "==", "'Windows'", ")", ")", "self", ".", "_dll", "=", "ctypes", ".", "CDLL", "(", "path", ".", "join", "(", "self", ".", "_dir", ",", "'pyrtlsim.so'", ")", ")", "self", ".", "_crun", "=", "self", ".", "_dll", ".", "sim_run_all", "self", ".", "_crun", ".", "restype", "=", "None" ]
Create a dynamically-linked library implementing the simulation logic.
[ "Create", "a", "dynamically", "-", "linked", "library", "implementing", "the", "simulation", "logic", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L214-L230
2,977
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation._makeini
def _makeini(self, w, v): """C initializer string for a wire with a given value.""" pieces = [] for n in range(self._limbs(w)): pieces.append(hex(v & ((1 << 64)-1))) v >>= 64 return ','.join(pieces).join('{}')
python
def _makeini(self, w, v): pieces = [] for n in range(self._limbs(w)): pieces.append(hex(v & ((1 << 64)-1))) v >>= 64 return ','.join(pieces).join('{}')
[ "def", "_makeini", "(", "self", ",", "w", ",", "v", ")", ":", "pieces", "=", "[", "]", "for", "n", "in", "range", "(", "self", ".", "_limbs", "(", "w", ")", ")", ":", "pieces", ".", "append", "(", "hex", "(", "v", "&", "(", "(", "1", "<<", "64", ")", "-", "1", ")", ")", ")", "v", ">>=", "64", "return", "','", ".", "join", "(", "pieces", ")", ".", "join", "(", "'{}'", ")" ]
C initializer string for a wire with a given value.
[ "C", "initializer", "string", "for", "a", "wire", "with", "a", "given", "value", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L236-L242
2,978
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation._makemask
def _makemask(self, dest, res, pos): """Create a bitmask. The value being masked is of width `res`. Limb number `pos` of `dest` is being assigned to. """ if (res is None or dest.bitwidth < res) and 0 < (dest.bitwidth - 64*pos) < 64: return '&0x{:X}'.format((1 << (dest.bitwidth % 64))-1) return ''
python
def _makemask(self, dest, res, pos): if (res is None or dest.bitwidth < res) and 0 < (dest.bitwidth - 64*pos) < 64: return '&0x{:X}'.format((1 << (dest.bitwidth % 64))-1) return ''
[ "def", "_makemask", "(", "self", ",", "dest", ",", "res", ",", "pos", ")", ":", "if", "(", "res", "is", "None", "or", "dest", ".", "bitwidth", "<", "res", ")", "and", "0", "<", "(", "dest", ".", "bitwidth", "-", "64", "*", "pos", ")", "<", "64", ":", "return", "'&0x{:X}'", ".", "format", "(", "(", "1", "<<", "(", "dest", ".", "bitwidth", "%", "64", ")", ")", "-", "1", ")", "return", "''" ]
Create a bitmask. The value being masked is of width `res`. Limb number `pos` of `dest` is being assigned to.
[ "Create", "a", "bitmask", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L257-L265
2,979
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation._getarglimb
def _getarglimb(self, arg, n): """Get the nth limb of the given wire. Returns '0' when the wire does not have sufficient limbs. """ return '{vn}[{n}]'.format(vn=self.varname[arg], n=n) if arg.bitwidth > 64*n else '0'
python
def _getarglimb(self, arg, n): return '{vn}[{n}]'.format(vn=self.varname[arg], n=n) if arg.bitwidth > 64*n else '0'
[ "def", "_getarglimb", "(", "self", ",", "arg", ",", "n", ")", ":", "return", "'{vn}[{n}]'", ".", "format", "(", "vn", "=", "self", ".", "varname", "[", "arg", "]", ",", "n", "=", "n", ")", "if", "arg", ".", "bitwidth", ">", "64", "*", "n", "else", "'0'" ]
Get the nth limb of the given wire. Returns '0' when the wire does not have sufficient limbs.
[ "Get", "the", "nth", "limb", "of", "the", "given", "wire", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L267-L272
2,980
UCSBarchlab/PyRTL
pyrtl/compilesim.py
CompiledSimulation._clean_name
def _clean_name(self, prefix, obj): """Create a C variable name with the given prefix based on the name of obj.""" return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))
python
def _clean_name(self, prefix, obj): return '{}{}_{}'.format(prefix, self._uid(), ''.join(c for c in obj.name if c.isalnum()))
[ "def", "_clean_name", "(", "self", ",", "prefix", ",", "obj", ")", ":", "return", "'{}{}_{}'", ".", "format", "(", "prefix", ",", "self", ".", "_uid", "(", ")", ",", "''", ".", "join", "(", "c", "for", "c", "in", "obj", ".", "name", "if", "c", ".", "isalnum", "(", ")", ")", ")" ]
Create a C variable name with the given prefix based on the name of obj.
[ "Create", "a", "C", "variable", "name", "with", "the", "given", "prefix", "based", "on", "the", "name", "of", "obj", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/compilesim.py#L274-L276
2,981
UCSBarchlab/PyRTL
pyrtl/rtllib/multipliers.py
_trivial_mult
def _trivial_mult(A, B): """ turns a multiplication into an And gate if one of the wires is a bitwidth of 1 :param A: :param B: :return: """ if len(B) == 1: A, B = B, A # so that we can reuse the code below :) if len(A) == 1: a_vals = A.sign_extended(len(B)) # keep the wirevector len consistent return pyrtl.concat_list([a_vals & B, pyrtl.Const(0)])
python
def _trivial_mult(A, B): if len(B) == 1: A, B = B, A # so that we can reuse the code below :) if len(A) == 1: a_vals = A.sign_extended(len(B)) # keep the wirevector len consistent return pyrtl.concat_list([a_vals & B, pyrtl.Const(0)])
[ "def", "_trivial_mult", "(", "A", ",", "B", ")", ":", "if", "len", "(", "B", ")", "==", "1", ":", "A", ",", "B", "=", "B", ",", "A", "# so that we can reuse the code below :)", "if", "len", "(", "A", ")", "==", "1", ":", "a_vals", "=", "A", ".", "sign_extended", "(", "len", "(", "B", ")", ")", "# keep the wirevector len consistent", "return", "pyrtl", ".", "concat_list", "(", "[", "a_vals", "&", "B", ",", "pyrtl", ".", "Const", "(", "0", ")", "]", ")" ]
turns a multiplication into an And gate if one of the wires is a bitwidth of 1 :param A: :param B: :return:
[ "turns", "a", "multiplication", "into", "an", "And", "gate", "if", "one", "of", "the", "wires", "is", "a", "bitwidth", "of", "1" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L49-L64
2,982
UCSBarchlab/PyRTL
pyrtl/rtllib/multipliers.py
tree_multiplier
def tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """ Build an fast unclocked multiplier for inputs A and B using a Wallace or Dada Tree. :param WireVector A, B: two input wires for the multiplication :param function reducer: Reduce the tree using either a Dada recuder or a Wallace reducer determines whether it is a Wallace tree multiplier or a Dada tree multiplier :param function adder_func: an adder function that will be used to do the last addition :return WireVector: The multiplied result Delay is order logN, while area is order N^2. """ """ The two tree multipliers basically works by splitting the multiplication into a series of many additions, and it works by applying 'reductions'. """ triv_res = _trivial_mult(A, B) if triv_res is not None: return triv_res bits_length = (len(A) + len(B)) # create a list of lists, with slots for all the weights (bit-positions) bits = [[] for weight in range(bits_length)] # AND every bit of A with every bit of B (N^2 results) and store by "weight" (bit-position) for i, a in enumerate(A): for j, b in enumerate(B): bits[i + j].append(a & b) return reducer(bits, bits_length, adder_func)
python
def tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """ The two tree multipliers basically works by splitting the multiplication into a series of many additions, and it works by applying 'reductions'. """ triv_res = _trivial_mult(A, B) if triv_res is not None: return triv_res bits_length = (len(A) + len(B)) # create a list of lists, with slots for all the weights (bit-positions) bits = [[] for weight in range(bits_length)] # AND every bit of A with every bit of B (N^2 results) and store by "weight" (bit-position) for i, a in enumerate(A): for j, b in enumerate(B): bits[i + j].append(a & b) return reducer(bits, bits_length, adder_func)
[ "def", "tree_multiplier", "(", "A", ",", "B", ",", "reducer", "=", "adders", ".", "wallace_reducer", ",", "adder_func", "=", "adders", ".", "kogge_stone", ")", ":", "\"\"\"\n The two tree multipliers basically works by splitting the multiplication\n into a series of many additions, and it works by applying 'reductions'.\n \"\"\"", "triv_res", "=", "_trivial_mult", "(", "A", ",", "B", ")", "if", "triv_res", "is", "not", "None", ":", "return", "triv_res", "bits_length", "=", "(", "len", "(", "A", ")", "+", "len", "(", "B", ")", ")", "# create a list of lists, with slots for all the weights (bit-positions)", "bits", "=", "[", "[", "]", "for", "weight", "in", "range", "(", "bits_length", ")", "]", "# AND every bit of A with every bit of B (N^2 results) and store by \"weight\" (bit-position)", "for", "i", ",", "a", "in", "enumerate", "(", "A", ")", ":", "for", "j", ",", "b", "in", "enumerate", "(", "B", ")", ":", "bits", "[", "i", "+", "j", "]", ".", "append", "(", "a", "&", "b", ")", "return", "reducer", "(", "bits", ",", "bits_length", ",", "adder_func", ")" ]
Build an fast unclocked multiplier for inputs A and B using a Wallace or Dada Tree. :param WireVector A, B: two input wires for the multiplication :param function reducer: Reduce the tree using either a Dada recuder or a Wallace reducer determines whether it is a Wallace tree multiplier or a Dada tree multiplier :param function adder_func: an adder function that will be used to do the last addition :return WireVector: The multiplied result Delay is order logN, while area is order N^2.
[ "Build", "an", "fast", "unclocked", "multiplier", "for", "inputs", "A", "and", "B", "using", "a", "Wallace", "or", "Dada", "Tree", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L125-L155
2,983
UCSBarchlab/PyRTL
pyrtl/rtllib/multipliers.py
signed_tree_multiplier
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """Same as tree_multiplier, but uses two's-complement signed integers""" if len(A) == 1 or len(B) == 1: raise pyrtl.PyrtlError("sign bit required, one or both wires too small") aneg, bneg = A[-1], B[-1] a = _twos_comp_conditional(A, aneg) b = _twos_comp_conditional(B, bneg) res = tree_multiplier(a[:-1], b[:-1]).zero_extended(len(A) + len(B)) return _twos_comp_conditional(res, aneg ^ bneg)
python
def signed_tree_multiplier(A, B, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): if len(A) == 1 or len(B) == 1: raise pyrtl.PyrtlError("sign bit required, one or both wires too small") aneg, bneg = A[-1], B[-1] a = _twos_comp_conditional(A, aneg) b = _twos_comp_conditional(B, bneg) res = tree_multiplier(a[:-1], b[:-1]).zero_extended(len(A) + len(B)) return _twos_comp_conditional(res, aneg ^ bneg)
[ "def", "signed_tree_multiplier", "(", "A", ",", "B", ",", "reducer", "=", "adders", ".", "wallace_reducer", ",", "adder_func", "=", "adders", ".", "kogge_stone", ")", ":", "if", "len", "(", "A", ")", "==", "1", "or", "len", "(", "B", ")", "==", "1", ":", "raise", "pyrtl", ".", "PyrtlError", "(", "\"sign bit required, one or both wires too small\"", ")", "aneg", ",", "bneg", "=", "A", "[", "-", "1", "]", ",", "B", "[", "-", "1", "]", "a", "=", "_twos_comp_conditional", "(", "A", ",", "aneg", ")", "b", "=", "_twos_comp_conditional", "(", "B", ",", "bneg", ")", "res", "=", "tree_multiplier", "(", "a", "[", ":", "-", "1", "]", ",", "b", "[", ":", "-", "1", "]", ")", ".", "zero_extended", "(", "len", "(", "A", ")", "+", "len", "(", "B", ")", ")", "return", "_twos_comp_conditional", "(", "res", ",", "aneg", "^", "bneg", ")" ]
Same as tree_multiplier, but uses two's-complement signed integers
[ "Same", "as", "tree_multiplier", "but", "uses", "two", "s", "-", "complement", "signed", "integers" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L158-L168
2,984
UCSBarchlab/PyRTL
pyrtl/rtllib/multipliers.py
generalized_fma
def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): """Generated an opimitized fused multiply adder. A generalized FMA unit that multiplies each pair of numbers in mult_pairs, then adds the resulting numbers and and the values of the add wires all together to form an answer. This is faster than separate adders and multipliers because you avoid unnecessary adder structures for intermediate representations. :param mult_pairs: Either None (if there are no pairs to multiply) or a list of pairs of wires to multiply: [(mult1_1, mult1_2), ...] :param add_wires: Either None (if there are no individual items to add other than the mult_pairs), or a list of wires for adding on top of the result of the pair multiplication. :param Bool signed: Currently not supported (will be added in the future) The default will likely be changed to True, so if you want the smallest set of wires in the future, specify this as False :param reducer: (advanced) The tree reducer to use :param adder_func: (advanced) The adder to use to add the two results at the end :return WireVector: The result WireVector """ # first need to figure out the max length if mult_pairs: # Need to deal with the case when it is empty mult_max = max(len(m[0]) + len(m[1]) - 1 for m in mult_pairs) else: mult_max = 0 if add_wires: add_max = max(len(x) for x in add_wires) else: add_max = 0 longest_wire_len = max(add_max, mult_max) bits = [[] for i in range(longest_wire_len)] for mult_a, mult_b in mult_pairs: for i, a in enumerate(mult_a): for j, b in enumerate(mult_b): bits[i + j].append(a & b) for wire in add_wires: for bit_loc, bit in enumerate(wire): bits[bit_loc].append(bit) import math result_bitwidth = (longest_wire_len + int(math.ceil(math.log(len(add_wires) + len(mult_pairs), 2)))) return reducer(bits, result_bitwidth, adder_func)
python
def generalized_fma(mult_pairs, add_wires, signed=False, reducer=adders.wallace_reducer, adder_func=adders.kogge_stone): # first need to figure out the max length if mult_pairs: # Need to deal with the case when it is empty mult_max = max(len(m[0]) + len(m[1]) - 1 for m in mult_pairs) else: mult_max = 0 if add_wires: add_max = max(len(x) for x in add_wires) else: add_max = 0 longest_wire_len = max(add_max, mult_max) bits = [[] for i in range(longest_wire_len)] for mult_a, mult_b in mult_pairs: for i, a in enumerate(mult_a): for j, b in enumerate(mult_b): bits[i + j].append(a & b) for wire in add_wires: for bit_loc, bit in enumerate(wire): bits[bit_loc].append(bit) import math result_bitwidth = (longest_wire_len + int(math.ceil(math.log(len(add_wires) + len(mult_pairs), 2)))) return reducer(bits, result_bitwidth, adder_func)
[ "def", "generalized_fma", "(", "mult_pairs", ",", "add_wires", ",", "signed", "=", "False", ",", "reducer", "=", "adders", ".", "wallace_reducer", ",", "adder_func", "=", "adders", ".", "kogge_stone", ")", ":", "# first need to figure out the max length", "if", "mult_pairs", ":", "# Need to deal with the case when it is empty", "mult_max", "=", "max", "(", "len", "(", "m", "[", "0", "]", ")", "+", "len", "(", "m", "[", "1", "]", ")", "-", "1", "for", "m", "in", "mult_pairs", ")", "else", ":", "mult_max", "=", "0", "if", "add_wires", ":", "add_max", "=", "max", "(", "len", "(", "x", ")", "for", "x", "in", "add_wires", ")", "else", ":", "add_max", "=", "0", "longest_wire_len", "=", "max", "(", "add_max", ",", "mult_max", ")", "bits", "=", "[", "[", "]", "for", "i", "in", "range", "(", "longest_wire_len", ")", "]", "for", "mult_a", ",", "mult_b", "in", "mult_pairs", ":", "for", "i", ",", "a", "in", "enumerate", "(", "mult_a", ")", ":", "for", "j", ",", "b", "in", "enumerate", "(", "mult_b", ")", ":", "bits", "[", "i", "+", "j", "]", ".", "append", "(", "a", "&", "b", ")", "for", "wire", "in", "add_wires", ":", "for", "bit_loc", ",", "bit", "in", "enumerate", "(", "wire", ")", ":", "bits", "[", "bit_loc", "]", ".", "append", "(", "bit", ")", "import", "math", "result_bitwidth", "=", "(", "longest_wire_len", "+", "int", "(", "math", ".", "ceil", "(", "math", ".", "log", "(", "len", "(", "add_wires", ")", "+", "len", "(", "mult_pairs", ")", ",", "2", ")", ")", ")", ")", "return", "reducer", "(", "bits", ",", "result_bitwidth", ",", "adder_func", ")" ]
Generated an opimitized fused multiply adder. A generalized FMA unit that multiplies each pair of numbers in mult_pairs, then adds the resulting numbers and and the values of the add wires all together to form an answer. This is faster than separate adders and multipliers because you avoid unnecessary adder structures for intermediate representations. :param mult_pairs: Either None (if there are no pairs to multiply) or a list of pairs of wires to multiply: [(mult1_1, mult1_2), ...] :param add_wires: Either None (if there are no individual items to add other than the mult_pairs), or a list of wires for adding on top of the result of the pair multiplication. :param Bool signed: Currently not supported (will be added in the future) The default will likely be changed to True, so if you want the smallest set of wires in the future, specify this as False :param reducer: (advanced) The tree reducer to use :param adder_func: (advanced) The adder to use to add the two results at the end :return WireVector: The result WireVector
[ "Generated", "an", "opimitized", "fused", "multiply", "adder", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/rtllib/multipliers.py#L208-L258
2,985
UCSBarchlab/PyRTL
pyrtl/transform.py
net_transform
def net_transform(transform_func, block=None, **kwargs): """ Maps nets to new sets of nets according to a custom function :param transform_func: Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool) :return: """ block = working_block(block) with set_working_block(block, True): for net in block.logic.copy(): keep_orig_net = transform_func(net, **kwargs) if not keep_orig_net: block.logic.remove(net)
python
def net_transform(transform_func, block=None, **kwargs): block = working_block(block) with set_working_block(block, True): for net in block.logic.copy(): keep_orig_net = transform_func(net, **kwargs) if not keep_orig_net: block.logic.remove(net)
[ "def", "net_transform", "(", "transform_func", ",", "block", "=", "None", ",", "*", "*", "kwargs", ")", ":", "block", "=", "working_block", "(", "block", ")", "with", "set_working_block", "(", "block", ",", "True", ")", ":", "for", "net", "in", "block", ".", "logic", ".", "copy", "(", ")", ":", "keep_orig_net", "=", "transform_func", "(", "net", ",", "*", "*", "kwargs", ")", "if", "not", "keep_orig_net", ":", "block", ".", "logic", ".", "remove", "(", "net", ")" ]
Maps nets to new sets of nets according to a custom function :param transform_func: Function signature: func(orig_net (logicnet)) -> keep_orig_net (bool) :return:
[ "Maps", "nets", "to", "new", "sets", "of", "nets", "according", "to", "a", "custom", "function" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L27-L40
2,986
UCSBarchlab/PyRTL
pyrtl/transform.py
all_nets
def all_nets(transform_func): """Decorator that wraps a net transform function""" @functools.wraps(transform_func) def t_res(**kwargs): net_transform(transform_func, **kwargs) return t_res
python
def all_nets(transform_func): @functools.wraps(transform_func) def t_res(**kwargs): net_transform(transform_func, **kwargs) return t_res
[ "def", "all_nets", "(", "transform_func", ")", ":", "@", "functools", ".", "wraps", "(", "transform_func", ")", "def", "t_res", "(", "*", "*", "kwargs", ")", ":", "net_transform", "(", "transform_func", ",", "*", "*", "kwargs", ")", "return", "t_res" ]
Decorator that wraps a net transform function
[ "Decorator", "that", "wraps", "a", "net", "transform", "function" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L43-L48
2,987
UCSBarchlab/PyRTL
pyrtl/transform.py
wire_transform
def wire_transform(transform_func, select_types=WireVector, exclude_types=(Input, Output, Register, Const), block=None): """ Maps Wires to new sets of nets and wires according to a custom function :param transform_func: The function you want to run on all wires Function signature: func(orig_wire (WireVector)) -> src_wire, dst_wire src_wire is the src for the stuff you made in the transform func and dst_wire is the sink to indicate that the wire has not been changed, make src_wire and dst_wire both the original wire :param select_types: Type or Tuple of types of WireVectors to replace :param exclude_types: Type or Tuple of types of WireVectors to exclude from replacement :param block: The Block to replace wires on """ block = working_block(block) for orig_wire in block.wirevector_subset(select_types, exclude_types): new_src, new_dst = transform_func(orig_wire) replace_wire(orig_wire, new_src, new_dst, block)
python
def wire_transform(transform_func, select_types=WireVector, exclude_types=(Input, Output, Register, Const), block=None): block = working_block(block) for orig_wire in block.wirevector_subset(select_types, exclude_types): new_src, new_dst = transform_func(orig_wire) replace_wire(orig_wire, new_src, new_dst, block)
[ "def", "wire_transform", "(", "transform_func", ",", "select_types", "=", "WireVector", ",", "exclude_types", "=", "(", "Input", ",", "Output", ",", "Register", ",", "Const", ")", ",", "block", "=", "None", ")", ":", "block", "=", "working_block", "(", "block", ")", "for", "orig_wire", "in", "block", ".", "wirevector_subset", "(", "select_types", ",", "exclude_types", ")", ":", "new_src", ",", "new_dst", "=", "transform_func", "(", "orig_wire", ")", "replace_wire", "(", "orig_wire", ",", "new_src", ",", "new_dst", ",", "block", ")" ]
Maps Wires to new sets of nets and wires according to a custom function :param transform_func: The function you want to run on all wires Function signature: func(orig_wire (WireVector)) -> src_wire, dst_wire src_wire is the src for the stuff you made in the transform func and dst_wire is the sink to indicate that the wire has not been changed, make src_wire and dst_wire both the original wire :param select_types: Type or Tuple of types of WireVectors to replace :param exclude_types: Type or Tuple of types of WireVectors to exclude from replacement :param block: The Block to replace wires on
[ "Maps", "Wires", "to", "new", "sets", "of", "nets", "and", "wires", "according", "to", "a", "custom", "function" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L51-L70
2,988
UCSBarchlab/PyRTL
pyrtl/transform.py
all_wires
def all_wires(transform_func): """Decorator that wraps a wire transform function""" @functools.wraps(transform_func) def t_res(**kwargs): wire_transform(transform_func, **kwargs) return t_res
python
def all_wires(transform_func): @functools.wraps(transform_func) def t_res(**kwargs): wire_transform(transform_func, **kwargs) return t_res
[ "def", "all_wires", "(", "transform_func", ")", ":", "@", "functools", ".", "wraps", "(", "transform_func", ")", "def", "t_res", "(", "*", "*", "kwargs", ")", ":", "wire_transform", "(", "transform_func", ",", "*", "*", "kwargs", ")", "return", "t_res" ]
Decorator that wraps a wire transform function
[ "Decorator", "that", "wraps", "a", "wire", "transform", "function" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L73-L78
2,989
UCSBarchlab/PyRTL
pyrtl/transform.py
replace_wires
def replace_wires(wire_map, block=None): """ Quickly replace all wires in a block :param {old_wire: new_wire} wire_map: mapping of old wires to new wires """ block = working_block(block) src_nets, dst_nets = block.net_connections(include_virtual_nodes=False) for old_w, new_w in wire_map.items(): replace_wire_fast(old_w, new_w, new_w, src_nets, dst_nets, block)
python
def replace_wires(wire_map, block=None): block = working_block(block) src_nets, dst_nets = block.net_connections(include_virtual_nodes=False) for old_w, new_w in wire_map.items(): replace_wire_fast(old_w, new_w, new_w, src_nets, dst_nets, block)
[ "def", "replace_wires", "(", "wire_map", ",", "block", "=", "None", ")", ":", "block", "=", "working_block", "(", "block", ")", "src_nets", ",", "dst_nets", "=", "block", ".", "net_connections", "(", "include_virtual_nodes", "=", "False", ")", "for", "old_w", ",", "new_w", "in", "wire_map", ".", "items", "(", ")", ":", "replace_wire_fast", "(", "old_w", ",", "new_w", ",", "new_w", ",", "src_nets", ",", "dst_nets", ",", "block", ")" ]
Quickly replace all wires in a block :param {old_wire: new_wire} wire_map: mapping of old wires to new wires
[ "Quickly", "replace", "all", "wires", "in", "a", "block" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L109-L119
2,990
UCSBarchlab/PyRTL
pyrtl/transform.py
clone_wire
def clone_wire(old_wire, name=None): """ Makes a copy of any existing wire :param old_wire: The wire to clone :param name: a name fo rhte new wire Note that this function is mainly intended to be used when the two wires are from different blocks. Making two wires with the same name in the same block is not allowed """ if isinstance(old_wire, Const): return Const(old_wire.val, old_wire.bitwidth) else: if name is None: return old_wire.__class__(old_wire.bitwidth, name=old_wire.name) return old_wire.__class__(old_wire.bitwidth, name=name)
python
def clone_wire(old_wire, name=None): if isinstance(old_wire, Const): return Const(old_wire.val, old_wire.bitwidth) else: if name is None: return old_wire.__class__(old_wire.bitwidth, name=old_wire.name) return old_wire.__class__(old_wire.bitwidth, name=name)
[ "def", "clone_wire", "(", "old_wire", ",", "name", "=", "None", ")", ":", "if", "isinstance", "(", "old_wire", ",", "Const", ")", ":", "return", "Const", "(", "old_wire", ".", "val", ",", "old_wire", ".", "bitwidth", ")", "else", ":", "if", "name", "is", "None", ":", "return", "old_wire", ".", "__class__", "(", "old_wire", ".", "bitwidth", ",", "name", "=", "old_wire", ".", "name", ")", "return", "old_wire", ".", "__class__", "(", "old_wire", ".", "bitwidth", ",", "name", "=", "name", ")" ]
Makes a copy of any existing wire :param old_wire: The wire to clone :param name: a name fo rhte new wire Note that this function is mainly intended to be used when the two wires are from different blocks. Making two wires with the same name in the same block is not allowed
[ "Makes", "a", "copy", "of", "any", "existing", "wire" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L166-L182
2,991
UCSBarchlab/PyRTL
pyrtl/transform.py
copy_block
def copy_block(block=None, update_working_block=True): """ Makes a copy of an existing block :param block: The block to clone. (defaults to the working block) :return: The resulting block """ block_in = working_block(block) block_out, temp_wv_map = _clone_block_and_wires(block_in) mems = {} for net in block_in.logic: _copy_net(block_out, net, temp_wv_map, mems) block_out.mem_map = mems if update_working_block: set_working_block(block_out) return block_out
python
def copy_block(block=None, update_working_block=True): block_in = working_block(block) block_out, temp_wv_map = _clone_block_and_wires(block_in) mems = {} for net in block_in.logic: _copy_net(block_out, net, temp_wv_map, mems) block_out.mem_map = mems if update_working_block: set_working_block(block_out) return block_out
[ "def", "copy_block", "(", "block", "=", "None", ",", "update_working_block", "=", "True", ")", ":", "block_in", "=", "working_block", "(", "block", ")", "block_out", ",", "temp_wv_map", "=", "_clone_block_and_wires", "(", "block_in", ")", "mems", "=", "{", "}", "for", "net", "in", "block_in", ".", "logic", ":", "_copy_net", "(", "block_out", ",", "net", ",", "temp_wv_map", ",", "mems", ")", "block_out", ".", "mem_map", "=", "mems", "if", "update_working_block", ":", "set_working_block", "(", "block_out", ")", "return", "block_out" ]
Makes a copy of an existing block :param block: The block to clone. (defaults to the working block) :return: The resulting block
[ "Makes", "a", "copy", "of", "an", "existing", "block" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L185-L201
2,992
UCSBarchlab/PyRTL
pyrtl/transform.py
_clone_block_and_wires
def _clone_block_and_wires(block_in): """ This is a generic function to copy the WireVectors for another round of synthesis This does not split a WireVector with multiple wires. :param block_in: The block to change :param synth_name: a name to prepend to all new copies of a wire :return: the resulting block and a WireVector map """ block_in.sanity_check() # make sure that everything is valid block_out = block_in.__class__() temp_wv_map = {} with set_working_block(block_out, no_sanity_check=True): for wirevector in block_in.wirevector_subset(): new_wv = clone_wire(wirevector) temp_wv_map[wirevector] = new_wv return block_out, temp_wv_map
python
def _clone_block_and_wires(block_in): block_in.sanity_check() # make sure that everything is valid block_out = block_in.__class__() temp_wv_map = {} with set_working_block(block_out, no_sanity_check=True): for wirevector in block_in.wirevector_subset(): new_wv = clone_wire(wirevector) temp_wv_map[wirevector] = new_wv return block_out, temp_wv_map
[ "def", "_clone_block_and_wires", "(", "block_in", ")", ":", "block_in", ".", "sanity_check", "(", ")", "# make sure that everything is valid", "block_out", "=", "block_in", ".", "__class__", "(", ")", "temp_wv_map", "=", "{", "}", "with", "set_working_block", "(", "block_out", ",", "no_sanity_check", "=", "True", ")", ":", "for", "wirevector", "in", "block_in", ".", "wirevector_subset", "(", ")", ":", "new_wv", "=", "clone_wire", "(", "wirevector", ")", "temp_wv_map", "[", "wirevector", "]", "=", "new_wv", "return", "block_out", ",", "temp_wv_map" ]
This is a generic function to copy the WireVectors for another round of synthesis This does not split a WireVector with multiple wires. :param block_in: The block to change :param synth_name: a name to prepend to all new copies of a wire :return: the resulting block and a WireVector map
[ "This", "is", "a", "generic", "function", "to", "copy", "the", "WireVectors", "for", "another", "round", "of", "synthesis", "This", "does", "not", "split", "a", "WireVector", "with", "multiple", "wires", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L204-L221
2,993
UCSBarchlab/PyRTL
pyrtl/transform.py
_copy_net
def _copy_net(block_out, net, temp_wv_net, mem_map): """This function makes a copy of all nets passed to it for synth uses """ new_args = tuple(temp_wv_net[a_arg] for a_arg in net.args) new_dests = tuple(temp_wv_net[a_dest] for a_dest in net.dests) if net.op in "m@": # special stuff for copying memories new_param = _get_new_block_mem_instance(net.op_param, mem_map, block_out) else: new_param = net.op_param new_net = LogicNet(net.op, new_param, args=new_args, dests=new_dests) block_out.add_net(new_net)
python
def _copy_net(block_out, net, temp_wv_net, mem_map): new_args = tuple(temp_wv_net[a_arg] for a_arg in net.args) new_dests = tuple(temp_wv_net[a_dest] for a_dest in net.dests) if net.op in "m@": # special stuff for copying memories new_param = _get_new_block_mem_instance(net.op_param, mem_map, block_out) else: new_param = net.op_param new_net = LogicNet(net.op, new_param, args=new_args, dests=new_dests) block_out.add_net(new_net)
[ "def", "_copy_net", "(", "block_out", ",", "net", ",", "temp_wv_net", ",", "mem_map", ")", ":", "new_args", "=", "tuple", "(", "temp_wv_net", "[", "a_arg", "]", "for", "a_arg", "in", "net", ".", "args", ")", "new_dests", "=", "tuple", "(", "temp_wv_net", "[", "a_dest", "]", "for", "a_dest", "in", "net", ".", "dests", ")", "if", "net", ".", "op", "in", "\"m@\"", ":", "# special stuff for copying memories", "new_param", "=", "_get_new_block_mem_instance", "(", "net", ".", "op_param", ",", "mem_map", ",", "block_out", ")", "else", ":", "new_param", "=", "net", ".", "op_param", "new_net", "=", "LogicNet", "(", "net", ".", "op", ",", "new_param", ",", "args", "=", "new_args", ",", "dests", "=", "new_dests", ")", "block_out", ".", "add_net", "(", "new_net", ")" ]
This function makes a copy of all nets passed to it for synth uses
[ "This", "function", "makes", "a", "copy", "of", "all", "nets", "passed", "to", "it", "for", "synth", "uses" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L224-L235
2,994
UCSBarchlab/PyRTL
pyrtl/transform.py
_get_new_block_mem_instance
def _get_new_block_mem_instance(op_param, mem_map, block_out): """ gets the instance of the memory in the new block that is associated with a memory in a old block """ memid, old_mem = op_param if old_mem not in mem_map: new_mem = old_mem._make_copy(block_out) new_mem.id = old_mem.id mem_map[old_mem] = new_mem return memid, mem_map[old_mem]
python
def _get_new_block_mem_instance(op_param, mem_map, block_out): memid, old_mem = op_param if old_mem not in mem_map: new_mem = old_mem._make_copy(block_out) new_mem.id = old_mem.id mem_map[old_mem] = new_mem return memid, mem_map[old_mem]
[ "def", "_get_new_block_mem_instance", "(", "op_param", ",", "mem_map", ",", "block_out", ")", ":", "memid", ",", "old_mem", "=", "op_param", "if", "old_mem", "not", "in", "mem_map", ":", "new_mem", "=", "old_mem", ".", "_make_copy", "(", "block_out", ")", "new_mem", ".", "id", "=", "old_mem", ".", "id", "mem_map", "[", "old_mem", "]", "=", "new_mem", "return", "memid", ",", "mem_map", "[", "old_mem", "]" ]
gets the instance of the memory in the new block that is associated with a memory in a old block
[ "gets", "the", "instance", "of", "the", "memory", "in", "the", "new", "block", "that", "is", "associated", "with", "a", "memory", "in", "a", "old", "block" ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/transform.py#L238-L247
2,995
UCSBarchlab/PyRTL
pyrtl/helperfuncs.py
probe
def probe(w, name=None): """ Print useful information about a WireVector when in debug mode. :param w: WireVector from which to get info :param name: optional name for probe (defaults to an autogenerated name) :return: original WireVector w Probe can be inserted into a existing design easily as it returns the original wire unmodified. For example ``y <<= x[0:3] + 4`` could be turned into ``y <<= probe(x)[0:3] + 4`` to give visibility into both the origin of ``x`` (including the line that WireVector was originally created) and the run-time values of ``x`` (which will be named and thus show up by default in a trace. Likewise ``y <<= probe(x[0:3]) + 4``, ``y <<= probe(x[0:3] + 4)``, and ``probe(y) <<= x[0:3] + 4`` are all valid uses of `probe`. Note: `probe` does actually add a wire to the working block of w (which can confuse various post-processing transforms such as output to verilog). """ if not isinstance(w, WireVector): raise PyrtlError('Only WireVectors can be probed') if name is None: name = '(%s: %s)' % (probeIndexer.make_valid_string(), w.name) print("Probe: " + name + ' ' + get_stack(w)) p = Output(name=name) p <<= w # late assigns len from w automatically return w
python
def probe(w, name=None): if not isinstance(w, WireVector): raise PyrtlError('Only WireVectors can be probed') if name is None: name = '(%s: %s)' % (probeIndexer.make_valid_string(), w.name) print("Probe: " + name + ' ' + get_stack(w)) p = Output(name=name) p <<= w # late assigns len from w automatically return w
[ "def", "probe", "(", "w", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "w", ",", "WireVector", ")", ":", "raise", "PyrtlError", "(", "'Only WireVectors can be probed'", ")", "if", "name", "is", "None", ":", "name", "=", "'(%s: %s)'", "%", "(", "probeIndexer", ".", "make_valid_string", "(", ")", ",", "w", ".", "name", ")", "print", "(", "\"Probe: \"", "+", "name", "+", "' '", "+", "get_stack", "(", "w", ")", ")", "p", "=", "Output", "(", "name", "=", "name", ")", "p", "<<=", "w", "# late assigns len from w automatically", "return", "w" ]
Print useful information about a WireVector when in debug mode. :param w: WireVector from which to get info :param name: optional name for probe (defaults to an autogenerated name) :return: original WireVector w Probe can be inserted into a existing design easily as it returns the original wire unmodified. For example ``y <<= x[0:3] + 4`` could be turned into ``y <<= probe(x)[0:3] + 4`` to give visibility into both the origin of ``x`` (including the line that WireVector was originally created) and the run-time values of ``x`` (which will be named and thus show up by default in a trace. Likewise ``y <<= probe(x[0:3]) + 4``, ``y <<= probe(x[0:3] + 4)``, and ``probe(y) <<= x[0:3] + 4`` are all valid uses of `probe`. Note: `probe` does actually add a wire to the working block of w (which can confuse various post-processing transforms such as output to verilog).
[ "Print", "useful", "information", "about", "a", "WireVector", "when", "in", "debug", "mode", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L24-L52
2,996
UCSBarchlab/PyRTL
pyrtl/helperfuncs.py
rtl_assert
def rtl_assert(w, exp, block=None): """ Add hardware assertions to be checked on the RTL design. :param w: should be a WireVector :param Exception exp: Exception to throw when assertion fails :param Block block: block to which the assertion should be added (default to working block) :return: the Output wire for the assertion (can be ignored in most cases) If at any time during execution the wire w is not `true` (i.e. asserted low) then simulation will raise exp. """ block = working_block(block) if not isinstance(w, WireVector): raise PyrtlError('Only WireVectors can be asserted with rtl_assert') if len(w) != 1: raise PyrtlError('rtl_assert checks only a WireVector of bitwidth 1') if not isinstance(exp, Exception): raise PyrtlError('the second argument to rtl_assert must be an instance of Exception') if isinstance(exp, KeyError): raise PyrtlError('the second argument to rtl_assert cannot be a KeyError') if w not in block.wirevector_set: raise PyrtlError('assertion wire not part of the block to which it is being added') if w not in block.wirevector_set: raise PyrtlError('assertion not a known wirevector in the target block') if w in block.rtl_assert_dict: raise PyrtlInternalError('assertion conflicts with existing registered assertion') assert_wire = Output(bitwidth=1, name=assertIndexer.make_valid_string(), block=block) assert_wire <<= w block.rtl_assert_dict[assert_wire] = exp return assert_wire
python
def rtl_assert(w, exp, block=None): block = working_block(block) if not isinstance(w, WireVector): raise PyrtlError('Only WireVectors can be asserted with rtl_assert') if len(w) != 1: raise PyrtlError('rtl_assert checks only a WireVector of bitwidth 1') if not isinstance(exp, Exception): raise PyrtlError('the second argument to rtl_assert must be an instance of Exception') if isinstance(exp, KeyError): raise PyrtlError('the second argument to rtl_assert cannot be a KeyError') if w not in block.wirevector_set: raise PyrtlError('assertion wire not part of the block to which it is being added') if w not in block.wirevector_set: raise PyrtlError('assertion not a known wirevector in the target block') if w in block.rtl_assert_dict: raise PyrtlInternalError('assertion conflicts with existing registered assertion') assert_wire = Output(bitwidth=1, name=assertIndexer.make_valid_string(), block=block) assert_wire <<= w block.rtl_assert_dict[assert_wire] = exp return assert_wire
[ "def", "rtl_assert", "(", "w", ",", "exp", ",", "block", "=", "None", ")", ":", "block", "=", "working_block", "(", "block", ")", "if", "not", "isinstance", "(", "w", ",", "WireVector", ")", ":", "raise", "PyrtlError", "(", "'Only WireVectors can be asserted with rtl_assert'", ")", "if", "len", "(", "w", ")", "!=", "1", ":", "raise", "PyrtlError", "(", "'rtl_assert checks only a WireVector of bitwidth 1'", ")", "if", "not", "isinstance", "(", "exp", ",", "Exception", ")", ":", "raise", "PyrtlError", "(", "'the second argument to rtl_assert must be an instance of Exception'", ")", "if", "isinstance", "(", "exp", ",", "KeyError", ")", ":", "raise", "PyrtlError", "(", "'the second argument to rtl_assert cannot be a KeyError'", ")", "if", "w", "not", "in", "block", ".", "wirevector_set", ":", "raise", "PyrtlError", "(", "'assertion wire not part of the block to which it is being added'", ")", "if", "w", "not", "in", "block", ".", "wirevector_set", ":", "raise", "PyrtlError", "(", "'assertion not a known wirevector in the target block'", ")", "if", "w", "in", "block", ".", "rtl_assert_dict", ":", "raise", "PyrtlInternalError", "(", "'assertion conflicts with existing registered assertion'", ")", "assert_wire", "=", "Output", "(", "bitwidth", "=", "1", ",", "name", "=", "assertIndexer", ".", "make_valid_string", "(", ")", ",", "block", "=", "block", ")", "assert_wire", "<<=", "w", "block", ".", "rtl_assert_dict", "[", "assert_wire", "]", "=", "exp", "return", "assert_wire" ]
Add hardware assertions to be checked on the RTL design. :param w: should be a WireVector :param Exception exp: Exception to throw when assertion fails :param Block block: block to which the assertion should be added (default to working block) :return: the Output wire for the assertion (can be ignored in most cases) If at any time during execution the wire w is not `true` (i.e. asserted low) then simulation will raise exp.
[ "Add", "hardware", "assertions", "to", "be", "checked", "on", "the", "RTL", "design", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L58-L90
2,997
UCSBarchlab/PyRTL
pyrtl/helperfuncs.py
check_rtl_assertions
def check_rtl_assertions(sim): """ Checks the values in sim to see if any registers assertions fail. :param sim: Simulation in which to check the assertions :return: None """ for (w, exp) in sim.block.rtl_assert_dict.items(): try: value = sim.inspect(w) if not value: raise exp except KeyError: pass
python
def check_rtl_assertions(sim): for (w, exp) in sim.block.rtl_assert_dict.items(): try: value = sim.inspect(w) if not value: raise exp except KeyError: pass
[ "def", "check_rtl_assertions", "(", "sim", ")", ":", "for", "(", "w", ",", "exp", ")", "in", "sim", ".", "block", ".", "rtl_assert_dict", ".", "items", "(", ")", ":", "try", ":", "value", "=", "sim", ".", "inspect", "(", "w", ")", "if", "not", "value", ":", "raise", "exp", "except", "KeyError", ":", "pass" ]
Checks the values in sim to see if any registers assertions fail. :param sim: Simulation in which to check the assertions :return: None
[ "Checks", "the", "values", "in", "sim", "to", "see", "if", "any", "registers", "assertions", "fail", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L93-L106
2,998
UCSBarchlab/PyRTL
pyrtl/helperfuncs.py
wirevector_list
def wirevector_list(names, bitwidth=None, wvtype=WireVector): """ Allocate and return a list of WireVectors. :param names: Names for the WireVectors. Can be a list or single comma/space-separated string :param bitwidth: The desired bitwidth for the resulting WireVectors. :param WireVector wvtype: Which WireVector type to create. :return: List of WireVectors. Additionally, the ``names`` string can also contain an additional bitwidth specification separated by a ``/`` in the name. This cannot be used in combination with a ``bitwidth`` value other than ``1``. Examples: :: wirevector_list(['name1', 'name2', 'name3']) wirevector_list('name1, name2, name3') wirevector_list('input1 input2 input3', bitwidth=8, wvtype=pyrtl.wire.Input) wirevector_list('output1, output2 output3', bitwidth=3, wvtype=pyrtl.wire.Output) wirevector_list('two_bits/2, four_bits/4, eight_bits/8') wirevector_list(['name1', 'name2', 'name3'], bitwidth=[2, 4, 8]) """ if isinstance(names, str): names = names.replace(',', ' ').split() if any('/' in name for name in names) and bitwidth is not None: raise PyrtlError('only one of optional "/" or bitwidth parameter allowed') if bitwidth is None: bitwidth = 1 if isinstance(bitwidth, numbers.Integral): bitwidth = [bitwidth]*len(names) if len(bitwidth) != len(names): raise ValueError('number of names ' + str(len(names)) + ' should match number of bitwidths ' + str(len(bitwidth))) wirelist = [] for fullname, bw in zip(names, bitwidth): try: name, bw = fullname.split('/') except ValueError: name, bw = fullname, bw wirelist.append(wvtype(bitwidth=int(bw), name=name)) return wirelist
python
def wirevector_list(names, bitwidth=None, wvtype=WireVector): if isinstance(names, str): names = names.replace(',', ' ').split() if any('/' in name for name in names) and bitwidth is not None: raise PyrtlError('only one of optional "/" or bitwidth parameter allowed') if bitwidth is None: bitwidth = 1 if isinstance(bitwidth, numbers.Integral): bitwidth = [bitwidth]*len(names) if len(bitwidth) != len(names): raise ValueError('number of names ' + str(len(names)) + ' should match number of bitwidths ' + str(len(bitwidth))) wirelist = [] for fullname, bw in zip(names, bitwidth): try: name, bw = fullname.split('/') except ValueError: name, bw = fullname, bw wirelist.append(wvtype(bitwidth=int(bw), name=name)) return wirelist
[ "def", "wirevector_list", "(", "names", ",", "bitwidth", "=", "None", ",", "wvtype", "=", "WireVector", ")", ":", "if", "isinstance", "(", "names", ",", "str", ")", ":", "names", "=", "names", ".", "replace", "(", "','", ",", "' '", ")", ".", "split", "(", ")", "if", "any", "(", "'/'", "in", "name", "for", "name", "in", "names", ")", "and", "bitwidth", "is", "not", "None", ":", "raise", "PyrtlError", "(", "'only one of optional \"/\" or bitwidth parameter allowed'", ")", "if", "bitwidth", "is", "None", ":", "bitwidth", "=", "1", "if", "isinstance", "(", "bitwidth", ",", "numbers", ".", "Integral", ")", ":", "bitwidth", "=", "[", "bitwidth", "]", "*", "len", "(", "names", ")", "if", "len", "(", "bitwidth", ")", "!=", "len", "(", "names", ")", ":", "raise", "ValueError", "(", "'number of names '", "+", "str", "(", "len", "(", "names", ")", ")", "+", "' should match number of bitwidths '", "+", "str", "(", "len", "(", "bitwidth", ")", ")", ")", "wirelist", "=", "[", "]", "for", "fullname", ",", "bw", "in", "zip", "(", "names", ",", "bitwidth", ")", ":", "try", ":", "name", ",", "bw", "=", "fullname", ".", "split", "(", "'/'", ")", "except", "ValueError", ":", "name", ",", "bw", "=", "fullname", ",", "bw", "wirelist", ".", "append", "(", "wvtype", "(", "bitwidth", "=", "int", "(", "bw", ")", ",", "name", "=", "name", ")", ")", "return", "wirelist" ]
Allocate and return a list of WireVectors. :param names: Names for the WireVectors. Can be a list or single comma/space-separated string :param bitwidth: The desired bitwidth for the resulting WireVectors. :param WireVector wvtype: Which WireVector type to create. :return: List of WireVectors. Additionally, the ``names`` string can also contain an additional bitwidth specification separated by a ``/`` in the name. This cannot be used in combination with a ``bitwidth`` value other than ``1``. Examples: :: wirevector_list(['name1', 'name2', 'name3']) wirevector_list('name1, name2, name3') wirevector_list('input1 input2 input3', bitwidth=8, wvtype=pyrtl.wire.Input) wirevector_list('output1, output2 output3', bitwidth=3, wvtype=pyrtl.wire.Output) wirevector_list('two_bits/2, four_bits/4, eight_bits/8') wirevector_list(['name1', 'name2', 'name3'], bitwidth=[2, 4, 8])
[ "Allocate", "and", "return", "a", "list", "of", "WireVectors", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L154-L197
2,999
UCSBarchlab/PyRTL
pyrtl/helperfuncs.py
val_to_signed_integer
def val_to_signed_integer(value, bitwidth): """ Return value as intrepreted as a signed integer under twos complement. :param value: a python integer holding the value to convert :param bitwidth: the length of the integer in bits to assume for conversion Given an unsigned integer (not a wirevector!) covert that to a signed integer. This is useful for printing and interpreting values which are negative numbers in twos complement. :: val_to_signed_integer(0xff, 8) == -1 """ if isinstance(value, WireVector) or isinstance(bitwidth, WireVector): raise PyrtlError('inputs must not be wirevectors') if bitwidth < 1: raise PyrtlError('bitwidth must be a positive integer') neg_mask = 1 << (bitwidth - 1) neg_part = value & neg_mask pos_mask = neg_mask - 1 pos_part = value & pos_mask return pos_part - neg_part
python
def val_to_signed_integer(value, bitwidth): if isinstance(value, WireVector) or isinstance(bitwidth, WireVector): raise PyrtlError('inputs must not be wirevectors') if bitwidth < 1: raise PyrtlError('bitwidth must be a positive integer') neg_mask = 1 << (bitwidth - 1) neg_part = value & neg_mask pos_mask = neg_mask - 1 pos_part = value & pos_mask return pos_part - neg_part
[ "def", "val_to_signed_integer", "(", "value", ",", "bitwidth", ")", ":", "if", "isinstance", "(", "value", ",", "WireVector", ")", "or", "isinstance", "(", "bitwidth", ",", "WireVector", ")", ":", "raise", "PyrtlError", "(", "'inputs must not be wirevectors'", ")", "if", "bitwidth", "<", "1", ":", "raise", "PyrtlError", "(", "'bitwidth must be a positive integer'", ")", "neg_mask", "=", "1", "<<", "(", "bitwidth", "-", "1", ")", "neg_part", "=", "value", "&", "neg_mask", "pos_mask", "=", "neg_mask", "-", "1", "pos_part", "=", "value", "&", "pos_mask", "return", "pos_part", "-", "neg_part" ]
Return value as intrepreted as a signed integer under twos complement. :param value: a python integer holding the value to convert :param bitwidth: the length of the integer in bits to assume for conversion Given an unsigned integer (not a wirevector!) covert that to a signed integer. This is useful for printing and interpreting values which are negative numbers in twos complement. :: val_to_signed_integer(0xff, 8) == -1
[ "Return", "value", "as", "intrepreted", "as", "a", "signed", "integer", "under", "twos", "complement", "." ]
0988e5c9c10ededd5e1f58d5306603f9edf4b3e2
https://github.com/UCSBarchlab/PyRTL/blob/0988e5c9c10ededd5e1f58d5306603f9edf4b3e2/pyrtl/helperfuncs.py#L200-L223